Courses/CS 460/Fall 2006/Java Expression Parser

From CSWiki

Jump to: navigation, search

The Java Expression Parser is an open source parser. You can download it, extract the jar file, and use it to parse expressions. (After unzipping it, you will find the jar file in the "dist" directory.)

JEP support a fairly simply grammar with a limited set of operators, but it will probably do for our purposes.

The following code illustrates parsing a simple expression (which can serve as a constraint) and traversing its parse tree.

The task will be to translate expressions into constraints.


import org.nfunk.jep.JEP;
import org.nfunk.jep.Node;


public class JEPTest {

  public static void main(String[] args) {
    JEP jep = new JEP();
    jep.setAllowUndeclared(true);
    jep.parseExpression("x + y == z");
    Node node = jep.getTopNode();
    traverseTree("", node);
  }

  private static void traverseTree(String indent, Node node) {
    System.out.println(indent + node);
    for (int i = 0; i < node.jjtGetNumChildren(); i++) {
      traverseTree(indent + "  ", node.jjtGetChild(i));
    }
  }

}

The output is as follows.

Function "=="
  Function "+"
    Variable: "x"
    Variable: "y"
  Variable: "z"


[edit] Other parsers