1 package edu.berkeley.sbp.misc;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import edu.berkeley.sbp.misc.*;
6 import edu.berkeley.sbp.meta.*;
7 import edu.berkeley.sbp.bind.*;
8 import edu.berkeley.sbp.util.*;
14 /** our grammar class */
15 public static class Math {
17 public static @bind.as("(") Expr parenthesis(Expr e) { return e; }
18 public static class Expr implements Reflection.Show { }
20 public static @bind.as("Expr") class Numeric extends Expr {
21 public @bind.arg String numeric;
24 public static class BinOp extends Expr {
25 public @bind.arg Expr left;
26 public @bind.arg Expr right;
29 public static @bind.as("*") class Multiply extends BinOp { }
30 public static @bind.as("/") class Divide extends BinOp { }
31 public static @bind.as("+") class Add extends BinOp { }
32 public static @bind.as("-") class Subtract extends BinOp { }
36 // invoke "java -jar edu.berkeley.sbp.jar edu.berkeley.sbp.misc.Demo tests/demo.g <expr>"
37 public static void main(String[] s) throws Exception {
39 Parser metaGrammarParser = new CharParser(MetaGrammar.newInstance());
40 Tree<String> parsedGrammar = metaGrammarParser.parse(new CharInput(new FileInputStream(s[0]))).expand1();
41 Grammar.Bindings gbr = new AnnotationGrammarBindings(Math.class);
42 Union mathGrammar = Grammar.create(parsedGrammar, "Expr", gbr);
43 Parser mathParser = new CharParser(mathGrammar);
45 System.out.println("about to parse: \""+s[1]+"\"");
46 Tree tree = mathParser.parse(new CharInput(new StringReader(s[1]))).expand1();
48 // below is ugly voodoo which will go away very soon. ignore it.
49 TreeFunctor tf = (TreeFunctor)tree.head();
50 Math.Expr e = (Math.Expr)tf.invoke(tree);
51 // above is ugly voodoo which will go away very soon. ignore it.
53 System.out.println("done!");
54 System.out.println(Reflection.show(e));