-
Notifications
You must be signed in to change notification settings - Fork 82
/
ExtractTempRefactoring.java
1800 lines (1589 loc) · 73.8 KB
/
ExtractTempRefactoring.java
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2000, 2023 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Nikolay Metchev <nikolaymetchev@gmail.com> - [extract local] Extract to local variable not replacing multiple occurrences in same statement - https://bugs.eclipse.org/406347
* Nicolaj Hoess <nicohoess@gmail.com> - [extract local] puts declaration at wrong position - https://bugs.eclipse.org/65875
* Pierre-Yves B. <pyvesdev@gmail.com> - [inline] Allow inlining of local variable initialized to null. - https://bugs.eclipse.org/93850
* Xiaye Chi <xychichina@gmail.com> - [extract local] Extract to local variable may result in NullPointerException. - https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/39
* Xiaye Chi <xychichina@gmail.com> - [extract local] Improve the Safety of Extract Local Variable Refactorings concering ClassCasts. - https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/331
* Xiaye Chi <xychichina@gmail.com> - [extract local] Improve the Safety of Extract Local Variable Refactorings by Identifying the Side Effect of Selected Expression. - https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/348
* Xiaye Chi <xychichina@gmail.com> - [extract local] Improve the Safety of Extract Local Variable Refactorings by identifying statements that may change the value of the extracted expressions - https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/432
* Taiming Wang <3120205503@bit.edu.cn> - [extract local] Automated Name Recommendation For The Extract Local Variable Refactoring. - https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/601
* Taiming Wang <3120205503@bit.edu.cn> - [extract local] Context-based Automated Name Recommendation For The Extract Local Variable Refactoring. - https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/655
* Taiming Wang <3120205503@bit.edu.cn> - [extract local] Extract Similar Expression in All Methods If End-Users Want. - https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/785
*******************************************************************************/
package org.eclipse.jdt.internal.corext.refactoring.code;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.text.edits.CopySourceEdit;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.text.edits.TextEditGroup;
import org.eclipse.text.edits.TextEditVisitor;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.NamingConventions;
import org.eclipse.jdt.core.SourceRange;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTMatcher;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Annotation;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.CatchClause;
import org.eclipse.jdt.core.dom.ChildListPropertyDescriptor;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.EnhancedForStatement;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IExtendedModifier;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.Initializer;
import org.eclipse.jdt.core.dom.LambdaExpression;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.NullLiteral;
import org.eclipse.jdt.core.dom.ParenthesizedExpression;
import org.eclipse.jdt.core.dom.PostfixExpression;
import org.eclipse.jdt.core.dom.PrefixExpression;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.SwitchCase;
import org.eclipse.jdt.core.dom.SwitchStatement;
import org.eclipse.jdt.core.dom.TryStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationExpression;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.TypeLocation;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.core.refactoring.CompilationUnitChange;
import org.eclipse.jdt.core.refactoring.IJavaRefactorings;
import org.eclipse.jdt.core.refactoring.descriptors.ExtractLocalDescriptor;
import org.eclipse.jdt.internal.core.manipulation.BindingLabelProviderCore;
import org.eclipse.jdt.internal.core.manipulation.JavaElementLabelsCore;
import org.eclipse.jdt.internal.core.manipulation.JavaManipulationPlugin;
import org.eclipse.jdt.internal.core.manipulation.StubUtility;
import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving;
import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels;
import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory;
import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.AbortSearchException;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.GenericVisitor;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
import org.eclipse.jdt.internal.corext.dom.fragments.ASTFragmentFactory;
import org.eclipse.jdt.internal.corext.dom.fragments.IASTFragment;
import org.eclipse.jdt.internal.corext.dom.fragments.IExpressionFragment;
import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore;
import org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroupCore;
import org.eclipse.jdt.internal.corext.refactoring.Checks;
import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments;
import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringDescriptorUtil;
import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusCodes;
import org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.refactoring.util.ChangedValueChecker;
import org.eclipse.jdt.internal.corext.refactoring.util.JavaStatusContext;
import org.eclipse.jdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer;
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
import org.eclipse.jdt.internal.corext.refactoring.util.SideEffectChecker;
import org.eclipse.jdt.internal.corext.refactoring.util.UnsafeCheckTester;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.internal.ui.util.Progress;
/**
* Extract Local Variable (from selected expression inside method or initializer).
*/
public class ExtractTempRefactoring extends Refactoring {
private static final String ATTRIBUTE_REPLACE= "replace"; //$NON-NLS-1$
private static final String ATTRIBUTE_REPLACE_ALL= "replaceAllInThisFile"; //$NON-NLS-1$
private static final String ATTRIBUTE_FINAL= "final"; //$NON-NLS-1$
private static final String ATTRIBUTE_TYPE_VAR= "varType"; //$NON-NLS-1$
private static final class ForStatementChecker extends ASTVisitor {
private final Collection<IVariableBinding> fForInitializerVariables;
private boolean fReferringToForVariable= false;
public ForStatementChecker(Collection<IVariableBinding> forInitializerVariables) {
Assert.isNotNull(forInitializerVariables);
fForInitializerVariables= forInitializerVariables;
}
public boolean isReferringToForVariable() {
return fReferringToForVariable;
}
@Override
public boolean visit(SimpleName node) {
IBinding binding= node.resolveBinding();
if (binding != null && fForInitializerVariables.contains(binding)) {
fReferringToForVariable= true;
}
return false;
}
}
private static final class LocalVariableWithIdenticalExpressionFinder extends ASTVisitor {
private ArrayList<String> usedNames;
private ASTNode expression;
private Boolean ifStopOnFirstMatch;
public LocalVariableWithIdenticalExpressionFinder(ASTNode expression, Boolean ifStopOnFirstMatch) {
usedNames= new ArrayList<>();
this.expression= expression;
this.ifStopOnFirstMatch= ifStopOnFirstMatch;
}
public String getUsedName() {
return this.usedNames.get(0);
}
public ArrayList<String> getUsedNames() {
return this.usedNames;
}
public void setUsedName(String usedName) {
this.usedNames.add(usedName);
}
@Override
public boolean visit(VariableDeclarationStatement node) {
for (Object obj : node.fragments()) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment)obj;
if (fragment.getInitializer() != null) {
Expression initializer= fragment.getInitializer();
if (initializer.subtreeMatch(new ASTMatcher(), this.expression)) {
setUsedName(fragment.getName().toString());
if (this.ifStopOnFirstMatch.booleanValue())
throw new AbortSearchException();
}
}
}
return true;
}
}
private static final class IdenticalExpressionFinder extends GenericVisitor {
private ArrayList<ASTNode> identicalFragments;
private ASTNode expression;
private HashMap<ASTNode, String> enclosingKeyMap;
public IdenticalExpressionFinder(ASTNode expression) {
this.identicalFragments= new ArrayList<>();
this.enclosingKeyMap= new HashMap<>();
this.expression= expression;
}
public ASTNode[] getIdenticalFragments() {
return this.identicalFragments.toArray(new ASTNode[identicalFragments.size()]);
}
public HashMap<ASTNode, String> getEclosingKeyMap() {
return enclosingKeyMap;
}
@Override
public boolean visitNode(ASTNode node) {
if (node.subtreeMatch(new ASTMatcher(), this.expression)) {
this.identicalFragments.add(node);
MethodDeclaration methodDeclaration= ASTNodes.getFirstAncestorOrNull(node, MethodDeclaration.class);
this.enclosingKeyMap.put(node, methodDeclaration.resolveBinding().getMethodDeclaration().getKey());
}
return true;
}
}
private static boolean allArraysEqual(ASTNode[][] arrays, int position) {
Object element= arrays[0][position];
for (ASTNode[] a : arrays) {
Object[] array= a;
if (!element.equals(array[position]))
return false;
}
return true;
}
private static boolean canReplace(IASTFragment fragment) {
ASTNode node= fragment.getAssociatedNode();
ASTNode parent= node.getParent();
if (parent instanceof VariableDeclarationFragment) {
VariableDeclarationFragment vdf= (VariableDeclarationFragment) parent;
if (node.equals(vdf.getName()))
return false;
}
if (isMethodParameter(node))
return false;
if (isThrowableInCatchBlock(node))
return false;
if (parent instanceof ExpressionStatement)
return false;
if (parent instanceof LambdaExpression)
return false;
if (isLeftValue(node))
return false;
if (isReferringToLocalVariableFromFor((Expression) node))
return false;
if (isUsedInForInitializerOrUpdater((Expression) node))
return false;
if (parent instanceof SuperConstructorInvocation)
return false;
if (parent instanceof ConstructorInvocation)
return false;
if (parent instanceof SwitchCase)
return true;
if (node instanceof SimpleName && node.getLocationInParent() != null) {
return !"name".equals(node.getLocationInParent().getId()); //$NON-NLS-1$
}
return true;
}
private static ASTNode[] getArrayPrefix(ASTNode[] array, int prefixLength) {
Assert.isTrue(prefixLength <= array.length);
Assert.isTrue(prefixLength >= 0);
ASTNode[] prefix= new ASTNode[prefixLength];
System.arraycopy(array, 0, prefix, 0, prefix.length);
return prefix;
}
// return List<IVariableBinding>
private static List<IVariableBinding> getForInitializedVariables(VariableDeclarationExpression variableDeclarations) {
List<IVariableBinding> forInitializerVariables= new ArrayList<>(1);
for (Iterator<VariableDeclarationFragment> iter= variableDeclarations.fragments().iterator(); iter.hasNext();) {
VariableDeclarationFragment fragment= iter.next();
IVariableBinding binding= fragment.resolveBinding();
if (binding != null)
forInitializerVariables.add(binding);
}
return forInitializerVariables;
}
private static ASTNode[] getLongestArrayPrefix(ASTNode[][] arrays) {
int length= -1;
if (arrays.length == 0)
return new ASTNode[0];
int minArrayLength= arrays[0].length;
for (int i= 1; i < arrays.length; i++)
minArrayLength= Math.min(minArrayLength, arrays[i].length);
for (int i= 0; i < minArrayLength; i++) {
if (!allArraysEqual(arrays, i))
break;
length++;
}
if (length == -1)
return new ASTNode[0];
return getArrayPrefix(arrays[0], length + 1);
}
private static ASTNode[] getParents(ASTNode node) {
ASTNode current= node;
List<ASTNode> parents= new ArrayList<>();
do {
parents.add(current.getParent());
current= current.getParent();
} while (current.getParent() != null);
Collections.reverse(parents);
return parents.toArray(new ASTNode[parents.size()]);
}
private static boolean isLeftValue(ASTNode node) {
ASTNode parent= node.getParent();
if (parent instanceof Assignment) {
Assignment assignment= (Assignment) parent;
if (assignment.getLeftHandSide() == node)
return true;
}
if (parent instanceof PostfixExpression)
return true;
if (parent instanceof PrefixExpression) {
PrefixExpression.Operator op= ((PrefixExpression) parent).getOperator();
if (op.equals(PrefixExpression.Operator.DECREMENT))
return true;
if (op.equals(PrefixExpression.Operator.INCREMENT))
return true;
return false;
}
return false;
}
private static boolean isMethodParameter(ASTNode node) {
return (node instanceof SimpleName) && (node.getParent() instanceof SingleVariableDeclaration) && (node.getParent().getParent() instanceof MethodDeclaration);
}
private static boolean isReferringToLocalVariableFromFor(Expression expression) {
ASTNode current= expression;
ASTNode parent= current.getParent();
while (parent != null && !(parent instanceof BodyDeclaration)) {
if (parent instanceof ForStatement) {
ForStatement forStmt= (ForStatement) parent;
if (forStmt.initializers().contains(current) || forStmt.updaters().contains(current) || forStmt.getExpression() == current) {
List<Expression> initializers= forStmt.initializers();
if (initializers.size() == 1 && initializers.get(0) instanceof VariableDeclarationExpression) {
List<IVariableBinding> forInitializerVariables= getForInitializedVariables((VariableDeclarationExpression) initializers.get(0));
ForStatementChecker checker= new ForStatementChecker(forInitializerVariables);
expression.accept(checker);
if (checker.isReferringToForVariable())
return true;
}
}
}
current= parent;
parent= current.getParent();
}
return false;
}
private static boolean isThrowableInCatchBlock(ASTNode node) {
return (node instanceof SimpleName) && (node.getParent() instanceof SingleVariableDeclaration) && (node.getParent().getParent() instanceof CatchClause);
}
private static boolean isUsedInForInitializerOrUpdater(Expression expression) {
ASTNode parent= expression.getParent();
if (parent instanceof ForStatement) {
ForStatement forStmt= (ForStatement) parent;
return forStmt.initializers().contains(expression) || forStmt.updaters().contains(expression);
}
return false;
}
private IASTFragment[] retainOnlyReplacableMatches(IASTFragment[] allMatches) {
List<IASTFragment> result= new ArrayList<>(allMatches.length);
for (IASTFragment match : allMatches) {
if (canReplace(match)) {
result.add(match);
}
}
Comparator<IASTFragment> comparator= (o1, o2) -> o1.getStartPosition() - o2.getStartPosition();
result.sort(comparator);
try {
boolean flag= false;
IExpressionFragment selectedFragment= getSelectedExpression();
ASTNode associatedNode= selectedFragment.getAssociatedNode();
IExpressionFragment firstExpression= getCertainReplacedExpression(result.toArray(new IASTFragment[result.size()]), 0);
if (firstExpression.getStartPosition() < selectedFragment.getStartPosition())
flag= false;
else
flag= (associatedNode.getParent() instanceof ExpressionStatement || associatedNode.getParent() instanceof LambdaExpression)
&& selectedFragment.matches(ASTFragmentFactory.createFragmentForFullSubtree(associatedNode));
int upper= result.size();
if (flag) {
ASTNode parent= associatedNode.getParent();
StructuralPropertyDescriptor location= parent.getLocationInParent();
while (parent != null) {
if (parent instanceof Block || parent instanceof BodyDeclaration || parent instanceof LambdaExpression && ((LambdaExpression) parent).resolveMethodBinding() != null
|| parent instanceof EnhancedForStatement || parent instanceof WhileStatement
|| parent instanceof ForStatement || parent instanceof DoStatement) {
break;
}
location= parent.getLocationInParent();
if (location == IfStatement.ELSE_STATEMENT_PROPERTY || location == IfStatement.THEN_STATEMENT_PROPERTY || location == SwitchStatement.STATEMENTS_PROPERTY) {
break;
}
parent= parent.getParent();
}
if (parent == null) {
return result.toArray(new IASTFragment[result.size()]);
}
int offset= parent.getStartPosition() + parent.getLength();
if (location == SwitchStatement.STATEMENTS_PROPERTY) {
SwitchStatement ss= (SwitchStatement) parent.getParent();
Iterator<Object> iterator= ss.statements().iterator();
int preOffset= -1;
while (iterator.hasNext()) {
Object obj= iterator.next();
if (obj instanceof ASTNode) {
ASTNode node= (ASTNode) obj;
if (node instanceof SwitchCase && node.getStartPosition() > offset) {
break;
}
preOffset= node.getStartPosition() + node.getLength();
}
}
if (preOffset > 0)
offset= preOffset;
}
for (int i= 0; i < result.size(); ++i) {
if (result.get(i).getStartPosition() > offset) {
upper= i;
break;
}
}
}
return result.subList(0, upper).toArray(new IASTFragment[upper]);
} catch (JavaModelException e) {
return result.toArray(new IASTFragment[result.size()]);
}
}
private CompilationUnit fCompilationUnitNode;
private CompilationUnitRewrite fCURewrite;
private ICompilationUnit fCu;
private boolean fDeclareFinal;
private boolean fDeclareVarType;
private String[] fExcludedVariableNames;
private boolean fReplaceAllOccurrences;
private boolean fReplaceAllOccurrencesInThisFile;
// caches:
private IExpressionFragment fSelectedExpression;
private int fSelectionLength;
private int fSelectionStart;
private String fTempName;
private String[] fGuessedTempNames;
private boolean fCheckResultForCompileProblems;
private CompilationUnitChange fChange;
private LinkedProposalModelCore fLinkedProposalModel;
private static final String KEY_NAME= "name"; //$NON-NLS-1$
private static final String KEY_TYPE= "type"; //$NON-NLS-1$
private int fStartPoint;
private int fEndPoint;
private HashSet<IASTFragment> fSeen= new HashSet<>();
private String fEnclosingKey;
private HashSet<String> fEnclosingKeySet;
private Map<String,String> fFormatterOptions;
/**
* Creates a new extract temp refactoring
*
* @param unit the compilation unit, or <code>null</code> if invoked by scripting
* @param selectionStart start of selection
* @param selectionLength length of selection
*/
public ExtractTempRefactoring(ICompilationUnit unit, int selectionStart, int selectionLength) {
this(unit, selectionStart, selectionLength, null);
}
public ExtractTempRefactoring(ICompilationUnit unit, int selectionStart, int selectionLength, Map<String,String> formatterOptions) {
Assert.isTrue(selectionStart >= 0);
Assert.isTrue(selectionLength >= 0);
fSelectionStart= selectionStart;
fSelectionLength= selectionLength;
fCu= unit;
fCompilationUnitNode= null;
fReplaceAllOccurrences= true; // default
fReplaceAllOccurrencesInThisFile= false; //default
fDeclareFinal= false; // default
fDeclareVarType= false; // default
fTempName= ""; //$NON-NLS-1$
fLinkedProposalModel= null;
fCheckResultForCompileProblems= true;
fStartPoint= -1; // default
fEndPoint= -1; // default
fEnclosingKey= null;
fEnclosingKeySet= new HashSet<>();
fFormatterOptions = formatterOptions;
}
public ExtractTempRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength) {
this(astRoot, selectionStart, selectionLength, null);
}
public ExtractTempRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength, Map<String,String> formatterOptions) {
Assert.isTrue(selectionStart >= 0);
Assert.isTrue(selectionLength >= 0);
Assert.isTrue(astRoot.getTypeRoot() instanceof ICompilationUnit);
fSelectionStart= selectionStart;
fSelectionLength= selectionLength;
fCu= (ICompilationUnit) astRoot.getTypeRoot();
fCompilationUnitNode= astRoot;
fReplaceAllOccurrences= true; // default
fReplaceAllOccurrencesInThisFile= false; //default
fDeclareFinal= false; // default
fDeclareVarType= false; // default
fTempName= ""; //$NON-NLS-1$
fLinkedProposalModel= null;
fCheckResultForCompileProblems= true;
fStartPoint= -1; // default
fEndPoint= -1; // default
fEnclosingKey= null;
fEnclosingKeySet= new HashSet<>();
fFormatterOptions = formatterOptions;
}
public ExtractTempRefactoring(JavaRefactoringArguments arguments, RefactoringStatus status) {
this((ICompilationUnit) null, 0, 0);
fStartPoint= -1; // default
fEndPoint= -1; // default
fEnclosingKey= null;
fEnclosingKeySet= new HashSet<>();
RefactoringStatus initializeStatus= initialize(arguments);
status.merge(initializeStatus);
}
public void setCheckResultForCompileProblems(boolean checkResultForCompileProblems) {
fCheckResultForCompileProblems= checkResultForCompileProblems;
}
public void setLinkedProposalModel(LinkedProposalModelCore linkedProposalModel) {
fLinkedProposalModel= linkedProposalModel;
}
private void addReplaceExpressionWithTemp() throws JavaModelException {
IASTFragment[] fragmentsToReplace= retainOnlyReplacableMatches(getMatchingFragments());
if (fragmentsToReplace.length == 0 || fEndPoint == -1) {
return;
}
//TODO: should not have to prune duplicates here...
ASTRewrite rewrite= fCURewrite.getASTRewrite();
for (int i= fEndPoint; i >= fStartPoint; --i) {
IASTFragment fragment= fragmentsToReplace[i];
if (!fSeen.add(fragment))
continue;
SimpleName tempName= fCURewrite.getAST().newSimpleName(fTempName);
TextEditGroup description= fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_replace);
fragment.replace(rewrite, tempName, description);
if (fLinkedProposalModel != null)
fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(rewrite.track(tempName), false);
}
}
private RefactoringStatus checkExpression() throws JavaModelException {
Expression selectedExpression= getSelectedExpression().getAssociatedExpression();
if (selectedExpression != null) {
final ASTNode parent= selectedExpression.getParent();
if (selectedExpression instanceof NullLiteral) {
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals);
} else if (selectedExpression instanceof ArrayInitializer) {
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer);
} else if (selectedExpression instanceof Assignment) {
if (parent instanceof Expression && !(parent instanceof ParenthesizedExpression))
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment);
else
return null;
} else if (selectedExpression instanceof SimpleName) {
if ((((SimpleName) selectedExpression)).isDeclaration())
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations);
if (parent instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
|| parent instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression);
} else if (selectedExpression instanceof VariableDeclarationExpression && parent instanceof TryStatement) {
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_resource_in_try_with_resources);
}
}
return null;
}
// !! Same as in ExtractConstantRefactoring
private RefactoringStatus checkExpressionFragmentIsRValue() throws JavaModelException {
switch (Checks.checkExpressionIsRValue(getSelectedExpression().getAssociatedExpression())) {
case Checks.NOT_RVALUE_MISC:
return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractTempRefactoring_select_expression, null, JavaManipulationPlugin.getPluginId(),
RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, null);
case Checks.NOT_RVALUE_VOID:
return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractTempRefactoring_no_void, null, JavaManipulationPlugin.getPluginId(),
RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID, null);
case Checks.IS_RVALUE_GUESSED:
case Checks.IS_RVALUE:
return new RefactoringStatus();
default:
Assert.isTrue(false);
return null;
}
}
private ITypeBinding guessBindingForReference(Expression expression) {
ITypeBinding binding= expression.resolveTypeBinding();
if (binding == null) {
binding= ASTResolving.guessBindingForReference(expression);
}
return binding;
}
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
try {
pm.beginTask(RefactoringCoreMessages.ExtractTempRefactoring_checking_preconditions, 4);
fCURewrite= new CompilationUnitRewrite(null, fCu, fCompilationUnitNode, fFormatterOptions);
fCURewrite.getASTRewrite().setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
RefactoringStatus result= new RefactoringStatus();
fStartPoint= -1;
fEndPoint= -1;
fSeen.clear();
boolean replaceAll= fReplaceAllOccurrences;
if (fReplaceAllOccurrences) {
RefactoringStatus checkSideEffectsInSelectedExpression= checkSideEffectsInSelectedExpression();
if (checkSideEffectsInSelectedExpression.hasInfo()) {
fReplaceAllOccurrences= false;
result.merge(checkSideEffectsInSelectedExpression);
}
}
doCreateChange(Progress.subMonitor(pm, 2));
fChange= fCURewrite.createChange(RefactoringCoreMessages.ExtractTempRefactoring_change_name, true, Progress.subMonitor(pm, 1));
fChange.getEdit().accept(new TextEditVisitor() {
@Override
public void preVisit(TextEdit edit) {
TextEdit[] children= edit.getChildren();
for (TextEdit te : children)
if (te instanceof CopySourceEdit) {
CopySourceEdit cse= (CopySourceEdit) te;
if (cse.getTargetEdit() == null || cse.getTargetEdit().getOffset() == 0) {
edit.removeChild(te);
}
}
super.preVisit(edit);
}
});
if (Arrays.asList(getExcludedVariableNames()).contains(fTempName))
result.addWarning(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_another_variable, BasicElementLabels.getJavaElementName(fTempName)));
result.merge(checkMatchingFragments());
fChange.setKeepPreviewEdits(false);
if (fCheckResultForCompileProblems) {
result.merge(RefactoringAnalyzeUtil.checkNewSource(fChange, fCu, fCompilationUnitNode, pm));
}
fReplaceAllOccurrences= replaceAll;
return result;
} finally {
pm.done();
}
}
private final ExtractLocalDescriptor createRefactoringDescriptor() {
final Map<String, String> arguments= new HashMap<>();
String project= null;
IJavaProject javaProject= fCu.getJavaProject();
if (javaProject != null)
project= javaProject.getElementName();
final String description= Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fTempName));
final String expression= ASTNodes.asString(fSelectedExpression.getAssociatedExpression());
final String header= Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description,
new String[] { BasicElementLabels.getJavaElementName(fTempName), BasicElementLabels.getJavaCodeString(expression) });
final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_name_pattern, BasicElementLabels.getJavaElementName(fTempName)));
final BodyDeclaration decl= ASTNodes.getParent(fSelectedExpression.getAssociatedExpression(), BodyDeclaration.class);
if (decl instanceof MethodDeclaration) {
final IMethodBinding method= ((MethodDeclaration) decl).resolveBinding();
final String label= method != null
? BindingLabelProviderCore.getBindingLabel(method, JavaElementLabelsCore.ALL_FULLY_QUALIFIED)
: BasicElementLabels.getJavaElementName('{' + JavaElementLabelsCore.ELLIPSIS_STRING + '}');
comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_destination_pattern, label));
}
comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_expression_pattern, BasicElementLabels.getJavaCodeString(expression)));
if (fReplaceAllOccurrences)
comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_replace_occurrences);
if (fReplaceAllOccurrencesInThisFile)
comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_replace_occurrences_in_this_file);
if (fDeclareFinal)
comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_declare_final);
if (fDeclareVarType)
comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_declare_var_type);
final ExtractLocalDescriptor descriptor= RefactoringSignatureDescriptorFactory.createExtractLocalDescriptor(project, description, comment.asString(), arguments, RefactoringDescriptor.NONE);
arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu));
arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fTempName);
arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, Integer.toString(fSelectionStart) + " " + Integer.toString(fSelectionLength)); //$NON-NLS-1$
arguments.put(ATTRIBUTE_REPLACE, Boolean.toString(fReplaceAllOccurrences));
arguments.put(ATTRIBUTE_REPLACE_ALL, Boolean.toString(fReplaceAllOccurrencesInThisFile));
arguments.put(ATTRIBUTE_FINAL, Boolean.toString(fDeclareFinal));
arguments.put(ATTRIBUTE_TYPE_VAR, Boolean.toString(fDeclareVarType));
return descriptor;
}
private void doCreateChange(IProgressMonitor pm) {
try {
pm.beginTask(RefactoringCoreMessages.ExtractTempRefactoring_checking_preconditions, 1);
try {
processSelectedExpression();
if (replaceAllOccurrences() && replaceAllOccurrencesInThisFile()) {
processOtherIdenticalExpressions();
}
} catch (CoreException exception) {
JavaManipulationPlugin.log(exception);
}
} finally {
pm.done();
}
}
private void processSelectedExpression() throws CoreException {
int cnt= 1;
getSelectedExpression();
MethodDeclaration methodDeclaration= ASTNodes.getFirstAncestorOrNull(fSelectedExpression.getAssociatedNode(), MethodDeclaration.class);
if (methodDeclaration != null && methodDeclaration.resolveBinding() != null && methodDeclaration.resolveBinding().getMethodDeclaration() != null) {
fEnclosingKey= methodDeclaration.resolveBinding().getMethodDeclaration().getKey();
fEnclosingKeySet.add(fEnclosingKey);
}
fSelectionStart= fSelectedExpression.getStartPosition();
fSelectionLength= fSelectedExpression.getLength();
IASTFragment[] retainOnlyReplacableMatches= retainOnlyReplacableMatches(getMatchingFragments());
int tmpFSelectionStart= fSelectionStart;
int tmpFSelectionLength= fSelectionLength;
IExpressionFragment tmpFSelectedExpression= fSelectedExpression;
Collection<String> usedNames= getUsedLocalNames(fSelectedExpression.getAssociatedNode());
String newName= fTempName;
if (!replaceAllOccurrences() || shouldReplaceSelectedExpressionWithTempDeclaration()
|| retainOnlyReplacableMatches.length == 0) {
createTempDeclaration();
addReplaceExpressionWithTemp();
fTempName= newName + ++cnt;
while (usedNames.contains(fTempName)) {
fTempName= newName + ++cnt;
}
}
while (replaceAllOccurrences() &&
retainOnlyReplacableMatches.length > fSeen.size()) {
fStartPoint= -1;
fEndPoint= -1;
boolean flag= false;
for (int i= 0; i < retainOnlyReplacableMatches.length; ++i) {
if (!fSeen.contains(retainOnlyReplacableMatches[i])) {
fSelectionStart= retainOnlyReplacableMatches[i].getStartPosition();
fSelectionLength= retainOnlyReplacableMatches[i].getLength();
fSelectedExpression= null;
getSelectedExpression();
flag= true;
break;
}
}
if (flag == false)
break;
createTempDeclaration();
if (fStartPoint != -1 && fEndPoint != -1) {
addReplaceExpressionWithTemp();
fTempName= newName + ++cnt;
while (usedNames.contains(fTempName)) {
fTempName= newName + ++cnt;
}
}
}
fSelectionStart= tmpFSelectionStart;
fSelectionLength= tmpFSelectionLength;
fSelectedExpression= tmpFSelectedExpression;
fTempName= newName;
}
private void processOtherIdenticalExpressions() throws CoreException {
ASTNode associatedNode= getSelectedExpression().getAssociatedNode();
CompilationUnit cuNode= ASTNodes.getFirstAncestorOrNull(associatedNode, CompilationUnit.class);
IdenticalExpressionFinder identicalExpressionFinder= new IdenticalExpressionFinder(associatedNode);
cuNode.accept(identicalExpressionFinder);
ASTNode[] matchedFragments= identicalExpressionFinder.getIdenticalFragments();
HashMap<ASTNode, String> enclosingKeyMap= identicalExpressionFinder.getEclosingKeyMap();
int realStartOffset= getRealStartOffset(matchedFragments, enclosingKeyMap);
int realLength= fSelectionLength;
for (ASTNode fragment : matchedFragments) {
fSeen.clear();
if (!fEnclosingKeySet.contains(enclosingKeyMap.get(fragment))) {
fSelectedExpression= getSelectedExpression(fragment.getStartPosition() + realStartOffset, realLength);
processSelectedExpression();
}
}
}
private int getRealStartOffset(ASTNode[] matchedFragments, HashMap<ASTNode, String> enclosingKeyMap) {
int realStartOffset= 0;
for (ASTNode fragment : matchedFragments) {
if (fragment.getLength() == fSelectionLength) {
return realStartOffset;
}
if (fEnclosingKeySet.contains(enclosingKeyMap.get(fragment))) {
int startOffset= Math.abs(fSelectionStart - fragment.getStartPosition());
if (realStartOffset != 0) {
realStartOffset= Math.min(realStartOffset, startOffset);
} else {
realStartOffset= startOffset;
}
}
}
return realStartOffset;
}
/**
* Retrieves used names for the block containing a node.
*
* @param selected the selected node
*
* @return an array of used variable names to avoid
*/
private Collection<String> getUsedLocalNames(ASTNode selected) {
ASTNode surroundingBlock= selected;
while ((surroundingBlock= surroundingBlock.getParent()) != null) {
if (surroundingBlock instanceof Block || surroundingBlock instanceof MethodDeclaration) {
break;
}
}
if (surroundingBlock == null) {
return new ArrayList<>();
}
Collection<String> localUsedNames= new ScopeAnalyzer((CompilationUnit) selected.getRoot()).getUsedVariableNames(surroundingBlock.getStartPosition(), surroundingBlock.getLength());
return localUsedNames;
}
/**
* Retrieves a used name in the whole compilation unit that is assigned with the same
* expression.
*
* @param selected the selected node
*
* @return a used variable name for recommending new names.
*/
private String getUsedNameForIdenticalExpressionInCu(ASTNode selected) {
ASTNode surroundingBlock= selected;
surroundingBlock= ASTNodes.getFirstAncestorOrNull(surroundingBlock, CompilationUnit.class);
if (surroundingBlock == null) {
return null;
}
LocalVariableWithIdenticalExpressionFinder localVariableWithIdenticalExpressionFinder= new LocalVariableWithIdenticalExpressionFinder(selected, Boolean.TRUE);
String usedNameForIdenticalExpressionInCu= null;
try {
surroundingBlock.accept(localVariableWithIdenticalExpressionFinder);
} catch (AbortSearchException e) {
usedNameForIdenticalExpressionInCu= localVariableWithIdenticalExpressionFinder.getUsedName();
}
return usedNameForIdenticalExpressionInCu;
}
/**
* Retrieves used names in the method declaration that is assigned with the same expression.
*
* @param selected the selected node
*
* @return an array of used variable names for avoiding conflicts.
*/
private Collection<String> getUsedNameForIdenticalExpressionInMethod(ASTNode selected) {
ASTNode surroundingBlock= selected;
surroundingBlock= ASTNodes.getFirstAncestorOrNull(surroundingBlock, MethodDeclaration.class);
if (surroundingBlock == null) {
return new ArrayList<>();
}
LocalVariableWithIdenticalExpressionFinder localVariableWithIdenticalExpressionFinder= new LocalVariableWithIdenticalExpressionFinder(selected, Boolean.FALSE);
surroundingBlock.accept(localVariableWithIdenticalExpressionFinder);
List<String> UsedNameForIdenticalExpressionInMethod= localVariableWithIdenticalExpressionFinder.getUsedNames();
return UsedNameForIdenticalExpressionInMethod;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
try {
pm.beginTask("", 6); //$NON-NLS-1$
RefactoringStatus result= Checks.validateModifiesFiles(ResourceUtil.getFiles(new ICompilationUnit[] { fCu }), getValidationContext(), pm);
if (result.hasFatalError())
return result;
if (fCompilationUnitNode == null) {
fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, Progress.subMonitor(pm, 3));
} else {
pm.worked(3);
}
result.merge(checkSelection(Progress.subMonitor(pm, 3)));
if (!result.hasFatalError() && isLiteralNodeSelected())
fReplaceAllOccurrences= false;
return result;
} finally {