-
Notifications
You must be signed in to change notification settings - Fork 395
Warn against assignment to read-only automatic variables #864
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 13 commits into
PowerShell:development
from
bergmeister:WarnAgainstAssignmentToAutomaticVariables
Feb 7, 2018
Merged
Changes from 10 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
5c0cb37
add simple prototype to warn against some automatic variables
bergmeister 94ee83b
test against variables used in parameters as well and apply it to rea…
bergmeister c4c8c6e
add first tests
bergmeister 456902d
parameterise tests
bergmeister 09e0692
test that setting the variable actually throws an error
bergmeister dc710a0
add documentation
bergmeister b54f759
fix test due to the addition of a new rule
bergmeister bc5aa8d
Fix false positive in parameter attributes and add tests for it.
bergmeister cf7c461
improve and simplify testing for exception
bergmeister 52df8d0
exclude PSEdition from test in wmf 4
bergmeister 9e559d4
Address PR comments
bergmeister aeb7f57
Merge branch 'development' of https://github.com/PowerShell/PSScriptA…
bergmeister 14ecd3a
trivial test fix due to merge with upstream branch
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
using System; | ||
using System.Globalization; | ||
|
||
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic | ||
{ | ||
public static class DiagnosticRecordHelper | ||
{ | ||
public static string FormatError(string format, params object[] args) | ||
{ | ||
return String.Format(CultureInfo.CurrentCulture, format, args); | ||
} | ||
} | ||
} |
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,33 @@ | ||
# AvoidAssignmentToAutomaticVariable | ||
|
||
**Severity Level: Warning** | ||
|
||
## Description | ||
|
||
`PowerShell` exposes some of its build in variables that are known as automatic variables. Many of them are read-only and PowerShell would throw an error when trying to assign an value on those. The remaining automatic variables should only be assigned to in certain special cases to achieve a certain effect as a special technique. | ||
|
||
To understand more about automatic variables, see ```Get-Help about_Automatic_Variables```. | ||
|
||
## How | ||
|
||
Use variable names in functions or their parameters that do not conflict with automatic variables. | ||
|
||
## Example | ||
|
||
### Wrong | ||
|
||
The variable `$Error` is an automatic variables that exists in the global scope and should therefore never be used as a variable or parameter name. | ||
|
||
``` PowerShell | ||
function foo($Error){ } | ||
``` | ||
|
||
``` PowerShell | ||
function Get-CustomErrorMessage($ErrorMessage){ $Error = "Error occurred: $ErrorMessage" } | ||
``` | ||
|
||
### Correct | ||
|
||
``` PowerShell | ||
function Get-CustomErrorMessage($ErrorMessage){ $FinalErrorMessage = "Error occurred: $ErrorMessage" } | ||
``` |
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,128 @@ | ||
// | ||
// 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 System; | ||
using System.Linq; | ||
using System.Collections.Generic; | ||
using System.Management.Automation.Language; | ||
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic; | ||
#if !CORECLR | ||
using System.ComponentModel.Composition; | ||
#endif | ||
using System.Globalization; | ||
|
||
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules | ||
{ | ||
/// <summary> | ||
/// AvoidAssignmentToAutomaticVariable: | ||
/// </summary> | ||
#if !CORECLR | ||
[Export(typeof(IScriptRule))] | ||
#endif | ||
public class AvoidAssignmentToAutomaticVariable : IScriptRule | ||
{ | ||
private static readonly IList<string> _readOnlyAutomaticVariables = new List<string>() | ||
{ | ||
// Attempting to assign to any of those read-only variable would result in an error at runtime | ||
"?", "true", "false", "Host", "PSCulture", "Error", "ExecutionContext", "Home", "PID", "PSEdition", "PSHome", "PSUICulture", "PSVersionTable", "ShellId" | ||
}; | ||
|
||
/// <summary> | ||
/// Checks for assignment to automatic variables. | ||
/// <param name="ast">The script's ast</param> | ||
/// <param name="fileName">The script's file name</param> | ||
/// <returns>The diagnostic results of this rule</returns> | ||
/// </summary> | ||
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) | ||
{ | ||
var variableExpressionAst = assignmentStatementAst.Find(testAst => testAst is VariableExpressionAst, searchNestedScriptBlocks: false) as VariableExpressionAst; | ||
var variableName = variableExpressionAst.VariablePath.UserPath; | ||
if (_readOnlyAutomaticVariables.Contains(variableName, StringComparer.OrdinalIgnoreCase)) | ||
{ | ||
yield return new DiagnosticRecord(DiagnosticRecordHelper.FormatError(Strings.AvoidAssignmentToReadOnlyAutomaticVariableError, variableName), | ||
variableExpressionAst.Extent, GetName(), DiagnosticSeverity.Error, fileName); | ||
} | ||
} | ||
|
||
IEnumerable<Ast> parameterAsts = ast.FindAll(testAst => testAst is ParameterAst, searchNestedScriptBlocks: true); | ||
foreach (ParameterAst parameterAst in parameterAsts) | ||
{ | ||
var variableExpressionAst = parameterAst.Find(testAst => testAst is VariableExpressionAst, searchNestedScriptBlocks: false) as VariableExpressionAst; | ||
var variableName = variableExpressionAst.VariablePath.UserPath; | ||
// also check the parent to exclude parameter attributes such as '[Parameter(Mandatory=$true)]' where the read-only variable $true appears. | ||
if (_readOnlyAutomaticVariables.Contains(variableName, StringComparer.OrdinalIgnoreCase) && !(variableExpressionAst.Parent is NamedAttributeArgumentAst)) | ||
{ | ||
yield return new DiagnosticRecord(DiagnosticRecordHelper.FormatError(Strings.AvoidAssignmentToReadOnlyAutomaticVariableError, variableName), | ||
variableExpressionAst.Extent, GetName(), DiagnosticSeverity.Error, 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.AvoidAssignmentToAutomaticVariableName); | ||
} | ||
|
||
/// <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.AvoidAssignmentToReadOnlyAutomaticVariableCommonName); | ||
} | ||
|
||
/// <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.AvoidAssignmentToReadOnlyAutomaticVariableDescription); | ||
} | ||
|
||
/// <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.Warning; | ||
} | ||
|
||
/// <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
Oops, something went wrong.
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.
built-in rather than "build in"
"the remaining" would probably be better as other