forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoslynTestUtils.cs
More file actions
296 lines (251 loc) · 11 KB
/
Copy pathRoslynTestUtils.cs
File metadata and controls
296 lines (251 loc) · 11 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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace SourceGenerators.Tests
{
internal static class RoslynTestUtils
{
/// <summary>
/// Creates a canonical Roslyn project for testing.
/// </summary>
/// <param name="references">Assembly references to include in the project.</param>
/// <param name="includeBaseReferences">Whether to include references to the BCL assemblies.</param>
public static Project CreateTestProject(IEnumerable<Assembly>? references, bool includeBaseReferences = true)
{
string corelib = Assembly.GetAssembly(typeof(object))!.Location;
string runtimeDir = Path.GetDirectoryName(corelib)!;
var refs = new List<MetadataReference>();
if (includeBaseReferences)
{
refs.Add(MetadataReference.CreateFromFile(corelib));
refs.Add(MetadataReference.CreateFromFile(Path.Combine(runtimeDir, "netstandard.dll")));
refs.Add(MetadataReference.CreateFromFile(Path.Combine(runtimeDir, "System.Runtime.dll")));
}
if (references != null)
{
foreach (var r in references)
{
refs.Add(MetadataReference.CreateFromFile(r.Location));
}
}
return new AdhocWorkspace()
.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create()))
.AddProject("Test", "test.dll", "C#")
.WithMetadataReferences(refs)
.WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable));
}
public static Task CommitChanges(this Project proj, params string[] ignorables)
{
Assert.True(proj.Solution.Workspace.TryApplyChanges(proj.Solution));
return AssertNoDiagnostic(proj, ignorables);
}
public static async Task AssertNoDiagnostic(this Project proj, params string[] ignorables)
{
foreach (Document doc in proj.Documents)
{
SemanticModel sm = await doc.GetSemanticModelAsync(CancellationToken.None).ConfigureAwait(false);
Assert.NotNull(sm);
foreach (Diagnostic d in sm!.GetDiagnostics())
{
bool ignore = ignorables.Any(ig => d.Id == ig);
Assert.True(ignore, d.ToString());
}
}
}
public static Project WithDocument(this Project proj, string name, string text)
{
return proj.AddDocument(name, text).Project;
}
public static Document FindDocument(this Project proj, string name)
{
foreach (Document doc in proj.Documents)
{
if (doc.Name == name)
{
return doc;
}
}
throw new FileNotFoundException(name);
}
/// <summary>
/// Looks for /*N+*/ and /*-N*/ markers in a string and creates a TextSpan containing the enclosed text.
/// </summary>
public static TextSpan MakeSpan(string text, int spanNum)
{
int start = text.IndexOf($"/*{spanNum}+*/", StringComparison.Ordinal);
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(spanNum));
}
start += 6;
int end = text.IndexOf($"/*-{spanNum}*/", StringComparison.Ordinal);
if (end < 0)
{
throw new ArgumentOutOfRangeException(nameof(spanNum));
}
end -= 1;
return new TextSpan(start, end - start);
}
/// <summary>
/// Runs a Roslyn generator over a set of source files.
/// </summary>
public static async Task<(ImmutableArray<Diagnostic>, ImmutableArray<GeneratedSourceResult>)> RunGenerator(
ISourceGenerator generator,
IEnumerable<Assembly>? references,
IEnumerable<string> sources,
AnalyzerConfigOptionsProvider? optionsProvider = null,
bool includeBaseReferences = true,
CancellationToken cancellationToken = default)
{
Project proj = CreateTestProject(references, includeBaseReferences);
int count = 0;
foreach (string s in sources)
{
proj = proj.WithDocument($"src-{count++}.cs", s);
}
Assert.True(proj.Solution.Workspace.TryApplyChanges(proj.Solution));
Compilation comp = await proj!.GetCompilationAsync(CancellationToken.None).ConfigureAwait(false);
CSharpGeneratorDriver cgd = CSharpGeneratorDriver.Create(new[] { generator }, optionsProvider: optionsProvider);
GeneratorDriver gd = cgd.RunGenerators(comp!, cancellationToken);
GeneratorDriverRunResult r = gd.GetRunResult();
return (r.Results[0].Diagnostics, r.Results[0].GeneratedSources);
}
/// <summary>
/// Runs a Roslyn analyzer over a set of source files.
/// </summary>
public static async Task<IList<Diagnostic>> RunAnalyzer(
DiagnosticAnalyzer analyzer,
IEnumerable<Assembly> references,
IEnumerable<string> sources)
{
Project proj = CreateTestProject(references);
int count = 0;
foreach (string s in sources)
{
proj = proj.WithDocument($"src-{count++}.cs", s);
}
await proj.CommitChanges().ConfigureAwait(false);
ImmutableArray<DiagnosticAnalyzer> analyzers = ImmutableArray.Create(analyzer);
Compilation comp = await proj!.GetCompilationAsync().ConfigureAwait(false);
return await comp!.WithAnalyzers(analyzers).GetAllDiagnosticsAsync().ConfigureAwait(false);
}
/// <summary>
/// Runs a Roslyn analyzer and fixer.
/// </summary>
public static async Task<IList<string>> RunAnalyzerAndFixer(
DiagnosticAnalyzer analyzer,
CodeFixProvider fixer,
IEnumerable<Assembly> references,
IEnumerable<string> sources,
IEnumerable<string>? sourceNames = null,
string? defaultNamespace = null,
string? extraFile = null)
{
Project proj = CreateTestProject(references);
int count = 0;
if (sourceNames != null)
{
List<string> l = sourceNames.ToList();
foreach (string s in sources)
{
proj = proj.WithDocument(l[count++], s);
}
}
else
{
foreach (string s in sources)
{
proj = proj.WithDocument($"src-{count++}.cs", s);
}
}
if (defaultNamespace != null)
{
proj = proj.WithDefaultNamespace(defaultNamespace);
}
await proj.CommitChanges().ConfigureAwait(false);
ImmutableArray<DiagnosticAnalyzer> analyzers = ImmutableArray.Create(analyzer);
while (true)
{
Compilation comp = await proj!.GetCompilationAsync().ConfigureAwait(false);
ImmutableArray<Diagnostic> diags = await comp!.WithAnalyzers(analyzers).GetAllDiagnosticsAsync().ConfigureAwait(false);
if (diags.IsEmpty)
{
// no more diagnostics reported by the analyzers
break;
}
var actions = new List<CodeAction>();
foreach (Diagnostic d in diags)
{
Document doc = proj.GetDocument(d.Location.SourceTree);
CodeFixContext context = new CodeFixContext(doc!, d, (action, _) => actions.Add(action), CancellationToken.None);
await fixer.RegisterCodeFixesAsync(context).ConfigureAwait(false);
}
if (actions.Count == 0)
{
// nothing to fix
break;
}
ImmutableArray<CodeActionOperation> operations = await actions[0].GetOperationsAsync(CancellationToken.None).ConfigureAwait(false);
Solution solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution;
Project changedProj = solution.GetProject(proj.Id);
if (changedProj != proj)
{
proj = await RecreateProjectDocumentsAsync(changedProj!).ConfigureAwait(false);
}
}
var results = new List<string>();
if (sourceNames != null)
{
List<string> l = sourceNames.ToList();
for (int i = 0; i < count; i++)
{
SourceText s = await proj.FindDocument(l[i]).GetTextAsync().ConfigureAwait(false);
results.Add(s.ToString().Replace("\r\n", "\n", StringComparison.Ordinal));
}
}
else
{
for (int i = 0; i < count; i++)
{
SourceText s = await proj.FindDocument($"src-{i}.cs").GetTextAsync().ConfigureAwait(false);
results.Add(s.ToString().Replace("\r\n", "\n", StringComparison.Ordinal));
}
}
if (extraFile != null)
{
SourceText s = await proj.FindDocument(extraFile).GetTextAsync().ConfigureAwait(false);
results.Add(s.ToString().Replace("\r\n", "\n", StringComparison.Ordinal));
}
return results;
}
private static async Task<Project> RecreateProjectDocumentsAsync(Project project)
{
foreach (DocumentId documentId in project.DocumentIds)
{
Document document = project.GetDocument(documentId);
document = await RecreateDocumentAsync(document!).ConfigureAwait(false);
project = document.Project;
}
return project;
}
private static async Task<Document> RecreateDocumentAsync(Document document)
{
SourceText newText = await document.GetTextAsync().ConfigureAwait(false);
return document.WithText(SourceText.From(newText.ToString(), newText.Encoding, newText.ChecksumAlgorithm));
}
}
}