Github user paulk-asert commented on a diff in the pull request: https://github.com/apache/groovy/pull/439#discussion_r82512007 --- Diff: src/spec/doc/core-metaprogramming.adoc --- @@ -2829,6 +2829,153 @@ to use the Groovy Console, in particular the AST browser tool, to gain knowledge resource for learning is the https://github.com/apache/groovy/tree/master/src/test/org/codehaus/groovy/ast/builder[AST Builder] test suite. +==== Macros + +===== Introduction + +Until version 2.5.0, when developing AST transformations, developers should have a deep knowledge about how the AST +(Abstract source tree) was built by the compiler in order to know how to add new expressions or statements during +compile time. + +Although the use of `org.codehaus.groovy.ast.tool.GeneralUtils` static methods could mitigate the burden of creating +expressions and statements, it's still a low-level way of writing those AST nodes directly. +We needed something to abstract us from writing the AST directly and that's exactly what Groovy macros were made for. +They allow you to add code during compile time directly, without having translate the code you had in mind to the +`org.codehaus.groovy.ast.*` node related classes. + +===== Statements and expressions + +Lets see an example, lets create a local AST transformation. `@AddMessageMethod`. When applied to a given class it +will add a new method called `getMessage` to that class. The method will return "42". The annotation it's pretty +straight forward: + +[source,groovy] +---- +include::{projectdir}/src/spec/test/metaprogramming/MacroStatementTest.groovy[tags=addmethodannotation,indent=0] +---- + +How would look like the AST transformation without the use of a macro: + +[source,groovy] +---- +include::{projectdir}/src/spec/test/metaprogramming/MacroStatementTest.groovy[tags=addmethodtransformationwithoutmacro,indent=0] +---- + +<1> Create a return statement +<2> Create a constant expression "42" +<3> Adding the code to the new method +<4> Adding the new method to the annotated class + +If you're not used to the AST API, that definitely doesn't look like the code you had in mind. Now look how the +previous code looks like with the use of macros. --- End diff -- looks like with the use of macros. => simplifies with the use of macros:
--- If your project is set up for it, you can reply to this email and have your reply appear on GitHub as well. If your project does not have this feature enabled and wishes so, or if the feature is enabled but not working, please contact infrastructure at infrastruct...@apache.org or file a JIRA ticket with INFRA. ---