Search in sources :

Example 21 with ChildListPropertyDescriptor

use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project AutoRefactor by JnRouvignac.

the class Refactorings method getListRewrite.

private ListRewrite getListRewrite(ASTNode node, ChildListPropertyDescriptor listProperty) {
    final Pair<ASTNode, ChildListPropertyDescriptor> key = Pair.of(node, listProperty);
    ListRewrite listRewrite = listRewriteCache.get(key);
    if (listRewrite == null) {
        listRewrite = rewrite.getListRewrite(node, listProperty);
        listRewriteCache.put(key, listRewrite);
    }
    return listRewrite;
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor)

Example 22 with ChildListPropertyDescriptor

use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor 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.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.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)

Example 23 with ChildListPropertyDescriptor

use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project eclipse.jdt.ls by eclipse.

the class NewVariableCorrectionProposal method doAddField.

private ASTRewrite doAddField(CompilationUnit astRoot) {
    SimpleName node = fOriginalNode;
    boolean isInDifferentCU = false;
    ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
    if (newTypeDecl == null) {
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
        isInDifferentCU = true;
    }
    ImportRewrite imports = createImportRewrite(astRoot);
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);
    if (newTypeDecl != null) {
        AST ast = newTypeDecl.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
        fragment.setName(ast.newSimpleName(node.getIdentifier()));
        Type type = evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding, TypeLocation.FIELD);
        FieldDeclaration newDecl = ast.newFieldDeclaration(fragment);
        newDecl.setType(type);
        newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));
        if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
            fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
        }
        ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
        List<BodyDeclaration> decls = ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);
        int maxOffset = isInDifferentCU ? -1 : node.getStartPosition();
        int insertIndex = findFieldInsertIndex(decls, newDecl, maxOffset);
        ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
        listRewriter.insertAt(newDecl, insertIndex, null);
        return rewrite;
    }
    return null;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 24 with ChildListPropertyDescriptor

use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor 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(fJavaProject.getProject());
            MethodDeclaration stub = StubUtility2.createImplementationStub(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType, settings, declaringType.isInterface(), declaringType, snippetStringSupport);
            ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
            rewriter.insertFirst(stub, null);
            ITrackedNodePosition position = rewrite.track(stub);
            try {
                Map<String, String> options = fJavaProject.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);
            }
        }
    }
    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.ls.core.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.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.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 25 with ChildListPropertyDescriptor

use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project AutoRefactor by JnRouvignac.

the class ASTRewrite method getListRewrite.

/**
 * Get the list rewrite.
 *
 * @param node The node
 * @param listProperty The list property
 * @return the list rewrite.
 */
public ListRewrite getListRewrite(final ASTNode node, final ChildListPropertyDescriptor listProperty) {
    Pair<ASTNode, ChildListPropertyDescriptor> key = Pair.of(node, listProperty);
    ListRewrite listRewrite = listRewriteCache.get(key);
    if (listRewrite == null) {
        listRewrite = rewrite.getListRewrite(node, listProperty);
        listRewriteCache.put(key, listRewrite);
    }
    return listRewrite;
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor)

Aggregations

ChildListPropertyDescriptor (org.eclipse.jdt.core.dom.ChildListPropertyDescriptor)26 ASTNode (org.eclipse.jdt.core.dom.ASTNode)20 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)17 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)14 AST (org.eclipse.jdt.core.dom.AST)10 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)10 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)10 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)8 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)8 Expression (org.eclipse.jdt.core.dom.Expression)7 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)7 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)6 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)6 Statement (org.eclipse.jdt.core.dom.Statement)6 Type (org.eclipse.jdt.core.dom.Type)6 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)6 Block (org.eclipse.jdt.core.dom.Block)5 ForStatement (org.eclipse.jdt.core.dom.ForStatement)5 SimpleName (org.eclipse.jdt.core.dom.SimpleName)5 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)5