checkpoint
[sbp.git] / src / edu / berkeley / sbp / misc / Demo.java
index 1e5a5bc..6384939 100644 (file)
@@ -8,37 +8,58 @@ 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();
-        
-        MetaGrammar.Meta m =
-            new ReflectiveMeta(MG.class,
-                               new Class[] {
-                                   MG.Grammar.class,
-                                   MG.NonTerminal.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();
 
+        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());
+
+        System.err.println("== parsing with parsed-parsed grammar ==========================================================================");
+        t = new CharParser(new Context(t, m).build()).parse(new FileInputStream(s[1])).expand1();
         System.out.println(t.toPrettyString());
-        Reducer red = (Reducer)t.head();
-        System.out.println(red.reduce(t));
+    }
+
+    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;
@@ -69,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++) {
@@ -87,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))
@@ -99,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+"\"");
+            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++)
-                }
-            };
-    }
-    */
 
     
     /**
@@ -123,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.
@@ -181,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;
@@ -217,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;
@@ -226,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);
@@ -366,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();
@@ -394,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++) {
@@ -416,8 +468,46 @@ 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) {
+                for(NonTerminal nt : nonterminals)
+                    if (nt.name.equals(s))
+                        return nt;
+                return null;
+            }
             public @arg("NonTerminal") NonTerminal[] nonterminals;
             public String toString() {
                 String ret = "[ ";
@@ -425,39 +515,50 @@ public class Demo {
                 return ret + " ]";
             }
         }
-        public static @nonterminal class NonTerminal extends El {
-            public @arg("Word") String  name;
-            public @arg("RHS")  Seq[][] sequences;
-            private static int anon = 0;
-            public NonTerminal() { }
-            public NonTerminal(Seq[][] sequences) {
-                this.name = "anon" + (anon++);
+        public abstract static class Un extends El {
+            public Seq[][] sequences;
+            public void build(Context cx, Union u) {
+                HashSet<Sequence> bad2 = new HashSet<Sequence>();
+                for(int i=0; i<sequences.length; i++) {
+                    Seq[] group = sequences[i];
+                    Union u2 = new Union();
+                    if (sequences.length==1) u2 = u;
+                    for(int j=0; j<group.length; j++) {
+                        group[j].build(cx, u2, false);
+                    }
+                    if (sequences.length==1) break;
+                    Sequence seq = Sequence.singleton(u2);
+                    for(Sequence s : bad2) {
+                        s.lame = true;
+                        seq = seq.not(s);
+                    }
+                    u.add(seq);
+                    bad2.add(Sequence.singleton(u2));
+                }
+            }
+        }
+        public static class NonTerminal extends Un {
+            public String  name = null;
+            public @nonterminal("NonTerminal") NonTerminal(@arg("Word") String name,
+                                                           @arg("RHS") Seq[][] sequences) {
+                this.name = name;
+                this.sequences = sequences;
+            }
+            public Element build(Context cx) { return cx.get(name); }
+        }
+
+        public static class AnonUn extends Un {
+            public @tag("(") AnonUn(Seq[][] sequences) {
                 this.sequences = sequences;
             }
             public Element build(Context cx) {
-                Element ret = cx.peek(name);
-                if (ret != null) return ret;
-                Union u = new Union(name);
-                cx.put(name, u);
-                HashSet<Sequence> bad = new HashSet<Sequence>();
-                for(Seq[] group : sequences) {
-                    Union u2 = new Union(""+anon++);
-                    HashSet<Sequence> bad2 = new HashSet<Sequence>();
-                    for(Seq seq : group) {
-                        Sequence built = seq.build(cx);
-                        for(Sequence s : bad)
-                            built = built.not(s);
-                        u2.add(built);
-                        bad2.add(built);
-                    }
-                    bad.addAll(bad2);
-                    u.add(Sequence.singleton(u2));
-                }
-                return u;
+                Union ret = new Union();
+                build(cx, ret);
+                return ret;
             }
         }
 
-        public static @tag void range(char c) { }
+        //public static @tag void range(char c) { }
         public static class Range {
             public @tag("range") Range(char only) { first = only; last = only; }
             public @tag("-")     Range(char first, char last) { this.first = first; this.last = last; }
@@ -475,6 +576,7 @@ public class Demo {
             public Drop(El e) { this.e = e; }
             public String getLabel() { return null; }
             public boolean drop() { return true; }
+            public String getOwnerTag() { return e.getOwnerTag(); }
             public Element build(Context cx) { return e.build(cx); }
         }
         public static class Label extends El {
@@ -482,6 +584,7 @@ public class Demo {
             public El e;
             public Label(String label, El e) { this.e = e; this.label = label; }
             public String getLabel() { return label; }
+            public String getOwnerTag() { return e.getOwnerTag(); }
             public Element build(Context cx) { return e.build(cx); }
         }
         public static /*abstract*/ class Seq {
@@ -490,6 +593,7 @@ public class Demo {
             El[] elements;
             El follow;
             String tag = null;
+            boolean lame;
             public Seq(El e) { this(new El[] { e }); }
             public Seq(El[] elements) { this.elements = elements; }
             public Seq tag(String tag) { this.tag = tag; return this; }
@@ -502,8 +606,8 @@ public class Demo {
                 ret.tag = tag;
                 return ret;
             }
-            public Seq and(Seq s) { and.add(s); return this; }
-            public Seq andnot(Seq s) { not.add(s); return this; }
+            public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
+            public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
             public Seq separate(El sep) {
                 El[] elements = new El[this.elements.length * 2 - 1];
                 for(int i=0; i<this.elements.length; i++) {
@@ -514,9 +618,17 @@ public class Demo {
                 this.elements = elements;
                 return this;
             }
-            public Sequence build(Context cx) {
+            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, 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];
@@ -531,12 +643,9 @@ public class Demo {
                 }
                 Sequence ret = null;
                 if (dropAll)     ret = Sequence.drop(els, false);
-                else if (unwrap) ret = Sequence.unwrap(els, repeatTag(), drops);
+                else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
                 else if (tag!=null) {
-                    //FIXME
-                    //ret = resolveTag(tag, bc.currentNonTerminal==null ? null : bc.currentNonTerminal.name, els, labels, drops);
-                    //System.err.println("resolvetag " + tag + " => " + ret);
-                    ret = Sequence.rewritingSequence(tag, els, labels, drops);
+                    ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
                 } else {
                     int idx = -1;
                     for(int i=0; i<els.length; i++)
@@ -548,6 +657,7 @@ public class Demo {
                 }
                 if (this.follow != null)
                     ret.follow = MetaGrammar.infer(this.follow.build(cx));
+                ret.lame = this.lame;
                 return ret;
             }
         }
@@ -565,22 +675,28 @@ public class Demo {
 
         public static @tag("nonTerminal") class NonTerminalReference extends El {
             public @arg String nonTerminal;
-            public Element build(Context cx) { return cx.get(nonTerminal); }
+            public Element build(Context cx) {
+                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; }
             public Element build(Context cx) {
                 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
-                for(Range r : ranges) set.add(r.first, r.last);
+                for(Range r : ranges)
+                        set.add(r.first, r.last);
                 return CharRange.set(set);
             }
         }
 
-        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();
@@ -593,11 +709,11 @@ public class Demo {
             public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
                 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
             public Element build(Context cx) {
-                return max
-                    ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), repeatTag())
+                return (!max)
+                    ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
                     : sep==null
-                    ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many,                                   repeatTag())
-                    : Sequence.repeatMaximal(e.build(cx),                    zero, many, MetaGrammar.infer(sep.build(cx)), repeatTag());
+                    ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many,                                   cx.rm.repeatTag())
+                    : Sequence.repeatMaximal(e.build(cx),                    zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
             }
         }
         public static class Constant extends El {
@@ -626,9 +742,9 @@ public class Demo {
         public static @tag("!")   El bang(final El e)                        { return new Drop(e); }
 
         public static @tag("^")   El caret(final String s) {
-            return new Constant(CharRange.string(s)) {
+            return new Drop(new Constant(CharRange.string(s)) {
                     public String getOwnerTag() { return s; }
-                };
+                });
         }
 
         public static @tag("~")   El tilde(final El e) {
@@ -639,7 +755,7 @@ public class Demo {
 
         public static @tag("^^")  void doublecaret(final El e)                 { throw new Error("not implemented"); }
 
-        public static @tag("(")   El subexpression(Seq[][] rhs)                { return new NonTerminal(rhs); }
+        //public static @tag("(")   El subexpression(Seq[][] rhs)                { return new NonTerminal(rhs); }
 
         public static @nonterminal("Word")    String word(String s) { return s; }
         public static @nonterminal("Quoted")  String quoted(String s) { return s; }
@@ -651,14 +767,45 @@ public class Demo {
     }
     public static class Context {
         HashMap<String,Union> map = new HashMap<String,Union>();
+        private MG.Grammar grammar;
+        public String cnt = null;
+        private ReflectiveMeta rm;
+        public Context(MG.Grammar g, ReflectiveMeta rm) {
+            this.grammar = g;
+            this.rm = rm;
+        }
+        public Union build() {
+            Union ret = null;
+            for(MG.NonTerminal nt : grammar.nonterminals) {
+                Union u = get(nt.name);
+                if ("s".equals(nt.name))
+                    ret = u;
+            }
+            return ret;
+        }
+        public Context(Tree t, ReflectiveMeta rm) {
+            this.rm = rm;
+            Reducer red = (Reducer)t.head();
+            this.grammar = (MG.Grammar)red.reduce(t);
+        }
         public Union peek(String name) { return map.get(name); }
         public void  put(String name, Union u) { map.put(name, u); }
         public Union get(String name) {
             Union ret = map.get(name);
-            if (ret==null) map.put(name, ret = new Union(name));
+            if (ret != null) return ret;
+            ret = new Union(name);
+            map.put(name, ret);
+            MG.NonTerminal nt = grammar.get(name);
+            if (nt==null) {
+                System.err.println("*** warning could not find " + name);
+            } else {
+                String old = cnt;
+                cnt = name;
+                nt.build(this, ret);
+                cnt = old;
+            }
             return ret;
         }
 
     }
-    public static Object repeatTag() { return null; }
 }