5.6. Translating the Coffee Grammar to Code

You can follow the rules of Section 3.6 “Translating a Grammar to Code,” and code subparsers as methods on a parser class. Figure 5.4 shows CoffeeParser.

Figure 5.4. The CoffeeParser class. This class organizes its subparsers as individual methods.

Most of the methods of the CoffeeParser class return a parser that recognizes one aspect of the coffee grammar. For example, the price() method returns a parser for the rule

price = Num; 

The code for CoffeeParser.price() plugs in the price assembler:

 /* * Return a parser that will recognize the sequence: * * price = Num; * * Use a PriceAssembler to update ...

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.