-
Notifications
You must be signed in to change notification settings - Fork 10
/
CompilationData.cs
394 lines (342 loc) · 14.3 KB
/
CompilationData.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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
using Basic.CompilerLog.Util.Impl;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.VisualBasic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace Basic.CompilerLog.Util;
[Flags]
public enum EmitFlags
{
Default = 0,
IncludePdbStream = 0b0001,
IncludeMetadataStream = 0b0010,
IncludeXmlStream = 0b0100,
MetadataOnly = 0b1000,
}
public abstract class CompilationData
{
private ImmutableArray<DiagnosticAnalyzer> _analyzers;
private ImmutableArray<ISourceGenerator> _generators;
private (Compilation, ImmutableArray<Diagnostic>)? _afterGenerators;
public CompilerCall CompilerCall { get; }
public Compilation Compilation { get; }
/// <summary>
/// The <see cref="BasicAnalyzerHost"/> for the analyzers and generators.
/// </summary>
/// <remarks>
/// This is *not* owned by this instance and should not be disposed from here. The creator
/// of this <see cref="CompilationData"/> is responsible for managing the lifetime of this
/// instance.
/// </remarks>
public BasicAnalyzerHost BasicAnalyzerHost { get; }
public EmitData EmitData { get; }
public ImmutableArray<AdditionalText> AdditionalTexts { get; }
public ImmutableArray<AnalyzerReference> AnalyzerReferences { get; }
public AnalyzerConfigOptionsProvider AnalyzerConfigOptionsProvider { get; }
public EmitOptions EmitOptions { get; }
public ParseOptions ParseOptions { get; }
public CompilationOptions CompilationOptions => Compilation.Options;
public bool IsCSharp => Compilation is CSharpCompilation;
public bool IsVisualBasic => !IsCSharp;
public CompilerCallKind Kind => CompilerCall.Kind;
public AnalyzerOptions AnalyzerOptions => new AnalyzerOptions(AdditionalTexts, AnalyzerConfigOptionsProvider);
public EmitFlags EmitFlags
{
get
{
var flags = EmitFlags.Default;
if (IncludePdbStream())
{
flags |= EmitFlags.IncludePdbStream;
}
if (EmitData.XmlFilePath is not null)
{
flags |= EmitFlags.IncludeXmlStream;
}
if (IncludeMetadataStream())
{
flags |= EmitFlags.IncludeMetadataStream;
}
if (EmitOptions.EmitMetadataOnly)
{
flags |= EmitFlags.MetadataOnly;
}
return flags;
}
}
private protected CompilationData(
CompilerCall compilerCall,
Compilation compilation,
ParseOptions parseOptions,
EmitOptions emitOptions,
EmitData emitData,
ImmutableArray<AdditionalText> additionalTexts,
BasicAnalyzerHost basicAnalyzerHost,
AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider)
{
CompilerCall = compilerCall;
Compilation = compilation;
ParseOptions = parseOptions;
EmitOptions = emitOptions;
EmitData = emitData;
AdditionalTexts = additionalTexts;
BasicAnalyzerHost = basicAnalyzerHost;
AnalyzerReferences = basicAnalyzerHost.AnalyzerReferences;
AnalyzerConfigOptionsProvider = analyzerConfigOptionsProvider;
}
public ImmutableArray<DiagnosticAnalyzer> GetAnalyzers()
{
EnsureAnalyzersLoaded();
return _analyzers;
}
public ImmutableArray<ISourceGenerator> GetGenerators()
{
EnsureAnalyzersLoaded();
return _generators;
}
public Compilation GetCompilationAfterGenerators(CancellationToken cancellationToken = default) =>
GetCompilationAfterGenerators(out _, cancellationToken);
public Compilation GetCompilationAfterGenerators(
out ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken = default)
{
if (_afterGenerators is { } tuple)
{
diagnostics = tuple.Item2;
return tuple.Item1;
}
var driver = CreateGeneratorDriver();
driver.RunGeneratorsAndUpdateCompilation(Compilation, out tuple.Item1, out tuple.Item2, cancellationToken);
_afterGenerators = tuple;
diagnostics = tuple.Item2;
// Now that analyzers have completed running add any diagnostics the host has captured
if (BasicAnalyzerHost.GetDiagnostics() is { Count: > 0} list)
{
diagnostics = diagnostics.AddRange(list);
}
return tuple.Item1;
}
public List<SyntaxTree> GetGeneratedSyntaxTrees(CancellationToken cancellationToken = default) =>
GetGeneratedSyntaxTrees(out _, cancellationToken);
public List<SyntaxTree> GetGeneratedSyntaxTrees(
out ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken = default)
{
var afterCompilation = GetCompilationAfterGenerators(out diagnostics, cancellationToken);
// Generated syntax trees are always added to the end of the list. This is an
// implementation detail of the compiler, but one that is unlikely to ever
// change. Doing so would represent a breaking change as file ordering impacts
// semantics.
var originalCount = Compilation.SyntaxTrees.Count();
return afterCompilation.SyntaxTrees.Skip(originalCount).ToList();
}
private void EnsureAnalyzersLoaded()
{
if (!_analyzers.IsDefault)
{
Debug.Assert(!_generators.IsDefault);
return;
}
var languageName = IsCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic;
var analyzerBuilder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>();
var generatorBuilder = ImmutableArray.CreateBuilder<ISourceGenerator>();
foreach (var analyzerReference in AnalyzerReferences)
{
analyzerBuilder.AddRange(analyzerReference.GetAnalyzers(languageName));
generatorBuilder.AddRange(analyzerReference.GetGenerators(languageName));
}
_analyzers = analyzerBuilder.ToImmutableArray();
_generators = generatorBuilder.ToImmutableArray();
}
protected abstract GeneratorDriver CreateGeneratorDriver();
/// <summary>
/// This gets diagnostics from the compiler (does not include analyzers)
/// </summary>
public ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default)
{
var diagnostics = GetCompilationAfterGenerators(out var hostDiagnostics, cancellationToken).GetDiagnostics();
return diagnostics.AddRange(hostDiagnostics);
}
/// <summary>
/// This gets diagnostics from the compiler and any attached analyzers.
/// </summary>
public async Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync(CancellationToken cancellationToken = default)
{
var compilation = GetCompilationAfterGenerators(out var hostDiagnostics, cancellationToken);
var analyzers = GetAnalyzers();
ImmutableArray<Diagnostic> diagnostics;
if (analyzers.IsDefaultOrEmpty)
{
diagnostics = compilation.GetDiagnostics(cancellationToken);
}
else
{
var cwa = new CompilationWithAnalyzers(compilation, GetAnalyzers(), AnalyzerOptions);
diagnostics = await cwa.GetAllDiagnosticsAsync().ConfigureAwait(false);
}
return diagnostics.AddRange(hostDiagnostics);
}
public EmitDiskResult EmitToDisk(string directory, CancellationToken cancellationToken = default) =>
EmitToDisk(directory, EmitFlags, EmitOptions, cancellationToken);
public EmitDiskResult EmitToDisk(string directory, EmitFlags emitFlags, EmitOptions? emitOptions = null, CancellationToken cancellationToken = default)
{
var compilation = GetCompilationAfterGenerators(out var diagnostics, cancellationToken);
var assemblyName = EmitData.AssemblyFileName;
string assemblyFilePath = Path.Combine(directory, assemblyName);
emitOptions ??= EmitOptions;
Stream? peStream = null;
Stream? pdbStream = null;
string? pdbFilePath = null;
Stream? xmlStream = null;
string? xmlFilePath = null;
Stream? metadataStream = null;
string? metadataFilePath = null;
try
{
peStream = OpenFile(assemblyFilePath);
if ((emitFlags & EmitFlags.IncludePdbStream) != 0)
{
pdbFilePath = Path.Combine(directory, Path.ChangeExtension(assemblyName, ".pdb"));
pdbStream = OpenFile(pdbFilePath);
}
if ((emitFlags & EmitFlags.IncludeXmlStream) != 0)
{
xmlFilePath = Path.Combine(directory, Path.ChangeExtension(assemblyName, ".xml"));
xmlStream = OpenFile(xmlFilePath);
}
if ((emitFlags & EmitFlags.IncludeMetadataStream) != 0)
{
metadataFilePath = Path.Combine(directory, "ref", assemblyName);
metadataStream = OpenFile(metadataFilePath);
}
if ((emitFlags & EmitFlags.MetadataOnly) != 0)
{
emitOptions = EmitOptions.WithEmitMetadataOnly(true);
}
var result = compilation.Emit(
peStream,
pdbStream,
xmlStream,
EmitData.Win32ResourceStream,
EmitData.Resources,
emitOptions,
debugEntryPoint: null,
EmitData.SourceLinkStream,
EmitData.EmbeddedTexts,
cancellationToken);
diagnostics = diagnostics.Concat(result.Diagnostics).ToImmutableArray();
return new EmitDiskResult(
result.Success,
directory,
assemblyName,
assemblyFilePath,
pdbFilePath,
xmlFilePath,
metadataFilePath,
diagnostics);
}
finally
{
peStream?.Dispose();
pdbStream?.Dispose();
xmlStream?.Dispose();
metadataStream?.Dispose();
}
Stream OpenFile(string filePath)
{
Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
return new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
}
}
public EmitMemoryResult EmitToMemory(
EmitFlags? emitFlags = null,
EmitOptions? emitOptions = null,
CancellationToken cancellationToken = default)
{
var compilation = GetCompilationAfterGenerators(out var diagnostics, cancellationToken);
var emitResult = compilation.EmitToMemory(
emitFlags ?? EmitFlags,
win32ResourceStream: EmitData.Win32ResourceStream,
manifestResources: EmitData.Resources,
emitOptions: emitOptions ?? EmitOptions,
sourceLinkStream: EmitData.SourceLinkStream,
embeddedTexts: EmitData.EmbeddedTexts,
cancellationToken: cancellationToken);
if (!diagnostics.IsDefaultOrEmpty)
{
emitResult = new EmitMemoryResult(
emitResult.Success,
emitResult.AssemblyStream,
emitResult.PdbStream,
emitResult.XmlStream,
emitResult.MetadataStream,
emitResult.Diagnostics.AddRange(diagnostics));
}
return emitResult;
}
private bool IncludePdbStream() =>
EmitOptions.DebugInformationFormat != DebugInformationFormat.Embedded &&
!EmitOptions.EmitMetadataOnly;
private bool IncludeMetadataStream() =>
!EmitOptions.EmitMetadataOnly &&
!EmitOptions.IncludePrivateMembers &&
CompilationOptions.OutputKind != OutputKind.NetModule;
}
public abstract class CompilationData<TCompilation, TParseOptions> : CompilationData
where TCompilation : Compilation
where TParseOptions : ParseOptions
{
public new TCompilation Compilation => (TCompilation)base.Compilation;
public new TParseOptions ParseOptions => (TParseOptions)base.ParseOptions;
private protected CompilationData(
CompilerCall compilerCall,
TCompilation compilation,
TParseOptions parseOptions,
EmitOptions emitOptions,
EmitData emitData,
ImmutableArray<AdditionalText> additionalTexts,
BasicAnalyzerHost basicAnalyzerHost,
AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider)
:base(compilerCall, compilation, parseOptions, emitOptions, emitData, additionalTexts, basicAnalyzerHost, analyzerConfigOptionsProvider)
{
}
}
public sealed class CSharpCompilationData : CompilationData<CSharpCompilation, CSharpParseOptions>
{
internal CSharpCompilationData(
CompilerCall compilerCall,
CSharpCompilation compilation,
CSharpParseOptions parseOptions,
EmitOptions emitOptions,
EmitData emitData,
ImmutableArray<AdditionalText> additionalTexts,
BasicAnalyzerHost basicAnalyzerHost,
AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider)
:base(compilerCall, compilation, parseOptions, emitOptions, emitData, additionalTexts, basicAnalyzerHost, analyzerConfigOptionsProvider)
{
}
protected override GeneratorDriver CreateGeneratorDriver() =>
CSharpGeneratorDriver.Create(GetGenerators(), AdditionalTexts, ParseOptions, AnalyzerConfigOptionsProvider);
}
public sealed class VisualBasicCompilationData : CompilationData<VisualBasicCompilation, VisualBasicParseOptions>
{
internal VisualBasicCompilationData(
CompilerCall compilerCall,
VisualBasicCompilation compilation,
VisualBasicParseOptions parseOptions,
EmitOptions emitOptions,
EmitData emitData,
ImmutableArray<AdditionalText> additionalTexts,
BasicAnalyzerHost basicAnalyzerHost,
AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider)
: base(compilerCall, compilation, parseOptions, emitOptions, emitData, additionalTexts, basicAnalyzerHost, analyzerConfigOptionsProvider)
{
}
protected override GeneratorDriver CreateGeneratorDriver() =>
VisualBasicGeneratorDriver.Create(GetGenerators(), AdditionalTexts, ParseOptions, AnalyzerConfigOptionsProvider);
}