Example usage for org.eclipse.jdt.core.dom Statement toString

List of usage examples for org.eclipse.jdt.core.dom Statement toString

Introduction

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

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string representation of this node suitable for debugging purposes only.

Usage

From source file:changetypes.ASTVisitorAtomicChange.java

License:Open Source License

public boolean visit(IfStatement node) {
    Statement thenStmt = node.getThenStatement();
    Statement elseStmt = node.getElseStatement();
    Expression condExpr = node.getExpression();

    String thenStr = thenStmt.toString().replace('\n', ' ');
    String elseStr = "";
    if (elseStmt != null) {
        elseStr = elseStmt.toString().replace('\n', ' ');
    }/*from  www .  j a v  a  2 s  .  c o m*/
    if (this.mtbStack.isEmpty()) {
        return true;
    }
    IMethodBinding mtb = (IMethodBinding) this.mtbStack.peek();
    String methodStr = getQualifiedName(mtb);
    String condStr = condExpr.toString();

    condStr = edit_str(condStr);
    thenStr = edit_str(thenStr);
    elseStr = edit_str(elseStr);
    try {
        this.facts.add(Fact.makeConditionalFact(condStr, thenStr, elseStr, methodStr));
    } catch (Exception e) {
        System.err.println("Cannot resolve conditional \"" + condExpr.toString() + "\"");
        System.out.println("ifStmt: " + thenStr);
        System.out.println("elseStmt: " + elseStr);
        System.err.println(e.getMessage());
    }
    return true;
}

From source file:com.google.gdt.eclipse.designer.model.widgets.panels.grid.FlexTableInfo.java

License:Open Source License

/**
 * Adds broadcast listener that keeps <code>FlexTableHelper.fixRowSpan()</code> as last statement
 * for this {@link FlexTableInfo}.//from  w  ww. j ava  2  s .  co m
 */
private void keepLast_FlexTableHelper() {
    addBroadcastListener(new JavaEventListener() {
        @Override
        public void target_isTerminalStatement(JavaInfo parent, JavaInfo child, Statement statement,
                boolean[] terminal) {
            if (parent == FlexTableInfo.this && isFlexTableHelperInvocation(statement)) {
                terminal[0] = true;
            }
        }

        private boolean isFlexTableHelperInvocation(Statement statement) {
            return statement.toString().contains("FlexTableHelper.fixRowSpan(");
        }
    });
}

From source file:com.motorola.studio.android.generatecode.AbstractCodeGenerator.java

License:Apache License

/**
 * Checks if the given declarationg statement is already available in the list of statements
 * @param declarationStatement//from  w  w w  .j  ava  2s. c  o  m
 * @param sameClass true, it will compare if there is the same statement class in the body of the methodDeclaration (but the content may be different), false it will ignore the class and it will compare if the content is the same (given by toString.equals())
 * @param alreadyDeclared
 * @param statements
 * @return true if statement found, false otherwise
 */
protected boolean isStatementAlreadyDeclared(Statement declarationStatement, boolean sameClass,
        List<Statement> statements) {
    boolean alreadyDeclared = false;
    if (statements != null) {
        for (Statement statement : statements) {
            if ((!sameClass && declarationStatement.toString().equals(statement.toString()))
                    || (sameClass && statement.getClass().equals(declarationStatement.getClass()))) {
                alreadyDeclared = true;
                break;
            }
        }
    }
    return alreadyDeclared;
}

From source file:com.motorola.studio.android.generatecode.AbstractCodeGenerator.java

License:Apache License

/**
 * Finds a statement if already declared
 * @param declarationStatement/*from  w w  w .  java2 s . co  m*/
 * @param sameClass true, it will compare if there is the same statement class in the body of the methodDeclaration (but the content may be different), false it will ignore the class and it will compare if the content is the same (given by toString.equals())
 * @param alreadyDeclared
 * @param statements
 * @return null if not found, the reference to the statement if it is found
 */
protected Statement findIfStatementAlreadyDeclared(Statement declarationStatement, boolean sameClass,
        List<Statement> statements) {
    Statement foundStatement = null;
    if (statements != null) {
        for (Statement statement : statements) {
            if ((!sameClass && declarationStatement.toString().equals(statement.toString()))
                    || (sameClass && statement.getClass().equals(declarationStatement.getClass()))) {
                foundStatement = statement;
                break;
            }
        }
    }
    return foundStatement;
}

From source file:egovframework.mgt.fit.library.parser.visitor.ClassParsingVisitor.java

License:Apache License

/**
 *   ?   .//from  w w  w. j  a v  a  2s. c  o m
 * @param node  
 * @return  ?
 */
private StatementList<AbstractStatement> getStatements(Block node) {
    StatementList<AbstractStatement> statements = new StatementList<AbstractStatement>();
    for (Object obj : node.statements()) {
        if (obj instanceof Statement) {
            Statement s = (Statement) obj;
            if (obj instanceof Block) {
                statements.addStatement(getStatements((Block) obj));
            } else {
                StatementLine sl = new StatementLine();
                sl.setStatementType(s.getNodeType());
                sl.setStatement(s.toString());
                statements.addStatement(sl);
            }
        }
    }
    return statements;
}

From source file:gr.uop.intermittent.faults.intermittentfaultscodeparser.ParsingWithEclipseJDT.java

private static void blockIterate(final Block block, final CompilationUnit cu, final Set fieldNames,
        final int blockNum, final Map<Integer, Set> variableNames, final Set<String> parameterNames,
        final BlockStructure bs, final ClassStructure cs, final FileStructure fStr) {
    List<Statement> statements = block.statements();
    // System.out.println("Statements : " + statements.toString());

    Set variables = new HashSet();
    variableNames.put(blockNum, variables);

    for (Statement s : statements) {

        if (s.toString().startsWith("if") || s.toString().startsWith("while") || s.toString().startsWith("for")
                || s.toString().startsWith("try")) {
            s.accept(new ASTVisitor() {
                public boolean visit(Block node) {
                    if (node != null) {
                        //  System.out.println("Block " + node.toString());
                        int blockNumber = blockNum + 1;
                        BlockStructure bs2 = new BlockStructure();
                        bs2.setBlockNum(blockNum);
                        bs2.setBlockParent(bs);
                        bs2.setVariables(new ArrayList<VariableStructure>());
                        Info info = new Info();
                        info.setLine(cu.getLineNumber(node.getStartPosition()));
                        info.setClassName(cs.getClassName());
                        bs2.addBlockInfo(info);
                        bs.addChildBlockStructure(bs2);
                        blockIterate(node, cu, fieldNames, blockNumber, variableNames, parameterNames, bs2, cs,
                                fStr);//from w  w  w .  j a v a2 s . c  o m

                        for (int i = blockNumber; i < variableNames.size(); i++)
                            variableNames.remove(i);
                    }
                    return false;
                }
            });
        } else {
            s.accept(new ASTVisitor() {

                public boolean visit(VariableDeclarationStatement node) {
                    String name = node.fragments().get(0).toString().split("=")[0];
                    String type = node.getType().toString();
                    variableNames.get(blockNum).add(name);
                    System.out.println("Declaration of variable '" + name + "' at line"
                            + cu.getLineNumber(node.getStartPosition()) + cs.getClassName());
                    VariableStructure vs = new VariableStructure();
                    vs.setBlockParent(bs);
                    Info info = new Info();
                    info.setClassName(cs.getClassName());
                    info.setLine(cu.getLineNumber(node.getStartPosition()));
                    fStr.addInfoInLineDictionary(cu.getLineNumber(node.getStartPosition()), info);
                    vs.addVariableInfo(info);
                    vs.setVariableName(name);
                    vs.setVariableType(type);
                    bs.addVariableStructure(vs);
                    return false;
                }

                public boolean visit(SimpleName node) {
                    if (searchVariable(variableNames, node.getIdentifier()) != -1
                            || searchField(fieldNames, node.getIdentifier())
                            || searchParameter(parameterNames, node.getIdentifier())) {
                        System.out.println("Usage of variable/field/parameter '" + node.getIdentifier()
                                + "' at line " + cu.getLineNumber(node.getStartPosition()) + cs.getClassName());

                        Info info = SearchCodeStructure.searchFieldOrVariable(node.getIdentifier(), bs);
                        Info infoNew = new Info();
                        infoNew.setClassName(cs.getClassName());
                        infoNew.setFile(cs.getParent().getFileName());
                        infoNew.setLine(cu.getLineNumber(node.getStartPosition()));
                        fStr.addInfoInLineDictionary(cu.getLineNumber(node.getStartPosition()), infoNew);
                        if (info.getParent() instanceof FieldStructure) {
                            ((FieldStructure) info.getParent()).addFieldInfo(infoNew);
                        } else if (info.getParent() instanceof VariableStructure) {
                            ((VariableStructure) info.getParent()).addVariableInfo(infoNew);
                        } else if (info.getParent() instanceof ParameterStructure) {
                            ((ParameterStructure) info.getParent()).addParameterInfo(infoNew);
                        }
                    }
                    return false;
                }

                public boolean visit(MethodInvocation node) {
                    System.out.println("MethodInvocation: " + node.getName() + " at line "
                            + cu.getLineNumber(node.getStartPosition()) + " with arguments " + node.arguments()
                            + cs.getClassName());

                    Expression expression = node.getExpression();

                    ClassStructure classStructure = null;
                    Info info = new Info();
                    if (expression != null) {
                        String className = "";
                        info = SearchCodeStructure.searchFieldOrVariable(expression.toString(), bs);
                        if (info != null) {
                            if (info.getParent() instanceof FieldStructure) {
                                className = ((FieldStructure) info.getParent()).getFieldType();
                            } else if (info.getParent() instanceof VariableStructure) {
                                className = ((VariableStructure) info.getParent()).getVariableType();
                            } else if (info.getParent() instanceof ParameterStructure) {
                                className = ((ParameterStructure) info.getParent()).getParameterType();
                            }
                            classStructure = SearchCodeStructure.searchClass(className, myFS);
                        }
                        System.out.println("Expr: " + expression.toString());
                    } else {
                        classStructure = cs;
                    }

                    Info info2 = SearchCodeStructure.searchMethod(node.getName().getIdentifier(),
                            classStructure);

                    if (info2 == null) {
                        info2 = SearchCodeStructure.searchMethodInAllFiles(node.getName().getIdentifier(),
                                myFS);
                    }

                    Info infoNew = new Info();
                    if (info2 != null) {
                        infoNew.setClassName(cs.getClassName());
                        infoNew.setFile(cs.getParent().getFileName());
                        infoNew.setLine(cu.getLineNumber(node.getStartPosition()));
                        fStr.addInfoInLineDictionary(cu.getLineNumber(node.getStartPosition()), infoNew);
                        ((MethodStructure) info2.getParent()).addMethodInfo(infoNew);
                    }

                    for (Object param : node.arguments()) {
                        info = SearchCodeStructure.searchFieldOrVariable(param.toString(), bs);
                        Info infoNew2 = new Info();
                        infoNew2.setClassName(cs.getClassName());
                        infoNew2.setFile(cs.getParent().getFileName());
                        infoNew2.setLine(cu.getLineNumber(node.getStartPosition()));
                        fStr.addInfoInLineDictionary(cu.getLineNumber(node.getStartPosition()), infoNew2);
                        if (info != null) {
                            if (info.getParent() instanceof FieldStructure) {
                                ((FieldStructure) info.getParent()).addFieldInfo(infoNew2);
                                DependancyInfo dependancyOn = new DependancyInfo();
                                dependancyOn.setDependencyInfoNode(info);
                                dependancyOn.setIsField(true);
                                dependancyOn.setName(param.toString());
                                infoNew.addDependancyInfo(dependancyOn);
                            } else if (info.getParent() instanceof VariableStructure) {
                                ((VariableStructure) info.getParent()).addVariableInfo(infoNew2);
                                DependancyInfo dependancyOn = new DependancyInfo();
                                dependancyOn.setDependencyInfoNode(info);
                                dependancyOn.setIsVariable(true);
                                dependancyOn.setName(param.toString());
                                infoNew.addDependancyInfo(dependancyOn);
                            } else if (info.getParent() instanceof ParameterStructure) {
                                ((ParameterStructure) info.getParent()).addParameterInfo(infoNew2);
                                DependancyInfo dependancyOn = new DependancyInfo();
                                dependancyOn.setDependencyInfoNode(info);
                                dependancyOn.setIsParam(true);
                                dependancyOn.setName(param.toString());
                                infoNew.addDependancyInfo(dependancyOn);
                            }
                        }
                    }

                    return false;
                }

                public boolean visit(Block node) {
                    if (node != null) {
                        //  System.out.println("Block " + node.toString());
                        int blockNumber = blockNum + 1;
                        BlockStructure bs2 = new BlockStructure();
                        bs2.setBlockNum(blockNum);
                        bs2.setBlockParent(bs);
                        bs2.setVariables(new ArrayList<VariableStructure>());
                        Info info = new Info();
                        info.setLine(cu.getLineNumber(node.getStartPosition()));
                        info.setClassName(cs.getClassName());
                        bs2.addBlockInfo(info);
                        bs.addChildBlockStructure(bs2);
                        blockIterate(node, cu, fieldNames, blockNumber, variableNames, parameterNames, bs2, cs,
                                fStr);

                        for (int i = blockNumber; i < variableNames.size(); i++)
                            variableNames.remove(i);
                    }
                    return false;
                }
            });
        }
    }
}

From source file:logic.Translator.java

License:Open Source License

/** This method translates an IF statement.
 * @param currentStatement the current statement.
 * @param md the method under translation.
 * @param normalStatementsList list of actual "normal" statements to handle.
 *//*from ww w  .j  a  v  a2s .  c o m*/
private void translateIfStatement(IfStatement currentStatement, MethodDeclaration md,
        LinkedList<ASTNode> normalStatementsList) {
    //metodo che traduce un IF

    //creiamo lo stato che rappresenta l'ingresso nell'IF

    // creiamo l'azione
    String a = "";
    String graphicAction = "";
    for (int i = 0; i < normalStatementsList.size(); i++) {
        String s = translateVars(normalStatementsList.get(i), md);
        if (s.equals("") == false) {
            a += Util.appendNewLine(s);
            graphicAction += Util.appendNewLine(normalStatementsList.get(i).toString());
        }
    }

    if (a.equals("") == false) {
        // se fino a questo punto l'azione non  vuota, creiamo la nuova
        // transizione, altrimenti lo stato che rappresenta l'ingresso
        // nell'IF  lo stato attuale

        a += createE();
        graphicAction += "postEvent(E);";

        // creiamo il trigger: controlla solo che l'evento sia di tipo "E"
        String trigger = createTriggerE();

        this.contSimpleStates++;
        int targetState = this.contSimpleStates; //prossimo stato (stato che rappresenta l'ingresso nell'IF)

        // creiamo lo stato semplice target
        createIntermediateSimpleState(targetState, md);

        // creiamo la transizione normale
        createNormalTransition(this.actualState, targetState, md, trigger, a, "E", graphicAction);

        // aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
        this.actualState = targetState;
    }

    //A partire dallo stato che rappresenta l'ingresso nell'IF, creiamo due transizioni:
    // - una che parte dallo stato che rappresenta l'ingresso nell'IF e,
    //   rispettando la condizione dell'IF, va nello stato semplice iniziale del blocco IF
    //   (stato_ingresso_if ---- E[condizione_if]/postMessage(E) ---> stato_iniziale_blocco_if);
    // - l'altra che parte dallo stato che rappresenta l'ingresso nell'IF e,
    //   NON rispettando la condizione dell'IF, va nello stato semplice iniziale del blocco ELSE
    //   (stato_ingresso_if ---- E[!condizione_if]/postMessage(E) ---> stato_iniziale_blocco_else).
    //Queste due transizioni hanno come azione soltanto l'invio dell'evento "E" e specificano
    //il trigger, altrimenti successivamente non  possibile specificarlo.
    //Poi, la traduzione del blocco IF partir dallo stato semplice "stato_iniziale_blocco_if",
    //mentre la traduzione del blocco ELSE partir dallo stato semplice "stato_iniziale_blocco_else".

    //ricaviamo lo stato che rappresenta l'ingresso nell'IF (creato in precedenza)
    int stato_ingresso_if = this.actualState;

    //creiamo la transizione:
    //stato_ingresso_if ---- E[condizione_if]/postMessage(E) ---> stato_iniziale_blocco_if

    //creiamo il trigger
    String trigger1 = "";
    trigger1 += "if((msg != null) && (msg instanceof DSCStarEvent) && (((DSCStarEvent) msg).getType() == DSCStarEvent.E)){\n";
    trigger1 += "if (" + translateVars(currentStatement.getExpression(), md) + "){\n"; //traduciamo la condizione dell'IF
    trigger1 += "return true;\n";
    trigger1 += "}\n";
    trigger1 += "}\n";
    trigger1 += "return false;\n";
    String graphicTrigger1 = "E[" + currentStatement.getExpression() + "]";

    //creiamo l'azione
    String action1 = createE();

    //creiamo lo stato iniziale del blocco IF
    this.contSimpleStates++;
    int stato_iniziale_blocco_if = this.contSimpleStates;
    createIntermediateSimpleState(stato_iniziale_blocco_if, md);

    //creiamo la transizione da "stato_ingresso_if" a "stato_iniziale_blocco_if"
    createNormalTransition(stato_ingresso_if, stato_iniziale_blocco_if, md, trigger1, action1, graphicTrigger1,
            "postEvent(E);");

    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
    this.actualState = stato_iniziale_blocco_if;

    //traduciamo il blocco IF
    boolean traduzioneBloccoIfInterrotta = false; //indica se la traduzione  stata interrotta perch  stato trovato un "return"
    if (currentStatement.getThenStatement() != null) {
        //siamo nel caso in cui: if(...){ c' qualche istruzione }

        if (currentStatement.getThenStatement() instanceof Block) {
            //siamo nel caso in cui: if(...){ pi istruzioni }
            traduzioneBloccoIfInterrotta = translateBlock((Block) currentStatement.getThenStatement(), md);
        } else {
            //siamo nel caso in cui: if(...) una istruzione

            //chiamiamo il metodo incaricato di gestire gli statement "speciali",
            //passandogli una lista vuota di statement "normali" da gestire
            boolean specialStatement = handleSpecialStatement(currentStatement.getThenStatement(), md,
                    new LinkedList<ASTNode>());
            if (specialStatement == false) {
                //se lo statement corrente non  uno statement "speciale",
                //lo gestiamo adesso creando un'apposita transizione
                Statement thenStat = currentStatement.getThenStatement();

                //creiamo l'azione
                String action = "";
                String graphicAction2 = "";
                String s = translateVars(thenStat, md);

                if (s.equals("") == false) {
                    //se l'istruzione attuale non  vuota, procediamo

                    action += Util.appendNewLine(s);
                    graphicAction2 += Util.appendNewLine(thenStat.toString());
                    action += createE();
                    graphicAction2 += "postEvent(E);";

                    //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
                    String trigger = createTriggerE();

                    //creiamo lo stato semplice target
                    this.contSimpleStates++;
                    int targetState = this.contSimpleStates;
                    createIntermediateSimpleState(targetState, md);

                    //creiamo la transizione che va dallo stato iniziale del blocco IF al nuovo stato target
                    createNormalTransition(stato_iniziale_blocco_if, targetState, md, trigger, action, "E",
                            graphicAction2);

                    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
                    this.actualState = targetState;
                }
            } else if (currentStatement.getThenStatement() instanceof ReturnStatement) {
                //indichiamo che  stato trovato un "return" nell'unica istruzione dell'IF
                traduzioneBloccoIfInterrotta = true;
            }
        }
    }

    //ricaviamo lo stato finale del blocco IF
    int stato_finale_blocco_if = this.actualState;

    //creiamo la transizione:
    //stato_ingresso_if ---- E[!condizione_if]/postMessage(E) ---> stato_iniziale_blocco_else

    //creiamo il trigger
    String trigger2 = "";
    trigger2 += "if((msg != null) && (msg instanceof DSCStarEvent) && (((DSCStarEvent) msg).getType() == DSCStarEvent.E)){\n";
    trigger2 += "if (!(" + translateVars(currentStatement.getExpression(), md) + ")){\n"; //traduciamo la condizione dell'IF
    trigger2 += "return true;\n";
    trigger2 += "}\n";
    trigger2 += "}\n";
    trigger2 += "return false;\n";
    String graphicTrigger2 = "E[!(" + currentStatement.getExpression() + ")]";

    //creiamo l'azione
    String action2 = createE();

    //creiamo lo stato iniziale del blocco ELSE
    this.contSimpleStates++;
    int stato_iniziale_blocco_else = this.contSimpleStates;
    createIntermediateSimpleState(stato_iniziale_blocco_else, md);

    //creiamo la transizione da "stato_ingresso_if" a "stato_iniziale_blocco_else"
    createNormalTransition(stato_ingresso_if, stato_iniziale_blocco_else, md, trigger2, action2,
            graphicTrigger2, "postEvent(E);");

    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
    this.actualState = stato_iniziale_blocco_else;

    //traduciamo il blocco ELSE
    boolean traduzioneBloccoElseInterrotta = false; //indica se la traduzione  stata interrotta perch  stato trovato un "return"
    if (currentStatement.getElseStatement() != null) {
        //siamo nel caso in cui: else{ c' qualche istruzione }

        if (currentStatement.getElseStatement() instanceof Block) {
            //siamo nel caso in cui: else{ pi istruzioni }
            traduzioneBloccoElseInterrotta = translateBlock((Block) currentStatement.getElseStatement(), md);
        } else {
            //siamo nel caso in cui: else una istruzione

            //chiamiamo il metodo incaricato di gestire gli statement "speciali",
            //passandogli una lista vuota di statement "normali" da gestire
            boolean specialStatement = handleSpecialStatement(currentStatement.getElseStatement(), md,
                    new LinkedList<ASTNode>());
            if (specialStatement == false) {
                //se lo statement corrente non  uno statement "speciale",
                //lo gestiamo adesso creando un'apposita transizione
                Statement elseStat = currentStatement.getElseStatement();

                //creiamo l'azione
                String action = "";
                String graphicAct = "";
                String s = translateVars(elseStat, md);

                if (s.equals("") == false) {
                    //se l'istruzione attuale non  vuota, procediamo

                    action += Util.appendNewLine(s);
                    graphicAct += Util.appendNewLine(elseStat.toString());
                    action += createE();
                    graphicAct += "postEvent(E);";

                    //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
                    String trigger = createTriggerE();

                    //creiamo lo stato semplice target
                    this.contSimpleStates++;
                    int targetState = this.contSimpleStates;
                    createIntermediateSimpleState(targetState, md);

                    //creiamo la transizione che va dallo stato iniziale del blocco ELSE al nuovo stato target
                    createNormalTransition(stato_iniziale_blocco_else, targetState, md, trigger, action, "E",
                            graphicAct);

                    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
                    this.actualState = targetState;
                }
            } else if (currentStatement.getElseStatement() instanceof ReturnStatement) {
                //indichiamo che  stato trovato un "return" nell'unica istruzione dell'ELSE
                traduzioneBloccoElseInterrotta = true;
            }
        }
    }

    //ricaviamo lo stato finale del blocco ELSE
    int stato_finale_blocco_else = this.actualState;

    if (traduzioneBloccoIfInterrotta == false && traduzioneBloccoElseInterrotta == false) {
        //se la traduzione del blocco IF e del blocco ELSE non  stata interrotta
        //(cio, se non  stato trovato un "return" nel blocco IF e nel blocco ELSE),
        //dopo aver tradotto i blocchi dell'IF e dell'ELSE, creiamo un nuovo stato semplice
        //"stato_fin" e due transizioni:
        // - una che parte dallo stato finale del blocco IF e va nel nuovo stato semplice "stato_fin"
        //   (stato_finale_blocco_if ---- E/postMessage(E) ---> stato_fin);
        // - l'altra parte dallo stato finale del blocco ELSE e va nel nuovo stato semplice "stato_fin"
        //   (stato_finale_blocco_else ---- E/postMessage(E) ---> stato_fin);
        //Queste due transizioni permettono di eseguire le istruzioni successive all'IF/ELSE
        //presenti nel blocco di codice parent, sia se abbiamo eseguito l'IF che se abbiamo
        //eseguito l'ELSE. Infatti, quando riprender la traduzione nel blocco di codice
        //parent dell'IF/ELSE (nel metodo "translateBlock"), si ripartir dallo stato attuale
        //"stato_fin" e le operazioni presenti dopo l'IF/ELSE nel blocco di codice parent
        //potranno essere eseguite sia quando viene eseguito l'IF che quando viene eseguito l'ELSE.

        //creiamo lo stato semplice "stato_fin"
        this.contSimpleStates++;
        int stato_fin = this.contSimpleStates;
        createIntermediateSimpleState(stato_fin, md);

        //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
        String trigger3 = createTriggerE();

        //creiamo l'azione
        String action3 = createE();

        //creiamo la transizione:
        //stato_finale_blocco_if ---- E/postMessage(E) ---> stato_fin
        createNormalTransition(stato_finale_blocco_if, stato_fin, md, trigger3, action3, "E", "postEvent(E);");

        //creiamo la transizione:
        //stato_finale_blocco_else ---- E/postMessage(E) ---> stato_fin
        createNormalTransition(stato_finale_blocco_else, stato_fin, md, trigger3, action3, "E",
                "postEvent(E);");

        //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
        this.actualState = stato_fin;
    } else if (traduzioneBloccoIfInterrotta == false) {
        //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
        this.actualState = stato_finale_blocco_if;
    } else if (traduzioneBloccoElseInterrotta == false) {
        //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
        this.actualState = stato_finale_blocco_else;
    }
}

From source file:logic.Translator.java

License:Open Source License

/** This method translates a WHILE statement.
 * @param currentStatement the current statement.
 * @param md the method under translation.
 * @param normalStatementsList list of actual "normal" statements to handle.
 *//*  w ww.  j av a  2s  .c o  m*/
private void translateWhileStatement(WhileStatement currentStatement, MethodDeclaration md,
        LinkedList<ASTNode> normalStatementsList) {
    //metodo che traduce un WHILE

    //creiamo lo stato che rappresenta l'ingresso nel WHILE

    //creiamo l'azione
    String a = "";
    String graphicAction = "";
    for (int i = 0; i < normalStatementsList.size(); i++) {
        String s = translateVars(normalStatementsList.get(i), md);
        if (s.equals("") == false) {
            a += Util.appendNewLine(s);
            graphicAction += Util.appendNewLine(normalStatementsList.get(i).toString());
        }
    }

    if (a.equals("") == false) {
        // se fino a questo punto l'azione non  vuota, creiamo la nuova
        // transizione, altrimenti lo stato che rappresenta l'ingresso nel
        // WHILE  lo stato attuale

        a += createE();
        graphicAction += "postEvent(E);";

        // creiamo il trigger: controlla solo che l'evento sia di tipo "E"
        String trigger = createTriggerE();

        this.contSimpleStates++;
        int targetState = this.contSimpleStates; // prossimo stato (stato che rappresenta l'ingresso nel WHILE)

        // creiamo lo stato semplice target
        createIntermediateSimpleState(targetState, md);

        // creiamo la transizione normale
        createNormalTransition(this.actualState, targetState, md, trigger, a, "E", graphicAction);

        // aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
        this.actualState = targetState;
    }

    //ricaviamo lo stato che rappresenta l'ingresso nel WHILE (creato in precedenza)
    int stato_ingresso_while = this.actualState;

    //creiamo la transizione:
    //stato_ingresso_while ---- E[condizione_while]/postMessage(E) ---> stato_iniziale_blocco_while

    //creiamo il trigger
    String trigger1 = "";
    trigger1 += "if((msg != null) && (msg instanceof DSCStarEvent) && (((DSCStarEvent) msg).getType() == DSCStarEvent.E)){\n";
    trigger1 += "if (" + translateVars(currentStatement.getExpression(), md) + "){\n"; //traduciamo la condizione del WHILE
    trigger1 += "return true;\n";
    trigger1 += "}\n";
    trigger1 += "}\n";
    trigger1 += "return false;\n";
    String graphicTrigger1 = "E[" + currentStatement.getExpression() + "]";

    //creiamo l'azione
    String action1 = createE();

    //creiamo lo stato iniziale del blocco WHILE
    this.contSimpleStates++;
    int stato_iniziale_blocco_while = this.contSimpleStates;
    createIntermediateSimpleState(stato_iniziale_blocco_while, md);

    //creiamo la transizione da "stato_ingresso_while" a "stato_iniziale_blocco_while"
    createNormalTransition(stato_ingresso_while, stato_iniziale_blocco_while, md, trigger1, action1,
            graphicTrigger1, "postEvent(E);");

    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
    this.actualState = stato_iniziale_blocco_while;

    //traduciamo il blocco WHILE
    boolean traduzioneBloccoWhileInterrotta = false; //indica se la traduzione  stata interrotta perch  stato trovato un "return"
    if (currentStatement.getBody() != null) {
        //siamo nel caso in cui: while(...){ c' qualche istruzione }

        if (currentStatement.getBody() instanceof Block) {
            //siamo nel caso in cui: while(...){ pi istruzioni }
            traduzioneBloccoWhileInterrotta = translateBlock((Block) currentStatement.getBody(), md);
        } else {
            //siamo nel caso in cui: while(...) una istruzione

            //chiamiamo il metodo incaricato di gestire gli statement "speciali",
            //passandogli una lista vuota di statement "normali" da gestire
            boolean specialStatement = handleSpecialStatement(currentStatement.getBody(), md,
                    new LinkedList<ASTNode>());
            if (specialStatement == false) {
                //se lo statement corrente non  uno statement "speciale",
                //lo gestiamo adesso creando un'apposita transizione
                Statement bodyStat = currentStatement.getBody();

                //creiamo l'azione
                String action = "";
                String graphicAct = "";
                String s = translateVars(bodyStat, md);

                if (s.equals("") == false) {
                    //se l'istruzione attuale non  vuota, procediamo

                    action += Util.appendNewLine(s);
                    graphicAct += Util.appendNewLine(bodyStat.toString());
                    action += createE();
                    graphicAct += "postEvent(E);";

                    //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
                    String trigger = createTriggerE();

                    //creiamo lo stato semplice target
                    this.contSimpleStates++;
                    int targetState = this.contSimpleStates;
                    createIntermediateSimpleState(targetState, md);

                    //creiamo la transizione che va dallo stato iniziale del blocco WHILE al nuovo stato target
                    createNormalTransition(stato_iniziale_blocco_while, targetState, md, trigger, action, "E",
                            graphicAct);

                    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
                    this.actualState = targetState;
                }
            } else if (currentStatement.getBody() instanceof ReturnStatement) {
                //indichiamo che  stato trovato un "return" nell'unica istruzione del WHILE
                traduzioneBloccoWhileInterrotta = true;
            }
        }
    }

    //ricaviamo lo stato finale del blocco WHILE
    int stato_finale_blocco_while = this.actualState;

    if (traduzioneBloccoWhileInterrotta == false) {
        //se la traduzione del blocco WHILE non  stata interrotta
        //(cio, se non  stato trovato un "return" nel blocco WHILE),
        //creiamo la transizione:
        //stato_finale_blocco_while ---- E/postMessage(E) ---> stato_ingresso_while

        //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
        String trigger2 = createTriggerE();

        //creiamo l'azione
        String action2 = createE();

        //creiamo la transizione che va da "stato_finale_blocco_while" a "stato_ingresso_while"
        createNormalTransition(stato_finale_blocco_while, stato_ingresso_while, md, trigger2, action2, "E",
                "postEvent(E);");
    }

    //creiamo la transizione:
    //stato_ingresso_while ---- E[!condizione_while]/postMessage(E) ---> stato_fin

    //creiamo il trigger
    String trigger3 = "";
    trigger3 += "if((msg != null) && (msg instanceof DSCStarEvent) && (((DSCStarEvent) msg).getType() == DSCStarEvent.E)){\n";
    trigger3 += "if (!(" + translateVars(currentStatement.getExpression(), md) + ")){\n"; //traduciamo la condizione del WHILE
    trigger3 += "return true;\n";
    trigger3 += "}\n";
    trigger3 += "}\n";
    trigger3 += "return false;\n";
    String graphicTrigger3 = "E[!(" + currentStatement.getExpression() + ")]";

    //creiamo l'azione
    String action3 = createE();

    //creiamo lo stato semplice "stato_fin"
    this.contSimpleStates++;
    int stato_fin = this.contSimpleStates;
    createIntermediateSimpleState(stato_fin, md);

    //creiamo la transizione da "stato_ingresso_while" a "stato_fin"
    createNormalTransition(stato_ingresso_while, stato_fin, md, trigger3, action3, graphicTrigger3,
            "postEvent(E);");

    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
    this.actualState = stato_fin;
}

From source file:logic.Translator.java

License:Open Source License

/** This method translates a FOR statement.
 * @param currentStatement the current statement.
 * @param md the method under translation.
 * @param normalStatementsList list of actual "normal" statements to handle.
 *//*  ww w .j  av a 2  s  .c  o m*/
private void translateForStatement(ForStatement currentStatement, MethodDeclaration md,
        LinkedList<ASTNode> normalStatementsList) {
    //metodo che traduce un FOR

    //creiamo lo stato che rappresenta l'ingresso nel FOR

    if (this.translationType == KEY_STATEMENTS_BASED) {
        // creiamo l'azione
        String action = "";
        String graphicAction = "";
        for (int i = 0; i < normalStatementsList.size(); i++) {
            String s = translateVars(normalStatementsList.get(i), md);
            if (s.equals("") == false) {
                action += Util.appendNewLine(s);
                graphicAction += Util.appendNewLine(normalStatementsList.get(i).toString());
            }
        }

        // inseriamo in questa azione l'inizializzazione degli indici del
        // FOR (ad esempio: for(i = 0; ... ))
        for (int i = 0; i < currentStatement.initializers().size(); i++) {
            String s = translateVars((ASTNode) currentStatement.initializers().get(i), md);
            if (s.equals("") == false) {
                action += s + ";\n";
                graphicAction += currentStatement.initializers().get(i) + ";\n";
            }
        }

        if (action.equals("") == false) {
            // se fino a questo punto l'azione non  vuota, creiamo la nuova
            // transizione, altrimenti lo stato che rappresenta l'ingresso
            // nel FOR  lo stato attuale

            action += createE();
            graphicAction += "postEvent(E);";

            // creiamo il trigger: controlla solo che l'evento sia di tipo "E"
            String trigger = createTriggerE();

            this.contSimpleStates++;
            int targetState = this.contSimpleStates; // prossimo stato (stato che rappresenta l'ingresso nel FOR)

            // creiamo lo stato semplice target
            createIntermediateSimpleState(targetState, md);

            // creiamo la transizione normale
            createNormalTransition(this.actualState, targetState, md, trigger, action, "E", graphicAction);

            // aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
            this.actualState = targetState;
        }
    } else if (this.translationType == FULL) {
        //per ogni inizializzazione di un indice del FOR, creiamo una transizione
        for (int i = 0; i < currentStatement.initializers().size(); i++) {
            //inseriamo in questa azione l'inizializzazione dell'indice del FOR corrente
            //(ad esempio: for(i = 0; ... ))
            String s = translateVars((ASTNode) currentStatement.initializers().get(i), md);
            if (s.equals("") == false) {
                //creiamo l'azione
                String action = "";
                String graphicAction = "";
                action += s + ";\n";
                graphicAction += currentStatement.initializers().get(i) + ";\n";
                action += createE();
                graphicAction += "postEvent(E);";

                //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
                String trigger = createTriggerE();

                this.contSimpleStates++;
                int targetState = this.contSimpleStates; //prossimo stato (stato che rappresenta l'ingresso nel FOR)

                //creiamo lo stato semplice target
                createIntermediateSimpleState(targetState, md);

                //creiamo la transizione normale
                createNormalTransition(this.actualState, targetState, md, trigger, action, "E", graphicAction);

                //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
                this.actualState = targetState;
            }
        }
    }

    //ricaviamo lo stato che rappresenta l'ingresso nel FOR (creato in precedenza)
    int stato_ingresso_for = this.actualState;

    //creiamo la transizione:
    //stato_ingresso_for ---- E[condizione_for]/postMessage(E) ---> stato_iniziale_blocco_for

    //creiamo il trigger
    String trigger1 = "";
    trigger1 += "if((msg != null) && (msg instanceof DSCStarEvent) && (((DSCStarEvent) msg).getType() == DSCStarEvent.E)){\n";
    trigger1 += "if (" + translateVars(currentStatement.getExpression(), md) + "){\n"; //traduciamo la condizione del FOR
    trigger1 += "return true;\n";
    trigger1 += "}\n";
    trigger1 += "}\n";
    trigger1 += "return false;\n";
    String graphicTrigger1 = "E[" + currentStatement.getExpression() + "]";

    //creiamo l'azione
    String action1 = createE();

    //creiamo lo stato iniziale del blocco FOR
    this.contSimpleStates++;
    int stato_iniziale_blocco_for = this.contSimpleStates;
    createIntermediateSimpleState(stato_iniziale_blocco_for, md);

    //creiamo la transizione da "stato_ingresso_for" a "stato_iniziale_blocco_for"
    createNormalTransition(stato_ingresso_for, stato_iniziale_blocco_for, md, trigger1, action1,
            graphicTrigger1, "postEvent(E);");

    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
    this.actualState = stato_iniziale_blocco_for;

    //traduciamo il blocco FOR
    boolean traduzioneBloccoForInterrotta = false; //indica se la traduzione  stata interrotta perch  stato trovato un "return"
    if (currentStatement.getBody() != null) {
        //siamo nel caso in cui: for(...){ c' qualche istruzione }

        if (currentStatement.getBody() instanceof Block) {
            //siamo nel caso in cui: for(...){ pi istruzioni }
            traduzioneBloccoForInterrotta = translateBlock((Block) currentStatement.getBody(), md);
        } else {
            //siamo nel caso in cui: for(...) una istruzione

            //chiamiamo il metodo incaricato di gestire gli statement "speciali",
            //passandogli una lista vuota di statement "normali" da gestire
            boolean specialStatement = handleSpecialStatement(currentStatement.getBody(), md,
                    new LinkedList<ASTNode>());
            if (specialStatement == false) {
                //se lo statement corrente non  uno statement "speciale",
                //lo gestiamo adesso creando un'apposita transizione
                Statement bodyStat = currentStatement.getBody();

                //creiamo l'azione
                String action = "";
                String graphicAct = "";
                String s = translateVars(bodyStat, md);

                if (s.equals("") == false) {
                    //se l'istruzione attuale non  vuota, procediamo

                    action += Util.appendNewLine(s);
                    graphicAct += Util.appendNewLine(bodyStat.toString());
                    action += createE();
                    graphicAct += "postEvent(E);";

                    //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
                    String trigger = createTriggerE();

                    //creiamo lo stato semplice target
                    this.contSimpleStates++;
                    int targetState = this.contSimpleStates;
                    createIntermediateSimpleState(targetState, md);

                    //creiamo la transizione che va dallo stato iniziale del blocco FOR al nuovo stato target
                    createNormalTransition(stato_iniziale_blocco_for, targetState, md, trigger, action, "E",
                            graphicAct);

                    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
                    this.actualState = targetState;
                }
            } else if (currentStatement.getBody() instanceof ReturnStatement) {
                //indichiamo che  stato trovato un "return" nell'unica istruzione del FOR
                traduzioneBloccoForInterrotta = true;
            }
        }
    }

    //ricaviamo lo stato finale del blocco FOR
    int stato_finale_blocco_for = this.actualState;

    if (this.translationType == KEY_STATEMENTS_BASED) {
        if (traduzioneBloccoForInterrotta == false) {
            //se la traduzione del blocco FOR non  stata interrotta
            //(cio, se non  stato trovato un "return" nel blocco FOR),
            //creiamo la transizione:
            //stato_finale_blocco_for ---- E / aggiornamento_indici_for; postMessage(E) ---> stato_ingresso_for

            //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
            String trigger = createTriggerE();

            //creiamo l'azione
            String action = "";
            String graphicAct = "";

            //inseriamo in questa azione l'aggiornamento degli indici del FOR
            //(ad esempio: for( ... ; ... ; i++))
            for (int i = 0; i < currentStatement.updaters().size(); i++) {
                String s = translateVars((ASTNode) currentStatement.updaters().get(i), md);
                if (s.equals("") == false) {
                    action += s + ";\n";
                    graphicAct += currentStatement.updaters().get(i) + ";\n";
                }
            }

            action += createE();
            graphicAct += "postEvent(E);";

            //creiamo la transizione da "stato_finale_blocco_for" a "stato_ingresso_for"
            createNormalTransition(stato_finale_blocco_for, stato_ingresso_for, md, trigger, action, "E",
                    graphicAct);
        }
    } else if (this.translationType == FULL) {
        if (traduzioneBloccoForInterrotta == false) {
            //se la traduzione del blocco FOR non  stata interrotta
            //(cio, se non  stato trovato un "return" nel blocco FOR),
            //creiamo le transizioni che permettono di aggiornare gli indici
            //del FOR e di tornare in "stato_ingresso_for"

            //per ogni aggiornamento di un indice del FOR, creiamo una transizione
            for (int i = 0; i < currentStatement.updaters().size(); i++) {

                //inseriamo in questa azione l'aggiornamento dell'indice del FOR corrente
                //(ad esempio: for( ... ; ... ; i++))
                String s = translateVars((ASTNode) currentStatement.updaters().get(i), md);

                if (i == (currentStatement.updaters().size() - 1)) {
                    //creiamo la transizione che va dallo stato attuale
                    //allo stato "stato_ingresso_for" 

                    //creiamo l'azione
                    String action = "";
                    String graphicAct = "";
                    if (s.equals("") == false) {
                        action += s + ";\n";
                        graphicAct += currentStatement.updaters().get(i) + ";\n";
                    }
                    action += createE();
                    graphicAct += "postEvent(E);";

                    //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
                    String trigger = createTriggerE();

                    //creiamo la transizione che va dallo stato attuale a "stato_ingresso_for"
                    createNormalTransition(this.actualState, stato_ingresso_for, md, trigger, action, "E",
                            graphicAct);
                } else if (s.equals("") == false) {

                    //creiamo l'azione
                    String action = "";
                    String graphicAct = "";
                    action += s + ";\n";
                    graphicAct += currentStatement.updaters().get(i) + ";\n";
                    action += createE();
                    graphicAct += "postEvent(E);";

                    //creiamo il trigger: controlla solo che l'evento sia di tipo "E"
                    String trigger = createTriggerE();

                    this.contSimpleStates++;
                    int targetState = this.contSimpleStates; //prossimo stato

                    //creiamo lo stato semplice target
                    createIntermediateSimpleState(targetState, md);

                    //creiamo la transizione normale
                    createNormalTransition(this.actualState, targetState, md, trigger, action, "E", graphicAct);

                    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
                    this.actualState = targetState;
                }
            }
        }
    }

    //creiamo la transizione:
    //stato_ingresso_for ---- E[!condizione_for]/postMessage(E) ---> stato_fin

    //creiamo il trigger
    String trigger3 = "";
    trigger3 += "if((msg != null) && (msg instanceof DSCStarEvent) && (((DSCStarEvent) msg).getType() == DSCStarEvent.E)){\n";
    trigger3 += "if (!(" + translateVars(currentStatement.getExpression(), md) + ")){\n"; //traduciamo la condizione del FOR
    trigger3 += "return true;\n";
    trigger3 += "}\n";
    trigger3 += "}\n";
    trigger3 += "return false;\n";
    String graphicTrigger3 = "E[!(" + currentStatement.getExpression() + ")]";

    //creiamo l'azione
    String action3 = createE();

    //creiamo lo stato semplice "stato_fin"
    this.contSimpleStates++;
    int stato_fin = this.contSimpleStates;
    createIntermediateSimpleState(stato_fin, md);

    //creiamo la transizione da "stato_ingresso_for" a "stato_fin"
    createNormalTransition(stato_ingresso_for, stato_fin, md, trigger3, action3, graphicTrigger3,
            "postEvent(E);");

    //aggiorniamo lo stato attuale, da cui verr ripresa la traduzione
    this.actualState = stato_fin;
}

From source file:org.eclipse.umlgen.reverse.java.JavaReverseCUVisitor.java

License:Open Source License

/**
 * call by postVisit for non processed statement => create an OpaqueAction.
 *
 * @param node// w w  w.  j a  va2s .co  m
 */
public void visitUnknownStat(Statement node) {
    // not applicable to structured nodes
    if (node instanceof DoStatement || node instanceof EnhancedForStatement || node instanceof BreakStatement
            || node instanceof SwitchStatement || node instanceof SwitchCase || node instanceof Block) {
        return;
    }

    OpaqueAction act = UMLFactory.eINSTANCE.createOpaqueAction();
    LogUtils.logCreation(null, null, act, null);
    act.setActivity(currentActivity);
    act.setName(node.toString().trim());
    entryNodeMap.put(node, act);
    exitNodeMap.put(node, act);
    linkToLastStatement(node);
    lastStatement = (Statement) node;

    // Java text for Body
    act.getLanguages().add("JAVA");
    act.getBodies().add(node.toString());
    return;
}