/
AssignedByValParameterMakeLocalCopyQuickFix.cs
169 lines (147 loc) · 6.89 KB
/
AssignedByValParameterMakeLocalCopyQuickFix.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using Antlr4.Runtime;
using Rubberduck.CodeAnalysis.Inspections;
using Rubberduck.CodeAnalysis.Inspections.Concrete;
using Rubberduck.CodeAnalysis.QuickFixes.Abstract;
using Rubberduck.Common;
using Rubberduck.Parsing;
using Rubberduck.Parsing.Grammar;
using Rubberduck.Parsing.Rewriter;
using Rubberduck.Parsing.Symbols;
using Rubberduck.Parsing.VBA;
using Rubberduck.Refactorings.Common;
using Rubberduck.UI.Refactorings;
namespace Rubberduck.CodeAnalysis.QuickFixes.Concrete
{
/// <summary>
/// Introduces a new local variable and assigns it at the top of the procedure scope, then updates all parameter references to refer to the new local variable.
/// </summary>
/// <inspections>
/// <inspection name="AssignedByValParameterInspection" />
/// </inspections>
/// <canfix multiple="false" procedure="false" module="false" project="false" all="false" />
/// <example>
/// <before>
/// <![CDATA[
/// Public Sub DoSomething(ByVal value As Long)
/// Debug.Print value
/// value = 42
/// Debug.Print value
/// End Sub
/// ]]>
/// </before>
/// <after>
/// <![CDATA[
/// Public Sub DoSomething(ByVal value As Long)
/// Dim localValue As Long
/// localValue = value
/// Debug.Print localValue
/// localValue = 42
/// Debug.Print localValue
/// End Sub
/// ]]>
/// </after>
/// </example>
internal sealed class AssignedByValParameterMakeLocalCopyQuickFix : QuickFixBase
{
private readonly IAssignedByValParameterQuickFixDialogFactory _dialogFactory;
private readonly IDeclarationFinderProvider _declarationFinderProvider;
private Declaration _quickFixTarget;
public AssignedByValParameterMakeLocalCopyQuickFix(IDeclarationFinderProvider declarationFinderProvider, IAssignedByValParameterQuickFixDialogFactory dialogFactory)
: base(typeof(AssignedByValParameterInspection))
{
_dialogFactory = dialogFactory;
_declarationFinderProvider = declarationFinderProvider;
}
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession)
{
Debug.Assert(result.Target.Context.Parent is VBAParser.ArgListContext);
Debug.Assert(null != ((ParserRuleContext)result.Target.Context.Parent.Parent).GetChild<VBAParser.EndOfStatementContext>());
_quickFixTarget = result.Target;
var localIdentifier = PromptForLocalVariableName(result.Target);
if (string.IsNullOrEmpty(localIdentifier))
{
return;
}
var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName);
ReplaceAssignedByValParameterReferences(rewriter, result.Target, localIdentifier);
InsertLocalVariableDeclarationAndAssignment(rewriter, result.Target, localIdentifier);
}
public override string Description(IInspectionResult result) => Resources.Inspections.QuickFixes.AssignedByValParameterMakeLocalCopyQuickFix;
public override bool CanFixMultiple => false;
public override bool CanFixInProcedure => false;
public override bool CanFixInModule => false;
public override bool CanFixInProject => false;
public override bool CanFixAll => false;
private string PromptForLocalVariableName(Declaration target)
{
IAssignedByValParameterQuickFixDialog view = null;
try
{
view = _dialogFactory.Create(target.IdentifierName, target.DeclarationType.ToString(), IsNameCollision);
view.NewName = GetDefaultLocalIdentifier(target);
view.ShowDialog();
if (view.DialogResult == DialogResult.Cancel || !IsValidVariableName(view.NewName))
{
return string.Empty;
}
return view.NewName;
}
finally
{
_dialogFactory.Release(view);
}
}
private bool IsNameCollision(string newName)
=> _declarationFinderProvider.DeclarationFinder.FindNewDeclarationNameConflicts(newName, _quickFixTarget).Any();
private string GetDefaultLocalIdentifier(Declaration target)
{
var newName = $"local{target.IdentifierName.CapitalizeFirstLetter()}";
if (IsValidVariableName(newName))
{
return newName;
}
for ( var attempt = 2; attempt < 10; attempt++)
{
var result = newName + attempt;
if (IsValidVariableName(result))
{
return result;
}
}
return newName;
}
private bool IsValidVariableName(string variableName)
{
return VBAIdentifierValidator.IsValidIdentifier(variableName, DeclarationType.Variable)
&& !IsNameCollision(variableName);
}
private void ReplaceAssignedByValParameterReferences(IModuleRewriter rewriter, Declaration target, string localIdentifier)
{
foreach (var identifierReference in target.References)
{
rewriter.Replace(identifierReference.Context, localIdentifier);
}
}
private void InsertLocalVariableDeclarationAndAssignment(IModuleRewriter rewriter, Declaration target, string localIdentifier)
{
var localVariableDeclaration = $"{Tokens.Dim} {localIdentifier} {Tokens.As} {target.AsTypeName}";
var requiresAssignmentUsingSet =
target.References.Any(refItem => VariableRequiresSetAssignmentEvaluator.RequiresSetAssignment(refItem, _declarationFinderProvider));
var localVariableAssignment =
$"{(requiresAssignmentUsingSet ? $"{Tokens.Set} " : string.Empty)}{localIdentifier} = {target.IdentifierName}";
var endOfStmtCtxt = ((ParserRuleContext)target.Context.Parent.Parent).GetChild<VBAParser.EndOfStatementContext>();
var eosContent = endOfStmtCtxt.GetText();
var idxLastNewLine = eosContent.LastIndexOf(Environment.NewLine, StringComparison.InvariantCultureIgnoreCase);
var endOfStmtCtxtComment = eosContent.Substring(0, idxLastNewLine);
var endOfStmtCtxtEndFormat = eosContent.Substring(idxLastNewLine);
var insertCtxt = ((ParserRuleContext) target.Context.Parent.Parent).GetChild<VBAParser.AsTypeClauseContext>()
?? (ParserRuleContext) target.Context.Parent;
rewriter.Remove(endOfStmtCtxt);
rewriter.InsertAfter(insertCtxt.Stop.TokenIndex, $"{endOfStmtCtxtComment}{endOfStmtCtxtEndFormat}{localVariableDeclaration}" + $"{endOfStmtCtxtEndFormat}{localVariableAssignment}{endOfStmtCtxtEndFormat}");
}
}
}