Skip to content

Commit

Permalink
Merge pull request PowerShell#837 from bergmeister/FixPSUseDeclaredVa…
Browse files Browse the repository at this point in the history
…rsMoreThanAssignments_StrongTyping_Issue832

Fix FixPSUseDeclaredVarsMoreThanAssignments to also detect variables that are strongly typed
  • Loading branch information
JamesWTruher committed Jan 20, 2018
2 parents 8fdb7ae + 68840ac commit a2ab2de
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Rules/UseDeclaredVarsMoreThanAssignments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,17 @@ private IEnumerable<DiagnosticRecord> AnalyzeScriptBlockAst(ScriptBlockAst scrip
// 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 function
Expand Down
6 changes: 6 additions & 0 deletions Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ function MyFunc2() {
Should Be 1
}

It "flags strongly typed variables" {
Invoke-ScriptAnalyzer -ScriptDefinition '[string]$s=''mystring''' -IncludeRule $violationName | `
Get-Count | `
Should Be 1
}

It "does not flag `$InformationPreference variable" {
Invoke-ScriptAnalyzer -ScriptDefinition '$InformationPreference=Stop' -IncludeRule $violationName | `
Get-Count | `
Expand Down

0 comments on commit a2ab2de

Please sign in to comment.