-
Notifications
You must be signed in to change notification settings - Fork 86
/
AdvancedQuickAssistProcessor.java
3245 lines (2982 loc) · 136 KB
/
AdvancedQuickAssistProcessor.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:
* Konstantin Scheglov (scheglov_ke@nlmk.ru) - initial API and implementation
* (reports 71244 & 74746: New Quick Assist's [quick assist])
* IBM Corporation - implementation
* Billy Huang <billyhuang31@gmail.com> - [quick assist] concatenate/merge string literals - https://bugs.eclipse.org/77632
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.eclipse.swt.graphics.Image;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.NamingConventions;
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.AssertStatement;
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.BooleanLiteral;
import org.eclipse.jdt.core.dom.BreakStatement;
import org.eclipse.jdt.core.dom.CastExpression;
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.ConditionalExpression;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.ContinueStatement;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.EnhancedForStatement;
import org.eclipse.jdt.core.dom.EnumConstantDeclaration;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IBinding;
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.InfixExpression;
import org.eclipse.jdt.core.dom.InfixExpression.Operator;
import org.eclipse.jdt.core.dom.InstanceofExpression;
import org.eclipse.jdt.core.dom.LambdaExpression;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.ParenthesizedExpression;
import org.eclipse.jdt.core.dom.PrefixExpression;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.RecordDeclaration;
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.StringLiteral;
import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.SwitchCase;
import org.eclipse.jdt.core.dom.SwitchStatement;
import org.eclipse.jdt.core.dom.ThrowStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
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.internal.core.manipulation.StubUtility;
import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving;
import org.eclipse.jdt.internal.core.manipulation.dom.NecessaryParenthesesChecker;
import org.eclipse.jdt.internal.core.manipulation.dom.OperatorPrecedence;
import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.GenericVisitor;
import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder;
import org.eclipse.jdt.internal.corext.dom.StatementRewrite;
import org.eclipse.jdt.internal.corext.fix.CleanUpConstants;
import org.eclipse.jdt.internal.corext.fix.ExpressionsFix;
import org.eclipse.jdt.internal.corext.fix.IProposableFix;
import org.eclipse.jdt.internal.corext.refactoring.code.Invocations;
import org.eclipse.jdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer;
import org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.ui.cleanup.CleanUpOptions;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.ui.text.java.IQuickAssistProcessor;
import org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal;
import org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal;
import org.eclipse.jdt.ui.text.java.correction.ICommandAccess;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.AddGetterSetterTypeProposal;
import org.eclipse.jdt.internal.ui.actions.HashCodeEqualsTypeProposal;
import org.eclipse.jdt.internal.ui.actions.ToStringTypeProposal;
import org.eclipse.jdt.internal.ui.fix.ExpressionsCleanUp;
import org.eclipse.jdt.internal.ui.text.correction.proposals.FixCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal;
import org.eclipse.jdt.internal.ui.util.ASTHelper;
public class AdvancedQuickAssistProcessor implements IQuickAssistProcessor {
public AdvancedQuickAssistProcessor() {
super();
}
@Override
public boolean hasAssists(IInvocationContext context) throws CoreException {
ASTNode coveringNode= context.getCoveringNode();
if (coveringNode != null) {
ArrayList<ASTNode> coveredNodes= getFullyCoveredNodes(context, coveringNode);
return getConvertToIfReturnProposals(context, coveringNode, null)
|| getInverseIfProposals(context, coveringNode, null)
|| getIfReturnIntoIfElseAtEndOfVoidMethodProposals(context, coveringNode, null)
|| getInverseIfContinueIntoIfThenInLoopsProposals(context, coveringNode, null)
|| getInverseIfIntoContinueInLoopsProposals(context, coveringNode, null)
|| getInverseConditionProposals(context, coveringNode, coveredNodes, null)
|| getRemoveExtraParenthesesProposals(context, coveringNode, coveredNodes, null)
|| getAddParanoidalParenthesesProposals(context, coveredNodes, null)
|| getAddParenthesesForExpressionProposals(context, coveringNode, null)
|| getJoinAndIfStatementsProposals(context, coveringNode, null)
|| getSplitAndConditionProposals(context, coveringNode, null)
|| getJoinOrIfStatementsProposals(context, coveringNode, coveredNodes, null)
|| getSplitOrConditionProposals(context, coveringNode, null)
|| getInverseConditionalExpressionProposals(context, coveringNode, null)
|| getExchangeInnerAndOuterIfConditionsProposals(context, coveringNode, null)
|| getExchangeOperandsProposals(context, coveringNode, null)
|| getCastAndAssignIfStatementProposals(context, coveringNode, null)
|| getCombineStringProposals(context, coveringNode, null)
|| getPickOutStringProposals(context, coveringNode, null)
|| getReplaceIfElseWithConditionalProposals(context, coveringNode, null)
|| getReplaceConditionalWithIfElseProposals(context, coveringNode, null)
|| getInverseLocalVariableProposals(context, coveringNode, null)
|| getPushNegationDownProposals(context, coveringNode, null)
|| getPullNegationUpProposals(context, coveredNodes, null)
|| getJoinIfListInIfElseIfProposals(context, coveringNode, coveredNodes, null)
|| getConvertSwitchToIfProposals(context, coveringNode, null)
|| getConvertIfElseToSwitchProposals(context, coveringNode, null)
|| GetterSetterCorrectionSubProcessor.addGetterSetterProposal(context, coveringNode, null, null)
|| getGettersSettersForTypeProposals(coveringNode, null)
|| getHashCodeEqualsForTypeProposals(coveringNode, null)
|| getToStringForTypeProposals(coveringNode, null)
|| ExternalNullAnnotationQuickAssistProcessor.canAssist(context);
}
return false;
}
@Override
public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
ASTNode coveringNode= context.getCoveringNode();
if (coveringNode != null) {
ArrayList<ASTNode> coveredNodes= getFullyCoveredNodes(context, coveringNode);
ArrayList<ICommandAccess> resultingCollections= new ArrayList<>();
//quick assists that show up also if there is an error/warning
getReplaceConditionalWithIfElseProposals(context, coveringNode, resultingCollections);
if (QuickAssistProcessor.noErrorsAtLocation(locations)) {
getConvertToIfReturnProposals(context, coveringNode, resultingCollections);
getInverseIfProposals(context, coveringNode, resultingCollections);
getIfReturnIntoIfElseAtEndOfVoidMethodProposals(context, coveringNode, resultingCollections);
getInverseIfContinueIntoIfThenInLoopsProposals(context, coveringNode, resultingCollections);
getInverseIfIntoContinueInLoopsProposals(context, coveringNode, resultingCollections);
getInverseConditionProposals(context, coveringNode, coveredNodes, resultingCollections);
getRemoveExtraParenthesesProposals(context, coveringNode, coveredNodes, resultingCollections);
getAddParanoidalParenthesesProposals(context, coveredNodes, resultingCollections);
getAddParenthesesForExpressionProposals(context, coveringNode, resultingCollections);
getJoinAndIfStatementsProposals(context, coveringNode, resultingCollections);
getSplitAndConditionProposals(context, coveringNode, resultingCollections);
getJoinOrIfStatementsProposals(context, coveringNode, coveredNodes, resultingCollections);
getSplitOrConditionProposals(context, coveringNode, resultingCollections);
getInverseConditionalExpressionProposals(context, coveringNode, resultingCollections);
getExchangeInnerAndOuterIfConditionsProposals(context, coveringNode, resultingCollections);
getExchangeOperandsProposals(context, coveringNode, resultingCollections);
getCastAndAssignIfStatementProposals(context, coveringNode, resultingCollections);
getCombineStringProposals(context, coveringNode, resultingCollections);
getPickOutStringProposals(context, coveringNode, resultingCollections);
getReplaceIfElseWithConditionalProposals(context, coveringNode, resultingCollections);
getInverseLocalVariableProposals(context, coveringNode, resultingCollections);
getPushNegationDownProposals(context, coveringNode, resultingCollections);
getPullNegationUpProposals(context, coveredNodes, resultingCollections);
getJoinIfListInIfElseIfProposals(context, coveringNode, coveredNodes, resultingCollections);
getConvertSwitchToIfProposals(context, coveringNode, resultingCollections);
getConvertIfElseToSwitchProposals(context, coveringNode, resultingCollections);
GetterSetterCorrectionSubProcessor.addGetterSetterProposal(context, coveringNode, locations, resultingCollections);
getGettersSettersForTypeProposals(coveringNode, resultingCollections);
getHashCodeEqualsForTypeProposals(coveringNode, resultingCollections);
getToStringForTypeProposals(coveringNode, resultingCollections);
ExternalNullAnnotationQuickAssistProcessor.getAnnotateProposals(context, resultingCollections);
}
return resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
}
return null;
}
private static boolean getConvertToIfReturnProposals(IInvocationContextCore context, ASTNode coveringNode, ArrayList<ICommandAccess> resultingCollections) {
if (!(coveringNode instanceof IfStatement)) {
return false;
}
IfStatement ifStatement= (IfStatement) coveringNode;
if (ifStatement.getElseStatement() != null) {
return false;
}
// enclosing lambda or method should return 'void'
LambdaExpression enclosingLambda= ASTResolving.findEnclosingLambdaExpression(ifStatement);
if (enclosingLambda != null) {
IMethodBinding lambdaMethodBinding= enclosingLambda.resolveMethodBinding();
if (lambdaMethodBinding == null) {
return false;
}
if (!(ifStatement.getAST().resolveWellKnownType("void").equals(lambdaMethodBinding.getReturnType()))) { //$NON-NLS-1$
return false;
}
} else {
MethodDeclaration coveringMethod= ASTResolving.findParentMethodDeclaration(ifStatement);
if (coveringMethod == null) {
return false;
}
Type returnType= coveringMethod.getReturnType2();
if (!isVoid(returnType)) {
return false;
}
}
// should be present in a block
if (!(ifStatement.getParent() instanceof Block)) {
return false;
}
// should have at least one statement in 'then' part other than 'return'
Statement thenStatement= ifStatement.getThenStatement();
if (thenStatement instanceof ReturnStatement) {
return false;
}
if (thenStatement instanceof Block) {
List<Statement> thenStatements= ((Block) thenStatement).statements();
if (thenStatements.isEmpty() || (thenStatements.size() == 1 && (thenStatements.get(0) instanceof ReturnStatement))) {
return false;
}
}
// should have no further executable statement
if (!isLastStatementInEnclosingMethodOrLambda(ifStatement)) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
AST ast= coveringNode.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
// create inverted 'if' statement
Expression inversedExpression= getInversedExpression(rewrite, ifStatement.getExpression());
IfStatement newIf= ast.newIfStatement();
newIf.setExpression(inversedExpression);
newIf.setThenStatement(ast.newReturnStatement());
ListRewrite listRewriter= rewrite.getListRewrite(ifStatement.getParent(), (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
listRewriter.replace(ifStatement, newIf, null);
// remove last 'return' in 'then' block
ArrayList<Statement> statements= getUnwrappedStatements(ifStatement.getThenStatement());
Statement lastStatement= statements.get(statements.size() - 1);
if (lastStatement instanceof ReturnStatement) {
statements.remove(lastStatement);
}
// add statements from 'then' to the end of block
for (Statement statement : statements) {
listRewriter.insertLast(rewrite.createMoveTarget(statement), null);
}
// add correction proposal
String label= CorrectionMessages.AdvancedQuickAssistProcessor_convertToIfReturn;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_IF_RETURN, image);
resultingCollections.add(proposal);
return true;
}
private static boolean isVoid(Type type) {
return type instanceof PrimitiveType && ((PrimitiveType) type).getPrimitiveTypeCode() == PrimitiveType.VOID;
}
private static boolean isLastStatementInEnclosingMethodOrLambda(Statement statement) {
ASTNode currentStructure= statement;
ASTNode currentParent= statement.getParent();
while (!(currentParent instanceof MethodDeclaration) && !(currentParent instanceof LambdaExpression)) {
// should not be in a loop
if (currentParent instanceof ForStatement || currentParent instanceof EnhancedForStatement
|| currentParent instanceof WhileStatement || currentParent instanceof DoStatement) {
return false;
}
if (currentParent instanceof Block) {
Block parentBlock= (Block) currentParent;
if (parentBlock.statements().indexOf(currentStructure) != parentBlock.statements().size() - 1) { // not last statement in the block
return false;
}
}
currentStructure= currentParent;
currentParent= currentParent.getParent();
}
return true;
}
private static boolean getIfReturnIntoIfElseAtEndOfVoidMethodProposals(IInvocationContextCore context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
if (!(covering instanceof IfStatement)) {
return false;
}
IfStatement ifStatement= (IfStatement) covering;
if (ifStatement.getElseStatement() != null) {
return false;
}
// 'then' block should have 'return' as last statement
Statement thenStatement= ifStatement.getThenStatement();
if (!(thenStatement instanceof Block)) {
return false;
}
Block thenBlock= (Block) thenStatement;
List<Statement> thenStatements= thenBlock.statements();
if (thenStatements.isEmpty() || !(thenStatements.get(thenStatements.size() - 1) instanceof ReturnStatement)) {
return false;
}
// method should return 'void'
MethodDeclaration coveringMetod= ASTResolving.findParentMethodDeclaration(covering);
if (coveringMetod == null) {
return false;
}
Type returnType= coveringMetod.getReturnType2();
if (!isVoid(returnType)) {
return false;
}
//
List<Statement> statements= coveringMetod.getBody().statements();
int ifIndex= statements.indexOf(ifStatement);
if (ifIndex == -1) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
//
AST ast= covering.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
// remove last 'return' in 'then' block
ListRewrite listRewriter= rewrite.getListRewrite(thenBlock, (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
listRewriter.remove(thenStatements.get(thenStatements.size() - 1), null);
// prepare original nodes
Expression conditionPlaceholder= (Expression) rewrite.createMoveTarget(ifStatement.getExpression());
Statement thenPlaceholder= (Statement) rewrite.createMoveTarget(ifStatement.getThenStatement());
// prepare 'else' block
Block elseBlock= ast.newBlock();
for (int i= ifIndex + 1; i < statements.size(); i++) {
Statement statement= statements.get(i);
elseBlock.statements().add(rewrite.createMoveTarget(statement));
}
// prepare new 'if' statement
IfStatement newIf= ast.newIfStatement();
newIf.setExpression(conditionPlaceholder);
newIf.setThenStatement(thenPlaceholder);
newIf.setElseStatement(elseBlock);
rewrite.replace(ifStatement, newIf, null);
// add correction proposal
String label= CorrectionMessages.AdvancedQuickAssistProcessor_convertToIfElse_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_IF_ELSE, image);
resultingCollections.add(proposal);
return true;
}
private static boolean getInverseIfProposals(IInvocationContextCore context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
if (!(covering instanceof IfStatement)) {
return false;
}
IfStatement ifStatement= (IfStatement) covering;
if (ifStatement.getElseStatement() == null) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
//
AST ast= covering.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
Statement thenStatement= ifStatement.getThenStatement();
Statement elseStatement= ifStatement.getElseStatement();
// prepare original nodes
Expression inversedExpression= getInversedExpression(rewrite, ifStatement.getExpression());
Statement newElseStatement= (Statement) rewrite.createMoveTarget(thenStatement);
Statement newThenStatement= (Statement) rewrite.createMoveTarget(elseStatement);
// set new nodes
rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, inversedExpression, null);
if (elseStatement instanceof IfStatement) {// bug 79507 && bug 74580
Block elseBlock= ast.newBlock();
elseBlock.statements().add(newThenStatement);
newThenStatement= elseBlock;
}
rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, newThenStatement, null);
rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, newElseStatement, null);
// add correction proposal
String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseIf_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_IF_STATEMENT, image);
resultingCollections.add(proposal);
return true;
}
private static boolean getInverseIfContinueIntoIfThenInLoopsProposals(IInvocationContextCore context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
if (!(covering instanceof IfStatement)) {
return false;
}
IfStatement ifStatement= (IfStatement) covering;
if (ifStatement.getElseStatement() != null) {
return false;
}
// check that 'then' is 'continue'
if (!(ifStatement.getThenStatement() instanceof ContinueStatement)) {
return false;
}
// check that 'if' statement is statement in block that is body of loop
Block loopBlock= null;
if (ifStatement.getParent() instanceof Block
&& (ifStatement.getParent().getParent() instanceof ForStatement || ifStatement.getParent().getParent() instanceof WhileStatement)) {
loopBlock= (Block) ifStatement.getParent();
} else {
return false;
}
if (resultingCollections == null) {
return true;
}
//
AST ast= covering.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
// create inverted 'if' statement
Expression inversedExpression= getInversedExpression(rewrite, ifStatement.getExpression());
IfStatement newIf= ast.newIfStatement();
newIf.setExpression(inversedExpression);
// prepare 'then' for new 'if'
Block thenBlock= ast.newBlock();
int ifIndex= loopBlock.statements().indexOf(ifStatement);
for (int i= ifIndex + 1; i < loopBlock.statements().size(); i++) {
Statement statement= (Statement) loopBlock.statements().get(i);
thenBlock.statements().add(rewrite.createMoveTarget(statement));
}
newIf.setThenStatement(thenBlock);
// replace 'if' statement in loop
rewrite.replace(ifStatement, newIf, null);
// add correction proposal
String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseIfContinue_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_IF_CONTINUE, image);
resultingCollections.add(proposal);
return true;
}
private static boolean getInverseIfIntoContinueInLoopsProposals(IInvocationContextCore context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
if (!(covering instanceof IfStatement)) {
return false;
}
IfStatement ifStatement= (IfStatement) covering;
if (ifStatement.getElseStatement() != null) {
return false;
}
// prepare outer control structure and block that contains 'if' statement
ASTNode ifParent= ifStatement.getParent();
Block ifParentBlock= null;
ASTNode ifParentStructure= ifParent;
if (ifParentStructure instanceof Block) {
ifParentBlock= (Block) ifParent;
ifParentStructure= ifParentStructure.getParent();
}
// check that control structure is loop and 'if' statement if last statement
if (!(ifParentStructure instanceof ForStatement) && !(ifParentStructure instanceof WhileStatement)) {
return false;
}
if (ifParentBlock != null && ifParentBlock.statements().indexOf(ifStatement) != ifParentBlock.statements().size() - 1) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
//
AST ast= covering.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
// create inverted 'if' statement
Expression inversedExpression= getInversedExpression(rewrite, ifStatement.getExpression());
IfStatement newIf= ast.newIfStatement();
newIf.setExpression(inversedExpression);
newIf.setThenStatement(ast.newContinueStatement());
//
if (ifParentBlock == null) {
// if there is no block, create it
ifParentBlock= ast.newBlock();
ifParentBlock.statements().add(newIf);
for (Statement statement : getUnwrappedStatements(ifStatement.getThenStatement())) {
ifParentBlock.statements().add(rewrite.createMoveTarget(statement));
}
// replace 'if' statement as body with new block
if (ifParentStructure instanceof ForStatement) {
rewrite.set(ifParentStructure, ForStatement.BODY_PROPERTY, ifParentBlock, null);
} else if (ifParentStructure instanceof WhileStatement) {
rewrite.set(ifParentStructure, WhileStatement.BODY_PROPERTY, ifParentBlock, null);
}
} else {
// if there was block, replace
ListRewrite listRewriter= rewrite.getListRewrite(ifParentBlock, (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
listRewriter.replace(ifStatement, newIf, null);
// add statements from 'then' to the end of block
for (Statement statement : getUnwrappedStatements(ifStatement.getThenStatement())) {
listRewriter.insertLast(rewrite.createMoveTarget(statement), null);
}
}
// add correction proposal
String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseIfToContinue_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERT_IF_TO_CONTINUE, image);
resultingCollections.add(proposal);
return true;
}
private static ArrayList<Statement> getUnwrappedStatements(Statement body) {
ArrayList<Statement> statements= new ArrayList<>();
if (body instanceof Block) {
for (Iterator<Statement> iter= ((Block) body).statements().iterator(); iter.hasNext();) {
Statement statement= iter.next();
statements.add(statement);
}
} else {
statements.add(body);
}
return statements;
}
private static boolean getInverseConditionProposals(IInvocationContextCore context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
if (coveredNodes.isEmpty()) {
return false;
}
//
final AST ast= covering.getAST();
final ASTRewrite rewrite= ASTRewrite.create(ast);
// check sub-expressions in fully covered nodes
boolean hasChanges= false;
for (ASTNode covered : coveredNodes) {
Expression coveredExpression= getBooleanExpression(covered);
if (coveredExpression != null) {
Expression inversedExpression= getInversedExpression(rewrite, coveredExpression);
rewrite.replace(coveredExpression, inversedExpression, null);
hasChanges= true;
}
}
//
if (!hasChanges) {
return false;
}
if (resultingCollections == null) {
return true;
}
// add correction proposal
String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseConditions_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_CONDITIONS, image);
resultingCollections.add(proposal);
return true;
}
private static Expression getInversedExpression(ASTRewrite rewrite, Expression expression) {
return getInversedExpression(rewrite, expression, null);
}
private interface SimpleNameRenameProvider {
SimpleName getRenamed(SimpleName name);
}
private static Expression getRenamedNameCopy(SimpleNameRenameProvider provider, ASTRewrite rewrite, Expression expression) {
if (provider != null) {
if (expression instanceof SimpleName) {
SimpleName name= (SimpleName) expression;
SimpleName newName= provider.getRenamed(name);
if (newName != null) {
return newName;
}
}
}
return (Expression) rewrite.createCopyTarget(expression);
}
private static Expression getInversedExpression(ASTRewrite rewrite, Expression expression, SimpleNameRenameProvider provider) {
AST ast= rewrite.getAST();
//
if (expression instanceof BooleanLiteral) {
return ast.newBooleanLiteral(!((BooleanLiteral) expression).booleanValue());
}
if (expression instanceof InfixExpression) {
InfixExpression infixExpression= (InfixExpression) expression;
InfixExpression.Operator operator= infixExpression.getOperator();
if (operator == InfixExpression.Operator.LESS) {
return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.GREATER_EQUALS, provider);
}
if (operator == InfixExpression.Operator.GREATER) {
return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.LESS_EQUALS, provider);
}
if (operator == InfixExpression.Operator.LESS_EQUALS) {
return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.GREATER, provider);
}
if (operator == InfixExpression.Operator.GREATER_EQUALS) {
return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.LESS, provider);
}
if (operator == InfixExpression.Operator.EQUALS) {
return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.NOT_EQUALS, provider);
}
if (operator == InfixExpression.Operator.NOT_EQUALS) {
return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.EQUALS, provider);
}
if (operator == InfixExpression.Operator.CONDITIONAL_AND) {
return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.CONDITIONAL_OR, provider);
}
if (operator == InfixExpression.Operator.CONDITIONAL_OR) {
return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.CONDITIONAL_AND, provider);
}
if (operator == InfixExpression.Operator.AND) {
return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.OR, provider);
}
if (operator == InfixExpression.Operator.OR) {
return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.AND, provider);
}
if (operator == InfixExpression.Operator.XOR) {
return getInversedNotExpression(rewrite, expression, ast);
}
}
if (expression instanceof PrefixExpression) {
PrefixExpression prefixExpression= (PrefixExpression) expression;
if (prefixExpression.getOperator() == PrefixExpression.Operator.NOT) {
Expression operand= prefixExpression.getOperand();
if ((operand instanceof ParenthesizedExpression)
&& NecessaryParenthesesChecker.canRemoveParentheses(operand, expression.getParent(), expression.getLocationInParent())) {
operand= ((ParenthesizedExpression)operand).getExpression();
}
Expression renamedNameCopy= getRenamedNameCopy(provider, rewrite, operand);
if (renamedNameCopy instanceof InfixExpression) {
InfixExpression infixExpression= (InfixExpression) renamedNameCopy;
infixExpression.setOperator(((InfixExpression) operand).getOperator());
}
return renamedNameCopy;
}
}
if (expression instanceof InstanceofExpression) {
return getInversedNotExpression(rewrite, expression, ast);
}
if (expression instanceof ParenthesizedExpression) {
ParenthesizedExpression parenthesizedExpression= (ParenthesizedExpression) expression;
Expression innerExpression= ASTNodes.getUnparenthesedExpression(parenthesizedExpression.getExpression());
if (innerExpression instanceof InstanceofExpression) {
return getInversedExpression(rewrite, innerExpression, provider);
}
parenthesizedExpression= getParenthesizedExpression(ast, getInversedExpression(rewrite, innerExpression, provider));
return parenthesizedExpression;
}
if (expression instanceof ConditionalExpression) {
ConditionalExpression conditionalExpression= (ConditionalExpression)expression;
ConditionalExpression newExpression= ast.newConditionalExpression();
newExpression.setExpression((Expression)rewrite.createCopyTarget(conditionalExpression.getExpression()));
newExpression.setThenExpression(getInversedExpression(rewrite, conditionalExpression.getThenExpression()));
newExpression.setElseExpression(getInversedExpression(rewrite, conditionalExpression.getElseExpression()));
return newExpression;
}
PrefixExpression prefixExpression= ast.newPrefixExpression();
prefixExpression.setOperator(PrefixExpression.Operator.NOT);
Expression renamedNameCopy= getRenamedNameCopy(provider, rewrite, expression);
if (NecessaryParenthesesChecker.needsParentheses(renamedNameCopy, prefixExpression, PrefixExpression.OPERAND_PROPERTY)) {
renamedNameCopy= getParenthesizedExpression(ast, renamedNameCopy);
}
prefixExpression.setOperand(renamedNameCopy);
return prefixExpression;
}
private static Expression getInversedNotExpression(ASTRewrite rewrite, Expression expression, AST ast) {
PrefixExpression prefixExpression= ast.newPrefixExpression();
prefixExpression.setOperator(PrefixExpression.Operator.NOT);
ParenthesizedExpression parenthesizedExpression= getParenthesizedExpression(ast, (Expression)rewrite.createCopyTarget(expression));
prefixExpression.setOperand(parenthesizedExpression);
return prefixExpression;
}
private static boolean isBoolean(Expression expression) {
ITypeBinding typeBinding= expression.resolveTypeBinding();
AST ast= expression.getAST();
return typeBinding == ast.resolveWellKnownType("boolean") //$NON-NLS-1$
|| typeBinding == ast.resolveWellKnownType("java.lang.Boolean"); //$NON-NLS-1$
}
private static Expression getInversedInfixExpression(ASTRewrite rewrite, InfixExpression expression, InfixExpression.Operator newOperator, SimpleNameRenameProvider provider) {
InfixExpression newExpression= rewrite.getAST().newInfixExpression();
newExpression.setOperator(newOperator);
newExpression.setLeftOperand(getRenamedNameCopy(provider, rewrite, expression.getLeftOperand()));
newExpression.setRightOperand(getRenamedNameCopy(provider, rewrite, expression.getRightOperand()));
return newExpression;
}
private static Expression parenthesizeIfRequired(Expression operand, int newOperatorPrecedence) {
if (newOperatorPrecedence > OperatorPrecedence.getExpressionPrecedence(operand)) {
return getParenthesizedExpression(operand.getAST(), operand);
}
return operand;
}
private static Expression getInversedAndOrExpression(ASTRewrite rewrite, InfixExpression infixExpression, Operator newOperator, SimpleNameRenameProvider provider) {
InfixExpression newExpression= rewrite.getAST().newInfixExpression();
newExpression.setOperator(newOperator);
int newOperatorPrecedence= OperatorPrecedence.getOperatorPrecedence(newOperator);
//
Expression leftOperand= getInversedExpression(rewrite, infixExpression.getLeftOperand(), provider);
newExpression.setLeftOperand(parenthesizeIfRequired(leftOperand, newOperatorPrecedence));
Expression rightOperand= getInversedExpression(rewrite, infixExpression.getRightOperand(), provider);
newExpression.setRightOperand(parenthesizeIfRequired(rightOperand, newOperatorPrecedence));
List<Expression> extraOperands= infixExpression.extendedOperands();
List<Expression> newExtraOperands= newExpression.extendedOperands();
for (int i= 0; i < extraOperands.size(); i++) {
Expression extraOperand= getInversedExpression(rewrite, extraOperands.get(i), provider);
newExtraOperands.add(parenthesizeIfRequired(extraOperand, newOperatorPrecedence));
}
return newExpression;
}
private static boolean getRemoveExtraParenthesesProposals(IInvocationContextCore context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
ArrayList<ASTNode> nodes;
if (context.getSelectionLength() == 0 && covering instanceof ParenthesizedExpression) {
nodes= new ArrayList<>();
nodes.add(covering);
} else {
nodes= coveredNodes;
}
if (nodes.isEmpty())
return false;
IProposableFix fix= ExpressionsFix.createRemoveUnnecessaryParenthesisFix(context.getASTRoot(), nodes.toArray(new ASTNode[nodes.size()]));
if (fix == null)
return false;
if (resultingCollections == null)
return true;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
Map<String, String> options= new Hashtable<>();
options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpOptions.TRUE);
options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER, CleanUpOptions.TRUE);
FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new ExpressionsCleanUp(options), IProposalRelevance.REMOVE_EXTRA_PARENTHESES, image, context);
resultingCollections.add(proposal);
return true;
}
private static boolean getAddParanoidalParenthesesProposals(IInvocationContextCore context, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
IProposableFix fix= ExpressionsFix.createAddParanoidalParenthesisFix(context.getASTRoot(), coveredNodes.toArray(new ASTNode[coveredNodes.size()]));
if (fix == null)
return false;
if (resultingCollections == null)
return true;
// add correction proposal
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
Map<String, String> options= new Hashtable<>();
options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpOptions.TRUE);
options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS, CleanUpOptions.TRUE);
FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new ExpressionsCleanUp(options), IProposalRelevance.ADD_PARANOIDAL_PARENTHESES, image, context);
resultingCollections.add(proposal);
return true;
}
private static boolean getAddParenthesesForExpressionProposals(IInvocationContextCore context, ASTNode coveringNode, Collection<ICommandAccess> resultingCollections) {
ASTNode node;
if (context.getSelectionLength() == 0) {
node= coveringNode;
while (node != null && !(node instanceof CastExpression) && !(node instanceof InfixExpression) && !(node instanceof InstanceofExpression) && !(node instanceof ConditionalExpression)) {
node= node.getParent();
}
} else {
node= context.getCoveredNode();
}
String label= null;
if (node instanceof CastExpression) {
label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
} else if (node instanceof InstanceofExpression) {
label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_instanceof_description;
} else if (node instanceof InfixExpression) {
InfixExpression infixExpression= (InfixExpression)node;
label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_description, infixExpression.getOperator().toString());
} else if (node instanceof ConditionalExpression) {
label= CorrectionMessages.AdvancedQuickAssistProcessor_putConditionalExpressionInParentheses;
} else {
return false;
}
if (node.getParent() instanceof ParenthesizedExpression)
return false;
if (resultingCollections == null)
return true;
AST ast= node.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
ParenthesizedExpression parenthesizedExpression= ast.newParenthesizedExpression();
parenthesizedExpression.setExpression((Expression)rewrite.createCopyTarget(node));
rewrite.replace(node, parenthesizedExpression, null);
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_PARENTHESES_FOR_EXPRESSION, image);
resultingCollections.add(proposal);
return true;
}
static ArrayList<ASTNode> getFullyCoveredNodes(IInvocationContextCore context, ASTNode coveringNode) {
final ArrayList<ASTNode> coveredNodes= new ArrayList<>();
final int selectionBegin= context.getSelectionOffset();
final int selectionEnd= selectionBegin + context.getSelectionLength();
coveringNode.accept(new GenericVisitor() {
@Override
protected boolean visitNode(ASTNode node) {
int nodeStart= node.getStartPosition();
int nodeEnd= nodeStart + node.getLength();
// if node does not intersects with selection, don't visit children
if (nodeEnd < selectionBegin || selectionEnd < nodeStart) {
return false;
}
// if node is fully covered, we don't need to visit children
if (isCovered(node)) {
ASTNode parent= node.getParent();
if (parent == null || !isCovered(parent)) {
coveredNodes.add(node);
return false;
}
}
// if node only partly intersects with selection, we try to find fully covered children
return true;
}
private boolean isCovered(ASTNode node) {
int begin= node.getStartPosition();
int end= begin + node.getLength();
return begin >= selectionBegin && end <= selectionEnd;
}
});
return coveredNodes;
}
private static boolean getJoinAndIfStatementsProposals(IInvocationContextCore context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
//
if (!(node instanceof IfStatement)) {
return false;
}
IfStatement ifStatement= (IfStatement) node;
if (ifStatement.getElseStatement() != null) {
return false;
}
// case when current IfStatement is sole child of another IfStatement
{
IfStatement outerIf= null;
if (ifStatement.getParent() instanceof IfStatement) {
outerIf= (IfStatement) ifStatement.getParent();
} else if (ifStatement.getParent() instanceof Block) {
Block block= (Block) ifStatement.getParent();
if (block.getParent() instanceof IfStatement && block.statements().size() == 1) {
outerIf= (IfStatement) block.getParent();
}
}
if (outerIf != null && outerIf.getElseStatement() == null) {
if (resultingCollections == null) {
return true;
}
//
AST ast= node.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
// create compound condition
InfixExpression condition= ast.newInfixExpression();
condition.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
// prepare condition parts, add parentheses if needed
Expression outerCondition= getParenthesizedExpressionIfNeeded(ast, rewrite, outerIf.getExpression(), condition, InfixExpression.LEFT_OPERAND_PROPERTY);
Expression innerCondition= getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.RIGHT_OPERAND_PROPERTY);
condition.setLeftOperand(outerCondition);
condition.setRightOperand(innerCondition);
// create new IfStatement
IfStatement newIf= ast.newIfStatement();
newIf.setExpression(condition);
Statement bodyPlaceholder= (Statement) rewrite.createCopyTarget(ifStatement.getThenStatement());
newIf.setThenStatement(bodyPlaceholder);
rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
rewrite.replace(outerIf, newIf, null);
// add correction proposal
String label= CorrectionMessages.AdvancedQuickAssistProcessor_joinWithOuter_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_IF_WITH_OUTER_IF, image);
resultingCollections.add(proposal);
}
}
// case when current IfStatement has another IfStatement as sole child
{
IfStatement innerIf= null;
if (ifStatement.getThenStatement() instanceof IfStatement) {
innerIf= (IfStatement) ifStatement.getThenStatement();
} else if (ifStatement.getThenStatement() instanceof Block) {
Block block= (Block) ifStatement.getThenStatement();
if (block.statements().size() == 1 && block.statements().get(0) instanceof IfStatement) {
innerIf= (IfStatement) block.statements().get(0);
}
}
if (innerIf != null && innerIf.getElseStatement() == null) {
if (resultingCollections == null) {
return true;
}
//
AST ast= node.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
// create compound condition
InfixExpression condition= ast.newInfixExpression();
condition.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
// prepare condition parts, add parentheses if needed
Expression outerCondition= getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.LEFT_OPERAND_PROPERTY);
Expression innerCondition= getParenthesizedExpressionIfNeeded(ast, rewrite, innerIf.getExpression(), condition, InfixExpression.RIGHT_OPERAND_PROPERTY);
condition.setLeftOperand(outerCondition);
condition.setRightOperand(innerCondition);
// create new IfStatement
IfStatement newIf= ast.newIfStatement();
newIf.setExpression(condition);
Statement bodyPlaceholder= (Statement) rewrite.createCopyTarget(innerIf.getThenStatement());
newIf.setThenStatement(bodyPlaceholder);
rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
rewrite.replace(ifStatement, newIf, null);
// add correction proposal
String label= CorrectionMessages.AdvancedQuickAssistProcessor_joinWithInner_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_IF_WITH_INNER_IF, image);
resultingCollections.add(proposal);
}
}
return true;
}
private static Expression getParenthesizedExpressionIfNeeded(AST ast, ASTRewrite rewrite, Expression expression, ASTNode parent, StructuralPropertyDescriptor locationInParent) {
boolean addParentheses= NecessaryParenthesesChecker.needsParentheses(expression, parent, locationInParent);
expression= (Expression)rewrite.createCopyTarget(expression);
if (addParentheses) {
return getParenthesizedExpression(ast, expression);
}
return expression;
}
private static ParenthesizedExpression getParenthesizedExpression(AST ast, Expression expression) {