Example usage for org.eclipse.jdt.core.dom ClassInstanceCreation setExpression

List of usage examples for org.eclipse.jdt.core.dom ClassInstanceCreation setExpression

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom ClassInstanceCreation setExpression.

Prototype

public void setExpression(Expression expression) 

Source Link

Document

Sets or clears the expression of this class instance creation expression.

Usage

From source file:java5totext.input.JDTVisitor.java

License:Open Source License

@Override
public void endVisit(org.eclipse.jdt.core.dom.ClassInstanceCreation node) {
    ClassInstanceCreation element = (ClassInstanceCreation) this.binding.get(node);
    this.initializeNode(element, node);

    MethodDeclaration anonymousConstructor = null;

    if (this.binding.get(node.getAnonymousClassDeclaration()) != null) {
        AnonymousClassDeclaration anoDecl = (AnonymousClassDeclaration) this.binding
                .get(node.getAnonymousClassDeclaration());
        element.setAnonymousClassDeclaration(anoDecl);
        anonymousConstructor = this.factory.createMethodDeclaration();
        anonymousConstructor.setProxy(true);
        anonymousConstructor.setName("");
        anoDecl.getBodyDeclarations().add(anonymousConstructor);
    }/*from  w  w w  .  j av a 2  s .c  o  m*/

    if (this.binding.get(node.getType()) != null)
        element.setType((NamedElementRef) this.binding.get(node.getType()));
    for (Iterator<?> i = node.arguments().iterator(); i.hasNext();) {
        Expression itElement = (Expression) this.binding.get(i.next());
        if (itElement != null)
            element.getArguments().add(itElement);
    }

    if (this.binding.get(node.getExpression()) != null)
        element.setExpression((Expression) this.binding.get(node.getExpression()));

    NamedElementRef constructorRef = this.factory.createNamedElementRef();
    element.setMethod(constructorRef);

    //if it is an anonymous class declaration we directly use the anonymous constructor
    if (anonymousConstructor != null) {
        constructorRef.setElement(anonymousConstructor);
    }

    else
        JDTVisitorUtils.manageBindingRef(constructorRef, node, this);

    /*original code for this method
    ClassInstanceCreation element= (ClassInstanceCreation)binding.get(node);
    if (binding.get(node.getAnonymousClassDeclaration()) != null)
       element.setAnonymousClassDeclaration((AnonymousClassDeclaration)binding.get(node.getAnonymousClassDeclaration()));
    if (binding.get(node.getType()) != null)
       element.setType((NamedElementRef)binding.get(node.getType()));
    for (Iterator i=node.arguments().iterator()  ;i.hasNext();){
       Expression itElement= (Expression) this.binding.get(i.next());
       if (itElement != null)
    element.getArguments().add(itElement);
    }
            
    if (binding.get(node.getExpression()) != null)
       element.setExpression((Expression)binding.get(node.getExpression()));
            
    NamedElementRef constructorRef= this.factory.createNamedElementRef();
    element.setMethod(constructorRef);
    JDTVisitorUtils.manageBindingRef(constructorRef, node, this);
     */
}

From source file:org.eclipse.jdt.core.dom.ASTConverter.java

License:Open Source License

public Expression convert(org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression allocation) {
    final ClassInstanceCreation classInstanceCreation = new ClassInstanceCreation(this.ast);
    if (allocation.enclosingInstance != null) {
        classInstanceCreation.setExpression(convert(allocation.enclosingInstance));
    }/*w w  w  .  j a  va  2 s . co m*/
    switch (this.ast.apiLevel) {
    case AST.JLS2_INTERNAL:
        classInstanceCreation.internalSetName(convert(allocation.type));
        break;
    default:
        classInstanceCreation.setType(convertType(allocation.type));
    }
    org.eclipse.jdt.internal.compiler.ast.Expression[] arguments = allocation.arguments;
    if (arguments != null) {
        int length = arguments.length;
        for (int i = 0; i < length; i++) {
            Expression argument = convert(arguments[i]);
            if (this.resolveBindings) {
                recordNodes(argument, arguments[i]);
            }
            classInstanceCreation.arguments().add(argument);
        }
    }
    if (allocation.typeArguments != null) {
        switch (this.ast.apiLevel) {
        case AST.JLS2_INTERNAL:
            classInstanceCreation.setFlags(classInstanceCreation.getFlags() | ASTNode.MALFORMED);
            break;
        default:
            for (int i = 0, max = allocation.typeArguments.length; i < max; i++) {
                classInstanceCreation.typeArguments().add(convertType(allocation.typeArguments[i]));
            }
        }
    }
    if (allocation.anonymousType != null) {
        int declarationSourceStart = allocation.sourceStart;
        classInstanceCreation.setSourceRange(declarationSourceStart,
                allocation.anonymousType.bodyEnd - declarationSourceStart + 1);
        final AnonymousClassDeclaration anonymousClassDeclaration = new AnonymousClassDeclaration(this.ast);
        int start = retrieveStartBlockPosition(allocation.anonymousType.sourceEnd,
                allocation.anonymousType.bodyEnd);
        anonymousClassDeclaration.setSourceRange(start, allocation.anonymousType.bodyEnd - start + 1);
        classInstanceCreation.setAnonymousClassDeclaration(anonymousClassDeclaration);
        buildBodyDeclarations(allocation.anonymousType, anonymousClassDeclaration);
        if (this.resolveBindings) {
            recordNodes(classInstanceCreation, allocation.anonymousType);
            recordNodes(anonymousClassDeclaration, allocation.anonymousType);
            anonymousClassDeclaration.resolveBinding();
        }
        return classInstanceCreation;
    } else {
        final int start = allocation.sourceStart;
        classInstanceCreation.setSourceRange(start, allocation.sourceEnd - start + 1);
        if (this.resolveBindings) {
            recordNodes(classInstanceCreation, allocation);
        }
        removeTrailingCommentFromExpressionEndingWithAParen(classInstanceCreation);
        return classInstanceCreation;
    }
}

From source file:org.eclipse.modisco.java.discoverer.internal.io.java.JDTVisitor.java

License:Open Source License

@Override
public void endVisit(final org.eclipse.jdt.core.dom.ClassInstanceCreation node) {
    ClassInstanceCreation element = (ClassInstanceCreation) this.binding.get(node);
    initializeNode(element, node);//w w  w  .  j  a v a 2s .  c o m

    ConstructorDeclaration anonymousConstructor = null;

    if (this.binding.get(node.getAnonymousClassDeclaration()) != null) {
        AnonymousClassDeclaration anoDecl = (AnonymousClassDeclaration) this.binding
                .get(node.getAnonymousClassDeclaration());
        element.setAnonymousClassDeclaration(anoDecl);
        anonymousConstructor = this.factory.createConstructorDeclaration();
        anonymousConstructor.setProxy(true);
        anonymousConstructor.setName(""); //$NON-NLS-1$
        anoDecl.getBodyDeclarations().add(anonymousConstructor);
    }

    if (this.binding.get(node.getType()) != null) {
        element.setType(JDTVisitorUtils.completeTypeAccess(this.binding.get(node.getType()), this));
    }

    for (Iterator<?> i = node.arguments().iterator(); i.hasNext();) {
        ASTNode itElement = this.binding.get(i.next());
        if (itElement != null) {
            element.getArguments().add(JDTVisitorUtils.completeExpression(itElement, this));
        }
    }

    for (Iterator<?> i = node.typeArguments().iterator(); i.hasNext();) {
        ASTNode itElement = this.binding.get(i.next());
        if (itElement != null) {
            element.getTypeArguments().add(JDTVisitorUtils.completeTypeAccess(itElement, this));
        }
    }

    if (this.binding.get(node.getExpression()) != null) {
        element.setExpression(JDTVisitorUtils.completeExpression(this.binding.get(node.getExpression()), this));
    }

    // if it is an anonymous class declaration we directly use the anonymous
    // constructor
    if (anonymousConstructor != null) {
        element.setMethod(anonymousConstructor);
    } else {
        PendingElement constructorRef = new PendingElement(this.factory);
        constructorRef.setClientNode(element);
        constructorRef.setLinkName("method"); //$NON-NLS-1$

        JDTVisitorUtils.manageBindingRef(constructorRef, node, this);
    }

}

From source file:org.eclipse.objectteams.otdt.ui.tests.dom.rewrite.ASTRewriteFlattenerTest.java

License:Open Source License

private Expression createExpression(Expression innerExpression, String className, List arguments,
        AnonymousClassDeclaration anonymousClass) {
    ClassInstanceCreation expression = _newAst.newClassInstanceCreation();
    expression.setType(_newAst.newSimpleType(_newAst.newName(className)));
    expression.setExpression(innerExpression);
    expression.setAnonymousClassDeclaration(anonymousClass);

    if (arguments != null && arguments.size() != 0) {
        List classArguments = expression.arguments();
        for (int idx = 0; idx < arguments.size(); idx++) {
            Expression tmp = (Expression) arguments.get(idx);
            classArguments.add(tmp);//from www.  j ava  2  s. c o m
        }
    }
    return expression;
}

From source file:org.evosuite.testcarver.codegen.JUnitCodeGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*w  w w.  j  a va  2s .  c om*/
public void createMethodCallStmt(CaptureLog log, int logRecNo) {
    PostProcessor.notifyRecentlyProcessedLogRecNo(logRecNo);

    // assumption: all necessary statements are created and there is one variable for reach referenced object
    final int oid = log.objectIds.get(logRecNo);
    Object[] methodArgs = log.params.get(logRecNo);
    final String methodName = log.methodNames.get(logRecNo);

    final String methodDesc = log.descList.get(logRecNo);
    org.objectweb.asm.Type[] methodParamTypes = org.objectweb.asm.Type.getArgumentTypes(methodDesc);

    Class<?>[] methodParamTypeClasses = new Class[methodParamTypes.length];
    for (int i = 0; i < methodParamTypes.length; i++) {
        methodParamTypeClasses[i] = getClassForName(methodParamTypes[i].getClassName());
    }

    final String typeName = log.oidClassNames.get(log.oidRecMapping.get(oid));
    Class<?> type = getClassForName(typeName);

    final boolean haveSamePackage = type.getPackage().getName().equals(packageName); // TODO might be nicer...

    final Statement finalStmt;

    @SuppressWarnings("rawtypes")
    final List arguments;
    if (CaptureLog.OBSERVED_INIT.equals(methodName)) {
        /*
         * Person var0 = null;
         * {
         *    var0 = new Person();
         * }
         * catch(Throwable t)
         * {
         *    org.uni.saarland.sw.prototype.capture.PostProcessor.captureException(<logRecNo>);
         * }
         */

        // e.g. Person var0 = null;
        final String varName = this.createNewVarName(oid, typeName);
        VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
        vd.setName(ast.newSimpleName(varName));
        VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd);
        stmt.setType(this.createAstType(typeName, ast));
        vd.setInitializer(ast.newNullLiteral());
        methodBlock.statements().add(stmt);

        //FIXME this does not make any sense
        try {
            this.getConstructorModifiers(type, methodParamTypeClasses);
        } catch (Exception e) {
            logger.error("" + e, e);
        }

        final int constructorTypeModifiers = this.getConstructorModifiers(type, methodParamTypeClasses);
        final boolean isPublic = java.lang.reflect.Modifier.isPublic(constructorTypeModifiers);
        final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage;

        if (isReflectionAccessNeeded) {
            this.isNewInstanceMethodNeeded = true;
            final MethodInvocation mi = this.createCallMethodOrNewInstanceCallStmt(true, ast, varName, typeName,
                    methodName, methodArgs, methodParamTypes);
            arguments = null;

            final Assignment assignment = ast.newAssignment();
            assignment.setLeftHandSide(ast.newSimpleName(varName));
            assignment.setOperator(Operator.ASSIGN);

            final CastExpression cast = ast.newCastExpression();
            cast.setType(this.createAstType(typeName, ast));
            cast.setExpression(mi);
            assignment.setRightHandSide(cast);

            finalStmt = ast.newExpressionStatement(assignment);
        } else {
            // e.g. var0 = new Person();
            final ClassInstanceCreation ci = ast.newClassInstanceCreation();

            final int recNo = log.oidRecMapping.get(oid);
            final int dependencyOID = log.dependencies.getQuick(recNo);

            if (dependencyOID == CaptureLog.NO_DEPENDENCY) {
                ci.setType(this.createAstType(typeName, ast));
            } else {
                //               final String varTypeName = oidToVarMapping.get(dependencyOID) + "." + typeName.substring(typeName.indexOf('$') + 1);
                //               ci.setType(this.createAstType(varTypeName, ast));
                /*
                 * e.g.
                 * OuterClass.InnerClass innerObject = outerObject.new InnerClass();
                 */
                ci.setType(this.createAstType(typeName.substring(typeName.indexOf('$') + 1), ast));
                ci.setExpression(ast.newSimpleName(oidToVarMapping.get(dependencyOID)));

                final int index = Arrays.binarySearch(methodArgs, dependencyOID);

                if (index > -1) {
                    logger.debug(varName + " xxxx3 " + index);

                    final Object[] newArgs = new Object[methodArgs.length - 1];
                    System.arraycopy(methodArgs, 0, newArgs, 0, index);
                    System.arraycopy(methodArgs, index + 1, newArgs, index, methodArgs.length - index - 1);
                    methodArgs = newArgs;

                    final Class<?>[] newParamTypeClasses = new Class<?>[methodParamTypeClasses.length - 1];
                    System.arraycopy(methodParamTypeClasses, 0, newParamTypeClasses, 0, index);
                    System.arraycopy(methodParamTypeClasses, index + 1, newParamTypeClasses, index,
                            methodParamTypeClasses.length - index - 1);
                    methodParamTypeClasses = newParamTypeClasses;

                    final org.objectweb.asm.Type[] newParamTypes = new org.objectweb.asm.Type[methodParamTypes.length
                            - 1];
                    System.arraycopy(methodParamTypes, 0, newParamTypes, 0, index);
                    System.arraycopy(methodParamTypes, index + 1, newParamTypes, index,
                            methodParamTypes.length - index - 1);
                    methodParamTypes = newParamTypes;
                }
            }

            final Assignment assignment = ast.newAssignment();
            assignment.setLeftHandSide(ast.newSimpleName(varName));
            assignment.setOperator(Operator.ASSIGN);
            assignment.setRightHandSide(ci);

            finalStmt = ast.newExpressionStatement(assignment);
            arguments = ci.arguments();
        }
    } else //------------------ handling for ordinary method calls e.g. var1 = var0.doSth();
    {
        String returnVarName = null;

        final String desc = log.descList.get(logRecNo);
        final String returnType = org.objectweb.asm.Type.getReturnType(desc).getClassName();

        final Object returnValue = log.returnValues.get(logRecNo);
        if (!CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) {
            Integer returnValueOID = (Integer) returnValue;

            // e.g. Person var0 = null;
            returnVarName = this.createNewVarName(returnValueOID, returnType);

            VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
            vd.setName(ast.newSimpleName(returnVarName));
            VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd);
            stmt.setType(this.createAstType(returnType, ast));
            vd.setInitializer(ast.newNullLiteral());
            methodBlock.statements().add(stmt);
        }

        final String varName = this.oidToVarMapping.get(oid);
        final int methodTypeModifiers = this.getMethodModifiers(type, methodName, methodParamTypeClasses);
        final boolean isPublic = java.lang.reflect.Modifier.isPublic(methodTypeModifiers);
        final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage;

        // e.g. Person var0 = var1.getPerson("Ben");

        final MethodInvocation mi;

        if (isReflectionAccessNeeded) {
            this.isCallMethodMethodNeeded = true;
            mi = this.createCallMethodOrNewInstanceCallStmt(false, ast, varName, typeName, methodName,
                    methodArgs, methodParamTypes);
            arguments = null;

            if (returnVarName != null) {
                final Assignment assignment = ast.newAssignment();
                assignment.setLeftHandSide(ast.newSimpleName(returnVarName));
                assignment.setOperator(Operator.ASSIGN);

                final CastExpression cast = ast.newCastExpression();
                cast.setType(this.createAstType(returnType, ast));
                cast.setExpression(mi);
                assignment.setRightHandSide(cast);

                finalStmt = ast.newExpressionStatement(assignment);
            } else {
                finalStmt = ast.newExpressionStatement(mi);
            }
        } else {
            mi = ast.newMethodInvocation();

            if (log.isStaticCallList.get(logRecNo)) {
                // can only happen, if this is a static method call (because constructor statement has been reported)
                final String tmpType = log.oidClassNames.get(log.oidRecMapping.get(oid));
                mi.setExpression(ast.newName(tmpType.split("\\.")));
            } else {
                try {
                    mi.setExpression(ast.newSimpleName(varName));
                } catch (final IllegalArgumentException ex) {

                    String msg = "";

                    msg += "--recno-- " + logRecNo + "\n";
                    msg += "--oid-- " + oid + "\n";
                    msg += "--method-- " + methodName + "\n";
                    msg += "--varName-- " + varName + "\n";
                    msg += "--oidToVarMap-- " + this.oidToVarMapping + "\n";
                    msg += (log) + "\n";

                    logger.error(msg);
                    throw new RuntimeException(msg);
                }
            }

            mi.setName(ast.newSimpleName(methodName));

            arguments = mi.arguments();

            if (returnVarName != null) {
                final Assignment assignment = ast.newAssignment();
                assignment.setLeftHandSide(ast.newSimpleName(returnVarName));
                assignment.setOperator(Operator.ASSIGN);
                assignment.setRightHandSide(mi);

                finalStmt = ast.newExpressionStatement(assignment);
            } else {
                finalStmt = ast.newExpressionStatement(mi);
            }
        }
    }

    if (postprocessing) {
        final TryStatement tryStmt = this.createTryStatementForPostProcessing(ast, finalStmt, logRecNo);
        methodBlock.statements().add(tryStmt);
    } else {
        if (this.failedRecords.contains(logRecNo)) {
            // we just need an empty catch block to preserve program flow
            final TryStatement tryStmt = this.createTryStmtWithEmptyCatch(ast, finalStmt);
            methodBlock.statements().add(tryStmt);
        } else {
            methodBlock.statements().add(finalStmt);
        }
    }

    if (arguments != null) {
        Class<?> methodParamType;
        Class<?> argType;

        Integer arg; // is either an oid or null
        for (int i = 0; i < methodArgs.length; i++) {
            arg = (Integer) methodArgs[i];
            if (arg == null) {
                arguments.add(ast.newNullLiteral());
            } else {
                methodParamType = CaptureUtil.getClassFromDesc(methodParamTypes[i].getDescriptor());
                argType = this.oidToTypeMapping.get(arg);

                // TODO: Warten was Florian und Gordon dazu sagen. Siehe Mail 04.08.2012
                if (argType == null) {
                    logger.error(
                            "Call within constructor needs instance of enclosing object as parameter -> ignored: "
                                    + arg);
                    methodBlock.statements().remove(methodBlock.statements().size() - 1);
                    return;
                }

                final CastExpression cast = ast.newCastExpression();

                if (methodParamType.isPrimitive()) {
                    // cast to ensure that right method is called
                    // --> see doSth(int) and doSth(Integer)

                    if (methodParamType.equals(boolean.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.BOOLEAN));
                    } else if (methodParamType.equals(byte.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.BYTE));
                    } else if (methodParamType.equals(char.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.CHAR));
                    } else if (methodParamType.equals(double.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.DOUBLE));
                    } else if (methodParamType.equals(float.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.FLOAT));
                    } else if (methodParamType.equals(int.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.INT));
                    } else if (methodParamType.equals(long.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.LONG));
                    } else if (methodParamType.equals(short.class)) {
                        cast.setType(ast.newPrimitiveType(PrimitiveType.SHORT));
                    } else {
                        throw new RuntimeException("unknown primitive type: " + methodParamType);
                    }

                } else {
                    // we need an up-cast
                    if (methodParamType.getName().contains(".")) {
                        cast.setType(this.createAstType(methodParamType.getName(), ast));
                    } else {
                        cast.setType(createAstType(methodParamType.getName(), ast));
                    }
                }

                cast.setExpression(ast.newSimpleName(this.oidToVarMapping.get(arg)));
                arguments.add(cast);
            }
        }
    }
}

From source file:org.whole.lang.java.util.JDTTransformerVisitor.java

License:Open Source License

public boolean visit(ClassInstanceCreation node) {
    org.whole.lang.java.model.ClassInstanceCreation newExp = lf
            .create(JavaEntityDescriptorEnum.ClassInstanceCreation);

    if (acceptChild(node.getExpression()))
        newExp.setExpression(exp);

    acceptChild(node.getType());//w  w w.j av  a  2s  .c om
    newExp.setType(type);

    Iterator<?> i = node.arguments().iterator();
    while (i.hasNext()) {
        ((ASTNode) i.next()).accept(this);
        newExp.getArguments().wAdd(exp);
    }

    if (acceptChild(node.getAnonymousClassDeclaration()))
        newExp.setAnonymousClassDeclaration(this.anonymousClassDeclaration);

    exp = newExp;
    return false;
}