a9601b926b6c72938525ff7cce6dbbcca0923559
[sbp.git] / src / edu / berkeley / sbp / misc / Demo.java
1 package edu.berkeley.sbp.misc;
2
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.*;
9 import java.util.*;
10 import java.io.*;
11
12 public class Demo {
13
14     /** our grammar class */
15     public static class Math {
16
17         public static @bind.as("(") Expr parenthesis(Expr e) { return e; }
18         public static class Expr implements Reflection.Show { }
19
20         public static @bind.as("Expr") class Numeric extends Expr {
21             public @bind.arg String numeric;
22         }
23
24         public static class BinOp extends Expr {
25             public @bind.arg Expr left;
26             public @bind.arg Expr right;
27         }
28
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 { }
33     }
34
35
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 {
38
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);
44
45         System.out.println("about to parse: \""+s[1]+"\"");
46         Tree tree = mathParser.parse(new CharInput(new StringReader(s[1]))).expand1();
47
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.
52
53         System.out.println("done!");
54         System.out.println(Reflection.show(e));
55     }
56
57 }