org.codehaus.groovy.ast.stmt.ExpressionStatement Java Examples

The following examples show how to use org.codehaus.groovy.ast.stmt.ExpressionStatement. 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: ClosureWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected BlockStatement createBlockStatementForConstructor(final ClosureExpression expression, final ClassNode outerClass, final ClassNode thisClassNode) {
    BlockStatement block = new BlockStatement();
    // this block does not get a source position, because we don't
    // want this synthetic constructor to show up in corbertura reports
    VariableExpression outer = new VariableExpression(OUTER_INSTANCE, outerClass);
    outer.setSourcePosition(expression);
    block.getVariableScope().putReferencedLocalVariable(outer);
    VariableExpression thisObject = new VariableExpression(THIS_OBJECT, thisClassNode);
    thisObject.setSourcePosition(expression);
    block.getVariableScope().putReferencedLocalVariable(thisObject);
    TupleExpression conArgs = new TupleExpression(outer, thisObject);
    block.addStatement(
            new ExpressionStatement(
                    new ConstructorCallExpression(
                            ClassNode.SUPER,
                            conArgs)));
    return block;
}
 
Example #2
Source File: AstUtils.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Nullable
public static MethodCallExpression extractBareMethodCall(Statement statement) {
    if (!(statement instanceof ExpressionStatement)) {
        return null;
    }

    ExpressionStatement expressionStatement = (ExpressionStatement) statement;
    if (!(expressionStatement.getExpression() instanceof MethodCallExpression)) {
        return null;
    }

    MethodCallExpression methodCall = (MethodCallExpression) expressionStatement.getExpression();
    if (!targetIsThis(methodCall)) {
        return null;
    }

    return methodCall;
}
 
Example #3
Source File: RuleVisitor.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitClosureExpression(ClosureExpression expression) {
    if (inputs == null) {
        inputs = ImmutableListMultimap.builder();
        try {
            accessVariable = new VariableExpression(ACCESS_HOLDER_FIELD, ACCESS_API_TYPE);

            super.visitClosureExpression(expression);

            BlockStatement code = (BlockStatement) expression.getCode();
            code.setNodeMetaData(AST_NODE_METADATA_INPUTS_KEY, inputs.build());
            accessVariable.setClosureSharedVariable(true);
            StaticMethodCallExpression getAccessCall = new StaticMethodCallExpression(CONTEXTUAL_INPUT_TYPE, GET_ACCESS, ArgumentListExpression.EMPTY_ARGUMENTS);
            DeclarationExpression variableDeclaration = new DeclarationExpression(accessVariable, new Token(Types.ASSIGN, "=", -1, -1), getAccessCall);
            code.getStatements().add(0, new ExpressionStatement(variableDeclaration));
            code.getVariableScope().putDeclaredVariable(accessVariable);
        } finally {
            inputs = null;
        }
    } else {
        expression.getVariableScope().putReferencedLocalVariable(accessVariable);
        super.visitClosureExpression(expression);
    }
}
 
Example #4
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_not_add_to_unknonwn_variables_a_variable_declared_but_not_in_the_process_scope() throws Exception {
    final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);

    final List<Statement> statements = new ArrayList<Statement>();
    statements.add(new ExpressionStatement(
            new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something"))));
    statements.add(new ReturnStatement(new VariableExpression("declaredVar")));
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("declaredVar"));
    final BlockStatement blockStatement = new BlockStatement(statements, variableScope);

    when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
    final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit);

    unknownElementsIndexer.run(new NullProgressMonitor());

    assertThat(unknownElementsIndexer.getUnknownVaraibles()).isEmpty();
}
 
Example #5
Source File: ScriptBlockToServiceConfigurationTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Statement transform(ScriptBlock scriptBlock) {
    Expression closureArg = scriptBlock.getClosureExpression();

    PropertyExpression servicesProperty = new PropertyExpression(VariableExpression.THIS_EXPRESSION, servicesFieldName);
    MethodCallExpression getServiceMethodCall = new MethodCallExpression(servicesProperty, "get",
            new ArgumentListExpression(
                    new ClassExpression(new ClassNode(serviceClass))
            )
    );

    // Remove access to any surrounding context
    Expression hydrateMethodCall = new MethodCallExpression(closureArg, "rehydrate", new ArgumentListExpression(
            ConstantExpression.NULL, getServiceMethodCall, getServiceMethodCall
    ));

    Expression closureCall = new MethodCallExpression(hydrateMethodCall, "call", ArgumentListExpression.EMPTY_ARGUMENTS);

    return new ExpressionStatement(closureCall);
}
 
Example #6
Source File: ScriptBlockToServiceConfigurationTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Statement transform(ScriptBlock scriptBlock) {
    Expression closureArg = scriptBlock.getClosureExpression();

    PropertyExpression servicesProperty = new PropertyExpression(VariableExpression.THIS_EXPRESSION, servicesFieldName);
    MethodCallExpression getServiceMethodCall = new MethodCallExpression(servicesProperty, "get",
            new ArgumentListExpression(
                    new ClassExpression(new ClassNode(serviceClass))
            )
    );

    // Remove access to any surrounding context
    Expression hydrateMethodCall = new MethodCallExpression(closureArg, "rehydrate", new ArgumentListExpression(
            ConstantExpression.NULL, getServiceMethodCall, getServiceMethodCall
    ));

    Expression closureCall = new MethodCallExpression(hydrateMethodCall, "call", ArgumentListExpression.EMPTY_ARGUMENTS);

    return new ExpressionStatement(closureCall);
}
 
Example #7
Source File: UnknownElementsIndexerTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_add_to_overriden_variables_a_variable_declared_and_already_in_the_process_scope() throws Exception {
    final BonitaScriptGroovyCompilationUnit groovyCompilationUnit = mock(BonitaScriptGroovyCompilationUnit.class, RETURNS_DEEP_STUBS);
    Map<String, ScriptVariable> context = new HashMap<String, ScriptVariable>();
    context.put("declaredVar", null);
    when(groovyCompilationUnit.getContext()).thenReturn(context);
    
    final List<Statement> statements = new ArrayList<Statement>();
    statements.add(new ExpressionStatement(
            new DeclarationExpression(new VariableExpression("declaredVar"), Token.NULL, new VariableExpression("something"))));
    statements.add(new ReturnStatement(new VariableExpression("declaredVar")));
    final VariableScope variableScope = new VariableScope();
    variableScope.putDeclaredVariable(new VariableExpression("declaredVar"));
    final BlockStatement blockStatement = new BlockStatement(statements, variableScope);

    when(groovyCompilationUnit.getModuleNode().getStatementBlock()).thenReturn(blockStatement);
    final UnknownElementsIndexer unknownElementsIndexer = new UnknownElementsIndexer(groovyCompilationUnit);

    unknownElementsIndexer.run(new NullProgressMonitor());

    assertThat(unknownElementsIndexer.getOverridenVariables()).containsExactly(entry("declaredVar", new Position(0)));
}
 
Example #8
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ConstructorCallExpression getConstructorCallExpression(
        ConstructorNode constructorNode) {
    Statement code = constructorNode.getCode();
    if (!(code instanceof BlockStatement)) {
        return null;
    }
    BlockStatement block = (BlockStatement) code;
    List<Statement> stats = block.getStatements();
    if (stats == null || stats.isEmpty()) {
        return null;
    }
    Statement stat = stats.get(0);
    if (!(stat instanceof ExpressionStatement)) {
        return null;
    }
    Expression expr = ((ExpressionStatement) stat).getExpression();
    if (!(expr instanceof ConstructorCallExpression)) {
        return null;
    }
    return (ConstructorCallExpression) expr;
}
 
Example #9
Source File: TemplateASTTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void createConstructor(final ClassNode classNode) {
    Parameter[] params = new Parameter[]{
            new Parameter(MarkupTemplateEngine.MARKUPTEMPLATEENGINE_CLASSNODE, "engine"),
            new Parameter(ClassHelper.MAP_TYPE.getPlainNodeReference(), "model"),
            new Parameter(ClassHelper.MAP_TYPE.getPlainNodeReference(), "modelTypes"),
            new Parameter(TEMPLATECONFIG_CLASSNODE, "tplConfig")
    };
    List<Expression> vars = new LinkedList<Expression>();
    for (Parameter param : params) {
        vars.add(new VariableExpression(param));
    }
    ExpressionStatement body = new ExpressionStatement(
            new ConstructorCallExpression(ClassNode.SUPER, new ArgumentListExpression(vars)));
    ConstructorNode ctor = new ConstructorNode(Opcodes.ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, body);
    classNode.addConstructor(ctor);
}
 
Example #10
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private ExpressionStatement makeVariableDeclarationFinal(ExpressionStatement variableDeclaration) {
    if (!asBoolean(variableDeclaration)) {
        return variableDeclaration;
    }

    if (!(variableDeclaration.getExpression() instanceof DeclarationExpression)) {
        throw new IllegalArgumentException("variableDeclaration is not a declaration statement");
    }

    DeclarationExpression declarationExpression = (DeclarationExpression) variableDeclaration.getExpression();
    if (!(declarationExpression.getLeftExpression() instanceof VariableExpression)) {
        throw astBuilder.createParsingFailedException("The expression statement is not a variable delcaration statement", variableDeclaration);
    }

    VariableExpression variableExpression = (VariableExpression) declarationExpression.getLeftExpression();
    variableExpression.setModifiers(variableExpression.getModifiers() | Opcodes.ACC_FINAL);

    return variableDeclaration;
}
 
Example #11
Source File: RuleVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitClosureExpression(ClosureExpression expression) {
    if (inputs == null) {
        inputs = ImmutableListMultimap.builder();
        try {
            accessVariable = new VariableExpression(ACCESS_HOLDER_FIELD, ACCESS_API_TYPE);

            super.visitClosureExpression(expression);

            BlockStatement code = (BlockStatement) expression.getCode();
            code.setNodeMetaData(AST_NODE_METADATA_INPUTS_KEY, inputs.build());
            accessVariable.setClosureSharedVariable(true);
            StaticMethodCallExpression getAccessCall = new StaticMethodCallExpression(CONTEXTUAL_INPUT_TYPE, GET_ACCESS, ArgumentListExpression.EMPTY_ARGUMENTS);
            DeclarationExpression variableDeclaration = new DeclarationExpression(accessVariable, new Token(Types.ASSIGN, "=", -1, -1), getAccessCall);
            code.getStatements().add(0, new ExpressionStatement(variableDeclaration));
            code.getVariableScope().putDeclaredVariable(accessVariable);
        } finally {
            inputs = null;
        }
    } else {
        expression.getVariableScope().putReferencedLocalVariable(accessVariable);
        super.visitClosureExpression(expression);
    }
}
 
Example #12
Source File: AstUtils.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Nullable
public static MethodCallExpression extractBareMethodCall(Statement statement) {
    if (!(statement instanceof ExpressionStatement)) {
        return null;
    }

    ExpressionStatement expressionStatement = (ExpressionStatement) statement;
    if (!(expressionStatement.getExpression() instanceof MethodCallExpression)) {
        return null;
    }

    MethodCallExpression methodCall = (MethodCallExpression) expressionStatement.getExpression();
    if (!targetIsThis(methodCall)) {
        return null;
    }

    return methodCall;
}
 
Example #13
Source File: ClassNode.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void positionStmtsAfterEnumInitStmts(List<Statement> staticFieldStatements) {
    MethodNode constructor = getOrAddStaticConstructorNode();
    Statement statement = constructor.getCode();
    if (statement instanceof BlockStatement) {
        BlockStatement block = (BlockStatement) statement;
        // add given statements for explicitly declared static fields just after enum-special fields
        // are found - the $VALUES binary expression marks the end of such fields.
        List<Statement> blockStatements = block.getStatements();
        ListIterator<Statement> litr = blockStatements.listIterator();
        while (litr.hasNext()) {
            Statement stmt = litr.next();
            if (stmt instanceof ExpressionStatement &&
                    ((ExpressionStatement) stmt).getExpression() instanceof BinaryExpression) {
                BinaryExpression bExp = (BinaryExpression) ((ExpressionStatement) stmt).getExpression();
                if (bExp.getLeftExpression() instanceof FieldExpression) {
                    FieldExpression fExp = (FieldExpression) bExp.getLeftExpression();
                    if (fExp.getFieldName().equals("$VALUES")) {
                        for (Statement tmpStmt : staticFieldStatements) {
                            litr.add(tmpStmt);
                        }
                    }
                }
            }
        }
    }
}
 
Example #14
Source File: GenericsUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static ClassNode[] parseClassNodesFromString(final String option, final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final MethodNode mn, final ASTNode usage) {
    try {
        ModuleNode moduleNode = ParserPlugin.buildAST("Dummy<" + option + "> dummy;", compilationUnit.getConfiguration(), compilationUnit.getClassLoader(), null);
        DeclarationExpression dummyDeclaration = (DeclarationExpression) ((ExpressionStatement) moduleNode.getStatementBlock().getStatements().get(0)).getExpression();

        // the returned node is DummyNode<Param1, Param2, Param3, ...)
        ClassNode dummyNode = dummyDeclaration.getLeftExpression().getType();
        GenericsType[] dummyNodeGenericsTypes = dummyNode.getGenericsTypes();
        if (dummyNodeGenericsTypes == null) {
            return null;
        }
        ClassNode[] signature = new ClassNode[dummyNodeGenericsTypes.length];
        for (int i = 0, n = dummyNodeGenericsTypes.length; i < n; i += 1) {
            final GenericsType genericsType = dummyNodeGenericsTypes[i];
            signature[i] = resolveClassNode(sourceUnit, compilationUnit, mn, usage, genericsType.getType());
        }
        return signature;
    } catch (Exception | LinkageError e) {
        sourceUnit.addError(new IncorrectTypeHintException(mn, e, usage.getLineNumber(), usage.getColumnNumber()));
    }
    return null;
}
 
Example #15
Source File: GeneralUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static boolean copyStatementsWithSuperAdjustment(final ClosureExpression pre, final BlockStatement body) {
    Statement preCode = pre.getCode();
    boolean changed = false;
    if (preCode instanceof BlockStatement) {
        BlockStatement block = (BlockStatement) preCode;
        List<Statement> statements = block.getStatements();
        for (int i = 0, n = statements.size(); i < n; i += 1) {
            Statement statement = statements.get(i);
            // adjust the first statement if it's a super call
            if (i == 0 && statement instanceof ExpressionStatement) {
                ExpressionStatement es = (ExpressionStatement) statement;
                Expression preExp = es.getExpression();
                if (preExp instanceof MethodCallExpression) {
                    MethodCallExpression mce = (MethodCallExpression) preExp;
                    String name = mce.getMethodAsString();
                    if ("super".equals(name)) {
                        es.setExpression(new ConstructorCallExpression(ClassNode.SUPER, mce.getArguments()));
                        changed = true;
                    }
                }
            }
            body.addStatement(statement);
        }
    }
    return changed;
}
 
Example #16
Source File: InnerClassVisitorHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected static void setPropertySetterDispatcher(BlockStatement block, Expression thiz, Parameter[] parameters) {
    List<ConstantExpression> gStringStrings = new ArrayList<ConstantExpression>();
    gStringStrings.add(new ConstantExpression(""));
    gStringStrings.add(new ConstantExpression(""));
    List<Expression> gStringValues = new ArrayList<Expression>();
    gStringValues.add(new VariableExpression(parameters[0]));
    block.addStatement(
            new ExpressionStatement(
                    new BinaryExpression(
                            new PropertyExpression(
                                    thiz,
                                    new GStringExpression("$name", gStringStrings, gStringValues)
                            ),
                            Token.newSymbol(Types.ASSIGN, -1, -1),
                            new VariableExpression(parameters[1])
                    )
            )
    );
}
 
Example #17
Source File: Verifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Statement getImplicitThis$0StmtIfInnerClass(List<Statement> otherStatements) {
    if (!(classNode instanceof InnerClassNode)) return null;
    for (Statement stmt : otherStatements) {
        if (stmt instanceof BlockStatement) {
            List<Statement> stmts = ((BlockStatement) stmt).getStatements();
            for (Statement bstmt : stmts) {
                if (bstmt instanceof ExpressionStatement) {
                    if (extractImplicitThis$0StmtIfInnerClassFromExpression(stmts, bstmt)) return bstmt;
                }
            }
        } else if (stmt instanceof ExpressionStatement) {
            if (extractImplicitThis$0StmtIfInnerClassFromExpression(otherStatements, stmt)) return stmt;
        }
    }
    return null;
}
 
Example #18
Source File: ConstructorNodeUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Return the first statement from the constructor code if it is a call to super or this, otherwise null.
 *
 * @param code
 * @return the first statement if a special call or null
 */
public static ConstructorCallExpression getFirstIfSpecialConstructorCall(Statement code) {
    if (code == null) return null;

    if (code instanceof BlockStatement) {
        final BlockStatement block = (BlockStatement) code;
        final List<Statement> statementList = block.getStatements();
        if (statementList.isEmpty()) return null;
        // handle blocks of blocks
        return getFirstIfSpecialConstructorCall(statementList.get(0));
    }

    if (!(code instanceof ExpressionStatement)) return null;

    Expression expression = ((ExpressionStatement) code).getExpression();
    if (!(expression instanceof ConstructorCallExpression)) return null;
    ConstructorCallExpression cce = (ConstructorCallExpression) expression;
    if (cce.isSpecialCall()) return cce;
    return null;
}
 
Example #19
Source File: TryWithResourcesASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private CatchStatement createCatchBlockForOuterNewTryCatchStatement(String primaryExcName) {
    // { ... }
    BlockStatement blockStatement = new BlockStatement();
    String tExcName = this.genTExcName();

    // #primaryExc = #t;
    ExpressionStatement primaryExcAssignStatement =
            new ExpressionStatement(
                    new BinaryExpression(
                            new VariableExpression(primaryExcName),
                            newSymbol(Types.ASSIGN, -1, -1),
                            new VariableExpression(tExcName)));
    astBuilder.appendStatementsToBlockStatement(blockStatement, primaryExcAssignStatement);

    // throw #t;
    ThrowStatement throwTExcStatement = new ThrowStatement(new VariableExpression(tExcName));
    astBuilder.appendStatementsToBlockStatement(blockStatement, throwTExcStatement);

    // Throwable #t
    Parameter tExcParameter = new Parameter(ClassHelper.make(Throwable.class), tExcName);

    return new CatchStatement(tExcParameter, blockStatement);
}
 
Example #20
Source File: StatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void writeExpressionStatement(final ExpressionStatement statement) {
    controller.getAcg().onLineNumber(statement, "visitExpressionStatement: " + statement.getExpression().getClass().getName());
    writeStatementLabel(statement);

    int mark = controller.getOperandStack().getStackLength();
    Expression expression = statement.getExpression();
    expression.visit(controller.getAcg());
    controller.getOperandStack().popDownTo(mark);
}
 
Example #21
Source File: ASTNodeVisitor.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public void visitExpressionStatement(ExpressionStatement node) {
	pushASTNode(node);
	try {
		super.visitExpressionStatement(node);
	} finally {
		popASTNode();
	}
}
 
Example #22
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean extractImplicitThis$0StmtIfInnerClassFromExpression(final List<Statement> stmts, final Statement bstmt) {
    Expression expr = ((ExpressionStatement) bstmt).getExpression();
    if (expr instanceof BinaryExpression) {
        Expression lExpr = ((BinaryExpression) expr).getLeftExpression();
        if (lExpr instanceof FieldExpression) {
            if ("this$0".equals(((FieldExpression) lExpr).getFieldName())) {
                stmts.remove(bstmt); // remove from here and let the caller reposition it
                return true;
            }
        }
    }
    return false;
}
 
Example #23
Source File: ReturnAdder.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean returns(final Statement statement) {
    return statement instanceof ReturnStatement
        || statement instanceof BlockStatement
        || statement instanceof IfStatement
        || statement instanceof ExpressionStatement
        || statement instanceof EmptyStatement
        || statement instanceof TryCatchStatement
        || statement instanceof ThrowStatement
        || statement instanceof SynchronizedStatement
        || statement instanceof BytecodeSequence;
}
 
Example #24
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitExpressionStatement(final ExpressionStatement statement) {
    if (statement.getNodeMetaData(StatementMeta.class) != null) return;
    opt.push();
    super.visitExpressionStatement(statement);
    if (opt.shouldOptimize()) {
        addMeta(statement, opt);
    }
    opt.pop(opt.shouldOptimize());
}
 
Example #25
Source File: StatementLabelsScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void call(final SourceUnit source) throws CompilationFailedException {
    final List<Statement> logStats = Lists.newArrayList();

    // currently we only look in script code; could extend this to build script classes
    AstUtils.visitScriptCode(source, new ClassCodeVisitorSupport() {
        @Override
        protected SourceUnit getSourceUnit() {
            return source;
        }

        @Override
        protected void visitStatement(Statement statement) {
            if (statement.getStatementLabel() != null) {
                // Because we aren't failing the build, the script will be cached and this transformer won't run the next time.
                // In order to make the deprecation warning stick, we have to weave the call to StatementLabelsDeprecationLogger
                // into the build script.
                String label = statement.getStatementLabel();
                String sample = source.getSample(statement.getLineNumber(), statement.getColumnNumber(), null);
                Expression logExpr = new StaticMethodCallExpression(ClassHelper.makeWithoutCaching(StatementLabelsDeprecationLogger.class), "log",
                        new ArgumentListExpression(new ConstantExpression(label), new ConstantExpression(sample)));
                logStats.add(new ExpressionStatement(logExpr));
            }
        }
    });

    source.getAST().getStatementBlock().addStatements(logStats);
}
 
Example #26
Source File: TupleListTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void assertIterate(String methodName, Expression listExpression) throws Exception {
    ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, ClassHelper.OBJECT_TYPE);
    classNode.addConstructor(new ConstructorNode(ACC_PUBLIC, null));
    classNode.addProperty(new PropertyNode("bar", ACC_PUBLIC, ClassHelper.STRING_TYPE, classNode, null, null, null));

    Statement loopStatement = createPrintlnStatement(new VariableExpression("i"));

    BlockStatement block = new BlockStatement();
    block.addStatement(new ExpressionStatement(new DeclarationExpression(new VariableExpression("list"), Token.newSymbol("=", 0, 0), listExpression)));
    block.addStatement(new ForStatement(new Parameter(ClassHelper.DYNAMIC_TYPE, "i"), new VariableExpression("list"), loopStatement));
    classNode.addMethod(new MethodNode(methodName, ACC_PUBLIC, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, block));

    Class fooClass = loadClass(classNode);
    assertTrue("Loaded a new class", fooClass != null);

    Object bean = fooClass.getDeclaredConstructor().newInstance();
    assertTrue("Managed to create bean", bean != null);

    System.out.println("################ Now about to invoke method");

    try {
        InvokerHelper.invokeMethod(bean, methodName, null);
    }
    catch (InvokerInvocationException e) {
        System.out.println("Caught: " + e.getCause());
        e.getCause().printStackTrace();
        fail("Should not have thrown an exception");
    }
    System.out.println("################ Done");
}
 
Example #27
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void writeExpressionStatement(final ExpressionStatement statement) {
    if (controller.isFastPath()) {
        super.writeExpressionStatement(statement);
    } else {
        StatementMeta meta = statement.getNodeMetaData(StatementMeta.class);
        // we have to have handle DelcarationExpressions special, since their
        // entry should be outside the optimization path, we have to do that of
        // course only if we are actually going to do two different paths,
        // otherwise it is not needed
        //
        // there are several cases to be considered now.
        // (1) no fast path possible, so just do super
        // (2) fast path possible, and at path split point (meaning not in
        //     fast path and not in slow path). Here we have to extract the
        //     Declaration and replace by an assignment
        // (3) fast path possible and in slow or fastPath. Nothing to do here.
        //
        // the only case we need to handle is then (2).
        if (isNewPathFork(meta) && writeDeclarationExtraction(statement)) {
            if (meta.declaredVariableExpression != null) {
                // declaration was replaced by assignment so we need to define the variable
                controller.getCompileStack().defineVariable(meta.declaredVariableExpression, false);
            }
            FastPathData fastPathData = writeGuards(meta, statement);

            boolean oldFastPathBlock = fastPathBlocked;
            fastPathBlocked = true;
            super.writeExpressionStatement(statement);
            fastPathBlocked = oldFastPathBlock;

            if (fastPathData == null) return;
            writeFastPathPrelude(fastPathData);
            super.writeExpressionStatement(statement);
            writeFastPathEpilogue(fastPathData);
        } else {
            super.writeExpressionStatement(statement);
        }
    }
}
 
Example #28
Source File: TestSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected ExpressionStatement createPrintlnStatement(Expression expression) throws NoSuchFieldException {
    return new ExpressionStatement(
            new MethodCallExpression(
                    new FieldExpression(FieldNode.newStatic(System.class, "out")),
                    "println",
                    expression));
}
 
Example #29
Source File: PluginsAndBuildscriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private ScriptBlock detectScriptBlock(Statement statement) {
    if (!(statement instanceof ExpressionStatement)) {
        return null;
    }

    ExpressionStatement expressionStatement = (ExpressionStatement) statement;
    if (!(expressionStatement.getExpression() instanceof MethodCallExpression)) {
        return null;
    }

    MethodCallExpression methodCall = (MethodCallExpression) expressionStatement.getExpression();
    if (!AstUtils.targetIsThis(methodCall)) {
        return null;
    }

    if (!(methodCall.getMethod() instanceof ConstantExpression)) {
        return null;
    }

    String methodName = methodCall.getMethod().getText();

    if (methodName.equals(PLUGINS) || methodName.equals(classpathBlockName)) {
        if (!(methodCall.getArguments() instanceof ArgumentListExpression)) {
            return null;
        }

        ArgumentListExpression args = (ArgumentListExpression) methodCall.getArguments();
        if (args.getExpressions().size() == 1 && args.getExpression(0) instanceof ClosureExpression) {
            return new ScriptBlock(methodName, (ClosureExpression) args.getExpression(0));
        } else {
            return null;
        }
    } else {
        return null;
    }
}
 
Example #30
Source File: ConstructorNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
public boolean firstStatementIsSpecialConstructorCall() {
    Statement code = getFirstStatement();
    if (!(code instanceof ExpressionStatement)) return false;

    Expression expression = ((ExpressionStatement) code).getExpression();
    if (!(expression instanceof ConstructorCallExpression)) return false;
    ConstructorCallExpression cce = (ConstructorCallExpression) expression;
    return cce.isSpecialCall();
}