forked from PowerShell/PSScriptAnalyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUseCompatibleSyntax.cs
378 lines (319 loc) · 12.9 KB
/
UseCompatibleSyntax.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Language;
using System.Text;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// Rule to diagnose syntactic incompatibilities with scripts
/// across PowerShell versions.
/// </summary>
#if !CORECLR
[System.ComponentModel.Composition.Export(typeof(IScriptRule))]
#endif
public class UseCompatibleSyntax : ConfigurableRule
{
private static readonly Version s_v3 = new Version(3,0);
private static readonly Version s_v4 = new Version(4,0);
private static readonly Version s_v5 = new Version(5,0);
private static readonly Version s_v6 = new Version(6,0);
private static readonly Version s_v7 = new Version(7,0);
private static readonly IReadOnlyList<Version> s_targetableVersions = new []
{
s_v3,
s_v4,
s_v5,
s_v6,
s_v7,
};
/// <summary>
/// The versions of PowerShell for the rule to target.
/// </summary>
[ConfigurableRuleProperty(new string[]{})]
public string[] TargetVersions { get; set; }
/// <summary>
/// The severity of diagnostics generated by this rule.
/// </summary>
public DiagnosticSeverity Severity => DiagnosticSeverity.Error;
/// <summary>
/// Analyze the given PowerShell AST for incompatible syntax usage.
/// </summary>
/// <param name="ast">The PowerShell AST to analyze.</param>
/// <param name="fileName">The name of the PowerShell file being analyzed.</param>
/// <returns>Diagnostics for any issues found while analyzing the given AST.</returns>
public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
HashSet<Version> targetVersions = GetTargetedVersions(TargetVersions);
var visitor = new SyntaxCompatibilityVisitor(this, fileName, targetVersions);
ast.Visit(visitor);
return visitor.GetDiagnosticRecords();
}
/// <summary>
/// Get the common name of this rule.
/// </summary>
public override string GetCommonName()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.UseCompatibleSyntaxCommonName);
}
/// <summary>
/// Get the description of this rule.
/// </summary>
public override string GetDescription()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.UseCompatibleSyntaxDescription);
}
/// <summary>
/// Get the localized name of this rule.
/// </summary>
public override string GetName()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.NameSpaceFormat,
GetSourceName(),
Strings.UseCompatibleSyntaxName);
}
/// <summary>
/// Get the severity of this rule.
/// </summary>
public override RuleSeverity GetSeverity()
{
return RuleSeverity.Error;
}
/// <summary>
/// Get the name of the source of this rule.
/// </summary>
public override string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName);
}
/// <summary>
/// Get the type of the source of this rule.
/// </summary>
public override SourceType GetSourceType()
{
return SourceType.Builtin;
}
private static HashSet<Version> GetTargetedVersions(string[] versionSettings)
{
if (versionSettings == null || versionSettings.Length <= 0)
{
return new HashSet<Version>(){ s_v5, s_v6, s_v7 };
}
var targetVersions = new HashSet<Version>();
foreach (string versionStr in versionSettings)
{
if (!Version.TryParse(versionStr, out Version version))
{
throw new ArgumentException($"Invalid version string: {versionStr}");
}
foreach (Version targetableVersion in s_targetableVersions)
{
if (version.Major == targetableVersion.Major)
{
targetVersions.Add(targetableVersion);
break;
}
}
}
return targetVersions;
}
#if !(PSV3 || PSV4)
private class SyntaxCompatibilityVisitor : AstVisitor2
#else
private class SyntaxCompatibilityVisitor : AstVisitor
#endif
{
private readonly UseCompatibleSyntax _rule;
private readonly string _analyzedFilePath;
private readonly HashSet<Version> _targetVersions;
private readonly List<DiagnosticRecord> _diagnosticAccumulator;
public SyntaxCompatibilityVisitor(
UseCompatibleSyntax rule,
string analyzedScriptPath,
HashSet<Version> targetVersions)
{
_diagnosticAccumulator = new List<DiagnosticRecord>();
_rule = rule;
_analyzedFilePath = analyzedScriptPath;
_targetVersions = targetVersions;
}
public IEnumerable<DiagnosticRecord> GetDiagnosticRecords()
{
return _diagnosticAccumulator;
}
public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
{
// Look for [typename]::new(...) and [typename]::$dynamicMethodName syntax
if (!_targetVersions.Contains(s_v3) && !_targetVersions.Contains(s_v4))
{
return AstVisitAction.Continue;
}
if (_targetVersions.Contains(s_v3) && methodCallAst.Member is VariableExpressionAst)
{
string message = string.Format(
CultureInfo.CurrentCulture,
Strings.UseCompatibleSyntaxError,
"dynamic method invocation",
methodCallAst.Extent.Text,
"3");
_diagnosticAccumulator.Add(new DiagnosticRecord(
message,
methodCallAst.Extent,
_rule.GetName(),
_rule.Severity,
_analyzedFilePath
));
}
if (!(methodCallAst.Expression is TypeExpressionAst typeExpressionAst))
{
return AstVisitAction.Continue;
}
if (!(methodCallAst.Member is StringConstantExpressionAst stringConstantAst))
{
return AstVisitAction.Continue;
}
if (stringConstantAst.Value.Equals("new", StringComparison.OrdinalIgnoreCase))
{
string typeName = typeExpressionAst.TypeName.FullName;
CorrectionExtent suggestedCorrection = CreateNewObjectCorrection(
_analyzedFilePath,
methodCallAst.Extent,
typeName,
methodCallAst.Arguments);
string message = string.Format(
CultureInfo.CurrentCulture,
Strings.UseCompatibleSyntaxError,
"constructor",
methodCallAst.Extent.Text,
"3,4");
_diagnosticAccumulator.Add(new DiagnosticRecord(
message,
methodCallAst.Extent,
_rule.GetName(),
_rule.Severity,
_analyzedFilePath,
ruleId: null,
suggestedCorrections: new [] { suggestedCorrection }
));
return AstVisitAction.Continue;
}
return AstVisitAction.Continue;
}
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
{
// Look for PowerShell workflows in the script
if (!(_targetVersions.Contains(s_v6) || _targetVersions.Contains(s_v7)))
{
return AstVisitAction.Continue;
}
if (!functionDefinitionAst.IsWorkflow)
{
return AstVisitAction.Continue;
}
string message = string.Format(
CultureInfo.CurrentCulture,
Strings.UseCompatibleSyntaxError,
"workflow",
"workflow { ... }",
"6");
_diagnosticAccumulator.Add(
new DiagnosticRecord(
message,
functionDefinitionAst.Extent,
_rule.GetName(),
_rule.Severity,
_analyzedFilePath
));
return AstVisitAction.Continue;
}
#if !(PSV3 || PSV4)
public override AstVisitAction VisitUsingStatement(UsingStatementAst usingStatementAst)
{
// Look for 'using ...;' at the top of scripts
if (!_targetVersions.Contains(s_v3) && !_targetVersions.Contains(s_v4))
{
return AstVisitAction.Continue;
}
string message = string.Format(
CultureInfo.CurrentCulture,
Strings.UseCompatibleSyntaxError,
"using statement",
"using ...;",
"3,4");
_diagnosticAccumulator.Add(
new DiagnosticRecord(
message,
usingStatementAst.Extent,
_rule.GetName(),
_rule.Severity,
_analyzedFilePath
));
return AstVisitAction.Continue;
}
public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst)
{
// Look for 'class MyClass { ... }' and 'enum MyEnum { ... }' definitions
if (!_targetVersions.Contains(s_v3) && !_targetVersions.Contains(s_v4))
{
return AstVisitAction.Continue;
}
string message = string.Format(
CultureInfo.CurrentCulture,
Strings.UseCompatibleSyntaxError,
"type definition",
"class MyClass { ... } | enum MyEnum { ... }",
"3,4");
_diagnosticAccumulator.Add(
new DiagnosticRecord(
message,
typeDefinitionAst.Extent,
_rule.GetName(),
_rule.Severity,
_analyzedFilePath
));
return AstVisitAction.Continue;
}
#endif
private static CorrectionExtent CreateNewObjectCorrection(
string filePath,
IScriptExtent offendingExtent,
string typeName,
IReadOnlyList<ExpressionAst> argumentAsts)
{
var sb = new StringBuilder("New-Object ")
.Append('\'')
.Append(typeName)
.Append('\'');
if (argumentAsts != null && argumentAsts.Count > 0)
{
sb.Append(" @(");
int i = 0;
for (; i < argumentAsts.Count - 1; i++)
{
ExpressionAst argAst = argumentAsts[i];
sb.Append(argAst.Extent.Text).Append(", ");
}
sb.Append(argumentAsts[i].Extent.Text).Append(")");
}
return new CorrectionExtent(
offendingExtent,
sb.ToString(),
filePath,
string.Format(
CultureInfo.CurrentCulture,
Strings.UseCompatibleSyntaxCorrection,
"New-Object @($arg1, $arg2, ...)",
"3,4"));
}
}
}
}