Skip to content

Commit 63ea749

Browse files
committed
Adapted the IntroduceLocalVariableQuickfix to make the tests pass.
1 parent efc822b commit 63ea749

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System;
22
using Rubberduck.Inspections.Abstract;
33
using Rubberduck.Inspections.Concrete;
4+
using Rubberduck.Parsing;
5+
using Rubberduck.Parsing.Grammar;
46
using Rubberduck.Parsing.Inspections.Abstract;
57
using Rubberduck.Parsing.VBA;
68

@@ -22,8 +24,25 @@ public IntroduceLocalVariableQuickFix(RubberduckParserState state)
2224

2325
public override void Fix(IInspectionResult result)
2426
{
25-
var instruction = $"{Environment.NewLine}Dim {result.Target.IdentifierName} As Variant{Environment.NewLine}";
26-
_state.GetRewriter(result.Target).InsertBefore(result.Target.Context.Start.TokenIndex, instruction);
27+
var identifierContext = result.Target.Context;
28+
var enclosingStatmentContext = identifierContext.GetAncestor<VBAParser.BlockStmtContext>();
29+
var instruction = IdentifierDeclarationText(result.Target.IdentifierName, EndOfStatementText(enclosingStatmentContext));
30+
_state.GetRewriter(result.Target).InsertBefore(enclosingStatmentContext.Start.TokenIndex, instruction);
31+
}
32+
33+
private string EndOfStatementText(VBAParser.BlockStmtContext context)
34+
{
35+
if (context.TryGetPrecedingContext<VBAParser.EndOfStatementContext>(out var endOfStmtContext))
36+
{
37+
return endOfStmtContext.GetText();
38+
}
39+
40+
return Environment.NewLine;
41+
}
42+
43+
private string IdentifierDeclarationText(string identifierName, string endOfStatementText)
44+
{
45+
return $"Dim {identifierName} As Variant{endOfStatementText}";
2746
}
2847

2948
public override string Description(IInspectionResult result) => Resources.Inspections.QuickFixes.IntroduceLocalVariableQuickFix;

0 commit comments

Comments
 (0)