forked from PowerShell/PSScriptAnalyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUseDeclaredVarsMoreThanAssignments.cs
534 lines (465 loc) · 23.4 KB
/
UseDeclaredVarsMoreThanAssignments.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Management.Automation.Language;
#if !CORECLR
using System.ComponentModel.Composition;
#endif
using System.Globalization;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
using System.Linq;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// UseDeclaredVarsMoreThanAssignments: Analyzes the ast to check that variables are used in more than just their assignment.
/// </summary>
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif
public class UseDeclaredVarsMoreThanAssignments : IScriptRule
{
/// <summary>
/// AnalyzeScript: Analyzes the ast to check that variables are used in more than just there assignment.
/// </summary>
/// <param name="ast">The script's ast</param>
/// <param name="fileName">The script's file name</param>
/// <returns>A List of results from this rule</returns>
public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (ast == null)
{
throw new ArgumentNullException(Strings.NullAstErrorMessage);
}
var scriptBlockAsts = ast.FindAll(x => x is ScriptBlockAst, true);
if (scriptBlockAsts == null)
{
yield break;
}
foreach (var scriptBlockAst in scriptBlockAsts)
{
var sbAst = scriptBlockAst as ScriptBlockAst;
foreach (var diagnosticRecord in AnalyzeScriptBlockAst(sbAst, fileName))
{
yield return diagnosticRecord;
}
}
}
/// <summary>
/// GetName: Retrieves the name of this rule.
/// </summary>
/// <returns>The name of this rule</returns>
public string GetName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.NameSpaceFormat, GetSourceName(), Strings.UseDeclaredVarsMoreThanAssignmentsName);
}
/// <summary>
/// GetCommonName: Retrieves the common name of this rule.
/// </summary>
/// <returns>The common name of this rule</returns>
public string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseDeclaredVarsMoreThanAssignmentsCommonName);
}
/// <summary>
/// GetDescription: Retrieves the description of this rule.
/// </summary>
/// <returns>The description of this rule</returns>
public string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseDeclaredVarsMoreThanAssignmentsDescription);
}
/// <summary>
/// GetSourceType: Retrieves the type of the rule: builtin, managed or module.
/// </summary>
public SourceType GetSourceType()
{
return SourceType.Builtin;
}
/// <summary>
/// GetSeverity: Retrieves the severity of the rule: error, warning of information.
/// </summary>
/// <returns></returns>
public RuleSeverity GetSeverity()
{
return RuleSeverity.Warning;
}
/// <summary>
/// GetSourceName: Retrieves the module/assembly name the rule is from.
/// </summary>
public string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName);
}
/// <summary>
/// Checks if a variable is initialized and referenced in either its assignment or children scopes
/// </summary>
/// <param name="scriptBlockAst">Ast of type ScriptBlock</param>
/// <param name="fileName">Name of file containing the ast</param>
/// <returns>An enumerable containing diagnostic records</returns>
private IEnumerable<DiagnosticRecord> AnalyzeScriptBlockAst(ScriptBlockAst scriptBlockAst, string fileName)
{
var visitor = new Visitor(this, fileName);
scriptBlockAst.Visit(visitor);
return visitor.GetDiagnostics();
}
private class Visitor : AstVisitor, IAstPostVisitHandler
{
// List of known dot-sourcing commands. Boolean is meaningless - allows concurrent hash lookup
private static ConcurrentDictionary<string, bool> s_dotSourcingCommands = new ConcurrentDictionary<string, bool>(new [] {
new KeyValuePair<string, bool>("ForEach-Object", true),
new KeyValuePair<string, bool>("%", true ),
new KeyValuePair<string, bool>("Where-Object", true),
new KeyValuePair<string, bool>("?", true),
}, StringComparer.OrdinalIgnoreCase);
private static ConcurrentDictionary<string, bool> s_variableCreationCommands = new ConcurrentDictionary<string, bool>(new [] {
new KeyValuePair<string, bool>("New-Variable", true),
new KeyValuePair<string, bool>("nv", true),
new KeyValuePair<string, bool>("Set-Variable", true),
new KeyValuePair<string, bool>("sv", true),
}, StringComparer.OrdinalIgnoreCase);
private static ConcurrentDictionary<string, string> s_variableCreationCommandSwitches = new ConcurrentDictionary<string, string>(new [] {
new KeyValuePair<string, string>("Force", "f"),
new KeyValuePair<string, string>("PassThru", "p"),
new KeyValuePair<string, string>("WhatIf", "wh"),
new KeyValuePair<string, string>("Confirm", "c"),
});
private static ConcurrentDictionary<string, string> s_getVariableCommandSwitches = new ConcurrentDictionary<string, string>(new []
{
new KeyValuePair<string, string>("ValueOnly", "v"),
});
private readonly IRule _rule;
private readonly string _scriptPath;
private readonly List<DiagnosticRecord> _diagnostics;
private readonly Stack<KeyValuePair<ScriptBlockAst, Dictionary<string, Ast>>> _scriptBlockContext;
private readonly Dictionary<string, Ast> _scriptScopeVariables;
private readonly HashSet<ScriptBlockAst> _dotSourcedScriptBlocks;
public Visitor(IRule rule, string scriptPath)
{
_rule = rule;
_scriptPath = scriptPath;
_diagnostics = new List<DiagnosticRecord>();
_scriptScopeVariables = new Dictionary<string, Ast>(StringComparer.OrdinalIgnoreCase);
_scriptBlockContext = new Stack<KeyValuePair<ScriptBlockAst, Dictionary<string, Ast>>>();
_dotSourcedScriptBlocks = new HashSet<ScriptBlockAst>();
}
public IEnumerable<DiagnosticRecord> GetDiagnostics()
{
return _diagnostics;
}
public void PostVisit(Ast ast)
{
// If we have no AST context on the stack, there's nothing to do
if (_scriptBlockContext.Count == 0)
{
return;
}
// See if we're leaving the context of the last scriptblock we entered
// and if so, pop it off and see if any of the variables in that scope went unused
//
// NOTE: We don't look up the stack for variables,
// since PowerShell has dynamic, and not lexical, scope;
// looking up the stack only happens at runtime, so it's something we can't analyze
if (_scriptBlockContext.Peek().Key == ast)
{
Dictionary<string, Ast> unusedVariables = _scriptBlockContext.Pop().Value;
foreach (ExpressionAst variableDefinition in unusedVariables.Values)
{
if (!TryGetVariableNameFromExpression(variableDefinition, out string variableName))
{
// We should only have added variable asts and set/new-variable arguments
throw new InvalidOperationException(
$"Unexpected variable AST recorded '{variableDefinition}' of type '{variableDefinition.GetType().FullName}'");
}
_diagnostics.Add(
new DiagnosticRecord(
string.Format(CultureInfo.CurrentCulture, Strings.UseDeclaredVarsMoreThanAssignmentsError, variableName),
variableDefinition.Extent,
_rule.GetName(),
DiagnosticSeverity.Warning,
_scriptPath));
}
}
}
public override AstVisitAction VisitScriptBlock(ScriptBlockAst scriptBlockAst)
{
// If we're not looking at a scriptblock that's being dot-sourced, push a new scope
if (!_dotSourcedScriptBlocks.Remove(scriptBlockAst))
{
_scriptBlockContext.Push(
new KeyValuePair<ScriptBlockAst, Dictionary<string, Ast>>(
scriptBlockAst,
new Dictionary<string, Ast>(StringComparer.OrdinalIgnoreCase)));
}
return AstVisitAction.Continue;
}
public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst)
{
Dictionary<string, Ast> scopeVariables = _scriptBlockContext.Peek().Value;
// Want to visit the RHS to check for used variables
// We visit it first since it's evaluated first, so we catch '$x = $x' when $x has never been set
assignmentStatementAst.Right.Visit(this);
switch (assignmentStatementAst.Left)
{
case MemberExpressionAst memberExpressionAst:
memberExpressionAst.Visit(this);
break;
case ArrayLiteralAst arrayLhs:
foreach (ExpressionAst expression in arrayLhs.Elements)
{
VariableExpressionAst arrayVariableAst = GetVariableAstFromExpression(expression);
scopeVariables[arrayVariableAst.VariablePath.UserPath] = arrayVariableAst;
}
break;
default:
VariableExpressionAst variableExpressionAst = GetVariableAstFromExpression(assignmentStatementAst.Left);
scopeVariables[variableExpressionAst.VariablePath.UserPath] = variableExpressionAst;
break;
}
// We don't want to visit the LHS,
// since we don't want to register them as variable usages
return AstVisitAction.SkipChildren;
}
public override AstVisitAction VisitCommand(CommandAst commandAst)
{
// If the command is mysteriously absent, move on with our lives
if (commandAst.CommandElements == null || commandAst.CommandElements.Count == 0)
{
return AstVisitAction.Continue;
}
// Dot sourcing brings a script block into the current scope
if (commandAst.InvocationOperator == TokenKind.Dot)
{
switch (commandAst.CommandElements[0])
{
case ScriptBlockExpressionAst scriptBlockExpression:
_dotSourcedScriptBlocks.Add(scriptBlockExpression.ScriptBlock);
break;
}
return AstVisitAction.Continue;
}
string commandName = commandAst.GetCommandName();
if (commandName == null)
{
return AstVisitAction.Continue;
}
// If the next command effectively dot-sources a scriptblock,
// mark this and continue
if (s_dotSourcingCommands.ContainsKey(commandName))
{
foreach (ScriptBlockAst scriptBlock in GetScriptBlockAstsFromCommandElements(commandAst.CommandElements))
{
_dotSourcedScriptBlocks.Add(scriptBlock);
}
return AstVisitAction.Continue;
}
Dictionary<string, Ast> scopeVariables = _scriptBlockContext.Peek().Value;
// We may encounter a Set-Variable (etc), which we treat as assignment
// The parameters here happen to be common to the variable definition cmdlets
// If s_variableCreateCommands is updated, this logic will need to be altered
if (s_variableCreationCommands.ContainsKey(commandName)
&& TryGetVariableNameFromParameters(commandAst.CommandElements, s_variableCreationCommandSwitches, out ExpressionAst createdVariableNameExpression))
{
if (createdVariableNameExpression is StringConstantExpressionAst stringConstantExpression)
{
scopeVariables[stringConstantExpression.Value] = createdVariableNameExpression;
}
return AstVisitAction.Continue;
}
// Get-Variable behaves as a variable reference
if ((String.Equals(commandName, "Get-Variable", StringComparison.OrdinalIgnoreCase)
|| String.Equals(commandName, "gv", StringComparison.OrdinalIgnoreCase))
&& TryGetVariableNameFromParameters(commandAst.CommandElements, s_getVariableCommandSwitches, out ExpressionAst usedVariableExpression))
{
if (usedVariableExpression is StringConstantExpressionAst stringConstantExpression)
{
scopeVariables.Remove(stringConstantExpression.Value);
}
return AstVisitAction.Continue;
}
return AstVisitAction.Continue;
}
public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst)
{
// Remove this variable from the table of defined variables if we see it
_scriptBlockContext.Peek().Value.Remove(variableExpressionAst.VariablePath.UserPath);
return AstVisitAction.SkipChildren;
}
public IEnumerable<ScriptBlockAst> GetScriptBlockAstsFromCommandElements(
ReadOnlyCollection<CommandElementAst> commandElements)
{
foreach (CommandElementAst commandElement in commandElements)
{
switch (commandElement)
{
case ScriptBlockExpressionAst scriptBlockExpression:
yield return scriptBlockExpression.ScriptBlock;
break;
}
}
}
private void RegisterVariableDeclaration(string variableName, Ast definingAst, VariableScope scope)
{
switch (scope)
{
case VariableScope.Private:
case VariableScope.Local:
case VariableScope.Normal:
_scriptBlockContext.Peek().Value[variableName] = definingAst;
return;
case VariableScope.Script:
_scriptScopeVariables[variableName] = definingAst;
return;
}
}
private void RegisterVariableUse(string variableName, VariableScope scope)
{
switch (scope)
{
case VariableScope.Private:
case VariableScope.Local:
case VariableScope.Normal:
_scriptBlockContext.Peek().Value.Remove(variableName);
return;
case VariableScope.Script:
_scriptScopeVariables.Remove(variableName);
return;
}
}
private static bool TryGetVariableNameFromParameters(
ReadOnlyCollection<CommandElementAst> commandElements,
IReadOnlyDictionary<string, string> switchParameters,
out ExpressionAst parameterValueExpression)
{
// We have three possibilities with multiple cases:
// - The value is passed positionally:
// + Set-Variable x 'Hi'
// + Set-Variable -Value 'Hi' x
// + Set-Variable -Value 'Hi' -Force x
// - The value is passed by parameter:
// + Set-Variable -Name x 'Hi'
// + Set-Variable -Name:x 'Hi'
// + Set-Variable 'Hi' -Name x
// + Set-Variable -Force 'Hi' -Name x
// - The command is semantically invalid (in which case we ignore it):
// + Set-Variable -Name -Force x 'Hi'
// + Set-Variable -Name x -Value
//
// We're forced to collect all the parameters because of cases like:
// Set-Variable 'Hi' -Name x
bool seenFirstPosition = false;
string currentParameterName = null;
ExpressionAst firstPositionalParameter = null;
var namedParameters = new Dictionary<string, ExpressionAst>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < commandElements.Count; i++)
{
CommandElementAst commandElement = commandElements[i];
switch (commandElement)
{
case CommandParameterAst parameterAst:
// The command is invalid
if (currentParameterName != null)
{
parameterValueExpression = null;
return false;
}
// Skip over switches
if (IsInParameterDict(switchParameters, parameterAst.ParameterName))
{
continue;
}
// Collect parameters that come with their argument
if (parameterAst.Argument != null)
{
namedParameters[parameterAst.ParameterName] = parameterAst.Argument;
continue;
}
// Set up collecting the argument for this parameter
currentParameterName = parameterAst.ParameterName;
continue;
case ExpressionAst argumentAst:
// Collect the argument if we have the name
if (currentParameterName != null)
{
namedParameters[currentParameterName] = argumentAst;
currentParameterName = null;
continue;
}
// If this is the first positional parameter, remember it
if (!seenFirstPosition)
{
firstPositionalParameter = argumentAst;
seenFirstPosition = true;
}
continue;
}
}
if (namedParameters.TryGetValue("Name", out parameterValueExpression)
|| namedParameters.TryGetValue("n", out parameterValueExpression)
|| namedParameters.TryGetValue("na", out parameterValueExpression)
|| namedParameters.TryGetValue("nam", out parameterValueExpression))
{
return true;
}
parameterValueExpression = firstPositionalParameter;
return parameterValueExpression != null;
}
private static VariableExpressionAst GetVariableAstFromExpression(ExpressionAst expressionAst)
{
switch (expressionAst)
{
case VariableExpressionAst variableExpressionAst:
return variableExpressionAst;
case AttributedExpressionAst attributedExpressionAst:
return GetVariableAstFromExpression(attributedExpressionAst.Child);
default:
throw new ArgumentException($"Assignment LHS '{expressionAst.Extent.Text}' was of unexpected type: '{expressionAst.GetType().FullName}'");
}
}
private static bool TryGetVariableNameFromExpression(ExpressionAst expressionAst, out string variableName)
{
switch (expressionAst)
{
case VariableExpressionAst variableExpressionAst:
variableName = variableExpressionAst.VariablePath.UserPath;
return true;
case StringConstantExpressionAst stringConstantExpressionAst:
variableName = stringConstantExpressionAst.Value;
return true;
default:
variableName = null;
return false;
}
}
private static bool IsInParameterDict(IReadOnlyDictionary<string, string> parameters, string parameterName)
{
if (parameters.ContainsKey(parameterName))
{
return true;
}
foreach (KeyValuePair<string, string> possibleParameter in parameters)
{
if (parameterName.StartsWith(possibleParameter.Value)
&& possibleParameter.Key.IndexOf(parameterName) >= 0)
{
return true;
}
}
return false;
}
}
private enum VariableScope
{
Unknown = 0,
Normal,
Private,
Local,
Script,
Global,
Env,
Using,
}
}
}