Example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite createCopyTarget

List of usage examples for org.eclipse.jdt.core.dom.rewrite ASTRewrite createCopyTarget

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite createCopyTarget.

Prototype

public final ASTNode createCopyTarget(ASTNode node) 

Source Link

Document

Creates and returns a placeholder node for a true copy of the given node.

Usage

From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.CreateDoPrivilegedBlockResolution.java

License:Open Source License

private ParameterizedType createPrivilegedActionType(ASTRewrite rewrite,
        ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();//  w  w w  .  j  a  va  2 s.com

    Name privilegedActionName;
    if (isUpdateImports()) {
        privilegedActionName = ast.newSimpleName(PrivilegedAction.class.getSimpleName());
    } else {
        privilegedActionName = ast.newName(PrivilegedAction.class.getName());
    }
    SimpleType rawPrivilegedActionType = ast.newSimpleType(privilegedActionName);
    ParameterizedType privilegedActionType = ast.newParameterizedType(rawPrivilegedActionType);
    Type typeArgument = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
    List<Type> typeArguments = checkedList(privilegedActionType.typeArguments());

    typeArguments.add(typeArgument);

    return privilegedActionType;
}

From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.CreateDoPrivilegedBlockResolution.java

License:Open Source License

private MethodDeclaration createRunMethodDeclaration(ASTRewrite rewrite,
        ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();/* www. j ava  2 s . co m*/

    MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
    SimpleName methodName = ast.newSimpleName("run");
    Type returnType = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
    Block methodBody = createRunMethodBody(rewrite, classLoaderCreation);
    List<Modifier> modifiers = checkedList(methodDeclaration.modifiers());

    modifiers.add(ast.newModifier(PUBLIC_KEYWORD));
    methodDeclaration.setName(methodName);
    methodDeclaration.setReturnType2(returnType);
    methodDeclaration.setBody(methodBody);

    return methodDeclaration;
}

From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.CreateDoPrivilegedBlockResolution.java

License:Open Source License

private Block createRunMethodBody(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();/*from www.j  av a  2  s. c o m*/

    Block methodBody = ast.newBlock();
    ReturnStatement returnStatement = ast.newReturnStatement();
    List<Statement> statements = checkedList(methodBody.statements());

    statements.add(returnStatement);
    returnStatement.setExpression((ClassInstanceCreation) rewrite.createCopyTarget(classLoaderCreation));

    return methodBody;
}

From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.CreateSuperCallResolution.java

License:Open Source License

protected SuperMethodInvocation createSuperMethodInvocation(ASTRewrite rewrite, MethodDeclaration method) {
    Assert.isNotNull(rewrite);//from w w  w.  j  a  va 2  s.c om
    Assert.isNotNull(method);

    AST ast = rewrite.getAST();
    SuperMethodInvocation invocation = ast.newSuperMethodInvocation();

    invocation.setName((SimpleName) rewrite.createCopyTarget(method.getName()));

    return invocation;
}

From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.UseValueOfResolution.java

License:Open Source License

protected MethodInvocation createValueOfInvocation(ASTRewrite rewrite, CompilationUnit compilationUnit,
        ClassInstanceCreation primitiveTypeCreation) {
    Assert.isNotNull(rewrite);/* w w w.  ja v  a2  s .  c o m*/
    Assert.isNotNull(primitiveTypeCreation);

    final AST ast = rewrite.getAST();
    MethodInvocation valueOfInvocation = ast.newMethodInvocation();
    valueOfInvocation.setName(ast.newSimpleName(VALUE_OF_METHOD_NAME));

    ITypeBinding binding = primitiveTypeCreation.getType().resolveBinding();
    if (isStaticImport()) {
        addStaticImports(rewrite, compilationUnit, binding.getQualifiedName() + "." + VALUE_OF_METHOD_NAME);
    } else {
        valueOfInvocation.setExpression(ast.newSimpleName(binding.getName()));
    }

    List<?> arguments = primitiveTypeCreation.arguments();
    List<Expression> newArguments = valueOfInvocation.arguments();
    for (Object argument : arguments) {
        Expression expression = (Expression) rewrite.createCopyTarget((ASTNode) argument);
        newArguments.add(expression);
    }

    return valueOfInvocation;
}

From source file:edu.umd.cs.findbugs.quickfix.resolution.CreateSuperCallResolution.java

License:Open Source License

protected SuperMethodInvocation createSuperMethodInvocation(ASTRewrite rewrite, MethodDeclaration method) {
    assert rewrite != null;
    assert method != null;

    AST ast = rewrite.getAST();// ww  w  . j  a  v  a 2 s.  co m
    SuperMethodInvocation invocation = ast.newSuperMethodInvocation();

    invocation.setName((SimpleName) rewrite.createCopyTarget(method.getName()));

    return invocation;
}

From source file:edu.umd.cs.findbugs.quickfix.resolution.UseValueOfResolution.java

License:Open Source License

protected MethodInvocation createValueOfInvocation(ASTRewrite rewrite, CompilationUnit compilationUnit,
        ClassInstanceCreation primitiveTypeCreation) {
    assert rewrite != null;
    assert primitiveTypeCreation != null;

    final AST ast = rewrite.getAST();
    MethodInvocation valueOfInvocation = ast.newMethodInvocation();
    valueOfInvocation.setName(ast.newSimpleName(VALUE_OF_METHOD_NAME));

    ITypeBinding binding = primitiveTypeCreation.getType().resolveBinding();
    if (isStaticImport()) {
        addStaticImports(rewrite, compilationUnit, binding.getQualifiedName() + "." + VALUE_OF_METHOD_NAME);
    } else {//from  w w  w  .ja v a 2 s  .  co  m
        valueOfInvocation.setExpression(ast.newSimpleName(binding.getName()));
    }

    List<?> arguments = primitiveTypeCreation.arguments();
    List<Expression> newArguments = valueOfInvocation.arguments();
    for (Object argument : arguments) {
        Expression expression = (Expression) rewrite.createCopyTarget((ASTNode) argument);
        newArguments.add(expression);
    }

    return valueOfInvocation;
}

From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.UnresolvedElementsSubProcessor.java

License:Open Source License

private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression,
        Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes,
        Collection proposals) {//from  w  ww  .  java  2s. c o  m
    ITypeBinding castType = expression.getType().resolveBinding();
    if (castType == null) {
        return false;
    }
    if (paramTypes != null) {
        if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
            return false;
        }
    } else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
        return false;
    }
    ITypeBinding bindingToCast = accessExpression.resolveTypeBinding();
    if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
        return false;
    }

    IMethodBinding res = Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
    if (res != null) {
        AST ast = expression.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        CastExpression newCast = ast.newCastExpression();
        newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
        newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
        ParenthesizedExpression parents = ast.newParenthesizedExpression();
        parents.setExpression(newCast);

        ASTNode node = rewrite.createCopyTarget(expression.getExpression());
        rewrite.replace(expression, node, null);
        rewrite.replace(accessExpression, parents, null);

        String label = CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image);
        proposals.add(proposal);
        return true;
    }
    return false;
}

From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.UnresolvedElementsSubProcessor.java

License:Open Source License

private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode,
        IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding,
        Collection proposals) throws CoreException {
    ITypeBinding[] paramTypes = methodBinding.getParameterTypes();
    int[] indexOfDiff = new int[paramTypes.length];
    int nDiffs = 0;
    for (int n = 0; n < argTypes.length; n++) {
        if (!canAssign(argTypes[n], paramTypes[n])) {
            indexOfDiff[nDiffs++] = n;// w  w  w  . j  a  v  a2s .  c  o  m
        }
    }
    ITypeBinding declaringTypeDecl = methodBinding.getDeclaringClass().getTypeDeclaration();

    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();

    ASTNode nameNode = problem.getCoveringNode(astRoot);
    if (nameNode == null) {
        return;
    }

    if (nDiffs == 0) {
        if (nameNode.getParent() instanceof MethodInvocation) {
            MethodInvocation inv = (MethodInvocation) nameNode.getParent();
            if (inv.getExpression() == null) {
                addQualifierToOuterProposal(context, inv, methodBinding, proposals);
            }
        }
        return;
    }

    if (nDiffs == 1) { // one argument mismatching: try to fix
        int idx = indexOfDiff[0];
        Expression nodeToCast = (Expression) arguments.get(idx);
        ITypeBinding castType = paramTypes[idx];
        castType = Bindings.normalizeTypeBinding(castType);
        if (castType.isWildcardType()) {
            castType = ASTResolving.normalizeWildcardType(castType, false, nodeToCast.getAST());
        }
        if (castType != null) {
            ITypeBinding binding = nodeToCast.resolveTypeBinding();
            if (binding == null || binding.isCastCompatible(castType)) {
                ASTRewriteCorrectionProposal proposal = TypeMismatchSubProcessor.createCastProposal(context,
                        castType, nodeToCast, 6);
                String castTypeName = BindingLabelProvider.getBindingLabel(castType,
                        JavaElementLabels.ALL_DEFAULT);
                String[] arg = new String[] { getArgumentName(cu, arguments, idx), castTypeName };
                proposal.setDisplayName(Messages.format(
                        CorrectionMessages.UnresolvedElementsSubProcessor_addargumentcast_description, arg));
                proposals.add(proposal);
            }
            TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, nodeToCast, castType, false, 5,
                    proposals);
        }
    }
    if (nDiffs == 2) { // try to swap
        int idx1 = indexOfDiff[0];
        int idx2 = indexOfDiff[1];
        boolean canSwap = canAssign(argTypes[idx1], paramTypes[idx2])
                && canAssign(argTypes[idx2], paramTypes[idx1]);
        if (canSwap) {
            Expression arg1 = (Expression) arguments.get(idx1);
            Expression arg2 = (Expression) arguments.get(idx2);

            ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
            rewrite.replace(arg1, rewrite.createCopyTarget(arg2), null);
            rewrite.replace(arg2, rewrite.createCopyTarget(arg1), null);
            {
                String[] arg = new String[] { getArgumentName(cu, arguments, idx1),
                        getArgumentName(cu, arguments, idx2) };
                String label = Messages.format(
                        CorrectionMessages.UnresolvedElementsSubProcessor_swaparguments_description, arg);
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label,
                        context.getCompilationUnit(), rewrite, 8, image);
                proposals.add(proposal);
            }

            if (declaringTypeDecl.isFromSource()) {
                ICompilationUnit targetCU = ASTResolving.findCompilationUnitForBinding(cu, astRoot,
                        declaringTypeDecl);
                if (targetCU != null) {
                    ChangeDescription[] changeDesc = new ChangeDescription[paramTypes.length];
                    for (int i = 0; i < nDiffs; i++) {
                        changeDesc[idx1] = new SwapDescription(idx2);
                    }
                    IMethodBinding methodDecl = methodBinding.getMethodDeclaration();
                    ITypeBinding[] declParamTypes = methodDecl.getParameterTypes();

                    ITypeBinding[] swappedTypes = new ITypeBinding[] { declParamTypes[idx1],
                            declParamTypes[idx2] };
                    /* AJDT 1.7 */
                    String[] args = new String[] { ASTResolving.getMethodSignature(methodDecl),
                            getTypeNames(swappedTypes) }; /* AJDT 1.7 */
                    String label;
                    if (methodDecl.isConstructor()) {
                        label = Messages.format(
                                CorrectionMessages.UnresolvedElementsSubProcessor_swapparams_constr_description,
                                args);
                    } else {
                        label = Messages.format(
                                CorrectionMessages.UnresolvedElementsSubProcessor_swapparams_description, args);
                    }
                    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                    ChangeMethodSignatureProposal proposal = new ChangeMethodSignatureProposal(label, targetCU,
                            invocationNode, methodDecl, changeDesc, null, 5, image);
                    proposals.add(proposal);
                }
            }
            return;
        }
    }

    if (declaringTypeDecl.isFromSource()) {
        ICompilationUnit targetCU = ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringTypeDecl);
        if (targetCU != null) {
            ChangeDescription[] changeDesc = createSignatureChangeDescription(indexOfDiff, nDiffs, paramTypes,
                    arguments, argTypes);
            if (changeDesc != null) {

                IMethodBinding methodDecl = methodBinding.getMethodDeclaration();
                ITypeBinding[] declParamTypes = methodDecl.getParameterTypes();

                ITypeBinding[] newParamTypes = new ITypeBinding[changeDesc.length];
                for (int i = 0; i < newParamTypes.length; i++) {
                    newParamTypes[i] = changeDesc[i] == null ? declParamTypes[i]
                            : ((EditDescription) changeDesc[i]).type;
                }

                /* AJDT 1.7 */
                String[] args = new String[] { ASTResolving.getMethodSignature(methodDecl), ASTResolving
                        .getMethodSignature(methodDecl.getName(), newParamTypes, false) }; /* AJDT 1.7 */
                String label;
                if (methodDecl.isConstructor()) {
                    label = Messages.format(
                            CorrectionMessages.UnresolvedElementsSubProcessor_changeparamsignature_constr_description,
                            args);
                } else {
                    label = Messages.format(
                            CorrectionMessages.UnresolvedElementsSubProcessor_changeparamsignature_description,
                            args);
                }
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                ChangeMethodSignatureProposal proposal = new ChangeMethodSignatureProposal(label, targetCU,
                        invocationNode, methodDecl, changeDesc, null, 7, image);
                proposals.add(proposal);
            }
        }
    }
}

From source file:org.eclipse.core.tools.nls.MessageBundleRefactoring.java

License:Open Source License

private void processAST(RefactoringStatus result, final CompilationUnit root, final ASTRewrite rewriter,
        SubProgressMonitor monitor) {//w  w w  .  j  a va 2 s.  co  m
    // keep track of the number of changes we make per line so we can get rid of the NLS comments.
    final IntegerMap map = new IntegerMap(10);
    ASTVisitor visitor = new ASTVisitor() {
        public boolean visit(MethodInvocation node) {
            Name messageBundleName = getMessageBundleReceiver(node);
            if (messageBundleName == null)
                return true;
            IMethodBinding method = node.resolveMethodBinding();
            // TODO here we have to do some checks whether the called method on the
            // resource bundle is something we have to rewrite. This depends on
            // the kind of the bundle and needs some AI.
            ITypeBinding[] params = method.getParameterTypes();
            if (params.length == 0)
                return true;
            if (!"java.lang.String".equals(params[0].getQualifiedName()))
                return true;
            List args = node.arguments();
            if (args.size() != 1)
                return true;
            Object obj = args.get(0);
            if (!(obj instanceof StringLiteral))
                return true;
            // compute the key of the message property
            StringLiteral string = (StringLiteral) obj;
            String key = PropertyFileConverter.convertToJavaIdentifier(string.getLiteralValue());

            // create the field access object
            FieldAccess fieldAccess = root.getAST().newFieldAccess();
            fieldAccess.setExpression((Expression) rewriter.createCopyTarget(messageBundleName));
            fieldAccess.setName(root.getAST().newSimpleName(key));

            // replace the method invocation with the field access
            rewriter.replace(node, fieldAccess, null);
            int line = 11;
            int value = map.get(line);
            value++;
            map.put(line, value);
            return true;
        }

        private Name getMessageBundleReceiver(MethodInvocation node) {
            Expression expression = node.getExpression();
            if (expression == null)
                return null;
            if (expression instanceof Name
                    && Bindings.equals(fAccessorTypeBinding, ((Name) expression).resolveBinding())) {
                return (Name) expression;
            }
            return null;
        }
    };
    root.accept(visitor);

    // create another visitor to trim the //$NON-NLS-N$ comments
    //      visitor = new ASTVisitor() {
    //         public boolean visit(LineComment node) {
    //            return true;
    //         }
    //      };
    //      root.accept(visitor);
}