forked from Cysharp/MemoryPack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemoryPackGenerator.cs
256 lines (215 loc) · 10 KB
/
MemoryPackGenerator.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Text;
namespace MemoryPack.Generator;
// dotnet/runtime generators.
// https://github.com/dotnet/runtime/blob/main/src/libraries/System.Text.RegularExpressions/gen/
// https://github.com/dotnet/runtime/tree/main/src/libraries/System.Text.Json/gen
// https://github.com/dotnet/runtime/tree/main/src/libraries/System.Private.CoreLib/gen
// https://github.com/dotnet/runtime/tree/main/src/libraries/Microsoft.Extensions.Logging.Abstractions/gen
// https://github.com/dotnet/runtime/tree/main/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator
// https://github.com/dotnet/runtime/tree/main/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator
// https://github.com/dotnet/runtime/tree/main/src/tests/Common/XUnitWrapperGenerator
// documents, blogs.
// https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md
// https://andrewlock.net/creating-a-source-generator-part-1-creating-an-incremental-source-generator/
// https://qiita.com/WiZLite/items/48f37278cf13be899e40
// https://zenn.dev/pcysl5edgo/articles/6d9be0dd99c008
// https://neue.cc/2021/05/08_600.html
// https://www.thinktecture.com/en/net/roslyn-source-generators-introduction/
// for check generated file
// <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
// <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
[Generator(LanguageNames.CSharp)]
public partial class MemoryPackGenerator : IIncrementalGenerator
{
public const string MemoryPackableAttributeFullName = "MemoryPack.MemoryPackableAttribute";
public const string GenerateTypeScriptAttributeFullName = "MemoryPack.GenerateTypeScriptAttribute";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// no need RegisterPostInitializationOutput
RegisterMemoryPackable(context);
RegisterTypeScript(context);
}
void RegisterMemoryPackable(IncrementalGeneratorInitializationContext context)
{
// return dir of info output or null .
var logProvider = context.AnalyzerConfigOptionsProvider
.Select((configOptions, token) =>
{
if (configOptions.GlobalOptions.TryGetValue("build_property.MemoryPackGenerator_SerializationInfoOutputDirectory", out var path))
{
return path;
}
return (string?)null;
});
var typeDeclarations = context.SyntaxProvider.ForAttributeWithMetadataName(
MemoryPackableAttributeFullName,
predicate: static (node, token) =>
{
// search [MemoryPackable] class or struct or interface or record
return (node is ClassDeclarationSyntax
or StructDeclarationSyntax
or RecordDeclarationSyntax
or InterfaceDeclarationSyntax);
},
transform: static (context, token) =>
{
return (TypeDeclarationSyntax)context.TargetNode;
});
var parseOptions = context.ParseOptionsProvider.Select((parseOptions, token) =>
{
var csOptions = (CSharpParseOptions)parseOptions;
var langVersion = csOptions.LanguageVersion;
var net7 = csOptions.PreprocessorSymbolNames.Contains("NET7_0_OR_GREATER");
return (langVersion, net7);
});
var source = typeDeclarations
.Combine(context.CompilationProvider)
.WithComparer(Comparer.Instance)
.Combine(logProvider)
.Combine(parseOptions);
context.RegisterSourceOutput(source, static (context, source) =>
{
var (typeDeclaration, compilation) = source.Left.Item1;
var logPath = source.Left.Item2;
var (langVersion, net7) = source.Right;
Generate(typeDeclaration, compilation, logPath, new GeneratorContext(context, langVersion, net7));
});
}
void RegisterTypeScript(IncrementalGeneratorInitializationContext context)
{
var typeScriptEnabled = context.AnalyzerConfigOptionsProvider
.Select((configOptions, token) =>
{
string? path;
if (!configOptions.GlobalOptions.TryGetValue("build_property.MemoryPackGenerator_TypeScriptOutputDirectory", out path))
{
path = null;
}
string ext;
if (!configOptions.GlobalOptions.TryGetValue("build_property.MemoryPackGenerator_TypeScriptImportExtension", out ext!))
{
ext = ".js";
}
return (path, ext);
});
var typeScriptDeclarations = context.SyntaxProvider.ForAttributeWithMetadataName(
GenerateTypeScriptAttributeFullName,
predicate: static (node, token) =>
{
return (node is ClassDeclarationSyntax
or RecordDeclarationSyntax
or InterfaceDeclarationSyntax);
},
transform: static (context, token) =>
{
return (TypeDeclarationSyntax)context.TargetNode;
});
var typeScriptGenerateSource = typeScriptDeclarations
.Combine(context.CompilationProvider)
.WithComparer(Comparer.Instance)
.Combine(typeScriptEnabled)
.Where(x => x.Right.path != null) // filter, exists TypeScriptOutputDirectory
.Collect();
context.RegisterSourceOutput(typeScriptGenerateSource, static (context, source) =>
{
ReferenceSymbols? reference = null;
string? generatePath = null;
var unionMap = new Dictionary<ITypeSymbol, ITypeSymbol>(SymbolEqualityComparer.Default); // <impl, base>
foreach (var item in source)
{
var syntax = item.Left.Item1;
var compilation = item.Left.Item2;
var semanticModel = compilation.GetSemanticModel(syntax.SyntaxTree);
var typeSymbol = semanticModel.GetDeclaredSymbol(syntax, context.CancellationToken) as ITypeSymbol;
if (typeSymbol == null) continue;
if (reference == null)
{
reference = new ReferenceSymbols(compilation);
}
var isUnion = typeSymbol.ContainsAttribute(reference.MemoryPackUnionAttribute);
if (isUnion)
{
var unionTags = typeSymbol.GetAttributes()
.Where(x => SymbolEqualityComparer.Default.Equals(x.AttributeClass, reference.MemoryPackUnionAttribute))
.Where(x => x.ConstructorArguments.Length == 2)
.Select(x => (INamedTypeSymbol)x.ConstructorArguments[1].Value!);
foreach (var implType in unionTags)
{
unionMap[implType] = typeSymbol;
}
}
}
var collector = new TypeCollector();
foreach (var item in source)
{
var typeDeclaration = item.Left.Item1;
var compilation = item.Left.Item2;
var path = generatePath = item.Right.path!;
var importExt = item.Right.ext;
if (reference == null)
{
reference = new ReferenceSymbols(compilation);
}
var meta = GenerateTypeScript(typeDeclaration, compilation, path, importExt, context, reference, unionMap);
if (meta != null)
{
collector.Visit(meta, false);
}
}
if (generatePath != null)
{
GenerateEnums(collector.GetEnums(), generatePath);
// generate runtime
var runtime = new[]{
("MemoryPackWriter.ts", TypeScriptRuntime.MemoryPackWriter),
("MemoryPackReader.ts", TypeScriptRuntime.MemoryPackReader),
};
foreach (var item in runtime)
{
var filePath = Path.Combine(generatePath, item.Item1);
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, item.Item2, new UTF8Encoding(false));
}
}
}
});
}
class Comparer : IEqualityComparer<(TypeDeclarationSyntax, Compilation)>
{
public static readonly Comparer Instance = new Comparer();
public bool Equals((TypeDeclarationSyntax, Compilation) x, (TypeDeclarationSyntax, Compilation) y)
{
return x.Item1.Equals(y.Item1);
}
public int GetHashCode((TypeDeclarationSyntax, Compilation) obj)
{
return obj.Item1.GetHashCode();
}
}
class GeneratorContext : IGeneratorContext
{
SourceProductionContext context;
public GeneratorContext(SourceProductionContext context, LanguageVersion languageVersion, bool isNet70OrGreater)
{
this.context = context;
this.LanguageVersion = languageVersion;
this.IsNet7OrGreater = isNet70OrGreater;
}
public CancellationToken CancellationToken => context.CancellationToken;
public Microsoft.CodeAnalysis.CSharp.LanguageVersion LanguageVersion { get; }
public bool IsNet7OrGreater { get; }
public bool IsForUnity => false;
public void AddSource(string hintName, string source)
{
context.AddSource(hintName, source);
}
public void ReportDiagnostic(Diagnostic diagnostic)
{
context.ReportDiagnostic(diagnostic);
}
}
}