-
Notifications
You must be signed in to change notification settings - Fork 296
/
MoveCloserToUsageRefactoring.cs
359 lines (299 loc) · 14.6 KB
/
MoveCloserToUsageRefactoring.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Rubberduck.Common;
using Rubberduck.Parsing;
using Rubberduck.Parsing.Grammar;
using Rubberduck.Parsing.Symbols;
using Rubberduck.Parsing.VBA;
using Rubberduck.UI;
using Rubberduck.VBEditor;
using Rubberduck.VBEditor.SafeComWrappers.Abstract;
namespace Rubberduck.Refactorings.MoveCloserToUsage
{
public class MoveCloserToUsageRefactoring : IRefactoring
{
private readonly List<Declaration> _declarations;
private readonly IVBE _vbe;
private readonly RubberduckParserState _state;
private readonly IMessageBox _messageBox;
private Declaration _target;
public MoveCloserToUsageRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox)
{
_declarations = state.AllUserDeclarations.ToList();
_vbe = vbe;
_state = state;
_messageBox = messageBox;
}
public void Refactor()
{
var qualifiedSelection = _vbe.ActiveCodePane.CodeModule.GetQualifiedSelection();
if (qualifiedSelection != null)
{
Refactor(_declarations.FindVariable(qualifiedSelection.Value));
}
else
{
_messageBox.Show(RubberduckUI.MoveCloserToUsage_InvalidSelection, RubberduckUI.MoveCloserToUsage_Caption, MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
public void Refactor(QualifiedSelection selection)
{
_target = _declarations.FindVariable(selection);
if (_target == null)
{
_messageBox.Show(RubberduckUI.MoveCloserToUsage_InvalidSelection, RubberduckUI.IntroduceParameter_Caption,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
MoveCloserToUsage();
}
public void Refactor(Declaration target)
{
if (target.DeclarationType != DeclarationType.Variable)
{
_messageBox.Show(RubberduckUI.MoveCloserToUsage_InvalidSelection, RubberduckUI.IntroduceParameter_Caption,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
// ReSharper disable once LocalizableElement
throw new ArgumentException("Invalid Argument. DeclarationType must be 'Variable'", "target");
}
_target = target;
MoveCloserToUsage();
}
private bool TargetIsReferencedFromMultipleMethods(Declaration target)
{
var firstReference = target.References.FirstOrDefault();
return firstReference != null && target.References.Any(r => r.ParentScoping != firstReference.ParentScoping);
}
private void MoveCloserToUsage()
{
if (!_target.References.Any())
{
var message = string.Format(RubberduckUI.MoveCloserToUsage_TargetHasNoReferences, _target.IdentifierName);
_messageBox.Show(message, RubberduckUI.MoveCloserToUsage_Caption, MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return;
}
if (TargetIsReferencedFromMultipleMethods(_target))
{
var message = string.Format(RubberduckUI.MoveCloserToUsage_TargetIsUsedInMultipleMethods, _target.IdentifierName);
_messageBox.Show(message, RubberduckUI.MoveCloserToUsage_Caption, MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return;
}
QualifiedSelection? oldSelection = null;
var pane = _vbe.ActiveCodePane;
var module = pane.CodeModule;
{
if (!module.IsWrappingNullReference)
{
oldSelection = module.GetQualifiedSelection();
}
// it doesn't make sense to do it backwards, but we need to work from the bottom up so our selections are accurate
InsertDeclaration();
if (oldSelection.HasValue)
{
pane.Selection = oldSelection.Value.Selection;
}
_state.StateChanged += _state_StateChanged;
_state.OnParseRequested(this);
}
}
private void _state_StateChanged(object sender, ParserStateEventArgs e)
{
if (e.State != ParserState.Ready) { return; }
QualifiedSelection? oldSelection = null;
var pane = _vbe.ActiveCodePane;
var module = pane.CodeModule;
{
if (!module.IsWrappingNullReference)
{
oldSelection = module.GetQualifiedSelection();
}
var newTarget = _state.AllUserDeclarations.FirstOrDefault(
item => item.ComponentName == _target.ComponentName &&
item.IdentifierName == _target.IdentifierName &&
item.ParentScope == _target.ParentScope &&
item.ProjectId == _target.ProjectId &&
Equals(item.Selection, _target.Selection));
if (newTarget != null)
{
UpdateCallsToOtherModule(newTarget.References.ToList());
RemoveField(newTarget);
}
if (oldSelection.HasValue)
{
pane.Selection = oldSelection.Value.Selection;
}
_state.StateChanged -= _state_StateChanged;
_state.OnParseRequested(this);
}
}
private void InsertDeclaration()
{
var module = _target.References.First().QualifiedModuleName.Component.CodeModule;
{
var firstReference = _target.References.OrderBy(r => r.Selection.StartLine).First();
var beginningOfInstructionSelection = GetBeginningOfInstructionSelection(firstReference);
var oldLines = module.GetLines(beginningOfInstructionSelection.StartLine, beginningOfInstructionSelection.LineCount);
var newLines = oldLines.Insert(beginningOfInstructionSelection.StartColumn - 1, GetDeclarationString());
var newLinesWithoutStringLiterals = newLines.StripStringLiterals();
var lastIndexOfColon = GetIndexOfLastStatementSeparator(newLinesWithoutStringLiterals);
// ReSharper disable once StringLastIndexOfIsCultureSpecific.1
while (lastIndexOfColon != -1)
{
var numberOfCharsToRemove = lastIndexOfColon == newLines.Length - 1 || newLines[lastIndexOfColon + 1] != ' '
? 1
: 2;
newLinesWithoutStringLiterals = newLinesWithoutStringLiterals
.Remove(lastIndexOfColon, numberOfCharsToRemove)
.Insert(lastIndexOfColon, Environment.NewLine);
newLines = newLines
.Remove(lastIndexOfColon, numberOfCharsToRemove)
.Insert(lastIndexOfColon, Environment.NewLine);
lastIndexOfColon = GetIndexOfLastStatementSeparator(newLinesWithoutStringLiterals);
}
module.DeleteLines(beginningOfInstructionSelection.StartLine, beginningOfInstructionSelection.LineCount);
module.InsertLines(beginningOfInstructionSelection.StartLine, newLines);
}
}
private static readonly Regex StatementSeparatorRegex = new Regex(":[^=]", RegexOptions.RightToLeft);
private static int GetIndexOfLastStatementSeparator(string input)
{
var matches = StatementSeparatorRegex.Matches(input);
return matches.Count == 0 ? -1 : matches[0].Index;
}
private Selection GetBeginningOfInstructionSelection(IdentifierReference reference)
{
var referenceSelection = reference.Selection;
var module = reference.QualifiedModuleName.Component.CodeModule;
{
var currentLine = referenceSelection.StartLine;
var codeLine = module.GetLines(currentLine, 1).StripStringLiterals();
while (GetIndexOfLastStatementSeparator(codeLine.Remove(referenceSelection.StartColumn)) == -1)
{
codeLine = module.GetLines(--currentLine, 1).StripStringLiterals();
if (!codeLine.EndsWith(" _"))
{
return new Selection(currentLine + 1, 1, currentLine + 1, 1);
}
}
var index = GetIndexOfLastStatementSeparator(codeLine.Remove(referenceSelection.StartColumn)) + 1;
return new Selection(currentLine, index, currentLine, index);
}
}
private string GetDeclarationString()
{
return Environment.NewLine + " Dim " + _target.IdentifierName + " As " + _target.AsTypeName + Environment.NewLine;
}
private void RemoveField(Declaration target)
{
Selection selection;
var declarationText = target.Context.GetText().Replace(" _" + Environment.NewLine, string.Empty);
var multipleDeclarations = target.HasMultipleDeclarationsInStatement();
var variableStmtContext = target.GetVariableStmtContext();
if (!multipleDeclarations)
{
declarationText = variableStmtContext.GetText().Replace(" _" + Environment.NewLine, string.Empty);
selection = target.GetVariableStmtContextSelection();
}
else
{
selection = new Selection(target.Context.Start.Line, target.Context.Start.Column,
target.Context.Stop.Line, target.Context.Stop.Column);
}
var module = target.QualifiedName.QualifiedModuleName.Component.CodeModule;
{
var oldLines = module.GetLines(selection.StartLine, selection.LineCount);
var newLines = oldLines.Replace(" _" + Environment.NewLine, string.Empty)
.Remove(selection.StartColumn, declarationText.Length);
if (multipleDeclarations)
{
selection = target.GetVariableStmtContextSelection();
newLines = RemoveExtraComma(module.GetLines(selection.StartLine, selection.LineCount).Replace(oldLines, newLines),
target.CountOfDeclarationsInStatement(), target.IndexOfVariableDeclarationInStatement());
}
var adjustedLines =
newLines.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => s.EndsWith(" _") ? s.Remove(s.Length - 2) : s)
.Where(s => s.Trim() != string.Empty)
.ToList();
module.DeleteLines(selection.StartLine, selection.LineCount);
if (adjustedLines.Any())
{
module.InsertLines(selection.StartLine, string.Join(string.Empty, adjustedLines));
}
}
}
private string RemoveExtraComma(string str, int numParams, int indexRemoved)
{
/* Example use cases for this method (fields and variables):
* Dim fizz as Boolean, dizz as Double
* Private fizz as Boolean, dizz as Double
* Public fizz as Boolean, _
* dizz as Double
* Private fizz as Boolean _
* , dizz as Double _
* , iizz as Integer
* Before this method is called, the parameter to be removed has
* already been removed. This means 'str' will look like:
* Dim fizz as Boolean,
* Private , dizz as Double
* Public fizz as Boolean, _
*
* Private _
* , dizz as Double _
* , iizz as Integer
* This method is responsible for removing the redundant comma
* and returning a string similar to:
* Dim fizz as Boolean
* Private dizz as Double
* Public fizz as Boolean _
*
* Private _
* dizz as Double _
* , iizz as Integer
*/
var commaToRemove = numParams == indexRemoved ? indexRemoved - 1 : indexRemoved;
return str.Remove(str.NthIndexOf(',', commaToRemove), 1);
}
private void UpdateCallsToOtherModule(List<IdentifierReference> references)
{
foreach (var reference in references.OrderByDescending(o => o.Selection.StartLine).ThenByDescending(t => t.Selection.StartColumn))
{
var module = reference.QualifiedModuleName.Component.CodeModule;
{
var parent = reference.Context.Parent;
while (!(parent is VBAParser.MemberAccessExprContext) && parent.Parent != null)
{
parent = parent.Parent;
}
if (!(parent is VBAParser.MemberAccessExprContext))
{
continue;
}
var parentSelection = ((VBAParser.MemberAccessExprContext)parent).GetSelection();
var oldText = module.GetLines(parentSelection.StartLine, parentSelection.LineCount);
string newText;
if (parentSelection.LineCount == 1)
{
newText = oldText.Remove(parentSelection.StartColumn - 1,
parentSelection.EndColumn - parentSelection.StartColumn);
}
else
{
var lines = oldText.Split(new[] { " _" + Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
newText = lines.First().Remove(parentSelection.StartColumn - 1);
newText += lines.Last().Remove(0, parentSelection.EndColumn - 1);
}
newText = newText.Insert(parentSelection.StartColumn - 1, reference.IdentifierName);
module.DeleteLines(parentSelection.StartLine, parentSelection.LineCount);
module.InsertLines(parentSelection.StartLine, newText);
}
}
}
}
}