checkpoint
[sbp.git] / src / edu / berkeley / sbp / misc / Demo.java
index 845b1cb..6384939 100644 (file)
@@ -8,46 +8,22 @@ import java.lang.reflect.*;
 import java.io.*;
 
 public class Demo {
+    
+    public static boolean harsh = false;
+
     public static void main(String[] s) throws Exception {
+
+        ReflectiveMeta m = new ReflectiveMeta();
         Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
-        
-        ReflectiveMeta m =
-            new ReflectiveMeta(MG.class,
-                               new Class[] {
-                                   MG.Grammar.class,
-                                   MG.NonTerminal.class,
-                                   MG.AnonUn.class,
-                                   MG.Range.class,
-                                   MG.El.class,
-                                   MG.Seq.class,
-                                   MG.NonTerminalReference.class,
-                                   MG.StringLiteral.class,
-                                   MG.Tree.class,
-                                   MG.CharClass.class
-                               });
         MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
         MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
-        Union meta = mgf.get("s").build(bc);
 
-        System.err.println("parsing " + s[1]);
+        Union meta = mgf.get("s").build(bc);
         Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
-        System.out.println("tree:\n" + t.toPrettyString());
 
-        Reducer red = (Reducer)t.head();
-        MG.Grammar g = (MG.Grammar)red.reduce(t);
-        System.out.println(g);
-        
-        Context cx = new Context(g,m);
-        Element u = null;
-        for(MG.NonTerminal nt : g.nonterminals) {
-            Union el = (Union)cx.get(nt.name);
-            StringBuffer st = new StringBuffer();
-            el.toString(st);
-            System.err.println(st);
-            if (nt.name.equals("s")) u = el;
-        }
-        System.err.println();
+        Union u = Demo.make(t, "s");
 
+        System.err.println();
         System.err.println("== parsing with parsed grammar =================================================================================");
         t = new CharParser((Union)u).parse(new FileInputStream(s[1])).expand1();
         System.out.println(t.toPrettyString());
@@ -57,9 +33,33 @@ public class Demo {
         System.out.println(t.toPrettyString());
     }
 
+    public static class ReflectiveMetaPlain extends ReflectiveMeta {
+        public Object repeatTag() { return null; }
+        public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
+            return null; }
+        public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
+            return Sequence.rewritingSequence(tag, els, labels, drops);
+        }
+    }
+
     public static class ReflectiveMeta extends MetaGrammar.Meta {
         private final Class _cl;
         private final Class[] _inner;
+        public ReflectiveMeta() {
+            this(MG.class,
+                 new Class[] {
+                     MG.Grammar.class,
+                     MG.NonTerminal.class,
+                     MG.AnonUn.class,
+                     MG.Range.class,
+                     MG.El.class,
+                     MG.Seq.class,
+                     MG.NonTerminalReference.class,
+                     MG.StringLiteral.class,
+                     MG.XTree.class,
+                     MG.CharClass.class
+                 });
+        }
         public ReflectiveMeta(Class c, Class[] inner) {
             this._cl = c;
             this._inner = inner;
@@ -90,7 +90,7 @@ public class Demo {
         }
         public Object repeatTag() {
             return new Reducer() {
-                    public String toString() { return "[**]"; }
+                    public String toString() { return ""; }
                     public Object reduce(Tree t) {
                         Object[] ret = new Object[t.numChildren()];
                         for(int i=0; i<t.numChildren(); i++) {
@@ -108,7 +108,7 @@ public class Demo {
                     }
                 };
         }
-        public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
+        public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
             Production p = new Production(tag, nonTerminalName, els, labels, drops);
             for(Method m : _cl.getMethods())
                 if (new TargetMethod(m).isCompatible(p))
@@ -120,20 +120,21 @@ public class Demo {
             for(Class c : _inner)
                 if (new TargetClass(c).isCompatible(p))
                     return new TargetClass(c).makeSequence(p);
-            throw new RuntimeException("could not find a Java method/class/ctor matching tag \""+tag+"\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments");
+            return null;
+        }
+        public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
+            Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
+            if (ret != null) return ret;
+            String message = "could not find a Java method/class/ctor matching tag \""+tag+
+                "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
+            if (harsh) {
+                throw new RuntimeException(message);
+            } else {
+                System.err.println(message);
+                return Sequence.rewritingSequence(tag, els, labels, drops);
+            }
         }
     }
-    /*
-    public static Object makeFlattener(final Method m, final Element[] els, final Object[] labels, final boolean[] drops) {
-        return new Reducer() {
-                public Object reduce(Tree t) {
-                    Object[] o = new Object[m.getParameterTypes()];
-                    int j = 0;
-                    for(int i=0; i<els.length; i++)
-                }
-            };
-    }
-    */
 
     
     /**
@@ -144,6 +145,8 @@ public class Demo {
      */ 
     @Retention(RetentionPolicy.RUNTIME) public static @interface nonterminal { String value() default ""; }
 
+    @Retention(RetentionPolicy.RUNTIME) public static @interface raw { }
+
     /**
      *  Constructors, classes, and methods with this attribute will
      *  match every tree tagged with "value()" that is arg-compatible.
@@ -202,13 +205,13 @@ public class Demo {
             tag t = getTag();
             if (t != null &&
                 (t.value().equals(p.tag) ||
-                 (t.value().equals("") && p.tag.equals(getName()))))
+                 (t.value().equals("") && getName().equals(p.tag))))
                 return buildSequence(p)!=null;
 
             nonterminal n = getNonTerminal();
             if (n != null &&
                 (n.value().equals(p.nonTerminal) ||
-                 (n.value().equals("") && p.nonTerminal.equals(getName()))))
+                 (n.value().equals("") && getName().equals(p.nonTerminal))))
                 return buildSequence(p)!=null;
 
             return false;
@@ -238,6 +241,8 @@ public class Demo {
             return Sequence.rewritingSequence(new TargetReducer(p), p.elements, p.labels, p.drops);
         }
         public abstract Object plant(Object[] fields, int[] map);
+        public boolean isRaw() { return false; }
+        public Object invokeRaw(Tree t) { return null; }
         public class TargetReducer implements Reducer {
             private Production p;
             private int[] map;
@@ -247,6 +252,7 @@ public class Demo {
             }
             public String toString() { return "reducer-"+Target.this; }
             public Object reduce(Tree t) {
+                if (isRaw()) return invokeRaw(t);
                 Object[] objects = new Object[t.numChildren()];
                 for(int i=0; i<t.numChildren(); i++) {
                     Tree tc = t.child(i);
@@ -387,6 +393,14 @@ public class Demo {
             int[] ret = buildSequence(p, names, argtags);
             return ret;
         }
+        public boolean isRaw() { return _method.isAnnotationPresent(raw.class); }
+        public Object invokeRaw(Tree t) {
+            try {
+                return _method.invoke(null, new Object[] { t });
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
         public Object plant(Object[] fields, int[] map) {
             try {
                 Class[] argTypes = _method.getParameterTypes();
@@ -415,11 +429,28 @@ public class Demo {
         if (c == char.class) {
             return o.toString().charAt(0);
         }
+
+        if (o.getClass().isArray() &&
+            o.getClass().getComponentType().isArray() &&
+            o.getClass().getComponentType().getComponentType() == String.class &&
+            c.isArray() &&
+            c.getComponentType() == String.class) {
+            String[] ret = new String[((Object[])o).length];
+            for(int i=0; i<ret.length; i++) {
+                StringBuffer sb = new StringBuffer();
+                for(Object ob : (Object[])(((Object[])o)[i]))
+                    sb.append(ob);
+                ret[i] = sb.toString();
+            }
+            return ret;
+        }
+
         if (c.isArray() && (c.getComponentType().isInstance(o))) {
             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
             ret[0] = o;
             return ret;
         }
+
         if (o.getClass().isArray() && c.isArray()) {
             boolean ok = true;
             for(int i=0; i<((Object[])o).length; i++) {
@@ -437,6 +468,38 @@ public class Demo {
         return o;
     }
 
+    public static Union cached = null;
+    public static Union make() {
+        if (cached != null) return cached;
+        try {
+            ReflectiveMeta m = new ReflectiveMeta();
+            Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
+            MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
+            MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
+            Union meta = mgf.get("s").build(bc);
+            Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
+            return cached = make(t, "s");
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+    public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
+    public static Union make(Tree t, String s, ReflectiveMeta rm) {
+        Reducer red = (Reducer)t.head();
+        MG.Grammar g = (MG.Grammar)red.reduce(t);
+        Context cx = new Context(g,rm);
+        Union u = null;
+        for(MG.NonTerminal nt : g.nonterminals) {
+            System.out.println(nt.name);
+            Union el = (Union)cx.get(nt.name);
+            StringBuffer st = new StringBuffer();
+            el.toString(st);
+            System.err.println(st);
+            if (nt.name.equals(s)) u = el;
+        }
+        return u;
+    }
+
     public static class MG {
         public static @tag("grammar") class Grammar {
             public NonTerminal get(String s) {
@@ -461,7 +524,7 @@ public class Demo {
                     Union u2 = new Union();
                     if (sequences.length==1) u2 = u;
                     for(int j=0; j<group.length; j++) {
-                        group[j].build(cx, u2);
+                        group[j].build(cx, u2, false);
                     }
                     if (sequences.length==1) break;
                     Sequence seq = Sequence.singleton(u2);
@@ -555,16 +618,17 @@ public class Demo {
                 this.elements = elements;
                 return this;
             }
-            public Sequence build(Context cx, Union u) {
-                Sequence ret = build0(cx);
-                for(Seq s : and) { Sequence dork = s.build(cx, u); dork.lame = true; ret = ret.and(dork); }
-                for(Seq s : not) { Sequence dork = s.build(cx, u); dork.lame = true; ret = ret.not(dork); }
+            public Sequence build(Context cx, Union u, boolean lame) {
+                Sequence ret = build0(cx, lame || this.lame);
+                for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
+                for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
                 u.add(ret);
+                ret.lame = lame;
                 return ret;
             }
-            public Sequence build0(Context cx) {
+            public Sequence build0(Context cx, boolean lame) {
                 boolean unwrap = false;
-                boolean dropAll = false;
+                boolean dropAll = lame;
                 if (tag!=null && tag.equals("[]")) unwrap  = true;
                 if (tag!=null && "()".equals(tag)) dropAll = true;
                 Object[] labels = new Object[elements.length];
@@ -615,10 +679,12 @@ public class Demo {
                 return cx.get(nonTerminal);
             }
         }
+
         public static class StringLiteral        extends Constant {
             public @tag("literal") StringLiteral(String string) { super(CharRange.string(string)); }
             public boolean drop() { return true; }
         }
+
         public static                     class CharClass            extends El {
             Range[] ranges;
             public @tag("[") CharClass(Range[] ranges) { this.ranges = ranges; }
@@ -630,7 +696,7 @@ public class Demo {
             }
         }
 
-        public static @tag("{")           class Tree                 extends El {
+        public static @tag("{")           class XTree                 extends El {
             public @arg Seq body;
             public Element build(Context cx) {
                 throw new Error();