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

7.2. An Arithmetic Grammar

To observe four levels of precedence, an arithmetic grammar needs to have four subparsers. Each of these subparsers handles operators of a common precedence, delegating interpretation of other operators to other subparsers. You can use the words expression, term, factor, and phrase to denote the four subparsers.

To begin, you can define expression as observing the lowest level of precedence.

expression = expression '+' term | 
             expression '–' term |
             term;

This rule suffers from left recursion, but it properly recognizes all pluses and minuses to the left of a term before adding or subtracting the term. To remove the left recursion, it helps to abbreviate the rule

e = e '+' t | e '-' t | t; 

and look at what an e might ...

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