Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

AST Transformations


[ 186 ]

What is an AST


The acronym AST is shorthand for the abstract syntax tree. During the compilation
process, the Groovy compiler groovyc will generate interim data structures that
represent the code that is being compiled. The main data structure that the complier
produces is the AST. The AST is quite literally an abstract syntax tree. In other
words, it is a tree structure in memory that describes the syntax of the code being
compiled. To illustrate this, let's take a simple example:


class Foo {
def barValue

def bar() {
return barValue
}
}

The compiler will parse this code and turn it into a tree structure to represent
the syntax of the code. At the top of the tree is a node, which represents the class
declaration. This node is represented by the Groovy AST class ClassNode. The class
node will have several child nodes of the type ConstructorNode, MethodNode,
FieldNode, and PropertyNode depending on what phase of compilation we are at.


The major elements of Groovy AST are represented by objects of the
type ASTNode and its subclasses. As you drill down the tree, you will
encounter elements that represent the expressions in the code represented
by the statement and its subclasses. You will encounter a lot of these
in the examples in this chapter. For more information, see the class
documentation for the ast package and its subpackages at http://
docs.groovy-lang.org/latest/html/api/org/codehaus/
groovy/ast/package-summary.html.

The method node for the bar method will have a block statement node, which
represents the block of code within the body of the method. As it happens, this
block of code is only a single statement, so the only child of the block statement
is a return statement node and the only child of the return statement is a variable
expression node.


The best way to explore the AST is via the groovyConsole tool. Type the preceding
code snippet into groovyConsole and view the AST in the AST viewer, accessible
via the script menu. By selecting the semantic analysis phase of compilation, we will
see the following tree of AST nodes are generated at this phase of compilation. More
and more detail is compiled into the class as the compiler reaches later phases. Let's
take a more detailed look at the phases of the Groovy compiler.


http://www.ebook3000.com
Free download pdf