O'Reilly logo

Building Parsers with Java™ by Steven John Metsker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.6. Translating a Grammar to Code

You can write the code of a parser directly from its grammar. You apply each principle of grammar translation in turn until the grammar becomes a set of Java statements that define a parser. The following principles apply:

  • Treat quoted strings as CaselessLiteral objects.
  • Create Sequence objects for sequences.
  • Create Alternation objects for alternations.
  • Translate Terminal references to objects.
  • Create a subparser for each rule.
  • Declare each subparser, or arrange subparsers as methods.
  • Add a start() method.

3.6.1. Translate Quoted Strings

Treat each quoted word, such as "pick", as a CaselessLiteral. For example, translate

pickCommand  = "pick" "carrier" "from" location; 

to

 pickCommand = new CaselessLiteral("pick") ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required