Skip to content

Fix NullReferenceException in AvoidAssignmentToAutomaticVariable rule when assigning a .Net property and only look at the LHS #1008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

5 changes: 3 additions & 2 deletions Rules/AvoidAssignmentToAutomaticVariable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage);

IEnumerable<Ast> assignmentStatementAsts = ast.FindAll(testAst => testAst is AssignmentStatementAst, searchNestedScriptBlocks: true);
foreach (var assignmentStatementAst in assignmentStatementAsts)
foreach (AssignmentStatementAst assignmentStatementAst in assignmentStatementAsts)
{
var variableExpressionAst = assignmentStatementAst.Find(testAst => testAst is VariableExpressionAst, searchNestedScriptBlocks: false) as VariableExpressionAst;
var variableExpressionAst = assignmentStatementAst.Left.Find(testAst => testAst is VariableExpressionAst && testAst.Parent == assignmentStatementAst, searchNestedScriptBlocks: false) as VariableExpressionAst;
if (variableExpressionAst == null) { continue; }
var variableName = variableExpressionAst.VariablePath.UserPath;
if (_readOnlyAutomaticVariables.Contains(variableName, StringComparer.OrdinalIgnoreCase))
{
Expand Down
14 changes: 14 additions & 0 deletions Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,20 @@ Describe "AvoidAssignmentToAutomaticVariables" {
$warnings.Count | Should -Be 0
}

It "Does not throw a NullReferenceException when using assigning a .Net property to a .Net property (Bug in 1.17.0 - issue 1007)" {
Invoke-ScriptAnalyzer -ScriptDefinition '[foo]::bar = [baz]::qux' -ErrorAction Stop
}

It "Does not flag properties of a readonly variable (issue 1012)" {
[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition '$Host.PrivateData["ErrorBackgroundColor"] = "Black"'
$warnings.Count | Should -Be 0
}

It "Does not flag RHS of variable assignment (Bug in 1.17.0, issue 1013)" {
[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition '[foo]::bar = $true'
$warnings.Count | Should -Be 0
}

It "Setting Variable <VariableName> throws exception in applicable PowerShell version to verify the variables is read-only" -TestCases $testCases_ReadOnlyVariables {
param ($VariableName, $ExpectedSeverity, $OnlyPresentInCoreClr)

Expand Down