
      BNF Grammar for the Language of Infix Arithmetic Expressions


   Expr ::= Expr '+' Term    // left recursion means left associative
          | Expr '-' Term
          | Term

   Term ::= Term '*' Signed  // left recursion means left associative
          | Term '/' Signed
          | Signed

 Signed ::= '-' Factor
          | Factor

 Factor ::= Base '^' Signed  // right recursion (through Signed) means right associative
          | Base

   Base ::= '(' Expr ')'     // parenthesized expressions,
          | 'sqrt' Base      // square roots, and
          | Number           // numbers, have the highest precedence

 Number ::= any valid Java double


There are five binary operators, +, -, *, /, ^, and two unary operators, - and sqrt. The binary operators +, -, *, and / are left associative. The binary operator ^ is right associative. The sqrt operator has highest precedence, followed by ^, followed by the unary -, followed by the multiplicative operators * and /, and, finally, + and - have the lowest precedence.


Because of the left recursion in the Exp and Term productions, the above grammar cannot be used for a recursive descent parser. We need to rewrite the grammar and "factor out" the left recursion. The rewritten EBNF grammar below can be used as the basis for a recursive descent parser.


   Expr ::= Term ( [ '+' | '-' ] Term )*

   Term ::= Signed ( [ '*' | '/' ] Signed )*

 Signed ::= [ '-' ] Factor

 Factor ::= Base [ '^' Signed ]

   Base ::= '(' Expr ')'
          | 'sqrt' Base
          | Number

 Number ::= any valid Java double