// Author: Gabriel J. Ferrer // This program is in the public domain. // BoolExprParser is a demo for the Squirrel parser // It serves as a parser for BoolExprEval.java import java.io.IOException; import squirrel.*; public class BoolExprParser implements HasGrammar { private Grammar g; public BoolExprParser() {this(true);} public BoolExprParser(boolean left) { g = new Grammar(); g.importFrom(new Standard()); g.addRule("", "", ""); g.addRule("", "set "); if (left) { // Left-associative, left-recursive g.addRule("", " or ", ""); g.addRule("", " and ", ""); } else { // Right-associative, right-recursive g.addRule("", " or ", ""); g.addRule("", " and ", ""); } g.addRule("", "not ", ""); g.addRule("","( [] [] )", ""); g.addToken("", " []"); } public Tree parse(String input) { Parser p = new Parser(getGrammar(), input); return p.bestTree(); } public Grammar getGrammar() {return g;} public static void main(String[] args) { BoolExprParser bep = new BoolExprParser(args[0].equals("left")); parse(bep, "x or y"); parse(bep, "x or y and a and (true or c)"); parse(bep, "x or "); parse(bep, "(x or y"); parse(bep, "set x true"); } public static void parse(BoolExprParser bep, String s) { System.out.println(bep.parse(s).textTree()); } }