Skip to content

New rule - ReviewUnusedParameter #1382

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
merged 14 commits into from
Jan 15, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions RuleDocumentation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
|[ProvideCommentHelp](./ProvideCommentHelp.md) | Information | Yes |
|[ReservedCmdletChar](./ReservedCmdletChar.md) | Error | |
|[ReservedParams](./ReservedParams.md) | Error | |
|[ReviewUnusedParameter](./ReviewUnusedParameter.md) | Warning | |
|[ShouldProcess](./ShouldProcess.md) | Error | |
|[UseApprovedVerbs](./UseApprovedVerbs.md) | Warning | |
|[UseBOMForUnicodeEncodedFile](./UseBOMForUnicodeEncodedFile.md) | Warning | |
Expand Down
45 changes: 45 additions & 0 deletions RuleDocumentation/ReviewUnusedParameter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# ReviewUnusedParameter

**Severity Level: Warning**

## Description

This rule identifies parameters declared in a script, scriptblock, or function scope that have not been used in that scope.

## How

Consider removing the unused parameter.

## Example

### Wrong

``` PowerShell
function Test-Parameter
{
Param (
$Parameter1,

# this parameter is never called in the function
$Parameter2
)

Get-Something $Parameter1
}
```

### Correct

``` PowerShell
function Test-Parameter
{
Param (
$Parameter1,

# now this parameter is being called in the same scope
$Parameter2
)

Get-Something $Parameter1 $Parameter2
}
```
129 changes: 129 additions & 0 deletions Rules/ReviewUnusedParameter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
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>
/// ReviewUnusedParameter: Check that all declared parameters are used in the script body.
/// </summary>
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif
public class ReviewUnusedParameter : IScriptRule
{
public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (ast == null)
{
throw new ArgumentNullException(Strings.NullAstErrorMessage);
}

var scriptBlockAsts = ast.FindAll(oneAst => oneAst is ScriptBlockAst, true);
if (scriptBlockAsts == null)
{
yield break;
}

foreach (ScriptBlockAst scriptBlockAst in scriptBlockAsts)
{
// find all declared parameters
IEnumerable<Ast> parameterAsts = scriptBlockAst.FindAll(oneAst => oneAst is ParameterAst, false);

// list all variables
IEnumerable<string> variables = scriptBlockAst.FindAll(oneAst => oneAst is VariableExpressionAst, false)
.Cast<VariableExpressionAst>()
.Select(variableExpressionAst => variableExpressionAst.VariablePath.ToString());

foreach (ParameterAst parameterAst in parameterAsts)
{
// compare the list of variables to the parameter name
// there should be at least two matches of the variable name since the parameter declaration counts as one
int matchCount = variables
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At this point, the algorithm becomes O(n^2) in the number of parameters, which is undesirable.

Instead, it should be possible to do the following:

  1. Create an empty case insensitive hashset of variable names
  2. Collect all the variable names used in the begin, process and end blocks of the script block
  3. Run through the parameters and warn for each one not found in the hashset

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rjmholt Forgive me, but I'm failing to see how that will reduce the complexity. Isn't the current code doing essentially what you've described?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It almost does, but currently:

  • The variable lookup is O(n) in the number of variables. The more variables that occur in a script, the longer it will take to verify that parameter is used in that script. Worse, we must look through the whole list of variables for each parameter. With particularly large scripts, the latency of that will start to hit (visible particularly in the VSCode scenario). Instead, we should use an O(1) lookup data structure like a HashSet<string>
  • Variable name comparison is currently case sensitive (done with .Where(variable => variable == parameterAst.Name.VariablePath.ToString())). Instead it should be case insensitive. This is easy to do with new HashSet<string>(StringComparer.OrdinalIgnoreCase).

Copy link
Contributor Author

@mattmcnabb mattmcnabb Jan 9, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it's definitely case-sensitive at the moment. I'll take a look at implementing the hashset - I think I can come up with something. Thanks!

.Where(variable => variable == parameterAst.Name.VariablePath.ToString())
.Take(2).Count();
if (matchCount == 2)
{
continue;
}

// all bets are off if the script uses PSBoundParameters
if (variables.Contains("PSBoundParameters"))
{
continue;
}

yield return new DiagnosticRecord(
string.Format(CultureInfo.CurrentCulture, Strings.ReviewUnusedParameterError, parameterAst.Name.VariablePath.UserPath),
parameterAst.Name.Extent,
GetName(),
DiagnosticSeverity.Warning,
fileName,
parameterAst.Name.VariablePath.UserPath
);
}
}
}

/// <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.ReviewUnusedParameterName);
}

/// <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.ReviewUnusedParameterCommonName);
}

/// <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.ReviewUnusedParameterDescription);
}

/// <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);
}
}
}
116 changes: 72 additions & 44 deletions Rules/Strings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions Rules/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -1104,4 +1104,16 @@
<data name="UseProcessBlockForPipelineCommandName" xml:space="preserve">
<value>UseProcessBlockForPipelineCommand</value>
</data>
<data name="ReviewUnusedParameterCommonName" xml:space="preserve">
<value>ReviewUnusedParameter</value>
</data>
<data name="ReviewUnusedParameterDescription" xml:space="preserve">
<value>Ensure all parameters are used within the same script, scriptblock, or function where they are declared.</value>
</data>
<data name="ReviewUnusedParameterError" xml:space="preserve">
<value>The parameter {0} has been declared but not used. </value>
</data>
<data name="ReviewUnusedParameterName" xml:space="preserve">
<value>ReviewUnusedParameter</value>
</data>
</root>
2 changes: 1 addition & 1 deletion Tests/Engine/GetScriptAnalyzerRule.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Describe "Test Name parameters" {

It "get Rules with no parameters supplied" {
$defaultRules = Get-ScriptAnalyzerRule
$expectedNumRules = 62
$expectedNumRules = 63
if ((Test-PSEditionCoreClr) -or (Test-PSVersionV3) -or (Test-PSVersionV4))
{
# for PSv3 PSAvoidGlobalAliases is not shipped because
Expand Down
6 changes: 3 additions & 3 deletions Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Describe "AvoidAssignmentToAutomaticVariables" {
It "Using Variable <VariableName> as parameter name produces warning of Severity error" -TestCases $testCases_ReadOnlyVariables {
param ($VariableName, $ExpectedSeverity)

[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition "function foo{Param(`$$VariableName)}"
[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition "function foo{Param(`$$VariableName)}" -ExcludeRule PSReviewUnusedParameter
$warnings.Count | Should -Be 1
$warnings.Severity | Should -Be $ExpectedSeverity
$warnings.RuleName | Should -Be $ruleName
Expand All @@ -59,7 +59,7 @@ Describe "AvoidAssignmentToAutomaticVariables" {
}

It "Does not flag parameter attributes" {
[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'function foo{Param([Parameter(Mandatory=$true)]$param1)}'
[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'function foo{Param([Parameter(Mandatory=$true)]$param1)}' -ExcludeRule PSReviewUnusedParameter
$warnings.Count | Should -Be 0
}

Expand All @@ -86,7 +86,7 @@ Describe "AvoidAssignmentToAutomaticVariables" {
Set-Variable -Name $VariableName -Value 'foo'
continue
}

# Setting the $Error variable has the side effect of the ErrorVariable to contain only the exception message string, therefore exclude this case.
# For the library test in WMF 4, assigning a value $PSEdition does not seem to throw an error, therefore this special case is excluded as well.
if ($VariableName -ne 'Error' -and ($VariableName -ne 'PSEdition' -and $PSVersionTable.PSVersion.Major -ne 4))
Expand Down
2 changes: 1 addition & 1 deletion Tests/Rules/AvoidPositionalParameters.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Describe "AvoidPositionalParameters" {
[Parameter(Position=3)]$C)
}
Foo "a" "b" "c"}
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition "$sb"
$warnings = Invoke-ScriptAnalyzer -ScriptDefinition "$sb" -ExcludeRule PSReviewUnusedParameter
$warnings.Count | Should -Be 1
$warnings.RuleName | Should -BeExactly $violationName
}
Expand Down
Loading