Search in sources :

Example 91 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project evosuite by EvoSuite.

the class JUnitCodeGenerator method createArrayInitStmt.

@Override
public void createArrayInitStmt(final CaptureLog log, final int logRecNo) {
    final int oid = log.objectIds.get(logRecNo);
    final Object[] params = log.params.get(logRecNo);
    final String arrTypeName = log.oidClassNames.get(log.oidRecMapping.get(oid));
    final Class<?> arrType = getClassForName(arrTypeName);
    // --- create array instance creation e.g. int[] var = new int[10];
    final ArrayType arrAstType = (ArrayType) createAstArrayType(arrTypeName, ast);
    final ArrayCreation arrCreationExpr = ast.newArrayCreation();
    arrCreationExpr.setType(arrAstType);
    arrCreationExpr.dimensions().add(ast.newNumberLiteral(String.valueOf(params.length)));
    final String arrVarName = this.createNewVarName(oid, arrTypeName);
    final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
    final SimpleName arrVarNameExpr = ast.newSimpleName(arrVarName);
    vd.setName(arrVarNameExpr);
    vd.setInitializer(arrCreationExpr);
    final VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(vd);
    varDeclStmt.setType(this.createAstType(arrTypeName, ast));
    methodBlock.statements().add(varDeclStmt);
    // create array access statements var[0] = var1;
    Integer paramOID;
    Assignment assign;
    ArrayAccess arrAccessExpr;
    for (int i = 0; i < params.length; i++) {
        assign = ast.newAssignment();
        arrAccessExpr = ast.newArrayAccess();
        arrAccessExpr.setIndex(ast.newNumberLiteral(String.valueOf(i)));
        arrAccessExpr.setArray(arrVarNameExpr);
        assign.setLeftHandSide(arrAccessExpr);
        paramOID = (Integer) params[i];
        if (paramOID == null) {
            assign.setRightHandSide(ast.newNullLiteral());
        } else {
            assign.setRightHandSide(ast.newSimpleName(this.oidToVarMapping.get(paramOID)));
        }
        methodBlock.statements().add(assign);
    }
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayType(org.eclipse.jdt.core.dom.ArrayType) Assignment(org.eclipse.jdt.core.dom.Assignment) ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement)

Example 92 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project evosuite by EvoSuite.

the class JUnitCodeGenerator method createMethodCallStmt.

/* (non-Javadoc)
	 * @see org.evosuite.testcarver.codegen.ICodeGenerator#createMethodCallStmt(org.evosuite.testcarver.capture.CaptureLog, int)
	 */
@SuppressWarnings("unchecked")
@Override
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);
    // TODO might be nicer...
    final boolean haveSamePackage = type.getPackage().getName().equals(packageName);
    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;
        // is either an oid or null
        Integer arg;
        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()) {
                    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);
            }
        }
    }
}
Also used : MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) Assignment(org.eclipse.jdt.core.dom.Assignment) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) TIntArrayList(gnu.trove.list.array.TIntArrayList) List(java.util.List) ArrayList(java.util.ArrayList) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) Statement(org.eclipse.jdt.core.dom.Statement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) CastExpression(org.eclipse.jdt.core.dom.CastExpression)

Example 93 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project whole by wholeplatform.

the class PartFactoryVisitorBuilder method addPartFactoryVisitMethod.

public MethodDeclaration addPartFactoryVisitMethod(String typeName, int size) {
    MethodDeclaration method = addVisitMethod(typeName);
    if (!isInterface) {
        ClassInstanceCreation partInstance;
        if (typeName.equals(((LanguageGenerator) generator).entityVariableName()))
            partInstance = newClassInstanceCreation(VariablePartName);
        else
            partInstance = newClassInstanceCreation(size < 5 ? SimplePartName : SimpleFoldablePartName, newMethodInvocation("entity", "wGetEntityDescriptor"));
        Assignment eq = newAssignment(ast.newSimpleName("part"), partInstance);
        method.getBody().statements().add(newExpressionStatement(eq));
    }
    return method;
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) Assignment(org.eclipse.jdt.core.dom.Assignment) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration)

Example 94 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project whole by wholeplatform.

the class CompilationUnitBuilder method newSetterMethodWithNotification.

public MethodDeclaration newSetterMethodWithNotification(String featuresEnum, String fType, String fName, String name, boolean isReference, boolean useQualifiedType) {
    MethodDeclaration method = ast.newMethodDeclaration();
    method.setConstructor(false);
    method.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    method.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
    method.setName(ast.newSimpleName(StringUtils.setterName(name)));
    method.parameters().add(newSingleVariableDeclaration(useQualifiedType ? newQualifiedType(fType) : newType(fType), fName));
    if (!isInterface) {
        Block body = newBlock();
        MethodInvocation callExp = ast.newMethodInvocation();
        callExp.setName(ast.newSimpleName("notifyChanged"));
        if (featuresEnum != null)
            callExp.arguments().add(newFieldAccess(featuresEnum, fName));
        FieldAccess fieldAcc = ast.newFieldAccess();
        fieldAcc.setExpression(ast.newThisExpression());
        fieldAcc.setName(ast.newSimpleName(fName));
        callExp.arguments().add(fieldAcc);
        fieldAcc = ast.newFieldAccess();
        fieldAcc.setExpression(ast.newThisExpression());
        fieldAcc.setName(ast.newSimpleName(fName));
        Assignment eq = ast.newAssignment();
        eq.setLeftHandSide(fieldAcc);
        eq.setRightHandSide(ast.newSimpleName(fName));
        callExp.arguments().add(eq);
        if (isReference)
            callExp.arguments().add(newLiteral(false));
        body.statements().add(ast.newExpressionStatement(callExp));
        method.setBody(body);
    }
    return method;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Block(org.eclipse.jdt.core.dom.Block) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) SuperFieldAccess(org.eclipse.jdt.core.dom.SuperFieldAccess)

Example 95 with Assignment

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

the class ASTNodes method decomposeInitializer.

/**
 * Decomposes an initializer into a {@link Pair} with the name of the
 * initialized variable and the initializing expression.
 *
 * @param init the initializer to decompose
 * @return a {@link Pair} with the name of the initialized variable and the
 *         initializing expression, or {@code null} if the initializer could not
 *         be decomposed
 */
public static Pair<Expression, Expression> decomposeInitializer(final Expression init) {
    if (init instanceof VariableDeclarationExpression) {
        VariableDeclarationExpression variableDeclarationExpression = (VariableDeclarationExpression) init;
        List<VariableDeclarationFragment> fragments = variableDeclarationExpression.fragments();
        if (fragments.size() == 1) {
            VariableDeclarationFragment fragment = fragments.get(0);
            return Pair.of(fragment.getName(), fragment.getInitializer());
        }
    } else if (init instanceof Assignment) {
        Assignment as = (Assignment) init;
        if (hasOperator(as, Assignment.Operator.ASSIGN)) {
            Name name = as(as.getLeftHandSide(), Name.class);
            FieldAccess fieldAccess = as(as.getLeftHandSide(), FieldAccess.class);
            if (name != null) {
                return Pair.of(name, as.getRightHandSide());
            }
            if (fieldAccess != null) {
                return Pair.of(fieldAccess, as.getRightHandSide());
            }
        }
    }
    return Pair.empty();
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name)

Aggregations

Assignment (org.eclipse.jdt.core.dom.Assignment)229 Expression (org.eclipse.jdt.core.dom.Expression)115 SimpleName (org.eclipse.jdt.core.dom.SimpleName)94 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)91 ASTNode (org.eclipse.jdt.core.dom.ASTNode)84 AST (org.eclipse.jdt.core.dom.AST)69 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)64 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)63 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)63 CastExpression (org.eclipse.jdt.core.dom.CastExpression)62 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)61 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)60 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)59 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)58 Statement (org.eclipse.jdt.core.dom.Statement)55 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)49 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)48 Block (org.eclipse.jdt.core.dom.Block)43 FieldAccess (org.eclipse.jdt.core.dom.FieldAccess)43 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)41