-
Notifications
You must be signed in to change notification settings - Fork 391
/
Copy pathUseConsistentWhitespace.cs
625 lines (555 loc) · 25.3 KB
/
UseConsistentWhitespace.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
#if !CORECLR
using System.ComponentModel.Composition;
#endif
using System.Globalization;
using System.Linq;
using System.Management.Automation.Language;
using System.Text;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// UseConsistentWhitespace: Checks if whitespace usage is consistent throughout the source file.
/// </summary>
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif
public class UseConsistentWhitespace : ConfigurableRule
{
private enum ErrorKind { BeforeOpeningBrace, Paren, Operator, SeparatorComma, SeparatorSemi,
AfterOpeningBrace, BeforeClosingBrace, BeforePipe, AfterPipe, BetweenParameter };
private const int whiteSpaceSize = 1;
private const string whiteSpace = " ";
private readonly SortedSet<TokenKind> openParenKeywordAllowList = new SortedSet<TokenKind>()
{
TokenKind.If,
TokenKind.ElseIf,
TokenKind.Switch,
TokenKind.For,
TokenKind.Foreach,
TokenKind.While
};
private List<Func<TokenOperations, IEnumerable<DiagnosticRecord>>> violationFinders
= new List<Func<TokenOperations, IEnumerable<DiagnosticRecord>>>();
[ConfigurableRuleProperty(defaultValue: true)]
public bool CheckOpenBrace { get; protected set; }
[ConfigurableRuleProperty(defaultValue: true)]
public bool CheckInnerBrace { get; protected set; }
[ConfigurableRuleProperty(defaultValue: true)]
public bool CheckPipe { get; protected set; }
[ConfigurableRuleProperty(defaultValue: false)]
public bool CheckPipeForRedundantWhitespace { get; protected set; }
[ConfigurableRuleProperty(defaultValue: true)]
public bool CheckOpenParen { get; protected set; }
[ConfigurableRuleProperty(defaultValue: true)]
public bool CheckOperator { get; protected set; }
[ConfigurableRuleProperty(defaultValue: true)]
public bool CheckSeparator { get; protected set; }
[ConfigurableRuleProperty(defaultValue: false)]
public bool CheckParameter { get; protected set; }
[ConfigurableRuleProperty(defaultValue: false)]
public bool IgnoreAssignmentOperatorInsideHashTable { get; protected set; }
public override void ConfigureRule(IDictionary<string, object> paramValueMap)
{
base.ConfigureRule(paramValueMap);
if (CheckOpenBrace)
{
violationFinders.Add(FindOpenBraceViolations);
}
if (CheckInnerBrace)
{
violationFinders.Add(FindInnerBraceViolations);
}
if (CheckPipe || CheckPipeForRedundantWhitespace)
{
violationFinders.Add(FindPipeViolations);
}
if (CheckOpenParen)
{
violationFinders.Add(FindOpenParenViolations);
}
if (CheckOperator)
{
violationFinders.Add(FindOperatorViolations);
}
if (CheckSeparator)
{
violationFinders.Add(FindSeparatorViolations);
}
}
/// <summary>
/// Analyzes the given ast to find the [violation]
/// </summary>
/// <param name="ast">AST to be analyzed. This should be non-null</param>
/// <param name="fileName">Name of file that corresponds to the input AST.</param>
/// <returns>A an enumerable type containing the violations</returns>
public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (ast == null)
{
throw new ArgumentNullException("ast");
}
var tokenOperations = new TokenOperations(Helper.Instance.Tokens, ast);
var diagnosticRecords = Enumerable.Empty<DiagnosticRecord>();
foreach (var violationFinder in violationFinders)
{
diagnosticRecords = diagnosticRecords.Concat(violationFinder(tokenOperations));
}
if (CheckParameter)
{
diagnosticRecords = diagnosticRecords.Concat(FindParameterViolations(ast));
}
return diagnosticRecords.ToArray(); // force evaluation here
}
/// <summary>
/// Retrieves the common name of this rule.
/// </summary>
public override string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceCommonName);
}
/// <summary>
/// Retrieves the description of this rule.
/// </summary>
public override string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceDescription);
}
/// <summary>
/// Retrieves the name of this rule.
/// </summary>
public override string GetName()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.NameSpaceFormat,
GetSourceName(),
Strings.UseConsistentWhitespaceName);
}
/// <summary>
/// Retrieves the severity of the rule: error, warning or information.
/// </summary>
public override RuleSeverity GetSeverity()
{
return RuleSeverity.Warning;
}
/// <summary>
/// Gets the severity of the returned diagnostic record: error, warning, or information.
/// </summary>
/// <returns></returns>
public DiagnosticSeverity GetDiagnosticSeverity()
{
return DiagnosticSeverity.Warning;
}
/// <summary>
/// Retrieves the name of the module/assembly the rule is from.
/// </summary>
public override string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName);
}
/// <summary>
/// Retrieves the type of the rule, Builtin, Managed or Module.
/// </summary>
public override SourceType GetSourceType()
{
return SourceType.Builtin;
}
private bool IsOperator(Token token)
{
return TokenTraits.HasTrait(token.Kind, TokenFlags.AssignmentOperator)
|| TokenTraits.HasTrait(token.Kind, TokenFlags.BinaryPrecedenceAdd)
|| TokenTraits.HasTrait(token.Kind, TokenFlags.BinaryPrecedenceMultiply)
|| token.Kind == TokenKind.AndAnd
|| token.Kind == TokenKind.OrOr;
}
private string GetError(ErrorKind kind)
{
switch (kind)
{
case ErrorKind.BeforeOpeningBrace:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorBeforeOpeningBrace);
case ErrorKind.AfterOpeningBrace:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorAfterOpeningBrace);
case ErrorKind.BeforeClosingBrace:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorBeforeClosingInnerBrace);
case ErrorKind.Operator:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorOperator);
case ErrorKind.BeforePipe:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorSpaceBeforePipe);
case ErrorKind.AfterPipe:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorSpaceAfterPipe);
case ErrorKind.SeparatorComma:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorSeparatorComma);
case ErrorKind.SeparatorSemi:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorSeparatorSemi);
case ErrorKind.BetweenParameter:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorSpaceBetweenParameter);
default:
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentWhitespaceErrorBeforeParen);
}
}
private IEnumerable<DiagnosticRecord> FindOpenBraceViolations(TokenOperations tokenOperations)
{
foreach (var lcurly in tokenOperations.GetTokenNodes(TokenKind.LCurly))
{
if (lcurly.Previous == null
|| !IsPreviousTokenOnSameLine(lcurly)
|| lcurly.Previous.Value.Kind == TokenKind.LCurly
|| lcurly.Previous.Value.Kind == TokenKind.Dot
|| ((lcurly.Previous.Value.TokenFlags & TokenFlags.MemberName) == TokenFlags.MemberName))
{
continue;
}
if (IsPreviousTokenApartByWhitespace(lcurly) || IsPreviousTokenLParen(lcurly))
{
continue;
}
yield return new DiagnosticRecord(
GetError(ErrorKind.BeforeOpeningBrace),
lcurly.Value.Extent,
GetName(),
GetDiagnosticSeverity(),
tokenOperations.Ast.Extent.File,
null,
GetCorrections(lcurly.Previous.Value, lcurly.Value, lcurly.Next.Value, false, true).ToList());
}
}
private IEnumerable<DiagnosticRecord> FindInnerBraceViolations(TokenOperations tokenOperations)
{
foreach (var lCurly in tokenOperations.GetTokenNodes(TokenKind.LCurly))
{
if (lCurly.Next == null
|| !IsPreviousTokenOnSameLine(lCurly)
|| lCurly.Next.Value.Kind == TokenKind.NewLine
|| lCurly.Next.Value.Kind == TokenKind.LineContinuation
|| lCurly.Next.Value.Kind == TokenKind.RCurly
)
{
continue;
}
if (!IsNextTokenApartByWhitespace(lCurly))
{
yield return new DiagnosticRecord(
GetError(ErrorKind.AfterOpeningBrace),
lCurly.Value.Extent,
GetName(),
GetDiagnosticSeverity(),
tokenOperations.Ast.Extent.File,
null,
GetCorrections(lCurly.Previous.Value, lCurly.Value, lCurly.Next.Value, true, false).ToList());
}
}
foreach (var rCurly in tokenOperations.GetTokenNodes(TokenKind.RCurly))
{
if (rCurly.Previous == null
|| !IsPreviousTokenOnSameLine(rCurly)
|| rCurly.Previous.Value.Kind == TokenKind.LCurly
|| rCurly.Previous.Value.Kind == TokenKind.NewLine
|| rCurly.Previous.Value.Kind == TokenKind.LineContinuation
|| rCurly.Previous.Value.Kind == TokenKind.AtCurly
)
{
continue;
}
if (!IsPreviousTokenApartByWhitespace(rCurly))
{
yield return new DiagnosticRecord(
GetError(ErrorKind.BeforeClosingBrace),
rCurly.Value.Extent,
GetName(),
GetDiagnosticSeverity(),
tokenOperations.Ast.Extent.File,
null,
GetCorrections(rCurly.Previous.Value, rCurly.Value, rCurly.Next.Value, false, true).ToList());
}
}
}
private IEnumerable<DiagnosticRecord> FindPipeViolations(TokenOperations tokenOperations)
{
foreach (var pipe in tokenOperations.GetTokenNodes(TokenKind.Pipe))
{
if (pipe.Next == null
|| !IsPreviousTokenOnSameLine(pipe)
|| pipe.Next.Value.Kind == TokenKind.Pipe
|| pipe.Next.Value.Kind == TokenKind.NewLine
|| pipe.Next.Value.Kind == TokenKind.LineContinuation
)
{
continue;
}
if (!IsNextTokenApartByWhitespace(pipe, out bool hasRedundantWhitespace))
{
if (CheckPipeForRedundantWhitespace && hasRedundantWhitespace || CheckPipe && !hasRedundantWhitespace)
{
yield return new DiagnosticRecord(
GetError(ErrorKind.AfterPipe),
pipe.Value.Extent,
GetName(),
GetDiagnosticSeverity(),
tokenOperations.Ast.Extent.File,
null,
GetCorrections(pipe.Previous.Value, pipe.Value, pipe.Next.Value, true, false).ToList());
}
}
}
foreach (var pipe in tokenOperations.GetTokenNodes(TokenKind.Pipe))
{
if (pipe.Previous == null
|| !IsPreviousTokenOnSameLine(pipe)
|| pipe.Previous.Value.Kind == TokenKind.Pipe
|| pipe.Previous.Value.Kind == TokenKind.NewLine
|| pipe.Previous.Value.Kind == TokenKind.LineContinuation
)
{
continue;
}
if (!IsPreviousTokenApartByWhitespace(pipe, out bool hasRedundantWhitespace))
{
if (CheckPipeForRedundantWhitespace && hasRedundantWhitespace || CheckPipe && !hasRedundantWhitespace)
{
yield return new DiagnosticRecord(
GetError(ErrorKind.BeforePipe),
pipe.Value.Extent,
GetName(),
GetDiagnosticSeverity(),
tokenOperations.Ast.Extent.File,
null,
GetCorrections(pipe.Previous.Value, pipe.Value, pipe.Next.Value, false, true).ToList());
}
}
}
}
private IEnumerable<DiagnosticRecord> FindOpenParenViolations(TokenOperations tokenOperations)
{
foreach (var lparen in tokenOperations.GetTokenNodes(TokenKind.LParen))
{
if (lparen.Previous != null
&& IsPreviousTokenOnSameLine(lparen)
&& TokenTraits.HasTrait(lparen.Previous.Value.Kind, TokenFlags.Keyword)
&& IsKeyword(lparen.Previous.Value)
&& !IsPreviousTokenApartByWhitespace(lparen))
{
yield return new DiagnosticRecord(
GetError(ErrorKind.Paren),
lparen.Value.Extent,
GetName(),
GetDiagnosticSeverity(),
tokenOperations.Ast.Extent.File,
null,
GetCorrections(lparen.Previous.Value, lparen.Value, lparen.Next.Value, false, true).ToList());
}
}
}
private IEnumerable<DiagnosticRecord> FindParameterViolations(Ast ast)
{
IEnumerable<Ast> commandAsts = ast.FindAll(
testAst => testAst is CommandAst, true);
foreach (CommandAst commandAst in commandAsts)
{
List<Ast> commandParameterAstElements = commandAst.FindAll(
testAst => testAst.Parent == commandAst, searchNestedScriptBlocks: false).ToList();
for (int i = 0; i < commandParameterAstElements.Count - 1; i++)
{
IScriptExtent leftExtent = commandParameterAstElements[i].Extent;
IScriptExtent rightExtent = commandParameterAstElements[i + 1].Extent;
if (leftExtent.EndLineNumber != rightExtent.StartLineNumber)
{
continue;
}
var expectedStartColumnNumberOfRightExtent = leftExtent.EndColumnNumber + 1;
if (rightExtent.StartColumnNumber > expectedStartColumnNumberOfRightExtent)
{
int numberOfRedundantWhiteSpaces = rightExtent.StartColumnNumber - expectedStartColumnNumberOfRightExtent;
var correction = new CorrectionExtent(
startLineNumber: leftExtent.StartLineNumber,
endLineNumber: leftExtent.EndLineNumber,
startColumnNumber: leftExtent.EndColumnNumber + 1,
endColumnNumber: leftExtent.EndColumnNumber + 1 + numberOfRedundantWhiteSpaces,
text: string.Empty,
file: leftExtent.File);
yield return new DiagnosticRecord(
GetError(ErrorKind.BetweenParameter),
leftExtent,
GetName(),
GetDiagnosticSeverity(),
leftExtent.File,
suggestedCorrections: new CorrectionExtent[] { correction });
}
}
}
}
private bool IsSeparator(Token token)
{
return token.Kind == TokenKind.Comma || token.Kind == TokenKind.Semi;
}
private IEnumerable<DiagnosticRecord> FindSeparatorViolations(TokenOperations tokenOperations)
{
Func<LinkedListNode<Token>, bool> predicate = node =>
{
return node.Next != null
&& node.Next.Value.Kind != TokenKind.NewLine
&& node.Next.Value.Kind != TokenKind.EndOfInput // semicolon can be followed by end of input
&& !IsPreviousTokenApartByWhitespace(node.Next);
};
foreach (var tokenNode in tokenOperations.GetTokenNodes(IsSeparator).Where(predicate))
{
var errorKind = tokenNode.Value.Kind == TokenKind.Comma
? ErrorKind.SeparatorComma
: ErrorKind.SeparatorSemi;
yield return getDiagnosticRecord(
tokenNode.Value,
errorKind,
GetCorrections(
tokenNode.Previous.Value,
tokenNode.Value,
tokenNode.Next.Value,
true,
false));
}
}
private DiagnosticRecord getDiagnosticRecord(
Token token,
ErrorKind errKind,
List<CorrectionExtent> corrections)
{
return new DiagnosticRecord(
GetError(errKind),
token.Extent,
GetName(),
GetDiagnosticSeverity(),
token.Extent.File,
null,
corrections);
}
private bool IsKeyword(Token token)
{
return openParenKeywordAllowList.Contains(token.Kind);
}
private static bool IsPreviousTokenApartByWhitespace(LinkedListNode<Token> tokenNode)
{
return IsPreviousTokenApartByWhitespace(tokenNode, out _);
}
private static bool IsPreviousTokenApartByWhitespace(LinkedListNode<Token> tokenNode, out bool hasRedundantWhitespace)
{
if (tokenNode.Value.Extent.StartLineNumber != tokenNode.Previous.Value.Extent.StartLineNumber)
{
hasRedundantWhitespace = false;
return true;
}
var actualWhitespaceSize = tokenNode.Value.Extent.StartColumnNumber - tokenNode.Previous.Value.Extent.EndColumnNumber;
hasRedundantWhitespace = actualWhitespaceSize - whiteSpaceSize > 0;
return whiteSpaceSize == actualWhitespaceSize;
}
private static bool IsPreviousTokenLParen(LinkedListNode<Token> tokenNode)
{
return tokenNode.Previous.Value.Kind == TokenKind.LParen;
}
private static bool IsNextTokenApartByWhitespace(LinkedListNode<Token> tokenNode)
{
return IsNextTokenApartByWhitespace(tokenNode, out _);
}
private static bool IsNextTokenApartByWhitespace(LinkedListNode<Token> tokenNode, out bool hasRedundantWhitespace)
{
var actualWhitespaceSize = tokenNode.Next.Value.Extent.StartColumnNumber - tokenNode.Value.Extent.EndColumnNumber;
hasRedundantWhitespace = actualWhitespaceSize - whiteSpaceSize > 0;
return whiteSpaceSize == actualWhitespaceSize;
}
private bool IsPreviousTokenOnSameLineAndApartByWhitespace(LinkedListNode<Token> tokenNode)
{
return IsPreviousTokenOnSameLine(tokenNode) && IsPreviousTokenApartByWhitespace(tokenNode);
}
private IEnumerable<DiagnosticRecord> FindOperatorViolations(TokenOperations tokenOperations)
{
foreach (var tokenNode in tokenOperations.GetTokenNodes(IsOperator))
{
if (tokenNode.Previous == null
|| tokenNode.Next == null
|| tokenNode.Value.Kind == TokenKind.DotDot)
{
continue;
}
// exclude unary operator for cases like $foo.bar(-$Var)
if (TokenTraits.HasTrait(tokenNode.Value.Kind, TokenFlags.UnaryOperator) &&
tokenNode.Previous.Value.Kind == TokenKind.LParen &&
tokenNode.Next.Value.Kind == TokenKind.Variable)
{
continue;
}
// exclude assignment operator inside of multi-line hash tables if requested
if (IgnoreAssignmentOperatorInsideHashTable && tokenNode.Value.Kind == TokenKind.Equals)
{
Ast containingAst = tokenOperations.GetAstPosition(tokenNode.Value);
if (containingAst is HashtableAst && containingAst.Extent.EndLineNumber != containingAst.Extent.StartLineNumber)
{
continue;
}
}
var hasWhitespaceBefore = IsPreviousTokenOnSameLineAndApartByWhitespace(tokenNode);
var hasWhitespaceAfter = tokenNode.Next.Value.Kind == TokenKind.NewLine
|| IsPreviousTokenOnSameLineAndApartByWhitespace(tokenNode.Next);
if (!hasWhitespaceAfter || !hasWhitespaceBefore)
{
yield return new DiagnosticRecord(
GetError(ErrorKind.Operator),
tokenNode.Value.Extent,
GetName(),
GetDiagnosticSeverity(),
tokenOperations.Ast.Extent.File,
null,
GetCorrections(
tokenNode.Previous.Value,
tokenNode.Value,
tokenNode.Next.Value,
hasWhitespaceBefore,
hasWhitespaceAfter));
}
}
}
private List<CorrectionExtent> GetCorrections(
Token prevToken,
Token token,
Token nextToken,
bool hasWhitespaceBefore, // if this is false, then the returned correction extent will add a whitespace before the token
bool hasWhitespaceAfter // if this is false, then the returned correction extent will add a whitespace after the token
)
{
var sb = new StringBuilder();
IScriptExtent e1 = token.Extent;
if (!hasWhitespaceBefore)
{
sb.Append(whiteSpace);
e1 = prevToken.Extent;
}
var e2 = token.Extent;
if (!hasWhitespaceAfter)
{
if (!hasWhitespaceBefore)
{
sb.Append(token.Text);
}
e2 = nextToken.Extent;
sb.Append(whiteSpace);
}
var extent = new ScriptExtent(
new ScriptPosition(e1.File, e1.EndLineNumber, e1.EndColumnNumber, null),
new ScriptPosition(e2.File, e2.StartLineNumber, e2.StartColumnNumber, null));
return new List<CorrectionExtent>()
{
new CorrectionExtent(
extent,
sb.ToString(),
token.Extent.File,
GetError(ErrorKind.Operator))
};
}
private bool IsPreviousTokenOnSameLine(LinkedListNode<Token> lparen)
{
return lparen.Previous.Value.Extent.EndLineNumber == lparen.Value.Extent.StartLineNumber;
}
}
}