Example usage for org.eclipse.jdt.core.dom AST newIfStatement

List of usage examples for org.eclipse.jdt.core.dom AST newIfStatement

Introduction

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

Prototype

public IfStatement newIfStatement() 

Source Link

Document

Creates a new unparented if statement node owned by this AST.

Usage

From source file:org.autorefactor.refactoring.rules.ReduceVariableScopeRefactoring.java

License:Open Source License

private void replace(VariableAccess varDecl, VariableAccess varAccess) {
    final ASTBuilder b = this.ctx.getASTBuilder();
    final AST ast = b.getAST();
    final ASTNode scope = varAccess.getScope();
    final Name varName = varAccess.getVariableName();
    final Type varType = getType(varDecl.getVariableName().getParent());
    if (scope instanceof Block) {
        final List<Statement> stmts = statements((Block) scope);
        for (int i = 0; i < stmts.size(); i++) {
            final Statement stmt = stmts.get(i);
            final Expression parentExpr = getAncestor(varName, Expression.class); // FIXME i=0
            final Statement parentStmt = getAncestor(parentExpr, Statement.class); // FIXME i=0
            if (stmt.equals(parentStmt)) {
                final VariableDeclarationFragment vdf = getVariableDeclarationFragment(parentExpr, varName);
                final VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
                vds.setType(varType);//from  ww w.  ja  v a2 s .c  o m
                this.ctx.getRefactorings().replace(stmt, vds);
                break;
            }
        }
    } else if (scope instanceof EnhancedForStatement) {
        final EnhancedForStatement efs = (EnhancedForStatement) scope;
        final EnhancedForStatement newEfs = b.copy(efs);
        newEfs.setParameter(b.copy(efs.getParameter()));
        newEfs.setExpression(b.copy(efs.getExpression()));
        final Statement parentStmt = getAncestor(varName, Statement.class);
        if (equalNotNull(efs.getBody(), parentStmt)) {
            newEfs.setBody(copy(efs.getBody(), varName));
        }
        this.ctx.getRefactorings().replace(efs, newEfs);
    } else if (scope instanceof ForStatement) {
        final ForStatement fs = (ForStatement) scope;
        final ForStatement newFs = b.copy(fs);
        final List<Expression> initializers = initializers(newFs);
        if (initializers.size() == 1) {
            final Expression init = initializers.remove(0);
            final VariableDeclarationFragment vdf = getVariableDeclarationFragment(init, varName);
            final VariableDeclarationExpression vde = ast.newVariableDeclarationExpression(vdf);
            vde.setType(varType);
            initializers.add(vde);
            this.ctx.getRefactorings().replace(fs, newFs);
            // TODO JNR
            // if (equalNotNull(fs.getBody(), parentStmt)) {
            // newFs.setBody(copy(fs.getBody()));
            // }
        } else {
            throw new NotImplementedException(scope, "for more than one initializer in for loop.");
        }
    } else if (scope instanceof WhileStatement) {
        final WhileStatement ws = (WhileStatement) scope;
        final WhileStatement newWs = ast.newWhileStatement();
        newWs.setExpression(b.copy(ws.getExpression()));
        final Statement parentStmt = getAncestor(varName, Statement.class);
        if (equalNotNull(ws.getBody(), parentStmt)) {
            newWs.setBody(copy(ws.getBody(), varName));
        }
        this.ctx.getRefactorings().replace(ws, newWs);
    } else if (scope instanceof IfStatement) {
        final IfStatement is = (IfStatement) scope;
        final IfStatement newIs = ast.newIfStatement();
        newIs.setExpression(b.copy(is.getExpression()));
        final Statement parentStmt = getAncestor(varName, Statement.class);
        if (equalNotNull(is.getThenStatement(), parentStmt)) {
            newIs.setThenStatement(copy(is.getThenStatement(), varName));
            if (is.getElseStatement() != null) {
                newIs.setElseStatement(b.copy(is.getElseStatement()));
            }
            this.ctx.getRefactorings().replace(is, newIs);
        } else if (equalNotNull(is.getElseStatement(), parentStmt)) {
            if (is.getThenStatement() != null) {
                newIs.setThenStatement(b.copy(is.getThenStatement()));
            }
            newIs.setElseStatement(copy(is.getElseStatement(), varName));
            this.ctx.getRefactorings().replace(is, newIs);
        } else {
            throw new IllegalStateException(is,
                    "Parent statement should be inside the then or else statement of this if statement: " + is);
        }
    } else {
        throw new NotImplementedException(scope);
    }
}

From source file:org.jboss.forge.roaster.model.impl.statements.IfStatementImpl.java

License:Open Source License

@Override
public org.eclipse.jdt.core.dom.IfStatement materialize(AST ast) {
    if (iff != null) {
        return iff;
    }/* ww w  . j  ava 2s .c om*/
    iff = ast.newIfStatement();

    if (condition != null) {
        iff.setExpression(wireAndGetExpression(condition, this, ast));
    }
    if (thenBody != null) {
        iff.setThenStatement(wireAndGetStatement(thenBody, this, ast));
    }
    if (elseBody != null) {
        iff.setElseStatement(wireAndGetStatement(elseBody, this, ast));
    }
    return iff;
}

From source file:ptolemy.backtrack.eclipse.ast.transform.AssignmentTransformer.java

License:Open Source License

/** Create the body of an assignment method, which backs up the field
 *  before a new value is assigned to it.
 *
 *  @param ast The {@link AST} object.//from w  w  w  .  jav  a 2  s . c  o m
 *  @param state The current state of the type analyzer.
 *  @param fieldName The name of the field.
 *  @param fieldType The type of the left-hand side (with <tt>indices</tt>
 *   dimensions less than the original field type).
 *  @param indices The number of indices.
 *  @param special Whether to handle special assign operators.
 *  @return The body of the assignment method.
 */
private Block _createAssignmentBlock(AST ast, TypeAnalyzerState state, String fieldName, Type fieldType,
        int indices, boolean special) {
    Block block = ast.newBlock();

    // Test if the checkpoint object is not null.
    IfStatement ifStatement = ast.newIfStatement();
    InfixExpression testExpression = ast.newInfixExpression();

    InfixExpression condition1 = ast.newInfixExpression();
    condition1.setLeftOperand(ast.newSimpleName(CHECKPOINT_NAME));
    condition1.setOperator(InfixExpression.Operator.NOT_EQUALS);
    condition1.setRightOperand(ast.newNullLiteral());

    InfixExpression condition2 = ast.newInfixExpression();
    MethodInvocation getTimestamp = ast.newMethodInvocation();
    getTimestamp.setExpression(ast.newSimpleName(CHECKPOINT_NAME));
    getTimestamp.setName(ast.newSimpleName("getTimestamp"));
    condition2.setLeftOperand(getTimestamp);
    condition2.setOperator(InfixExpression.Operator.GREATER);
    condition2.setRightOperand(ast.newNumberLiteral("0"));

    testExpression.setLeftOperand(condition1);
    testExpression.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
    testExpression.setRightOperand(condition2);
    ifStatement.setExpression(testExpression);

    // The "then" branch.
    Block thenBranch = ast.newBlock();

    // Method call to store old value.
    MethodInvocation recordInvocation = ast.newMethodInvocation();
    recordInvocation.setExpression(ast.newSimpleName(_getRecordName(fieldName)));
    recordInvocation.setName(ast.newSimpleName("add"));

    // If there are indices, create an integer array of those indices,
    // and add it as an argument.
    if (indices == 0) {
        recordInvocation.arguments().add(ast.newNullLiteral());
    } else {
        ArrayCreation arrayCreation = ast.newArrayCreation();
        ArrayType arrayType = ast.newArrayType(ast.newPrimitiveType(PrimitiveType.INT));
        ArrayInitializer initializer = ast.newArrayInitializer();

        for (int i = 0; i < indices; i++) {
            initializer.expressions().add(ast.newSimpleName("index" + i));
        }

        arrayCreation.setType(arrayType);
        arrayCreation.setInitializer(initializer);
        recordInvocation.arguments().add(arrayCreation);
    }

    // If there are indices, add them ("index0", "index1", ...) after the
    // field.
    Expression field = ast.newSimpleName(fieldName);

    if (indices > 0) {
        for (int i = 0; i < indices; i++) {
            ArrayAccess arrayAccess = ast.newArrayAccess();
            arrayAccess.setArray(field);
            arrayAccess.setIndex(ast.newSimpleName("index" + i));
            field = arrayAccess;
        }
    }

    // Set the field as the next argument.
    recordInvocation.arguments().add(field);

    // Get current timestamp from the checkpoint object.
    MethodInvocation timestampGetter = ast.newMethodInvocation();
    timestampGetter.setExpression(ast.newSimpleName(CHECKPOINT_NAME));
    timestampGetter.setName(ast.newSimpleName("getTimestamp"));

    // Set the timestamp as the next argument.
    recordInvocation.arguments().add(timestampGetter);

    // The statement of the method call.
    ExpressionStatement recordStatement = ast.newExpressionStatement(recordInvocation);
    thenBranch.statements().add(recordStatement);

    ifStatement.setThenStatement(thenBranch);
    block.statements().add(ifStatement);

    // Finally, assign the new value to the field.
    Assignment assignment = ast.newAssignment();
    assignment.setLeftHandSide((Expression) ASTNode.copySubtree(ast, field));
    assignment.setRightHandSide(ast.newSimpleName("newValue"));
    assignment.setOperator(Assignment.Operator.ASSIGN);

    // Set the checkpoint object of the new value, if necessary.
    Class c;

    try {
        c = fieldType.toClass(state.getClassLoader());
    } catch (ClassNotFoundException e) {
        throw new ASTClassNotFoundException(fieldType.getName());
    }

    if (hasMethod(c, _getSetCheckpointMethodName(false), new Class[] { Checkpoint.class })
            || state.getCrossAnalyzedTypes().contains(c.getName())) {
        block.statements().add(_createSetCheckpointInvocation(ast));
    } else {
        addToLists(_fixSetCheckpoint, c.getName(), block);
    }

    // Return the result of the assignment.
    if (special && _assignOperators.containsKey(fieldType.getName())) {
        String[] operators = _assignOperators.get(fieldType.getName());

        SwitchStatement switchStatement = ast.newSwitchStatement();
        switchStatement.setExpression(ast.newSimpleName("operator"));

        boolean isPostfix = true;

        for (int i = 0; i < operators.length; i++) {
            String operator = operators[i];

            SwitchCase switchCase = ast.newSwitchCase();
            switchCase.setExpression(ast.newNumberLiteral(Integer.toString(i)));
            switchStatement.statements().add(switchCase);

            ReturnStatement returnStatement = ast.newReturnStatement();

            if (operator.equals("=")) {
                Assignment newAssignment = (Assignment) ASTNode.copySubtree(ast, assignment);
                returnStatement.setExpression(newAssignment);
            } else if (operator.equals("++") || operator.equals("--")) {
                Expression expression;

                if (isPostfix) {
                    PostfixExpression postfix = ast.newPostfixExpression();
                    postfix.setOperand((Expression) ASTNode.copySubtree(ast, assignment.getLeftHandSide()));
                    postfix.setOperator(PostfixExpression.Operator.toOperator(operator));
                    expression = postfix;

                    // Produce prefix operators next time.
                    if (operator.equals("--")) {
                        isPostfix = false;
                    }
                } else {
                    PrefixExpression prefix = ast.newPrefixExpression();
                    prefix.setOperand((Expression) ASTNode.copySubtree(ast, assignment.getLeftHandSide()));
                    prefix.setOperator(PrefixExpression.Operator.toOperator(operator));
                    expression = prefix;
                }

                returnStatement.setExpression(expression);
            } else {
                Assignment newAssignment = (Assignment) ASTNode.copySubtree(ast, assignment);
                newAssignment.setOperator(Assignment.Operator.toOperator(operator));
                returnStatement.setExpression(newAssignment);
            }

            switchStatement.statements().add(returnStatement);
        }

        // The default statement: just return the old value.
        // This case should not be reached.
        SwitchCase defaultCase = ast.newSwitchCase();
        defaultCase.setExpression(null);
        switchStatement.statements().add(defaultCase);

        ReturnStatement defaultReturn = ast.newReturnStatement();
        defaultReturn.setExpression((Expression) ASTNode.copySubtree(ast, assignment.getLeftHandSide()));
        switchStatement.statements().add(defaultReturn);

        block.statements().add(switchStatement);
    } else {
        ReturnStatement returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(assignment);
        block.statements().add(returnStatement);
    }

    return block;
}

From source file:ptolemy.backtrack.eclipse.ast.transform.AssignmentTransformer.java

License:Open Source License

/** Create a restore method for a class, which restores all its state
 *  variables./*from w  w  w  .  j  ava 2 s.  c  om*/
 *
 *  @param ast The {@link AST} object.
 *  @param root The root of the AST.
 *  @param state The current state of the type analyzer.
 *  @param fieldNames The list of all the accessed fields.
 *  @param fieldTypes The types corresponding to the accessed fields.
 *  @param isAnonymous Whether the current class is anonymous.
 *  @param isInterface Whether the current type is an interface.
 *  @return The declaration of the method that restores the old value
 *   of all the private fields.
 */
private MethodDeclaration _createRestoreMethod(AST ast, CompilationUnit root, TypeAnalyzerState state,
        List fieldNames, List fieldTypes, boolean isAnonymous, boolean isInterface) {
    Class currentClass = state.getCurrentClass();
    Class parent = currentClass.getSuperclass();
    String methodName = _getRestoreMethodName(isAnonymous);

    // Check if the method is duplicated (possibly because the source
    // program is refactored twice).
    if (hasMethod(currentClass, methodName, new Class[] { int.class, boolean.class }, true)) {
        throw new ASTDuplicatedMethodException(currentClass.getName(), methodName);
    }

    MethodDeclaration method = ast.newMethodDeclaration();

    // Set the method name.
    method.setName(ast.newSimpleName(methodName));

    // Add a timestamp parameter.
    SingleVariableDeclaration timestamp = ast.newSingleVariableDeclaration();
    timestamp.setType(ast.newPrimitiveType(PrimitiveType.LONG));
    timestamp.setName(ast.newSimpleName("timestamp"));
    method.parameters().add(timestamp);

    // Add a trim parameter.
    SingleVariableDeclaration trim = ast.newSingleVariableDeclaration();
    trim.setType(ast.newPrimitiveType(PrimitiveType.BOOLEAN));
    trim.setName(ast.newSimpleName("trim"));
    method.parameters().add(trim);

    // Return type default to "void".
    if (!isInterface) {
        // The method body.
        Block body = ast.newBlock();
        method.setBody(body);

        // Create a restore statement for each managed field.
        Iterator namesIter = fieldNames.iterator();
        Iterator typesIter = fieldTypes.iterator();

        while (namesIter.hasNext()) {
            String fieldName = (String) namesIter.next();
            Type fieldType = (Type) typesIter.next();

            MethodInvocation restoreMethodCall = ast.newMethodInvocation();
            restoreMethodCall.setExpression(ast.newSimpleName(_getRecordName(fieldName)));

            // Set the restore method name.
            restoreMethodCall.arguments().add(ast.newSimpleName(fieldName));
            restoreMethodCall.setName(ast.newSimpleName("restore"));

            // Add two arguments to the restore method call.
            restoreMethodCall.arguments().add(ast.newSimpleName("timestamp"));
            restoreMethodCall.arguments().add(ast.newSimpleName("trim"));

            boolean isFinal = false;

            try {
                Field field = currentClass.getDeclaredField(fieldName);

                if (java.lang.reflect.Modifier.isFinal(field.getModifiers())) {
                    isFinal = true;
                }
            } catch (NoSuchFieldException e) {
            }

            if (isFinal) {
                if ((_getAccessedField(currentClass.getName(), fieldName) != null)
                        || !Type.isPrimitive(Type.getElementType(fieldType.getName()))) {
                    body.statements().add(ast.newExpressionStatement(restoreMethodCall));
                }
            } else {
                Expression rightHandSide;

                if (fieldType.isPrimitive()) {
                    rightHandSide = restoreMethodCall;
                } else {
                    CastExpression castExpression = ast.newCastExpression();
                    String typeName = getClassName(fieldType.getName(), state, root);
                    castExpression.setType(createType(ast, typeName));
                    castExpression.setExpression(restoreMethodCall);
                    rightHandSide = castExpression;
                }

                Assignment assignment = ast.newAssignment();
                assignment.setLeftHandSide(ast.newSimpleName(fieldName));
                assignment.setRightHandSide(rightHandSide);
                body.statements().add(ast.newExpressionStatement(assignment));
            }
        }

        // Add a call to the restore method in the superclass, if necessary.
        SuperMethodInvocation superRestore = ast.newSuperMethodInvocation();
        superRestore.setName(ast.newSimpleName(_getRestoreMethodName(false)));
        superRestore.arguments().add(ast.newSimpleName("timestamp"));
        superRestore.arguments().add(ast.newSimpleName("trim"));

        Statement superRestoreStatement = ast.newExpressionStatement(superRestore);

        if ((parent != null) && (state.getCrossAnalyzedTypes().contains(parent.getName())
                || hasMethod(parent, methodName, new Class[] { int.class, boolean.class }))) {
            body.statements().add(superRestoreStatement);
        } else {
            // Restore the previous checkpoint, if necessary.
            IfStatement restoreCheckpoint = ast.newIfStatement();

            InfixExpression timestampTester = ast.newInfixExpression();
            timestampTester.setLeftOperand(ast.newSimpleName("timestamp"));
            timestampTester.setOperator(InfixExpression.Operator.LESS_EQUALS);

            MethodInvocation topTimestamp = ast.newMethodInvocation();
            topTimestamp.setExpression(ast.newSimpleName(CHECKPOINT_RECORD_NAME));
            topTimestamp.setName(ast.newSimpleName("getTopTimestamp"));
            timestampTester.setRightOperand(topTimestamp);
            restoreCheckpoint.setExpression(timestampTester);

            Block restoreBlock = ast.newBlock();
            restoreCheckpoint.setThenStatement(restoreBlock);

            // Assign the old checkpoint.
            Assignment assignCheckpoint = ast.newAssignment();
            assignCheckpoint.setLeftHandSide(ast.newSimpleName(CHECKPOINT_NAME));

            MethodInvocation restoreCheckpointInvocation = ast.newMethodInvocation();
            restoreCheckpointInvocation.setExpression(ast.newSimpleName(CHECKPOINT_RECORD_NAME));
            restoreCheckpointInvocation.setName(ast.newSimpleName("restore"));
            restoreCheckpointInvocation.arguments().add(ast.newSimpleName(CHECKPOINT_NAME));
            restoreCheckpointInvocation.arguments().add(_createRollbackableObject(ast, isAnonymous));
            restoreCheckpointInvocation.arguments().add(ast.newSimpleName("timestamp"));
            restoreCheckpointInvocation.arguments().add(ast.newSimpleName("trim"));
            assignCheckpoint.setRightHandSide(restoreCheckpointInvocation);
            restoreBlock.statements().add(ast.newExpressionStatement(assignCheckpoint));

            // Pop the old states.
            MethodInvocation popStates = ast.newMethodInvocation();
            String recordType = getClassName(FieldRecord.class, state, root);
            popStates.setExpression(createName(ast, recordType));
            popStates.setName(ast.newSimpleName("popState"));
            popStates.arguments().add(ast.newSimpleName(RECORDS_NAME));
            restoreBlock.statements().add(ast.newExpressionStatement(popStates));

            // Recall the restore method.
            MethodInvocation recursion = ast.newMethodInvocation();
            recursion.setName(ast.newSimpleName(methodName));
            recursion.arguments().add(ast.newSimpleName("timestamp"));
            recursion.arguments().add(ast.newSimpleName("trim"));
            restoreBlock.statements().add(ast.newExpressionStatement(recursion));

            body.statements().add(restoreCheckpoint);

            if (parent != null) {
                addToLists(_nodeSubstitution, parent.getName(),
                        new NodeReplace(restoreCheckpoint, superRestoreStatement));
            }
        }
    }

    method.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    return method;
}

From source file:ptolemy.backtrack.eclipse.ast.transform.AssignmentTransformer.java

License:Open Source License

/** Create a set checkpoint method invocation for an assignment block.
 *
 *  @param ast The {@link AST} object.//from w  ww .j  a  v a  2s  . c  o m
 *  @return The statement that tests whether the checkpoint objects of the
 *   current object and the new value are the same; if not, assign the
 *   checkpoint object of the current object to the checkpoint of the new
 *   value.
 */
private Statement _createSetCheckpointInvocation(AST ast) {
    InfixExpression test = ast.newInfixExpression();

    InfixExpression condition1 = ast.newInfixExpression();
    condition1.setLeftOperand(ast.newSimpleName("newValue"));
    condition1.setOperator(InfixExpression.Operator.NOT_EQUALS);
    condition1.setRightOperand(ast.newNullLiteral());

    InfixExpression condition2 = ast.newInfixExpression();
    condition2.setLeftOperand(ast.newSimpleName(CHECKPOINT_NAME));
    condition2.setOperator(InfixExpression.Operator.NOT_EQUALS);

    MethodInvocation getCheckpoint = ast.newMethodInvocation();
    getCheckpoint.setExpression(ast.newSimpleName("newValue"));
    getCheckpoint.setName(ast.newSimpleName(_getGetCheckpointMethodName(false)));
    condition2.setRightOperand(getCheckpoint);

    test.setLeftOperand(condition1);
    test.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
    test.setRightOperand(condition2);

    IfStatement ifStatement = ast.newIfStatement();
    ifStatement.setExpression(test);

    Block thenBranch = ast.newBlock();
    ifStatement.setThenStatement(thenBranch);

    MethodInvocation setCheckpoint = ast.newMethodInvocation();
    setCheckpoint.setExpression(ast.newSimpleName("newValue"));
    setCheckpoint.setName(ast.newSimpleName(SET_CHECKPOINT_NAME));
    setCheckpoint.arguments().add(ast.newSimpleName(CHECKPOINT_NAME));
    thenBranch.statements().add(ast.newExpressionStatement(setCheckpoint));

    return ifStatement;
}

From source file:ptolemy.backtrack.eclipse.ast.transform.AssignmentTransformer.java

License:Open Source License

/** Create a set checkpoint method for a class, which sets its checkpoint
 *  object.// ww  w.j  ava2 s  . c  om
 *
 *  @param ast The {@link AST} object.
 *  @param root The root of the AST.
 *  @param state The current state of the type analyzer.
 *  @param isAnonymous Whether the current class is anonymous.
 *  @param isInterface Whether the current type is an interface.
 *  @return The declaration of the method that sets the checkpoint object.
 */
private MethodDeclaration _createSetCheckpointMethod(AST ast, CompilationUnit root, TypeAnalyzerState state,
        boolean isAnonymous, boolean isInterface) {
    String methodName = _getSetCheckpointMethodName(isAnonymous);

    Class currentClass = state.getCurrentClass();
    Class parent = currentClass.getSuperclass();

    // Check if the method is duplicated (possibly because the source
    // program is refactored twice).
    if (hasMethod(currentClass, methodName, new Class[] { Checkpoint.class }, true)) {
        throw new ASTDuplicatedMethodException(currentClass.getName(), methodName);
    }

    if (!isAnonymous && (parent != null) && (state.getCrossAnalyzedTypes().contains(parent.getName())
            || hasMethod(parent, methodName, new Class[] { Checkpoint.class }))) {
        return null;
    }

    MethodDeclaration method = ast.newMethodDeclaration();

    // Set the method name.
    method.setName(ast.newSimpleName(methodName));

    // Add a checkpoint parameter.
    SingleVariableDeclaration checkpoint = ast.newSingleVariableDeclaration();
    String checkpointType = getClassName(Checkpoint.class, state, root);
    checkpoint.setType(createType(ast, checkpointType));
    checkpoint.setName(ast.newSimpleName("checkpoint"));
    method.parameters().add(checkpoint);

    // Return type is Object.
    method.setReturnType2(createType(ast, getClassName(Object.class, state, root)));

    if (!isInterface) {
        // The test.
        IfStatement test = ast.newIfStatement();
        InfixExpression testExpression = ast.newInfixExpression();
        testExpression.setLeftOperand(ast.newSimpleName(CHECKPOINT_NAME));
        testExpression.setOperator(InfixExpression.Operator.NOT_EQUALS);
        testExpression.setRightOperand(ast.newSimpleName("checkpoint"));
        test.setExpression(testExpression);

        // The "then" branch of the test.
        Block thenBranch = ast.newBlock();
        test.setThenStatement(thenBranch);

        Block body = ast.newBlock();
        body.statements().add(test);
        method.setBody(body);

        // Backup the old checkpoint.
        VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
        fragment.setName(ast.newSimpleName("oldCheckpoint"));
        fragment.setInitializer(ast.newSimpleName(CHECKPOINT_NAME));

        VariableDeclarationStatement tempDeclaration = ast.newVariableDeclarationStatement(fragment);
        tempDeclaration.setType(createType(ast, checkpointType));
        thenBranch.statements().add(tempDeclaration);

        // Record the old checkpoint if the new checkpoint is not null.
        // If it is null, it is impossible to roll back to the previous
        // checkpoint.
        IfStatement testNewCheckpoint = ast.newIfStatement();
        InfixExpression testNull = ast.newInfixExpression();
        testNull.setLeftOperand(ast.newSimpleName("checkpoint"));
        testNull.setOperator(InfixExpression.Operator.NOT_EQUALS);
        testNull.setRightOperand(ast.newNullLiteral());
        testNewCheckpoint.setExpression(testNull);

        Block testNewCheckpointBody = ast.newBlock();
        testNewCheckpoint.setThenStatement(testNewCheckpointBody);

        MethodInvocation record = ast.newMethodInvocation();
        record.setExpression(ast.newSimpleName(CHECKPOINT_RECORD_NAME));
        record.setName(ast.newSimpleName("add"));
        record.arguments().add(ast.newSimpleName(CHECKPOINT_NAME));

        MethodInvocation getTimestamp = ast.newMethodInvocation();
        getTimestamp.setExpression(ast.newSimpleName("checkpoint"));
        getTimestamp.setName(ast.newSimpleName("getTimestamp"));
        record.arguments().add(getTimestamp);
        testNewCheckpointBody.statements().add(ast.newExpressionStatement(record));

        MethodInvocation pushStates = ast.newMethodInvocation();
        String recordType = getClassName(FieldRecord.class, state, root);
        pushStates.setExpression(createName(ast, recordType));
        pushStates.setName(ast.newSimpleName("pushState"));
        pushStates.arguments().add(ast.newSimpleName(RECORDS_NAME));
        testNewCheckpointBody.statements().add(ast.newExpressionStatement(pushStates));
        thenBranch.statements().add(testNewCheckpoint);

        // Assign the new checkpoint.
        Assignment assignment = ast.newAssignment();
        assignment.setLeftHandSide(ast.newSimpleName(CHECKPOINT_NAME));
        assignment.setRightHandSide(ast.newSimpleName("checkpoint"));

        ExpressionStatement statement = ast.newExpressionStatement(assignment);
        thenBranch.statements().add(statement);

        // Propagate the change to other objects monitored by the same old
        // checkpoint.
        MethodInvocation propagate = ast.newMethodInvocation();
        propagate.setExpression(ast.newSimpleName("oldCheckpoint"));
        propagate.setName(ast.newSimpleName("setCheckpoint"));
        propagate.arguments().add(ast.newSimpleName("checkpoint"));
        thenBranch.statements().add(ast.newExpressionStatement(propagate));

        // Add this object to the list in the checkpoint.
        MethodInvocation addInvocation = ast.newMethodInvocation();
        addInvocation.setExpression(ast.newSimpleName("checkpoint"));
        addInvocation.setName(ast.newSimpleName("addObject"));
        addInvocation.arguments().add(_createRollbackableObject(ast, isAnonymous));
        thenBranch.statements().add(ast.newExpressionStatement(addInvocation));

        // Return this object.
        ReturnStatement returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(ast.newThisExpression());
        body.statements().add(returnStatement);
    }

    method.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    if (!isInterface) {
        method.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
    }

    if (!isAnonymous && (parent != null)) {
        addToLists(_nodeSubstitution, parent.getName(), new NodeReplace(method, null));
    }

    return method;
}

From source file:refactorer.Refactorer.java

License:Apache License

@SuppressWarnings("unchecked")
protected void processMethodInvocation(MethodInvocation methodInvocation) {
    if (methodInvocation == null)
        return;//from  www. j  av a2 s. co  m

    Expression methodExpression = methodInvocation.getExpression();
    if (methodExpression != null) {
        ITypeBinding type = methodExpression.resolveTypeBinding();
        String methodName = methodInvocation.getName().getFullyQualifiedName();
        if (type != null && methodName != null) {
            AST ast = methodExpression.getAST();
            String typeName = type.getQualifiedName();
            if (("javax.media.opengl.GLContext".equals(typeName)
                    || "javax.media.opengl.GLAutoDrawable".equals(type.getQualifiedName()))
                    && "getGL".equals(methodName)) {
                Expression newExpression = ast.newName("IGNORED");
                newExpression = (Expression) ASTNode.copySubtree(newExpression.getAST(),
                        methodInvocation.getExpression());
                MethodInvocation newInvocation = ast.newMethodInvocation();
                newInvocation.setExpression(newExpression);
                newInvocation.setName(ast.newSimpleName("getGL"));
                methodInvocation.setExpression(newInvocation);
                methodInvocation.setName(ast.newSimpleName("getGL2"));
            } else if ("javax.media.opengl.GL".equals(typeName)) {
                if (methodName.endsWith("EXT") || methodName.endsWith("ARB")) {
                    methodInvocation
                            .setName(ast.newSimpleName(methodName.substring(0, methodName.length() - 3)));
                }
            } else if ("com.sun.opengl.util.BufferUtil".equals(typeName)) {
                methodInvocation.setExpression(ast.newSimpleName("Buffers"));
                if ("newByteBuffer".equals(methodName)) {
                    methodInvocation.setName(ast.newSimpleName("newDirectByteBuffer"));
                } else if ("newIntBuffer".equals(methodName)) {
                    methodInvocation.setName(ast.newSimpleName("newDirectIntBuffer"));
                } else if ("newFloatBuffer".equals(methodName)) {
                    methodInvocation.setName(ast.newSimpleName("newDirectFloatBuffer"));
                } else if ("newDoubleBuffer".equals(methodName)) {
                    methodInvocation.setName(ast.newSimpleName("newDirectDoubleBuffer"));
                }
            } else if ("com.sun.opengl.util.texture.TextureIO".equals(typeName)) {
                boolean newTexture = "newTexture".equals(methodName);
                boolean newTextureData = "newTextureData".equals(methodName);
                if (newTexture || newTextureData) {
                    boolean addGLProfile = newTextureData;
                    if (methodInvocation.arguments().size() == 2) {
                        Expression secondArgument = (Expression) methodInvocation.arguments().get(0);
                        if ("java.awt.image.BufferedImage"
                                .equals(secondArgument.resolveTypeBinding().getQualifiedName())) {
                            methodInvocation.setExpression(ast.newSimpleName("AWTTextureIO"));
                            addImportIfRequired("com.jogamp.opengl.util.texture.awt.AWTTextureIO");
                            addGLProfile = true;
                        }
                    }

                    if (addGLProfile) {
                        MethodInvocation newMethodInvocation = ast.newMethodInvocation();
                        newMethodInvocation.setExpression(ast.newSimpleName("GLProfile"));
                        newMethodInvocation.setName(ast.newSimpleName("get"));
                        newMethodInvocation.arguments()
                                .add(ast.newQualifiedName(ast.newName("GLProfile"), ast.newSimpleName("GL2")));
                        methodInvocation.arguments().add(0, newMethodInvocation);
                        addImportIfRequired("javax.media.opengl.GLProfile");
                    }
                }
            } else if ("com.sun.opengl.util.texture.Texture".equals(typeName)
                    && ("bind".equals(methodName) || "getTextureObject".equals(methodName)
                            || "setTexParameteri".equals(methodName) || "dispose".equals(methodName)
                            || "enable".equals(methodName) || "disable".equals(methodName)
                            || "updateSubImage".equals(methodName) || "updateImage".equals(methodName))) {
                List<LocalVariable> locals = variables.getLocalVariablesMatchingType("javax.media.opengl.GL");
                if (!locals.isEmpty()) {
                    Name name = ast.newName(locals.get(0).name);
                    methodInvocation.arguments().add(name);
                } else {
                    locals = variables.getLocalVariablesMatchingType("gov.nasa.worldwind.render.DrawContext");
                    if (!locals.isEmpty()) {
                        MethodInvocation newMethodInvocation = ast.newMethodInvocation();
                        newMethodInvocation.setExpression(ast.newSimpleName(locals.get(0).name));
                        newMethodInvocation.setName(ast.newSimpleName("getGL"));
                        methodInvocation.arguments().add(0, newMethodInvocation);
                    } else {
                        //GLContext.getCurrent().getGL().getGL2()
                        MethodInvocation mi1 = ast.newMethodInvocation();
                        mi1.setExpression(ast.newName("GLContext"));
                        mi1.setName(ast.newSimpleName("getCurrent"));

                        MethodInvocation mi2 = ast.newMethodInvocation();
                        mi2.setExpression(mi1);
                        mi2.setName(ast.newSimpleName("getGL"));

                        MethodInvocation mi3 = ast.newMethodInvocation();
                        mi3.setExpression(mi2);
                        mi3.setName(ast.newSimpleName("getGL2"));

                        methodInvocation.arguments().add(0, mi3);

                        addImportIfRequired("javax.media.opengl.GLContext");
                    }
                }

                if ("dispose".equals(methodName)) {
                    methodInvocation.setName(ast.newSimpleName("destroy"));
                }
            } else if ("javax.media.opengl.GLAutoDrawable".equals(typeName) && "repaint".equals(methodName)) {
                ASTNode parent = methodInvocation.getParent().getParent();
                if (parent.getNodeType() == ASTNode.BLOCK || parent.getNodeType() == ASTNode.IF_STATEMENT) {
                    IfStatement ifStatement = ast.newIfStatement();
                    InstanceofExpression instanceofExpression = ast.newInstanceofExpression();
                    ifStatement.setExpression(instanceofExpression);

                    Expression leftOperation = ast.newName("IGNORED");
                    leftOperation = (Expression) ASTNode.copySubtree(leftOperation.getAST(),
                            methodInvocation.getExpression());
                    instanceofExpression.setLeftOperand(leftOperation);
                    instanceofExpression.setRightOperand(ast.newSimpleType(ast.newName("Component")));

                    Expression castExpressionExpression = ast.newName("IGNORED");
                    castExpressionExpression = (Expression) ASTNode
                            .copySubtree(castExpressionExpression.getAST(), methodInvocation.getExpression());

                    CastExpression castExpression = ast.newCastExpression();
                    castExpression.setExpression(castExpressionExpression);
                    castExpression.setType(ast.newSimpleType(ast.newName("Component")));

                    ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
                    parenthesizedExpression.setExpression(castExpression);
                    methodInvocation.setExpression(parenthesizedExpression);

                    if (parent.getNodeType() == ASTNode.BLOCK) {
                        Block parentBlock = (Block) parent;
                        parentBlock.statements().remove(methodInvocation.getParent());
                        parentBlock.statements().add(ifStatement);
                    } else if (parent.getNodeType() == ASTNode.IF_STATEMENT) {
                        IfStatement parentIfStatement = (IfStatement) parent;
                        if (parentIfStatement.getThenStatement() == methodInvocation.getParent()) {
                            parentIfStatement.setThenStatement(ifStatement);
                        } else if (parentIfStatement.getElseStatement() == methodInvocation.getParent()) {
                            parentIfStatement.setElseStatement(ifStatement);
                        }
                    }
                    ifStatement.setThenStatement((Statement) methodInvocation.getParent());

                    addImportIfRequired("java.awt.Component");
                }
            } else if ("com.sun.opengl.util.Screenshot".equals(typeName)) {
                methodInvocation.setExpression(ast.newSimpleName("Screenshot"));
                addImportIfRequired("com.jogamp.opengl.util.awt.Screenshot");
            }
        }
    }

    processExpression(methodInvocation.getExpression());
    for (Expression e : (List<Expression>) methodInvocation.arguments()) {
        processExpression(e);
    }
}