Jim Driscoll's Blog

Notes on Technology and the Web

Word order and Groovy Parsing

leave a comment »

 

In my previous post on Optional Parenthesis in Groovy, I mentioned using the optional parenthesis to make natural looking chains of commands.  But I realize that I overlooked mentioning a really important limitation with this approach, namely, how Groovy will parse these parentheses lacking statements.

Consider this code:

one two three four five

Since Groovy is a dynamic language, this statement will need to figured out by Groovy at compile time with almost no available context.  Is the token one a method, or a binding variable?  That information isn’t available to the compiler, so Groovy has to guess.  Here’s how to figure out what Groovy will do:

Fire up groovyConsole from a command line which has the GDK in it’s PATH.

Type in the line above.

From the menus, select Script -> Inspect AST

In the lower pane of the frame that pops up, you’ll see what Java code is going to be generated by the Groovy parser.  Take special note of the run() method – that’s the part that actually contains the code we typed in, turned into the code below:

public java.lang.Object run() {    
    return this.one(two).three(four).five
}

This really tells us all we need to know about how Groovy’s going to parse a String of words – it’s going to always follow the pattern:

method(param).method(param).variable

Where the first two words are going to be treated as a method name and a parameter (from a binding variable or locally scoped variable), respectively, while any odd instance will be a variable.

So, while you can use optional parentheses to construct a grammar, you should be aware that there are significant restrictions on how you can do so.

Advertisements

Written by jamesgdriscoll

September 15, 2012 at 11:52 AM

Posted in DSL, Groovy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: