generated from atc-net/atc-template-dotnet-package
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAttributeDataExtensions.cs
110 lines (98 loc) · 3.29 KB
/
AttributeDataExtensions.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
namespace Atc.Wpf.SourceGenerators.Extensions.CodeAnalysis;
internal static class AttributeDataExtensions
{
[SuppressMessage("Design", "MA0051:Method is too long", Justification = "OK.")]
public static Dictionary<string, string?> ExtractConstructorArgumentValues(
this AttributeData attributeData)
{
if (attributeData.ConstructorArguments.Length == 0 &&
attributeData.NamedArguments.Length == 0)
{
// Syntax check
if (attributeData.ApplicationSyntaxReference is not null)
{
return attributeData
.ApplicationSyntaxReference
.GetSyntax()
.ToFullString()
.ExtractAttributeConstructorParameters();
}
}
else
{
// Runtime check
return RunTimeExtractConstructorArgumentValues(attributeData);
}
return new Dictionary<string, string?>(StringComparer.Ordinal);
}
public static string ExtractClassFirstArgumentType(
this AttributeData propertyAttribute,
ref object? defaultValue)
{
var type = "int";
if (propertyAttribute.AttributeClass is not { TypeArguments.Length: 1 })
{
return type;
}
var typeSymbol = propertyAttribute.AttributeClass.TypeArguments[0];
type = typeSymbol.ToDisplayString().EnsureCSharpAliasIfNeeded();
if (type == "bool")
{
defaultValue = "false";
}
return type;
}
private static Dictionary<string, string?> RunTimeExtractConstructorArgumentValues(
AttributeData attributeData)
{
var result = new Dictionary<string, string?>(StringComparer.Ordinal);
var arrayIndex = 0;
foreach (var arg in attributeData.ConstructorArguments)
{
if (arg.Kind == TypedConstantKind.Array)
{
foreach (var typedConstant in arg.Values)
{
if (typedConstant.Value is null)
{
continue;
}
arrayIndex++;
result.Add(
arrayIndex.ToString(CultureInfo.InvariantCulture),
typedConstant.Value.ToString());
}
}
else if (arg.Value is not null)
{
result.Add(
NameConstants.Name,
arg.Value.ToString());
}
}
foreach (var arg in attributeData.NamedArguments)
{
if (arg.Value.Kind == TypedConstantKind.Array)
{
foreach (var typedConstant in arg.Value.Values)
{
if (typedConstant.Value is null)
{
continue;
}
arrayIndex++;
result.Add(
arrayIndex.ToString(CultureInfo.InvariantCulture),
$"nameof({typedConstant.Value})");
}
}
else
{
result.Add(
arg.Key,
$"nameof({arg.Value.Value})");
}
}
return result;
}
}