-
Notifications
You must be signed in to change notification settings - Fork 395
Warn when an if statement contains an assignment #859
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
Merged
JamesWTruher
merged 7 commits into
PowerShell:development
from
bergmeister:warnWhenUsingAssignmentInsideIfStatement
Feb 5, 2018
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
413e6c0
first try at implementation rule. basically works but also catches ca…
bergmeister e452a99
remove unused variables and fix test to import pssa and fix some rule…
bergmeister 647a6a6
Improve rule to only assert against clause in if statement. TODO: Mak…
bergmeister 93660bd
Improve rule to reduce false warnings and adds lots more tests. The o…
bergmeister 3a35ba3
fix false positive when the command is wrapped in an expression
bergmeister 79fa369
simplify and cleanup
bergmeister 4029359
Uncomment import of PSSA in test to be consistent with other tests
bergmeister File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 7 additions & 0 deletions
7
RuleDocumentation/PossibleIncorrectUsageOfAssignmentOperator.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
# PossibleIncorrectUsageOfAssignmentOperator | ||
|
||
**Severity Level: Information** | ||
|
||
## Description | ||
|
||
In many programming languages, the equality operator is denoted as `==` or `=`, but `PowerShell` uses `-eq`. Since assignment inside if statements are very rare, this rule wants to call out this case because it might have been unintentional. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
// | ||
// Copyright (c) Microsoft Corporation. | ||
// | ||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
// THE SOFTWARE. | ||
// | ||
|
||
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic; | ||
using System; | ||
using System.Collections.Generic; | ||
#if !CORECLR | ||
using System.ComponentModel.Composition; | ||
#endif | ||
using System.Management.Automation.Language; | ||
using System.Globalization; | ||
|
||
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules | ||
{ | ||
/// <summary> | ||
/// PossibleIncorrectUsageOfAssignmentOperator: Warn if someone uses the '=' or '==' by accident in an if statement because in most cases that is not the intention. | ||
/// </summary> | ||
#if !CORECLR | ||
[Export(typeof(IScriptRule))] | ||
#endif | ||
public class PossibleIncorrectUsageOfAssignmentOperator : AstVisitor, IScriptRule | ||
{ | ||
/// <summary> | ||
/// The idea is to get all AssignmentStatementAsts and then check if the parent is an IfStatementAst, which includes if, elseif and else statements. | ||
/// </summary> | ||
public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName) | ||
{ | ||
if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage); | ||
|
||
var ifStatementAsts = ast.FindAll(testAst => testAst is IfStatementAst, searchNestedScriptBlocks: true); | ||
foreach (IfStatementAst ifStatementAst in ifStatementAsts) | ||
{ | ||
foreach (var clause in ifStatementAst.Clauses) | ||
{ | ||
var assignmentStatementAst = clause.Item1.Find(testAst => testAst is AssignmentStatementAst, searchNestedScriptBlocks: false) as AssignmentStatementAst; | ||
if (assignmentStatementAst != null) | ||
{ | ||
// Check if someone used '==', which can easily happen when the person is used to coding a lot in C#. | ||
// In most cases, this will be a runtime error because PowerShell will look for a cmdlet name starting with '=', which is technically possible to define | ||
if (assignmentStatementAst.Right.Extent.Text.StartsWith("=")) | ||
{ | ||
yield return new DiagnosticRecord( | ||
Strings.PossibleIncorrectUsageOfAssignmentOperatorError, assignmentStatementAst.Extent, | ||
GetName(), DiagnosticSeverity.Warning, fileName); | ||
} | ||
else | ||
{ | ||
// If the right hand side contains a CommandAst at some point, then we do not want to warn | ||
// because this could be intentional in cases like 'if ($a = Get-ChildItem){ }' | ||
var commandAst = assignmentStatementAst.Right.Find(testAst => testAst is CommandAst, searchNestedScriptBlocks: true) as CommandAst; | ||
if (commandAst == null) | ||
{ | ||
yield return new DiagnosticRecord( | ||
Strings.PossibleIncorrectUsageOfAssignmentOperatorError, assignmentStatementAst.Extent, | ||
GetName(), DiagnosticSeverity.Information, fileName); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
/// <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.PossibleIncorrectUsageOfAssignmentOperatorName); | ||
} | ||
|
||
/// <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.PossibleIncorrectUsageOfAssignmentOperatorCommonName); | ||
} | ||
|
||
/// <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.AvoidUsingWriteHostDescription); | ||
} | ||
|
||
/// <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.Information; | ||
} | ||
|
||
/// <summary> | ||
/// GetSourceName: Retrieves the module/assembly name the rule is from. | ||
/// </summary> | ||
public string GetSourceName() | ||
{ | ||
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName); | ||
} | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
63 changes: 63 additions & 0 deletions
63
Tests/Rules/PossibleIncorrectUsageOfAssignmentOperator.tests.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
Import-Module PSScriptAnalyzer | ||
$ruleName = "PSPossibleIncorrectUsageOfAssignmentOperator" | ||
|
||
Describe "PossibleIncorrectUsageOfAssignmentOperator" { | ||
Context "When there are violations" { | ||
It "assignment inside if statement causes warning" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a=$b){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 1 | ||
} | ||
|
||
It "assignment inside if statement causes warning when when wrapped in command expression" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a=($b)){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 1 | ||
} | ||
|
||
It "assignment inside if statement causes warning when wrapped in expression" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a="$b"){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 1 | ||
} | ||
|
||
It "assignment inside elseif statement causes warning" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a -eq $b){}elseif($a = $b){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 1 | ||
} | ||
|
||
It "double equals inside if statement causes warning" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a == $b){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 1 | ||
} | ||
|
||
It "double equals inside if statement causes warning when wrapping it in command expresion" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a == ($b)){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 1 | ||
} | ||
|
||
It "double equals inside if statement causes warning when wrapped in expression" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a == "$b"){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 1 | ||
} | ||
} | ||
|
||
Context "When there are no violations" { | ||
It "returns no violations when there is no equality operator" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a -eq $b){$a=$b}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 0 | ||
} | ||
|
||
It "returns no violations when there is an evaluation on the RHS" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a = Get-ChildItem){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 0 | ||
} | ||
|
||
It "returns no violations when there is an evaluation on the RHS wrapped in an expression" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a = (Get-ChildItem)){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 0 | ||
} | ||
|
||
It "returns no violations when there is an evaluation on the RHS wrapped in an expression and also includes a variable" { | ||
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'if ($a = (Get-ChildItem $b)){}' | Where-Object {$_.RuleName -eq $ruleName} | ||
$warnings.Count | Should Be 0 | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this will miss the case of
$a = = $b
but that's probably ok