Skip to content

Commit

Permalink
Fix #3278: Missing variable declaration in nested for-loop after many…
Browse files Browse the repository at this point in the history
… other loops
  • Loading branch information
siegfriedpammer committed Sep 20, 2024
1 parent 4ff0c26 commit 966b99a
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 12 deletions.
75 changes: 75 additions & 0 deletions ICSharpCode.Decompiler.Tests/TestCases/Pretty/VariableNaming.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,80 @@ private static void NestedForLoopTest(int sizeX, int sizeY, int[] array)
}
#endif
}

private static void NestedForLoopTest2()
{
for (int i = 0; i < 10; i++)
{
Nop(i);
}
#if EXPECTED_OUTPUT && !(LEGACY_CSC && !OPT)
for (int j = 0; j < 10; j++)
{
Nop(j);
}

for (int k = 0; k < 10; k++)
{
Nop(k);
}

for (int l = 0; l < 10; l++)
{
Nop(l);
}

for (int m = 0; m < 10; m++)
{
for (int n = 0; n < 10; n++)
{
Nop(n);
}
}

for (int num = 0; num < 10; num++)
{
for (int num2 = 0; num2 < 10; num2++)
{
Nop(num2);
}
}
#else
for (int i = 0; i < 10; i++)
{
Nop(i);
}

for (int i = 0; i < 10; i++)
{
Nop(i);
}

for (int i = 0; i < 10; i++)
{
Nop(i);
}

for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Nop(j);
}
}

for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Nop(j);
}
}
#endif
}

private static void Nop(int v)
{
}
}
}
24 changes: 12 additions & 12 deletions ICSharpCode.Decompiler/IL/Transforms/AssignVariableNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,6 @@ string AssignName(ILVariable v, Dictionary<ILVariable, string> variableMapping)
string nameWithoutNumber = SplitName(newName, out int newIndex);
if (reservedVariableNames.TryGetValue(nameWithoutNumber, out int lastUsedIndex))
{
// name without number was already used
if (v.Type.IsKnownType(KnownTypeCode.Int32) && loopCounters.Contains(v))
{
// special case for loop counters,
Expand All @@ -298,20 +297,21 @@ string AssignName(ILVariable v, Dictionary<ILVariable, string> variableMapping)
nameWithoutNumber = newName;
newIndex = 1;
}
}
if (reservedVariableNames.TryGetValue(nameWithoutNumber, out lastUsedIndex))
{
// name without number was already used
if (newIndex > lastUsedIndex)
{
// new index is larger than last, so we can use it
}
else
{
if (newIndex > lastUsedIndex)
{
// new index is larger than last, so we can use it
}
else
{
// new index is smaller or equal, so we use the next value
newIndex = lastUsedIndex + 1;
}
// resolve conflicts by appending the index to the new name:
newName = nameWithoutNumber + newIndex.ToString();
// new index is smaller or equal, so we use the next value
newIndex = lastUsedIndex + 1;
}
// resolve conflicts by appending the index to the new name:
newName = nameWithoutNumber + newIndex.ToString();
}
// update the last used index
reservedVariableNames[nameWithoutNumber] = newIndex;
Expand Down

0 comments on commit 966b99a

Please sign in to comment.