<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Jim Driscoll&#039;s Blog</title>
	<atom:link href="https://jamesgdriscoll.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://jamesgdriscoll.wordpress.com</link>
	<description>Notes on Technology and the Web</description>
	<lastBuildDate>Mon, 06 May 2013 15:35:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='jamesgdriscoll.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://secure.gravatar.com/blavatar/4f889d949e717cc65412623dcffec642?s=96&#038;d=https%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Jim Driscoll&#039;s Blog</title>
		<link>https://jamesgdriscoll.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://jamesgdriscoll.wordpress.com/osd.xml" title="Jim Driscoll&#039;s Blog" />
	<atom:link rel='hub' href='https://jamesgdriscoll.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Turtle Graphics DSL Implementation, part 2</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/11/03/turtle-graphics-dsl-implementation-part-2/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/11/03/turtle-graphics-dsl-implementation-part-2/#comments</comments>
		<pubDate>Sat, 03 Nov 2012 17:20:24 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=208</guid>
		<description><![CDATA[In the previous post, I described the first part of how Napili implements a simple Turtle Graphics DSL.  Please follow the link to download the whole program, if you want to see the code in context.  This time, we&#8217;ll cover the Binding class. As I&#8217;ve talked about before, the Binding class provides default values to [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=208&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In the <a href="https://jamesgdriscoll.wordpress.com/2012/10/13/turtle-graphics-dsl-implementation-part-1/">previous post</a>, I described the first part of how <a href="https://github.com/netdance/Napili">Napili</a> implements a simple Turtle Graphics DSL.  Please follow the link to download the whole program, if you want to see the code in context.  This time, we&#8217;ll cover the Binding class.</p>
<p>As I&#8217;ve <a href="https://jamesgdriscoll.wordpress.com/2012/04/14/groovy-bindings-or-adding-keywords-to-your-dsl/">talked about before</a>, the Binding class provides default values to variables.  I&#8217;ve also previously discussed <a href="https://jamesgdriscoll.wordpress.com/2012/09/29/property-dispatch-on-groovy-objects/">Property Dispatch,</a> as well as a trick in using the Binding to work around the problem of <a href="https://jamesgdriscoll.wordpress.com/2012/04/29/using-optional-parenthesis-in-groovy-to-your-advantage/">optional parenthesis</a> only being possible for methods with arguments.  I&#8217;ll go over all of that again here, but just in case you&#8217;re joining us for the first time, rereading those older posts might be handy.</p>
<p>The BasicBinding class in Napili serves several purposes &#8211; it creates the Turtle object, and serves it out to either the user directly or via the BaseScript (as I covered in the previous post).  It also handles the &#8220;out&#8221; Binding variable (more on that later).  And it handles no-arg methods on the Turtle object.  Let&#8217;s go through the class, section by section, and we&#8217;ll discuss how it does that.</p>
<pre>private static class BasicBinding extends Binding {
  Turtle turtle

  public BasicBinding() {
    super();
    turtle = new Turtle()
  }
</pre>
<p>This part should be self expanitory &#8211; the constructor  creates the Turtle object which is used to draw, and saves that for later use.</p>
<p>The next method, getVariable, provides the Binding variables to the user scripts.</p>
<pre>  public Object getVariable(String name) {
    if (name == 'out') {
      return NapiliOutput.getPrintWriter();
    } </pre>
<p><code>out</code> is a special value for Bindings &#8211; it&#8217;s the value that&#8217;s used by the <code>println()</code> method.  So, by supplying our own value for it, we can redirect user println calls from going to System.out (and the console) and instead send the output to somewhere more useful and visible to the user. In this case, that redirection happens to an output tab in the UI.</p>
<pre>    if (name == 'turtle') {
      return turtle;
    }
</pre>
<p>The turtle variable is used in the BaseScript file we covered last time.  It&#8217;s also present for the user to manipulate directly &#8211; which could be handy for advanced users who want to create two or more turtles.</p>
<pre>    // treat all no-arg methods on Turtle as binding variables with side effects
    if (turtle.metaClass.respondsTo(turtle,name)) {
      return turtle.metaClass.invokeMethod(turtle, name)
    }
    return super.getVariable(name)
  }
</pre>
<p>The next method, setVariable, isn&#8217;t anything special &#8211; since all the code will stop working in a strange and mysterious way if the value of turtle is overridden, don&#8217;t allow that to happen.</p>
<pre>  public void setVariable(String name, Object value) {
    if ("turtle".equals(name)) {
      NapiliOutput.println('Unable to set "turtle" to value' + value)
      return;
    }
    super.setVariable(name, value);
  }
}</pre>
<p>And that&#8217;s it.  I&#8217;ve now gone over all the DSL magic in the Groovy Turtle Graphics program.  Hopefully you found this relatively clear &#8211; if not, don&#8217;t hesitate to ask questions.  </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/208/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=208&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/11/03/turtle-graphics-dsl-implementation-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>Turtle Graphics DSL Implementation, part 1</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/10/13/turtle-graphics-dsl-implementation-part-1/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/10/13/turtle-graphics-dsl-implementation-part-1/#comments</comments>
		<pubDate>Sat, 13 Oct 2012 21:38:40 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=203</guid>
		<description><![CDATA[Last post, I described a Turtle Graphics DSL, as implemented in my sample program Napili.  (Please download it if you want to see the full code I&#8217;m discussing here).  This time, I&#8217;ll discuss how to implement it.  It&#8217;s surprisingly easy &#8211; though long enough that I&#8217;m going to tackle it in chunks, this is just [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=203&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://jamesgdriscoll.wordpress.com/2012/10/06/a-turtle-graphics-dsl/">Last post</a>, I described a Turtle Graphics DSL, as implemented in my sample program <a href="https://github.com/netdance/Napili">Napili</a>.  (Please download it if you want to see the full code I&#8217;m discussing here).  This time, I&#8217;ll discuss how to implement it.  It&#8217;s surprisingly easy &#8211; though long enough that I&#8217;m going to tackle it in chunks, this is just Part 1.</p>
<p>First, to run the program, there&#8217;s the following snip of code inside a Java class (which is triggered when the user clicks the Run button):</p>
<pre>Class clazz = Class.forName("org.netdance.napili.language.BasicRunner"); 
InvokerHelper.getMetaClass(clazz).invokeStaticMethod(clazz, "run", new Object[]{});</pre>
<p>All this does is use Groovy&#8217;s dynamic invoker structures to invoke BasicRunner.run() &#8211; this code is only there so I can swap out the Groovy DSL classes at a later time, when I&#8217;ll discuss things like security.  I could have done the same thing with Java&#8217;s reflection classes, but if you already have Groovy in your class path, I heartily advise using InvokerHelper, there&#8217;s lots of handy stuff in there, and it&#8217;s considerably easier than using Java&#8217;s native reflection library.  One thing to be aware of, though, if you do:  it&#8217;s in the package <code>org.codehaus.groovy.runtime</code>, which means that the Groovy team reserves the right to change the APIs whenever they need to &#8211; which could make an upgrade of your Groovy version painful (though it&#8217;s not likely that InvokerHelper.getMetaClass(Class) is going to change anytime soon).</p>
<p>There are three classes that make up the language portion of the code.  The first, and by far easiest, is the BaseScript (you&#8217;ll remember, I hope, that I <a href="https://jamesgdriscoll.wordpress.com/2012/04/22/adding-default-methods-with-a-groovy-basescript/">already discussed BaseScripts</a>).  Written in Groovy, it becomes fairly trivial:</p>
<pre>package org.netdance.napili.language
abstract class TurtleDelegateBaseScript extends Script {
    def methodMissing(String name, args) {
        <strong>turtle."$name"(*args)</strong>
    }
}</pre>
<p>This uses a different method of Method Dispatch than I&#8217;ve <a href="https://jamesgdriscoll.wordpress.com/2012/09/29/method-dispatch-on-groovy-objects/">previously discussed</a> &#8211; he methodMissing method is called by Groovy whenever there&#8217;s no method found which matches a given name.  Since we don&#8217;t provide any methods at all, that means that pretty much every method called is going to go through this method.  (Since Scripts define other methods which will be inherited, like run and getBinding, and those won&#8217;t go through <code>methodMissing</code>, but that&#8217;s a problem for another day).  </p>
<p>The meat of the program is just a single line, in bold above.  I&#8217;ve already described what that kind of call does when I discussed <a href="https://jamesgdriscoll.wordpress.com/2012/09/29/method-dispatch-on-groovy-objects/">Method Dispatch</a>, but it&#8217;s worth going through one more time.  The first word, <em>turtle</em>, is interpreted as a Binding variable.   So the Groovy script goes into the Binding class (which I&#8217;ll describe shortly), and fetches the value corresponding to <em>turtle</em>.   Next, the &#8220;$name&#8221; is substituted with the method name called, which will then call the method name on the Turtle object.  Lastly, * is called the spread operator, and serves to break up the list of arguments into individual objects.   At runtime, a command like <code>forward 100</code> will thus be transformed into something like: <code>getBinding().getVariable("turtle").forward(100)</code> - moving the turtle forward 100 steps.</p>
<p>The next portion is the BasicRunner itself &#8211; you&#8217;ll recall that we called the static public run method of that class, above.  It looks something like this:</p>
<pre>static def run() {
  String scriptStr = Napili.code;
  def config = new CompilerConfiguration()
  config.setScriptBaseClass("org.netdance.napili.language.TurtleDelegateBaseScript")
  def ic = new ImportCustomizer();
  ic.addImports('javafx.scene.paint.Color')
  def ti = new ASTTransformationCustomizer([value: 15L],TimedInterrupt)
  config.addCompilationCustomizers(ic, ti)
  def shell = new GroovyShell(config)
  try {
    def script = shell.parse(scriptStr)
    script.setBinding(new BasicBinding())
    script.run()
  } catch (Exception e) {
    // error handling here
  }
}</pre>
<p>In this method, first you fetch the script String to execute from the passed class.  Then, create a <code>CompilerConfiguration</code> object.  To the configuration object, set the BaseScript to the TurtleDelegateBaseScript just described, above.  Add a new import of javafx.scene.paint.Color, which will be applied to every script, so the user can say things like <code>pencolor Color.PURPLE</code> without having to do an import themselves. </p>
<p>The next line, with it&#8217;s creation of an ASTTransformationCustomizer, looks a bit mysterious, but it&#8217;s effect is very straightforward &#8211; it sets a timeout on the script of 15 seconds.  After that, the script will throw an exception.  How it does this <strong>is </strong>a bit of an involved explanation, but we&#8217;ll have a lot more to say about AST Tranformations in a future post.</p>
<p>Then, as I&#8217;ve <a href="https://jamesgdriscoll.wordpress.com/2012/03/17/executing-groovy-programs-in-memory/">previously covered</a>, just create a GroovyShell, parse the script, add a Binding (as I&#8217;ve also <a href="https://jamesgdriscoll.wordpress.com/2012/04/14/groovy-bindings-or-adding-keywords-to-your-dsl/">previously covered</a>), and run the script.  If the user makes an error in the program, it&#8217;ll be caught as an Exception in the catch block.</p>
<p>The Binding itself isn&#8217;t terribly complicated either, but this is getting long, so I&#8217;ll continue on to describe the Binding section in the next post.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/203/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=203&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/10/13/turtle-graphics-dsl-implementation-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>A Turtle Graphics DSL</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/10/06/a-turtle-graphics-dsl/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/10/06/a-turtle-graphics-dsl/#comments</comments>
		<pubDate>Sat, 06 Oct 2012 20:46:28 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=198</guid>
		<description><![CDATA[In my previous post, I discussed the example program that I wrote to exercise the things I&#8217;ve described so far.  Today I&#8217;ll discuss what the DSL will actually look like &#8211; as with most programming tasks, designing your DSL before implementation is almost always advised. There are a couple of different ways that you can [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=198&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In my <a href="https://jamesgdriscoll.wordpress.com/2012/10/03/napili-a-turtle-graphics-program-with-javafx-and-groovy/">previous post</a>, I discussed the <a href="https://github.com/netdance/Napili">example program</a> that I wrote to exercise the things I&#8217;ve described so far.  Today I&#8217;ll discuss what the DSL will actually look like &#8211; as with most programming tasks, designing your DSL before implementation is almost always advised.</p>
<p>There are a couple of different ways that you can use to describe languages, the most popular (and my favorite) being <a href="http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form">BNF</a>, but for our purposes, that&#8217;s certainly overkill.  Instead, let&#8217;s just do this informally.</p>
<p>First, we&#8217;ll allow all existing Groovy operators and control structures &#8211; there are good reasons to strip those out on occasion, but this isn&#8217;t one of them.  We&#8217;ll cover how to do that at a later date.  What this means is that structures like while (condition) {block} and if (condition) {block} will work just fine.  We&#8217;ll also be able to create methods inline, just as you can with Groovy scripts.  And standard comments (i.e., // and /* */) will also work as expected.</p>
<p>We&#8217;ll need the following commands to create an environment that allows for turtle graphics:</p>
<ul>
<li>Turtle / Movement Commands</li>
<ul>
<li><strong>forward</strong> <em>number </em></li>
<ul>
<li>move the turtle forward by <em>number</em> of steps</li>
</ul>
<li><strong>back</strong> <em>number</em></li>
<ul>
<li>move the turtle backward by <em>number</em> of steps</li>
</ul>
<li><strong>right</strong> <em>number</em></li>
<ul>
<li>turn the turtle number of degrees to the right (clockwise)</li>
</ul>
<li><strong>left</strong> <em>number</em></li>
<ul>
<li>turn the turtle number of degrees to the left (counter clockwise)</li>
</ul>
<li><strong>home</strong></li>
<ul>
<li>return the turtle to the starting position, without drawing any lines</li>
</ul>
</ul>
<li>Pen / Drawing Commands</li>
<ul>
<li><strong>pendown</strong></li>
<ul>
<li>set the pen to draw when the turtle moves</li>
</ul>
<li><strong>penup</strong></li>
<ul>
<li>set the pen to not draw when the turtle moves</li>
</ul>
<li><strong>pencolor</strong> <em>Color</em></li>
<ul>
<li>change the pen color to <em>Color</em></li>
</ul>
</ul>
<li>Animation / Demo Commands</li>
<ul>
<li><strong>show</strong></li>
<ul>
<li>show the turtle icon</li>
</ul>
<li><strong>hide</strong></li>
<ul>
<li>hide the turtle icon</li>
</ul>
<li><strong>speed</strong> <em>number</em></li>
<ul>
<li>change the speed at which the turtle draws, larger is faster</li>
</ul>
</ul>
</ul>
<div>Keywords/methods are in <strong>bold</strong>, parameters are in <em>italics</em>.  Since we need to decide what <em>number</em> means, we can define it as a <code>double</code>, and since Groovy will auto convert <code>int</code> to <code>double</code>, we&#8217;re done with that.  <em>Color</em> is a little more problematic &#8211; ideally, we&#8217;d make it easy to use and understand, and have a whole bunch of code to do that, but since we&#8217;re currently just making a sample program, we&#8217;ll just use <code>javafx.scene.paint.Color</code>.</div>
<div> </div>
<div>If you download the Groovy Turtle Graphics program <a href="https://github.com/netdance/Napili">Napili</a>, you&#8217;ll see that all of these methods are already implemented in <code>org.netdance.napili.Turtle</code>.  I&#8217;ll talk about how to turn those methods into a DSL in the next post.  For now, here&#8217;s a sample program that you can run using these commands, along with the standard stuff that Groovy provides:</div>
<div> </div>
<pre>def circle(size) {
    45.times {
        forward size
        right 8
    }
}

speed 3
penup
forward 250
pendown
pencolor Color.PURPLE

12.times {
    circle 10
    right 30
}

home
hide
</pre>
<p>This program draws a series of interlocking circles, like you&#8217;d get from the child&#8217;s toy <a href="http://en.wikipedia.org/wiki/Spirograph">Spirograph</a>.   We define a method (circle), set the speed a bit higher to make it all draw quickly, move forward without drawing to center the design, set the pen color to purple (PURPLE is one of many predefined values in <span style="font-family:monospace;">javafx.scene.paint.Color</span>), then draw 12 circles, turning 30 degrees after each.  At the end, we park the turtle in the home position and then hide it.  If you&#8217;re unfamiliar with Groovy, <code>Integer.times(Closure)</code> is a method that Groovy places on all values of Integer (and primitives are auto boxed to their class type in Groovy) &#8211; it just executes the closure as many times as the value of the integer &#8211; remember, parenthesis are optional for methods with arguments, so the circle method is really the equivalent of <code>Integer.valueOf(45).times({forward size; right 8;})</code> - I trust you&#8217;ll agree that the format I used is actually easier to read, once you&#8217;re used to it.</p>
<p>See you next time, where I&#8217;ll talk about how to turn the methods on Class Turtle into the DSL above.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/198/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=198&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/10/06/a-turtle-graphics-dsl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>Napili &#8211; a Turtle Graphics program with JavaFX and Groovy</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/10/03/napili-a-turtle-graphics-program-with-javafx-and-groovy/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/10/03/napili-a-turtle-graphics-program-with-javafx-and-groovy/#comments</comments>
		<pubDate>Wed, 03 Oct 2012 19:53:11 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[JavaFX]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=195</guid>
		<description><![CDATA[My very first programming language was BASIC.  But the first time I ever thought I could do this for a living was when I discovered LOGO.  While the language itself didn&#8217;t interest me in particular, I was fascinated by Turtle Graphics. If you&#8217;re unfamiliar with Turtle Graphics, it&#8217;s a pretty simple concept:  while traditional graphics [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=195&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>My very first programming language was <a href="http://en.wikipedia.org/wiki/BASIC">BASIC</a>.  But the first time I ever thought I could do this for a living was when I discovered <a href="http://en.wikipedia.org/wiki/Logo_(programming_language)">LOGO</a>.  While the language itself didn&#8217;t interest me in particular, I was fascinated by <a href="http://en.wikipedia.org/wiki/Turtle_graphics">Turtle Graphics</a>.</p>
<p>If you&#8217;re unfamiliar with Turtle Graphics, it&#8217;s a pretty simple concept:  while traditional graphics paradigms involve an x/y coordinate system, where each pixel is filled in based on it&#8217;s coordinate location, and all functionality is built around coordinates, turtle graphics systems instead work with a two objects:  a drawing surface, whose properties are opaque to the programmer (except possibly it&#8217;s size), and a turtle, which is the object the programmer manipulates.  The Turtle is, in turn, an abstraction &#8211; it has a location, an orientation, and a pen.  The pen, in turn, has attributes such as color, width, and up verses down.  The turtle is usually represented on the screen by either a triangle, a diamond, or a bitmap of a cartoon turtle.</p>
<p>The turtle is controlled via commands, such as <strong>PEN DOWN</strong>, <strong>FORWARD 100</strong>, and <strong>RIGHT 45</strong> (which sets the pen to draw, moves forward by 100 arbitrary units, and turns the turtle 45 degrees clockwise).</p>
<p>This is a great example of a DSL for our purposes, since it&#8217;s a very specific domain (drawing via a turtle), is a very well understood paradigm, and would benefit greatly from the control structures that Groovy gives us.</p>
<p>At the same time that I was thinking about what kinds of programs to use for my examples, I attended the <a href="http://gr8conf.us/index">GR8US</a> conference, and several speakers sang the praises of <a href="http://docs.oracle.com/javafx/">JavaFX</a>, which had just been released as part of the <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">JDK</a>.  So, I thought, why not learn about JavaFX while creating this Groovy Turtle Graphics program?  Scala already has the excellent <a href="http://www.kogics.net/sf:kojo">Kojo</a>, but I couldn&#8217;t find something similar for Groovy, so, why not?</p>
<p>The result is <a href="https://github.com/netdance/Napili">Napili</a>, now available  on GitHub under the Apache License.</p>
<p>Over the next few posts, I&#8217;ll go over how I applied my previous posts on DSLs to the problem of creating a Turtle Graphics DSL.  I&#8217;ll also use this program to cover a few other topics that I have planned, such as program throttling and security.</p>
<p>In the interim, if you&#8217;re interested in a small, simple example of a DSL (or, for that matter, of JavaFX animations), <a href="https://github.com/netdance/Napili">download it and check it out</a>.  </p>
<p>One last note: Napili isn&#8217;t really ready to indoctrinate some new high school kid into the world of Groovy programming.  In particular, it&#8217;s &#8220;editor&#8221; is just a text area, not some spiffy syntax highlighting full featured component, and it&#8217;s error reporting is very, very primitive.  If you think that the world really needs a Groovy turtle graphics programming IDE, please drop me a line and let me know.  Bonus points if you want to help.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/195/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=195&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/10/03/napili-a-turtle-graphics-program-with-javafx-and-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>DSLs &#8211; What we&#8217;ve covered so far&#8230;</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/10/01/dsls-what-weve-covered-so-far/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/10/01/dsls-what-weve-covered-so-far/#comments</comments>
		<pubDate>Tue, 02 Oct 2012 03:33:49 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=192</guid>
		<description><![CDATA[At this point, we&#8217;ve covered many of the basics of creating DSLs in Groovy: What DSLs are, and why you&#8217;d use them A quick introduction to Groovy, part 1 and part 2 Dynamically executing Groovy Programs Creating binding variables (the nouns of your language) Creating new methods (the verbs of your language) Delegating behavior via [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=192&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>At this point, we&#8217;ve covered many of the basics of creating DSLs in Groovy:</p>
<ul>
<li><a href="https://jamesgdriscoll.wordpress.com/2012/03/12/what-is-a-dsl-anyway-why-should-you-care/">What DSLs are</a>, and why you&#8217;d use them</li>
<li>A quick introduction to Groovy, <a href="https://jamesgdriscoll.wordpress.com/2012/03/16/a-quick-introduction-to-the-groovy-language-part-1/">part 1</a> and <a href="https://jamesgdriscoll.wordpress.com/2012/03/17/a-quick-introduction-to-the-groovy-language-part-2/">part 2</a></li>
<li><a href="https://jamesgdriscoll.wordpress.com/2012/03/17/executing-groovy-programs-in-memory/">Dynamically executing Groovy Programs</a></li>
<li><a href="https://jamesgdriscoll.wordpress.com/2012/04/14/groovy-bindings-or-adding-keywords-to-your-dsl/">Creating binding variables</a> (the nouns of your language)</li>
<li><a href="https://jamesgdriscoll.wordpress.com/2012/04/22/adding-default-methods-with-a-groovy-basescript/">Creating new methods</a> (the verbs of your language)</li>
<li>Delegating behavior via <a href="https://jamesgdriscoll.wordpress.com/2012/09/29/method-dispatch-on-groovy-objects/">Method Dispatch</a> and <a href="https://jamesgdriscoll.wordpress.com/2012/09/29/property-dispatch-on-groovy-objects/">Property Dispatch</a></li>
</ul>
<p>With that, we&#8217;re ready to tackle a real example…  Which I&#8217;ll detail in the next post.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/192/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=192&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/10/01/dsls-what-weve-covered-so-far/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>Property Dispatch on Groovy Objects</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/09/29/property-dispatch-on-groovy-objects/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/09/29/property-dispatch-on-groovy-objects/#comments</comments>
		<pubDate>Sat, 29 Sep 2012 20:19:41 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=189</guid>
		<description><![CDATA[In my last post, I covered Method Dispatch on Groovy Objects.  The next topic is similar, Property Dispatch. In Groovy, you can specify properties on objects in the same way that you can specify fields in Java:  With the &#8220;.&#8221; operator.  I.e., if I have an object named &#8220;Test&#8221;, and it has a class variable [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=189&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In my last post, I covered <a href="https://jamesgdriscoll.wordpress.com/2012/09/29/method-dispatch-on-groovy-objects/">Method Dispatch on Groovy Objects</a>.  The next topic is similar, Property Dispatch.</p>
<p>In Groovy, you can specify properties on objects in the same way that you can specify fields in Java:  With the &#8220;.&#8221; operator.  I.e., if I have an object named &#8220;Test&#8221;, and it has a class variable named &#8220;test&#8221;, you can access it with the phrase &#8220;Test.test&#8221; (just like Java).</p>
<p>As I already mentioned in my <a href="https://jamesgdriscoll.wordpress.com/2012/03/16/a-quick-introduction-to-the-groovy-language-part-1/">Introduction to Groovy</a>, Groovy provides automatic creation of accessors and mutators (get and set).    That&#8217;s actually an oversimplification, but we&#8217;ll leave it at that for now.  As a result, consider the following Groovy class:</p>
<pre>class GetSet {
   def firstField = 1
}</pre>
<p>This can be used in the following way, inside a Java class:</p>
<pre>GetSet gs = new GetSet();
System.out.println(gs.getFirstField());
gs.setFirstField("test");
System.out.println(gs.getFirstField());</pre>
<p>That&#8217;s because, under the covers, <code>void setFirstField(Object)</code> and <code>Object getFirstField()</code> are added to the Groovy class.  Note that because the class field is declared as <code>def</code>, the type of these messages is <code>Object</code>.</p>
<p>While that&#8217;s handy in Java, in Groovy, we can do so much more with properties.  You can access them with dot notation:</p>
<pre>def gs = new GetSet()
gs.firstField = 2.5
println gs.firstField</pre>
<p>You can access them with get/setProperty (which is part of <code>GroovyObject</code>, the base object for all objects in Groovy):</p>
<pre>def gs = new GetSet()
gs.setProperty('firstField','test2')
println gs.getProperty('firstField')</pre>
<p>And you can even access a Map of all the properties on the object, and operate on that:</p>
<pre>def gs = new GetSet()
println gs.properties.firstField</pre>
<p>This last example is interesting since it&#8217;s using a few features of Groovy: the <code>properties</code> property is actually a shortcut to the <code>getProperties()</code> method, which returns a <code>Map</code>.  In turn, you can access the values of the map by using the key in dot notation.  So this is actually a shortcut for the following Java code: </p>
<pre>GetSet gs = new GetSet();
System.out.println(gs.getProperties().get("firstField"));</pre>
<p>While all that&#8217;s handy, that&#8217;s still not dispatch.  In order to handle properties dispatch, there are two different methods we can use.  Consider the following code:</p>
<pre>GetSet gs = new GetSet();
gs.newprop = 'new value'
println gs.newprop</pre>
<p><span class="Apple-style-span" style="font-family:monospace;">newprop</span> doesn&#8217;t exist in GetSet &#8211; we want to handle adding it at runtime.  The first method to do so is to override <code>missingProperty(String)</code> and <code>missingProperty(String, Object)</code>.  The first method handles gets of properties that don&#8217;t exist, the second handles sets.  So the following code handles unknown properties seamlessly:</p>
<pre>Map props = [:]
    
def propertyMissing(String name, value) {
    props[name] = value
}
    
def propertyMissing(String name) {
    return props[name]
}</pre>
<p>In Groovy, Maps can be initialized to be empty with<code> [:]</code> and the values in that map can be accessed with the syntax pattern <code>map[key]</code>.  So, in this code, if the property doesn&#8217;t exist, it will be added into an internal Map if you are setting it, and that value will be returned when the property is later used.  If the property is accessed before it&#8217;s set, a null is returned.  Of course, we could check for existence, and throw an exception if we desired to. </p>
<p>This method will only add to the existing properties, however.  If there&#8217;s already a property (a class instance field, for instance) on the class, such as firstField in our example, this code is never touched.</p>
<p>If instead you want to completely override the access to fields, you can instead override <code>getProperty(String)</code>, <code>setProperty(String, Object)</code> and<code> getProperties()</code> for good measure, if desired.  Here&#8217;s an example:</p>
<pre>Map props = [:]
    
void setProperty(String name, value) {
    props[name] = value
}
    
Object getProperty(String name) {
    return props[name]
}
    
Map getProperties() {
    return props
}
</pre>
<p>This code actually does almost the same thing as the previous example, except that now, any instance or class fields are hidden from property access.    Meaning that the following code prints <code>null</code>:</p>
<pre>GetSet gs = new GetSet();
println gs.firstField</pre>
<p>But note that the following code will still print <span class="Apple-style-span" style="font-family:monospace;">1:</span></p>
<pre>GetSet gs = new GetSet();
println gs.@firstField</pre>
<p>This is because we&#8217;re using the &#8220;Java field accessor&#8221; in the second example &#8211; the <code>.@  </code>notation bypasses get/setProperty methods, and directly act on the underlying Java field.</p>
<p>Dispatch is just a short step away from the above code.  Instead of using the internal Map of properties, you could instead route the property lookup anywhere &#8211; an xml file, a database, or any other class or computation.</p>
<p>So, now that we&#8217;ve looked at method and property dispatch, we&#8217;ll run through some ways to use these in a DSL next time.  Until then&#8230;</p>
<p> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/189/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/189/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=189&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/09/29/property-dispatch-on-groovy-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>Method dispatch on Groovy objects</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/09/29/method-dispatch-on-groovy-objects/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/09/29/method-dispatch-on-groovy-objects/#comments</comments>
		<pubDate>Sat, 29 Sep 2012 18:30:04 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=186</guid>
		<description><![CDATA[  As I promised my post about optional parenthesis, today I&#8217;m going to talk about method dispatch in  Groovy &#8211; specifically, dynamically dispatching methods on Groovy objects via the invokeMethod mechanism.  We&#8217;ll tie it into DSL creation in a later post. The key method to know about for method dispatch is GroovyObject.invokeMethod(String name, Object args).  This [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=186&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p> </p>
<p>As I promised my post about <a href="https://jamesgdriscoll.wordpress.com/2012/04/29/using-optional-parenthesis-in-groovy-to-your-advantage/">optional parenthesis</a>, today I&#8217;m going to talk about method dispatch in  Groovy &#8211; specifically, dynamically dispatching methods on Groovy objects via the invokeMethod mechanism.  We&#8217;ll tie it into DSL creation in a later post.</p>
<p>The key method to know about for method dispatch is <a href="http://groovy.codehaus.org/api/groovy/lang/GroovyObject.html">GroovyObject.invokeMethod(String name, Object args)</a>.  This method is located on GroovyObject, and is called when the method you called isn&#8217;t present on the object.</p>
<p>Consider the following Groovy code:</p>
<pre>class Test {
  def <strong>invokeMethod(String name, args)</strong> {
    println "called invokeMethod $name $args"
  }

  def test() {
    println 'in test'
  }
}

def t = new Test()
t.test()
t.bogus('testing!',1,2,3)</pre>
<p> </p>
<p>This code prints out the following text, when run in groovyConsole:</p>
<pre>in test
called invokeMethod bogus [testing!, 1, 2, 3]
</pre>
<p>the first call goes to the test method, as usual.  The second call, instead of resulting in a MissingMethodException, will route through the invokeMethod method.</p>
<p>This can be handy for all kinds of things, but the use I&#8217;ve put it to is as a dispatcher, routing calls to an underlying class or set of classes &#8211; here&#8217;s an example:</p>
<p> </p>
<pre>class One {
  static def test1() {
    println 'in test1'
  }
}

class Test {
  def invokeMethod(String name, args) {
    if (<strong>One.metaClass.respondsTo(One, name, *args)</strong>) {
      return <strong>One."$name"(*args)</strong>
    }
  }
}

def t = new Test()
t.test1()</pre>
<p>This prints out </p>
<pre>in test1</pre>
<p>Now, this example is flagrantly using a few tricks in Groovy, so let me mention how they work…  (Feel free to skip this paragraph if you&#8217;re content with this being a magic incantation.)   The first bolded line, with the respondsTo method, will retrieve the metaClass of the One class, which acts in a similar way to the Class class, but allows additional capabilities.  The respondsTo method of MetaClass takes, as it&#8217;s first argument, the actual object (or class, for static methods) that you&#8217;re checking, the name of the method, and then the arguments.  The asterisk in front of the &#8220;*args&#8221; argument is called the &#8220;spread operator&#8221;, and will derefrerence the array of args to instead be a list of arguments placed at the end of the method call.  The second bolded line is using the String substitution capability of Groovy&#8217;s double quoted Strings (called GStrings) to dynamically execute the method called name, again passed the arguments with the spread operator.  An additional wrinkle is that respondsTo actually  returns a ArrayList &#8211; which is treated as false by Groovy if empty, and true if not.  Now, you <em>could</em> do all this in Java, via reflection and other code, but the pain of doing so really makes this something you should probably do in Groovy.</p>
<p>There&#8217;s one other case we should probably cover &#8211; if your class implements the marker interface GroovyInterceptable, it won&#8217;t just intercept methods it can&#8217;t find &#8211; it will intercept <strong>all </strong>method calls on the class, including methods that are actually there.  That unfortunately means that we can&#8217;t directly call the method from within the invokeMethod though &#8211; instead, you must use the metaClass to invoke the method, getting around that interception.  Here&#8217;s how:</p>
<pre>class One {
  static def test() {
    println 'in One.test'
  }
}

class Test implements <strong>GroovyInterceptable</strong> {
  def firstTime = true
  def invokeMethod(String name, args) {
    if (firstTime) {
      firstTime = false
      return One."$name"(*args)
    }
    return <strong>metaClass.getMetaMethod(name,args).invoke(this,args)</strong>
  }
  def test() {
    println 'in Test.test'
  }
}

def t = new Test()
t.test()
t.test()</pre>
<p> </p>
<p>This prints out:</p>
<pre>in One.test
in Test.test</pre>
<p> </p>
<p>We&#8217;ll leave the explanation of how all this works for another time &#8211; the MetaClass is used pretty heavily in all kinds of Metaprogramming in Groovy, and we&#8217;ll cover it pretty extensively as we go on &#8211; but it&#8217;s use should be obvious from context.  Note that unlike our other use of args, we do <em>not</em> need to use the spread operator.  But keep the MetaClass in mind, because when it comes to adding methods dynamically at runtime, it&#8217;s the way to go.</p>
<p>Next up, we&#8217;ll talk about the related topic of Property Dispatch.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/186/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=186&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/09/29/method-dispatch-on-groovy-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>Word order and Groovy Parsing</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/09/15/word-order-and-groovy-parsing/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/09/15/word-order-and-groovy-parsing/#comments</comments>
		<pubDate>Sat, 15 Sep 2012 19:52:27 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=183</guid>
		<description><![CDATA[  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 [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=183&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p> </p>
<p>In my previous post on <a href="https://jamesgdriscoll.wordpress.com/2012/04/29/using-optional-parenthesis-in-groovy-to-your-advantage/">Optional Parenthesis in Groovy</a>, 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.</p>
<p>Consider this code:</p>
<p><code>one two three four five</code></p>
<p>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&#8217;t available to the compiler, so Groovy has to guess.  Here&#8217;s how to figure out what Groovy will do:</p>
<p>Fire up groovyConsole from a command line which has the GDK in it&#8217;s PATH.</p>
<p>Type in the line above.</p>
<p>From the menus, select <em>Script </em>-&gt;<em> Inspect AST</em></p>
<p>In the lower pane of the frame that pops up, you&#8217;ll see what Java code is going to be generated by the Groovy parser.  Take special note of the run() method &#8211; that&#8217;s the part that actually contains the code we typed in, turned into the code below:</p>
<pre>public java.lang.Object run() {    
    return this.one(two).three(four).five
}</pre>
<p>This really tells us all we need to know about how Groovy&#8217;s going to parse a String of words &#8211; it&#8217;s going to always follow the pattern:</p>
<p>method(param).method(param).variable</p>
<p>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.</p>
<p>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.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/183/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=183&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/09/15/word-order-and-groovy-parsing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>Laforge on DSLs in Groovy</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/05/05/laforge-on-dsls-in-groovy/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/05/05/laforge-on-dsls-in-groovy/#comments</comments>
		<pubDate>Sat, 05 May 2012 20:22:36 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=180</guid>
		<description><![CDATA[Groovy expert Guillaume Laforge has posted on DSLs in Groovy, using lots of neat Groovy tricks to make the language sing. If you&#8217;re curious, check it out. I&#8217;ll probably be covering some of his more interesting tricks later in these pages. (At the rate I&#8217;m going, much, much later.)<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=180&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Groovy expert <a href="http://glaforge.appspot.com/">Guillaume Laforge</a> has posted on DSLs in Groovy, using lots of neat Groovy tricks to make the language sing. If you&#8217;re curious, <a href="http://www.slideshare.net/mobile/glaforge/going-to-mars-with-groovy-domainspecific-languages">check it out</a>. I&#8217;ll probably be covering some of his more interesting tricks later in these pages. (At the rate I&#8217;m going, much, much later.)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/180/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=180&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/05/05/laforge-on-dsls-in-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
		<item>
		<title>Using optional parenthesis in Groovy to your advantage</title>
		<link>https://jamesgdriscoll.wordpress.com/2012/04/29/using-optional-parenthesis-in-groovy-to-your-advantage/</link>
		<comments>https://jamesgdriscoll.wordpress.com/2012/04/29/using-optional-parenthesis-in-groovy-to-your-advantage/#comments</comments>
		<pubDate>Sun, 29 Apr 2012 21:48:45 +0000</pubDate>
		<dc:creator>jamesgdriscoll</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">https://jamesgdriscoll.wordpress.com/?p=171</guid>
		<description><![CDATA[Now that we&#8217;ve discussed adding default methods to your scripts with a BaseScript, it&#8217;s time to talk about one way to hide the fact that you&#8217;re calling a method:   Groovy allows you to omit parenthesis in cases where there is a parameter, and there is no ambiguity in use. We can use this optional [...]<img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=171&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Now that we&#8217;ve discussed <a href="https://jamesgdriscoll.wordpress.com/2012/04/22/adding-default-methods-with-a-groovy-basescript/">adding default methods to your scripts</a> with a BaseScript, it&#8217;s time to talk about one way to hide the fact that you&#8217;re calling a method:   Groovy allows you to omit parenthesis in cases where there is a parameter, and there is no ambiguity in use.</p>
<p>We can use this optional parens feature of Groovy to create more natural looking DSLs, and with judicious use of method chaining, we can create a simple grammar with very little code.  Let&#8217;s say that I want to create a simple DSL that moves a marker around in a confined space, and that the language should look similar to Logo, with a series of commands all in a line.  Since I don&#8217;t enjoy trigonometry,  I&#8217;ll forgo the usual two vector (x,y) space of Logo for a simpler single line.  That means than instead of needing to allow for commands like &#8220;forward 10 right 90 forward 6&#8243;, I can just use two verbs &#8211; &#8220;forward&#8221; and &#8220;back&#8221;.  We&#8217;ll add one more, &#8220;traveled&#8221;, to report total progress.  So, to define our DSL in a simple manner, I want to accept commands like &#8220;forward 10 forward 6 back 3 traveled&#8221;.</p>
<p>So, we can start by creating a simple BaseScript with the three verbs (let&#8217;s do it this time in Groovy, I&#8217;m feeling lazy):</p>
<p> </p>
<pre>abstract class BaseScript extends Script {

  <strong>int distance = 0;</strong>
    
  def <strong>forward(int i)</strong> {
    distance += i
    println "moved forward "+i
    <strong>return this</strong>
  }
    
  def <strong>back(int i)</strong> {
    distance -= i;
    println "moved back "+i
    <strong>return this</strong>
  }
    
  def <strong>traveled()</strong> {
    println "total distance traveled " + distance
    <strong>return this</strong>
  }

}
</pre>
<p> </p>
<p>The script is storing the distance as an instance variable, and then all the methods are acting on that variable in some way.  Also, note that each method returns the current script object, enabling method chaining.</p>
<p>Once this is set up, we can use the following code to execute a script:</p>
<pre>  CompilerConfiguration config = new CompilerConfiguration();
  config.setScriptBaseClass("groovybasescriptlogo.BaseScript");
  GroovyShell shell = new GroovyShell(config);
  Script script = shell.parse("<strong>forward 10 back 3 forward 5 traveled()</strong>");
  script.run();
</pre>
<p> </p>
<p>The output when we run this is as you&#8217;d expect:</p>
<pre>moved forward 10
moved back 3
moved forward 5
total distance traveled 12
</pre>
<p> </p>
<p>But note there&#8217;s a catch here:  because traveled is a method without a parameter, there still needs to be a set of parenthesis at the end.  The reason why is also a clue as to how we can fix it.  Without the parenthesis, the traveled keyword will be interpreted as a binding variable instead of a method.  Since <a href="https://jamesgdriscoll.wordpress.com/2012/04/14/groovy-bindings-or-adding-keywords-to-your-dsl/">we&#8217;ve already covered how to handle Binding variables</a>, we can change the code by using a Binding class.  First, eliminate the first bolded line in the BaseScript &#8211; that changes the <em>distance</em> variable from an instance variable on the Script class to a Binding variable.  You can also remove the traveled() method from the BaseScript as well, or leave it in there, to cover the case of using a parenthesis.  Then create a Binding class like so:</p>
<p> </p>
<pre>public class SimpleBinding extends Binding {
    
  <strong>int distance = 0</strong>;
  Script script;
    
  public SimpleBinding(Script script) {
    super();
    this.script = script;
  }

  public Object getVariable(String name) {
    if (<strong>"distance".equals(name)</strong>) {
      <strong>return distance</strong>;
    }
    if (<strong>"traveled".equals(name)</strong>) {
      System.out.println("total distance traveled " + distance);
      <strong>return script</strong>;
    }
    return super.getVariable(name);
    }
        
  public void setVariable(String name, Object value) {
    if (<strong>"distance".equals(name)</strong>) {
      <strong>distance = (Integer)value</strong>;
      return;
    }
    super.setVariable(name, value);
  }
    
}</pre>
<p> </p>
<p>So, the distance variable moves from the BaseScript to the Binding.  In the setVariable, add the ability to set the distance variable.  That covers the usage in the BaseScript.  We&#8217;ve also moved code around <em>traveled</em> to the Binding as well:  Now, when <em>traveled</em> is used without a parenthesis, it will go to the binding, print out the message, and still return the Script object (which is passed into the Binding at creation).  To use this code, just modify the calling code like so:</p>
<p> </p>
<pre>  CompilerConfiguration config = new CompilerConfiguration();
  config.setScriptBaseClass("groovybasescriptlogo.BaseScript");
  GroovyShell shell = new GroovyShell(config);
  Script script = shell.parse("<strong>forward 10 back 3 forward 5 traveled</strong>");
  <strong>script.setBinding(new SimpleBinding(script))</strong>;
  script.run();
</pre>
<p> </p>
<p>The output remains the same.  Doing this now eliminates the need for the trailing parenthesis on the <em>traveled</em> keyword.  That concludes this topic &#8211; feel free to ask any questions, below &#8211; I know this example is a little more involved than previous ones, but the concepts are still pretty simple, even if there&#8217;s more code on the page.  The next posting will cover a different way to handle adding verbs dynamically, via the invokeMethod mechanism.</p>
<p> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jamesgdriscoll.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jamesgdriscoll.wordpress.com/171/" /></a> <img alt="" border="0" src="https://stats.wordpress.com/b.gif?host=jamesgdriscoll.wordpress.com&#038;blog=9405854&#038;post=171&#038;subd=jamesgdriscoll&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://jamesgdriscoll.wordpress.com/2012/04/29/using-optional-parenthesis-in-groovy-to-your-advantage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://2.gravatar.com/avatar/5d9afbb6c607e6444dcad007a6180ced?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jamesgdriscoll</media:title>
		</media:content>
	</item>
	</channel>
</rss>
