-
Notifications
You must be signed in to change notification settings - Fork 382
/
UseConsistentIndentation.cs
577 lines (511 loc) · 23.2 KB
/
UseConsistentIndentation.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
// 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 Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// UseConsistentIndentation: Checks if indentation is consistent throughout the source file.
/// </summary>
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif
public class UseConsistentIndentation : ConfigurableRule
{
/// <summary>
/// The indentation size in number of space characters.
///
/// Default value if 4.
/// </summary>
[ConfigurableRuleProperty(defaultValue: 4)]
public int IndentationSize { get; protected set; }
// Cannot name to IndentationKind due to the enum type of the same name.
/// <summary>
/// Represents the kind of indentation to be used.
///
/// Possible values are: `space`, `tab`. If any invalid value is given, the
/// property defaults to `space`.
///
/// `space` means `IndentationSize` number of `space` characters are used to provide one level of indentation.
/// `tab` means a tab character, `\t`.
///</summary>
[ConfigurableRuleProperty(defaultValue: "space")]
public string Kind
{
get
{
return indentationKind.ToString();
}
set
{
if (String.IsNullOrWhiteSpace(value) ||
!Enum.TryParse<IndentationKind>(value, true, out indentationKind))
{
indentationKind = IndentationKind.Space;
}
}
}
[ConfigurableRuleProperty(defaultValue: "IncreaseIndentationForFirstPipeline")]
public string PipelineIndentation
{
get
{
return pipelineIndentationStyle.ToString();
}
set
{
if (String.IsNullOrWhiteSpace(value) ||
!Enum.TryParse(value, true, out pipelineIndentationStyle))
{
pipelineIndentationStyle = PipelineIndentationStyle.IncreaseIndentationForFirstPipeline;
}
}
}
private bool insertSpaces;
private char indentationChar;
private int indentationLevelMultiplier;
// TODO Enable auto when the rule is able to detect indentation
private enum IndentationKind {
Space,
Tab,
// Auto
};
private enum PipelineIndentationStyle
{
IncreaseIndentationForFirstPipeline,
IncreaseIndentationAfterEveryPipeline,
NoIndentation,
None
}
// TODO make this configurable
private IndentationKind indentationKind = IndentationKind.Space;
private PipelineIndentationStyle pipelineIndentationStyle = PipelineIndentationStyle.IncreaseIndentationForFirstPipeline;
/// <summary>
/// Analyzes the given ast to find violations.
/// </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");
}
// we add this switch because there is no clean way
// to disable the rule by default
if (!Enable)
{
return Enumerable.Empty<DiagnosticRecord>();
}
// It is more efficient to initialize these fields in ConfigurRule method
// but when the rule will enable `Auto` IndentationKind, we will anyways need to move
// the setting of these variables back here after the rule detects the indentation kind for
// each invocation.
insertSpaces = indentationKind == IndentationKind.Space;
indentationChar = insertSpaces ? ' ' : '\t';
indentationLevelMultiplier = insertSpaces ? IndentationSize : 1;
var tokens = Helper.Instance.Tokens;
var diagnosticRecords = new List<DiagnosticRecord>();
var indentationLevel = 0;
var currentIndenationLevelIncreaseDueToPipelines = 0;
var onNewLine = true;
var pipelineAsts = ast.FindAll(testAst => testAst is PipelineAst && (testAst as PipelineAst).PipelineElements.Count > 1, true).ToList();
/*
When an LParen and LBrace are on the same line, it can lead to too much de-indentation.
In order to prevent the RParen code from de-indenting too much, we keep a stack of when we skipped the indentation
caused by tokens that require a closing RParen (which are LParen, AtParen and DollarParen).
*/
var lParenSkippedIndentation = new Stack<bool>();
for (int tokenIndex = 0; tokenIndex < tokens.Length; tokenIndex++)
{
var token = tokens[tokenIndex];
if (token.Kind == TokenKind.EndOfInput)
{
break;
}
switch (token.Kind)
{
case TokenKind.AtCurly:
case TokenKind.LCurly:
AddViolation(token, indentationLevel++, diagnosticRecords, ref onNewLine);
break;
case TokenKind.DollarParen:
case TokenKind.AtParen:
lParenSkippedIndentation.Push(false);
AddViolation(token, indentationLevel++, diagnosticRecords, ref onNewLine);
break;
case TokenKind.LParen:
// When a line starts with a parenthesis and it is not the last non-comment token of that line,
// then indentation does not need to be increased.
if ((tokenIndex == 0 || tokens[tokenIndex - 1].Kind == TokenKind.NewLine) &&
NextTokenIgnoringComments(tokens, tokenIndex)?.Kind != TokenKind.NewLine)
{
onNewLine = false;
lParenSkippedIndentation.Push(true);
break;
}
lParenSkippedIndentation.Push(false);
AddViolation(token, indentationLevel++, diagnosticRecords, ref onNewLine);
break;
case TokenKind.Pipe:
if (pipelineIndentationStyle == PipelineIndentationStyle.None) { break; }
bool pipelineIsFollowedByNewlineOrLineContinuation =
PipelineIsFollowedByNewlineOrLineContinuation(tokens, tokenIndex);
if (!pipelineIsFollowedByNewlineOrLineContinuation)
{
break;
}
if (pipelineIndentationStyle == PipelineIndentationStyle.IncreaseIndentationAfterEveryPipeline)
{
AddViolation(token, indentationLevel++, diagnosticRecords, ref onNewLine);
currentIndenationLevelIncreaseDueToPipelines++;
break;
}
if (pipelineIndentationStyle == PipelineIndentationStyle.IncreaseIndentationForFirstPipeline)
{
bool isFirstPipeInPipeline = pipelineAsts.Any(pipelineAst =>
PositionIsEqual(LastPipeOnFirstLineWithPipeUsage((PipelineAst)pipelineAst).Extent.EndScriptPosition,
tokens[tokenIndex - 1].Extent.EndScriptPosition));
if (isFirstPipeInPipeline)
{
AddViolation(token, indentationLevel++, diagnosticRecords, ref onNewLine);
currentIndenationLevelIncreaseDueToPipelines++;
}
}
break;
case TokenKind.RParen:
bool matchingLParenIncreasedIndentation = false;
if (lParenSkippedIndentation.Count > 0)
{
matchingLParenIncreasedIndentation = lParenSkippedIndentation.Pop();
}
if (matchingLParenIncreasedIndentation)
{
onNewLine = false;
break;
}
indentationLevel = ClipNegative(indentationLevel - 1);
AddViolation(token, indentationLevel, diagnosticRecords, ref onNewLine);
break;
case TokenKind.RCurly:
indentationLevel = ClipNegative(indentationLevel - 1);
AddViolation(token, indentationLevel, diagnosticRecords, ref onNewLine);
break;
case TokenKind.NewLine:
case TokenKind.LineContinuation:
onNewLine = true;
break;
default:
// we do not want to make a call for every token, hence
// we add this redundant check
if (onNewLine)
{
var tempIndentationLevel = indentationLevel;
// Check if the preceding character is an escape character
if (tokenIndex > 0 && tokens[tokenIndex - 1].Kind == TokenKind.LineContinuation)
{
++tempIndentationLevel;
}
// check for comments in between multi-line commands with line continuation
if (tokenIndex > 2 && tokens[tokenIndex - 1].Kind == TokenKind.NewLine
&& tokens[tokenIndex - 2].Kind == TokenKind.Comment)
{
int searchForPrecedingLineContinuationIndex = tokenIndex - 2;
while (searchForPrecedingLineContinuationIndex > 0 && tokens[searchForPrecedingLineContinuationIndex].Kind == TokenKind.Comment)
{
searchForPrecedingLineContinuationIndex--;
}
if (searchForPrecedingLineContinuationIndex >= 0 && tokens[searchForPrecedingLineContinuationIndex].Kind == TokenKind.LineContinuation)
{
tempIndentationLevel++;
}
}
if (pipelineIndentationStyle == PipelineIndentationStyle.None && PreviousLineEndedWithPipe(tokens, tokenIndex, token))
{
onNewLine = false;
continue;
}
bool lineHasPipelineBeforeToken = LineHasPipelineBeforeToken(tokens, tokenIndex, token);
AddViolation(token, tempIndentationLevel, diagnosticRecords, ref onNewLine, lineHasPipelineBeforeToken);
}
break;
}
if (pipelineIndentationStyle == PipelineIndentationStyle.None) { continue; }
// Check if the current token matches the end of a PipelineAst
PipelineAst matchingPipeLineAstEnd = MatchingPipelineAstEnd(pipelineAsts, token);
if (matchingPipeLineAstEnd == null)
{
continue;
}
IScriptExtent firstPipelineElementExtent = matchingPipeLineAstEnd.PipelineElements[0].Extent;
IScriptExtent lastPipelineElementExtent = matchingPipeLineAstEnd.PipelineElements[matchingPipeLineAstEnd.PipelineElements.Count - 1].Extent;
bool pipelinesSpanOnlyOneLine = firstPipelineElementExtent.EndLineNumber == lastPipelineElementExtent.EndLineNumber
|| firstPipelineElementExtent.StartLineNumber == lastPipelineElementExtent.StartLineNumber;
if (pipelinesSpanOnlyOneLine)
{
continue;
}
if (pipelineIndentationStyle == PipelineIndentationStyle.IncreaseIndentationForFirstPipeline ||
pipelineIndentationStyle == PipelineIndentationStyle.IncreaseIndentationAfterEveryPipeline)
{
indentationLevel = ClipNegative(indentationLevel - currentIndenationLevelIncreaseDueToPipelines);
currentIndenationLevelIncreaseDueToPipelines = 0;
}
}
return diagnosticRecords;
}
private static Token NextTokenIgnoringComments(Token[] tokens, int startIndex)
{
if (startIndex >= tokens.Length - 1)
{
return null;
}
for (int i = startIndex + 1; i < tokens.Length; i++)
{
switch (tokens[i].Kind)
{
case TokenKind.Comment:
continue;
default:
return tokens[i];
}
}
// We've run out of tokens
return null;
}
private static bool PipelineIsFollowedByNewlineOrLineContinuation(Token[] tokens, int startIndex)
{
if (startIndex >= tokens.Length - 1)
{
return false;
}
Token nextToken = null;
for (int i = startIndex + 1; i < tokens.Length; i++)
{
nextToken = tokens[i];
switch (nextToken.Kind)
{
case TokenKind.Comment:
continue;
case TokenKind.NewLine:
case TokenKind.LineContinuation:
return true;
default:
return false;
}
}
// We've run out of tokens but haven't seen a newline
return false;
}
private static bool PreviousLineEndedWithPipe(Token[] tokens, int tokenIndex, Token token)
{
if (tokenIndex < 2 || token.Extent.StartLineNumber == 1)
{
return false;
}
int searchIndex = tokenIndex - 2;
int searchLine;
do
{
searchLine = tokens[searchIndex].Extent.StartLineNumber;
if (tokens[searchIndex].Kind == TokenKind.Comment)
{
searchIndex--;
}
else if (tokens[searchIndex].Kind == TokenKind.Pipe)
{
return true;
}
else
{
break;
}
} while (searchLine == token.Extent.StartLineNumber - 1 && searchIndex >= 0);
return false;
}
private static bool LineHasPipelineBeforeToken(Token[] tokens, int tokenIndex, Token token)
{
int searchIndex = tokenIndex;
int searchLine = token.Extent.StartLineNumber;
do
{
searchLine = tokens[searchIndex].Extent.StartLineNumber;
int searchcolumn = tokens[searchIndex].Extent.StartColumnNumber;
if (tokens[searchIndex].Kind == TokenKind.Pipe && searchcolumn < token.Extent.StartColumnNumber)
{
return true;
}
searchIndex--;
} while (searchLine == token.Extent.StartLineNumber && searchIndex >= 0);
return false;
}
private static CommandBaseAst LastPipeOnFirstLineWithPipeUsage(PipelineAst pipelineAst)
{
CommandBaseAst lastPipeOnFirstLineWithPipeUsage = pipelineAst.PipelineElements[0];
foreach (CommandBaseAst pipelineElement in pipelineAst.PipelineElements.Skip(1))
{
if (pipelineElement.Extent.StartLineNumber == pipelineAst.PipelineElements[0].Extent.StartLineNumber ||
pipelineElement.Extent.StartLineNumber == pipelineAst.PipelineElements[0].Extent.EndLineNumber ||
pipelineElement.Extent.EndLineNumber == pipelineAst.PipelineElements[0].Extent.EndLineNumber)
{
lastPipeOnFirstLineWithPipeUsage = pipelineElement;
}
}
return lastPipeOnFirstLineWithPipeUsage;
}
private static PipelineAst MatchingPipelineAstEnd(List<Ast> pipelineAsts, Token token)
{
PipelineAst matchingPipeLineAstEnd = null;
for (int i = 0; i < pipelineAsts.Count; i++)
{
if (pipelineAsts[i].Extent.EndScriptPosition.LineNumber > token.Extent.EndScriptPosition.LineNumber)
{
break;
}
if (PositionIsEqual(pipelineAsts[i].Extent.EndScriptPosition, token.Extent.EndScriptPosition))
{
matchingPipeLineAstEnd = pipelineAsts[i] as PipelineAst;
break;
}
}
return matchingPipeLineAstEnd;
}
private static bool PositionIsEqual(IScriptPosition position1, IScriptPosition position2)
{
return position1.ColumnNumber == position2.ColumnNumber &&
position1.LineNumber == position2.LineNumber &&
position1.File == position2.File;
}
/// <summary>
/// Retrieves the common name of this rule.
/// </summary>
public override string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentIndentationCommonName);
}
/// <summary>
/// Retrieves the description of this rule.
/// </summary>
public override string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseConsistentIndentationDescription);
}
/// <summary>
/// Retrieves the name of this rule.
/// </summary>
public override string GetName()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.NameSpaceFormat,
GetSourceName(),
Strings.UseConsistentIndentationName);
}
/// <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 void AddViolation(
Token token,
int expectedIndentationLevel,
List<DiagnosticRecord> diagnosticRecords,
ref bool onNewLine,
bool lineHasPipelineBeforeToken = false)
{
if (onNewLine)
{
onNewLine = false;
if (token.Extent.StartColumnNumber - 1 != GetIndentation(expectedIndentationLevel))
{
var fileName = token.Extent.File;
var extent = token.Extent;
var violationExtent = extent = new ScriptExtent(
new ScriptPosition(
fileName,
extent.StartLineNumber,
1, // first column in the line
extent.StartScriptPosition.Line),
new ScriptPosition(
fileName,
extent.StartLineNumber,
extent.StartColumnNumber,
extent.StartScriptPosition.Line));
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture, Strings.UseConsistentIndentationError),
violationExtent,
GetName(),
GetDiagnosticSeverity(),
fileName,
null,
GetSuggestedCorrections(token, expectedIndentationLevel, lineHasPipelineBeforeToken)));
}
}
}
private List<CorrectionExtent> GetSuggestedCorrections(
Token token,
int indentationLevel,
bool lineHasPipelineBeforeToken = false)
{
// TODO Add another constructor for correction extent that takes extent
// TODO handle param block
// TODO handle multiline commands
var corrections = new List<CorrectionExtent>();
var optionalPipeline = lineHasPipelineBeforeToken ? "| " : string.Empty;
corrections.Add(new CorrectionExtent(
token.Extent.StartLineNumber,
token.Extent.EndLineNumber,
1,
token.Extent.EndColumnNumber,
GetIndentationString(indentationLevel) + optionalPipeline + token.Extent.Text,
token.Extent.File));
return corrections;
}
private static int ClipNegative(int x)
{
return x > 0 ? x : 0;
}
private int GetIndentation(int indentationLevel)
{
// todo if condition can be evaluated during rule configuration
return indentationLevel * indentationLevelMultiplier;
}
private string GetIndentationString(int indentationLevel)
{
return new string(indentationChar, GetIndentation(indentationLevel));
}
}
}