83154727202d25cff8fc6ddacfc7550f5bf0c1ff
[sbp.git] / src / edu / berkeley / sbp / misc / Demo.java
1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
2
3 package edu.berkeley.sbp.misc;
4
5 import edu.berkeley.sbp.*;
6 import edu.berkeley.sbp.chr.*;
7 import edu.berkeley.sbp.misc.*;
8 import edu.berkeley.sbp.meta.*;
9 import edu.berkeley.sbp.bind.*;
10 import edu.berkeley.sbp.util.*;
11 import java.util.*;
12 import java.io.*;
13
14 public class Demo {
15
16     /** our grammar class */
17     public static class Math {
18
19         public static @bind.as("(") Expr parenthesis(Expr e) { return e; }
20         public static class Expr implements Reflection.Show { }
21
22         public static @bind.as("Expr") class Numeric extends Expr {
23             public @bind.arg String numeric;
24         }
25
26         public static class BinOp extends Expr {
27             public @bind.arg Expr left;
28             public @bind.arg Expr right;
29         }
30
31         public static @bind.as("*") class Multiply extends BinOp { }
32         public static @bind.as("/") class Divide   extends BinOp { }
33         public static @bind.as("+") class Add      extends BinOp { }
34         public static @bind.as("-") class Subtract extends BinOp { }
35     }
36
37
38     // invoke "java -jar edu.berkeley.sbp.jar edu.berkeley.sbp.misc.Demo tests/demo.g <expr>"
39     public static void main(String[] s) throws Exception {
40
41         Parser metaGrammarParser   = new CharParser(MetaGrammar.newInstance());
42         Tree<String> parsedGrammar = metaGrammarParser.parse(new CharInput(new FileInputStream(s[0]))).expand1();
43         Grammar.Bindings gbr       = new AnnotationGrammarBindings(Math.class);
44         Union   mathGrammar        = Grammar.create(parsedGrammar, "Expr", gbr);
45         Parser  mathParser         = new CharParser(mathGrammar);
46
47         System.out.println("about to parse: \""+s[1]+"\"");
48         Tree tree = mathParser.parse(new CharInput(new StringReader(s[1]))).expand1();
49
50         // below is ugly voodoo which will go away very soon.  ignore it.
51         TreeFunctor tf = (TreeFunctor)tree.head();
52         Math.Expr e = (Math.Expr)tf.invoke(tree);
53         // above is ugly voodoo which will go away very soon.  ignore it.
54
55         System.out.println("done!");
56         System.out.println(Reflection.show(e));
57     }
58
59 }