Search in sources :

Example 86 with ImportRewriteContext

use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project eclipse.jdt.ls by eclipse.

the class ExtractConstantRefactoring method getConstantType.

private Type getConstantType() throws JavaModelException {
    if (fConstantTypeCache == null) {
        IExpressionFragment fragment = getSelectedExpression();
        ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
        AST ast = fCuRewrite.getAST();
        typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
        ImportRewrite importRewrite = fCuRewrite.getImportRewrite();
        ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), fSelectionStart, importRewrite);
        fConstantTypeCache = importRewrite.addImport(typeBinding, ast, context, TypeLocation.FIELD);
    }
    return fConstantTypeCache;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IExpressionFragment(org.eclipse.jdt.internal.corext.dom.fragments.IExpressionFragment) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Example 87 with ImportRewriteContext

use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project eclipse.jdt.ls by eclipse.

the class OverrideCompletionProposal method updateReplacementString.

/*
	 * @see JavaTypeCompletionProposal#updateReplacementString(IDocument,char,int,ImportRewrite)
	 */
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean snippetStringSupport) throws CoreException, BadLocationException {
    Document recoveredDocument = new Document();
    CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);
    ITypeBinding declaringType = null;
    ChildListPropertyDescriptor descriptor = null;
    ASTNode node = NodeFinder.perform(unit, offset, 1);
    node = ASTResolving.findParentType(node);
    String result = null;
    if (node instanceof AnonymousClassDeclaration) {
        declaringType = ((AnonymousClassDeclaration) node).resolveBinding();
        descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
    } else if (node instanceof AbstractTypeDeclaration) {
        AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) node;
        descriptor = declaration.getBodyDeclarationsProperty();
        declaringType = declaration.resolveBinding();
    }
    if (declaringType != null) {
        ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
        IMethodBinding methodToOverride = Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
        if (methodToOverride == null && declaringType.isInterface()) {
            // $NON-NLS-1$
            methodToOverride = Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes);
        }
        if (methodToOverride != null) {
            CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fCompilationUnit);
            MethodDeclaration stub = StubUtility2Core.createImplementationStubCore(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType, settings, declaringType.isInterface(), node, snippetStringSupport);
            ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
            rewriter.insertFirst(stub, null);
            ITrackedNodePosition position = rewrite.track(stub);
            try {
                Map<String, String> options = fCompilationUnit.getOptions(true);
                rewrite.rewriteAST(recoveredDocument, options).apply(recoveredDocument);
                String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
                String indentAt = getIndentAt(recoveredDocument, position.getStartPosition(), settings);
                int generatedIndent = IndentManipulation.measureIndentUnits(indentAt, settings.tabWidth, settings.indentWidth);
                // Kinda fishy but empirical data shows Override needs to change indent by at
                // least 1
                generatedIndent = Math.max(1, generatedIndent);
                // Cancel generated code indent
                String delimiter = TextUtilities.getDefaultLineDelimiter(document);
                result = IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth, settings.indentWidth, "", delimiter);
            } catch (MalformedTreeException | BadLocationException exception) {
                JavaLanguageServerPlugin.logException("Unable to compute override proposal", exception);
            }
        }
    }
    if (result == null) {
        return replacementString;
    }
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) BadLocationException(org.eclipse.jface.text.BadLocationException) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 88 with ImportRewriteContext

use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project eclipse.jdt.ls by eclipse.

the class ConstructorFromSuperclassProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    AST ast = fTypeNode.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    createImportRewrite((CompilationUnit) fTypeNode.getRoot());
    CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit());
    if (!settings.createComments) {
        settings = null;
    }
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(fTypeNode, getImportRewrite());
    MethodDeclaration newMethodDecl = createNewMethodDeclaration(ast, fSuperConstructor, rewrite, importRewriteContext, settings);
    rewrite.getListRewrite(fTypeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY).insertFirst(newMethodDecl, null);
    addLinkedRanges(rewrite, newMethodDecl);
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 89 with ImportRewriteContext

use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project eclipse.jdt.ls by eclipse.

the class ImplementInterfaceProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    ASTNode boundNode = fAstRoot.findDeclaringNode(fBinding);
    ASTNode declNode = null;
    CompilationUnit newRoot = fAstRoot;
    if (boundNode != null) {
        // is same CU
        declNode = boundNode;
    } 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;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration)

Example 90 with ImportRewriteContext

use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project eclipse.jdt.ls by eclipse.

the class NewVariableCorrectionProposal method doAddLocal.

private ASTRewrite doAddLocal(CompilationUnit cu) {
    AST ast = cu.getAST();
    Block body;
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(fOriginalNode);
    IBinding targetContext = null;
    if (decl instanceof MethodDeclaration) {
        body = (((MethodDeclaration) decl).getBody());
        targetContext = ((MethodDeclaration) decl).resolveBinding();
    } else if (decl instanceof Initializer) {
        body = (((Initializer) decl).getBody());
        targetContext = Bindings.getBindingOfParentType(decl);
    } else {
        return null;
    }
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
    SimpleName[] names = getAllReferences(body);
    ASTNode dominant = getDominantNode(names);
    Statement dominantStatement = ASTResolving.findParentStatement(dominant);
    if (ASTNodes.isControlStatementBody(dominantStatement.getLocationInParent())) {
        dominantStatement = (Statement) dominantStatement.getParent();
    }
    SimpleName node = names[0];
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
    if (isAssigned(dominantStatement, node)) {
        // x = 1; -> int x = 1;
        Assignment assignment = (Assignment) node.getParent();
        // trick to avoid comment removal around the statement: keep the expression statement
        // and replace the assignment with an VariableDeclarationExpression
        VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
        VariableDeclarationExpression newDecl = ast.newVariableDeclarationExpression(newDeclFrag);
        newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
        Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
        newDeclFrag.setInitializer(placeholder);
        newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
        rewrite.replace(assignment, newDecl, null);
        return rewrite;
    } else if ((dominant != dominantStatement) && isForStatementInit(dominantStatement, node)) {
        // for (x = 1;;) ->for (int x = 1;;)
        Assignment assignment = (Assignment) node.getParent();
        VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
        VariableDeclarationExpression expression = ast.newVariableDeclarationExpression(frag);
        frag.setName(ast.newSimpleName(node.getIdentifier()));
        Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
        frag.setInitializer(placeholder);
        expression.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
        rewrite.replace(assignment, expression, null);
        return rewrite;
    } else if ((dominant != dominantStatement) && isEnhancedForStatementVariable(dominantStatement, node)) {
        // for (x: collectionOfT) -> for (T x: collectionOfT)
        EnhancedForStatement enhancedForStatement = (EnhancedForStatement) dominantStatement;
        SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
        Expression expression = enhancedForStatement.getExpression();
        SimpleName newName = (SimpleName) rewrite.createMoveTarget(node);
        rewrite.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, newName, null);
        ITypeBinding elementBinding = null;
        ITypeBinding typeBinding = expression.resolveTypeBinding();
        if (typeBinding != null) {
            if (typeBinding.isArray()) {
                elementBinding = typeBinding.getElementType();
            } else {
                // $NON-NLS-1$
                ITypeBinding iterable = Bindings.findTypeInHierarchy(typeBinding, "java.lang.Iterable");
                if (iterable != null) {
                    ITypeBinding[] typeArguments = iterable.getTypeArguments();
                    if (typeArguments.length == 1) {
                        elementBinding = typeArguments[0];
                        elementBinding = Bindings.normalizeForDeclarationUse(elementBinding, ast);
                    }
                }
            }
        }
        Type type;
        if (elementBinding != null) {
            type = imports.addImport(elementBinding, ast, importRewriteContext, TypeLocation.LOCAL_VARIABLE);
        } else {
            // $NON-NLS-1$
            type = ast.newSimpleType(ast.newSimpleName("Object"));
        }
        rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
        return rewrite;
    }
    // foo(x) -> int x; foo(x)
    VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
    VariableDeclarationStatement newDecl = ast.newVariableDeclarationStatement(newDeclFrag);
    newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
    newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
    // newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
    Statement statement = dominantStatement;
    List<? extends ASTNode> list = ASTNodes.getContainingList(statement);
    while (list == null && statement.getParent() instanceof Statement) {
        // parent must be if, for or while
        statement = (Statement) statement.getParent();
        list = ASTNodes.getContainingList(statement);
    }
    if (list != null) {
        ASTNode parent = statement.getParent();
        StructuralPropertyDescriptor childProperty = statement.getLocationInParent();
        if (childProperty.isChildListProperty()) {
            rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) childProperty).insertBefore(newDecl, statement, null);
            return rewrite;
        } else {
            return null;
        }
    }
    return rewrite;
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) IBinding(org.eclipse.jdt.core.dom.IBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Assignment(org.eclipse.jdt.core.dom.Assignment) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Initializer(org.eclipse.jdt.core.dom.Initializer) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Aggregations

ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)91 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)80 AST (org.eclipse.jdt.core.dom.AST)65 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)60 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)56 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)55 ASTNode (org.eclipse.jdt.core.dom.ASTNode)50 Type (org.eclipse.jdt.core.dom.Type)48 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)40 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)35 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)34 Expression (org.eclipse.jdt.core.dom.Expression)31 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)31 SimpleName (org.eclipse.jdt.core.dom.SimpleName)29 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)23 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)22 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)22 CastExpression (org.eclipse.jdt.core.dom.CastExpression)18 Javadoc (org.eclipse.jdt.core.dom.Javadoc)18 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)17