1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
3 package edu.berkeley.sbp.misc;
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.*;
16 /** our grammar class */
17 public static class Math {
19 public static @bind.as("(") Expr parenthesis(Expr e) { return e; }
20 public static class Expr implements Reflection.Show { }
22 public static @bind.as("Expr") class Numeric extends Expr {
23 public @bind.arg String numeric;
26 public static class BinOp extends Expr {
27 public @bind.arg Expr left;
28 public @bind.arg Expr right;
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 { }
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 {
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);
47 System.out.println("about to parse: \""+s[1]+"\"");
48 Tree tree = mathParser.parse(new CharInput(new StringReader(s[1]))).expand1();
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.
55 System.out.println("done!");
56 System.out.println(Reflection.show(e));