7.4. An Arithmetic Grammar Parser

You can create an arithmetic parser by translating the arithmetic grammar into a parser class and plugging in the assemblers. Section 3.6, “Translating a Grammar to Code,” gives a set of rules for creating a parser from a grammar. The only remaining problem is to prevent looping in the subparser definitions.

Section 6.5, “Eliminating Parser Class Loops,” explains how to address loops in a grammar. The arithmetic grammar has two cycles.

 expression = term (plusTerm | minusTerm)*; term = factor (timesFactor | divideFactor)*; plusTerm = '+' term; minusTerm = '-' term; factor = phrase expFactor | phrase; timesFactor = '*' factor; divideFactor = '/' factor; expFactor = '^' factor; phrase = '(' expression ')' | Num; ...

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.