org.codehaus.groovy.syntax.Token Java Examples

The following examples show how to use org.codehaus.groovy.syntax.Token. 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: ScopeVisitor.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    Token operation = expression.getOperation();
    if (operation.isA(Types.LEFT_SHIFT) && expression.getLeftExpression() instanceof VariableExpression && expression.getRightExpression() instanceof ClosureExpression) {
        addCreator(scope, (VariableExpression) expression.getLeftExpression(), (ClosureExpression) expression.getRightExpression());
    } else if (operation.isA(Types.ASSIGN)) {
        if (expression.getLeftExpression() instanceof VariableExpression) {
            addCreator(scope, (VariableExpression) expression.getLeftExpression(), expression.getRightExpression());
        } else if (expression.getLeftExpression() instanceof PropertyExpression) {
            addCreator(scope, (PropertyExpression) expression.getLeftExpression(), expression.getRightExpression());
        } else {
            super.visitBinaryExpression(expression);
        }
    } else {
        super.visitBinaryExpression(expression);
    }
}
 
Example #2
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 #3
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 #4
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 6 votes vote down vote up
private void multipleAssignment(final Expression parentExpression,
                                final TupleExpression tuple,
                                final Expression rhs) {
    List<Expression> tupleExpressions = tuple.getExpressions();

    final VariableExpression rhsTmpVar = new VariableExpression("___cpsTmpVar___" + iota.getAndIncrement());
    rhsTmpVar.setAccessedVariable(rhsTmpVar);
    DeclarationExpression decl = new DeclarationExpression(rhsTmpVar, new Token(ASSIGN, "=", -1, -1), rhs);
    visit(decl);
    for (int i = 0, tupleExpressionsSize = tupleExpressions.size(); i < tupleExpressionsSize; i++) {
        final Expression tupleExpression = tupleExpressions.get(i);
        final Expression index = new ConstantExpression(i, true);
        // def (a, b, c) = [1, 2] is allowed - c will just be null in that scenario.
        // def (a, b) = [1, 2, 3] is allowed as well - 3 is just discarded.
        // def (a, b) = 4 will error due to Integer.getAt(int) not being a thing
        // def (a, b) = "what" is allowed - a will equal 'w', and b will equal 'h'
        makeNode("assign", new Runnable() {
            @Override
            public void run() {
                loc(parentExpression);
                visit(tupleExpression);
                getMultipleAssignmentValueOrCast((VariableExpression)tupleExpression, rhsTmpVar, index);
            }
        });
    }
}
 
Example #5
Source File: ScopeVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void visitBinaryExpression(BinaryExpression expression) {
    Token operation = expression.getOperation();
    if (operation.isA(Types.LEFT_SHIFT) && expression.getLeftExpression() instanceof VariableExpression && expression.getRightExpression() instanceof ClosureExpression) {
        addCreator(scope, (VariableExpression) expression.getLeftExpression(), (ClosureExpression) expression.getRightExpression());
    } else if (operation.isA(Types.ASSIGN)) {
        if (expression.getLeftExpression() instanceof VariableExpression) {
            addCreator(scope, (VariableExpression) expression.getLeftExpression(), expression.getRightExpression());
        } else if (expression.getLeftExpression() instanceof PropertyExpression) {
            addCreator(scope, (PropertyExpression) expression.getLeftExpression(), expression.getRightExpression());
        } else {
            super.visitBinaryExpression(expression);
        }
    } else {
        super.visitBinaryExpression(expression);
    }
}
 
Example #6
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 #7
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 #8
Source File: NAryOperationRewriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Expression transformBinaryExpression(final BinaryExpression exp) {
    final int op = exp.getOperation().getType();
    int token = TokenUtil.removeAssignment(op);
    if (token == op) {
        // no transform needed
        return super.transform(exp);
    }
    BinaryExpression operation = new BinaryExpression(
            exp.getLeftExpression(),
            Token.newSymbol(token, -1, -1),
            exp.getRightExpression()
    );
    operation.setSourcePosition(exp);
    BinaryExpression result = new BinaryExpression(
            exp.getLeftExpression(),
            Token.newSymbol(EQUAL, -1, -1),
            operation
    );
    result.setSourcePosition(exp);
    return result;
}
 
Example #9
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 #10
Source File: SqlWhereVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void visitBinaryExpression(BinaryExpression expression) {
    Expression left = expression.getLeftExpression();
    Expression right = expression.getRightExpression();
    boolean leaf = (right instanceof ConstantExpression || left instanceof ConstantExpression);

    if (!leaf) buffer.append("(");
    left.visit(this);
    buffer.append(" ");

    Token token = expression.getOperation();
    buffer.append(tokenAsSql(token));

    buffer.append(" ");
    right.visit(this);
    if (!leaf) buffer.append(")");
}
 
Example #11
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void evaluateElvisEqual(final BinaryExpression expression) {
    Token operation = expression.getOperation();
    BinaryExpression elvisAssignmentExpression = binX(
            expression.getLeftExpression(),
            Token.newSymbol(ASSIGN, operation.getStartLine(), operation.getStartColumn()),
            new ElvisOperatorExpression(expression.getLeftExpression(), expression.getRightExpression())
    );
    this.evaluateEqual(elvisAssignmentExpression, false);
}
 
Example #12
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void evaluateBinaryExpressionWithAssignment(final String method, final BinaryExpression expression) {
    Expression leftExpression = expression.getLeftExpression();
    if (leftExpression instanceof PropertyExpression) {
        PropertyExpression pexp = (PropertyExpression) leftExpression;

        BinaryExpression expressionWithoutAssignment = binX(
                leftExpression,
                Token.newSymbol(
                        TokenUtil.removeAssignment(expression.getOperation().getType()),
                        expression.getOperation().getStartLine(),
                        expression.getOperation().getStartColumn()
                ),
                expression.getRightExpression()
        );
        expressionWithoutAssignment.copyNodeMetaData(expression);
        expressionWithoutAssignment.setSafe(expression.isSafe());
        expressionWithoutAssignment.setSourcePosition(expression);

        if (makeSetProperty(
                pexp.getObjectExpression(),
                pexp.getProperty(),
                expressionWithoutAssignment,
                pexp.isSafe(),
                pexp.isSpreadSafe(),
                pexp.isImplicitThis(),
                pexp instanceof AttributeExpression)) {
            return;
        }
    }
    super.evaluateBinaryExpressionWithAssignment(method, expression);
}
 
Example #13
Source File: BinaryExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression convertInOperatorToTernary(final BinaryExpression bin, final Expression rightExpression, final Expression leftExpression) {
    MethodCallExpression call = callX(rightExpression, "isCase", leftExpression);
    call.setMethodTarget(bin.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET));
    call.setSourcePosition(bin);
    call.copyNodeMetaData(bin);
    Expression tExp = ternaryX(
            boolX(binX(rightExpression, Token.newSymbol("==", -1, -1), nullX())),
            binX(leftExpression, Token.newSymbol("==", -1, -1), nullX()),
            call
    );
    return tExp;
}
 
Example #14
Source File: BinaryExpression.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an assignment expression in which the specified expression
 * is written into the specified variable name.
 */

public static BinaryExpression newAssignmentExpression(Variable variable, Expression rhs) {
    VariableExpression lhs = new VariableExpression(variable);
    Token operator = Token.newPlaceholder(Types.ASSIGN);

    return new BinaryExpression(lhs, operator, rhs);
}
 
Example #15
Source File: BinaryExpression.java    From groovy with Apache License 2.0 5 votes vote down vote up
public BinaryExpression(Expression leftExpression,
                        Token operation,
                        Expression rightExpression,
                        boolean safe) {
    this(leftExpression, operation, rightExpression);
    this.safe = safe;
}
 
Example #16
Source File: BinaryExpression.java    From groovy with Apache License 2.0 5 votes vote down vote up
public BinaryExpression(Expression leftExpression,
                        Token operation,
                        Expression rightExpression) {
    this.leftExpression = leftExpression;
    this.operation = operation;
    this.rightExpression = rightExpression;
}
 
Example #17
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 #18
Source File: SecureASTCustomizer.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that a given token is either in the allowed list or not in the disallowed list.
 *
 * @param token the token to be checked
 * @throws SecurityException if usage of this token is forbidden
 */
protected void assertTokenAuthorized(final Token token) throws SecurityException {
    final int value = token.getType();
    if (disallowedTokens != null && disallowedTokens.contains(value)) {
        throw new SecurityException("Token " + token + " is not allowed");
    } else if (allowedTokens != null && !allowedTokens.contains(value)) {
        throw new SecurityException("Token " + token + " is not allowed");
    }
}
 
Example #19
Source File: SqlWhereVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected String tokenAsSql(Token token) {
    switch (token.getType()) {
        case Types.COMPARE_EQUAL:
            return "=";
        case Types.LOGICAL_AND:
            return "and";
        case Types.LOGICAL_OR:
            return "or";
        default:
            return token.getText();
    }
}
 
Example #20
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
protected String prepostfixOperatorSuffix(Token operation) {
    switch (operation.getType()) {
    case PLUS_PLUS:
        return "Inc";
    case MINUS_MINUS:
        return "Dec";
    default:
        throw new UnsupportedOperationException("Unknown operator:" + operation.getText());
    }
}
 
Example #21
Source File: VariablesVisitorTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_add_decalred_expression_with_position() throws Exception {
    final VariablesVisitor variablesVisitor = new VariablesVisitor(new VariableScope());

    final DeclarationExpression declarationExpression = new DeclarationExpression(new VariableExpression("myVar"), Token.NULL,
            new VariableExpression("anotherVar"));
    declarationExpression.setStart(42);
    variablesVisitor.visitDeclarationExpression(declarationExpression);

    assertThat(variablesVisitor.getDeclaredExpressions()).containsExactly(entry("myVar", new Position(42)));
}
 
Example #22
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private BinaryExpression createAssignmentToField(final Expression rightExpression,
                                                 final Token operation, final String fieldName) {
    return new BinaryExpression(
            new PropertyExpression(
                    new VariableExpression(weaved),
                    fieldName
            ),
            operation,
            transform(rightExpression));
}
 
Example #23
Source File: TraitReceiverTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private TernaryExpression createStaticReceiver(final Expression receiver) {
    return new TernaryExpression(
            new BooleanExpression(new BinaryExpression(
                    receiver,
                    Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1),
                    new ClassExpression(ClassHelper.CLASS_Type)
            )),
            receiver,
            new MethodCallExpression(createFieldHelperReceiver(), "getClass", ArgumentListExpression.EMPTY_ARGUMENTS)
    );
}
 
Example #24
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement createSuperFallback(MethodNode forwarderMethod, ClassNode returnType) {
    ArgumentListExpression args = new ArgumentListExpression();
    Parameter[] forwarderMethodParameters = forwarderMethod.getParameters();
    for (final Parameter forwarderMethodParameter : forwarderMethodParameters) {
        args.addExpression(new VariableExpression(forwarderMethodParameter));
    }
    BinaryExpression instanceOfExpr = new BinaryExpression(new VariableExpression("this"), Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1), new ClassExpression(Traits.GENERATED_PROXY_CLASSNODE));
    MethodCallExpression superCall = new MethodCallExpression(
            new VariableExpression("super"),
            forwarderMethod.getName(),
            args
    );
    superCall.setImplicitThis(false);
    CastExpression proxyReceiver = new CastExpression(Traits.GENERATED_PROXY_CLASSNODE, new VariableExpression("this"));
    MethodCallExpression getProxy = new MethodCallExpression(proxyReceiver, "getProxyTarget", ArgumentListExpression.EMPTY_ARGUMENTS);
    getProxy.setImplicitThis(true);
    StaticMethodCallExpression proxyCall = new StaticMethodCallExpression(
            ClassHelper.make(InvokerHelper.class),
            "invokeMethod",
            new ArgumentListExpression(getProxy, new ConstantExpression(forwarderMethod.getName()), new ArrayExpression(ClassHelper.OBJECT_TYPE, args.getExpressions()))
    );
    IfStatement stmt = new IfStatement(
            new BooleanExpression(instanceOfExpr),
            new ExpressionStatement(new CastExpression(returnType,proxyCall)),
            new ExpressionStatement(superCall)
    );
    return stmt;
}
 
Example #25
Source File: BinaryExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static DeclarationExpression optimizeConstantInitialization(final BinaryExpression originalDeclaration, final Token operation, final ConstantExpression constant, final Expression leftExpression, final ClassNode declarationType) {
    Expression cexp = constX(convertConstant((Number) constant.getValue(), ClassHelper.getWrapper(declarationType)), true);
    cexp.setType(declarationType);
    cexp.setSourcePosition(constant);
    DeclarationExpression result = new DeclarationExpression(
            leftExpression,
            operation,
            cexp
    );
    result.setSourcePosition(originalDeclaration);
    result.copyNodeMetaData(originalDeclaration);
    return result;
}
 
Example #26
Source File: NAryOperationRewriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformPostfixExpression(final PostfixExpression exp) {
    if (isInternalFieldAccess(exp.getExpression())) {
        Token operation = exp.getOperation();
        sourceUnit.addError(new SyntaxException("Postfix expressions on trait fields/properties  are not supported in traits.", operation.getStartLine(), operation.getStartColumn()));
        return exp;
    } else {
        return super.transform(exp);
    }
}
 
Example #27
Source File: NAryOperationRewriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformPrefixExpression(final PrefixExpression exp) {
    if (isInternalFieldAccess(exp.getExpression())) {
        Token operation = exp.getOperation();
        sourceUnit.addError(new SyntaxException("Prefix expressions on trait fields/properties are not supported in traits.", operation.getStartLine(), operation.getStartColumn()));
        return exp;
    } else {
        return super.transform(exp);
    }
}
 
Example #28
Source File: CompareToNullExpression.java    From groovy with Apache License 2.0 4 votes vote down vote up
public CompareToNullExpression(final Expression objectExpression, final boolean compareToNull) {
    super(objectExpression, new Token(Types.COMPARE_TO, compareToNull ? "==" : "!=", -1, -1), ConstantExpression.NULL);
    this.objectExpression = objectExpression;
    this.equalsNull = compareToNull;
}
 
Example #29
Source File: IfElseTest.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void testLoop() 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));

    classNode.addProperty(new PropertyNode("result", ACC_PUBLIC, ClassHelper.STRING_TYPE, classNode, null, null, null));

    BooleanExpression expression =
            new BooleanExpression(
                    new BinaryExpression(
                            new FieldExpression(
                                    new FieldNode("bar", ACC_PRIVATE, ClassHelper.STRING_TYPE, classNode, ConstantExpression.NULL)),
                            Token.newSymbol("==", 0, 0),
                            new ConstantExpression("abc")));

    Statement trueStatement =
            new ExpressionStatement(
                    new BinaryExpression(
                            new FieldExpression(
                                    new FieldNode("result", ACC_PRIVATE, ClassHelper.STRING_TYPE, classNode, ConstantExpression.NULL)),
                            Token.newSymbol("=", 0, 0),
                            new ConstantExpression("worked")));

    Statement falseStatement = createPrintlnStatement(new ConstantExpression("false"));

    IfStatement statement = new IfStatement(expression, trueStatement, falseStatement);
    classNode.addMethod(new MethodNode("ifDemo", ACC_PUBLIC, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, statement));

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

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

    assertSetProperty(bean, "bar", "abc");

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

    Object[] array = {
    };

    InvokerHelper.invokeMethod(bean, "ifDemo", array);

    System.out.println("################ Done");

    assertGetProperty(bean, "result", "worked");
}
 
Example #30
Source File: GStringTest.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void testConstructor() throws Exception {
    ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, ClassHelper.OBJECT_TYPE);

    //Statement printStatement = createPrintlnStatement(new VariableExpression("str"));

    // simulate "Hello ${user}!"
    GStringExpression compositeStringExpr = new GStringExpression("hello ${user}!");
    compositeStringExpr.addString(new ConstantExpression("Hello "));
    compositeStringExpr.addValue(new VariableExpression("user"));
    compositeStringExpr.addString(new ConstantExpression("!"));
    BlockStatement block = new BlockStatement();
    block.addStatement(
            new ExpressionStatement(
                    new DeclarationExpression(
                            new VariableExpression("user"),
                            Token.newSymbol("=", -1, -1),
                            new ConstantExpression("World"))));
    block.addStatement(
            new ExpressionStatement(
                    new DeclarationExpression(new VariableExpression("str"), Token.newSymbol("=", -1, -1), compositeStringExpr)));
    block.addStatement(
            new ExpressionStatement(
                    new MethodCallExpression(VariableExpression.THIS_EXPRESSION, "println", new VariableExpression("str"))));

    block.addStatement(
            new ExpressionStatement(
                    new DeclarationExpression(
                            new VariableExpression("text"),
                            Token.newSymbol("=", -1, -1),
                            new MethodCallExpression(new VariableExpression("str"), "toString", MethodCallExpression.NO_ARGUMENTS))));

    block.addStatement(
            new AssertStatement(
                    new BooleanExpression(
                            new BinaryExpression(
                                    new VariableExpression("text"),
                                    Token.newSymbol("==", -1, -1),
                                    new ConstantExpression("Hello World!"))),
                    new ConstantExpression("Assertion failed") // TODO FIX if empty, AssertionWriter fails because source text is null
            )
    );
    classNode.addMethod(new MethodNode("stringDemo", 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);

    //Object[] array = { new Integer(1234), "abc", "def" };

    try {
        InvokerHelper.invokeMethod(bean, "stringDemo", null);
    }
    catch (InvokerInvocationException e) {
        System.out.println("Caught: " + e.getCause());
        e.getCause().printStackTrace();
        fail("Should not have thrown an exception");
    }
}