org.eclipse.jdt.core.dom.rewrite.ImportRewrite Java Examples
The following examples show how to use
org.eclipse.jdt.core.dom.rewrite.ImportRewrite.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavaTypeCompletionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Updates the replacement string. * * @param document the document * @param trigger the trigger * @param offset the offset * @param impRewrite the import rewrite * @return <code>true</code> if the cursor position should be updated, <code>false</code> otherwise * @throws BadLocationException if accessing the document fails * @throws CoreException if something else fails */ protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException { // avoid adding imports when inside imports container if (impRewrite != null && fFullyQualifiedTypeName != null) { String replacementString= getReplacementString(); String qualifiedType= fFullyQualifiedTypeName; if (qualifiedType.indexOf('.') != -1 && replacementString.startsWith(qualifiedType) && !replacementString.endsWith(String.valueOf(';'))) { IType[] types= impRewrite.getCompilationUnit().getTypes(); if (types.length > 0 && types[0].getSourceRange().getOffset() <= offset) { // ignore positions above type. setReplacementString(impRewrite.addImport(getReplacementString())); return true; } } } return false; }
Example #2
Source File: UnresolvedElementsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= problem.getOffset(); int len= problem.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) { String qualifiedTypeName= ((IType) curr).getFullyQualifiedName('.'); CompilationUnit root= context.getASTRoot(); String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, BasicElementLabels.getJavaElementName(qualifiedTypeName)); Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, ASTRewrite.create(root.getAST()), IProposalRelevance.IMPORT_EXPLICIT, image); ImportRewrite imports= proposal.createImportRewrite(root); imports.addImport(qualifiedTypeName); proposals.add(proposal); } } }
Example #3
Source File: OrganizeImportsOperation.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
public TypeReferenceProcessor(Set<String> oldSingleImports, Set<String> oldDemandImports, CompilationUnit root, ImportRewrite impStructure, boolean ignoreLowerCaseNames) { fOldSingleImports= oldSingleImports; fOldDemandImports= oldDemandImports; fImpStructure= impStructure; fDoIgnoreLowerCaseNames= ignoreLowerCaseNames; ICompilationUnit cu= impStructure.getCompilationUnit(); fImplicitImports= new HashSet<String>(3); fImplicitImports.add(""); //$NON-NLS-1$ fImplicitImports.add("java.lang"); //$NON-NLS-1$ fImplicitImports.add(cu.getParent().getElementName()); fAnalyzer= new ScopeAnalyzer(root); fCurrPackage= (IPackageFragment) cu.getParent(); fAllowDefaultPackageImports= cu.getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true).equals(JavaCore.VERSION_1_3); fImportsAdded= new HashSet<String>(); fUnresolvedTypes= new HashMap<String, UnresolvedTypeData>(); }
Example #4
Source File: ImplementInterfaceProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Override protected ASTRewrite getRewrite() throws CoreException { ASTNode boundNode= fAstRoot.findDeclaringNode(fBinding); ASTNode declNode= null; CompilationUnit newRoot= fAstRoot; if (boundNode != null) { declNode= boundNode; // is same CU } else { newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null); declNode= newRoot.findDeclaringNode(fBinding.getKey()); } ImportRewrite imports= createImportRewrite(newRoot); if (declNode instanceof TypeDeclaration) { AST ast= declNode.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(declNode, imports); Type newInterface= imports.addImport(fNewInterface, ast, importRewriteContext, TypeLocation.OTHER); ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); listRewrite.insertLast(newInterface, null); return rewrite; } return null; }
Example #5
Source File: UpdateAsyncSignatureProposal.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
@Override protected List<SingleVariableDeclaration> computeParams(AST ast, MethodDeclaration srcMethod, MethodDeclaration dstMethod, ImportRewrite imports) { // Clone the sync method parameters List<SingleVariableDeclaration> params = new ArrayList<SingleVariableDeclaration>(); params.addAll(JavaASTUtils.cloneParameters(ast, adjustSrcParams(srcMethod), imports)); // Append an AsyncCallback params.add(Util.createAsyncCallbackParameter(ast, srcMethod.getReturnType2(), computeCallBackName(dstMethod), imports)); return params; }
Example #6
Source File: MoveInnerToTopRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void addImportsToTargetUnit(final ICompilationUnit targetUnit, final IProgressMonitor monitor) throws CoreException, JavaModelException { monitor.beginTask("", 2); //$NON-NLS-1$ try { ImportRewrite rewrite= StubUtility.createImportRewrite(targetUnit, true); if (fTypeImports != null) { ITypeBinding type= null; for (final Iterator<ITypeBinding> iterator= fTypeImports.iterator(); iterator.hasNext();) { type= iterator.next(); rewrite.addImport(type); } } if (fStaticImports != null) { IBinding binding= null; for (final Iterator<IBinding> iterator= fStaticImports.iterator(); iterator.hasNext();) { binding= iterator.next(); rewrite.addStaticImport(binding); } } fTypeImports= null; fStaticImports= null; TextEdit edits= rewrite.rewriteImports(new SubProgressMonitor(monitor, 1)); JavaModelUtil.applyEdit(targetUnit, edits, false, new SubProgressMonitor(monitor, 1)); } finally { monitor.done(); } }
Example #7
Source File: ASTNodeFactory.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private static Type newType(LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method= lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding[] parameterTypes= method.getParameterTypes(); int index= lambdaExpression.parameters().indexOf(declaration); ITypeBinding typeBinding= parameterTypes[index]; if (importRewrite != null) { return importRewrite.addImport(typeBinding, ast, context); } else { String qualifiedName= typeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
Example #8
Source File: CompilationUnitRewrite.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
public ImportRewrite getImportRewrite() { if (fImportRewrite == null) { // lazily initialized to avoid lengthy processing in checkInitialConditions(..) try { /* If bindings are to be resolved, then create the AST, so that * ImportRewrite#setUseContextToFilterImplicitImports(boolean) will be set to true * and ContextSensitiveImportRewriteContext etc. can be used. */ if (fRoot == null && ! fResolveBindings) { fImportRewrite= StubUtility.createImportRewrite(fCu, true); } else { fImportRewrite= StubUtility.createImportRewrite(getRoot(), true); } } catch (CoreException e) { JavaPlugin.log(e); throw new IllegalStateException(e.getMessage()); // like ASTParser#createAST(..) does } } return fImportRewrite; }
Example #9
Source File: JavaASTUtils.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
/** * Generates the normalized form and adds the required imports for a given * {@link Type}. */ public static Type normalizeTypeAndAddImport(AST ast, Type type, ImportRewrite imports) { ITypeBinding binding = type.resolveBinding(); // Eliminate type variables in the generated type // TODO(): maybe leave the type variables, if we can verify that the type // parameters on the target type are exactly the same as those on the source // type (all names and type bounds are identical) if (JavaASTUtils.containsTypeVariable(type)) { binding = binding.getErasure(); } // Report the type binding to the import rewriter, which will record the // import and give us either a SimpleType or a QualifiedType to use. return imports.addImport(binding, ast); }
Example #10
Source File: SurroundWith.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void qualifyThisExpressions(ASTNode node, final ASTRewrite rewrite, final ImportRewrite importRewrite, final ImportRewriteContext importRewriteContext) { node.accept(new GenericVisitor() { /** * {@inheritDoc} */ @Override public boolean visit(ThisExpression thisExpr) { if (thisExpr.getQualifier() == null) { ITypeBinding typeBinding= thisExpr.resolveTypeBinding(); if (typeBinding != null) { String typeName= importRewrite.addImport(typeBinding.getTypeDeclaration(), importRewriteContext); SimpleName simpleName= thisExpr.getAST().newSimpleName(typeName); rewrite.set(thisExpr, ThisExpression.QUALIFIER_PROPERTY, simpleName, null); } } return super.visit(thisExpr); } }); }
Example #11
Source File: CodeStyleFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private static AddThisQualifierOperation getUnqualifiedFieldAccessResolveOperation(CompilationUnit compilationUnit, IProblemLocation problem) { SimpleName name= getName(compilationUnit, problem); if (name == null) return null; IBinding binding= name.resolveBinding(); if (binding == null || binding.getKind() != IBinding.VARIABLE) return null; ImportRewrite imports= StubUtility.createImportRewrite(compilationUnit, true); String replacement= getThisExpressionQualifier(((IVariableBinding) binding).getDeclaringClass(), imports, name); if (replacement == null) return null; if (replacement.length() == 0) replacement= null; return new AddThisQualifierOperation(replacement, name); }
Example #12
Source File: UnresolvedElementsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static void getAmbiguousTypeReferenceProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= problem.getOffset(); int len= problem.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) { String qualifiedTypeName= ((IType) curr).getFullyQualifiedName('.'); CompilationUnit root= context.getASTRoot(); String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, BasicElementLabels.getJavaElementName(qualifiedTypeName)); ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, ASTRewrite.create(root.getAST()), IProposalRelevance.IMPORT_EXPLICIT); ImportRewrite imports= proposal.createImportRewrite(root); imports.addImport(qualifiedTypeName); proposals.add(proposal); } } }
Example #13
Source File: GetterSetterCompletionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
/** * @param document * @param offset * @param importRewrite * @param completionSnippetsSupported * @param addComments * @return * @throws CoreException * @throws BadLocationException */ public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean completionSnippetsSupported, boolean addComments) throws CoreException, BadLocationException { int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic); String stub; if (fIsGetter) { String getterName= GetterSetterUtil.getGetterName(fField, null); stub = GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags); } else { String setterName= GetterSetterUtil.getSetterName(fField, null); stub = GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags); } // use the code formatter String lineDelim= TextUtilities.getDefaultLineDelimiter(document); String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, 0, lineDelim, fField.getJavaProject()); if (replacement.endsWith(lineDelim)) { replacement = replacement.substring(0, replacement.length() - lineDelim.length()); } return replacement; }
Example #14
Source File: ConvertAnonymousToNestedRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void addExceptionsToNewConstructor(MethodDeclaration newConstructor, ImportRewrite importRewrite) { IMethodBinding constructorBinding= getSuperConstructorBinding(); if (constructorBinding == null) return; ITypeBinding[] exceptions= constructorBinding.getExceptionTypes(); for (int i= 0; i < exceptions.length; i++) { Type exceptionType= importRewrite.addImport(exceptions[i], fAnonymousInnerClassNode.getAST()); newConstructor.thrownExceptionTypes().add(exceptionType); } }
Example #15
Source File: CallContext.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public CallContext(ASTNode inv, CodeScopeBuilder.Scope s, int cm, ImportRewrite i) { super(); invocation= inv; scope= s; callMode= cm; importer= i; }
Example #16
Source File: ContextSensitiveImportRewriteContext.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Creates an import rewrite context at the given start position. * * @param compilationUnit the root (must have resolved bindings) * @param position the context position * @param importRewrite the import rewrite */ public ContextSensitiveImportRewriteContext(CompilationUnit compilationUnit, int position, ImportRewrite importRewrite) { fCompilationUnit= compilationUnit; fPosition= position; fImportRewrite= importRewrite; fDeclarationsInScope= null; fImportedNames= null; }
Example #17
Source File: ChangeTypeRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * update a CompilationUnit's imports after changing the type of declarations * @param astRoot the AST * @param rootEdit the resulting edit * @return the type name to use * @throws CoreException */ private String updateImports(CompilationUnit astRoot, MultiTextEdit rootEdit) throws CoreException{ ImportRewrite rewrite= StubUtility.createImportRewrite(astRoot, true); ContextSensitiveImportRewriteContext context= new ContextSensitiveImportRewriteContext(astRoot, fSelectionStart, rewrite); String typeName= rewrite.addImport(fSelectedType.getQualifiedName(), context); rootEdit.addChild(rewrite.rewriteImports(null)); return typeName; }
Example #18
Source File: ASTNodeFactory.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public static Type newCreationType(AST ast, ITypeBinding typeBinding, ImportRewrite importRewrite, ImportRewriteContext importContext) { if (typeBinding.isParameterizedType()) { Type baseType= newCreationType(ast, typeBinding.getTypeDeclaration(), importRewrite, importContext); ParameterizedType parameterizedType= ast.newParameterizedType(baseType); for (ITypeBinding typeArgument : typeBinding.getTypeArguments()) { parameterizedType.typeArguments().add(newCreationType(ast, typeArgument, importRewrite, importContext)); } return parameterizedType; } else if (typeBinding.isParameterizedType()) { Type elementType= newCreationType(ast, typeBinding.getElementType(), importRewrite, importContext); ArrayType arrayType= ast.newArrayType(elementType, 0); while (typeBinding.isArray()) { Dimension dimension= ast.newDimension(); IAnnotationBinding[] typeAnnotations= typeBinding.getTypeAnnotations(); for (IAnnotationBinding typeAnnotation : typeAnnotations) { dimension.annotations().add(importRewrite.addAnnotation(typeAnnotation, ast, importContext)); } arrayType.dimensions().add(dimension); typeBinding= typeBinding.getComponentType(); } return arrayType; } else if (typeBinding.isWildcardType()) { ITypeBinding bound= typeBinding.getBound(); typeBinding= (bound != null) ? bound : typeBinding.getErasure(); return newCreationType(ast, typeBinding, importRewrite, importContext); } else { return importRewrite.addImport(typeBinding, ast, importContext); } }
Example #19
Source File: SourceProvider.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void updateStaticReferences(ASTRewrite rewriter, CallContext context) { ImportRewrite importer= context.importer; for (Iterator<SimpleName> iter= fAnalyzer.getStaticsToImport().iterator(); iter.hasNext();) { Name element= iter.next(); IBinding binding= element.resolveBinding(); if (binding != null) { String s= importer.addStaticImport(binding); if (!ASTNodes.asString(element).equals(s)) { rewriter.replace(element, rewriter.createStringPlaceholder(s, ASTNode.SIMPLE_NAME), null); } } } }
Example #20
Source File: MoveCuUpdateCreator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void addImportRewriteUpdates(TextChangeManager changeManager) throws CoreException { for (Iterator<ICompilationUnit> iter= fImportRewrites.keySet().iterator(); iter.hasNext();) { ICompilationUnit cu= iter.next(); ImportRewrite importRewrite= fImportRewrites.get(cu); if (importRewrite != null && importRewrite.hasRecordedChanges()) { TextChangeCompatibility.addTextEdit(changeManager.get(cu), RefactoringCoreMessages.MoveCuUpdateCreator_update_imports, importRewrite.rewriteImports(null)); } } }
Example #21
Source File: ChangeSignatureProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@Override public void updateNode() throws JavaModelException { ImportRewrite importRewrite= fCuRewrite.getImportRewrite(); QualifiedName name= (QualifiedName) fImportDecl.getName(); //will be removed by importRemover if not used elsewhere ... importRewrite.removeStaticImport(name.getFullyQualifiedName()); importRewrite.addStaticImport(name.getQualifier().getFullyQualifiedName(), fMethodName, false); }
Example #22
Source File: GeneratedCssResource.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
@Override public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite, ImportRewrite importRewrite, boolean addComments) throws CoreException { createType(clientBundle.getPackageFragment(), addComments); return super.createMethodDeclaration(clientBundle, astRewrite, importRewrite, addComments); }
Example #23
Source File: UpdateSyncSignatureProposal.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
@Override protected List<SingleVariableDeclaration> computeParams(AST ast, MethodDeclaration srcMethod, MethodDeclaration dstMethod, ImportRewrite imports) { // Just clone the adjusted async parameters List<SingleVariableDeclaration> params = new ArrayList<SingleVariableDeclaration>(); params.addAll(JavaASTUtils.cloneParameters(ast, adjustSrcParams(srcMethod), imports)); return params; }
Example #24
Source File: UpdateAsyncSignatureProposal.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
@Override protected Type computeReturnType(AST ast, MethodDeclaration srcMethod, MethodDeclaration dstMethod, ImportRewrite imports) { // Use the previous async return type if valid ITypeBinding typeBinding = dstMethod.getReturnType2().resolveBinding(); if (typeBinding != null && Util.VALID_ASYNC_RPC_RETURN_TYPES.contains(typeBinding.getQualifiedName())) { return JavaASTUtils.normalizeTypeAndAddImport(ast, dstMethod.getReturnType2(), imports); } return ast.newPrimitiveType(PrimitiveType.VOID); }
Example #25
Source File: TypeCreator.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
private String createTypeStub(ICompilationUnit cu, ImportRewrite imports) throws CoreException { StringBuffer buffer = new StringBuffer(); // Default modifiers is just: public buffer.append("public "); String type = ""; String templateID = ""; switch (elementType) { case CLASS: type = "class "; templateID = CodeGeneration.CLASS_BODY_TEMPLATE_ID; break; case INTERFACE: type = "interface "; templateID = CodeGeneration.INTERFACE_BODY_TEMPLATE_ID; break; } buffer.append(type); buffer.append(simpleTypeName); addInterfaces(buffer, imports); buffer.append(" {").append(lineDelimiter); // Generate the type body according to the template in preferences String typeBody = CodeGeneration.getTypeBody(templateID, cu, simpleTypeName, lineDelimiter); if (typeBody != null) { buffer.append(typeBody); } else { buffer.append(lineDelimiter); } buffer.append('}').append(lineDelimiter); return buffer.toString(); }
Example #26
Source File: SelfEncapsulateFieldRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void createEdits(ICompilationUnit unit, ASTRewrite rewriter, List<TextEditGroup> groups, ImportRewrite importRewrite) throws CoreException { TextChange change= fChangeManager.get(unit); MultiTextEdit root= new MultiTextEdit(); change.setEdit(root); root.addChild(importRewrite.rewriteImports(null)); root.addChild(rewriter.rewriteAST()); for (Iterator<TextEditGroup> iter= groups.iterator(); iter.hasNext();) { change.addTextEditGroup(iter.next()); } }
Example #27
Source File: JavaASTUtils.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
/** * Clones a method's parameter list. */ public static List<SingleVariableDeclaration> cloneParameters(AST ast, List<SingleVariableDeclaration> params, ImportRewrite imports) { List<SingleVariableDeclaration> newParams = new ArrayList<SingleVariableDeclaration>(); for (SingleVariableDeclaration param : params) { SingleVariableDeclaration newParam = cloneMethodParameter(ast, param, imports); newParams.add(newParam); } return newParams; }
Example #28
Source File: JavaASTUtils.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
/** * Clones the given parameter declaration. */ public static SingleVariableDeclaration cloneMethodParameter(AST ast, SingleVariableDeclaration param, ImportRewrite imports) { SingleVariableDeclaration newParam = ast.newSingleVariableDeclaration(); // New parameter has a normalized type equivalent to the original Type type = normalizeTypeAndAddImport(ast, param.getType(), imports); newParam.setType(type); // Give new parameter same name as the original newParam.setName(ast.newSimpleName(param.getName().getIdentifier())); return newParam; }
Example #29
Source File: OverrideMethodsOperation.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static TextEdit createTextEditForOverridableMethods(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding typeBinding, IMethodBinding[] methodBindings) throws CoreException { ASTRewrite astRewrite = ASTRewrite.create(astRoot.getAST()); ImportRewrite importRewrite = StubUtility.createImportRewrite(astRoot, true); ListRewrite listRewrite = null; ASTNode typeNode = astRoot.findDeclaringNode(typeBinding); if (typeNode instanceof AnonymousClassDeclaration) { listRewrite = astRewrite.getListRewrite(typeNode, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY); } else if (typeNode instanceof AbstractTypeDeclaration) { listRewrite = astRewrite.getListRewrite(typeNode, ((AbstractTypeDeclaration) typeNode).getBodyDeclarationsProperty()); } else { return null; } CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(cu.getResource()); ImportRewriteContext context = new ContextSensitiveImportRewriteContext(astRoot, typeNode.getStartPosition(), importRewrite); for (IMethodBinding methodBinding : methodBindings) { MethodDeclaration stub = StubUtility2Core.createImplementationStubCore(cu, astRewrite, importRewrite, context, methodBinding, typeBinding, settings, typeBinding.isInterface(), typeNode, false); if (stub != null) { listRewrite.insertLast(stub, null); } } MultiTextEdit edit = new MultiTextEdit(); edit.addChild(importRewrite.rewriteImports(null)); edit.addChild(astRewrite.rewriteAST()); return edit; }
Example #30
Source File: CastCorrectionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) { AST ast= rewrite.getAST(); ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite); if (fCastType != null) { return importRewrite.addImport(fCastType, ast,context); } ASTNode node= fNodeToCast; ASTNode parent= node.getParent(); if (parent instanceof CastExpression) { node= parent; parent= parent.getParent(); } while (parent instanceof ParenthesizedExpression) { node= parent; parent= parent.getParent(); } if (parent instanceof MethodInvocation) { MethodInvocation invocation= (MethodInvocation) node.getParent(); if (invocation.getExpression() == node) { IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node); ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext); if (bindings.length > 0) { ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding()); Type newTypeNode= importRewrite.addImport(first, ast, context); addLinkedPosition(rewrite.track(newTypeNode), true, "casttype"); //$NON-NLS-1$ for (int i= 0; i < bindings.length; i++) { addLinkedPositionProposal("casttype", bindings[i]); //$NON-NLS-1$ } return newTypeNode; } } } Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ addLinkedPosition(rewrite.track(newCastType), true, "casttype"); //$NON-NLS-1$ return newCastType; }