-
Notifications
You must be signed in to change notification settings - Fork 172
/
AnalyzerAssemblyGenerator.cs
112 lines (102 loc) · 4.5 KB
/
AnalyzerAssemblyGenerator.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
namespace Microsoft.CodeAnalysis.Tools.Tests.Analyzers
{
public static class AnalyzerAssemblyGenerator
{
public static SyntaxTree GenerateCodeFix(string typeName, string diagnosticId)
{
var codefix = $@"
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof({typeName})), Shared]
public class {typeName} : CodeFixProvider
{{
public const string DiagnosticId = ""{diagnosticId}"";
public sealed override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider()
{{
return WellKnownFixAllProviders.BatchFixer;
}}
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{{
throw new NotImplementedException();
}}
}}";
return CSharpSyntaxTree.ParseText(codefix);
}
public static SyntaxTree GenerateAnalyzerCode(string typeName, string diagnosticId)
{
var analyzer = $@"
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class {typeName} : DiagnosticAnalyzer
{{
public const string DiagnosticId = ""{diagnosticId}"";
internal static readonly LocalizableString Title = ""{typeName} Title"";
internal static readonly LocalizableString MessageFormat = ""{typeName} '{{0}}'"";
internal const string Category = ""{typeName} Category"";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{{
}}
}}";
return CSharpSyntaxTree.ParseText(analyzer);
}
public static async Task<Assembly> GenerateAssemblyAsync(params SyntaxTree[] trees)
{
var assemblyName = Guid.NewGuid().ToString();
var references = new List<MetadataReference>()
{
MetadataReference.CreateFromFile(typeof(ImmutableArray).Assembly.Location),
MetadataReference.CreateFromFile(typeof(SharedAttribute).Assembly.Location),
MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location),
MetadataReference.CreateFromFile(typeof(DiagnosticAnalyzer).Assembly.Location),
MetadataReference.CreateFromFile(typeof(CodeFixProvider).Assembly.Location),
};
var netstandardMetaDataReferences = await ReferenceAssemblies.NetStandard.NetStandard20.ResolveAsync(LanguageNames.CSharp, CancellationToken.None);
references.AddRange(netstandardMetaDataReferences);
var compilation = CSharpCompilation.Create(assemblyName, trees, references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
if (!result.Success)
{
var failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error)
.Select(diagnostic => $"{diagnostic.Id}: {diagnostic.GetMessage()}");
throw new Exception(string.Join(Environment.NewLine, failures));
}
else
{
ms.Seek(0, SeekOrigin.Begin);
var assembly = Assembly.Load(ms.ToArray());
return assembly;
}
}
}
}
}