-
Notifications
You must be signed in to change notification settings - Fork 4
/
Settings.cs
405 lines (336 loc) · 13.4 KB
/
Settings.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
395
396
397
398
399
400
401
402
403
404
405
namespace Menees.Analyzers
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Win32;
#endregion
internal sealed class Settings
{
#region Private Data Members
private const string SettingsBaseName = "Menees.Analyzers.Settings";
private const string SettingsFileName = SettingsBaseName + ".xml";
private static readonly SourceTextValueProvider<Settings> ValueProvider = new(LoadSettings);
private static readonly IEnumerable<Predicate<string>> DefaultTypeFileNameExclusions = new[]
{
CreateFileNamePredicate("Enumerations.cs"),
CreateFileRegexPredicate(@"^Enumerations\..*\.cs$"),
CreateFileNamePredicate("Interfaces.cs"),
CreateFileRegexPredicate(@"^Interfaces\..*\.cs$"),
CreateFileNamePredicate("Delegates.cs"),
CreateFileRegexPredicate(@"^Delegates\..*\.cs$"),
// Razor pages like Page.cshtml.cs contain PageModel instead of just Page.
CreateFileRegexPredicate(@"^.*\.cshtml.*\.cs$"),
// Note: We don't need to do the following because these files shouldn't contain types (just assembly attributes):
// CreateFileRegexPredicate(".*AssemblyInfo\.cs$"),
// CreateFileNamePredicate("GlobalSuppressions.cs"),
};
// Note: The UL compound suffix is handled in a loop through these suffixes.
private static readonly HashSet<char> CSharpNumericSuffixes = new(new[] { 'L', 'D', 'F', 'U', 'M', 'l', 'd', 'f', 'u', 'm', });
private static readonly Dictionary<string, string> DefaultPreferredTerms = new()
{
// These are the single terms from CA1726 plus the special case of "ID -> Id" from CA1709.
// https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1726?view=vs-2019#rule-description
// https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1709?view=vs-2019#rule-description
{ "Arent", "AreNot" },
{ "Cancelled", "Canceled" },
{ "Cant", "Cannot" },
{ "Couldnt", "CouldNot" },
{ "Didnt", "DidNot" },
{ "Doesnt", "DoesNot" },
{ "Dont", "DoNot" },
{ "Hadnt", "HadNot" },
{ "Hasnt", "HasNot" },
{ "Havent", "HaveNot" },
{ "ID", "Id" },
{ "Indices", "Indexes" },
{ "Isnt", "IsNot" },
{ "Shouldnt", "ShouldNot" },
{ "Wasnt", "WasNot" },
{ "Werent", "WereNot" },
{ "Wont", "WillNot" },
{ "Wouldnt", "WouldNot" },
{ "Writeable", "Writable" },
};
private static readonly Settings DefaultSettings = new();
private readonly IEnumerable<Predicate<string>> typeFileNameExclusions = DefaultTypeFileNameExclusions;
private readonly HashSet<string> allowedNumericLiterals = new(new[] { "0", "1", "2", "100" });
private readonly HashSet<string> allowedNumericCallerNames = new(new[]
{
"FromDays", "FromHours", "FromMilliseconds", "FromSeconds", "FromTicks"
});
private readonly IEnumerable<Predicate<string>> allowedNumericCallerRegexes;
private readonly Dictionary<string, string> preferredTerms = DefaultPreferredTerms;
#endregion
#region Constructors
private Settings()
{
// This just uses the default settings.
}
private Settings(XElement xml)
{
this.TabSize = GetSetting(xml, nameof(this.TabSize), this.TabSize);
this.MaxLineColumns = GetSetting(xml, nameof(this.MaxLineColumns), this.MaxLineColumns);
this.MaxMethodLines = GetSetting(xml, nameof(this.MaxMethodLines), this.MaxMethodLines);
this.MaxPropertyAccessorLines = GetSetting(xml, nameof(this.MaxPropertyAccessorLines), this.MaxPropertyAccessorLines);
this.MaxFileLines = GetSetting(xml, nameof(this.MaxFileLines), this.MaxFileLines);
this.MaxUnregionedLines = GetSetting(xml, nameof(this.MaxUnregionedLines), this.MaxUnregionedLines);
XElement typeFileNameExclusionsElement = xml.Element("TypeFileNameExclusions");
if (typeFileNameExclusionsElement != null)
{
this.typeFileNameExclusions =
typeFileNameExclusionsElement.Elements("FileRegex").Select(element => CreateFileRegexPredicate(element.Value))
.Concat(typeFileNameExclusionsElement.Elements("FileName").Select(element => CreateFileNamePredicate(element.Value)))
.ToList();
}
XElement allowedNumericLiteralsElement = xml.Element("AllowedNumericLiterals");
if (allowedNumericLiteralsElement != null)
{
this.allowedNumericLiterals = new HashSet<string>(
allowedNumericLiteralsElement.Elements("Literal").Select(literal => literal.Value));
this.allowedNumericCallerNames = new HashSet<string>(
allowedNumericLiteralsElement.Elements("CallerName").Select(callerName => callerName.Value));
this.allowedNumericCallerRegexes = allowedNumericLiteralsElement.Elements("CallerRegex")
.Select<XElement, Predicate<string>>(callerRegex => callerName => Regex.IsMatch(callerName, callerRegex.Value)).ToList();
}
XElement unitTestAttributes = xml.Element("UnitTestAttributes");
if (unitTestAttributes != null)
{
this.TestClassAttributeNames = new HashSet<string>(
unitTestAttributes.Elements("Class").Select(element => element.Value));
this.TestMethodAttributeNames = new HashSet<string>(
unitTestAttributes.Elements("Method").Select(element => element.Value));
}
XElement preferredTermsElement = xml.Element("PreferredTerms");
if (preferredTermsElement != null)
{
this.preferredTerms = preferredTermsElement.Elements("Term")
.Select(term => new KeyValuePair<string, string>(term.Attribute("Avoid").Value, term.Attribute("Prefer").Value))
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
}
#endregion
#region Private Enums
private enum NumberBase
{
Decimal,
Hexadecimal,
Binary,
}
#endregion
#region Public Properties
/// <summary>
/// Gets the tab size to use when applying diagnostic analyzers,
/// which don't have access to the user's workspace options.
///
/// This should NOT be used by code fix providers because they
/// can get the user's preferred tab size from the workspace options
/// (e.g., Men001CodeFixProvider.GetTabSize).
/// </summary>
public int TabSize { get; } = 4;
public int MaxLineColumns { get; } = 160;
public int MaxMethodLines { get; } = 120;
public int MaxPropertyAccessorLines { get; } = 80;
public int MaxFileLines { get; } = 2000;
public int MaxUnregionedLines { get; } = 100;
// These attributes cover MSTest, NUnit, and xUnit.
public HashSet<string> TestMethodAttributeNames { get; } = new HashSet<string>(new[] { "TestMethod", "Test", "Fact" });
public HashSet<string> TestClassAttributeNames { get; } = new HashSet<string>(new[] { "TestClass", "TestFixture" });
public bool HasPreferredTerms => this.preferredTerms.Count > 0;
#endregion
#region Public Methods
#pragma warning disable RS1012 // Start action has no registered actions.
public static Settings Cache(CompilationStartAnalysisContext context)
#pragma warning restore RS1012 // Start action has no registered actions.
{
// See docs for using AdditionalFiles:
// https://github.com/dotnet/roslyn/blob/master/docs/analyzers/Using%20Additional%20Files.md
// Using OrdinalIgnoreCase to compare file names per MSDN:
// https://msdn.microsoft.com/en-us/library/dd465121.aspx#choosing_a_stringcomparison_member_for_your_method_call
AdditionalText additionalText = context.Options?.AdditionalFiles
.FirstOrDefault(file => string.Equals(Path.GetFileName(file.Path), SettingsFileName, StringComparison.OrdinalIgnoreCase));
SourceText sourceText = additionalText?.GetText(context.CancellationToken);
if (sourceText == null || !context.TryGetValue(sourceText, ValueProvider, out Settings result))
{
result = DefaultSettings;
}
return result;
}
public static bool TryParseIntegerLiteral(string text, out ulong value)
{
Tuple<string, NumberBase> split = SplitNumericLiteral(text);
bool result;
switch (split.Item2)
{
case NumberBase.Hexadecimal:
result = ulong.TryParse(split.Item1, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value);
break;
case NumberBase.Binary:
try
{
// They began the literal with a "0b" prefix, so this should always succeed unless
// they've typed an invalid binary literal (e.g., too long or with non-0|1 chars.
value = Convert.ToUInt64(split.Item1, 2);
result = true;
}
catch (Exception ex) when (ex is ArgumentException || ex is FormatException || ex is OverflowException)
{
value = 0;
result = false;
}
break;
default:
result = ulong.TryParse(split.Item1, NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
break;
}
return result;
}
public static bool TryParseIntegerLiteral(string text, out byte value)
{
bool result = TryParseIntegerLiteral(text, out ulong bigValue)
&& bigValue >= byte.MinValue && bigValue <= byte.MaxValue;
value = result ? (byte)bigValue : (byte)0;
return result;
}
public bool IsTypeFileNameCandidate(string fileName)
=> !string.IsNullOrEmpty(fileName) && !this.typeFileNameExclusions.Any(isExcluded => isExcluded(Path.GetFileName(fileName)));
public bool IsAllowedNumericLiteral(string text)
{
bool result = this.allowedNumericLiterals.Contains(text);
if (!result)
{
// Ignore any type suffix (e.g., m, L), base prefix (e.g., 0x or 0b), leading zeros,
// or trailing fractional zeros (e.g., .0 on 1.0).
Tuple<string, NumberBase> split = SplitNumericLiteral(text);
result = this.allowedNumericLiterals.Contains(split.Item1);
}
return result;
}
public bool IsAllowedNumericLiteralCaller(string callerName)
{
bool result = this.allowedNumericCallerNames.Contains(callerName);
if (!result && this.allowedNumericCallerRegexes != null)
{
result = this.allowedNumericCallerRegexes.Any(regexIsMatch => regexIsMatch(callerName));
}
return result;
}
public bool UsePreferredTerm(string term, out string preferredTerm)
{
bool result = false;
if (string.IsNullOrEmpty(term))
{
preferredTerm = term;
}
else if (char.IsLower(term[0]))
{
StringBuilder change = new(term);
change[0] = char.ToUpper(change[0]);
term = change.ToString();
if (this.preferredTerms.TryGetValue(term, out preferredTerm))
{
change = new(preferredTerm);
change[0] = char.ToLower(change[0]);
preferredTerm = change.ToString();
result = true;
}
}
else if (this.preferredTerms.TryGetValue(term, out preferredTerm))
{
result = true;
}
return result;
}
#endregion
#region Private Methods
private static Settings LoadSettings(SourceText sourceText)
{
string text = sourceText.ToString();
XElement xml = XElement.Parse(text);
Settings result = new(xml);
return result;
}
private static int GetSetting(XElement xml, string elementName, int defaultValue)
{
int result = defaultValue;
XElement element = xml.Element(elementName);
if (element != null)
{
if (int.TryParse(element.Value, out int value) && value > 0)
{
result = value;
}
}
return result;
}
private static Predicate<string> CreateFileRegexPredicate(string fileRegex)
=> value => Regex.IsMatch(value, fileRegex, RegexOptions.IgnoreCase);
private static Predicate<string> CreateFileNamePredicate(string fileName)
=> value => string.Equals(value, fileName, StringComparison.CurrentCultureIgnoreCase);
private static Tuple<string, NumberBase> SplitNumericLiteral(string text)
{
// Remove digit separators first so we can shrink the text correctly (e.g., trim leading zeros).
text = text.Replace("_", string.Empty);
// Skip numeric suffixes including compound ones like UL and LU.
int substringLength = text.Length;
while (substringLength >= 1 && CSharpNumericSuffixes.Contains(text[substringLength - 1]))
{
substringLength--;
}
// Skip a fractional zero, which can be used to make a double without using a suffix.
const string FractionalZero = ".0";
if (substringLength > FractionalZero.Length
&& string.CompareOrdinal(text, substringLength - FractionalZero.Length, FractionalZero, 0, FractionalZero.Length) == 0)
{
substringLength -= FractionalZero.Length;
}
// Skip hex or binary specifiers. This allows 0x1 or 0b1 to match 1, for example.
int startIndex = 0;
const string HexPrefix = "0x";
const string BinaryPrefix = "0b";
NumberBase numberBase = NumberBase.Decimal;
if (text.StartsWith(HexPrefix, StringComparison.OrdinalIgnoreCase))
{
startIndex += HexPrefix.Length;
substringLength -= HexPrefix.Length;
numberBase = NumberBase.Hexadecimal;
}
else if (text.StartsWith(BinaryPrefix, StringComparison.OrdinalIgnoreCase))
{
startIndex += BinaryPrefix.Length;
substringLength -= BinaryPrefix.Length;
numberBase = NumberBase.Binary;
}
// Skip leading zeros but not the final zero. This allows 00 to match 0, for example.
while (startIndex < text.Length && substringLength > 1 && text[startIndex] == '0')
{
startIndex++;
substringLength--;
}
string result;
if ((startIndex + substringLength) <= text.Length && (startIndex > 0 || substringLength < text.Length))
{
result = text.Substring(startIndex, substringLength);
}
else
{
result = text;
}
return Tuple.Create(result, numberBase);
}
#endregion
}
}