-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathCollectionInference.cs
70 lines (60 loc) · 3.08 KB
/
CollectionInference.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using M31.FluentApi.Generator.CodeGeneration.CodeBoardActors.MethodCreation.Collections;
using Microsoft.CodeAnalysis;
using static M31.FluentApi.Generator.CodeGeneration.CodeBoardElements.CodeTypeExtractor;
namespace M31.FluentApi.Generator.SourceGenerators.Collections;
internal class CollectionInference
{
private static readonly Dictionary<string, GeneratedCollection> genericTypeToCollection =
new Dictionary<string, GeneratedCollection>()
{
{ "System.Collections.Generic.IEnumerable<T>", GeneratedCollection.Array },
{ "System.Collections.Generic.IReadOnlyList<T>", GeneratedCollection.Array },
{ "System.Collections.Generic.IReadOnlyCollection<T>", GeneratedCollection.Array },
{ "System.Collections.Generic.List<T>", GeneratedCollection.List },
{ "System.Collections.Generic.IList<T>", GeneratedCollection.List },
{ "System.Collections.Generic.ICollection<T>", GeneratedCollection.List },
{ "System.Collections.Generic.HashSet<T>", GeneratedCollection.HashSet },
{ "System.Collections.Generic.ISet<T>", GeneratedCollection.HashSet },
{ "System.Collections.Generic.IReadOnlySet<T>", GeneratedCollection.HashSet },
};
private static readonly Dictionary<string, GeneratedCollection> nonGenericTypeToCollection =
new Dictionary<string, GeneratedCollection>()
{
{ "System.Array", GeneratedCollection.Array },
{ "System.Collections.IEnumerable", GeneratedCollection.Array },
{ "System.Collections.IList", GeneratedCollection.List },
{ "System.Collections.ICollection", GeneratedCollection.List },
};
internal static CollectionType? InferCollectionType(ITypeSymbol typeSymbol)
{
if (typeSymbol is IArrayTypeSymbol arrayTypeSymbol)
{
return new CollectionType(
GeneratedCollection.Array,
GetTypeForCodeGeneration(arrayTypeSymbol.ElementType),
arrayTypeSymbol.ElementType);
}
if (typeSymbol is INamedTypeSymbol { IsGenericType: true, TypeArguments.Length: 1 } genericNamedTypeSymbol)
{
string baseType = genericNamedTypeSymbol.ConstructedFrom.ToString();
ITypeSymbol genericArgument = genericNamedTypeSymbol.TypeArguments[0];
string genericTypeArgument = GetTypeForCodeGeneration(genericArgument);
if (!genericTypeToCollection.TryGetValue(baseType, out GeneratedCollection collection))
{
return null;
}
return new CollectionType(collection, genericTypeArgument, genericArgument);
}
if (typeSymbol is INamedTypeSymbol { IsGenericType: false } nonGenericNamedTypeSymbol)
{
if (!nonGenericTypeToCollection.TryGetValue(
nonGenericNamedTypeSymbol.ToString(),
out GeneratedCollection collection))
{
return null;
}
return new CollectionType(collection, "object", null);
}
return null;
}
}