Use this page to list use cases for AST-level macros in Groovy.
How do you want to use such macros? Show examples of their usage (without showing how they're implemented). Add to the bottom of the page.
Increase code readability
Rearrange code portions
The end-weight principle for natural languages says the longer stuff should be at the end of a sentence.
In Groovy/Java, while and if statements are usually heavy in the block/statement, and light in the condition.
When the statement/block is short and the condition long, it can be more readable to put the block last.
Eg:
do{ i++; return c }if( ( severance.taxAmount >= TaxYear2006.taxAmounts.severanceLimit['dependent'] || ... ... ... ... ... ... )
is transformed to:
if( ... ... ... ){ i++; return c }
We could use 'unless' and 'until' if using 'if' and 'while' caused problems.
Common modifier
When a long list of methods and/or fields have the same modifier/s,
it may be more readable to apply them to a whole block, eg:
static{
def a(){ ... }
def b(){ ... }
}
becomes
static a(){ ... } static b(){ ... }
Transform statements
Eg:
def genUniqueScriptName(){ static int i=1; 'Script_' + i++ }
becomes
class UniqueScriptName{ static int i=1; static gen(){ 'Script_' + i++ }
triggered by the 'static' modifier of a field in a function.
Use other natural languages with Groovy
Enable fuller internationalization of Groovy, eg:
mientras( i < 10 ){ ... ... ... }
would convert to
while( i < 10 ){ ... ... ... }
if a Spanish option for Groovy was loaded.
More Seamless Integration with Java and Java-like languages
Embed Java code within Groovy without quoting it,
and without needing to bind variables to the same name, ie, no binding.setVariable('i', i).
eg:
int i= 0 java('jdk1.5.0_07'){ System.out.println i; class ... ... ... }
Simplify the Antlr lexer/parser
Many existing syntactic sugars could be re-implemented as macros in a standard macro library.
This might simplify the Antlr lexer/parser, enabling better maintenance of and extensions to it.
Eg, properties where:
String reading= 'OK
expands to:
private String reading= 'OK' public String getReading(){ this.xxxx } public void setReading( String s ){ this.xxxx= s }
Other examples:
- for( i in ... ) expanding to code using iterator
- shorthand notation for invoking method with closure/s at last parameter/s






