Search in sources :

Example 51 with IBinding

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

the class QuickAssistProcessor method getJoinVariableProposals.

private static boolean getJoinVariableProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    ASTNode parent = node.getParent();
    VariableDeclarationFragment fragment = null;
    boolean onFirstAccess = false;
    if (node instanceof SimpleName && node.getLocationInParent() == Assignment.LEFT_HAND_SIDE_PROPERTY) {
        onFirstAccess = true;
        SimpleName name = (SimpleName) node;
        IBinding binding = name.resolveBinding();
        if (!(binding instanceof IVariableBinding)) {
            return false;
        }
        ASTNode declaring = context.getASTRoot().findDeclaringNode(binding);
        if (declaring instanceof VariableDeclarationFragment) {
            fragment = (VariableDeclarationFragment) declaring;
        } else {
            return false;
        }
    } else if (parent instanceof VariableDeclarationFragment) {
        fragment = (VariableDeclarationFragment) parent;
    } else {
        return false;
    }
    IVariableBinding binding = fragment.resolveBinding();
    Expression initializer = fragment.getInitializer();
    if ((initializer != null && initializer.getNodeType() != ASTNode.NULL_LITERAL) || binding == null || binding.isField()) {
        return false;
    }
    if (!(fragment.getParent() instanceof VariableDeclarationStatement)) {
        return false;
    }
    VariableDeclarationStatement statement = (VariableDeclarationStatement) fragment.getParent();
    SimpleName[] names = LinkedNodeFinder.findByBinding(statement.getParent(), binding);
    if (names.length <= 1 || names[0] != fragment.getName()) {
        return false;
    }
    SimpleName firstAccess = names[1];
    if (onFirstAccess) {
        if (firstAccess != node) {
            return false;
        }
    } else {
        if (firstAccess.getLocationInParent() != Assignment.LEFT_HAND_SIDE_PROPERTY) {
            return false;
        }
    }
    Assignment assignment = (Assignment) firstAccess.getParent();
    if (assignment.getLocationInParent() != ExpressionStatement.EXPRESSION_PROPERTY) {
        return false;
    }
    ExpressionStatement assignParent = (ExpressionStatement) assignment.getParent();
    if (resultingCollections == null) {
        return true;
    }
    AST ast = statement.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    //		TightSourceRangeComputer sourceRangeComputer= new TightSourceRangeComputer();
    //		sourceRangeComputer.addTightSourceNode(assignParent);
    //		rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
    String label = CorrectionMessages.QuickAssistProcessor_joindeclaration_description;
    //		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
    LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_VARIABLE_DECLARATION);
    proposal.setCommandId(SPLIT_JOIN_VARIABLE_DECLARATION_ID);
    Expression placeholder = (Expression) rewrite.createMoveTarget(assignment.getRightHandSide());
    rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, placeholder, null);
    if (onFirstAccess) {
        // replace assignment with variable declaration
        rewrite.replace(assignParent, rewrite.createMoveTarget(statement), null);
    } else {
        // different scopes -> remove assignments, set variable initializer
        if (ASTNodes.isControlStatementBody(assignParent.getLocationInParent())) {
            Block block = ast.newBlock();
            rewrite.replace(assignParent, block, null);
        } else {
            rewrite.remove(assignParent, null);
        }
    }
    proposal.setEndPosition(rewrite.track(fragment.getName()));
    resultingCollections.add(proposal);
    return true;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Assignment(org.eclipse.jdt.core.dom.Assignment) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block)

Example 52 with IBinding

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

the class AdvancedQuickAssistProcessor method getInverseLocalVariableProposals.

private static boolean getInverseLocalVariableProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
    final AST ast = covering.getAST();
    // cursor should be placed on variable name
    if (!(covering instanceof SimpleName)) {
        return false;
    }
    SimpleName coveringName = (SimpleName) covering;
    if (!coveringName.isDeclaration()) {
        return false;
    }
    // prepare bindings
    final IBinding variableBinding = coveringName.resolveBinding();
    if (!(variableBinding instanceof IVariableBinding)) {
        return false;
    }
    IVariableBinding binding = (IVariableBinding) variableBinding;
    if (binding.isField()) {
        return false;
    }
    // we operate only on boolean variable
    if (!isBoolean(coveringName)) {
        return false;
    }
    //  we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    // find linked nodes
    final MethodDeclaration method = ASTResolving.findParentMethodDeclaration(covering);
    SimpleName[] linkedNodes = LinkedNodeFinder.findByBinding(method, variableBinding);
    //
    final ASTRewrite rewrite = ASTRewrite.create(ast);
    // create proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseBooleanVariable;
    //		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    //$NON-NLS-1$
    final String KEY_NAME = "name";
    final LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_BOOLEAN_VARIABLE);
    // prepare new variable identifier
    final String oldIdentifier = coveringName.getIdentifier();
    //$NON-NLS-1$
    final String notString = Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_negatedVariableName, "");
    final String newIdentifier;
    if (oldIdentifier.startsWith(notString)) {
        int notLength = notString.length();
        if (oldIdentifier.length() > notLength) {
            newIdentifier = Character.toLowerCase(oldIdentifier.charAt(notLength)) + oldIdentifier.substring(notLength + 1);
        } else {
            newIdentifier = oldIdentifier;
        }
    } else {
        newIdentifier = Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_negatedVariableName, Character.toUpperCase(oldIdentifier.charAt(0)) + oldIdentifier.substring(1));
    }
    //
    proposal.addLinkedPositionProposal(KEY_NAME, newIdentifier, null);
    proposal.addLinkedPositionProposal(KEY_NAME, oldIdentifier, null);
    // iterate over linked nodes and replace variable references with negated reference
    final HashSet<SimpleName> renamedNames = new HashSet<SimpleName>();
    for (int i = 0; i < linkedNodes.length; i++) {
        SimpleName name = linkedNodes[i];
        if (renamedNames.contains(name)) {
            continue;
        }
        // prepare new name with new identifier
        SimpleName newName = ast.newSimpleName(newIdentifier);
        proposal.addLinkedPosition(rewrite.track(newName), name == coveringName, KEY_NAME);
        //
        StructuralPropertyDescriptor location = name.getLocationInParent();
        if (location == SingleVariableDeclaration.NAME_PROPERTY) {
            // set new name
            rewrite.replace(name, newName, null);
        } else if (location == Assignment.LEFT_HAND_SIDE_PROPERTY) {
            Assignment assignment = (Assignment) name.getParent();
            Expression expression = assignment.getRightHandSide();
            int exStart = expression.getStartPosition();
            int exEnd = exStart + expression.getLength();
            // collect all names that are used in assignments
            HashSet<SimpleName> overlapNames = new HashSet<SimpleName>();
            for (int j = 0; j < linkedNodes.length; j++) {
                SimpleName name2 = linkedNodes[j];
                if (name2 == null) {
                    continue;
                }
                int name2Start = name2.getStartPosition();
                if (exStart <= name2Start && name2Start < exEnd) {
                    overlapNames.add(name2);
                }
            }
            // prepare inverted expression
            SimpleNameRenameProvider provider = new SimpleNameRenameProvider() {

                public SimpleName getRenamed(SimpleName simpleName) {
                    if (simpleName.resolveBinding() == variableBinding) {
                        renamedNames.add(simpleName);
                        return ast.newSimpleName(newIdentifier);
                    }
                    return null;
                }
            };
            Expression inversedExpression = getInversedExpression(rewrite, expression, provider);
            // if any name was not renamed during expression inverting, we can not already rename it, so fail to create assist
            for (Iterator<SimpleName> iter = overlapNames.iterator(); iter.hasNext(); ) {
                Object o = iter.next();
                if (!renamedNames.contains(o)) {
                    return false;
                }
            }
            // check operator and replace if needed
            Assignment.Operator operator = assignment.getOperator();
            if (operator == Assignment.Operator.BIT_AND_ASSIGN) {
                Assignment newAssignment = ast.newAssignment();
                newAssignment.setLeftHandSide(newName);
                newAssignment.setRightHandSide(inversedExpression);
                newAssignment.setOperator(Assignment.Operator.BIT_OR_ASSIGN);
                rewrite.replace(assignment, newAssignment, null);
            } else if (operator == Assignment.Operator.BIT_OR_ASSIGN) {
                Assignment newAssignment = ast.newAssignment();
                newAssignment.setLeftHandSide(newName);
                newAssignment.setRightHandSide(inversedExpression);
                newAssignment.setOperator(Assignment.Operator.BIT_AND_ASSIGN);
                rewrite.replace(assignment, newAssignment, null);
            } else {
                rewrite.replace(expression, inversedExpression, null);
                // set new name
                rewrite.replace(name, newName, null);
            }
        } else if (location == VariableDeclarationFragment.NAME_PROPERTY) {
            // replace initializer for variable
            VariableDeclarationFragment vdf = (VariableDeclarationFragment) name.getParent();
            Expression expression = vdf.getInitializer();
            if (expression != null) {
                rewrite.replace(expression, getInversedExpression(rewrite, expression), null);
            }
            // set new name
            rewrite.replace(name, newName, null);
        } else if (name.getParent() instanceof PrefixExpression && ((PrefixExpression) name.getParent()).getOperator() == PrefixExpression.Operator.NOT) {
            rewrite.replace(name.getParent(), newName, null);
        } else {
            PrefixExpression expression = ast.newPrefixExpression();
            expression.setOperator(PrefixExpression.Operator.NOT);
            expression.setOperand(newName);
            rewrite.replace(name, expression, null);
        }
    }
    // add correction proposal
    resultingCollections.add(proposal);
    return true;
}
Also used : Operator(org.eclipse.jdt.core.dom.InfixExpression.Operator) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Assignment(org.eclipse.jdt.core.dom.Assignment) 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) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) Iterator(java.util.Iterator) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) HashSet(java.util.HashSet) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 53 with IBinding

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

the class ScopeAnalyzer method getUsedVariableNames.

public Collection<String> getUsedVariableNames(int offset, int length) {
    HashSet<String> result = new HashSet<String>();
    IBinding[] bindingsBefore = getDeclarationsInScope(offset, VARIABLES);
    for (int i = 0; i < bindingsBefore.length; i++) {
        result.add(bindingsBefore[i].getName());
    }
    IBinding[] bindingsAfter = getDeclarationsAfter(offset + length, VARIABLES);
    for (int i = 0; i < bindingsAfter.length; i++) {
        result.add(bindingsAfter[i].getName());
    }
    List<ImportDeclaration> imports = fRoot.imports();
    for (int i = 0; i < imports.size(); i++) {
        ImportDeclaration decl = imports.get(i);
        if (decl.isStatic() && !decl.isOnDemand()) {
            result.add(ASTNodes.getSimpleNameIdentifier(decl.getName()));
        }
    }
    return result;
}
Also used : IBinding(org.eclipse.jdt.core.dom.IBinding) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) HashSet(java.util.HashSet)

Example 54 with IBinding

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

the class ScopeAnalyzer method getDeclarationsAfter.

public IBinding[] getDeclarationsAfter(int offset, int flags) {
    try {
        org.eclipse.jdt.core.dom.NodeFinder finder = new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0);
        ASTNode node = finder.getCoveringNode();
        if (node == null) {
            return null;
        }
        ASTNode declaration = ASTResolving.findParentStatement(node);
        while (declaration instanceof Statement && declaration.getNodeType() != ASTNode.BLOCK) {
            declaration = declaration.getParent();
        }
        if (declaration instanceof Block) {
            DefaultBindingRequestor requestor = new DefaultBindingRequestor();
            DeclarationsAfterVisitor visitor = new DeclarationsAfterVisitor(node.getStartPosition(), flags, requestor);
            declaration.accept(visitor);
            List<IBinding> result = requestor.getResult();
            return result.toArray(new IBinding[result.size()]);
        }
        return NO_BINDING;
    } finally {
        clearLists();
    }
}
Also used : SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) Statement(org.eclipse.jdt.core.dom.Statement) TypeDeclarationStatement(org.eclipse.jdt.core.dom.TypeDeclarationStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) IBinding(org.eclipse.jdt.core.dom.IBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block)

Example 55 with IBinding

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

the class VariableDeclarationFix method createChangeModifierToFinalFix.

public static VariableDeclarationFix createChangeModifierToFinalFix(final CompilationUnit compilationUnit, ASTNode[] selectedNodes) {
    HashMap<IBinding, List<SimpleName>> writtenNames = new HashMap<IBinding, List<SimpleName>>();
    WrittenNamesFinder finder = new WrittenNamesFinder(writtenNames);
    compilationUnit.accept(finder);
    List<ModifierChangeOperation> ops = new ArrayList<ModifierChangeOperation>();
    VariableDeclarationFinder visitor = new VariableDeclarationFinder(true, true, true, ops, writtenNames);
    if (selectedNodes.length == 1) {
        selectedNodes[0].accept(visitor);
    } else {
        for (int i = 0; i < selectedNodes.length; i++) {
            ASTNode selectedNode = selectedNodes[i];
            selectedNode.accept(visitor);
        }
    }
    if (ops.size() == 0)
        return null;
    CompilationUnitRewriteOperation[] result = ops.toArray(new CompilationUnitRewriteOperation[ops.size()]);
    String label;
    if (result.length == 1) {
        label = FixMessages.VariableDeclarationFix_changeModifierOfUnknownToFinal_description;
    } else {
        label = FixMessages.VariableDeclarationFix_ChangeMidifiersToFinalWherPossible_description;
    }
    return new VariableDeclarationFix(label, compilationUnit, result);
}
Also used : HashMap(java.util.HashMap) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

IBinding (org.eclipse.jdt.core.dom.IBinding)103 SimpleName (org.eclipse.jdt.core.dom.SimpleName)59 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)48 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)41 ASTNode (org.eclipse.jdt.core.dom.ASTNode)40 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)25 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)25 Name (org.eclipse.jdt.core.dom.Name)20 Expression (org.eclipse.jdt.core.dom.Expression)19 ArrayList (java.util.ArrayList)16 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)14 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)13 CastExpression (org.eclipse.jdt.core.dom.CastExpression)12 FieldAccess (org.eclipse.jdt.core.dom.FieldAccess)11 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)11 QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)11 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)11 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)11 AST (org.eclipse.jdt.core.dom.AST)10 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)10