-
Notifications
You must be signed in to change notification settings - Fork 382
/
UseDeclaredVarsMoreThanAssignments.cs
275 lines (245 loc) · 12.8 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
// 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;
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)
{
IEnumerable<Ast> assignmentAsts = scriptBlockAst.FindAll(testAst => testAst is AssignmentStatementAst, false);
IEnumerable<Ast> varAsts = scriptBlockAst.FindAll(testAst => testAst is VariableExpressionAst, true);
IEnumerable<Ast> varsInAssignment;
Dictionary<string, AssignmentStatementAst> assignmentsDictionary_OrdinalIgnoreCase = new Dictionary<string, AssignmentStatementAst>(StringComparer.OrdinalIgnoreCase);
string varKey;
bool inAssignment;
if (assignmentAsts == null)
{
yield break;
}
foreach (AssignmentStatementAst assignmentAst in assignmentAsts)
{
// Only checks for the case where lhs is a variable. Ignore things like $foo.property
VariableExpressionAst assignmentVarAst = assignmentAst.Left as VariableExpressionAst;
if (assignmentVarAst == null)
{
// If the variable is declared in a strongly typed way, e.g. [string]$s = 'foo' then the type is ConvertExpressionAst.
// Therefore we need to the VariableExpressionAst from its Child property.
var assignmentVarAstAsConvertExpressionAst = assignmentAst.Left as ConvertExpressionAst;
if (assignmentVarAstAsConvertExpressionAst != null && assignmentVarAstAsConvertExpressionAst.Child != null)
{
assignmentVarAst = assignmentVarAstAsConvertExpressionAst.Child as VariableExpressionAst;
}
}
if (assignmentVarAst != null)
{
// Ignore if variable is global or environment variable or scope is drive qualified variable
if (!Helper.Instance.IsVariableGlobalOrEnvironment(assignmentVarAst, scriptBlockAst)
&& !assignmentVarAst.VariablePath.IsScript
&& assignmentVarAst.VariablePath.DriveName == null)
{
string variableName = Helper.Instance.VariableNameWithoutScope(assignmentVarAst.VariablePath);
if (!assignmentsDictionary_OrdinalIgnoreCase.ContainsKey(variableName))
{
assignmentsDictionary_OrdinalIgnoreCase.Add(variableName, assignmentAst);
}
}
}
}
if (varAsts != null)
{
foreach (VariableExpressionAst varAst in varAsts)
{
varKey = Helper.Instance.VariableNameWithoutScope(varAst.VariablePath);
inAssignment = false;
if (assignmentsDictionary_OrdinalIgnoreCase.ContainsKey(varKey))
{
varsInAssignment = assignmentsDictionary_OrdinalIgnoreCase[varKey].Left.FindAll(testAst => testAst is VariableExpressionAst, true);
// Checks if this variableAst is part of the logged assignment
foreach (VariableExpressionAst varInAssignment in varsInAssignment)
{
// Try casting to AssignmentStatementAst to be able to catch case where a variable is assigned more than once (https://github.com/PowerShell/PSScriptAnalyzer/issues/833)
var varInAssignmentAsStatementAst = varInAssignment.Parent as AssignmentStatementAst;
var varAstAsAssignmentStatementAst = varAst.Parent as AssignmentStatementAst;
if (varAstAsAssignmentStatementAst != null)
{
if (varAstAsAssignmentStatementAst.Operator == TokenKind.Equals)
{
if (varInAssignmentAsStatementAst != null)
{
inAssignment = varInAssignmentAsStatementAst.Left.Extent.Text.Equals(varAstAsAssignmentStatementAst.Left.Extent.Text, StringComparison.OrdinalIgnoreCase);
}
else
{
inAssignment = varInAssignment.Equals(varAst);
}
}
}
else
{
inAssignment = varInAssignment.Equals(varAst);
}
}
if (!inAssignment)
{
assignmentsDictionary_OrdinalIgnoreCase.Remove(varKey);
}
// Check if variable belongs to PowerShell built-in variables
if (Helper.Instance.HasSpecialVars(varKey))
{
assignmentsDictionary_OrdinalIgnoreCase.Remove(varKey);
}
}
}
}
AnalyzeGetVariableCommands(scriptBlockAst, assignmentsDictionary_OrdinalIgnoreCase);
foreach (string key in assignmentsDictionary_OrdinalIgnoreCase.Keys)
{
yield return new DiagnosticRecord(
string.Format(CultureInfo.CurrentCulture, Strings.UseDeclaredVarsMoreThanAssignmentsError, key),
assignmentsDictionary_OrdinalIgnoreCase[key].Left.Extent,
GetName(),
DiagnosticSeverity.Warning,
fileName,
key);
}
}
/// <summary>
/// Detects variables retrieved by usage of Get-Variable and remove those
/// variables from the entries in <paramref name="assignmentsDictionary_OrdinalIgnoreCase"/>.
/// </summary>
/// <param name="scriptBlockAst"></param>
/// <param name="assignmentsDictionary_OrdinalIgnoreCase"></param>
private void AnalyzeGetVariableCommands(
ScriptBlockAst scriptBlockAst,
Dictionary<string, AssignmentStatementAst> assignmentsDictionary_OrdinalIgnoreCase)
{
var getVariableCmdletNamesAndAliases = Helper.Instance.CmdletNameAndAliases("Get-Variable");
IEnumerable<Ast> getVariableCommandAsts = scriptBlockAst.FindAll(testAst => testAst is CommandAst commandAst &&
getVariableCmdletNamesAndAliases.Contains(commandAst.GetCommandName(), StringComparer.OrdinalIgnoreCase), true);
foreach (CommandAst getVariableCommandAst in getVariableCommandAsts)
{
var commandElements = getVariableCommandAst.CommandElements.ToList();
// The following extracts the variable name(s) only in the simplest possible usage of Get-Variable.
// Usage of a named parameter and an array of variables is accounted for though.
if (commandElements.Count < 2 || commandElements.Count > 3) { continue; }
var commandElementAstOfVariableName = commandElements[commandElements.Count - 1];
if (commandElements.Count == 3)
{
if (!(commandElements[1] is CommandParameterAst commandParameterAst)) { continue; }
// Check if the named parameter -Name is used (PowerShell does not need the full
// parameter name and there is no other parameter of Get-Variable starting with n).
if (!commandParameterAst.ParameterName.StartsWith("n", StringComparison.OrdinalIgnoreCase))
{
continue;
}
}
if (commandElementAstOfVariableName is StringConstantExpressionAst constantExpressionAst)
{
assignmentsDictionary_OrdinalIgnoreCase.Remove(constantExpressionAst.Value);
continue;
}
if (!(commandElementAstOfVariableName is ArrayLiteralAst arrayLiteralAst)) { continue; }
foreach (var expressionAst in arrayLiteralAst.Elements)
{
if (expressionAst is StringConstantExpressionAst constantExpressionAstOfArray)
{
assignmentsDictionary_OrdinalIgnoreCase.Remove(constantExpressionAstOfArray.Value);
}
}
}
}
}
}