checkpoint
[sbp.git] / src / edu / berkeley / sbp / meta / MetaGrammarBindings.java
index c7952b0..196394a 100644 (file)
@@ -10,13 +10,15 @@ import java.lang.reflect.*;
 import java.io.*;
 
 /** The java classes typically used to represent a parsed grammar AST; each inner class is a type of AST node. */
-public class MetaGrammarBindings {
+public class MetaGrammarBindings extends AnnotationGrammarBindings {
+
+    public MetaGrammarBindings() { super(MetaGrammarBindings.class); }
 
     // FIXME ugly ugly ugly scary dangerous
     public static String prefix = "";
-
+    
     /** A grammar (a set of nonterminals) */
-    public static class GrammarNode extends HashMap<String,NonTerminalNode> implements NonTerminalSource {
+    public static class GrammarNode extends HashMap<String,NonTerminalNode> {
         public NonTerminalNode[] getNonTerminals() {
             return (NonTerminalNode[])values().toArray(new NonTerminalNode[0]);
         }
@@ -28,9 +30,7 @@ public class MetaGrammarBindings {
                 this.put(nt.name, nt);
             }
         }
-        public @bind.as("Grammar") GrammarNode(Object[] nt) {
-            add(nt);
-        }
+        public @bind.as("Grammar") GrammarNode(Object[] nt) { add(nt); }
         private void add(Object[] obs) {
             for(Object o : obs) {
                 if (o==null) continue;
@@ -41,7 +41,7 @@ public class MetaGrammarBindings {
                         throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
                     this.put(nt.name, nt);
                 }
-                else if (o instanceof NonTerminalSource) add(((NonTerminalSource)o).getNonTerminals());
+                else if (o instanceof GrammarNode) add(((GrammarNode)o).getNonTerminals());
             }
         }
         public String toString() {
@@ -49,7 +49,7 @@ public class MetaGrammarBindings {
             for(NonTerminalNode nt : values()) ret += nt + ", ";
             return ret + " ]";
         }
-        public Union build(String s, GrammarBindingResolver rm) {
+        public Union build(String s, Grammar.Bindings rm) {
             Context cx = new Context(this,rm);
             Union u = null;
             for(MetaGrammarBindings.NonTerminalNode nt : values()) {
@@ -64,11 +64,18 @@ public class MetaGrammarBindings {
 
     public abstract static class UnionNode extends ElementNode {
         public Seq[][] sequences;
+        public Atom toAtom(Context cx) {
+            Atom ret = null;
+            for(Seq[] ss : sequences)
+                for(Seq s : ss)
+                    ret = ret==null ? s.toAtom(cx) : infer(ret.union(s.toAtom(cx)));
+            return ret;
+        }
         public void build(Context cx, Union u, NonTerminalNode cnt) {
             HashSet<Sequence> bad2 = new HashSet<Sequence>();
             for(int i=0; i<sequences.length; i++) {
                 Seq[] group = sequences[i];
-                Union u2 = new Union();
+                Union u2 = new Union(null, false);
                 if (sequences.length==1) u2 = u;
                 for(int j=0; j<group.length; j++) {
                     group[j].build(cx, u2, false, cnt);
@@ -89,11 +96,10 @@ public class MetaGrammarBindings {
         if (as==null) as = "";
         else if ("".equals(as)) { }
         else as = as +".";
-        
-        System.err.println("#import " + fileName + " as " + as);
+
         try {
-            Tree t = new CharParser(MetaGrammar.make()).parse(new FileInputStream(fileName)).expand1();
-            Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
+            Tree t = new CharParser(MetaGrammar.newInstance()).parse(new FileInputStream("tests/"+fileName)).expand1();
+            TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
             String oldprefix = prefix;
             prefix = as;
             GrammarNode gn = (GrammarNode)red.invoke(t);
@@ -105,38 +111,38 @@ public class MetaGrammarBindings {
         }
     }
 
-    public static interface NonTerminalSource {
-        public NonTerminalNode[] getNonTerminals();
-    }
-
-    public static class NonTerminalNode extends UnionNode implements NonTerminalSource {
+    public static class NonTerminalNode extends UnionNode {
         public boolean rep;
         public String  name = null;
         public String sep = null;
         public NonTerminalNode[] getNonTerminals() { return new NonTerminalNode[] { this }; }
-        public @bind.as("NonTerminal") NonTerminalNode(@bind.arg String name, @bind.arg Seq[][] sequences) { this(name, sequences, false); }
+        public @bind.as("NonTerminal") NonTerminalNode(@bind.arg String name, @bind.arg Seq[][] sequences) {
+            this(name, sequences, false); }
         public NonTerminalNode(String name, Seq[][] sequences, boolean rep) { this(name, sequences, rep, null); }
         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep) {
             this.name = prefix + name;
             this.sequences = sequences;
             this.rep = rep;
-            this.sep = prefix + sep;
+            this.sep = sep==null?null:(prefix + sep);
         }
         public Element build(Context cx, NonTerminalNode cnt) { return cx.get(name); }
         public void build(Context cx, Union u, NonTerminalNode cnt) {
             if (!rep) { super.build(cx, u, this); return; }
             HashSet<Sequence> bad2 = new HashSet<Sequence>();
 
-            Union urep = new Union();
+            Union urep = new Union(null, false);
             urep.add(Sequence.empty);
-            urep.add(Sequence.singleton(new Element[] { cx.get(sep), u }, 1));
+            if (sep != null)
+                urep.add(Sequence.singleton(new Element[] { cx.get(sep), u }, 1));
+            else
+                urep.add(Sequence.singleton(new Element[] { u }, 0));
 
             for(int i=0; i<sequences.length; i++) {
                 Seq[] group = sequences[i];
-                Union u2 = new Union();
+                Union u2 = new Union(null, false);
                 if (sequences.length==1) u2 = u;
                 for(int j=0; j<group.length; j++) {
-                    Union u3 = new Union();
+                    Union u3 = new Union(null, false);
                     group[j].build(cx, u3, false, this);
                     Sequence s = Sequence.unwrap(new Element[] { u3, urep },
                                                  cx.rm.repeatTag(),
@@ -154,17 +160,18 @@ public class MetaGrammarBindings {
             }
         }
     }
-    public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg Seq[][] sequences) { return new NonTerminalNode(name, sequences, true); }
+
+    public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg Seq[][] sequences) {
+        return new NonTerminalNode(name, sequences, true); }
     public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg String sep, @bind.arg Seq[][] sequences) {
-        return new NonTerminalNode(name, sequences, true, sep);
-    }
+        return new NonTerminalNode(name, sequences, true, sep); }
 
     public static class AnonUnionNode extends UnionNode {
         public @bind.as("(") AnonUnionNode(Seq[][] sequences) {
             this.sequences = sequences;
         }
         public Element build(Context cx, NonTerminalNode cnt) {
-            Union ret = new Union();
+            Union ret = new Union(null, false);
             build(cx, ret, cnt);
             return ret;
         }
@@ -177,31 +184,6 @@ public class MetaGrammarBindings {
         public char last;
     }
 
-    public static abstract class ElementNode {
-        public String getLabel() { return null; }
-        public String getOwnerTag() { return null; }
-        public boolean drop() { return false; }
-        public abstract Element build(Context cx, NonTerminalNode cnt);
-    }
-
-    public static class Drop extends ElementNode {
-        public ElementNode e;
-        public Drop(ElementNode 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, NonTerminalNode cnt) { return e.build(cx, cnt); }
-    }
-
-    public static class Label extends ElementNode {
-        public String label;
-        public ElementNode e;
-        public Label(String label, ElementNode e) { this.e = e; this.label = label; }
-        public String getLabel() { return label; }
-        public String getOwnerTag() { return e.getOwnerTag(); }
-        public Element build(Context cx, NonTerminalNode cnt) { return e.build(cx, cnt); }
-    }
-
     public static /*abstract*/ class Seq {
         HashSet<Seq> and = new HashSet<Seq>();
         HashSet<Seq> not = new HashSet<Seq>();
@@ -217,8 +199,15 @@ public class MetaGrammarBindings {
         }
         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
         public Seq(ElementNode[] elements) { this.elements = elements; }
+        public Atom toAtom(Context cx) {
+            if (elements.length != 1) throw new Error("FIXME");
+            return elements[0].toAtom(cx);
+        }
         public Seq tag(String tag) { this.tag = prefix+tag; return this; }
-        public Seq follow(ElementNode follow) { this.follow = follow; return this; }
+        public Seq follow(ElementNode follow) {
+            this.follow = follow;
+            return this;
+       }
         public Seq dup() {
             Seq ret = new Seq(elements);
             ret.and.addAll(and);
@@ -261,35 +250,39 @@ public class MetaGrammarBindings {
             Sequence ret = null;
             if (dropAll)     ret = Sequence.drop(els, false);
             else {
-                ret = cx.rm.tryResolveTag(tag, cnt==null?null:cnt.name, els, drops);
+                Production prod = new Production(tag, (cnt==null?null:cnt.name), els, drops);
+                ret = cx.rm.createSequence(prod);
                 if (ret == null) {
                     int idx = -1;
                     for(int i=0; i<els.length; i++)
                         if (!drops[i])
                             if (idx==-1) idx = i;
-                            else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
+                            else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els, false));
                     if (idx != -1) ret = Sequence.singleton(els, idx);
                     else           ret = Sequence.drop(els, false);
                 }
             }
             if (this.follow != null)
-                ret.follow = infer(this.follow.build(cx, null));
+                ret.follow = this.follow.toAtom(cx);
             ret.lame = this.lame;
             return ret;
         }
     }
-    public static @bind.as("&")   Seq  and2(Seq s,        Seq a) { return s.and(a); }
-    public static @bind.as("&~")  Seq  andnot2(Seq s,     Seq a) { return s.andnot(a); }
-    public static @bind.as("->")  Seq  arrow(Seq s, ElementNode e)                { return s.follow(e); }
-    public static @bind.as("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
-    public static @bind.as("/")   Seq  slash(Seq s, ElementNode e)                { return s.separate(e); }
+    public static @bind.as("&")   Seq  and2(Seq s,        Seq a)   { return s.and(a); }
+    public static @bind.as("&~")  Seq  andnot2(Seq s,     Seq a)   { return s.andnot(a); }
+    public static @bind.as("->")  Seq  arrow(Seq s, ElementNode e) { return s.follow(e); }
+    public static @bind.as("::")  Seq  tag(String tagname, Seq s)  { return s.tag(tagname); }
+    public static @bind.as("/")   Seq  slash(Seq s, ElementNode e) { return s.separate(e); }
 
     public static Seq  seq(ElementNode[] elements)               { return new Seq(elements); }
     public static @bind.as("Elements")  Seq  seq2(ElementNode[] elements)               { return new Seq(elements); }
     public static @bind.as        Seq  psx(Seq s)                        { return s; }
     public static @bind.as(":")   ElementNode   colon(String s, ElementNode e)             { return new Label(s, e); }
     public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
-    public static @bind.as("()")  ElementNode   epsilon()                         { return new Constant(Union.epsilon); }
+    public static @bind.as("()")  ElementNode   epsilon()                         { return new Constant(epsilon); }
+
+    private static Union epsilon = new Union("()");
+    static { epsilon.add(Sequence.empty); }
 
     public static class NonTerminalReferenceNode extends ElementNode {
         public String nonTerminal;
@@ -297,6 +290,9 @@ public class MetaGrammarBindings {
         public @bind.as("NonTerminalReference") NonTerminalReferenceNode(String nonTerminal) {
             this.nonTerminal = prefix + nonTerminal;
         }
+        public Atom toAtom(Context cx) {
+            return cx.grammar.get(nonTerminal).toAtom(cx);
+        }
         public Element build(Context cx, NonTerminalNode cnt) {
             if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
             Element ret = cx.get(nonTerminal);
@@ -306,33 +302,49 @@ public class MetaGrammarBindings {
     }
 
     public static class Literal extends Constant {
-        public @bind Literal(@bind.arg String string) { super(CharRange.string(string)); }
+        private String string;
+        public @bind Literal(@bind.arg String string) {
+            super(CharAtom.string(string));
+            this.string = string;
+        }
         public boolean drop() { return true; }
+        public Atom toAtom(Context cx) {
+            if (string.length()!=1) return super.toAtom(cx);
+            edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
+            set.add(string.charAt(0), string.charAt(0));
+            return CharAtom.set(set);
+        }
     }
 
     public static                     class CharClass            extends ElementNode {
         Range[] ranges;
         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
+        public Atom toAtom(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);
+            return CharAtom.set(set);
+        }
         public Element build(Context cx, NonTerminalNode cnt) {
             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
             for(Range r : ranges)
                 set.add(r.first, r.last);
-            return CharRange.set(set);
+            return CharAtom.set(set);
         }
     }
 
     public static @bind.as("{")           class XTree                 extends ElementNode {
         public @bind.arg Seq body;
         public Element build(Context cx, NonTerminalNode cnt) {
-            Union u = new Union();
+            Union u = new Union(null, false);
             Sequence s = body.build(cx, u, false, null);
-            Union u2 = new Union();
+            Union u2 = new Union(null, false);
             u2.add(Sequence.singleton(new Element[] {
-                CharRange.leftBrace,
+                CharAtom.leftBrace,
                 cx.get("ws"),
                 u,
                 cx.get("ws"),
-                CharRange.rightBrace
+                CharAtom.rightBrace
             }, 2));
             return u2;
         }
@@ -343,25 +355,18 @@ public class MetaGrammarBindings {
         public boolean zero, many, max;
         public Rep(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
+        public Atom toAtom(Context cx) {
+            if (sep != null) return super.toAtom(cx);
+            return e.toAtom(cx);
+        }
         public Element build(Context cx, NonTerminalNode cnt) {
             return (!max)
-                ? Sequence.repeat(e.build(cx, null),        zero, many, sep==null ? null : sep.build(cx, null), cx.rm.repeatTag())
+                ? Sequence.repeat(e.build(cx, null), zero, many, sep==null ? null : sep.build(cx, null), cx.rm.repeatTag())
                 : sep==null
-                ? Sequence.repeatMaximal(infer(e.build(cx, null)), zero, many,                                   cx.rm.repeatTag())
-                : Sequence.repeatMaximal(e.build(cx, null),                    zero, many, infer(sep.build(cx, null)), cx.rm.repeatTag());
+                ? Sequence.repeatMaximal(e.toAtom(cx), zero, many, cx.rm.repeatTag())
+                : Sequence.repeatMaximal(e.build(cx, null), zero, many, sep.toAtom(cx), cx.rm.repeatTag());
         }
     }
-    public static class Constant extends ElementNode {
-        Element constant;
-        public Constant(Element constant) { this.constant = constant; }
-        public Element build(Context cx, NonTerminalNode cnt) { return constant; }
-    }
-    public abstract static class PostProcess extends ElementNode {
-        ElementNode e;
-        public PostProcess(ElementNode e) { this.e = e; }
-        public Element build(Context cx, NonTerminalNode cnt) { return postProcess(e.build(cx, cnt)); }
-        public abstract Element postProcess(Element e);
-    }
 
     // FIXME: it would be nice if we could hoist this into "Rep"
     public static @bind.as("++")  ElementNode plusmax(final ElementNode e)                     
@@ -387,15 +392,19 @@ public class MetaGrammarBindings {
 
     public static @bind.as("^")   ElementNode caret(final String s) {
         final String thePrefix = prefix;
-        return new Drop(new Constant(CharRange.string(s)) {
+        return new Constant(CharAtom.string(s)) {
                 public String getOwnerTag() { return thePrefix+s; }
-            });
+                public boolean drop() { return true; }
+            };
     }
 
     public static @bind.as("~")   ElementNode tilde(final ElementNode e) {
-        return new PostProcess(e) {
-                public Element postProcess(Element e) {
-                    return infer((Topology<Character>)Atom.toAtom(e).complement().minus(CharRange.braces));
+        return new ElementNodeWrapper(e) {
+                public Atom toAtom(Context cx) {
+                    return infer((Topology<Character>)e.toAtom(cx).complement().minus(CharAtom.braces));
+                }
+                public Element build(Context cx, NonTerminalNode cnt) {
+                    return infer((Topology<Character>)e.toAtom(cx).complement().minus(CharAtom.braces));
                 } }; }
 
     public static @bind.as("Word")        String word(String s) { return s; }
@@ -405,15 +414,15 @@ public class MetaGrammarBindings {
     public static @bind.as("\n")          String retur() { return "\n"; }
     public static @bind.as("\r")          String lf() { return "\r"; }
 
-    static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
-    static Atom infer(Topology<Character> t) { return new CharRange(new CharTopology(t)); }
+    //static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
+    static Atom infer(Topology<Character> t) { return new CharAtom(new CharTopology(t)); }
 
     public static class Context {
         public HashMap<String,Union> map = new HashMap<String,Union>();
         public GrammarNode grammar;
         public String cnt = null;
-        public GrammarBindingResolver rm;
-        public Context(GrammarNode g, GrammarBindingResolver rm) {
+        public Grammar.Bindings rm;
+        public Context(GrammarNode g, Grammar.Bindings rm) {
             this.grammar = g;
             this.rm = rm;
         }
@@ -426,9 +435,9 @@ public class MetaGrammarBindings {
             }
             return ret;
         }
-        public Context(Tree t, GrammarBindingResolver rm) {
+        public Context(Tree t, Grammar.Bindings rm) {
             this.rm = rm;
-            Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
+            TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
             this.grammar = (GrammarNode)red.invoke(t);
         }
         public Union peek(String name) { return map.get(name); }
@@ -440,7 +449,6 @@ public class MetaGrammarBindings {
             map.put(name, ret);
             NonTerminalNode nt = grammar.get(name);
             if (nt==null) {
-                //System.err.println("*** warning could not find " + name);
                 throw new Error("warning could not find " + name);
             } else {
                 String old = cnt;
@@ -453,4 +461,55 @@ public class MetaGrammarBindings {
 
     }
 
+    public static abstract class ElementNode {
+        public String getLabel() { return null; }
+        public String getOwnerTag() { return null; }
+        public boolean drop() { return false; }
+        public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom"); }
+        public abstract Element build(Context cx, NonTerminalNode cnt);
+    }
+
+    public static abstract class ElementNodeWrapper extends ElementNode {
+        protected ElementNode _e;
+        public ElementNodeWrapper(ElementNode e) { this._e = e; }
+        public String getLabel() { return _e.getLabel(); }
+        public String getOwnerTag() { return _e.getOwnerTag(); }
+        public boolean drop() { return _e.drop(); }
+        public Atom toAtom(Context cx) { return _e.toAtom(cx); }
+        public Element build(Context cx, NonTerminalNode cnt) { return _e.build(cx, cnt); }
+    }
+
+    public static class Constant extends ElementNode {
+        Element constant;
+        public Constant(Element constant) { this.constant = constant; }
+        public Element build(Context cx, NonTerminalNode cnt) { return constant; }
+        public Atom toAtom(Context cx) {
+            if (constant instanceof Atom) return ((Atom)constant);
+            return super.toAtom(cx);
+        }
+    }
+
+    public abstract static class PostProcess extends ElementNodeWrapper {
+        public PostProcess(ElementNode e) { super(e); }
+        public Element build(Context cx, NonTerminalNode cnt) { return postProcess(_e.build(cx, cnt)); }
+        public abstract Element postProcess(Element e);
+    }
+
+    public static class Drop extends ElementNodeWrapper {
+        public Drop(ElementNode e) { super(e); }
+        public boolean drop() { return true; }
+    }
+
+    public static class Label extends ElementNodeWrapper {
+        public String label;
+        public Label(String label, ElementNode e) { super(e); this.label = label; }
+        public String getLabel() { return label; }
+    }
+
+    static class Invert extends Atom {
+        private final Atom a;
+        public Invert(Atom a) { this.a = a; }
+        public Topology top() { return a.complement(); }
+        public String toString() { return "~"+a; }
+    }
 }