Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: cfe292e8e3dd36d4e75be4ea46e2a04279954ac1 (plain) (blame)
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
/*******************************************************************************
 * Copyright (c) 2019 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
 *     Red Hat Inc. - copied and modified for use in jdt.core.manipulation
 *******************************************************************************/
package org.eclipse.jdt.internal.corext.fix;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import org.eclipse.core.runtime.CoreException;

import org.eclipse.text.edits.TextEditGroup;

import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.Block;
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.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.FieldDeclaration;
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.ImportDeclaration;
import org.eclipse.jdt.core.dom.Javadoc;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.NodeFinder;
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.SimpleName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.TagElement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclarationStatement;
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.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.core.manipulation.CleanUpOptionsCore;
import org.eclipse.jdt.core.manipulation.ICleanUpFixCore;

import org.eclipse.jdt.internal.core.manipulation.dom.NecessaryParenthesesChecker;
import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder;
import org.eclipse.jdt.internal.corext.dom.StatementRewrite;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.util.Messages;

import org.eclipse.jdt.internal.ui.fix.UnusedCodeCleanUpCore;
import org.eclipse.jdt.internal.ui.text.correction.IProblemLocationCore;
import org.eclipse.jdt.internal.ui.text.correction.JavadocTagsSubProcessorCore;
import org.eclipse.jdt.internal.ui.text.correction.ProblemLocationCore;

/**
 * Fix which removes unused code.
 */
public class UnusedCodeFixCore extends CompilationUnitRewriteOperationsFixCore {

	public static class SideEffectFinder extends ASTVisitor {

		private final ArrayList<Expression> fSideEffectNodes;

		public SideEffectFinder(ArrayList<Expression> res) {
			fSideEffectNodes= res;
		}

		@Override
		public boolean visit(Assignment node) {
			fSideEffectNodes.add(node);
			return false;
		}

		@Override
		public boolean visit(PostfixExpression node) {
			fSideEffectNodes.add(node);
			return false;
		}

		@Override
		public boolean visit(PrefixExpression node) {
			Object operator= node.getOperator();
			if (operator == PrefixExpression.Operator.INCREMENT || operator == PrefixExpression.Operator.DECREMENT) {
				fSideEffectNodes.add(node);
				return false;
			}
			return true;
		}

		@Override
		public boolean visit(MethodInvocation node) {
			fSideEffectNodes.add(node);
			return false;
		}

		@Override
		public boolean visit(ClassInstanceCreation node) {
			fSideEffectNodes.add(node);
			return false;
		}

		@Override
		public boolean visit(SuperMethodInvocation node) {
			fSideEffectNodes.add(node);
			return false;
		}
	}

	public static class RemoveImportOperation extends CompilationUnitRewriteOperation {

		private final ImportDeclaration fImportDeclaration;

		public RemoveImportOperation(ImportDeclaration importDeclaration) {
			fImportDeclaration= importDeclaration;
		}

		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore model) throws CoreException {
			ImportDeclaration node= fImportDeclaration;
			TextEditGroup group= createTextEditGroup(FixMessages.UnusedCodeFix_RemoveImport_description, cuRewrite);
			cuRewrite.getASTRewrite().remove(node, group);
		}

	}

	/**
	 * Removes the unused type parameter.
	 *
	 */
	public static class RemoveUnusedTypeParameterOperation extends CompilationUnitRewriteOperation {
		private final SimpleName fUnusedName;

		public RemoveUnusedTypeParameterOperation(SimpleName unusedName) {
			fUnusedName= unusedName;
		}

		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore linkedModel) throws CoreException {
			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			IBinding binding= fUnusedName.resolveBinding();
			CompilationUnit root= (CompilationUnit) fUnusedName.getRoot();
			String displayString= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
			TextEditGroup group= createTextEditGroup(displayString, cuRewrite);

			if (binding.getKind() == IBinding.TYPE) {
				ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
				ASTNode declaration= root.findDeclaringNode(decl);
				if (declaration.getParent() instanceof TypeDeclarationStatement) {
					declaration= declaration.getParent();
				}
				rewrite.remove(declaration, group);
			}
		}
	}

	public static class RemoveUnusedMemberOperation extends CompilationUnitRewriteOperation {

		private final SimpleName[] fUnusedNames;
		private boolean fForceRemove;
		private int fRemovedAssignmentsCount;
		private int fAlteredAssignmentsCount;

		public RemoveUnusedMemberOperation(SimpleName[] unusedNames, boolean removeAllAsignements) {
			fUnusedNames= unusedNames;
			fForceRemove= removeAllAsignements;
		}

		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore model) throws CoreException {
			for (SimpleName unusedName : fUnusedNames) {
				removeUnusedName(cuRewrite, unusedName);
			}
		}

		private void removeUnusedName(CompilationUnitRewrite cuRewrite, SimpleName simpleName) {
			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			CompilationUnit completeRoot= cuRewrite.getRoot();

			IBinding binding= simpleName.resolveBinding();
			CompilationUnit root= (CompilationUnit) simpleName.getRoot();
			String displayString= getDisplayString(binding);
			TextEditGroup group= createTextEditGroup(displayString, cuRewrite);
			if (binding.getKind() == IBinding.METHOD) {
				IMethodBinding decl= ((IMethodBinding) binding).getMethodDeclaration();
				ASTNode declaration= root.findDeclaringNode(decl);
				rewrite.remove(declaration, group);
			} else if (binding.getKind() == IBinding.TYPE) {
				ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
				ASTNode declaration= root.findDeclaringNode(decl);
				if (declaration.getParent() instanceof TypeDeclarationStatement) {
					declaration= declaration.getParent();
				}
				rewrite.remove(declaration, group);
			} else if (binding.getKind() == IBinding.VARIABLE) {
				SimpleName nameNode= (SimpleName) NodeFinder.perform(completeRoot, simpleName.getStartPosition(), simpleName.getLength());
				for (SimpleName reference : LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding())) {
					removeVariableReferences(rewrite, reference, group);
				}

				IVariableBinding bindingDecl= ((IVariableBinding) nameNode.resolveBinding()).getVariableDeclaration();
				ASTNode declaringNode= completeRoot.findDeclaringNode(bindingDecl);
				if (declaringNode instanceof SingleVariableDeclaration) {
					removeParamTag(rewrite, (SingleVariableDeclaration) declaringNode, group);
				}
			} else {
				// unexpected
			}
		}

		private String getDisplayString(IBinding binding) {
			switch (binding.getKind()) {
				case IBinding.TYPE:
					return FixMessages.UnusedCodeFix_RemoveUnusedType_description;
				case IBinding.METHOD:
					if (((IMethodBinding) binding).isConstructor()) {
						return FixMessages.UnusedCodeFix_RemoveUnusedConstructor_description;
					} else {
						return FixMessages.UnusedCodeFix_RemoveUnusedPrivateMethod_description;
					}
				case IBinding.VARIABLE:
					if (((IVariableBinding) binding).isField()) {
						return FixMessages.UnusedCodeFix_RemoveUnusedField_description;
					} else {
						return FixMessages.UnusedCodeFix_RemoveUnusedVariabl_description;
					}
				default:
					return ""; //$NON-NLS-1$
			}
		}

		private void removeParamTag(ASTRewrite rewrite, SingleVariableDeclaration varDecl, TextEditGroup group) {
			if (varDecl.getParent() instanceof MethodDeclaration) {
				Javadoc javadoc= ((MethodDeclaration) varDecl.getParent()).getJavadoc();
				if (javadoc != null) {
					TagElement tagElement= JavadocTagsSubProcessorCore.findParamTag(javadoc, varDecl.getName().getIdentifier());
					if (tagElement != null) {
						rewrite.remove(tagElement, group);
					}
				}
			}
		}

		/**
		 * Remove the field or variable declaration including the initializer.
		 * @param rewrite the AST rewriter to use
		 * @param reference a reference to the variable to remove
		 * @param group the text edit group to use
		 */
		private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference, TextEditGroup group) {
			ASTNode parent= reference.getParent();
			while (parent instanceof QualifiedName) {
				parent= parent.getParent();
			}
			if (parent instanceof FieldAccess) {
				parent= parent.getParent();
			}

			int nameParentType= parent.getNodeType();
			if (nameParentType == ASTNode.ASSIGNMENT) {
				Assignment assignment= (Assignment) parent;
				Expression rightHand= assignment.getRightHandSide();

				ASTNode assignParent= assignment.getParent();
				if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
					removeVariableWithInitializer(rewrite, rightHand, assignParent, group);
				}	else {
					rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), group);
				}
			} else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
				rewrite.remove(parent, group);
			} else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
				VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
				ASTNode varDecl= frag.getParent();
				List<VariableDeclarationFragment> fragments;
				if (varDecl instanceof VariableDeclarationExpression) {
					fragments= ((VariableDeclarationExpression) varDecl).fragments();
				} else if (varDecl instanceof FieldDeclaration) {
					fragments= ((FieldDeclaration) varDecl).fragments();
				} else {
					fragments= ((VariableDeclarationStatement) varDecl).fragments();
				}
				Expression initializer= frag.getInitializer();
				ArrayList<Expression> sideEffects= new ArrayList<>();
				if (initializer != null) {
					initializer.accept(new SideEffectFinder(sideEffects));
				}

				/*
				 * Special case for when the variable initializer is a conditional expression.
				 * Certain actions must be taken depending on where in the conditional the side effect expressions are located.
				 */
				if (initializer instanceof ConditionalExpression && varDecl instanceof VariableDeclarationStatement) {
					AST ast= rewrite.getAST();
					ConditionalExpression ce= (ConditionalExpression) initializer;

					// check if side effects and both expressions are to be removed then we remove whole statement
					if (fForceRemove || (!checkSideEffects(sideEffects) &&
							!checkCondtionalExpression(ce.getThenExpression()) &&
							!checkCondtionalExpression(ce.getElseExpression()))) {
						rewrite.remove(varDecl, group);
						return;
					}

					IfStatement ifStatement= ast.newIfStatement();
					ifStatement.setExpression((Expression) rewrite.createCopyTarget(ASTNodes.getUnparenthesedExpression(ce.getExpression())));

					Block thenBlock= ast.newBlock();
					// check if 'then' block contains code to keep
					if (checkCondtionalExpression(ce.getThenExpression())) {
						ASTNode thenExpression= rewrite.createCopyTarget(ASTNodes.getUnparenthesedExpression(ce.getThenExpression()));
						thenBlock.statements().add(ast.newExpressionStatement((Expression) thenExpression));
					}
					ifStatement.setThenStatement(thenBlock);

					// check if 'else' block contains code to keep
					if (checkCondtionalExpression(ce.getElseExpression())) {
						Block elseBlock= ast.newBlock();
						ASTNode elseExpression= rewrite.createCopyTarget(ASTNodes.getUnparenthesedExpression(ce.getElseExpression()));
						elseBlock.statements().add(ast.newExpressionStatement((Expression) elseExpression));
						ifStatement.setElseStatement(elseBlock);
					}

					rewrite.replace(varDecl, ifStatement, group);
					return;
				}

				boolean sideEffectInitializer= sideEffects.size() > 0;
				if (fragments.size() == fUnusedNames.length) {
					if (fForceRemove) {
						rewrite.remove(varDecl, group);
						return;
					}
					if (parent.getParent() instanceof FieldDeclaration) {
						rewrite.remove(varDecl, group);
						return;
					}
					if (sideEffectInitializer) {
						Statement[] wrapped= new Statement[sideEffects.size()];
						for (int i= 0; i < wrapped.length; i++) {
							Expression sideEffect= sideEffects.get(i);
							Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect);
							wrapped[i]= rewrite.getAST().newExpressionStatement(movedInit);
						}
						StatementRewrite statementRewrite= new StatementRewrite(rewrite, new ASTNode[] { varDecl });
						statementRewrite.replace(wrapped, group);
					} else {
						rewrite.remove(varDecl, group);
					}
				} else {
					if (fForceRemove) {
						rewrite.remove(frag, group);
						return;
					}
					//multiple declarations in one line
					ASTNode declaration = parent.getParent();
					if (declaration instanceof FieldDeclaration) {
						rewrite.remove(frag, group);
						return;
					}
					if (declaration instanceof VariableDeclarationStatement) {
						splitUpDeclarations(rewrite, group, frag, (VariableDeclarationStatement) declaration, sideEffects);
						rewrite.remove(frag, group);
						return;
					}
					if (declaration instanceof VariableDeclarationExpression) {
						//keep constructors and method invocations
						if (!sideEffectInitializer){
							rewrite.remove(frag, group);
						}
					}
				}
			} else if (nameParentType == ASTNode.POSTFIX_EXPRESSION || nameParentType == ASTNode.PREFIX_EXPRESSION) {
				Expression expression= (Expression)parent;
				ASTNode expressionParent= expression.getParent();
				if (expressionParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
					removeStatement(rewrite, expressionParent, group);
				} else {
					rewrite.remove(expression, group);
				}
			}
		}

		/*
		 * Return TRUE if the expression node type is a method, pre/posfix or assignment
		 */
		private static boolean checkCondtionalExpression(Expression expression) {
			int nodeType= ASTNodes.getUnparenthesedExpression(expression).getNodeType();
			if (nodeType == ASTNode.METHOD_INVOCATION ||
					nodeType == ASTNode.POSTFIX_EXPRESSION ||
					nodeType == ASTNode.PREFIX_EXPRESSION ||
					nodeType == ASTNode.ASSIGNMENT) {
				return true;
			}
			return false;
		}

		/*
		 * Return TRUE if any of the sideEffects expression node type is a method, pre/posfix or assignment
		 */
		private static boolean checkSideEffects(List<Expression> sideEffects) {
			if (sideEffects.isEmpty()) {
				return false;
			}
			for (Expression expression : sideEffects) {
				if (checkCondtionalExpression(expression)) {
					return true;
				}
			}
			return false;
		}

		private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, VariableDeclarationStatement originalStatement, List<Expression> sideEffects) {
			if (sideEffects.size() > 0) {
				ListRewrite statementRewrite= rewrite.getListRewrite(originalStatement.getParent(), (ChildListPropertyDescriptor) originalStatement.getLocationInParent());

				Statement previousStatement= originalStatement;
				for (Expression sideEffect : sideEffects) {
					Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect);
					ExpressionStatement wrapped= rewrite.getAST().newExpressionStatement(movedInit);
					statementRewrite.insertAfter(wrapped, previousStatement, group);
					previousStatement= wrapped;
				}

				VariableDeclarationStatement newDeclaration= null;
				List<VariableDeclarationFragment> fragments= originalStatement.fragments();
				int fragIndex= fragments.indexOf(frag);
				ListIterator<VariableDeclarationFragment> fragmentIterator= fragments.listIterator(fragIndex+1);
				while (fragmentIterator.hasNext()) {
					VariableDeclarationFragment currentFragment= fragmentIterator.next();
					VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment);
					if (newDeclaration == null) {
						newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment);
						Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType());
						newDeclaration.setType(copiedType);
					} else {
						newDeclaration.fragments().add(movedFragment);
					}
				}
				if (newDeclaration != null){
					statementRewrite.insertAfter(newDeclaration, previousStatement, group);
					if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){
						rewrite.remove(originalStatement, group);
					}
				}
			}
		}

		private void removeVariableWithInitializer(ASTRewrite rewrite, ASTNode initializerNode, ASTNode statementNode, TextEditGroup group) {
			boolean performRemove= fForceRemove;
			if (!performRemove) {
				ArrayList<Expression> sideEffectNodes= new ArrayList<>();
				initializerNode.accept(new SideEffectFinder(sideEffectNodes));
				performRemove= sideEffectNodes.isEmpty();
			}
			if (performRemove) {
				removeStatement(rewrite, statementNode, group);
				fRemovedAssignmentsCount++;
			} else {
				ASTNode initNode = rewrite.createMoveTarget(initializerNode);
				ExpressionStatement statement = rewrite.getAST().newExpressionStatement((Expression) initNode);
				rewrite.replace(statementNode, statement, null);
				fAlteredAssignmentsCount++;
			}
		}

		private void removeStatement(ASTRewrite rewrite, ASTNode statementNode, TextEditGroup group) {
			if (ASTNodes.isControlStatementBody(statementNode.getLocationInParent())) {
				rewrite.replace(statementNode, rewrite.getAST().newBlock(), group);
			} else {
				rewrite.remove(statementNode, group);
			}
		}

		@Override
		public String getAdditionalInfo() {
			StringBuilder sb=new StringBuilder();
			if (fRemovedAssignmentsCount == 1) {
				sb.append(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_RemovedAssignments_preview_singular);
			} else if (fRemovedAssignmentsCount > 1) {
				sb.append(Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_RemovedAssignments_preview_plural, String.valueOf(fRemovedAssignmentsCount)));
			}
			if (fAlteredAssignmentsCount == 1) {
				sb.append(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_AlteredAssignments_preview_singular);
			} else if (fAlteredAssignmentsCount > 1) {
				sb.append(Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_AlteredAssignments_preview_plural, String.valueOf(fAlteredAssignmentsCount)));
			}
			if (sb.length()>0) {
				return sb.toString();
			} else
				return null;
		}
	}

	public static class RemoveCastOperation extends CompilationUnitRewriteOperation {

		private final CastExpression fCast;

		public RemoveCastOperation(CastExpression cast) {
			fCast= cast;
		}

		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore model) throws CoreException {

			TextEditGroup group= createTextEditGroup(FixMessages.UnusedCodeFix_RemoveCast_description, cuRewrite);

			ASTRewrite rewrite= cuRewrite.getASTRewrite();

			CastExpression cast= fCast;
			Expression expression= cast.getExpression();
			if (expression instanceof ParenthesizedExpression) {
				Expression childExpression= ((ParenthesizedExpression) expression).getExpression();
				if (NecessaryParenthesesChecker.needsParentheses(childExpression, cast, CastExpression.EXPRESSION_PROPERTY)) {
					expression= childExpression;
				}
			}

			replaceCast(cast, expression, rewrite, group);
		}
	}

	public static class RemoveAllCastOperation extends CompilationUnitRewriteOperation {

		private final LinkedHashSet<CastExpression> fUnnecessaryCasts;

		public RemoveAllCastOperation(LinkedHashSet<CastExpression> unnecessaryCasts) {
			fUnnecessaryCasts= unnecessaryCasts;
		}

		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore model) throws CoreException {
			ASTRewrite rewrite= cuRewrite.getASTRewrite();

			TextEditGroup group= createTextEditGroup(FixMessages.UnusedCodeFix_RemoveCast_description, cuRewrite);

			while (fUnnecessaryCasts.size() > 0) {
				CastExpression castExpression= fUnnecessaryCasts.iterator().next();
				fUnnecessaryCasts.remove(castExpression);

				/*
				 * ASTRewrite doesn't allow replacing (deleting) of moved nodes. To solve problems
				 * with nested casts, we need to replace all casts at once.
				 *
				 * The loop proceeds downwards to find the innermost expression that stays in the result (downChild)
				 * and it also skips necessary parentheses.
				 */
				CastExpression down= castExpression;
				Expression downChild= down.getExpression();
				while (true) {
					if (fUnnecessaryCasts.contains(downChild)) {
						down= (CastExpression) downChild;
						fUnnecessaryCasts.remove(down);
						downChild= down.getExpression();
					} else if (downChild instanceof ParenthesizedExpression) {
						Expression downChildExpression= ((ParenthesizedExpression) downChild).getExpression();
						// is it justified that downChild is a ParenthesizedExpression?
						if (NecessaryParenthesesChecker.needsParentheses(downChildExpression, down, CastExpression.EXPRESSION_PROPERTY)) {
							// yes => continue walking down
							downChild= downChildExpression;
						} else {
							// no => stop walking
							break;
						}
					} else {
						break;
					}
				}

				// downChild is the innermost CastExpression's expression, stripped of a necessary surrounding ParenthesizedExpression
				// Move either downChild (if it doesn't need parentheses), or a parenthesized version if necessary

				replaceCast(castExpression, downChild, rewrite, group);
			}
		}
	}

	public static UnusedCodeFixCore createRemoveUnusedImportFix(CompilationUnit compilationUnit, IProblemLocationCore problem) {
		if (isUnusedImport(problem)) {
			ImportDeclaration node= getImportDeclaration(problem, compilationUnit);
			if (node != null) {
				String label= FixMessages.UnusedCodeFix_RemoveImport_description;
				RemoveImportOperation operation= new RemoveImportOperation(node);
				Map<String, String> options= new Hashtable<>();
				options.put(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS, CleanUpOptionsCore.TRUE);
				return new UnusedCodeFixCore(label, compilationUnit, new CompilationUnitRewriteOperation[] {operation}, options);
			}
		}
		return null;
	}

	public static boolean isUnusedImport(IProblemLocationCore problem) {
		int id= problem.getProblemId();
		return id == IProblem.UnusedImport || id == IProblem.DuplicateImport || id == IProblem.ConflictingImport || id == IProblem.CannotImportPackage || id == IProblem.ImportNotFound;
	}

	public static UnusedCodeFixCore createUnusedMemberFix(CompilationUnit compilationUnit, IProblemLocationCore problem, boolean removeAllAssignements) {
		if (isUnusedMember(problem)) {
			SimpleName name= getUnusedName(compilationUnit, problem);
			if (name != null) {
				IBinding binding= name.resolveBinding();
				if (binding != null) {
					if (isFormalParameterInEnhancedForStatement(name))
						return null;

					String label= getDisplayString(name, binding, removeAllAssignements);
					RemoveUnusedMemberOperation operation= new RemoveUnusedMemberOperation(new SimpleName[] { name }, removeAllAssignements);
					return new UnusedCodeFixCore(label, compilationUnit, new CompilationUnitRewriteOperation[] { operation }, getCleanUpOptions(binding, removeAllAssignements));
				}
			}
		}
		return null;
	}

	public static UnusedCodeFixCore createUnusedTypeParameterFix(CompilationUnit compilationUnit, IProblemLocationCore problemLoc) {
		if (problemLoc.getProblemId() == IProblem.UnusedTypeParameter) {
			SimpleName name= getUnusedName(compilationUnit, problemLoc);
			if (name != null) {
				IBinding binding= name.resolveBinding();
				if (binding != null) {
					String label= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
					RemoveUnusedTypeParameterOperation operation= new RemoveUnusedTypeParameterOperation(name);
					return new UnusedCodeFixCore(label, compilationUnit, new CompilationUnitRewriteOperation[] { operation }, getCleanUpOptions(binding, false));
				}
			}
		}
		return null;
	}

	public static boolean isUnusedMember(IProblemLocationCore problem) {
		int id= problem.getProblemId();
		return id == IProblem.UnusedPrivateMethod || id == IProblem.UnusedPrivateConstructor || id == IProblem.UnusedPrivateField || id == IProblem.UnusedPrivateType
				|| id == IProblem.LocalVariableIsNeverUsed || id == IProblem.ArgumentIsNeverUsed;
	}

	public static UnusedCodeFixCore createRemoveUnusedCastFix(CompilationUnit compilationUnit, IProblemLocationCore problem) {
		if (problem.getProblemId() != IProblem.UnnecessaryCast)
			return null;

		ASTNode selectedNode= problem.getCoveringNode(compilationUnit);

		ASTNode curr= ASTNodes.getUnparenthesedExpression(selectedNode);

		if (!(curr instanceof CastExpression))
			return null;

		return new UnusedCodeFixCore(FixMessages.UnusedCodeFix_RemoveCast_description, compilationUnit, new CompilationUnitRewriteOperation[] {new RemoveCastOperation((CastExpression)curr)});
	}

	public static ICleanUpFixCore createCleanUp(CompilationUnit compilationUnit,
			boolean removeUnusedPrivateMethods,
			boolean removeUnusedPrivateConstructors,
			boolean removeUnusedPrivateFields,
			boolean removeUnusedPrivateTypes,
			boolean removeUnusedLocalVariables,
			boolean removeUnusedImports,
			boolean removeUnusedCast) {

		IProblem[] problems= compilationUnit.getProblems();
		IProblemLocationCore[] locations= new IProblemLocationCore[problems.length];
		for (int i= 0; i < problems.length; i++) {
			locations[i]= new ProblemLocationCore(problems[i]);
		}

		return createCleanUp(compilationUnit, locations,
				removeUnusedPrivateMethods,
				removeUnusedPrivateConstructors,
				removeUnusedPrivateFields,
				removeUnusedPrivateTypes,
				removeUnusedLocalVariables,
				removeUnusedImports,
				removeUnusedCast);
	}

	public static ICleanUpFixCore createCleanUp(CompilationUnit compilationUnit, IProblemLocationCore[] problems,
			boolean removeUnusedPrivateMethods,
			boolean removeUnusedPrivateConstructors,
			boolean removeUnusedPrivateFields,
			boolean removeUnusedPrivateTypes,
			boolean removeUnusedLocalVariables,
			boolean removeUnusedImports,
			boolean removeUnusedCast) {

		List<CompilationUnitRewriteOperation> result= new ArrayList<>();
		Hashtable<ASTNode, List<SimpleName>> variableDeclarations= new Hashtable<>();
		LinkedHashSet<CastExpression> unnecessaryCasts= new LinkedHashSet<>();
		for (IProblemLocationCore problem : problems) {
			int id= problem.getProblemId();

			if (removeUnusedImports && (id == IProblem.UnusedImport || id == IProblem.DuplicateImport || id == IProblem.ConflictingImport ||
				    id == IProblem.CannotImportPackage || id == IProblem.ImportNotFound))
			{
				ImportDeclaration node= UnusedCodeFixCore.getImportDeclaration(problem, compilationUnit);
				if (node != null) {
					result.add(new RemoveImportOperation(node));
				}
			}

			if ((removeUnusedPrivateMethods && id == IProblem.UnusedPrivateMethod) || (removeUnusedPrivateConstructors && id == IProblem.UnusedPrivateConstructor) ||
			    (removeUnusedPrivateTypes && id == IProblem.UnusedPrivateType)) {

				SimpleName name= getUnusedName(compilationUnit, problem);
				if (name != null) {
					IBinding binding= name.resolveBinding();
					if (binding != null) {
						result.add(new RemoveUnusedMemberOperation(new SimpleName[] {name}, false));
					}
				}
			}

			if ((removeUnusedLocalVariables && id == IProblem.LocalVariableIsNeverUsed) ||  (removeUnusedPrivateFields && id == IProblem.UnusedPrivateField)) {
				SimpleName name= getUnusedName(compilationUnit, problem);
				if (name != null) {
					IBinding binding= name.resolveBinding();
					if (binding instanceof IVariableBinding && !isFormalParameterInEnhancedForStatement(name) && (!((IVariableBinding) binding).isField() || isSideEffectFree(name, compilationUnit))) {
						VariableDeclarationFragment parent= ASTNodes.getParent(name, VariableDeclarationFragment.class);
						if (parent != null) {
							ASTNode varDecl= parent.getParent();
							if (!variableDeclarations.containsKey(varDecl)) {
								variableDeclarations.put(varDecl, new ArrayList<SimpleName>());
							}
							variableDeclarations.get(varDecl).add(name);
						} else {
							result.add(new RemoveUnusedMemberOperation(new SimpleName[] {name}, false));
						}
					}
				}
			}

			if (removeUnusedCast && id == IProblem.UnnecessaryCast) {
				ASTNode selectedNode= problem.getCoveringNode(compilationUnit);

				ASTNode curr= ASTNodes.getUnparenthesedExpression(selectedNode);

				if (curr instanceof CastExpression) {
					unnecessaryCasts.add((CastExpression) curr);
				}
			}
		}
		for (List<SimpleName> names : variableDeclarations.values()) {
			result.add(new RemoveUnusedMemberOperation(names.toArray(new SimpleName[0]), false));
		}
		if (unnecessaryCasts.size() > 0)
			result.add(new RemoveAllCastOperation(unnecessaryCasts));

		if (result.isEmpty())
			return null;

		return new UnusedCodeFixCore(FixMessages.UnusedCodeFix_change_name, compilationUnit, result.toArray(new CompilationUnitRewriteOperation[result.size()]));
	}

	public static boolean isFormalParameterInEnhancedForStatement(SimpleName name) {
		return name.getParent() instanceof SingleVariableDeclaration && name.getParent().getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY;
	}

	public static boolean isSideEffectFree(SimpleName simpleName, CompilationUnit completeRoot) {
		SimpleName nameNode= (SimpleName) NodeFinder.perform(completeRoot, simpleName.getStartPosition(), simpleName.getLength());
		SimpleName[] references= LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
		for (SimpleName reference : references) {
			if (hasSideEffect(reference))
				return false;
		}
		return true;
	}

	private static boolean hasSideEffect(SimpleName reference) {
		ASTNode parent= reference.getParent();
		while (parent instanceof QualifiedName) {
			parent= parent.getParent();
		}
		if (parent instanceof FieldAccess) {
			parent= parent.getParent();
		}

		ASTNode node= null;
		int nameParentType= parent.getNodeType();
		if (nameParentType == ASTNode.ASSIGNMENT) {
			Assignment assignment= (Assignment) parent;
			node= assignment.getRightHandSide();
		} else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
			SingleVariableDeclaration decl= (SingleVariableDeclaration)parent;
			node= decl.getInitializer();
			if (node == null)
				return false;
		} else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
			node= parent;
		} else {
			return false;
		}

		ArrayList<Expression> sideEffects= new ArrayList<>();
		node.accept(new SideEffectFinder(sideEffects));
		return sideEffects.size() > 0;
	}

	public static SimpleName getUnusedName(CompilationUnit compilationUnit, IProblemLocationCore problem) {
		ASTNode selectedNode= problem.getCoveringNode(compilationUnit);

		if (selectedNode instanceof MethodDeclaration) {
			return ((MethodDeclaration) selectedNode).getName();
		} else if (selectedNode instanceof SimpleName) {
			return (SimpleName) selectedNode;
		}

		return null;
	}

	public static String getDisplayString(SimpleName simpleName, IBinding binding, boolean removeAllAssignements) {
		String name= BasicElementLabels.getJavaElementName(simpleName.getIdentifier());
		switch (binding.getKind()) {
			case IBinding.TYPE:
				return Messages.format(FixMessages.UnusedCodeFix_RemoveType_description, name);
			case IBinding.METHOD:
				if (((IMethodBinding) binding).isConstructor()) {
					return Messages.format(FixMessages.UnusedCodeFix_RemoveConstructor_description, name);
				} else {
					return Messages.format(FixMessages.UnusedCodeFix_RemoveMethod_description, name);
				}
			case IBinding.VARIABLE:
				if (removeAllAssignements) {
					return Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocalWithInitializer_description, name);
				} else {
					return Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_description, name);
				}
			default:
				return ""; //$NON-NLS-1$
		}
	}

	public static Map<String, String> getCleanUpOptions(IBinding binding, boolean removeAll) {
		Map<String, String> result= new Hashtable<>();

		result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, CleanUpOptionsCore.TRUE);
		switch (binding.getKind()) {
			case IBinding.TYPE:
				result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES, CleanUpOptionsCore.TRUE);
				break;
			case IBinding.METHOD:
				if (((IMethodBinding) binding).isConstructor()) {
					result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS, CleanUpOptionsCore.TRUE);
				} else {
					result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS, CleanUpOptionsCore.TRUE);
				}
				break;
			case IBinding.VARIABLE:
				if (removeAll)
					return null;

				result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS, CleanUpOptionsCore.TRUE);
				result.put(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES, CleanUpOptionsCore.TRUE);
				break;
			default:
				break;
		}

		return result;
	}

	public static ImportDeclaration getImportDeclaration(IProblemLocationCore problem, CompilationUnit compilationUnit) {
		ASTNode selectedNode= problem.getCoveringNode(compilationUnit);
		if (selectedNode != null) {
			ASTNode node= ASTNodes.getParent(selectedNode, ASTNode.IMPORT_DECLARATION);
			if (node instanceof ImportDeclaration) {
				return (ImportDeclaration)node;
			}
		}
		return null;
	}

	private static void replaceCast(CastExpression castExpression, Expression replacement, ASTRewrite rewrite, TextEditGroup group) {
		boolean castEnclosedInNecessaryParentheses= castExpression.getParent() instanceof ParenthesizedExpression
				&& NecessaryParenthesesChecker.needsParentheses(castExpression, castExpression.getParent().getParent(), castExpression.getParent().getLocationInParent());

		ASTNode toReplace= castEnclosedInNecessaryParentheses ? castExpression.getParent() : castExpression;
		ASTNode move;
		if (NecessaryParenthesesChecker.needsParentheses(replacement, toReplace.getParent(), toReplace.getLocationInParent())) {
			if (replacement.getParent() instanceof ParenthesizedExpression) {
				move= rewrite.createMoveTarget(replacement.getParent());
			} else if (castEnclosedInNecessaryParentheses) {
				toReplace= castExpression;
				move= rewrite.createMoveTarget(replacement);
			} else {
				ParenthesizedExpression parentheses= replacement.getAST().newParenthesizedExpression();
				parentheses.setExpression((Expression) rewrite.createMoveTarget(replacement));
				move= parentheses;
			}
		} else {
			move= rewrite.createMoveTarget(replacement);
		}
		rewrite.replace(toReplace, move, group);
	}

	private final Map<String, String> fCleanUpOptions;

	private UnusedCodeFixCore(String name, CompilationUnit compilationUnit, CompilationUnitRewriteOperation[] fixRewriteOperations) {
		this(name, compilationUnit, fixRewriteOperations, null);
	}

	private UnusedCodeFixCore(String name, CompilationUnit compilationUnit, CompilationUnitRewriteOperation[] fixRewriteOperations, Map<String, String> options) {
		super(name, compilationUnit, fixRewriteOperations);
		fCleanUpOptions= options;
	}

	public UnusedCodeCleanUpCore getCleanUp() {
		if (fCleanUpOptions == null)
			return null;

		return new UnusedCodeCleanUpCore(fCleanUpOptions);
	}

}

Back to the top