-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathOneOfGenerator.cs
173 lines (138 loc) · 6.49 KB
/
OneOfGenerator.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
namespace OneOf.SourceGenerator
{
[Generator]
public class OneOfGenerator : IIncrementalGenerator
{
private const string AttributeName = "GenerateOneOfAttribute";
private const string AttributeNamespace = "OneOf";
private readonly string _attributeText = $@"// <auto-generated />
using System;
#pragma warning disable 1591
namespace {AttributeNamespace}
{{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class {AttributeName} : Attribute
{{
}}
}}
";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterPostInitializationOutput(ctx => ctx.AddSource($"{AttributeName}.g.cs", _attributeText));
var oneOfClasses = context.SyntaxProvider
.ForAttributeWithMetadataName(
fullyQualifiedMetadataName: $"{AttributeNamespace}.{AttributeName}",
predicate: static (s, _) => IsSyntaxTargetForGeneration(s),
transform: static (ctx, _) => GetSemanticTargetForGeneration(ctx))
.Where(static m => m is not null)
.Collect();
context.RegisterSourceOutput(oneOfClasses, Execute);
static bool IsSyntaxTargetForGeneration(SyntaxNode node)
{
return node is ClassDeclarationSyntax classDeclarationSyntax
&& classDeclarationSyntax.Modifiers.Any(SyntaxKind.PartialKeyword);
}
static INamedTypeSymbol? GetSemanticTargetForGeneration(GeneratorAttributeSyntaxContext context)
{
var symbol = context.TargetSymbol;
if (symbol is not INamedTypeSymbol namedTypeSymbol)
{
return null;
}
var attributeData = namedTypeSymbol.GetAttributes().FirstOrDefault(ad =>
string.Equals(ad.AttributeClass?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), $"global::{AttributeNamespace}.{AttributeName}"));
return attributeData is null ? null : namedTypeSymbol;
}
}
private static string GenerateClassSource(INamedTypeSymbol classSymbol,
ImmutableArray<ITypeParameterSymbol> typeParameters, ImmutableArray<ITypeSymbol> typeArguments)
{
var paramArgPairs =
typeParameters.Zip(typeArguments, (param, arg) => (param, arg));
var oneOfGenericPart = GetGenericPart(typeArguments);
var classNameWithGenericTypes = $"{classSymbol.Name}{GetOpenGenericPart(classSymbol)}";
StringBuilder source = new($@"// <auto-generated />
#pragma warning disable 1591
namespace {classSymbol.ContainingNamespace.ToDisplayString()}
{{
partial class {classNameWithGenericTypes}");
source.Append($@"
{{
public {classSymbol.Name}(OneOf.OneOf<{oneOfGenericPart}> _) : base(_) {{ }}
");
foreach (var (param, arg) in paramArgPairs)
{
source.Append($@"
public static implicit operator {classNameWithGenericTypes}({arg.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)} _) => new {classNameWithGenericTypes}(_);
public static explicit operator {arg.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}({classNameWithGenericTypes} _) => _.As{param.Name};
");
}
source.Append(@" }
}");
return source.ToString();
}
private static void Execute(SourceProductionContext context, ImmutableArray<INamedTypeSymbol?> symbols)
{
foreach (var namedTypeSymbol in symbols.Where(symbol => symbol is not null))
{
var classSource = ProcessClass(namedTypeSymbol!, context);
if (classSource is null)
{
continue;
}
context.AddSource($"{namedTypeSymbol!.ContainingNamespace}_{namedTypeSymbol.Name}.g.cs", classSource);
}
}
private static string? ProcessClass(INamedTypeSymbol classSymbol, SourceProductionContext context)
{
var attributeLocation = classSymbol.Locations.FirstOrDefault() ?? Location.None;
if (!classSymbol.ContainingSymbol.Equals(classSymbol.ContainingNamespace, SymbolEqualityComparer.Default))
{
CreateDiagnosticError(GeneratorDiagnosticDescriptors.TopLevelError);
return null;
}
if (classSymbol.BaseType is null || classSymbol.BaseType.Name != "OneOfBase" || classSymbol.BaseType.ContainingNamespace.ToString() != "OneOf")
{
CreateDiagnosticError(GeneratorDiagnosticDescriptors.WrongBaseType);
return null;
}
var typeArguments = classSymbol.BaseType.TypeArguments;
foreach (var typeSymbol in typeArguments)
{
if (typeSymbol.Name == nameof(Object))
{
CreateDiagnosticError(GeneratorDiagnosticDescriptors.ObjectIsOneOfType);
return null;
}
if (typeSymbol.TypeKind == TypeKind.Interface)
{
CreateDiagnosticError(GeneratorDiagnosticDescriptors.UserDefinedConversionsToOrFromAnInterfaceAreNotAllowed);
return null;
}
}
return GenerateClassSource(classSymbol, classSymbol.BaseType.TypeParameters, typeArguments);
void CreateDiagnosticError(DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, attributeLocation, classSymbol.Name,
DiagnosticSeverity.Error));
}
}
private static string GetGenericPart(ImmutableArray<ITypeSymbol> typeArguments) =>
string.Join(", ", typeArguments.Select(x => x.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)));
private static string? GetOpenGenericPart(INamedTypeSymbol classSymbol)
{
if (!classSymbol.TypeArguments.Any())
{
return null;
}
return $"<{GetGenericPart(classSymbol.TypeArguments)}>";
}
}
}