Skip to content

Commit 59b69c8

Browse files
committed
fix: Handle functions with scopes
1 parent 382278a commit 59b69c8

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

Rules/AvoidReservedWordsAsFunctionNames.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,15 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
6565

6666
foreach (var function in functionDefinitions)
6767
{
68-
if (reservedWords.Contains(function.Name))
68+
if (reservedWords.Contains(
69+
Helper.Instance.FunctionNameWithoutScope(function.Name)
70+
))
6971
{
7072
yield return new DiagnosticRecord(
7173
string.Format(
7274
CultureInfo.CurrentCulture,
7375
Strings.AvoidReservedWordsAsFunctionNamesError,
74-
function.Name),
76+
Helper.Instance.FunctionNameWithoutScope(function.Name)),
7577
Helper.Instance.GetScriptExtentForFunctionName(function) ?? function.Extent,
7678
GetName(),
7779
DiagnosticSeverity.Warning,

Tests/Rules/AvoidReservedWordsAsFunctionNames.tests.ps1

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,20 @@ $randomCasedReservedWords = @(
3030
'uNtIl','UsInG','VaR','wHiLe','wOrKfLoW'
3131
)
3232

33+
$functionScopes = @(
34+
"global", "local", "script", "private"
35+
)
36+
37+
# Generate all combinations of reserved words and function scopes
38+
$scopedReservedWordCases = foreach ($scope in $functionScopes) {
39+
foreach ($word in $reservedWords) {
40+
@{
41+
Scope = $scope
42+
Name = $word
43+
}
44+
}
45+
}
46+
3347
$substringReservedWords = $reservedWords | ForEach-Object {
3448
"$($_)Func"
3549
}
@@ -58,6 +72,22 @@ Describe 'AvoidReservedWordsAsFunctionNames' {
5872
$violations[0].Extent.Text | Should -Be $_
5973
}
6074

75+
# Functions can have scopes. So function global:function {} should still
76+
# alert.
77+
It 'flags reserved word "<Name>" with scope "<Scope>" as a violation' -TestCases $scopedReservedWordCases {
78+
param($Scope, $Name)
79+
80+
$scriptDefinition = "function $($Scope):$($Name) { 'test' }"
81+
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName)
82+
83+
$violations.Count | Should -Be 1
84+
$violations[0].Severity | Should -Be 'Warning'
85+
$violations[0].RuleName | Should -Be $ruleName
86+
$violations[0].Message | Should -Be "The reserved word '$Name' was used as a function name. This should be avoided."
87+
$violations[0].Extent.Text | Should -Be "$($Scope):$($Name)"
88+
}
89+
90+
6191
It 'detects case-insensitively for "<_>"' -TestCases $randomCasedReservedWords {
6292
$scriptDefinition = "function $_ { }"
6393
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName)

0 commit comments

Comments
 (0)