Skip to content

Commit a2ab2de

Browse files
authored
Merge pull request #837 from bergmeister/FixPSUseDeclaredVarsMoreThanAssignments_StrongTyping_Issue832
Fix FixPSUseDeclaredVarsMoreThanAssignments to also detect variables that are strongly typed
2 parents 8fdb7ae + 68840ac commit a2ab2de

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

Rules/UseDeclaredVarsMoreThanAssignments.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,17 @@ private IEnumerable<DiagnosticRecord> AnalyzeScriptBlockAst(ScriptBlockAst scrip
135135
// Only checks for the case where lhs is a variable. Ignore things like $foo.property
136136
VariableExpressionAst assignmentVarAst = assignmentAst.Left as VariableExpressionAst;
137137

138+
if (assignmentVarAst == null)
139+
{
140+
// If the variable is declared in a strongly typed way, e.g. [string]$s = 'foo' then the type is ConvertExpressionAst.
141+
// Therefore we need to the VariableExpressionAst from its Child property.
142+
var assignmentVarAstAsConvertExpressionAst = assignmentAst.Left as ConvertExpressionAst;
143+
if (assignmentVarAstAsConvertExpressionAst != null && assignmentVarAstAsConvertExpressionAst.Child != null)
144+
{
145+
assignmentVarAst = assignmentVarAstAsConvertExpressionAst.Child as VariableExpressionAst;
146+
}
147+
}
148+
138149
if (assignmentVarAst != null)
139150
{
140151
// Ignore if variable is global or environment variable or scope is function

Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ function MyFunc2() {
3838
Should Be 1
3939
}
4040

41+
It "flags strongly typed variables" {
42+
Invoke-ScriptAnalyzer -ScriptDefinition '[string]$s=''mystring''' -IncludeRule $violationName | `
43+
Get-Count | `
44+
Should Be 1
45+
}
46+
4147
It "does not flag `$InformationPreference variable" {
4248
Invoke-ScriptAnalyzer -ScriptDefinition '$InformationPreference=Stop' -IncludeRule $violationName | `
4349
Get-Count | `

0 commit comments

Comments
 (0)