checkpoint
[sbp.git] / src / edu / berkeley / sbp / meta / MetaGrammarBindings.java
index dc35dfc..742918b 100644 (file)
@@ -12,10 +12,38 @@ 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 {
 
+    // FIXME ugly ugly ugly scary dangerous
+    public static String prefix = "";
+
     /** A grammar (a set of nonterminals) */
-    public static class GrammarNode extends HashMap<String,NonTerminalNode> {
-        public @bind.as("Grammar") GrammarNode(NonTerminalNode[] nonterminals) {
-            for(NonTerminalNode nt : nonterminals) this.put(nt.name, nt); }
+    public static class GrammarNode extends HashMap<String,NonTerminalNode> implements NonTerminalSource {
+        public NonTerminalNode[] getNonTerminals() {
+            return (NonTerminalNode[])values().toArray(new NonTerminalNode[0]);
+        }
+        public GrammarNode(NonTerminalNode[] nonterminals) {
+            for(NonTerminalNode nt : nonterminals) {
+                if (nt==null) continue;
+                if (this.get(nt.name)!=null)
+                    throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
+                this.put(nt.name, nt);
+            }
+        }
+        public @bind.as("Grammar") GrammarNode(Object[] nt) {
+            add(nt);
+        }
+        private void add(Object[] obs) {
+            for(Object o : obs) {
+                if (o==null) continue;
+                else if (o instanceof Object[]) add((Object[])o);
+                else if (o instanceof NonTerminalNode) {
+                    NonTerminalNode nt = (NonTerminalNode)o;
+                    if (this.get(nt.name)!=null)
+                        throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
+                    this.put(nt.name, nt);
+                }
+                else if (o instanceof NonTerminalSource) add(((NonTerminalSource)o).getNonTerminals());
+            }
+        }
         public String toString() {
             String ret = "[ ";
             for(NonTerminalNode nt : values()) ret += nt + ", ";
@@ -36,14 +64,14 @@ public class MetaGrammarBindings {
 
     public abstract static class UnionNode extends ElementNode {
         public Seq[][] sequences;
-        public void build(Context cx, Union u) {
+        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();
                 if (sequences.length==1) u2 = u;
                 for(int j=0; j<group.length; j++) {
-                    group[j].build(cx, u2, false);
+                    group[j].build(cx, u2, false, cnt);
                 }
                 if (sequences.length==1) break;
                 Sequence seq = Sequence.singleton(u2);
@@ -57,21 +85,43 @@ public class MetaGrammarBindings {
         }
     }
 
-    public static class NonTerminalNode extends UnionNode {
+    public static @bind.as("#import") GrammarNode poundimport(String fileName, String as) {
+        if (as==null) 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();
+            String oldprefix = prefix;
+            prefix = as;
+            GrammarNode gn = (GrammarNode)red.invoke(t);
+            prefix = oldprefix;
+            return gn;
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new RuntimeException(e);
+        }
+    }
+
+    public static interface NonTerminalSource {
+        public NonTerminalNode[] getNonTerminals();
+    }
+
+    public static class NonTerminalNode extends UnionNode implements NonTerminalSource {
         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 NonTerminalNode(String name, Seq[][] sequences, boolean rep) { this(name, sequences, rep, null); }
         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep) {
-            this.name = name;
+            this.name = prefix + name;
             this.sequences = sequences;
             this.rep = rep;
-            this.sep = sep;
+            this.sep = prefix + sep;
         }
-        public Element build(Context cx) { return cx.get(name); }
-        public void build(Context cx, Union u) {
-            if (!rep) { super.build(cx, u); return; }
+        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();
@@ -84,7 +134,7 @@ public class MetaGrammarBindings {
                 if (sequences.length==1) u2 = u;
                 for(int j=0; j<group.length; j++) {
                     Union u3 = new Union();
-                    group[j].build(cx, u3, false);
+                    group[j].build(cx, u3, false, this);
                     Sequence s = Sequence.unwrap(new Element[] { u3, urep },
                                                  cx.rm.repeatTag(),
                                                  new boolean[] { false, false });
@@ -110,9 +160,9 @@ public class MetaGrammarBindings {
         public @bind.as("(") AnonUnionNode(Seq[][] sequences) {
             this.sequences = sequences;
         }
-        public Element build(Context cx) {
+        public Element build(Context cx, NonTerminalNode cnt) {
             Union ret = new Union();
-            build(cx, ret);
+            build(cx, ret, cnt);
             return ret;
         }
     }
@@ -128,7 +178,7 @@ public class MetaGrammarBindings {
         public String getLabel() { return null; }
         public String getOwnerTag() { return null; }
         public boolean drop() { return false; }
-        public abstract Element build(Context cx);
+        public abstract Element build(Context cx, NonTerminalNode cnt);
     }
 
     public static class Drop extends ElementNode {
@@ -137,7 +187,7 @@ public class MetaGrammarBindings {
         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 Element build(Context cx, NonTerminalNode cnt) { return e.build(cx, cnt); }
     }
 
     public static class Label extends ElementNode {
@@ -146,7 +196,7 @@ public class MetaGrammarBindings {
         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) { return e.build(cx); }
+        public Element build(Context cx, NonTerminalNode cnt) { return e.build(cx, cnt); }
     }
 
     public static /*abstract*/ class Seq {
@@ -186,31 +236,29 @@ public class MetaGrammarBindings {
             this.elements = elements;
             return this;
         }
-        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); }
+        public Sequence build(Context cx, Union u, boolean lame, NonTerminalNode cnt) {
+            Sequence ret = build0(cx, lame || this.lame, cnt);
+            for(Seq s : and) { Sequence dork = s.build(cx, u, true, cnt); ret = ret.and(dork); }
+            for(Seq s : not) { Sequence dork = s.build(cx, u, true, cnt); ret = ret.not(dork); }
             u.add(ret);
             ret.lame = lame;
             return ret;
         }
-        public Sequence build0(Context cx, boolean lame) {
+        public Sequence build0(Context cx, boolean lame, NonTerminalNode cnt) {
             boolean dropAll = lame;
             if (tag!=null && "()".equals(tag)) dropAll = true;
-            Object[] labels = new Object[elements.length];
             boolean[] drops = new boolean[elements.length];
             Element[] els = new Element[elements.length];
             for(int i=0; i<elements.length; i++) {
-                labels[i] = elements[i].getLabel();
                 drops[i]  = elements[i].drop();
-                els[i] = elements[i].build(cx);
+                els[i] = elements[i].build(cx, cnt);
                 if (elements[i].getOwnerTag() != null)
                     tag = elements[i].getOwnerTag();
             }
             Sequence ret = null;
             if (dropAll)     ret = Sequence.drop(els, false);
             else {
-                ret = cx.rm.tryResolveTag(tag, cx.cnt, els, labels, drops);
+                ret = cx.rm.tryResolveTag(tag, cnt==null?null:cnt.name, els, drops);
                 if (ret == null) {
                     int idx = -1;
                     for(int i=0; i<els.length; i++)
@@ -222,7 +270,7 @@ public class MetaGrammarBindings {
                 }
             }
             if (this.follow != null)
-                ret.follow = infer(this.follow.build(cx));
+                ret.follow = infer(this.follow.build(cx, null));
             ret.lame = this.lame;
             return ret;
         }
@@ -240,9 +288,18 @@ public class MetaGrammarBindings {
     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("NonTerminalReference") class NonTerminalReferenceNode extends ElementNode {
-        public @bind.arg String nonTerminal;
-        public Element build(Context cx) { return cx.get(nonTerminal); }
+    public static class NonTerminalReferenceNode extends ElementNode {
+        public String nonTerminal;
+        public NonTerminalReferenceNode() { }
+        public @bind.as("NonTerminalReference") NonTerminalReferenceNode(String nonTerminal) {
+            this.nonTerminal = prefix + nonTerminal;
+        }
+        public Element build(Context cx, NonTerminalNode cnt) {
+            if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
+            Element ret = cx.get(nonTerminal);
+            if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
+            return ret;
+        }
     }
 
     public static class Literal extends Constant {
@@ -253,7 +310,7 @@ public class MetaGrammarBindings {
     public static                     class CharClass            extends ElementNode {
         Range[] ranges;
         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
-        public Element build(Context cx) {
+        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);
@@ -263,9 +320,9 @@ public class MetaGrammarBindings {
 
     public static @bind.as("{")           class XTree                 extends ElementNode {
         public @bind.arg Seq body;
-        public Element build(Context cx) {
+        public Element build(Context cx, NonTerminalNode cnt) {
             Union u = new Union();
-            Sequence s = body.build(cx, u, false);
+            Sequence s = body.build(cx, u, false, null);
             Union u2 = new Union();
             u2.add(Sequence.singleton(new Element[] {
                 CharRange.leftBrace,
@@ -283,38 +340,47 @@ 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 Element build(Context cx) {
+        public Element build(Context cx, NonTerminalNode cnt) {
             return (!max)
-                ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), 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)), zero, many,                                   cx.rm.repeatTag())
-                : Sequence.repeatMaximal(e.build(cx),                    zero, many, infer(sep.build(cx)), cx.rm.repeatTag());
+                ? 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());
         }
     }
     public static class Constant extends ElementNode {
         Element constant;
         public Constant(Element constant) { this.constant = constant; }
-        public Element build(Context cx) { return 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) { return postProcess(e.build(cx)); }
+        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)                     { return new Rep(e, null, false, true, true); }
-    public static @bind.as("+")   ElementNode plus(final ElementNode e)                        { return new Rep(e, null, false, true, false); }
-    public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep) { return new Rep(e, sep,  false, true, true); }
-    public static @bind.as("+/")  ElementNode plusfollow(final ElementNode e, final ElementNode sep)    { return new Rep(e, sep,  false, true, false); }
-    public static @bind.as("**")  ElementNode starmax(final ElementNode e)                     { return new Rep(e, null, true,  true, true); }
-    public static @bind.as("*")   ElementNode star(final ElementNode e)                        { return new Rep(e, null, true,  true, false); }
-    public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep) { return new Rep(e, sep,  true,  true, true); }
-    public static @bind.as("*/")  ElementNode starfollow(final ElementNode e, final ElementNode sep)    { return new Rep(e, sep,  true,  true, false); }
-    public static @bind.as("?")   ElementNode question(final ElementNode e)                    { return new Rep(e, null, true,  true, false); }
-
-    public static @bind.as("!")   ElementNode bang(final ElementNode e)                        { return new Drop(e); }
+    public static @bind.as("++")  ElementNode plusmax(final ElementNode e)                     
+    { return new Rep(e, null, false, true, true); }
+    public static @bind.as("+")   ElementNode plus(final ElementNode e)                        
+    { return new Rep(e, null, false, true, false); }
+    public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep) 
+    { return new Rep(e, sep,  false, true, true); }
+    public static @bind.as("+/")  ElementNode plusfollow(final ElementNode e, final ElementNode sep)    
+    { return new Rep(e, sep,  false, true, false); }
+    public static @bind.as("**")  ElementNode starmax(final ElementNode e)                     
+    { return new Rep(e, null, true,  true, true); }
+    public static @bind.as("*")   ElementNode star(final ElementNode e)                        
+    { return new Rep(e, null, true,  true, false); }
+    public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep) 
+    { return new Rep(e, sep,  true,  true, true); }
+    public static @bind.as("*/")  ElementNode starfollow(final ElementNode e, final ElementNode sep)    
+    { return new Rep(e, sep,  true,  true, false); }
+    public static @bind.as("?")   ElementNode question(final ElementNode e)                    
+    { return new Rep(e, null, true,  true, false); }
+    public static @bind.as("!")   ElementNode bang(final ElementNode e)                        
+    { return new Drop(e); }
 
     public static @bind.as("^")   ElementNode caret(final String s) {
         return new Drop(new Constant(CharRange.string(s)) {
@@ -325,7 +391,7 @@ public class MetaGrammarBindings {
     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()); 
+                    return infer((Topology<Character>)Atom.toAtom(e).complement().minus(CharRange.braces));
                 } }; }
 
     public static @bind.as("Word")        String word(String s) { return s; }
@@ -359,7 +425,7 @@ public class MetaGrammarBindings {
         public Context(Tree t, GrammarBindingResolver rm) {
             this.rm = rm;
             Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
-            this.grammar = (GrammarNode)red.invoke(t.children());
+            this.grammar = (GrammarNode)red.invoke(t);
         }
         public Union peek(String name) { return map.get(name); }
         public void  put(String name, Union u) { map.put(name, u); }
@@ -370,11 +436,12 @@ public class MetaGrammarBindings {
             map.put(name, ret);
             NonTerminalNode nt = grammar.get(name);
             if (nt==null) {
-                System.err.println("*** warning could not find " + name);
+                //System.err.println("*** warning could not find " + name);
+                throw new Error("warning could not find " + name);
             } else {
                 String old = cnt;
                 cnt = name;
-                nt.build(this, ret);
+                nt.build(this, ret, nt);
                 cnt = old;
             }
             return ret;