A Skeleton Command Interpreter in Ragel for Ruby

Synopsis: Do you need to write a command interpreter to accept input from a user or even an automated protocol? Commands must be parsed and an action taken when the command is recognized. An error action or message must be produced when a bad command is given. The following is a Ragel definition I developed as a common starting point for a command interpreter. The target in this case is generated in Ruby, but could easily be adapted for C or Java targets. The code demonstrates how to interpret three fictitious commands and catch syntactically incorrect inputs as well. It demonstrates Ragel error handling actions that apply to command interpretation. The Ragel code is liberally commented.

In this example command interpreter grammar there are 3 commands: "Bark", "Shout", "Grunt". Each command takes a numeric parameter up to 5 digits long.

When a specific command is recognized, a "found" action is called based on the type of command recognized. This “found” action is where you would perform some task based on the command that was recognized.

When a command is syntactically incorrect, an error action is called. The command error handler can be filled in to specifically deal with command errors for your application.

Finally, this code also demonstrates the start and end events that can be captured when a command is being parsed - start and end actions are fired at the appropriate times so you can fill in those handlers to do something special when command parsing starts or finishes.

To build the Ragel code and generate the state diagram, you can use this Bash script:
To run the resulting parser (Ragel will generate testcmd.rb):

expected output from running the generated Ruby is


The Ragel code for a simple command interpreter with error handling:

Landon Cox
www.ESawdust.com

Full list of Ragel Recipes
asdfasdf