Skip to content

Commit 987e2b4

Browse files
Razmo99JustinGrote
authored andcommitted
Added a new test case for renaming an inner variable leaking out the functions scope
1 parent 0dd88cd commit 987e2b4

File tree

5 files changed

+29
-0
lines changed

5 files changed

+29
-0
lines changed

src/PowerShellEditorServices/Services/PowerShell/Refactoring/IterativeVariableVisitor.cs

+7
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,13 @@ private void ProcessVariableExpressionAst(VariableExpressionAst variableExpressi
322322
{
323323
ShouldRename = true;
324324
}
325+
// The TargetVariable is defined within a function
326+
// This commandAst is not within that function's scope so we should not rename
327+
if (GetAstParentScope(TargetVariableAst) is FunctionDefinitionAst && !WithinTargetsScope(TargetVariableAst, commandAst))
328+
{
329+
ShouldRename = false;
330+
}
331+
325332
}
326333
// Is this a Variable Assignment thats not within scope
327334
else if (variableExpressionAst.Parent is AssignmentStatementAst assignment &&

test/PowerShellEditorServices.Test.Shared/Refactoring/Variables/RefactorVariablesData.cs

+7
Original file line numberDiff line numberDiff line change
@@ -163,5 +163,12 @@ internal static class RenameVariableData
163163
Line = 9,
164164
RenameTo = "Renamed"
165165
};
166+
public static readonly RenameSymbolParams VariableNestedScopeFunctionRefactorInner = new()
167+
{
168+
FileName = "VariableNestedScopeFunctionRefactorInner.ps1",
169+
Column = 5,
170+
Line = 3,
171+
RenameTo = "Renamed"
172+
};
166173
}
167174
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
$var = 10
2+
function TestFunction {
3+
$var = 20
4+
Write-Output $var
5+
}
6+
TestFunction
7+
Write-Output $var
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
$var = 10
2+
function TestFunction {
3+
$Renamed = 20
4+
Write-Output $Renamed
5+
}
6+
TestFunction
7+
Write-Output $var

test/PowerShellEditorServices.Test/Refactoring/RefactorVariableTests.cs

+1
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ public VariableRenameTestData()
7171
Add(new RenameSymbolParamsSerialized(RenameVariableData.VariableCommandParameterSplattedFromSplat));
7272
Add(new RenameSymbolParamsSerialized(RenameVariableData.VariableInForeachDuplicateAssignment));
7373
Add(new RenameSymbolParamsSerialized(RenameVariableData.VariableInForloopDuplicateAssignment));
74+
Add(new RenameSymbolParamsSerialized(RenameVariableData.VariableNestedScopeFunctionRefactorInner));
7475
}
7576
}
7677

0 commit comments

Comments
 (0)