KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > text > correction > LocalCorrectionsSubProcessor


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * Renaud Waldura <renaud+eclipse@waldura.com> - Access to static proposal
11  *******************************************************************************/

12 package org.eclipse.jdt.internal.ui.text.correction;
13
14 import java.util.ArrayList JavaDoc;
15 import java.util.Collection JavaDoc;
16 import java.util.HashMap JavaDoc;
17 import java.util.Hashtable JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Map JavaDoc;
21
22 import org.eclipse.text.edits.InsertEdit;
23 import org.eclipse.text.edits.TextEdit;
24
25 import org.eclipse.core.runtime.CoreException;
26
27 import org.eclipse.core.resources.IFile;
28
29 import org.eclipse.swt.graphics.Image;
30
31 import org.eclipse.jface.viewers.StructuredSelection;
32
33 import org.eclipse.jface.text.IDocument;
34
35 import org.eclipse.ui.IEditorInput;
36 import org.eclipse.ui.IEditorPart;
37 import org.eclipse.ui.IEditorSite;
38 import org.eclipse.ui.ISharedImages;
39 import org.eclipse.ui.IWorkbenchPage;
40 import org.eclipse.ui.part.FileEditorInput;
41
42 import org.eclipse.jdt.core.ICompilationUnit;
43 import org.eclipse.jdt.core.JavaModelException;
44 import org.eclipse.jdt.core.compiler.IProblem;
45 import org.eclipse.jdt.core.dom.AST;
46 import org.eclipse.jdt.core.dom.ASTNode;
47 import org.eclipse.jdt.core.dom.ASTVisitor;
48 import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
49 import org.eclipse.jdt.core.dom.Annotation;
50 import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
51 import org.eclipse.jdt.core.dom.Assignment;
52 import org.eclipse.jdt.core.dom.Block;
53 import org.eclipse.jdt.core.dom.BodyDeclaration;
54 import org.eclipse.jdt.core.dom.CatchClause;
55 import org.eclipse.jdt.core.dom.ClassInstanceCreation;
56 import org.eclipse.jdt.core.dom.CompilationUnit;
57 import org.eclipse.jdt.core.dom.Expression;
58 import org.eclipse.jdt.core.dom.ExpressionStatement;
59 import org.eclipse.jdt.core.dom.FieldAccess;
60 import org.eclipse.jdt.core.dom.IBinding;
61 import org.eclipse.jdt.core.dom.IMethodBinding;
62 import org.eclipse.jdt.core.dom.ITypeBinding;
63 import org.eclipse.jdt.core.dom.IVariableBinding;
64 import org.eclipse.jdt.core.dom.IfStatement;
65 import org.eclipse.jdt.core.dom.InfixExpression;
66 import org.eclipse.jdt.core.dom.Initializer;
67 import org.eclipse.jdt.core.dom.InstanceofExpression;
68 import org.eclipse.jdt.core.dom.MethodDeclaration;
69 import org.eclipse.jdt.core.dom.MethodInvocation;
70 import org.eclipse.jdt.core.dom.Modifier;
71 import org.eclipse.jdt.core.dom.Name;
72 import org.eclipse.jdt.core.dom.ParenthesizedExpression;
73 import org.eclipse.jdt.core.dom.PrefixExpression;
74 import org.eclipse.jdt.core.dom.SimpleName;
75 import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
76 import org.eclipse.jdt.core.dom.Statement;
77 import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
78 import org.eclipse.jdt.core.dom.SwitchCase;
79 import org.eclipse.jdt.core.dom.SwitchStatement;
80 import org.eclipse.jdt.core.dom.TryStatement;
81 import org.eclipse.jdt.core.dom.Type;
82 import org.eclipse.jdt.core.dom.TypeDeclaration;
83 import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
84 import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
85 import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
86 import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
87
88 import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
89 import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
90 import org.eclipse.jdt.internal.corext.dom.ASTNodes;
91 import org.eclipse.jdt.internal.corext.dom.Bindings;
92 import org.eclipse.jdt.internal.corext.dom.Selection;
93 import org.eclipse.jdt.internal.corext.fix.CleanUpConstants;
94 import org.eclipse.jdt.internal.corext.fix.CodeStyleFix;
95 import org.eclipse.jdt.internal.corext.fix.IFix;
96 import org.eclipse.jdt.internal.corext.fix.Java50Fix;
97 import org.eclipse.jdt.internal.corext.fix.StringFix;
98 import org.eclipse.jdt.internal.corext.fix.UnusedCodeFix;
99 import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
100 import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
101 import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
102 import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
103 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
104 import org.eclipse.jdt.internal.corext.util.Messages;
105
106 import org.eclipse.jdt.ui.actions.InferTypeArgumentsAction;
107 import org.eclipse.jdt.ui.text.java.IInvocationContext;
108 import org.eclipse.jdt.ui.text.java.IProblemLocation;
109
110 import org.eclipse.jdt.internal.ui.JavaPlugin;
111 import org.eclipse.jdt.internal.ui.JavaPluginImages;
112 import org.eclipse.jdt.internal.ui.fix.CodeStyleCleanUp;
113 import org.eclipse.jdt.internal.ui.fix.Java50CleanUp;
114 import org.eclipse.jdt.internal.ui.fix.StringCleanUp;
115 import org.eclipse.jdt.internal.ui.fix.UnnecessaryCodeCleanUp;
116 import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
117 import org.eclipse.jdt.internal.ui.refactoring.RefactoringSaveHelper;
118 import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
119 import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
120 import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
121 import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
122 import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription;
123
124 /**
125   */

126 public class LocalCorrectionsSubProcessor {
127
128     private static final String JavaDoc RAW_TYPE_REFERENCE_ID= "org.eclipse.jdt.ui.correction.rawTypeReference"; //$NON-NLS-1$
129
private static final String JavaDoc ADD_EXCEPTION_TO_THROWS_ID= "org.eclipse.jdt.ui.correction.addThrowsDecl"; //$NON-NLS-1$
130
private static final String JavaDoc ADD_NON_NLS_ID= "org.eclipse.jdt.ui.correction.addNonNLS"; //$NON-NLS-1$
131
private static final String JavaDoc ADD_FIELD_QUALIFICATION_ID= "org.eclipse.jdt.ui.correction.qualifyField"; //$NON-NLS-1$
132
private static final String JavaDoc ADD_STATIC_ACCESS_ID= "org.eclipse.jdt.ui.correction.changeToStatic"; //$NON-NLS-1$
133
private static final String JavaDoc REMOVE_UNNECESSARY_NLS_TAG_ID= "org.eclipse.jdt.ui.correction.removeNlsTag"; //$NON-NLS-1$
134

135     public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) throws CoreException {
136         ICompilationUnit cu= context.getCompilationUnit();
137
138         CompilationUnit astRoot= context.getASTRoot();
139         ASTNode selectedNode= problem.getCoveringNode(astRoot);
140         if (selectedNode == null) {
141             return;
142         }
143         while (selectedNode != null && !(selectedNode instanceof Statement)) {
144             selectedNode= selectedNode.getParent();
145         }
146         if (selectedNode == null) {
147             return;
148         }
149
150         int offset= selectedNode.getStartPosition();
151         int length= selectedNode.getLength();
152         int selectionEnd= context.getSelectionOffset() + context.getSelectionLength();
153         if (selectionEnd > offset + length) {
154             // extend the selection if more than one statement is selected (bug 72149)
155
length= selectionEnd - offset;
156         }
157
158         SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, offset, length, null);
159         if (refactoring == null)
160             return;
161
162         refactoring.setLeaveDirty(true);
163         if (refactoring.checkActivationBasics(astRoot).isOK()) {
164             String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_description;
165             Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
166             CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, (CompilationUnitChange) refactoring.createChange(null), 6, image);
167             proposals.add(proposal);
168         }
169
170         BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
171         if (decl == null) {
172             return;
173         }
174
175         ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(offset, length));
176         if (uncaughtExceptions.length == 0) {
177             return;
178         }
179
180         TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode);
181         if (surroundingTry != null && ASTNodes.isParent(selectedNode, surroundingTry.getBody())) {
182             ASTRewrite rewrite= ASTRewrite.create(surroundingTry.getAST());
183
184             String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalcatch_description;
185             Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
186             LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 7, image);
187             
188             ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
189
190             AST ast= astRoot.getAST();
191             ListRewrite clausesRewrite= rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
192             for (int i= 0; i < uncaughtExceptions.length; i++) {
193                 ITypeBinding excBinding= uncaughtExceptions[i];
194                 String JavaDoc varName= StubUtility.getExceptionVariableName(cu.getJavaProject());
195                 SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
196                 var.setName(ast.newSimpleName(varName));
197                 var.setType(imports.addImport(excBinding, ast));
198                 CatchClause newClause= ast.newCatchClause();
199                 newClause.setException(var);
200                 String JavaDoc catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), varName, selectedNode, String.valueOf('\n'));
201                 if (catchBody != null) {
202                     ASTNode node= rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
203                     newClause.getBody().statements().add(node);
204                 }
205                 clausesRewrite.insertLast(newClause, null);
206
207                 String JavaDoc typeKey= "type" + i; //$NON-NLS-1$
208
String JavaDoc nameKey= "name" + i; //$NON-NLS-1$
209
proposal.addLinkedPosition(rewrite.track(var.getType()), false, typeKey);
210                 proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
211                 addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
212             }
213             proposals.add(proposal);
214         }
215
216         if (decl instanceof MethodDeclaration) {
217             MethodDeclaration methodDecl= (MethodDeclaration) decl;
218             IMethodBinding binding= methodDecl.resolveBinding();
219             if (binding != null) {
220                 ITypeBinding[] methodExceptions= binding.getExceptionTypes();
221                 ArrayList JavaDoc unhandledExceptions= new ArrayList JavaDoc(uncaughtExceptions.length);
222                 for (int i= 0; i < uncaughtExceptions.length; i++) {
223                     ITypeBinding curr= uncaughtExceptions[i];
224                     if (!canRemoveException(curr, methodExceptions)) {
225                         unhandledExceptions.add(curr);
226                     }
227                 }
228                 uncaughtExceptions= (ITypeBinding[]) unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
229
230                 List JavaDoc exceptions= methodDecl.thrownExceptions();
231                 int nExistingExceptions= exceptions.size();
232                 ChangeDescription[] desc= new ChangeDescription[nExistingExceptions + uncaughtExceptions.length];
233                 for (int i= 0; i < exceptions.size(); i++) {
234                     Name elem= (Name) exceptions.get(i);
235                     if (canRemoveException(elem.resolveTypeBinding(), uncaughtExceptions)) {
236                         desc[i]= new RemoveDescription();
237                     }
238                 }
239                 for (int i = 0; i < uncaughtExceptions.length; i++) {
240                     desc[i + nExistingExceptions]= new InsertDescription(uncaughtExceptions[i], ""); //$NON-NLS-1$
241
}
242
243                 String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_addthrows_description;
244                 Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
245
246                 ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, desc, 8, image);
247                 for (int i= 0; i < uncaughtExceptions.length; i++) {
248                     addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], proposal.getExceptionTypeGroupId(i + nExistingExceptions));
249                 }
250                 proposal.setCommandId(ADD_EXCEPTION_TO_THROWS_ID);
251                 proposals.add(proposal);
252             }
253         }
254     }
255
256     private static void addExceptionTypeLinkProposals(LinkedCorrectionProposal proposal, ITypeBinding exc, String JavaDoc key) {
257         // all super classes except Object
258
while (exc != null && !"java.lang.Object".equals(exc.getQualifiedName())) { //$NON-NLS-1$
259
proposal.addLinkedPositionProposal(key, exc);
260             exc= exc.getSuperclass();
261         }
262     }
263
264
265     private static boolean canRemoveException(ITypeBinding curr, ITypeBinding[] addedExceptions) {
266         while (curr != null) {
267             for (int i= 0; i < addedExceptions.length; i++) {
268                 if (curr == addedExceptions[i]) {
269                     return true;
270                 }
271             }
272             curr= curr.getSuperclass();
273         }
274         return false;
275     }
276
277     public static void addUnreachableCatchProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
278         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
279         if (selectedNode == null) {
280             return;
281         }
282
283         QuickAssistProcessor.getCatchClauseToThrowsProposals(context, selectedNode, proposals);
284     }
285
286     public static void addNLSProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) throws CoreException {
287         final ICompilationUnit cu= context.getCompilationUnit();
288         if (cu == null || !cu.exists()){
289             return;
290         }
291         String JavaDoc name= CorrectionMessages.LocalCorrectionsSubProcessor_externalizestrings_description;
292
293         ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 2, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)) {
294             public void apply(IDocument document) {
295                 try {
296                     NLSRefactoring refactoring= NLSRefactoring.create(cu);
297                     if (refactoring == null)
298                         return;
299                     ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
300                     String JavaDoc dialogTitle= CorrectionMessages.LocalCorrectionsSubProcessor_externalizestrings_dialog_title;
301                     new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES);
302                 } catch (JavaModelException e) {
303                     JavaPlugin.log(e);
304                 }
305             }
306             public String JavaDoc getAdditionalProposalInfo() {
307                 return CorrectionMessages.LocalCorrectionsSubProcessor_externalizestrings_additional_info;
308             }
309             
310         };
311         proposals.add(proposal);
312         
313         IFix fix= StringFix.createFix(context.getASTRoot(), problem, false, true);
314         if (fix != null) {
315             Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
316             Map JavaDoc options= new Hashtable JavaDoc();
317             options.put(CleanUpConstants.ADD_MISSING_NLS_TAGS, CleanUpConstants.TRUE);
318             FixCorrectionProposal addNLS= new FixCorrectionProposal(fix, new StringCleanUp(options), 3, image, context);
319             addNLS.setCommandId(ADD_NON_NLS_ID);
320             proposals.add(addNLS);
321         }
322     }
323     
324     public static void getUnnecessaryNLSTagProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) throws CoreException {
325         IFix fix= StringFix.createFix(context.getASTRoot(), problem, true, false);
326         if (fix != null) {
327             Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
328             Map JavaDoc options= new Hashtable JavaDoc();
329             options.put(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS, CleanUpConstants.TRUE);
330             FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new StringCleanUp(options), 6, image, context);
331             proposal.setCommandId(REMOVE_UNNECESSARY_NLS_TAG_ID);
332             proposals.add(proposal);
333         }
334     }
335     
336
337     /*
338      * Fix instance accesses and indirect (static) accesses to static fields/methods
339      */

340     public static void addCorrectAccessToStaticProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) throws CoreException {
341         IFix fix= CodeStyleFix.createIndirectAccessToStaticFix(context.getASTRoot(), problem);
342         if (fix != null) {
343             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
344             Map JavaDoc options= new HashMap JavaDoc();
345             options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, CleanUpConstants.TRUE);
346             options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS, CleanUpConstants.TRUE);
347             FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new CodeStyleCleanUp(options), 6, image, context);
348             proposal.setCommandId(ADD_STATIC_ACCESS_ID);
349             proposals.add(proposal);
350             return;
351         }
352         
353         IFix[] fixes= CodeStyleFix.createNonStaticAccessFixes(context.getASTRoot(), problem);
354         if (fixes != null) {
355             IFix fix1= fixes[0];
356             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
357             Map JavaDoc options= new HashMap JavaDoc();
358             options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, CleanUpConstants.TRUE);
359             options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS, CleanUpConstants.TRUE);
360             FixCorrectionProposal proposal= new FixCorrectionProposal(fix1, new CodeStyleCleanUp(options), 6, image, context);
361             proposal.setCommandId(ADD_STATIC_ACCESS_ID);
362             proposals.add(proposal);
363             
364             if (fixes.length > 1) {
365                 Map JavaDoc options1= new HashMap JavaDoc();
366                 options1.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, CleanUpConstants.TRUE);
367                 options1.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS, CleanUpConstants.TRUE);
368                 options1.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS, CleanUpConstants.TRUE);
369                 IFix fix2= fixes[1];
370                 proposal= new FixCorrectionProposal(fix2, new CodeStyleCleanUp(options), 5, image, context);
371                 proposals.add(proposal);
372             }
373         }
374         ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC, 4);
375     }
376
377     public static void addUnimplementedMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
378         ICompilationUnit cu= context.getCompilationUnit();
379         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
380         if (selectedNode == null) {
381             return;
382         }
383         ASTNode typeNode= null;
384         ITypeBinding binding= null;
385         if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent() instanceof AbstractTypeDeclaration) {
386             AbstractTypeDeclaration typeDecl= (AbstractTypeDeclaration) selectedNode.getParent();
387             binding= typeDecl.resolveBinding();
388             typeNode= typeDecl;
389         } else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
390             ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
391             AnonymousClassDeclaration anonymDecl= creation.getAnonymousClassDeclaration();
392             binding= anonymDecl.resolveBinding();
393             typeNode= anonymDecl;
394         }
395         if (typeNode != null && binding != null) {
396             UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10);
397             proposals.add(proposal);
398         }
399         if (typeNode instanceof TypeDeclaration) {
400             TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
401             ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeAbstractProposal(cu, typeDeclaration, 5);
402             proposals.add(proposal);
403         }
404     }
405
406     public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
407         ICompilationUnit cu= context.getCompilationUnit();
408
409         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
410         if (!(selectedNode instanceof Name)) {
411             return;
412         }
413         Name name= (Name) selectedNode;
414         IBinding binding= name.resolveBinding();
415         if (!(binding instanceof IVariableBinding)) {
416             return;
417         }
418         IVariableBinding varBinding= (IVariableBinding) binding;
419
420         CompilationUnit astRoot= context.getASTRoot();
421         ASTNode node= astRoot.findDeclaringNode(binding);
422         if (node instanceof VariableDeclarationFragment) {
423             ASTRewrite rewrite= ASTRewrite.create(node.getAST());
424
425             VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
426             if (fragment.getInitializer() != null) {
427                 return;
428             }
429             Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType());
430             if (expression == null) {
431                 return;
432             }
433             rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null);
434
435             String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description;
436             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
437
438             LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
439             proposal.addLinkedPosition(rewrite.track(expression), false, "initializer"); //$NON-NLS-1$
440
proposals.add(proposal);
441         }
442     }
443
444     public static void addConstructorFromSuperclassProposal(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) throws CoreException {
445         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
446         if (selectedNode == null) {
447             return;
448         }
449         
450         TypeDeclaration typeDeclaration= null;
451         if (selectedNode.getLocationInParent() == TypeDeclaration.NAME_PROPERTY) {
452             typeDeclaration= (TypeDeclaration) selectedNode.getParent();
453         } else {
454             BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode);
455             if (declaration instanceof Initializer && problem.getProblemId() == IProblem.UnhandledExceptionInDefaultConstructor) {
456                 addUncaughtExceptionProposals(context, problem, proposals);
457             }
458             return;
459         }
460         
461         ITypeBinding binding= typeDeclaration.resolveBinding();
462         if (binding == null || binding.getSuperclass() == null) {
463             return;
464         }
465         ICompilationUnit cu= context.getCompilationUnit();
466         IMethodBinding[] methods= binding.getSuperclass().getDeclaredMethods();
467         for (int i= 0; i < methods.length; i++) {
468             IMethodBinding curr= methods[i];
469             if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) {
470                 proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 5));
471             }
472         }
473     }
474
475     public static void addUnusedMemberProposal(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
476         int problemId = problem.getProblemId();
477         UnusedCodeFix fix= UnusedCodeFix.createUnusedMemberFix(context.getASTRoot(), problem, false);
478         if (fix != null) {
479             addProposal(context, proposals, fix);
480         }
481         
482         if (problemId==IProblem.LocalVariableIsNeverUsed){
483             fix= UnusedCodeFix.createUnusedMemberFix(context.getASTRoot(), problem, true);
484             addProposal(context, proposals, fix);
485         }
486         
487     }
488
489     private static void addProposal(IInvocationContext context, Collection JavaDoc proposals, final UnusedCodeFix fix) {
490         if (fix != null) {
491             Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
492             FixCorrectionProposal proposal= new FixCorrectionProposal(fix, fix.getCleanUp(), 10, image, context);
493             proposals.add(proposal);
494         }
495     }
496
497     public static void addSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
498         String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_removesemicolon_description;
499         ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", 6); //$NON-NLS-1$
500
proposals.add(proposal);
501     }
502
503     public static void addUnnecessaryCastProposal(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
504         
505         IFix fix= UnusedCodeFix.createRemoveUnusedCastFix(context.getASTRoot(), problem);
506         if (fix != null) {
507             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
508             Map JavaDoc options= new Hashtable JavaDoc();
509             options.put(CleanUpConstants.REMOVE_UNNECESSARY_CASTS, CleanUpConstants.TRUE);
510             FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new UnnecessaryCodeCleanUp(options), 5, image, context);
511             proposals.add(proposal);
512         }
513     }
514
515     public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
516         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
517
518         ASTNode curr= selectedNode;
519         while (curr instanceof ParenthesizedExpression) {
520             curr= ((ParenthesizedExpression) curr).getExpression();
521         }
522
523         if (curr instanceof InstanceofExpression) {
524             AST ast= curr.getAST();
525
526             ASTRewrite rewrite= ASTRewrite.create(ast);
527
528             InstanceofExpression inst= (InstanceofExpression) curr;
529
530             InfixExpression expression= ast.newInfixExpression();
531             expression.setLeftOperand((Expression) rewrite.createCopyTarget(inst.getLeftOperand()));
532             expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
533             expression.setRightOperand(ast.newNullLiteral());
534
535
536             if (false/*ASTNodes.needsParentheses(expression)*/) {
537                 ParenthesizedExpression parents= ast.newParenthesizedExpression();
538                 parents.setExpression(expression);
539                 rewrite.replace(inst, parents, null);
540             } else {
541                 rewrite.replace(inst, expression, null);
542             }
543
544             String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessaryinstanceof_description;
545             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
546             ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
547             proposals.add(proposal);
548         }
549
550     }
551
552     public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
553         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
554         if (selectedNode == null || !(selectedNode.getParent() instanceof MethodDeclaration)) {
555             return;
556         }
557         MethodDeclaration decl= (MethodDeclaration) selectedNode.getParent();
558         IMethodBinding binding= decl.resolveBinding();
559         if (binding != null) {
560             List JavaDoc thrownExceptions= decl.thrownExceptions();
561             int index= thrownExceptions.indexOf(selectedNode);
562             if (index == -1) {
563                 return;
564             }
565             ChangeDescription[] desc= new ChangeDescription[thrownExceptions.size()];
566             desc[index]= new RemoveDescription();
567
568             ICompilationUnit cu= context.getCompilationUnit();
569             String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessarythrow_description;
570             Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
571
572             proposals.add(new ChangeMethodSignatureProposal(label, cu, selectedNode, binding, null, desc, 5, image));
573         }
574     }
575
576     public static void addUnqualifiedFieldAccessProposal(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) throws CoreException {
577         IFix fix= CodeStyleFix.createAddFieldQualifierFix(context.getASTRoot(), problem);
578         if (fix != null) {
579             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
580             Map JavaDoc options= new HashMap JavaDoc();
581             options.put(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS, CleanUpConstants.TRUE);
582             options.put(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS, CleanUpConstants.TRUE);
583             FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new CodeStyleCleanUp(options), 5, image, context);
584             proposal.setCommandId(ADD_FIELD_QUALIFICATION_ID);
585             proposals.add(proposal);
586         }
587     }
588
589     public static void addInvalidVariableNameProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
590         // hiding, redefined or future keyword
591

592         CompilationUnit root= context.getASTRoot();
593         ASTNode selectedNode= problem.getCoveringNode(root);
594         if (selectedNode instanceof MethodDeclaration) {
595             selectedNode= ((MethodDeclaration) selectedNode).getName();
596         }
597         if (!(selectedNode instanceof SimpleName)) {
598             return;
599         }
600         SimpleName nameNode= (SimpleName) selectedNode;
601         String JavaDoc valueSuggestion= null;
602
603         String JavaDoc name;
604         switch (problem.getProblemId()) {
605             case IProblem.LocalVariableHidingLocalVariable:
606             case IProblem.LocalVariableHidingField:
607                 name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_local_label, nameNode.getIdentifier());
608                 break;
609             case IProblem.FieldHidingLocalVariable:
610             case IProblem.FieldHidingField:
611             case IProblem.DuplicateField:
612                 name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_field_label, nameNode.getIdentifier());
613                 break;
614             case IProblem.ArgumentHidingLocalVariable:
615             case IProblem.ArgumentHidingField:
616                 name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_argument_label, nameNode.getIdentifier());
617                 break;
618             case IProblem.DuplicateMethod:
619                 name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_renaming_duplicate_method, nameNode.getIdentifier());
620                 break;
621                 
622             default:
623                 name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_rename_var_label, nameNode.getIdentifier());
624         }
625
626         if (problem.getProblemId() == IProblem.UseEnumAsAnIdentifier) {
627             valueSuggestion= "enumeration"; //$NON-NLS-1$
628
} else {
629             valueSuggestion= nameNode.getIdentifier() + '1';
630         }
631
632         LinkedNamesAssistProposal proposal= new LinkedNamesAssistProposal(name, context.getCompilationUnit(), nameNode, valueSuggestion);
633         proposals.add(proposal);
634     }
635
636     public static void getInvalidOperatorProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
637         CompilationUnit root= context.getASTRoot();
638         AST ast= root.getAST();
639
640         ASTNode selectedNode= problem.getCoveringNode(root);
641
642         while (selectedNode instanceof ParenthesizedExpression) {
643             selectedNode= ((ParenthesizedExpression) selectedNode).getExpression();
644         }
645
646         if (selectedNode instanceof PrefixExpression) {
647             // !x instanceof X -> !(x instanceof X)
648

649             PrefixExpression expression= (PrefixExpression) selectedNode;
650             if (expression.getOperator() == PrefixExpression.Operator.NOT) {
651                 ASTNode parent= expression.getParent();
652
653                 String JavaDoc label= null;
654                 switch (parent.getNodeType()) {
655                     case ASTNode.INSTANCEOF_EXPRESSION:
656                         label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_instanceof_description;
657                         break;
658                     case ASTNode.INFIX_EXPRESSION:
659                         label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_description;
660                         break;
661                 }
662
663                 if (label != null) {
664                     ASTRewrite rewrite= ASTRewrite.create(ast);
665                     rewrite.replace(selectedNode, rewrite.createMoveTarget(expression.getOperand()), null);
666
667                     ParenthesizedExpression newParentExpr= ast.newParenthesizedExpression();
668                     newParentExpr.setExpression((Expression) rewrite.createMoveTarget(parent));
669                     PrefixExpression newPrefixExpr= ast.newPrefixExpression();
670                     newPrefixExpr.setOperand(newParentExpr);
671                     newPrefixExpr.setOperator(PrefixExpression.Operator.NOT);
672
673                     rewrite.replace(parent, newPrefixExpr, null);
674
675                     Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
676                     ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
677                     proposals.add(proposal);
678                 }
679             }
680         } else if (selectedNode instanceof InfixExpression && isBitOperation((((InfixExpression) selectedNode).getOperator()))) {
681             // a & b == c -> (a & b) == c
682
final CompareInBitWiseOpFinder opFinder= new CompareInBitWiseOpFinder(selectedNode);
683             if (opFinder.getCompareExpression() != null) { // compare operation inside bit operations: set parents
684
String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_bitop_description;
685                 Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
686                 CUCorrectionProposal proposal= new CUCorrectionProposal(label, context.getCompilationUnit(), 5, image) {
687                     protected void addEdits(IDocument document, TextEdit edit) throws CoreException {
688                         InfixExpression compareExpression= opFinder.getCompareExpression();
689                         InfixExpression expression= opFinder.getParentInfixExpression();
690                         ASTNode left= compareExpression.getLeftOperand();
691                         if (expression.getStartPosition() < left.getStartPosition()) {
692                             edit.addChild(new InsertEdit(expression.getStartPosition(), String.valueOf('(')));
693                             edit.addChild(new InsertEdit(ASTNodes.getExclusiveEnd(left), String.valueOf(')')));
694                         }
695                         ASTNode rigth= compareExpression.getRightOperand();
696                         int selEnd= ASTNodes.getExclusiveEnd(expression);
697                         if (selEnd > ASTNodes.getExclusiveEnd(rigth)) {
698                             edit.addChild(new InsertEdit(rigth.getStartPosition(), String.valueOf('(')));
699                             edit.addChild(new InsertEdit(selEnd, String.valueOf(')')));
700                         }
701                     }
702                 };
703                 proposals.add(proposal);
704             }
705         }
706     }
707
708     private static boolean isBitOperation(InfixExpression.Operator op) {
709         return op == InfixExpression.Operator.AND || op == InfixExpression.Operator.OR || op == InfixExpression.Operator.XOR;
710     }
711
712     private static class CompareInBitWiseOpFinder extends ASTVisitor {
713         
714         private InfixExpression fCompareExpression= null;
715         private final ASTNode fSelectedNode;
716
717         public CompareInBitWiseOpFinder(ASTNode selectedNode) {
718             fSelectedNode= selectedNode;
719             selectedNode.accept(this);
720         }
721         
722         public boolean visit(InfixExpression e) {
723             InfixExpression.Operator op= e.getOperator();
724             if (isBitOperation(op)) {
725                 return true;
726             } else if (op == InfixExpression.Operator.EQUALS || op == InfixExpression.Operator.NOT_EQUALS) {
727                 fCompareExpression= e;
728                 return false;
729             }
730             return false;
731         }
732         
733         public InfixExpression getCompareExpression() {
734             return fCompareExpression;
735         }
736         
737         public InfixExpression getParentInfixExpression() {
738             ASTNode expr= fSelectedNode;
739             ASTNode parent= expr.getParent(); // include all parents
740
while (parent instanceof InfixExpression && isBitOperation(((InfixExpression) parent).getOperator())) {
741                 expr= parent;
742                 parent= expr.getParent();
743             }
744             return (InfixExpression) expr;
745         }
746     }
747
748     public static void getUnnecessaryElseProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
749         CompilationUnit root= context.getASTRoot();
750         ASTNode selectedNode= problem.getCoveringNode(root);
751         if (selectedNode == null) {
752             return;
753         }
754         if (!(selectedNode.getParent() instanceof IfStatement)) {
755             return;
756         }
757         IfStatement ifStatement= (IfStatement) selectedNode.getParent();
758         ASTNode ifParent= ifStatement.getParent();
759         if (!(ifParent instanceof Block)) {
760             return;
761         }
762
763         ASTRewrite rewrite= ASTRewrite.create(root.getAST());
764         ASTNode placeholder=QuickAssistProcessor.getCopyOfInner(rewrite, ifStatement.getElseStatement(), false);
765         if (placeholder == null) {
766             return;
767         }
768         rewrite.remove(ifStatement.getElseStatement(), null);
769
770         ListRewrite listRewrite= rewrite.getListRewrite(ifParent, Block.STATEMENTS_PROPERTY);
771         listRewrite.insertAfter(placeholder, ifStatement, null);
772
773         String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_removeelse_description;
774         Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
775         ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
776         proposals.add(proposal);
777     }
778
779
780     public static void getInterfaceExtendsClassProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
781         CompilationUnit root= context.getASTRoot();
782         ASTNode selectedNode= problem.getCoveringNode(root);
783         if (selectedNode == null) {
784             return;
785         }
786         while (selectedNode.getParent() instanceof Type) {
787             selectedNode= selectedNode.getParent();
788         }
789
790         StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent();
791         if (locationInParent != TypeDeclaration.SUPERCLASS_TYPE_PROPERTY) {
792             return;
793         }
794
795         TypeDeclaration typeDecl= (TypeDeclaration) selectedNode.getParent();
796         {
797             ASTRewrite rewrite= ASTRewrite.create(root.getAST());
798             ASTNode placeHolder= rewrite.createMoveTarget(selectedNode);
799             ListRewrite interfaces= rewrite.getListRewrite(typeDecl, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
800             interfaces.insertFirst(placeHolder, null);
801
802             String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_extendstoimplements_description;
803             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
804             ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 6, image);
805             proposals.add(proposal);
806         }
807         {
808             ASTRewrite rewrite= ASTRewrite.create(root.getAST());
809
810             rewrite.set(typeDecl, TypeDeclaration.INTERFACE_PROPERTY, Boolean.TRUE, null);
811
812             String JavaDoc typeName= typeDecl.getName().getIdentifier();
813             String JavaDoc label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_classtointerface_description, typeName);
814             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
815             ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 3, image);
816             proposals.add(proposal);
817         }
818     }
819
820     public static void getUnreachableCodeProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
821         CompilationUnit root= context.getASTRoot();
822         ASTNode selectedNode= problem.getCoveringNode(root);
823         if (selectedNode == null) {
824             return;
825         }
826         if (selectedNode.getParent() instanceof ExpressionStatement) {
827             selectedNode= selectedNode.getParent();
828         }
829         
830         if (selectedNode instanceof Statement) {
831             ASTRewrite rewrite= ASTRewrite.create(selectedNode.getAST());
832             rewrite.remove(selectedNode, null);
833             String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_removeunreachablecode_description;
834             Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
835             ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 3, image);
836             proposals.add(proposal);
837         }
838     }
839
840     public static void getAssignmentHasNoEffectProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
841         CompilationUnit root= context.getASTRoot();
842         ASTNode selectedNode= problem.getCoveringNode(root);
843         if (!(selectedNode instanceof Assignment)) {
844             return;
845         }
846         ASTNode assignedNode= ((Assignment) selectedNode).getLeftHandSide();
847         ASTNode assignExpression= ((Assignment) selectedNode).getRightHandSide();
848         if (!(assignedNode instanceof SimpleName) && !(assignExpression instanceof SimpleName)) {
849             return;
850         }
851         
852         IBinding binding= (assignedNode instanceof SimpleName) ? ((SimpleName) assignedNode).resolveBinding() : ((SimpleName) assignExpression).resolveBinding();
853         if (!(binding instanceof IVariableBinding)) {
854             return;
855         }
856         ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
857         if (typeBinding == null) {
858             return;
859         }
860         IVariableBinding fieldBinding= Bindings.findFieldInHierarchy(typeBinding, binding.getName());
861         if (fieldBinding == null || fieldBinding.getDeclaringClass() != typeBinding && Modifier.isPrivate(fieldBinding.getModifiers())) {
862             return;
863         }
864         
865         if (binding != fieldBinding) {
866             if (assignedNode instanceof SimpleName) {
867                 String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_qualify_left_hand_side_description;
868                 proposals.add(createNoSideEffectProposal(context, (SimpleName) assignedNode, fieldBinding, label, 6));
869             }
870             if (assignExpression instanceof SimpleName) {
871                 String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_LocalCorrectionsSubProcessor_qualify_right_hand_side_description;
872                 proposals.add(createNoSideEffectProposal(context, (SimpleName) assignExpression, fieldBinding, label, 5));
873             }
874         }
875         
876         if (binding == fieldBinding && ASTResolving.findParentBodyDeclaration(selectedNode) instanceof MethodDeclaration) {
877             SimpleName simpleName= (SimpleName) ((assignedNode instanceof SimpleName) ? assignedNode : assignExpression);
878             String JavaDoc label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createparameter_description, simpleName.getIdentifier());
879             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
880             proposals.add(new NewVariableCompletionProposal(label, context.getCompilationUnit(), NewVariableCompletionProposal.PARAM, simpleName, null, 5, image));
881         }
882         
883     
884     }
885
886     private static ASTRewriteCorrectionProposal createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String JavaDoc label, int relevance) {
887         AST ast= nodeToQualify.getAST();
888         
889         Expression qualifier;
890         if (Modifier.isStatic(fieldBinding.getModifiers())) {
891             ITypeBinding declaringClass= fieldBinding.getDeclaringClass();
892             qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName());
893         } else {
894             qualifier= ast.newThisExpression();
895         }
896
897         ASTRewrite rewrite= ASTRewrite.create(ast);
898         FieldAccess access= ast.newFieldAccess();
899         access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify));
900         access.setExpression(qualifier);
901         rewrite.replace(nodeToQualify, access, null);
902         
903
904         Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
905         return new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image);
906     }
907
908     public static void addValueForAnnotationProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
909         ICompilationUnit cu= context.getCompilationUnit();
910         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
911         if (selectedNode instanceof Annotation) {
912             Annotation annotation= (Annotation) selectedNode;
913             if (annotation.resolveTypeBinding() == null) {
914                 return;
915             }
916             MissingAnnotationAttributesProposal proposal= new MissingAnnotationAttributesProposal(cu, annotation, 10);
917             proposals.add(proposal);
918         }
919     }
920
921     public static void addTypePrametersToRawTypeReference(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
922         IFix fix= Java50Fix.createRawTypeReferenceFix(context.getASTRoot(), problem);
923         if (fix != null) {
924             for (Iterator JavaDoc iter= proposals.iterator(); iter.hasNext();) {
925                 Object JavaDoc element= iter.next();
926                 if (element instanceof FixCorrectionProposal) {
927                     FixCorrectionProposal fixProp= (FixCorrectionProposal)element;
928                     if (RAW_TYPE_REFERENCE_ID.equals(fixProp.getCommandId())) {
929                         return;
930                     }
931                 }
932             }
933             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
934             Map JavaDoc options= new Hashtable JavaDoc();
935             options.put(CleanUpConstants.VARIABLE_DECLARATION_USE_TYPE_ARGUMENTS_FOR_RAW_TYPE_REFERENCES, CleanUpConstants.TRUE);
936             FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new Java50CleanUp(options), 6, image, context);
937             proposal.setCommandId(RAW_TYPE_REFERENCE_ID);
938             proposals.add(proposal);
939         }
940         
941         //Infer Generic Type Arguments... proposal
942
final ICompilationUnit cu= context.getCompilationUnit();
943         ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(CorrectionMessages.LocalCorrectionsSubProcessor_InferGenericTypeArguments, null, 5, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)) {
944             public void apply(IDocument document) {
945                 IEditorInput input= new FileEditorInput((IFile) cu.getResource());
946                 IWorkbenchPage p= JavaPlugin.getActivePage();
947                 if (p == null)
948                     return;
949                 
950                 IEditorPart part= p.findEditor(input);
951                 if (!(part instanceof JavaEditor))
952                     return;
953                 
954                 IEditorSite site= ((JavaEditor)part).getEditorSite();
955                 InferTypeArgumentsAction action= new InferTypeArgumentsAction(site);
956                 action.run(new StructuredSelection(cu));
957             }
958
959             /**
960              * {@inheritDoc}
961              */

962             public String JavaDoc getAdditionalProposalInfo() {
963                 return CorrectionMessages.LocalCorrectionsSubProcessor_InferGenericTypeArguments_description;
964             }
965         };
966         proposals.add(proposal);
967     }
968     
969     public static void addFallThroughProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
970         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
971         if (selectedNode instanceof SwitchCase && selectedNode.getParent() instanceof SwitchStatement) {
972             AST ast= selectedNode.getAST();
973             ASTRewrite rewrite= ASTRewrite.create(ast);
974             ListRewrite listRewrite= rewrite.getListRewrite(selectedNode.getParent(), SwitchStatement.STATEMENTS_PROPERTY);
975             listRewrite.insertBefore(ast.newBreakStatement(), selectedNode, null);
976             
977             String JavaDoc label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_break_statement;
978             Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
979             ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
980             proposals.add(proposal);
981         }
982     }
983     
984     public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection JavaDoc proposals) {
985         ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
986         if (selectedNode instanceof Name) {
987             IBinding binding= ((Name) selectedNode).resolveBinding();
988             if (binding instanceof IVariableBinding) {
989                 IVariableBinding variableBinding= (IVariableBinding) binding;
990                 if (variableBinding.isField()) {
991                     String JavaDoc qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
992                     String JavaDoc fieldName= variableBinding.getName();
993                     String JavaDoc[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
994                     if (methodName != null) {
995                         AST ast= selectedNode.getAST();
996                         ASTRewrite astRewrite= ASTRewrite.create(ast);
997                         ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true);
998
999                         MethodInvocation method= ast.newMethodInvocation();
1000                        String JavaDoc qfn= importRewrite.addImport(methodName[0]);
1001                        method.setExpression(ast.newName(qfn));
1002                        method.setName(ast.newSimpleName(methodName[1]));
1003                        astRewrite.replace(selectedNode, method, null);
1004
1005                        String JavaDoc label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, method);
1006                        Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
1007                        ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), astRewrite, 10, image);
1008                        proposal.setImportRewrite(importRewrite);
1009                        proposals.add(proposal);
1010                    }
1011                }
1012            }
1013        }
1014    }
1015    
1016    private static Map JavaDoc/*<String,String[]>*/ resolveMap;
1017    private static String JavaDoc[] getMethod(String JavaDoc fieldName) {
1018        if (resolveMap==null){
1019            resolveMap=new HashMap JavaDoc();
1020            resolveMap.put("java.util.Collections.EMPTY_MAP", new String JavaDoc[]{"java.util.Collections","emptyMap"}); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
1021
resolveMap.put("java.util.Collections.EMPTY_SET", new String JavaDoc[]{"java.util.Collections","emptySet"}); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
1022
resolveMap.put("java.util.Collections.EMPTY_LIST", new String JavaDoc[]{"java.util.Collections","emptyList"});//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
1023
}
1024        return (String JavaDoc[]) resolveMap.get(fieldName);
1025    }
1026}
1027
Popular Tags