-
-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathCSharpGeneratorRunner.cs
More file actions
188 lines (157 loc) · 6.97 KB
/
CSharpGeneratorRunner.cs
File metadata and controls
188 lines (157 loc) · 6.97 KB
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
using MemoryPack.Generator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
namespace MemoryPack.Tests.Utils;
public static class CSharpGeneratorRunner
{
static Compilation baseCompilation = default!;
[ModuleInitializer]
public static void InitializeCompilation()
{
var globalUsings = """
global using System;
global using System.Linq;
global using System.Collections;
global using System.Collections.Generic;
global using System.Threading;
global using System.Threading.Tasks;
global using System.ComponentModel.DataAnnotations;
global using MemoryPack;
""";
var systemAssemblies = AppDomain.CurrentDomain.GetAssemblies()
.Where(x => !x.IsDynamic && !string.IsNullOrWhiteSpace(x.Location));
var references = systemAssemblies
.Append(typeof(MemoryPackableAttribute).Assembly) // System Assemblies + MemoryPack.Core.dll
.Select(x => MetadataReference.CreateFromFile(x.Location))
.ToArray();
var compilation = CSharpCompilation.Create("generatortest",
references: references,
syntaxTrees: [CSharpSyntaxTree.ParseText(globalUsings, path: "GlobalUsings.cs")],
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true));
baseCompilation = compilation;
}
public static (Compilation, ImmutableArray<Diagnostic>) RunGenerator(string source, string[]? preprocessorSymbols = null, AnalyzerConfigOptionsProvider? options = null)
{
if (preprocessorSymbols == null)
{
preprocessorSymbols = new[] { "NET7_0_OR_GREATER" };
}
var parseOptions = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: preprocessorSymbols);
var driver = CSharpGeneratorDriver.Create(new MemoryPackGenerator()).WithUpdatedParseOptions(parseOptions);
if (options != null)
{
driver = (Microsoft.CodeAnalysis.CSharp.CSharpGeneratorDriver)driver.WithUpdatedAnalyzerConfigOptions(options);
}
var compilation = baseCompilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(source, parseOptions));
driver.RunGeneratorsAndUpdateCompilation(compilation, out var newCompilation, out var diagnostics);
return (newCompilation, diagnostics);
}
public static (string Key, string Reasons)[][] GetIncrementalGeneratorTrackedStepsReasons(string keyPrefixFilter, params string[] sources)
{
var parseOptions = new CSharpParseOptions(LanguageVersion.Latest);
var driver = CSharpGeneratorDriver.Create(
[new MemoryPackGenerator().AsSourceGenerator()],
driverOptions: new GeneratorDriverOptions(IncrementalGeneratorOutputKind.None, trackIncrementalGeneratorSteps: true))
.WithUpdatedParseOptions(parseOptions);
var generatorResults = sources
.Select(source =>
{
var compilation = baseCompilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(source, parseOptions));
driver = driver.RunGenerators(compilation);
return driver.GetRunResult().Results[0];
})
.ToArray();
var reasons = generatorResults
.Select(x => x.TrackedSteps
.Where(x => x.Key.StartsWith(keyPrefixFilter) || x.Key == "SourceOutput")
.Select(x =>
{
if (x.Key == "SourceOutput")
{
var values = x.Value.Where(x => x.Inputs[0].Source.Name?.StartsWith(keyPrefixFilter) ?? false);
return (
x.Key,
Reasons: string.Join(", ", values.SelectMany(x => x.Outputs).Select(x => x.Reason).ToArray())
);
}
else
{
return (
Key: x.Key.Substring(keyPrefixFilter.Length),
Reasons: string.Join(", ", x.Value.SelectMany(x => x.Outputs).Select(x => x.Reason).ToArray())
);
}
})
.OrderBy(x => x.Key)
.ToArray())
.ToArray();
return reasons;
}
}
public class VerifyHelper(ITestOutputHelper output, string idPrefix)
{
// Diagnostics Verify
public void Ok([StringSyntax("C#-test")] string code, [CallerArgumentExpression("code")] string? codeExpr = null)
{
output.WriteLine(codeExpr);
var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator(code);
foreach (var item in diagnostics)
{
output.WriteLine(item.ToString());
}
OutputGeneratedCode(compilation);
diagnostics.Length.Should().Be(0);
}
public void Verify(int id, [StringSyntax("C#-test")] string code, string diagnosticsCodeSpan, [CallerArgumentExpression("code")] string? codeExpr = null)
{
output.WriteLine(codeExpr);
var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator(code);
foreach (var item in diagnostics)
{
output.WriteLine(item.ToString());
}
OutputGeneratedCode(compilation);
diagnostics.Length.Should().Be(1);
diagnostics[0].Id.Should().Be(idPrefix + id.ToString("000"));
var text = GetLocationText(diagnostics[0], compilation.SyntaxTrees);
text.Should().Be(diagnosticsCodeSpan);
}
public (string, string)[] Verify([StringSyntax("C#-test")] string code, [CallerArgumentExpression("code")] string? codeExpr = null)
{
output.WriteLine(codeExpr);
var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator(code);
OutputGeneratedCode(compilation);
return diagnostics.Select(x => (x.Id, GetLocationText(x, compilation.SyntaxTrees))).ToArray();
}
string GetLocationText(Diagnostic diagnostic, IEnumerable<SyntaxTree> syntaxTrees)
{
var location = diagnostic.Location;
var textSpan = location.SourceSpan;
var sourceTree = location.SourceTree;
if (sourceTree == null)
{
var lineSpan = location.GetLineSpan();
if (lineSpan.Path == null) return "";
sourceTree = syntaxTrees.FirstOrDefault(x => x.FilePath == lineSpan.Path);
if (sourceTree == null) return "";
}
var text = sourceTree.GetText().GetSubText(textSpan).ToString();
return text;
}
void OutputGeneratedCode(Compilation compilation)
{
foreach (var syntaxTree in compilation.SyntaxTrees)
{
// only shows ConsoleApp.Run/Builder generated code
if (!syntaxTree.FilePath.Contains("g.cs")) continue;
output.WriteLine(syntaxTree.ToString());
}
}
}