-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCompilationExtensions.cs
More file actions
59 lines (51 loc) · 1.82 KB
/
CompilationExtensions.cs
File metadata and controls
59 lines (51 loc) · 1.82 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
namespace NServiceBus.AzureFunctions.InProcess.Analyzer.Tests;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
static class CompilationExtensions
{
public static void Compile(this Compilation compilation, bool throwOnFailure = true)
{
using (var peStream = new MemoryStream())
{
var emitResult = compilation.Emit(peStream);
if (!emitResult.Success)
{
if (throwOnFailure)
{
throw new Exception("Compilation failed.");
}
else
{
Debug.WriteLine("Compilation failed.");
}
}
}
}
public static async Task<IEnumerable<Diagnostic>> GetAnalyzerDiagnostics(this Compilation compilation, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken = default)
{
var exceptions = new List<Exception>();
var analysisOptions = new CompilationWithAnalyzersOptions(
new AnalyzerOptions(ImmutableArray<AdditionalText>.Empty),
(exception, _, __) => exceptions.Add(exception),
concurrentAnalysis: false,
logAnalyzerExecutionTime: false);
var diagnostics = await compilation
.WithAnalyzers([analyzer], analysisOptions)
.GetAnalyzerDiagnosticsAsync(cancellationToken);
if (exceptions.Any())
{
throw new AggregateException(exceptions);
}
return diagnostics
.OrderBy(diagnostic => diagnostic.Location.SourceSpan)
.ThenBy(diagnostic => diagnostic.Id);
}
}