// 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("<command>", "<setter>", "<expr>");
        g.addRule("<setter>", "set <sp> <var> <sp> <expr>");
        
        if (left) {
            // Left-associative, left-recursive
            g.addRule("<expr>", "<expr> <sp> or <sp> <andExpr>", "<andExpr>");
            g.addRule("<andExpr>", "<andExpr> <sp> and <sp> <notExpr>", "<notExpr>");
        } else {
            // Right-associative, right-recursive
            g.addRule("<expr>", "<andExpr> <sp> or <sp> <expr>", "<andExpr>");
            g.addRule("<andExpr>", "<notExpr> <sp> and <sp> <andExpr>", "<notExpr>");
        }
        g.addRule("<notExpr>", "not <sp> <value>", "<value>");
        g.addRule("<value>","( [<sp>] <expr> [<sp>] )", "<var>");
        g.addToken("<var>", "<alpha> [<var>]");
    }
    
    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());
    }
}
