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") ...

Get Building Parsers with Java™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.