Java Mailing List Archive

http://www.gg3721.com/

Home » user.groovy »

Re: [groovy-user] Trying to figure out AST on a Closure

Cédric Champeau

2012-01-27

Replies: Find Java Web Hosting

Author LoginPost Reply
Hi,

The easiest way is to retrieve the code from the closure and add what you want inside. For example :

ClosureExpression annotatedClosure = (ClosureExpression)astNodes[1]
Statement code = annotatedClosure.getCode()
BlockStatement newCode = new BlockStatement()
// add your "before" statements here
// newCode.addStatement(...)

if (code instanceof BlockStatement) {
   BlockStatement oldCode = (BlockStatement) code
   oldCode.statements.each { newCode.addStatement() }
}

// add your "after" statements here
// newCode.addStatement (...)

annotatedClosure.code = newCode

That's all ;)

Le 27/01/2012 18:25, virtualdogbert a écrit :
So what I want to do is make an AST transformation for a closure(grails controller action) that add code around the closure body. My first instinct was to use new AstBuilder().buildFromSpec make a new closure with the dsl and just copy everything from the old closure something like this:
       ClosureExpression annotatedClosure = (ClosureExpression)astNodes[1]
       Statement closureStatement = annotatedClosure.getCode()

       def ast = new AstBuilder().buildFromSpec {
            closure {
                parameters {
                    parameter 'parms': Object.class // need to transfer prams from original here
                }
                block {
                    //add some code here
                    owner.expression.addAll closureStatement //add the original statement
                    //add some code here
                }
            }
        }
Now I'm not sure if any of that is correct at this point, but the problem that I'm going to get into is how to copy all the parameters over, in the context of the dsl. Or is there another/better way to do it. Keep in mind that for now I'm on grails 1.3.4 which means groovy 1.7.4 and the ClosureExpression does not have a set Method. Any suggestions would be appreciated, I've been trying to make sense of various tutorials, and the documentation. So I thought maybe I could just ask, and someone could point me in the right direction.

View this message in context: Trying to figure out AST on a Closure
Sent from the groovy - user mailing list archive at Nabble.com.


-- 
Cédric Champeau
SpringSource - A Division Of VMware
http://www.springsource.com/
http://twitter.com/CedricChampeau
©2008 gg3721.com - Jax Systems, LLC, U.S.A.