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

The following examples show how to use org.codehaus.groovy.ast.stmt.Statement. 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: StatementLabelsScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void call(final SourceUnit source) throws CompilationFailedException {
    // 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) {
                String message = String.format("Statement labels may not be used in build scripts.%nIn case you tried to configure a property named '%s', replace ':' with '=' or ' ', otherwise it will not have the desired effect.",
                        statement.getStatementLabel());
                addError(message, statement);
            }
        }
    });
}
 
Example #2
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 #3
Source File: DefaultPropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public Statement createPropInit(AbstractASTTransformation xform, AnnotationNode anno, ClassNode cNode, PropertyNode pNode, Parameter namedArgsMap) {
    String name = pNode.getName();
    FieldNode fNode = pNode.getField();
    boolean useSetters = xform.memberHasValue(anno, "useSetters", true);
    boolean hasSetter = cNode.getProperty(name) != null && !fNode.isFinal();
    if (namedArgsMap != null) {
        return assignFieldS(useSetters, namedArgsMap, name);
    } else {
        Expression var = varX(name);
        if (useSetters && hasSetter) {
            return setViaSetterS(name, var);
        } else {
            return assignToFieldS(name, var);
        }
    }
}
 
Example #4
Source File: DefaultScriptCompilationHandler.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean isEmpty(SourceUnit source) {
    if (!source.getAST().getMethods().isEmpty()) {
        return false;
    }
    List<Statement> statements = source.getAST().getStatementBlock().getStatements();
    if (statements.size() > 1) {
        return false;
    }
    if (statements.isEmpty()) {
        return true;
    }

    Statement statement = statements.get(0);
    if (statement instanceof ReturnStatement) {
        ReturnStatement returnStatement = (ReturnStatement) statement;
        if (returnStatement.getExpression() instanceof ConstantExpression) {
            ConstantExpression constantExpression = (ConstantExpression) returnStatement.getExpression();
            if (constantExpression.getValue() == null) {
                return true;
            }
        }
    }

    return false;
}
 
Example #5
Source File: ReturnAdder.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Statement adjustSwitchCaseCode(final Statement statement, final VariableScope scope, final boolean defaultCase) {
    if (statement instanceof BlockStatement) {
        List<Statement> statements = ((BlockStatement) statement).getStatements();
        if (!statements.isEmpty()) {
            int lastIndex = statements.size() - 1;
            Statement last = statements.get(lastIndex);
            if (last instanceof BreakStatement) {
                if (doAdd) {
                    statements.remove(lastIndex);
                    return addReturnsIfNeeded(statement, scope);
                } else {
                    BlockStatement newBlock = new BlockStatement();
                    for (int i = 0; i < lastIndex; i += 1) {
                        newBlock.addStatement(statements.get(i));
                    }
                    return addReturnsIfNeeded(newBlock, scope);
                }
            } else if (defaultCase) {
                return addReturnsIfNeeded(statement, scope);
            }
        }
    }
    return statement;
}
 
Example #6
Source File: ClassNode.java    From groovy with Apache License 2.0 6 votes vote down vote up
public PropertyNode addProperty(String name,
                                int modifiers,
                                ClassNode type,
                                Expression initialValueExpression,
                                Statement getterBlock,
                                Statement setterBlock) {
    for (PropertyNode pn : getProperties()) {
        if (pn.getName().equals(name)) {
            if (pn.getInitialExpression() == null && initialValueExpression != null)
                pn.getField().setInitialValueExpression(initialValueExpression);

            if (pn.getGetterBlock() == null && getterBlock != null)
                pn.setGetterBlock(getterBlock);

            if (pn.getSetterBlock() == null && setterBlock != null)
                pn.setSetterBlock(setterBlock);

            return pn;
        }
    }
    PropertyNode node =
            new PropertyNode(name, modifiers, type, redirect(), initialValueExpression, getterBlock, setterBlock);
    addProperty(node);
    return node;
}
 
Example #7
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Statement createConstructorStatementDate(FieldNode fNode, Parameter namedArgsMap, boolean shouldNullCheck) {
    final Expression fieldExpr = propX(varX("this"), fNode.getName());
    final Expression param = getParam(fNode, namedArgsMap != null);
    Statement assignStmt = assignS(fieldExpr, cloneDateExpr(param));
    assignStmt = ifElseS(
            equalsNullX(param),
            shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr),
            assignStmt);
    final Statement assignInit;
    Expression initExpr = fNode.getInitialValueExpression();
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
    } else {
        assignInit = assignS(fieldExpr, cloneDateExpr(initExpr));
    }
    return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
 
Example #8
Source File: MemoizedASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static MethodNode buildDelegatingMethod(final MethodNode annotatedMethod, final ClassNode ownerClassNode) {
    Statement code = annotatedMethod.getCode();
    int access = ACC_PROTECTED;
    if (annotatedMethod.isStatic()) {
        access = ACC_PRIVATE | ACC_STATIC;
    }
    MethodNode method = new MethodNode(
            buildUniqueName(ownerClassNode, METHOD_LABEL, annotatedMethod),
            access,
            annotatedMethod.getReturnType(),
            cloneParams(annotatedMethod.getParameters()),
            annotatedMethod.getExceptions(),
            code
    );
    method.addAnnotations(filterAnnotations(annotatedMethod.getAnnotations()));
    return method;
}
 
Example #9
Source File: StaticTypesLambdaWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void addDeserializeLambdaMethod() {
    ClassNode enclosingClass = controller.getClassNode();
    Parameter[] parameters = createDeserializeLambdaMethodParams();
    if (enclosingClass.hasMethod("$deserializeLambda$", parameters)) {
        return;
    }

    Statement code = block(
            declS(localVarX("enclosingClass", OBJECT_TYPE), classX(enclosingClass)),
            ((BlockStatement) new AstStringCompiler().compile(
                    "return enclosingClass" +
                            ".getDeclaredMethod(\"\\$deserializeLambda_${serializedLambda.getImplClass().replace('/', '$')}\\$\", serializedLambda.getClass())" +
                            ".invoke(null, serializedLambda)"
            ).get(0)).getStatements().get(0)
    );

    enclosingClass.addSyntheticMethod(
            "$deserializeLambda$",
            ACC_PRIVATE | ACC_STATIC,
            OBJECT_TYPE,
            parameters,
            ClassNode.EMPTY_ARRAY,
            code);
}
 
Example #10
Source File: GradleModellingLanguageTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void call(SourceUnit source) throws CompilationFailedException {
    ModelRegistryDslHelperStatementGenerator statementGenerator = new ModelRegistryDslHelperStatementGenerator();
    BlockStatement rootStatementBlock = source.getAST().getStatementBlock();
    ListIterator<Statement> statementsIterator = rootStatementBlock.getStatements().listIterator();
    while (statementsIterator.hasNext()) {
        Statement statement = statementsIterator.next();
        ScriptBlock scriptBlock = AstUtils.detectScriptBlock(statement, SCRIPT_BLOCK_NAMES);
        if (scriptBlock != null) {
            statementsIterator.remove();
            ScopeVisitor scopeVisitor = new ScopeVisitor(source, statementGenerator);
            scriptBlock.getClosureExpression().getCode().visit(scopeVisitor);
        }
    }
    rootStatementBlock.addStatements(statementGenerator.getGeneratedStatements());
}
 
Example #11
Source File: ClassNode.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void addStaticInitializerStatements(List<Statement> staticStatements, boolean fieldInit) {
    MethodNode method = getOrAddStaticConstructorNode();
    BlockStatement block = getCodeAsBlock(method);

    // while anything inside a static initializer block is appended
    // we don't want to append in the case we have a initialization
    // expression of a static field. In that case we want to add
    // before the other statements
    if (!fieldInit) {
        block.addStatements(staticStatements);
    } else {
        List<Statement> blockStatements = block.getStatements();
        staticStatements.addAll(blockStatements);
        blockStatements.clear();
        blockStatements.addAll(staticStatements);
    }
}
 
Example #12
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Expression transformClosureExpression(final ClosureExpression ce) {
    boolean oldInClosure = inClosure;
    inClosure = true;
    for (Parameter para : getParametersSafe(ce)) {
        ClassNode t = para.getType();
        resolveOrFail(t, ce);
        visitAnnotations(para);
        if (para.hasInitialExpression()) {
            para.setInitialExpression(transform(para.getInitialExpression()));
        }
        visitAnnotations(para);
    }

    Statement code = ce.getCode();
    if (code != null) code.visit(this);
    inClosure = oldInClosure;
    return ce;
}
 
Example #13
Source File: ClassNode.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * If a method with the given name and parameters is already defined then it is returned
 * otherwise the given method is added to this node. This method is useful for
 * default method adding like getProperty() or invokeMethod() where there may already
 * be a method defined in a class and so the default implementations should not be added
 * if already present.
 */
public MethodNode addMethod(String name,
                            int modifiers,
                            ClassNode returnType,
                            Parameter[] parameters,
                            ClassNode[] exceptions,
                            Statement code) {
    MethodNode other = getDeclaredMethod(name, parameters);
    // don't add duplicate methods
    if (other != null) {
        return other;
    }
    MethodNode node = new MethodNode(name, modifiers, returnType, parameters, exceptions, code);
    addMethod(node);
    return node;
}
 
Example #14
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 #15
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 #16
Source File: BeanUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void addIfMissing(ClassNode cNode, List<PropertyNode> result, Set<String> names, MethodNode mNode, ClassNode returnType, String propName, Statement getter, Statement setter) {
    if (cNode.getProperty(propName) != null) return;
    if (names.contains(propName)) {
        for (PropertyNode pn : result) {
            if (pn.getName().equals(propName) && getter != null && pn.getGetterBlock() == null) {
                pn.setGetterBlock(getter);
            }
            if (pn.getName().equals(propName) && setter != null && pn.getSetterBlock() == null) {
                pn.setSetterBlock(setter);
            }
        }
    } else {
        result.add(new PropertyNode(propName, mNode.getModifiers(), returnType, cNode, null, getter, setter));
        names.add(propName);
    }
}
 
Example #17
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 #18
Source File: Verifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitMethod(MethodNode node) {
    // GROOVY-3712 - if it's an MOP method, it's an error as they aren't supposed to exist before ACG is invoked
    if (MopWriter.isMopMethod(node.getName())) {
        throw new RuntimeParserException("Found unexpected MOP methods in the class node for " + classNode.getName() + "(" + node.getName() + ")", classNode);
    }

    adjustTypesIfStaticMainMethod(node);
    this.methodNode = node;
    addReturnIfNeeded(node);

    Statement stmt = node.getCode();
    if (stmt != null) {
        stmt.visit(new VerifierCodeVisitor(getClassNode()));
    }
}
 
Example #19
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 #20
Source File: AstUtils.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Nullable
public static ScriptBlock detectScriptBlock(Statement statement) {
    MethodCallExpression methodCall = extractBareMethodCall(statement);
    if (methodCall == null) {
        return null;
    }

    String methodName = extractConstantMethodName(methodCall);
    if (methodName == null) {
        return null;
    }

    ClosureExpression closureExpression = getSingleClosureArg(methodCall);
    return closureExpression == null ? null : new ScriptBlock(methodName, closureExpression);
}
 
Example #21
Source File: AbstractInterruptibleASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * @return Returns the interruption check statement.
 */
protected Statement createInterruptStatement() {
    return ifS(createCondition(),
            throwS(
                    ctorX(thrownExceptionType, args(constX(getErrorMessage())))
            )
    );
}
 
Example #22
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Return an existing method if one exists or else create a new method and mark it as {@code @Generated}.
 *
 * @see ClassNode#addMethod(String, int, ClassNode, Parameter[], ClassNode[], Statement)
 */
public static MethodNode addGeneratedMethod(ClassNode cNode, String name,
                            int modifiers,
                            ClassNode returnType,
                            Parameter[] parameters,
                            ClassNode[] exceptions,
                            Statement code) {
    MethodNode existing = cNode.getDeclaredMethod(name, parameters);
    if (existing != null) return existing;
    MethodNode result = new MethodNode(name, modifiers, returnType, parameters, exceptions, code);
    addGeneratedMethod(cNode, result);
    return result;
}
 
Example #23
Source File: GrabAnnotationTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addGrabResolverAsStaticInitIfNeeded(ClassNode grapeClassNode, AnnotationNode node,
                                                  List<Statement> grabResolverInitializers, Map<String, Object> grabResolverMap) {
    if ((node.getMember("initClass") == null)
        || (node.getMember("initClass") == ConstantExpression.TRUE))
    {
        MapExpression resolverArgs = new MapExpression();
        for (Map.Entry<String, Object> next : grabResolverMap.entrySet()) {
            resolverArgs.addMapEntryExpression(constX(next.getKey()), constX(next.getValue()));
        }
        grabResolverInitializers.add(stmt(callX(grapeClassNode, "addResolver", args(resolverArgs))));
    }
}
 
Example #24
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 #25
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Statement assignFieldWithDefault(Parameter map, FieldNode fNode, Statement assignStmt, Statement assignInit) {
    if (map == null) {
        return assignStmt;
    }
    ArgumentListExpression nameArg = args(constX(fNode.getName()));
    MethodCallExpression var = callX(varX(map), "get", nameArg);
    var.setImplicitThis(false);
    MethodCallExpression containsKey = callX(varX(map), "containsKey", nameArg);
    containsKey.setImplicitThis(false);
    fNode.getDeclaringClass().getField(fNode.getName()).setInitialValueExpression(null); // to avoid default initialization
    return ifElseS(containsKey, assignStmt, assignInit);
}
 
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: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void visitGetter(PropertyNode node, Statement getterBlock, int getterModifiers, String getterName) {
    MethodNode getter =
            new MethodNode(getterName, getterModifiers, node.getType(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, getterBlock);
    getter.setSynthetic(true);
    addPropertyMethod(getter);
    visitMethod(getter);
}
 
Example #28
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 #29
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createSoftGetter(FieldNode fieldNode, Expression initExpr, ClassNode type) {
    final BlockStatement body = new BlockStatement();
    final Expression fieldExpr = varX(fieldNode);
    final Expression resExpr = localVarX("_result", type);
    final MethodCallExpression callExpression = callX(fieldExpr, "get");
    callExpression.setSafe(true);
    body.addStatement(declS(resExpr, callExpression));

    final Statement mainIf = ifElseS(notNullX(resExpr), stmt(resExpr), block(
            assignS(resExpr, initExpr),
            assignS(fieldExpr, ctorX(SOFT_REF, resExpr)),
            stmt(resExpr)));

    if (fieldNode.isVolatile()) {
        body.addStatement(ifElseS(
                notNullX(resExpr),
                stmt(resExpr),
                new SynchronizedStatement(syncTarget(fieldNode), block(
                        assignS(resExpr, callExpression),
                        mainIf)
                )
        ));
    } else {
        body.addStatement(mainIf);
    }
    addMethod(fieldNode, body, type);
}
 
Example #30
Source File: VetoableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Wrap an existing setter.
 */
private static void wrapSetterMethod(ClassNode classNode, boolean bindable, String propertyName) {
    String getterName = "get" + capitalize(propertyName);
    MethodNode setter = classNode.getSetterMethod(getSetterName(propertyName));

    if (setter != null) {
        // Get the existing code block
        Statement code = setter.getCode();

        Expression oldValue = localVarX("$oldValue");
        Expression newValue = localVarX("$newValue");
        Expression proposedValue = varX(setter.getParameters()[0].getName());
        BlockStatement block = new BlockStatement();

        // create a local variable to hold the old value from the getter
        block.addStatement(declS(oldValue, callThisX(getterName)));

        // add the fireVetoableChange method call
        block.addStatement(stmt(callThisX("fireVetoableChange", args(
                constX(propertyName), oldValue, proposedValue))));

        // call the existing block, which will presumably set the value properly
        block.addStatement(code);

        if (bindable) {
            // get the new value to emit in the event
            block.addStatement(declS(newValue, callThisX(getterName)));

            // add the firePropertyChange method call
            block.addStatement(stmt(callThisX("firePropertyChange", args(constX(propertyName), oldValue, newValue))));
        }

        // replace the existing code block with our new one
        setter.setCode(block);
    }
}