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

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

Introduction

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

Prototype

public ExpressionStatement newExpressionStatement(Expression expression) 

Source Link

Document

Creates a new unparented expression statement node owned by this AST, for the given expression.

Usage

From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.PathWithUncertaintyTestStrategy.java

License:Open Source License

/**
 * /*from  ww  w  . j ava2 s. c  om*/
 * @param state - the state for which we inspect the transitions and generate the test plan
 * @param rewrite - rewriter used to modify the generated code
 * @param planMethodDeclaration - the method in which the code must be added
 * @param parrentPlanBlock - the block of code where the new state code must be added. Can be a method body, the body of an If statement, etc
 * @param pathTransitions - used to avoid testing cycles and ensure test plan keeps uniqueness on transitions
 */
private void generatePlanForState(final StateMachineState state, final ASTRewrite rewrite,
        final MethodDeclaration planMethodDeclaration, final Set<StateMachineStateTransition> pathTransitions) {

    AST ast = planMethodDeclaration.getAST();
    Block parrentPlanBlock = planMethodDeclaration.getBody();

    ListRewrite listRewrite = rewrite.getListRewrite(parrentPlanBlock, Block.STATEMENTS_PROPERTY);

    /**
     * First we create an abstract method to assert that we have reached current state and we call it
     * only if the state is not a choice. Choices are "virtual" states that signal splits in transition.
     * 
     */
    {

        //only create method if not previously created
        String stateName = state.getName();
        String methodName = ASSERT_STATE_LEADING + stateName;
        if (!generatedAbstractMethods.containsKey(stateName)) {
            MethodDeclaration method = createAbstractMethodForState(state, planMethodDeclaration.getAST());
            generatedAbstractMethods.put(stateName, method);
        }

        /**
         * Call the assert state method to check if we have reached the current state.
         * For the initial state this assert can also reset the system to initial state.
         */
        {
            //invoke guard as Assert statement
            AssertStatement assertStatement = ast.newAssertStatement();
            MethodInvocation invocation = ast.newMethodInvocation();
            invocation.setName(ast.newSimpleName(methodName));
            assertStatement.setExpression(invocation);

            parrentPlanBlock.statements().add(assertStatement);

            //                  listRewrite.insertFirst(rewrite.createStringPlaceholder("//Call the assert state method to check if we have reached the current state.", ASTNode.EMPTY_STATEMENT), null);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("//For the initial state this assert can also reset the system to initial state.", ASTNode.EMPTY_STATEMENT), null);
            //                  listRewrite.insertLast(assertStatement, null);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
        }

    }

    /**
     * If from one state we have multiple triggers, or from a choice we can go to multiple classes
     * then we generate for each of these transitions paths a separate test plan.
     * This means we clone the previous method into how many we need
     */
    List<StateMachineStateTransition> transitions = state.getOutTransitions();

    //if 1 transition, then we add to same plan
    //if more, we need separate test plans for each branching
    if (transitions.isEmpty() && !(state.getVertex() instanceof FinalState)) {
        //notify user that  something is wrong with the model we are converting 
        notifyUser("State \"" + state.getName()
                + "\"is not final and does not have any transitions. All state machine flows must reach a FinalState.");
        System.err.println(state.getName()
                + " is not final and does not have any transitions. All state machine flows must reach a FinalState to be converted in test plans.");
    } else if (transitions.size() == 1) {
        StateMachineStateTransition transition = transitions.get(0);

        //if we have visited this transition, continue
        if (pathTransitions.contains(transition)) {
            return;
        } else {
            // add transition to visited transitions
            pathTransitions.add(transition);
        }

        //                listRewrite.insertLast(rewrite.createStringPlaceholder("//Test transition " + transition.getTransition().getName(), ASTNode.EMPTY_STATEMENT), null);

        /**
         * Must assert before any transition that the guard condition is fulfilled
         */
        {
            //get transition condition (could also be Rule, currently we get only Guard transitions)
            Constraint guard = transition.getTransition().getGuard();
            if (guard != null) {
                for (Element element : guard.allOwnedElements()) {
                    //currently condition retrieved as plain text that will need to be parsed and evaluated
                    OpaqueExpression expression = (OpaqueExpression) element;
                    for (String body : expression.getBodies()) {
                        if (body.isEmpty()) {
                            notifyUser("Guard condition for transition  " + transition.getTransition().getName()
                                    + " from state " + state.getName() + " is empty");
                            System.err.println(
                                    "Guard condition for transition  " + transition.getTransition().getName()
                                            + " from state " + state.getName() + " is empty");
                            continue;
                        }
                        MethodDeclaration method = createAbstractMethodForGuard(body, ast);
                        if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                            generatedAbstractMethods.put(method.getName().toString(), method);
                        }
                        //invoke guard as Assert statement
                        AssertStatement assertStatement = ast.newAssertStatement();
                        MethodInvocation invocation = ast.newMethodInvocation();
                        invocation.setName(ast.newSimpleName(method.getName().toString()));
                        assertStatement.setExpression(invocation);

                        parrentPlanBlock.statements().add(assertStatement);

                        //                           listRewrite.insertLast(rewrite.createStringPlaceholder("//Assert guard condition for next transition is true", ASTNode.EMPTY_STATEMENT), null);
                        //                           listRewrite.insertLast(assertStatement, null);
                        //                           listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                    }
                }
            }
        }

        //get all transition triggers
        List<Trigger> triggers = transition.getTransition().getTriggers();

        //for each trigger
        for (Trigger trigger : triggers) {

            /**
             * If we have not created it already, we create an abstract method to invoke the trigger
             */
            {
                //TODO: update so we do not generate the trigger if it was already generated
                MethodDeclaration method = createAbstractTriggerInvocation(trigger,
                        planMethodDeclaration.getAST());
                if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                    generatedAbstractMethods.put(method.getName().toString(), method);
                }
                //invoke trigger
                MethodInvocation invocation = ast.newMethodInvocation();
                invocation.setName(ast.newSimpleName(method.getName().toString()));
                //                     listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null);
                //                     listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                //                     listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);

                parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));

            }

        }

        if (!(state.getVertex() instanceof FinalState)) {
            //continue from target state with plan generation

            StateMachineState targetState = transition.getTargetState();
            generatePlanForState(targetState, rewrite, planMethodDeclaration, pathTransitions);
        } else {
            if (transition.getTargetState() == null) {
                notifyUser(state.getName() + " is not final and does not have a target state on transition "
                        + transition.getTransition().getName());
                System.err.println(
                        state.getName() + " is not final and does not have a target state on transition "
                                + transition.getTransition().getName());
            }
        }

    } else if (transitions.size() > 1) {
        for (StateMachineStateTransition transition : transitions) {

            //clone transitions to use clean path for each sub-trees
            Set<StateMachineStateTransition> transitionsCopy = new HashSet<>();
            transitionsCopy.addAll(pathTransitions);

            //if we have visited this transition, continue
            if (transitionsCopy.contains(transition)) {
                continue;
            } else {
                // add transition to visited transitions
                transitionsCopy.add(transition);
            }

            //for each transition we do a clone of the plan until now
            MethodDeclaration transitionMethod = cloneMethodDeclaration(planMethodDeclaration);
            transitionMethod.setName(ast
                    .newSimpleName(PLAN_METHOD_LEADING + (UUID.randomUUID().toString().replaceAll("\\W", ""))));

            //shadowing to local parrentPlanBlock
            parrentPlanBlock = transitionMethod.getBody();

            //shadowing to local ListRewrite 
            //                  listRewrite = rewrite.getListRewrite(transitionMethod.getBody(), Block.STATEMENTS_PROPERTY);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("//Forcing transition " + transition.getTransition().getName() + " by ensuring guard conditions are met and triggers are invoked.", ASTNode.EMPTY_STATEMENT), null);
            /**
             * Must force-set all guard conditions to navigate to this particular execution branch
             */
            {
                //get transition condition (could also be Rule, currently we get only Guard transitions)
                //force for the current test the transition condition to true, to enable the system to navigate to expected state
                Constraint guard = transition.getTransition().getGuard();
                if (guard != null) {
                    for (Element element : guard.allOwnedElements()) {
                        //currently condition retrieved as plain text that will need to be parsed and evaluated
                        OpaqueExpression expression = (OpaqueExpression) element;
                        for (String body : expression.getBodies()) {

                            if (body.isEmpty()) {
                                notifyUser("Guard condition for transition  "
                                        + transition.getTransition().getName() + " from state "
                                        + state.getName() + " is empty");
                                System.err.println("Guard condition for transition  "
                                        + transition.getTransition().getName() + " from state "
                                        + state.getName() + " is empty");
                                continue;
                            }

                            MethodDeclaration method = createAbstractForceConditionMethod(body, ast);
                            if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                                generatedAbstractMethods.put(method.getName().toString(), method);
                            }
                            //invoke method to force guard condition to true
                            MethodInvocation invocation = ast.newMethodInvocation();
                            invocation.setName(ast.newSimpleName(method.getName().toString()));
                            //                              listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke method to force guard condition to true: " + body, ASTNode.EMPTY_STATEMENT), null);
                            //                              listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                            //                              listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                            parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));
                        }
                    }
                }
            }

            //get all transition triggers and execute them, like if we had only one transition
            List<Trigger> triggers = transition.getTransition().getTriggers();

            //for each trigger
            for (Trigger trigger : triggers) {

                /**
                 * If we have not created it already, we create an abstract method to invoke the trigger
                 */
                {
                    //TODO: update so we do not generate the trigger if it was already generated
                    MethodDeclaration method = createAbstractTriggerInvocation(trigger,
                            transitionMethod.getAST());
                    if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                        generatedAbstractMethods.put(method.getName().toString(), method);
                    }
                    //invoke trigger
                    MethodInvocation invocation = ast.newMethodInvocation();
                    invocation.setName(ast.newSimpleName(method.getName().toString()));
                    //                        listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null);
                    //                        listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                    //                        listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                    parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));
                }

            }

            if (!(state.getVertex() instanceof FinalState)) {
                //continue from target state with plan generation
                StateMachineState targetState = transition.getTargetState();
                generatePlanForState(targetState, rewrite, transitionMethod, transitionsCopy);
            } else {
                if (transition.getTargetState() == null) {
                    notifyUser(state.getName() + " is not final and does not have a target state on transition "
                            + transition.getTransition().getName());
                    System.err.println(
                            state.getName() + " is not final and does not have a target state on transition "
                                    + transition.getTransition().getName());
                }
            }

        }

    }

    if (state.getVertex() instanceof FinalState) {
        //store generated method in methods
        //check and store only if there is at least one transition with an uncertain state 
        boolean hasUncertainty = false;
        for (StateMachineStateTransition transition : pathTransitions) {

            //TODO: remove constant and make this efficient

            //check for all transitions only initial state for uncertainties
            //as for next transition, the initial will be the target of this one (except for final state)
            for (Stereotype stereotype : transition.getSourceState().getVertex().getAppliedStereotypes()) {
                //check if the applied stereotype is InfrastructureLevelUncertainty
                if (stereotype.getName().equals(INFRASTRUCTURE_UNCERTAINTY_NAME)) {
                    hasUncertainty = true;
                    break;
                }
            }
        }

        //if does not have any uncertainty on it, do not add it to generated plans
        if (hasUncertainty) {
            generatedPlans.put(planMethodDeclaration.getName().toString(), planMethodDeclaration);
        }
    }

}

From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.TransitionCorrectnessTestStrategy.java

License:Open Source License

/**
 * // w  ww  .  j  a  v  a2 s .  c  o  m
 * @param state - the state for which we inspect the transitions and generate the test plan
 * @param rewrite - rewriter used to modify the generated code
 * @param planMethodDeclaration - the method in which the code must be added
 * @param parrentPlanBlock - the block of code where the new state code must be added. Can be a method body, the body of an If statement, etc
 * @param pathTransitions - used to avoid testing cycles and ensure test plan keeps uniqueness on transitions
 */
private void generatePlanForState(final StateMachineState state, final ASTRewrite rewrite,
        final MethodDeclaration planMethodDeclaration, final Set<StateMachineStateTransition> pathTransitions) {

    AST ast = planMethodDeclaration.getAST();
    Block parrentPlanBlock = planMethodDeclaration.getBody();

    ListRewrite listRewrite = rewrite.getListRewrite(parrentPlanBlock, Block.STATEMENTS_PROPERTY);

    /**
     * First we create an abstract method to assert that we have reached current state and we call it
     * only if the state is not a choice. Choices are "virtual" states that signal splits in transition.
     * 
     */
    {

        //only create method if not previously created
        String stateName = state.getName();
        String methodName = ASSERT_STATE_LEADING + stateName;
        if (!generatedAbstractMethods.containsKey(stateName)) {
            MethodDeclaration method = createAbstractMethodForState(state, planMethodDeclaration.getAST());
            generatedAbstractMethods.put(stateName, method);
        }

        /**
        * Call the assert state method to check if we have reached the current state.
        * For the initial state this assert can also reset the system to initial state.
        */
        {
            //invoke guard as Assert statement
            AssertStatement assertStatement = ast.newAssertStatement();
            MethodInvocation invocation = ast.newMethodInvocation();
            invocation.setName(ast.newSimpleName(methodName));
            assertStatement.setExpression(invocation);

            parrentPlanBlock.statements().add(assertStatement);

            //                  listRewrite.insertFirst(rewrite.createStringPlaceholder("//Call the assert state method to check if we have reached the current state.", ASTNode.EMPTY_STATEMENT), null);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("//For the initial state this assert can also reset the system to initial state.", ASTNode.EMPTY_STATEMENT), null);
            //                  listRewrite.insertLast(assertStatement, null);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
        }

    }

    /**
     * If from one state we have multiple triggers, or from a choice we can go to multiple classes
     * then we generate for each of these transitions paths a separate test plan.
     * This means we clone the previous method into how many we need
     */
    List<StateMachineStateTransition> transitions = state.getOutTransitions();

    //if 1 transition, then we add to same plan
    //if more, we need separate test plans for each branching
    if (transitions.isEmpty() && !(state.getVertex() instanceof FinalState)) {
        //notify user that  something is wrong with the model we are converting 
        notifyUser("State \"" + state.getName()
                + "\"is not final and does not have any transitions. All state machine flows must reach a FinalState.");
        System.err.println(state.getName()
                + " is not final and does not have any transitions. All state machine flows must reach a FinalState to be converted in test plans.");
    } else if (transitions.size() == 1) {
        StateMachineStateTransition transition = transitions.get(0);

        //if we have visited this transition, continue
        if (pathTransitions.contains(transition)) {
            return;
        } else {
            // add transition to visited transitions
            pathTransitions.add(transition);
        }

        //                listRewrite.insertLast(rewrite.createStringPlaceholder("//Test transition " + transition.getTransition().getName(), ASTNode.EMPTY_STATEMENT), null);

        /**
        * Must assert before any transition that the guard condition is fulfilled
        */
        {
            //get transition condition (could also be Rule, currently we get only Guard transitions)
            Constraint guard = transition.getTransition().getGuard();
            if (guard != null) {
                for (Element element : guard.allOwnedElements()) {
                    //currently condition retrieved as plain text that will need to be parsed and evaluated
                    OpaqueExpression expression = (OpaqueExpression) element;
                    for (String body : expression.getBodies()) {
                        if (body.isEmpty()) {
                            notifyUser("Guard condition for transition  " + transition.getTransition().getName()
                                    + " from state " + state.getName() + " is empty");
                            System.err.println(
                                    "Guard condition for transition  " + transition.getTransition().getName()
                                            + " from state " + state.getName() + " is empty");
                            continue;
                        }
                        MethodDeclaration method = createAbstractMethodForGuard(body, ast);
                        if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                            generatedAbstractMethods.put(method.getName().toString(), method);
                        }
                        //invoke guard as Assert statement
                        AssertStatement assertStatement = ast.newAssertStatement();
                        MethodInvocation invocation = ast.newMethodInvocation();
                        invocation.setName(ast.newSimpleName(method.getName().toString()));
                        assertStatement.setExpression(invocation);

                        parrentPlanBlock.statements().add(assertStatement);

                        //                           listRewrite.insertLast(rewrite.createStringPlaceholder("//Assert guard condition for next transition is true", ASTNode.EMPTY_STATEMENT), null);
                        //                           listRewrite.insertLast(assertStatement, null);
                        //                           listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                    }
                }
            }
        }

        //get all transition triggers
        List<Trigger> triggers = transition.getTransition().getTriggers();

        //for each trigger
        for (Trigger trigger : triggers) {

            /**
             * If we have not created it already, we create an abstract method to invoke the trigger
             */
            {
                //TODO: update so we do not generate the trigger if it was already generated
                MethodDeclaration method = createAbstractTriggerInvocation(trigger,
                        planMethodDeclaration.getAST());
                if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                    generatedAbstractMethods.put(method.getName().toString(), method);
                }
                //invoke trigger
                MethodInvocation invocation = ast.newMethodInvocation();
                invocation.setName(ast.newSimpleName(method.getName().toString()));
                //                     listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null);
                //                     listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                //                     listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);

                parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));

            }

        }

        if (!(state.getVertex() instanceof FinalState)) {
            //continue from target state with plan generation
            StateMachineState targetState = transition.getTargetState();
            generatePlanForState(targetState, rewrite, planMethodDeclaration, pathTransitions);
        } else {
            if (transition.getTargetState() == null) {
                notifyUser(state.getName() + " is not final and does not have a target state on transition "
                        + transition.getTransition().getName());
                System.err.println(
                        state.getName() + " is not final and does not have a target state on transition "
                                + transition.getTransition().getName());
            }
        }

    } else if (transitions.size() > 1) {

        for (StateMachineStateTransition transition : transitions) {

            //clone transitions to use clean path for each sub-trees
            //cloning is done here as we are generating different paths for each transition at this point
            Set<StateMachineStateTransition> transitionsCopy = new HashSet<>();
            transitionsCopy.addAll(pathTransitions);

            //if we have visited this transition, continue
            if (transitionsCopy.contains(transition)) {
                continue;
            } else {
                // add transition to visited transitions
                transitionsCopy.add(transition);
            }

            //for each transition we do a clone of the plan until now
            MethodDeclaration transitionMethod = cloneMethodDeclaration(planMethodDeclaration);
            transitionMethod.setName(ast
                    .newSimpleName(PLAN_METHOD_LEADING + (UUID.randomUUID().toString().replaceAll("\\W", ""))));

            //shadowing to local parrentPlanBlock
            parrentPlanBlock = transitionMethod.getBody();

            //shadowing to local ListRewrite 
            //                  listRewrite = rewrite.getListRewrite(transitionMethod.getBody(), Block.STATEMENTS_PROPERTY);
            //                  listRewrite.insertLast(rewrite.createStringPlaceholder("//Forcing transition " + transition.getTransition().getName() + " by ensuring guard conditions are met and triggers are invoked.", ASTNode.EMPTY_STATEMENT), null);
            /**
             * Must force-set all guard conditions to navigate to this particular execution branch
             */
            {
                //get transition condition (could also be Rule, currently we get only Guard transitions)
                //force for the current test the transition condition to true, to enable the system to navigate to expected state
                Constraint guard = transition.getTransition().getGuard();
                if (guard != null) {
                    for (Element element : guard.allOwnedElements()) {
                        //currently condition retrieved as plain text that will need to be parsed and evaluated
                        OpaqueExpression expression = (OpaqueExpression) element;
                        for (String body : expression.getBodies()) {

                            if (body.isEmpty()) {
                                notifyUser("Guard condition for transition  "
                                        + transition.getTransition().getName() + " from state "
                                        + state.getName() + " is empty");
                                System.err.println("Guard condition for transition  "
                                        + transition.getTransition().getName() + " from state "
                                        + state.getName() + " is empty");
                                continue;
                            }

                            MethodDeclaration method = createAbstractForceConditionMethod(body, ast);
                            if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                                generatedAbstractMethods.put(method.getName().toString(), method);
                            }
                            //invoke method to force guard condition to true
                            MethodInvocation invocation = ast.newMethodInvocation();
                            invocation.setName(ast.newSimpleName(method.getName().toString()));
                            //                              listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke method to force guard condition to true: " + body, ASTNode.EMPTY_STATEMENT), null);
                            //                              listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                            //                              listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                            parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));
                        }
                    }
                }
            }

            //get all transition triggers and execute them, like if we had only one transition
            List<Trigger> triggers = transition.getTransition().getTriggers();

            //for each trigger
            for (Trigger trigger : triggers) {

                /**
                 * If we have not created it already, we create an abstract method to invoke the trigger
                 */
                {
                    //TODO: update so we do not generate the trigger if it was already generated
                    MethodDeclaration method = createAbstractTriggerInvocation(trigger,
                            transitionMethod.getAST());
                    if (!generatedAbstractMethods.containsKey(method.getName().toString())) {
                        generatedAbstractMethods.put(method.getName().toString(), method);
                    }
                    //invoke trigger
                    MethodInvocation invocation = ast.newMethodInvocation();
                    invocation.setName(ast.newSimpleName(method.getName().toString()));
                    //                        listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null);
                    //                        listRewrite.insertLast(ast.newExpressionStatement(invocation), null);
                    //                        listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null);
                    parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation));
                }

            }

            if (!(state.getVertex() instanceof FinalState)) {
                //continue from target state with plan generation
                StateMachineState targetState = transition.getTargetState();
                generatePlanForState(targetState, rewrite, transitionMethod, transitionsCopy);
            } else {
                if (transition.getTargetState() == null) {
                    notifyUser(state.getName() + " is not final and does not have a target state on transition "
                            + transition.getTransition().getName());
                    System.err.println(
                            state.getName() + " is not final and does not have a target state on transition "
                                    + transition.getTransition().getName());
                }
            }

        }

    }

    if (state.getVertex() instanceof FinalState) {
        //store generated method in methods
        generatedPlans.put(planMethodDeclaration.getName().toString(), planMethodDeclaration);
    }

}

From source file:br.com.objectos.way.core.code.jdt.ASTTest.java

License:Apache License

@SuppressWarnings("unchecked")
public void stackoverflow_answer() {
    AST ast = AST.newAST(AST.JLS8);
    CompilationUnit cu = ast.newCompilationUnit();

    PackageDeclaration p1 = ast.newPackageDeclaration();
    p1.setName(ast.newSimpleName("foo"));
    cu.setPackage(p1);/*from  w ww  .  j  ava  2  s. co  m*/

    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "java", "util", "Set" }));
    cu.imports().add(id);

    TypeDeclaration td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName("Foo"));
    TypeParameter tp = ast.newTypeParameter();
    tp.setName(ast.newSimpleName("X"));
    td.typeParameters().add(tp);
    cu.types().add(td);

    MethodDeclaration md = ast.newMethodDeclaration();
    md.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    md.setName(ast.newSimpleName("bar"));

    SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
    var.setType(ast.newSimpleType(ast.newSimpleName("String")));
    var.setName(ast.newSimpleName("a"));
    md.parameters().add(var);
    td.bodyDeclarations().add(md);

    Block block = ast.newBlock();
    md.setBody(block);

    MethodInvocation mi = ast.newMethodInvocation();
    mi.setName(ast.newSimpleName("x"));

    ExpressionStatement e = ast.newExpressionStatement(mi);
    block.statements().add(e);

    System.out.println(cu);
}

From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

private static void rewriteOnCreate(CompilationUnit unit, String dbName, List<String> tableCreators) {
    AST ast = unit.getAST();
    TypeDeclaration type = (TypeDeclaration) unit.types().get(0);
    MethodDeclaration onCreate = getMethod(type, ("onCreate"), null);
    if (onCreate != null) {
        Block methodBlock = ast.newBlock();

        // mOpenHelper = new
        // InlineOpenHelper(this.getContext(),"person.db",null,1);
        Assignment a = ast.newAssignment();
        a.setOperator(Assignment.Operator.ASSIGN);

        a.setLeftHandSide(ast.newSimpleName("mOpenHelper"));

        ClassInstanceCreation cc = ast.newClassInstanceCreation();
        cc.setType(ast.newSimpleType(ast.newSimpleName("SQLiteOpenHelper")));
        ThisExpression thisExp = ast.newThisExpression();
        MethodInvocation mi = ast.newMethodInvocation();
        mi.setName(ast.newSimpleName("getContext"));
        mi.setExpression(thisExp);//from  w  w w  . ja  v a 2  s.c  o m
        cc.arguments().add(mi);
        StringLiteral sl = ast.newStringLiteral();
        sl.setLiteralValue(dbName);

        cc.arguments().add(sl);
        cc.arguments().add(ast.newNullLiteral());
        cc.arguments().add(ast.newNumberLiteral("1"));
        a.setRightHandSide(cc);
        methodBlock.statements().add(ast.newExpressionStatement(a));

        AnonymousClassDeclaration acd = ast.newAnonymousClassDeclaration();
        cc.setAnonymousClassDeclaration(acd);
        genInnerSQLiteOpenHelper(acd, ast, tableCreators);

        a = ast.newAssignment();
        a.setOperator(Assignment.Operator.ASSIGN);

        a.setLeftHandSide(ast.newSimpleName("session"));

        ClassInstanceCreation cic = ast.newClassInstanceCreation();
        cic.setType(ast.newSimpleType(ast.newSimpleName("Session")));

        // SingleVariableDeclaration svd =
        // ast.newSingleVariableDeclaration();
        // svd.setName(ast.newSimpleName("mOpenHelper"));
        cic.arguments().add(ast.newSimpleName("mOpenHelper"));
        // vdf.setInitializer(cic);
        a.setRightHandSide(cic);
        // methodBlock.statements().add(vde);
        methodBlock.statements().add(ast.newExpressionStatement(a));

        ReturnStatement returnStmt = ast.newReturnStatement();
        returnStmt.setExpression(ast.newBooleanLiteral(true));
        methodBlock.statements().add(returnStmt);

        onCreate.setBody(methodBlock);
    }
}

From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

private static void genInnerSQLiteOpenHelper(AnonymousClassDeclaration acd, AST ast,
        List<String> tableCreators) {
    MethodDeclaration md = ast.newMethodDeclaration();
    md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC)));
    md.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
    md.setName(ast.newSimpleName("onCreate"));
    SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
    svd.setName(ast.newSimpleName("db"));
    svd.setType(ast.newSimpleType(ast.newSimpleName("SQLiteDatabase")));
    md.parameters().add(svd);//from ww w.jav  a  2  s.  co m
    Block innerBlock = ast.newBlock();
    md.setBody(innerBlock);
    VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("sql"));
    StringLiteral sl = ast.newStringLiteral();
    sl.setLiteralValue("");
    vdf.setInitializer(sl);
    VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
    vds.setType(ast.newSimpleType(ast.newSimpleName("String")));
    innerBlock.statements().add(vds);
    for (String creator : tableCreators) {
        String[] lines = creator.split(SourceAnalysis.LF);
        for (String line : lines) {
            Assignment a = ast.newAssignment();
            a.setOperator(Assignment.Operator.PLUS_ASSIGN);
            a.setLeftHandSide(ast.newSimpleName("sql"));
            StringLiteral temp = ast.newStringLiteral();
            temp.setLiteralValue(line);
            a.setRightHandSide(temp);
            innerBlock.statements().add(ast.newExpressionStatement(a));
        }

        MethodInvocation mi = ast.newMethodInvocation();
        mi.setName(ast.newSimpleName("execSQL"));
        mi.setExpression(ast.newSimpleName("db"));
        mi.arguments().add(ast.newSimpleName("sql"));
        innerBlock.statements().add(ast.newExpressionStatement(mi));
    }

    acd.bodyDeclarations().add(md);
    // onUpgrade
    md = ast.newMethodDeclaration();
    md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC)));
    md.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
    md.setName(ast.newSimpleName("onUpgrade"));
    svd = ast.newSingleVariableDeclaration();
    svd.setName(ast.newSimpleName("db"));
    svd.setType(ast.newSimpleType(ast.newSimpleName("SQLiteDatabase")));
    md.parameters().add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setName(ast.newSimpleName("oldVersion"));
    svd.setType(ast.newPrimitiveType(PrimitiveType.INT));
    md.parameters().add(svd);

    svd = ast.newSingleVariableDeclaration();
    svd.setName(ast.newSimpleName("newVersion"));
    svd.setType(ast.newPrimitiveType(PrimitiveType.INT));
    md.parameters().add(svd);

    innerBlock = ast.newBlock();
    md.setBody(innerBlock);
    acd.bodyDeclarations().add(md);
}

From source file:com.google.devtools.j2cpp.translate.ClassConverter.java

License:Open Source License

protected Statement createAssignment(IVariableBinding field, IVariableBinding param, AST ast) {
    SimpleName fieldName = ast.newSimpleName(field.getName());
    Types.addBinding(fieldName, field);
    SimpleName paramName = ast.newSimpleName(param.getName());
    Types.addBinding(paramName, param);
    Assignment assign = ast.newAssignment();
    assign.setLeftHandSide(fieldName);//from  w  w w . j a v  a  2  s.co m
    assign.setRightHandSide(paramName);
    Types.addBinding(assign, field.getType());
    return ast.newExpressionStatement(assign);
}

From source file:com.google.devtools.j2cpp.translate.DestructorGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
private void addReleaseStatements(MethodDeclaration method, List<IVariableBinding> fields) {
    // Find existing super.finalize(), if any.
    final boolean[] hasSuperFinalize = new boolean[1];
    method.accept(new ASTVisitor() {
        @Override//from   w  ww .  j  a  v a 2 s .c  o  m
        public void endVisit(SuperMethodInvocation node) {
            if (FINALIZE_METHOD.equals(node.getName().getIdentifier())) {
                hasSuperFinalize[0] = true;
            }
        }
    });

    List<Statement> statements = method.getBody().statements(); // safe by definition
    if (!statements.isEmpty() && statements.get(0) instanceof TryStatement) {
        TryStatement tryStatement = ((TryStatement) statements.get(0));
        if (tryStatement.getBody() != null) {
            statements = tryStatement.getBody().statements(); // safe by definition
        }
    }
    AST ast = method.getAST();
    int index = statements.size();
    for (IVariableBinding field : fields) {
        if (!field.getType().isPrimitive() && !Types.isWeakReference(field)) {
            Assignment assign = ast.newAssignment();
            SimpleName receiver = ast.newSimpleName(field.getName());
            Types.addBinding(receiver, field);
            assign.setLeftHandSide(receiver);
            assign.setRightHandSide(Types.newNullLiteral());
            Types.addBinding(assign, field.getDeclaringClass());
            ExpressionStatement stmt = ast.newExpressionStatement(assign);
            statements.add(index, stmt);
        }
    }
    if (Options.useReferenceCounting() && !hasSuperFinalize[0]) {
        SuperMethodInvocation call = ast.newSuperMethodInvocation();
        IMethodBinding methodBinding = Types.getMethodBinding(method);
        GeneratedMethodBinding binding = new GeneratedMethodBinding(destructorName, Modifier.PUBLIC,
                Types.mapTypeName("void"), methodBinding.getDeclaringClass(), false, false, true);
        Types.addBinding(call, binding);
        call.setName(ast.newSimpleName(destructorName));
        Types.addBinding(call.getName(), binding);
        ExpressionStatement stmt = ast.newExpressionStatement(call);
        statements.add(stmt);
    }
}

From source file:com.google.devtools.j2cpp.translate.InitializationNormalizer.java

License:Open Source License

private ExpressionStatement makeAssignmentStatement(VariableDeclarationFragment fragment) {
    AST ast = fragment.getAST();
    IVariableBinding varBinding = Types.getVariableBinding(fragment);
    Assignment assignment = ast.newAssignment();
    Types.addBinding(assignment, varBinding.getType());
    Expression lhs = ast.newSimpleName(fragment.getName().getIdentifier());
    Types.addBinding(lhs, varBinding);
    assignment.setLeftHandSide(lhs);/*w  ww  . j a va2 s  .  c  o m*/

    Expression initializer = fragment.getInitializer();
    if (initializer instanceof ArrayInitializer) {
        // An array initializer cannot be directly assigned, since by itself
        // it's just shorthand for an array creation node.  This therefore
        // builds an array creation node with the existing initializer.
        ArrayCreation arrayCreation = ast.newArrayCreation();
        ITypeBinding arrayType = varBinding.getType();
        Types.addBinding(arrayCreation, arrayType);
        Type newType = Types.makeIOSType(arrayType);
        assert newType != null;
        ArrayType newArrayType = ast.newArrayType(newType);
        Types.addBinding(newArrayType, arrayType);
        arrayCreation.setType(newArrayType);
        arrayCreation.setInitializer((ArrayInitializer) NodeCopier.copySubtree(ast, initializer));
        assignment.setRightHandSide(arrayCreation);
    } else {
        assignment.setRightHandSide(NodeCopier.copySubtree(ast, initializer));
    }
    return ast.newExpressionStatement(assignment);
}

From source file:com.google.devtools.j2cpp.translate.Rewriter.java

License:Open Source License

@Override
public boolean visit(FieldDeclaration node) {
    int mods = node.getModifiers();
    if (Modifier.isStatic(mods)) {
        ASTNode parent = node.getParent();
        @SuppressWarnings("unchecked")
        List<BodyDeclaration> classMembers = parent instanceof AbstractTypeDeclaration
                ? ((AbstractTypeDeclaration) parent).bodyDeclarations()
                : ((AnonymousClassDeclaration) parent).bodyDeclarations(); // safe by specification
        int indexOfNewMember = classMembers.indexOf(node) + 1;

        @SuppressWarnings("unchecked")
        List<VariableDeclarationFragment> fragments = node.fragments(); // safe by specification
        for (VariableDeclarationFragment var : fragments) {
            IVariableBinding binding = Types.getVariableBinding(var);
            if (Types.isPrimitiveConstant(binding) && Modifier.isPrivate(binding.getModifiers())) {
                // Don't define accessors for private constants, since they can be
                // directly referenced.
                continue;
            }/*from  w w  w . j  a  va 2  s . c  o m*/

            // rename varName to varName_, per Obj-C style guide
            SimpleName oldName = var.getName();
            ITypeBinding type = ((AbstractTypeDeclaration) node.getParent()).resolveBinding();
            String varName = NameTable.getStaticVarQualifiedName(type, oldName.getIdentifier());
            NameTable.rename(binding, varName);
            ITypeBinding typeBinding = binding.getType();
            var.setExtraDimensions(0); // if array, type was corrected above

            // add accessor(s)
            if (needsReader(var, classMembers)) {
                classMembers.add(indexOfNewMember++, makeStaticReader(var, mods));
            }
            if (!Modifier.isFinal(node.getModifiers()) && needsWriter(var, classMembers)) {
                classMembers.add(indexOfNewMember++,
                        makeStaticWriter(var, oldName.getIdentifier(), node.getType(), mods));
            }

            // move non-constant initialization to init block
            Expression initializer = var.getInitializer();
            if (initializer != null && initializer.resolveConstantExpressionValue() == null) {
                var.setInitializer(null);

                AST ast = var.getAST();
                SimpleName newName = ast.newSimpleName(varName);
                Types.addBinding(newName, binding);
                Assignment assign = ast.newAssignment();
                assign.setLeftHandSide(newName);
                Expression newInit = NodeCopier.copySubtree(ast, initializer);
                assign.setRightHandSide(newInit);
                Types.addBinding(assign, typeBinding);

                Block initBlock = ast.newBlock();
                @SuppressWarnings("unchecked")
                List<Statement> stmts = initBlock.statements(); // safe by definition
                stmts.add(ast.newExpressionStatement(assign));
                Initializer staticInitializer = ast.newInitializer();
                staticInitializer.setBody(initBlock);
                @SuppressWarnings("unchecked")
                List<IExtendedModifier> initMods = staticInitializer.modifiers(); // safe by definition
                initMods.add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
                classMembers.add(indexOfNewMember++, staticInitializer);
            }
        }
    }
    return true;
}

From source file:com.google.devtools.j2cpp.translate.Rewriter.java

License:Open Source License

/**
 * Add a static write accessor method for a specified variable.
 *//*from  ww  w  . ja va2 s  .  com*/
private MethodDeclaration makeStaticWriter(VariableDeclarationFragment var, String paramName, Type type,
        int modifiers) {
    AST ast = var.getAST();
    String varName = var.getName().getIdentifier();
    IVariableBinding varBinding = Types.getVariableBinding(var);

    Type returnType = ast.newPrimitiveType(PrimitiveType.VOID);
    Types.addBinding(returnType, ast.resolveWellKnownType("void"));
    String methodName = "set" + NameTable.capitalize(varName);
    MethodDeclaration accessor = createBlankAccessor(var, methodName, modifiers, returnType);
    GeneratedMethodBinding binding = new GeneratedMethodBinding(accessor, varBinding.getDeclaringClass(),
            false);
    Types.addBinding(accessor, binding);
    Types.addBinding(accessor.getName(), binding);

    SingleVariableDeclaration param = ast.newSingleVariableDeclaration();
    param.setName(ast.newSimpleName(paramName));
    Type paramType = NodeCopier.copySubtree(ast, type);
    param.setType(paramType);
    Types.addBinding(paramType, type.resolveBinding());
    @SuppressWarnings("unchecked")
    List<SingleVariableDeclaration> parameters = accessor.parameters(); // safe by definition
    GeneratedVariableBinding paramBinding = new GeneratedVariableBinding(paramName, 0, type.resolveBinding(),
            false, true, varBinding.getDeclaringClass(), binding);
    Types.addBinding(param, paramBinding);
    Types.addBinding(param.getName(), paramBinding);
    parameters.add(param);
    binding.addParameter(paramBinding);

    Assignment assign = ast.newAssignment();
    SimpleName sn = ast.newSimpleName(NameTable.getName(varBinding));
    assign.setLeftHandSide(sn);
    Types.addBinding(sn, varBinding);
    assign.setRightHandSide(NodeCopier.copySubtree(ast, param.getName()));
    Types.addBinding(assign, varBinding.getType());
    ExpressionStatement assignStmt = ast.newExpressionStatement(assign);

    @SuppressWarnings("unchecked")
    List<Statement> stmts = accessor.getBody().statements(); // safe by definition
    stmts.add(assignStmt);
    Symbols.scanAST(accessor);
    return accessor;
}