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 { }
37 // invoke "java -jar edu.berkeley.sbp.jar edu.berkeley.sbp.misc.Demo tests/demo.g <expr>"
38 public static void main(String[] s) throws Exception {
40 Parser metaGrammarParser = new CharParser(MetaGrammar.make());
41 Tree<String> parsedGrammar = metaGrammarParser.parse(new CharInput(new FileInputStream(s[0]))).expand1();
42 GrammarBindingResolver gbr = new AnnotationGrammarBindingResolver(Math.class);
43 Union mathGrammar = MetaGrammar.make(parsedGrammar, "Expr", gbr);
44 Parser mathParser = new CharParser(mathGrammar);
46 System.out.println("about to parse: \""+s[1]+"\"");
47 Tree tree = mathParser.parse(new CharInput(new StringReader(s[1]))).expand1();
49 // below is ugly voodoo which will go away very soon. ignore it.
50 Tree.TreeFunctor tf = (Tree.TreeFunctor)tree.head();
51 Math.Expr e = (Math.Expr)tf.invoke(tree.children());
52 // above is ugly voodoo which will go away very soon. ignore it.
54 System.out.println("done!");
55 System.out.println(Reflection.show(e));