CMSI 488/588
Homework #2
Partial Answers
  1. A grammar for Polynomials, amenable for LL(1) parsing. Making it LL(1) requires putting choice points after the coefficient.
    Microsyntax:
      N -> \p{Nd}+
    
    Macrosyntax:
      P -> "-"? T ([+-] T)*
      T -> N ("x" ("^" N)?)? | "x" ("^" N)?
    
  2. A Polynomial Evaluator
    // Evaluator.jj
    //
    // This spec generates a (threadsafe) utility parser class called 
    // Evaluator.java that contains a static method that takes in a 
    // string representing a polynomial p and a value x and returns p(x).
    
    PARSER_BEGIN(Evaluator)
    import java.io.*;
    
    public class Evaluator {
    
        /**
         * Returns the value of the polynomial at the given value.
         */
        public static double eval(String p, double x) throws ParseException {
            return new Evaluator(new StringReader(p)).parsePolynomial(x);
        }
    
        /**
         * Writes the value of args[0] on the value args[1] to standard output.
         */
        public static void main(String[] args) throws ParseException {
            System.out.println(eval(args[0], Double.parseDouble(args[1])));
        }
    }
    PARSER_END(Evaluator)
    
    // P -> "-"? T ( ("+"|"-") T )*
    // T -> INTLIT? "x" ("^" INTLIT)?  |  INTLIT
    
    SKIP: {" " | "\t" | "\n" | "\r"}
    TOKEN: {"+" | "-" | "^" | "x" | <INTLIT: (["0"-"9"])+>}
    
    double parsePolynomial(double x):
      {double result = 0.0; int multiplier = 1; double termValue;}
    {
      ["-" {multiplier = -1;}] result=parseTerm(x) {result *= multiplier;}
      (
        ("+" {multiplier = 1;} | "-" {multiplier = -1;})
        termValue=parseTerm(x)
        {result += multiplier * termValue;}
      )*
      <EOF>
      {return result;}
    }
    
    double parseTerm(double x):
        {int coefficient = 1; int exponent = 1; Token c, e;}
    {
        LOOKAHEAD(2)
        [c=<INTLIT> {coefficient = Integer.parseInt(c.image);}]
        "x"
        ["^" e=<INTLIT> {exponent = Integer.parseInt(e.image);}]
        {return coefficient * Math.pow(x, exponent);}
    |
        c=<INTLIT> {return Integer.parseInt(c.image);}
    }
    
  3. Unit test for the Polynomial Evaluator