Search in sources :

Example 6 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project che by eclipse.

the class ConvertAnonymousToNestedRefactoring method getAllAccessedFields.

private List<IBinding> getAllAccessedFields() {
    final List<IBinding> accessedFields = new ArrayList<IBinding>();
    ASTVisitor visitor = new ASTVisitor() {

        @Override
        public boolean visit(FieldAccess node) {
            final IVariableBinding binding = node.resolveFieldBinding();
            if (binding != null && !binding.isEnumConstant())
                accessedFields.add(binding);
            return super.visit(node);
        }

        @Override
        public boolean visit(QualifiedName node) {
            final IBinding binding = node.resolveBinding();
            if (binding != null && binding instanceof IVariableBinding) {
                IVariableBinding variable = (IVariableBinding) binding;
                if (!variable.isEnumConstant() && variable.isField())
                    accessedFields.add(binding);
            }
            return super.visit(node);
        }

        @Override
        public boolean visit(SimpleName node) {
            final IBinding binding = node.resolveBinding();
            if (binding != null && binding instanceof IVariableBinding) {
                IVariableBinding variable = (IVariableBinding) binding;
                if (!variable.isEnumConstant() && variable.isField())
                    accessedFields.add(binding);
            }
            return super.visit(node);
        }

        @Override
        public boolean visit(SuperFieldAccess node) {
            final IVariableBinding binding = node.resolveFieldBinding();
            if (binding != null && !binding.isEnumConstant())
                accessedFields.add(binding);
            return super.visit(node);
        }
    };
    fAnonymousInnerClassNode.accept(visitor);
    return accessedFields;
}
Also used : IBinding(org.eclipse.jdt.core.dom.IBinding) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) SuperFieldAccess(org.eclipse.jdt.core.dom.SuperFieldAccess) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) SuperFieldAccess(org.eclipse.jdt.core.dom.SuperFieldAccess) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 7 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project flux by eclipse.

the class ASTNodes method getLeftMostSimpleName.

public static SimpleName getLeftMostSimpleName(Name name) {
    if (name instanceof SimpleName) {
        return (SimpleName) name;
    } else {
        final SimpleName[] result = new SimpleName[1];
        ASTVisitor visitor = new ASTVisitor() {

            @Override
            public boolean visit(QualifiedName qualifiedName) {
                Name left = qualifiedName.getQualifier();
                if (left instanceof SimpleName)
                    result[0] = (SimpleName) left;
                else
                    left.accept(this);
                return false;
            }
        };
        name.accept(visitor);
        return result[0];
    }
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name)

Example 8 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project flux by eclipse.

the class ASTNodes method getTypeName.

/**
	 * Returns the simple name of the type, followed by array dimensions.
	 * Skips qualifiers, type arguments, and type annotations.
	 * <p>
	 * Does <b>not</b> work for WildcardTypes, etc.!
	 * 
	 * @param type a type that has a simple name
	 * @return the simple name, followed by array dimensions
	 * @see #getSimpleNameIdentifier(Name)
	 * @since 3.10
	 */
public static String getTypeName(Type type) {
    final StringBuffer buffer = new StringBuffer();
    ASTVisitor visitor = new ASTVisitor() {

        @Override
        public boolean visit(PrimitiveType node) {
            buffer.append(node.getPrimitiveTypeCode().toString());
            return false;
        }

        @Override
        public boolean visit(SimpleType node) {
            buffer.append(getSimpleNameIdentifier(node.getName()));
            return false;
        }

        @Override
        public boolean visit(QualifiedType node) {
            buffer.append(node.getName().getIdentifier());
            return false;
        }

        @Override
        public boolean visit(NameQualifiedType node) {
            buffer.append(node.getName().getIdentifier());
            return false;
        }

        @Override
        public boolean visit(ParameterizedType node) {
            node.getType().accept(this);
            return false;
        }

        @Override
        public void endVisit(ArrayType node) {
            for (int i = 0; i < node.dimensions().size(); i++) {
                //$NON-NLS-1$
                buffer.append("[]");
            }
        }
    };
    type.accept(visitor);
    return buffer.toString();
}
Also used : ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 9 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project flux by eclipse.

the class AdvancedQuickAssistProcessor method getCastAndAssignIfStatementProposals.

private static boolean getCastAndAssignIfStatementProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    if (node instanceof IfStatement) {
        node = ((IfStatement) node).getExpression();
    } else if (node instanceof WhileStatement) {
        node = ((WhileStatement) node).getExpression();
    } else if (node instanceof Block) {
        List<Statement> statements = ((Block) node).statements();
        if (statements.size() > 0) {
            if (context.getSelectionOffset() > statements.get(0).getStartPosition()) {
                return false;
            }
        }
        ASTNode parent = node.getParent();
        Expression expression = null;
        if (parent instanceof IfStatement) {
            expression = ((IfStatement) parent).getExpression();
        } else if (parent instanceof WhileStatement) {
            expression = ((WhileStatement) parent).getExpression();
        } else {
            return false;
        }
        if (expression instanceof InstanceofExpression) {
            node = expression;
        } else {
            final ArrayList<InstanceofExpression> nodes = new ArrayList<InstanceofExpression>();
            expression.accept(new ASTVisitor() {

                @Override
                public boolean visit(InstanceofExpression instanceofExpression) {
                    nodes.add(instanceofExpression);
                    return false;
                }
            });
            if (nodes.size() != 1) {
                return false;
            }
            node = nodes.get(0);
        }
    } else {
        while (node != null && !(node instanceof InstanceofExpression) && !(node instanceof Statement)) {
            node = node.getParent();
        }
    }
    if (!(node instanceof InstanceofExpression)) {
        return false;
    }
    InstanceofExpression expression = (InstanceofExpression) node;
    // test that we are the expression of a 'while' or 'if'
    while (node.getParent() instanceof Expression) {
        node = node.getParent();
    }
    StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
    boolean negated = isNegated(expression);
    Statement body = null;
    ASTNode insertionPosition = null;
    if (negated) {
        insertionPosition = node.getParent();
        if (locationInParent == IfStatement.EXPRESSION_PROPERTY) {
            body = ((IfStatement) node.getParent()).getElseStatement();
            if (body != null) {
                negated = false;
            }
        }
        if (body == null && insertionPosition.getParent() instanceof Block) {
            body = (Statement) insertionPosition.getParent();
        }
    } else {
        if (locationInParent == IfStatement.EXPRESSION_PROPERTY) {
            body = ((IfStatement) node.getParent()).getThenStatement();
        } else if (locationInParent == WhileStatement.EXPRESSION_PROPERTY) {
            body = ((WhileStatement) node.getParent()).getBody();
        }
    }
    if (body == null) {
        return false;
    }
    Type originalType = expression.getRightOperand();
    if (originalType.resolveBinding() == null) {
        return false;
    }
    //  we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    //$NON-NLS-1$
    final String KEY_NAME = "name";
    //$NON-NLS-1$
    final String KEY_TYPE = "type";
    //
    AST ast = expression.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ICompilationUnit cu = context.getCompilationUnit();
    // prepare correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_castAndAssign;
    //		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
    LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CAST_AND_ASSIGN);
    // prepare possible variable names
    List<String> excludedNames = Arrays.asList(ASTResolving.getUsedVariableNames(body));
    String[] varNames = suggestLocalVariableNames(cu, originalType.resolveBinding(), excludedNames);
    for (int i = 0; i < varNames.length; i++) {
        proposal.addLinkedPositionProposal(KEY_NAME, varNames[i], null);
    }
    CastExpression castExpression = ast.newCastExpression();
    castExpression.setExpression((Expression) rewrite.createCopyTarget(expression.getLeftOperand()));
    castExpression.setType((Type) ASTNode.copySubtree(ast, originalType));
    // prepare new variable declaration
    VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName(varNames[0]));
    vdf.setInitializer(castExpression);
    // prepare new variable declaration statement
    VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
    vds.setType((Type) ASTNode.copySubtree(ast, originalType));
    // add new variable declaration statement
    if (negated) {
        ListRewrite listRewriter = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
        listRewriter.insertAfter(vds, insertionPosition, null);
    } else {
        if (body instanceof Block) {
            ListRewrite listRewriter = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
            listRewriter.insertAt(vds, 0, null);
        } else {
            Block newBlock = ast.newBlock();
            List<Statement> statements = newBlock.statements();
            statements.add(vds);
            statements.add((Statement) rewrite.createMoveTarget(body));
            rewrite.replace(body, newBlock, null);
        }
    }
    // setup linked positions
    proposal.addLinkedPosition(rewrite.track(vdf.getName()), true, KEY_NAME);
    proposal.addLinkedPosition(rewrite.track(vds.getType()), false, KEY_TYPE);
    proposal.addLinkedPosition(rewrite.track(castExpression.getType()), false, KEY_TYPE);
    // set cursor after expression statement
    proposal.setEndPosition(rewrite.track(vds));
    // add correction proposal
    resultingCollections.add(proposal);
    return true;
}
Also used : ArrayList(java.util.ArrayList) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IfStatement(org.eclipse.jdt.core.dom.IfStatement) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) AssertStatement(org.eclipse.jdt.core.dom.AssertStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) Block(org.eclipse.jdt.core.dom.Block) CastExpression(org.eclipse.jdt.core.dom.CastExpression) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 10 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project flux by eclipse.

the class RenameService method computeReferences.

public JSONArray computeReferences(String username, String resourcePath, int offset, int length) {
    try {
        ICompilationUnit unit = liveEditUnits.getLiveEditUnit(username, resourcePath);
        if (unit != null) {
            final ASTParser parser = ASTParser.newParser(AST.JLS4);
            // Parse the class as a compilation unit.
            parser.setKind(ASTParser.K_COMPILATION_UNIT);
            parser.setSource(unit);
            parser.setResolveBindings(true);
            // Return the compiled class as a compilation unit
            final ASTNode compilationUnit = parser.createAST(null);
            final ASTNode nameNode = NodeFinder.perform(compilationUnit, offset, length);
            final List<ASTNode> nodes = new ArrayList<ASTNode>();
            if (nameNode instanceof SimpleName) {
                compilationUnit.accept(new ASTVisitor() {

                    @Override
                    public boolean visit(SimpleName node) {
                        if (node.getIdentifier().equals(((SimpleName) nameNode).getIdentifier())) {
                            nodes.add(node);
                        }
                        return super.visit(node);
                    }
                });
            }
            JSONArray references = new JSONArray();
            for (ASTNode astNode : nodes) {
                JSONObject nodeObject = new JSONObject();
                nodeObject.put("offset", astNode.getStartPosition());
                nodeObject.put("length", astNode.getLength());
                references.put(nodeObject);
            }
            return references;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) JSONObject(org.json.JSONObject) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) ASTParser(org.eclipse.jdt.core.dom.ASTParser) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Aggregations

ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)23 SimpleName (org.eclipse.jdt.core.dom.SimpleName)14 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)9 ArrayList (java.util.ArrayList)8 ASTNode (org.eclipse.jdt.core.dom.ASTNode)8 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)8 Name (org.eclipse.jdt.core.dom.Name)7 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)5 ForStatement (org.eclipse.jdt.core.dom.ForStatement)5 IBinding (org.eclipse.jdt.core.dom.IBinding)5 SimpleType (org.eclipse.jdt.core.dom.SimpleType)5 Statement (org.eclipse.jdt.core.dom.Statement)5 LinkedList (java.util.LinkedList)4 ArrayType (org.eclipse.jdt.core.dom.ArrayType)4 Expression (org.eclipse.jdt.core.dom.Expression)4 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)4 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)4 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)4 ParameterizedType (org.eclipse.jdt.core.dom.ParameterizedType)4 QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)4