Java Code Examples for org.codehaus.groovy.ast.stmt.Statement#visit()

The following examples show how to use org.codehaus.groovy.ast.stmt.Statement#visit() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Verifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode type) {
    ConstructorNode newConstructor = type.addConstructor(ctor.getModifiers(), newParams, ctor.getExceptions(), code);
    newConstructor.putNodeMetaData(DEFAULT_PARAMETER_GENERATED, Boolean.TRUE);
    markAsGenerated(type, newConstructor);
    // TODO: Copy annotations, etc.?

    // set anon. inner enclosing method reference
    code.visit(new CodeVisitorSupport() {
        @Override
        public void visitConstructorCallExpression(ConstructorCallExpression call) {
            if (call.isUsingAnonymousInnerClass()) {
                call.getType().setEnclosingMethod(newConstructor);
            }
            super.visitConstructorCallExpression(call);
        }
    });
}
 
Example 2
Source File: DataSet.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void visit(Closure closure, CodeVisitorSupport visitor) {
    if (closure != null) {
        ClassNode classNode = closure.getMetaClass().getClassNode();
        if (classNode == null) {
            throw new GroovyRuntimeException(
                    "DataSet unable to evaluate expression. AST not available for closure: " + closure.getMetaClass().getTheClass().getName() +
                            ". Is the source code on the classpath?");
        }
        List methods = classNode.getDeclaredMethods("doCall");
        if (!methods.isEmpty()) {
            MethodNode method = (MethodNode) methods.get(0);
            if (method != null) {
                Statement statement = method.getCode();
                if (statement != null) {
                    statement.visit(visitor);
                }
            }
        }
    }
}
 
Example 3
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitBlockStatement(final BlockStatement statement) {
    opt.push();
    boolean optAll = true;
    for (Statement stmt : statement.getStatements()) {
        opt.push();
        stmt.visit(this);
        optAll = optAll && opt.canOptimize();
        opt.pop(true);
    }
    if (statement.isEmpty()) {
        opt.chainCanOptimize(true);
        opt.pop(true);
    } else {
        opt.chainShouldOptimize(optAll);
        if (optAll) {
            addMeta(statement, opt);
        }
        opt.pop(optAll);
    }
}
 
Example 4
Source File: StatementWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void writeBlockStatement(final BlockStatement block) {
    writeStatementLabel(block);

    int mark = controller.getOperandStack().getStackLength();
    CompileStack compileStack = controller.getCompileStack();
    compileStack.pushVariableScope(block.getVariableScope());
    for (Statement statement : block.getStatements()) {
        statement.visit(controller.getAcg());
    }
    compileStack.pop();

    // GROOVY-7647, GROOVY-9126
    if (block.getLastLineNumber() > 0 && !isMethodOrConstructorNonEmptyBlock(block)) {
        MethodVisitor mv = controller.getMethodVisitor();
        Label blockEnd = new Label();
        mv.visitLabel(blockEnd);
        mv.visitLineNumber(block.getLastLineNumber(), blockEnd);
    }

    controller.getOperandStack().popDownTo(mark);
}
 
Example 5
Source File: AndroidGradleDependenciesVisitor.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public void visitBlockStatement(BlockStatement block) {
    if (block.equals(rootBlockStatement)) {
        List<Statement> statements = block.getStatements();
        for (int i = 0; i < statements.size(); i++) {
            //workaround to exlude buildscript->dependencies
            buildScript = false;
            Statement st = statements.get(i);
            st.visit(this);
        }
    } else {
        super.visitBlockStatement(block);
    }
}
 
Example 6
Source File: RulesVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void visitBlockStatement(BlockStatement block) {
    block.setNodeMetaData(AST_NODE_METADATA_KEY, true);

    for (Statement statement : block.getStatements()) {
        statement.visit(this);
    }
}
 
Example 7
Source File: SecureASTCustomizer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitBlockStatement(final BlockStatement block) {
    assertStatementAuthorized(block);
    for (Statement statement : block.getStatements()) {
        statement.visit(this);
    }
}
 
Example 8
Source File: TraitASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Statement processBody(VariableExpression thisObject, Statement code, ClassNode trait, ClassNode traitHelper, ClassNode fieldHelper, Collection<String> knownFields) {
    if (code == null) return null;
    NAryOperationRewriter operationRewriter = new NAryOperationRewriter(unit, knownFields);
    code.visit(operationRewriter);
    SuperCallTraitTransformer superTrn = new SuperCallTraitTransformer(unit);
    code.visit(superTrn);
    TraitReceiverTransformer trn = new TraitReceiverTransformer(thisObject, unit, trait, traitHelper, fieldHelper, knownFields);
    code.visit(trn);
    return code;
}
 
Example 9
Source File: RulesVisitor.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void visitBlockStatement(BlockStatement block) {
    block.setNodeMetaData(AST_NODE_METADATA_KEY, true);

    for (Statement statement : block.getStatements()) {
        statement.visit(this);
    }
}
 
Example 10
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void visitCatchFinally(Map<Variable, VariableState> initialVarState, List<Map<Variable, VariableState>> afterTryCatchStates, CatchStatement catchStatement, Statement finallyStatement) {
    pushState();
    getState().putAll(initialVarState);
    Statement code = catchStatement.getCode();
    catchStatement.visit(this);
    finallyStatement.visit(this);
    if (code == null || !returningBlock(code)) {
        afterTryCatchStates.add(new HashMap<>(getState()));
    }
    popState();
}
 
Example 11
Source File: EnumCompletionVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private String getUniqueVariableName(final String name, Statement code) {
    if (code == null) return name;
    final Object[] found = new Object[1];
    CodeVisitorSupport cv = new CodeVisitorSupport() {
        public void visitVariableExpression(VariableExpression expression) {
            if (expression.getName().equals(name)) found[0] = Boolean.TRUE;
        }
    };
    code.visit(cv);
    if (found[0] != null) return getUniqueVariableName("_" + name, code);
    return name;
}
 
Example 12
Source File: ClassCodeVisitorSupport.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void visitClassCodeContainer(Statement code) {
    if (code != null) code.visit(this);
}
 
Example 13
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitConstructorCallExpression(final ConstructorCallExpression expression) {
    boolean oldInSpecialCtorFlag = inSpecialConstructorCall;
    inSpecialConstructorCall |= expression.isSpecialCall();
    super.visitConstructorCallExpression(expression);
    inSpecialConstructorCall = oldInSpecialCtorFlag;

    if (!expression.isUsingAnonymousInnerClass()) return;

    pushState();
    InnerClassNode innerClass = (InnerClassNode) expression.getType();
    innerClass.setVariableScope(currentScope);
    currentScope.setClassScope(innerClass);
    currentScope.setInStaticContext(false);
    for (MethodNode method : innerClass.getMethods()) {
        Parameter[] parameters = method.getParameters();
        if (parameters.length == 0) {
            parameters = null; // null means no implicit "it"
        }
        visitClosureExpression(new ClosureExpression(parameters, method.getCode()));
    }

    for (FieldNode field : innerClass.getFields()) {
        Expression initExpression = field.getInitialExpression();
        pushState(field.isStatic());
        if (initExpression != null) {
            if (initExpression.isSynthetic() && initExpression instanceof VariableExpression
                    && ((VariableExpression) initExpression).getAccessedVariable() instanceof Parameter) {
                // GROOVY-6834: accessing a parameter which is not yet seen in scope
                popState();
                continue;
            }
            initExpression.visit(this);
        }
        popState();
    }

    for (Statement initStatement : innerClass.getObjectInitializerStatements()) {
        initStatement.visit(this);
    }
    markClosureSharedVariables();
    popState();
}
 
Example 14
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitTryCatchFinally(final TryCatchStatement statement) {
    visitStatement(statement);
    Map<Variable, VariableState> beforeTryState = new HashMap<>(getState());
    pushState();
    Statement tryStatement = statement.getTryStatement();
    tryStatement.visit(this);
    Map<Variable, VariableState> afterTryState = new HashMap<>(getState());
    Statement finallyStatement = statement.getFinallyStatement();
    List<Map<Variable, VariableState>> afterStates = new ArrayList<>();
    // the try finally case
    finallyStatement.visit(this);
    if (!returningBlock(tryStatement)) {
        afterStates.add(new HashMap<>(getState()));
    }
    popState();
    // now the finally only case but only if no catches
    if (statement.getCatchStatements().isEmpty()) {
        finallyStatement.visit(this);
        if (!returningBlock(tryStatement)) {
            afterStates.add(new HashMap<>(getState()));
        }
    }
    for (CatchStatement catchStatement : statement.getCatchStatements()) {
        // We don't try to analyse which statement within the try block might have thrown an exception.
        // We make a crude assumption that anywhere from none to all of the statements might have been executed.
        // Run visitor for both scenarios so the eager checks will be performed for either of these cases.
        visitCatchFinally(beforeTryState, afterStates, catchStatement, finallyStatement);
        visitCatchFinally(afterTryState, afterStates, catchStatement, finallyStatement);
    }
    // after states can only be empty if try and catch statements all return in which case nothing to do
    if (afterStates.isEmpty()) return;
    // now adjust the state variables - any early returns won't have gotten here
    // but we need to check that the same status was observed by all paths
    // and mark as ambiguous if needed
    Map<Variable, VariableState> corrected = afterStates.remove(0);
    for (Map<Variable, VariableState> nextState : afterStates) {
        for (Map.Entry<Variable, VariableState> entry : corrected.entrySet()) {
            Variable var = entry.getKey();
            VariableState currentCorrectedState = entry.getValue();
            VariableState candidateCorrectedState = nextState.get(var);
            if (currentCorrectedState == VariableState.is_ambiguous) continue;
            if (currentCorrectedState != candidateCorrectedState) {
                if (currentCorrectedState == VariableState.is_uninitialized || candidateCorrectedState == VariableState.is_uninitialized) {
                    corrected.put(var, VariableState.is_ambiguous);
                } else {
                    corrected.put(var, VariableState.is_var);
                }
            }
        }
    }
    getState().putAll(corrected);
}
 
Example 15
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitSwitch(SwitchStatement switchS) {
    visitStatement(switchS);
    switchS.getExpression().visit(this);
    List<Statement> branches = new ArrayList<>(switchS.getCaseStatements());
    if (!(switchS.getDefaultStatement() instanceof EmptyStatement)) {
        branches.add(switchS.getDefaultStatement());
    }
    List<Map<Variable, VariableState>> afterStates = new ArrayList<>();

    // collect after states
    int lastIndex = branches.size() - 1;
    for (int i = 0; i <= lastIndex; i++) {
        pushState();
        boolean done = false;
        boolean returning = false;
        for (int j = i; !done; j++) {
            Statement branch = branches.get(j);
            Statement block = branch; // default branch
            if (branch instanceof CaseStatement) {
                CaseStatement caseS = (CaseStatement) branch;
                block = caseS.getCode();
                caseS.getExpression().visit(this);
            }
            block.visit(this);
            done = j == lastIndex || !fallsThrough(block);
            if (done) {
                returning = returningBlock(block);
            }
        }
        if (!returning) {
            afterStates.add(getState());
        }
        popState();
    }
    if (afterStates.isEmpty()) {
        return;
    }

    // merge branches
    Map<Variable, VariableState> beforeState = getState();
    Set<Variable> allVars = new HashSet<>(beforeState.keySet());
    for (Map<Variable, VariableState> map : afterStates) {
        allVars.addAll(map.keySet());
    }
    for (Variable var : allVars) {
        VariableState beforeValue = beforeState.get(var);
        if (beforeValue != null) {
            final VariableState merged = afterStates.get(0).get(var);
            if (merged != null) {
                if (afterStates.stream().allMatch(state -> merged.equals(state.get(var)))) {
                    beforeState.put(var, merged);
                } else {
                    VariableState different = beforeValue == VariableState.is_uninitialized ? VariableState.is_ambiguous : VariableState.is_var;
                    beforeState.put(var, different);
                }
            }
        }
    }
}
 
Example 16
Source File: ReferenceDetectingVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void visitBlockStatement(BlockStatement block) {
    for (Statement statement : block.getStatements()) {
        statement.visit(this);
    }
}
 
Example 17
Source File: CodeVisitorSupport.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitBlockStatement(BlockStatement block) {
    for (Statement statement : block.getStatements()) {
        statement.visit(this);
    }
}
 
Example 18
Source File: SandboxCpsTransformer.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
/**
 * Miscellaneous statements like object initializers are never transformed, but we still need to run the sandbox transformer on them.
 * @see SandboxTransformer#call
 */
@Override
protected void visitNontransformedStatement(Statement s) {
    s.visit(stv);
}
 
Example 19
Source File: TemplateASTTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void transformRunMethod(final ClassNode classNode, final SourceUnit source) {
    MethodNode runMethod = classNode.getDeclaredMethod("run", Parameter.EMPTY_ARRAY);
    Statement code = runMethod.getCode();
    MarkupBuilderCodeTransformer transformer = new MarkupBuilderCodeTransformer(source, classNode, config.isAutoEscape());
    code.visit(transformer);
}
 
Example 20
Source File: ReferenceDetectingVisitor.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void visitBlockStatement(BlockStatement block) {
    for (Statement statement : block.getStatements()) {
        statement.visit(this);
    }
}