-
Notifications
You must be signed in to change notification settings - Fork 4k
/
AnalyzerConfigSet.cs
208 lines (183 loc) · 9.89 KB
/
AnalyzerConfigSet.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
// 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.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.AnalyzerConfig;
using AnalyzerOptions = System.Collections.Immutable.ImmutableDictionary<string, string>;
using TreeOptions = System.Collections.Immutable.ImmutableDictionary<string, Microsoft.CodeAnalysis.ReportDiagnostic>;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a set of <see cref="AnalyzerConfig"/>, and can compute the effective analyzer options for a given source file. This is used to
/// collect all the <see cref="AnalyzerConfig"/> files for that would apply to a compilation.
/// </summary>
public sealed class AnalyzerConfigSet
{
/// <summary>
/// The list of <see cref="AnalyzerConfig" />s in this set. This list has been sorted per <see cref="AnalyzerConfig.DirectoryLengthComparer"/>.
/// </summary>
private readonly ImmutableArray<AnalyzerConfig> _analyzerConfigs;
/// <summary>
/// <see cref="SectionNameMatcher"/>s for each section. The entries in the outer array correspond to entries in <see cref="_analyzerConfigs"/>, and each inner array
/// corresponds to each <see cref="AnalyzerConfig.NamedSections"/>.
/// </summary>
private readonly ImmutableArray<ImmutableArray<SectionNameMatcher?>> _analyzerMatchers;
private readonly static DiagnosticDescriptor InvalidAnalyzerConfigSeverityDescriptor
= new DiagnosticDescriptor(
"InvalidSeverityInAnalyzerConfig",
CodeAnalysisResources.WRN_InvalidSeverityInAnalyzerConfig_Title,
CodeAnalysisResources.WRN_InvalidSeverityInAnalyzerConfig,
"AnalyzerConfig",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static AnalyzerConfigSet Create<TList>(TList analyzerConfigs) where TList : IReadOnlyCollection<AnalyzerConfig>
{
var sortedAnalyzerConfigs = ArrayBuilder<AnalyzerConfig>.GetInstance(analyzerConfigs.Count);
sortedAnalyzerConfigs.AddRange(analyzerConfigs);
sortedAnalyzerConfigs.Sort(AnalyzerConfig.DirectoryLengthComparer);
return new AnalyzerConfigSet(sortedAnalyzerConfigs.ToImmutableAndFree());
}
private AnalyzerConfigSet(ImmutableArray<AnalyzerConfig> analyzerConfigs)
{
_analyzerConfigs = analyzerConfigs;
var allMatchers = ArrayBuilder<ImmutableArray<SectionNameMatcher?>>.GetInstance(_analyzerConfigs.Length);
foreach (var config in _analyzerConfigs)
{
// Create an array of regexes with each entry corresponding to the same index
// in <see cref="EditorConfig.NamedSections"/>.
var builder = ArrayBuilder<SectionNameMatcher?>.GetInstance(config.NamedSections.Length);
foreach (var section in config.NamedSections)
{
SectionNameMatcher? matcher = AnalyzerConfig.TryCreateSectionNameMatcher(section.Name);
builder.Add(matcher);
}
Debug.Assert(builder.Count == config.NamedSections.Length);
allMatchers.Add(builder.ToImmutableAndFree());
}
Debug.Assert(allMatchers.Count == _analyzerConfigs.Length);
_analyzerMatchers = allMatchers.ToImmutableAndFree();
}
/// <summary>
/// Returns a <see cref="AnalyzerConfigOptionsResult"/> for a source file. This computes which <see cref="AnalyzerConfig"/> rules applies to this file, and correctly applies
/// precedence rules if there are multiple rules for the same file.
/// </summary>
/// <param name="sourcePath">The path to a file such as a source file or additional file. Must be non-null.</param>
public AnalyzerConfigOptionsResult GetOptionsForSourcePath(string sourcePath)
{
if (sourcePath == null)
{
throw new System.ArgumentNullException(nameof(sourcePath));
}
var treeOptionsBuilder = ImmutableDictionary.CreateBuilder<string, ReportDiagnostic>(
CaseInsensitiveComparison.Comparer);
var analyzerOptionsBuilder = ImmutableDictionary.CreateBuilder<string, string>(
CaseInsensitiveComparison.Comparer);
var diagnosticBuilder = ArrayBuilder<Diagnostic>.GetInstance();
var normalizedPath = PathUtilities.NormalizeWithForwardSlash(sourcePath);
// The editorconfig paths are sorted from shortest to longest, so matches
// are resolved from most nested to least nested, where last setting wins
for (int analyzerConfigIndex = 0; analyzerConfigIndex < _analyzerConfigs.Length; analyzerConfigIndex++)
{
var config = _analyzerConfigs[analyzerConfigIndex];
if (normalizedPath.StartsWith(config.NormalizedDirectory, StringComparison.Ordinal))
{
int dirLength = config.NormalizedDirectory.Length;
// Leave '/' if the normalized directory ends with a '/'. This can happen if
// we're in a root directory (e.g. '/' or 'Z:/'). The section matching
// always expects that the relative path start with a '/'.
if (config.NormalizedDirectory[dirLength - 1] == '/')
{
dirLength--;
}
string relativePath = normalizedPath.Substring(dirLength);
ImmutableArray<SectionNameMatcher?> matchers = _analyzerMatchers[analyzerConfigIndex];
for (int sectionIndex = 0; sectionIndex < matchers.Length; sectionIndex++)
{
if (matchers[sectionIndex]?.IsMatch(relativePath) == true)
{
var section = config.NamedSections[sectionIndex];
addOptions(section, treeOptionsBuilder, analyzerOptionsBuilder, config.PathToFile);
}
}
}
}
return new AnalyzerConfigOptionsResult(
treeOptionsBuilder.Count > 0 ? treeOptionsBuilder.ToImmutable() : SyntaxTree.EmptyDiagnosticOptions,
analyzerOptionsBuilder.Count > 0 ? analyzerOptionsBuilder.ToImmutable() : AnalyzerConfigOptions.EmptyDictionary,
diagnosticBuilder.ToImmutableAndFree());
void addOptions(
AnalyzerConfig.Section section,
TreeOptions.Builder treeBuilder,
AnalyzerOptions.Builder analyzerBuilder,
string analyzerConfigPath)
{
const string DiagnosticOptionPrefix = "dotnet_diagnostic.";
const string DiagnosticOptionSuffix = ".severity";
foreach (var (key, value) in section.Properties)
{
// Keys are lowercased in editorconfig parsing
int diagIdLength = -1;
if (key.StartsWith(DiagnosticOptionPrefix, StringComparison.Ordinal) &&
key.EndsWith(DiagnosticOptionSuffix, StringComparison.Ordinal))
{
diagIdLength = key.Length - (DiagnosticOptionPrefix.Length + DiagnosticOptionSuffix.Length);
}
if (diagIdLength >= 0)
{
var diagId = key.Substring(
DiagnosticOptionPrefix.Length,
diagIdLength);
ReportDiagnostic? severity;
var comparer = StringComparer.OrdinalIgnoreCase;
if (comparer.Equals(value, "default"))
{
severity = ReportDiagnostic.Default;
}
else if (comparer.Equals(value, "error"))
{
severity = ReportDiagnostic.Error;
}
else if (comparer.Equals(value, "warning"))
{
severity = ReportDiagnostic.Warn;
}
else if (comparer.Equals(value, "suggestion"))
{
severity = ReportDiagnostic.Info;
}
else if (comparer.Equals(value, "silent") || comparer.Equals(value, "refactoring"))
{
severity = ReportDiagnostic.Hidden;
}
else if (comparer.Equals(value, "none"))
{
severity = ReportDiagnostic.Suppress;
}
else
{
severity = null;
diagnosticBuilder.Add(Diagnostic.Create(
InvalidAnalyzerConfigSeverityDescriptor,
Location.None,
diagId,
value,
analyzerConfigPath));
}
if (severity.HasValue)
{
treeBuilder[diagId] = severity.GetValueOrDefault();
}
}
else
{
analyzerBuilder[key] = value;
}
}
}
}
}
}