7.3. Arithmetic Assemblers

An arithmetic parser has no need of a target because you can accumulate a result of recognizing an assembly by working on the assembly's stack. The key design idea, then, is to produce the right number on an assembly's stack.

First, when the parser sees a number with Num, the Num terminal places a token on the stack. The arithmetic parser must replace this token with its Double value, and to perform this task it needs an assembler. The parser also needs an assembler for each of the five operators. For example, after seeing ('+' term), the parser must perform an addition. To see where assemblers plug in to subparsers, it helps to write each operator on a separate line, as follows:

 expression = term (plusTerm | minusTerm)*; ...

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.