add some commenting to GrammarAST
[sbp.git] / src / edu / berkeley / sbp / meta / GrammarAST.java
index fc76a00..e039b37 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
+// Copyright 2006-2007 all rights reserved; see LICENSE file for BSD-style license
 
 package edu.berkeley.sbp.meta;
 import edu.berkeley.sbp.util.*;
@@ -16,6 +16,18 @@ import java.io.*;
  */
 public class GrammarAST {
 
+    public static interface ImportResolver {
+        public InputStream getImportStream(String importname);
+    }
+
+    /**
+     *  Returns a Union representing the metagrammar (<tt>meta.g</tt>); the Tree produced by
+     *  parsing with this Union should be provided to <tt>buildFromAST</tt>
+     */
+    public static Union getMetaGrammar() {
+        return buildFromAST(MetaGrammar.meta, "s", null);
+    }
+
     /**
      *  Create a grammar from a parse tree and binding resolver
      * 
@@ -23,8 +35,8 @@ public class GrammarAST {
      *  @param s   the name of the "start symbol"
      *  @param gbr a GrammarBindingResolver that resolves grammatical reductions into tree-node-heads
      */
-    public static Union buildFromAST(Tree grammarAST, String startingNonterminal, File[] includes) {
-        return new GrammarAST(includes, "").buildGrammar(grammarAST, startingNonterminal);
+    public static Union buildFromAST(Tree grammarAST, String startingNonterminal, ImportResolver resolver) {
+        return new GrammarAST(resolver, "").buildGrammar(grammarAST, startingNonterminal);
     }
 
     private static Object illegalTag = ""; // this is the tag that should never appear in the non-dropped output FIXME
@@ -32,29 +44,28 @@ public class GrammarAST {
     // Instance //////////////////////////////////////////////////////////////////////////////
 
     private final String prefix;
-    private final File[] includes;
+    private final ImportResolver resolver;
 
-    public GrammarAST(File[] includes, String prefix) {
+    public GrammarAST(ImportResolver resolver, String prefix) {
         this.prefix = prefix;
-        this.includes = includes;
+        this.resolver = resolver;
     }
 
     // Methods //////////////////////////////////////////////////////////////////////////////
 
     private Union buildGrammar(Tree t, String rootNonTerminal) {
-        return ((GrammarAST.GrammarNode)walk(t)).build(rootNonTerminal);
+        Object o = walk(t);
+        if (o instanceof Union) return (Union)o;
+        return ((GrammarAST.GrammarNode)o).build(rootNonTerminal);
     }
 
-    public Object[] walkChildren(Tree t) {
+    private Object[] walkChildren(Tree t) {
         Object[] ret = new Object[t.size()];
-        for(int i=0; i<ret.length; i++) {
+        for(int i=0; i<ret.length; i++)
             ret[i] = walk(t.child(i));
-            if (ret[i] instanceof Object[])
-                ret[i] = Reflection.lub((Object[])ret[i]);
-        }
         return Reflection.lub(ret);
     }
-    private String stringifyChildren(Tree t) {
+    private static String stringifyChildren(Tree t) {
         StringBuffer sb = new StringBuffer();
         for(int i=0; i<t.size(); i++) {
             sb.append(t.child(i).head());
@@ -62,7 +73,7 @@ public class GrammarAST {
         }
         return sb.toString();
     }
-    private String unescape(Tree t) {
+    private static String unescape(Tree t) {
         StringBuffer sb = new StringBuffer();
         for(int i=0; i<t.size(); i++)
             sb.append(t.child(i).head()+stringifyChildren(t.child(i)));
@@ -85,7 +96,6 @@ public class GrammarAST {
         if (head.equals("Elements")) return new Seq((ElementNode[])Reflection.rebuild(walkChildren(t), ElementNode[].class));
         if (head.equals("NonTerminalReference")) return new ReferenceNode(stringifyChildren(t.child(0)));
         if (head.equals(")"))   return new ReferenceNode(stringifyChildren(t.child(0)), true);
-        if (head.equals("{"))   return new BracedNode(walkSeq(t.child(0)));
         if (head.equals("::"))  return walkSeq(t.child(1)).tag(walkString(t.child(0)));
         if (head.equals("...")) return new DropNode(new RepeatNode(new TildeNode(new AtomNode()), null, true,  true,  false));
 
@@ -101,15 +111,15 @@ public class GrammarAST {
 
         if (head.equals("!"))   return new DropNode(walkElement(t.child(0)));
         if (head.equals("^"))   return new LiteralNode(walkString(t.child(0)), true);
-        if (head.equals("`"))   return walkElement(t.child(0)).lifted();
+        if (head.equals("`"))   return new BacktickNode(walkElement(t.child(0)));
         if (head.equals("Quoted")) return stringifyChildren(t);
         if (head.equals("Literal")) return new LiteralNode(walkString(t.child(0)));
         if (head.equals("->")) return walkSeq(t.child(0)).follow(walkElement(t.child(1)));
         if (head.equals("DropNT")) return new NonTerminalNode(walkString(t.child(0)), (Seq[][])walkChildren(t.child(1)), false, null, true);
         if (head.equals("=")) return new NonTerminalNode(walkString(t.child(0)), (Seq[][])walk(t.child(2)),
                                                          true, t.size()==2 ? null : walkString(t.child(1)), false);
-        if (head.equals("&"))   return and2(walkSeq(t.child(0)), walkSeq(t.child(1)));
-        if (head.equals("&~"))  return andnot2(walkSeq(t.child(0)), walkSeq(t.child(1)));
+        if (head.equals("&"))   return walkSeq(t.child(0)).and(walkSeq(t.child(1)));
+        if (head.equals("&~"))  return walkSeq(t.child(0)).andnot(walkSeq(t.child(1)));
         if (head.equals("/"))   return (walkSeq(t.child(0))).separate(walkElement(t.child(1)));
         if (head.equals("()"))  return new LiteralNode("");
         if (head.equals("["))   return new AtomNode((char[][])Reflection.rebuild(walkChildren(t), char[][].class));
@@ -119,17 +129,17 @@ public class GrammarAST {
         if (head.equals("<<"))  return new DropNode(new AtomNode(new char[] { CharAtom.right, CharAtom.right }));
         if (head.equals("~"))   return new TildeNode(walkElement(t.child(0)));
         if (head.equals("~~"))  return new Seq(new RepeatNode(new TildeNode(new AtomNode()), null, true,  true,  false)).andnot(walkSeq(t.child(0)));
-        if (head.equals("Range") && t.size()==2 && ">".equals(t.child(0).head()))
-            return new char[] { CharAtom.left, CharAtom.left };
-        if (head.equals("Range") && t.size()==2 && "<".equals(t.child(0).head()))
-            return new char[] { CharAtom.right, CharAtom.right };
-        if (head.equals("Range") && t.size()==1) return new char[] { unescape(t).charAt(0), unescape(t).charAt(0) };
-        if (head.equals("Range")) return new char[] { unescape(t).charAt(0), unescape(t).charAt(1) };
+        if (head.equals("Range")) {
+            if (t.size()==2 && ">".equals(t.child(0).head())) return new char[] { CharAtom.left, CharAtom.left };
+            if (t.size()==2 && "<".equals(t.child(0).head())) return new char[] { CharAtom.right, CharAtom.right };
+            if (t.size()==1) return new char[] { unescape(t).charAt(0), unescape(t).charAt(0) };
+            return new char[] { unescape(t).charAt(0), unescape(t).charAt(1) };
+        }
         if (head.equals("\"\"")) return "";
-        if (head.equals("\n")) return "\n";
-        if (head.equals("\r")) return "\r";
-        if (head.equals("grammar.Grammar")) return walkChildren(t);
-        if (head.equals("SubGrammar")) return GrammarAST.buildFromAST(t.child(0), "s", includes);
+        if (head.equals("\n"))   return "\n";
+        if (head.equals("\t"))   return "\t";
+        if (head.equals("\r"))   return "\r";
+        if (head.equals("SubGrammar")) return GrammarAST.buildFromAST(t.child(0), "s", resolver);
         if (head.equals("NonTerminal"))
             return new NonTerminalNode(walkString(t.child(0)),
                                        (Seq[][])walkChildren(t.child(1)), false, null, false);
@@ -141,28 +151,22 @@ public class GrammarAST {
                     seq[i] = seq[i].tag(tag);
             return new NonTerminalNode(tag, seqs, false, null, false);
         }
-        if (head.equals("TestCase"))
-            return new RegressionTests.TestCase(walkString(t.child(0)),
-                                                walkString(t.child(1)),
-                                                (String[])Reflection.coerce(walkChildren(t.child(2)), String[].class),
-                                                (Union)walk(t.child(3)),
-                                                false,
-                                                false);
         if (head.equals("#import")) {
-            String fileName = (String)stringifyChildren(t.child(0));
-            for(File f : includes) {
-                File file = new File(f.getAbsolutePath()+File.separatorChar+fileName);
-                if (!file.exists()) continue;
+            if (resolver != null) {
+                String fileName = (String)stringifyChildren(t.child(0));
                 try {
                     String newPrefix = t.size()<2 ? "" : (walkString(t.child(1))+".");
-                    FileInputStream fis = new FileInputStream(file);
-                    Tree tr = new CharParser(MetaGrammar.newInstance()).parse(fis).expand1();
-                    return (GrammarNode)new GrammarAST(includes, newPrefix).walk(tr);
+                    InputStream fis = resolver.getImportStream(fileName);
+                    if (fis==null)
+                        throw new RuntimeException("unable to find #include file \""+fileName+"\"");
+                    Tree tr = new CharParser(getMetaGrammar()).parse(fis).expand1();
+                    return (GrammarNode)new GrammarAST(resolver, newPrefix).walk(tr);
                 } catch (Exception e) {
-                    throw new RuntimeException("while parsing " + file, e);
+                    throw new RuntimeException("while parsing " + fileName, e);
                 }
+            } else {
+                throw new RuntimeException("no resolver given");
             }
-            throw new RuntimeException("unable to find #include file \""+fileName+"\"");
         }
         throw new RuntimeException("unknown head: \"" + head + "\" => " + (head.equals("...")));
     }
@@ -209,10 +213,26 @@ public class GrammarAST {
         }
     }
 
+    /** a node in the AST which is resolved into an Element */
+    private abstract class ElementNode {
+        public boolean isLifted() { return false; }
+        public boolean isDropped(Context cx) { return false; }
+        public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom: " + this); }
+        public abstract Element build(Context cx, NonTerminalNode cnt, boolean dropall);
+    }
+
+    /** a union, produced by a ( .. | .. | .. ) construct */
     private class UnionNode extends ElementNode {
+
+        /** each component of a union is a sequence */
         public Seq[][] sequences;
-        public String  sep = null;
+
+        /** if the union is a NonTerminal specified as Foo*=..., this is true */
         public boolean rep;
+
+        /** if the union is a NonTerminal specified as Foo* /ws=..., then this is "ws" */
+        public String  sep = null;
+
         public UnionNode(Seq seq) { this(new Seq[][] { new Seq[] { seq } }); }
         public UnionNode(Seq[][] sequences) { this(sequences, false, null); }
         public UnionNode(Seq[][] sequences, boolean rep, String sep) {
@@ -220,10 +240,10 @@ public class GrammarAST {
             this.rep = rep;
             this.sep = sep;
         }
-        public boolean drop(Context cx) {
+        public boolean isDropped(Context cx) {
             for(Seq[] seqs : sequences)
                 for(Seq seq : seqs)
-                    if (!seq.drop(cx))
+                    if (!seq.isDropped(cx))
                         return false;
             return true;
         }
@@ -272,10 +292,11 @@ public class GrammarAST {
         }
     }
 
+    /** a NonTerminal is always a union at the top level */
     private class NonTerminalNode extends UnionNode {
         public boolean alwaysDrop;
         public String  name = null;
-        public boolean drop(Context cx) { return alwaysDrop; }
+        public boolean isDropped(Context cx) { return alwaysDrop; }
         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep, boolean alwaysDrop) {
             super(sequences, rep, sep==null?null:(prefix + sep));
             this.name = prefix + name;
@@ -284,21 +305,27 @@ public class GrammarAST {
         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return cx.get(name); }
     }
 
+    /** a sequence */
     private class Seq {
+        /** elements of the sequence */
+        ElementNode[] elements;
+        /** follow-set, if explicit */
+        ElementNode follow;
+        /** tag to add when building the AST */
+        String tag = null;
+        /** positive conjuncts */
+        HashSet<Seq> and = new HashSet<Seq>();
+        /** negative conjuncts */
+        HashSet<Seq> not = new HashSet<Seq>();
         public boolean alwaysDrop = false;
-        public boolean drop(Context cx) {
+        public boolean isDropped(Context cx) {
             if (alwaysDrop) return true;
             if (tag!=null) return false;
             for(int i=0; i<elements.length; i++)
-                if (!elements[i].drop(cx))
+                if (!elements[i].isDropped(cx) || ((elements[i] instanceof LiteralNode) && ((LiteralNode)elements[i]).caret))
                     return false;
             return true;
         }
-        HashSet<Seq> and = new HashSet<Seq>();
-        HashSet<Seq> not = new HashSet<Seq>();
-        ElementNode[] elements;
-        ElementNode follow;
-        String tag = null;
         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
         public Seq(ElementNode[] elements) { this(elements, true); }
         public Seq(ElementNode[] el, boolean check) {
@@ -307,7 +334,6 @@ public class GrammarAST {
             for(int i=0; i<elements.length; i++) {
                 if (elements[i]==null)
                     throw new RuntimeException();
-                elements[i].ownerSeq = this;
             }
             // FIXME: this whole mechanism is sketchy
             if (check)
@@ -336,8 +362,8 @@ public class GrammarAST {
         }
         public Seq tag(String tag) { this.tag = tag; return this; }
         public Seq follow(ElementNode follow) { this.follow = follow; return this; }
-        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.alwaysDrop = true; return this; }
+        public Seq andnot(Seq s) { not.add(s); s.alwaysDrop = true; return this; }
         public Seq separate(ElementNode sep) {
             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
             for(int i=0; i<this.elements.length; i++) {
@@ -358,12 +384,14 @@ public class GrammarAST {
         public Sequence build0(Context cx, NonTerminalNode cnt, boolean dropall) {
             boolean[] drops = new boolean[elements.length];
             Element[] els = new Element[elements.length];
-            dropall |= drop(cx);
+            dropall |= isDropped(cx);
             for(int i=0; i<elements.length; i++) {
                 if (dropall) drops[i] = true;
-                else         drops[i] = elements[i].drop(cx);
-                if (elements[i].getOwnerTag() != null)
-                    tag = elements[i].getOwnerTag();
+                else         drops[i] = elements[i].isDropped(cx);
+                if (elements[i] instanceof LiteralNode && ((LiteralNode)elements[i]).caret) {
+                    if (tag != null) throw new RuntimeException("cannot have multiple tags in a sequence: " + this);
+                    tag = ((LiteralNode)elements[i]).getLiteralTag();
+                }
             }
             Sequence ret = null;
             int idx = -1;
@@ -383,7 +411,7 @@ public class GrammarAST {
                 throw new RuntimeException("multiple non-dropped elements in sequence: " + Sequence.create("", els));
             boolean[] lifts = new boolean[elements.length];
             for(int i=0; i<elements.length; i++)
-                lifts[i] = elements[i].lifted;
+                lifts[i] = elements[i].isLifted();
             if (!multiNonDrop) {
                 if (idx == -1) 
                     ret = tag==null
@@ -400,6 +428,7 @@ public class GrammarAST {
         }
     }
 
+    /** reference to a NonTerminal by name */
     private class ReferenceNode extends ElementNode {
         public String nonTerminal;
         public boolean parenthesized;
@@ -419,18 +448,15 @@ public class GrammarAST {
             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
             return ret.toAtom(cx);
         }
-        public boolean drop(Context cx) { return resolve(cx).drop(cx); }
+        public boolean isDropped(Context cx) { return resolve(cx).isDropped(cx); }
         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
-            /*
-            if (!this.nonTerminal.startsWith(prefix))
-                nonTerminal = prefix + nonTerminal;
-            */
             Element ret = cx.get(nonTerminal);
             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
             return ret;
         }
     }
 
+    /** a literal string */
     private class LiteralNode extends ElementNode {
         private String string;
         private final String thePrefix = prefix;
@@ -440,9 +466,9 @@ public class GrammarAST {
             this.string = string;
             this.caret = caret;
         }
-        public String getOwnerTag() { return caret ? thePrefix+string : super.getOwnerTag(); }
+        public String getLiteralTag() { return caret ? thePrefix+string : null; }
         public String toString() { return "\""+string+"\""; }
-        public boolean drop(Context cx) { return true; }
+        public boolean isDropped(Context cx) { return true; }
         public Atom toAtom(Context cx) {
             if (string.length()!=1) return super.toAtom(cx);
             Range.Set set = new Range.Set();
@@ -452,6 +478,7 @@ public class GrammarAST {
         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return CharAtom.string(string); }
     }
 
+    /** an atom (usually a character class) */
     private class AtomNode extends ElementNode {
         char[][] ranges;
         public AtomNode() { this(new char[0][]); }
@@ -465,6 +492,7 @@ public class GrammarAST {
         }
     }
 
+    /** a repetition */
     private class RepeatNode extends ElementNode {
         public ElementNode e, sep;
         public final boolean zero, many, max;
@@ -472,11 +500,11 @@ public class GrammarAST {
             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;
         }
         public Atom toAtom(Context cx) { return sep==null ? e.toAtom(cx) : super.toAtom(cx); }
-        public boolean drop(Context cx) { return e.drop(cx); }
+        public boolean isDropped(Context cx) { return e.isDropped(cx); }
         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
             Element ret = build(cx, cnt, dropall, illegalTag);
             String must = "must be tagged unless they appear within a dropped expression or their contents are dropped: ";
-            if (!dropall && !drop(cx) && !e.drop(cx))
+            if (!dropall && !isDropped(cx) && !e.isDropped(cx))
                 if (!many)      throw new RuntimeException("options (?) " + must + ret);
                 else if (zero)  throw new RuntimeException("zero-or-more repetitions (*) " + must + ret);
                 else            throw new RuntimeException("one-or-more repetitions (+) " + must + ret);
@@ -491,25 +519,22 @@ public class GrammarAST {
         }
     }
 
-    private abstract class ElementNode {
-        public boolean lifted = false;
-        public Seq ownerSeq = null;
-        public String getOwnerTag() { return null; }
-        public ElementNode lifted() { this.lifted = true; return this; }
-        public boolean drop(Context cx) { return false; }
-        public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom: " + this); }
-        public abstract Element build(Context cx, NonTerminalNode cnt, boolean dropall);
-    }
-
+    /** helper class for syntactic constructs that wrap another construct */
     private abstract class ElementNodeWrapper extends ElementNode {
         protected ElementNode _e;
         public ElementNodeWrapper(ElementNode e) { this._e = e; }
-        public String getOwnerTag() { return _e.getOwnerTag(); }
-        public boolean drop(Context cx) { return _e.drop(cx); }
+        public boolean isDropped(Context cx) { return _e.isDropped(cx); }
         public Atom toAtom(Context cx) { return _e.toAtom(cx); }
         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return _e.build(cx, cnt, dropall); }
     }
 
+    /** a backtick node indicating that, when building the AST, the node's children should be inserted here */
+    private class BacktickNode extends ElementNodeWrapper {
+        public BacktickNode(ElementNode e) { super(e); }
+        public boolean isLifted() { return true; }
+    }
+
+    /** negation */
     private class TildeNode extends ElementNodeWrapper {
         public TildeNode(ElementNode e) { super(e); }
         public Atom toAtom(Context cx) { return (Atom)((Topology<Character>)_e.toAtom(cx).complement()); }
@@ -518,29 +543,9 @@ public class GrammarAST {
 
     private class DropNode extends ElementNodeWrapper {
         public DropNode(ElementNode e) { super(e); }
-        public boolean drop(Context cx) { return true; }
+        public boolean isDropped(Context cx) { return true; }
     }
 
-    // FIXME: doesn't this require a tag?
-    private class BracedNode extends ElementNode {
-        public Seq body;
-        public BracedNode(Seq seq) { this.body = seq; }
-        public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
-            Union u = new Union(null, false);
-            Sequence s = body.build(cx, u, null, dropall);
-            Union u2 = new Union(null, false);
-            u2.add(Sequence.create(new Element[] {
-                CharAtom.leftBrace,
-                u,
-                CharAtom.rightBrace
-            }, 1));
-            return u2;
-        }
-    }
-
-    public Seq  and2(Seq s,    Seq a) { a.alwaysDrop = true; return s.and(a);    }
-    public Seq  andnot2(Seq s, Seq a) { a.alwaysDrop = true; return s.andnot(a); }
-
     //////////////////////////////////////////////////////////////////////////////
 
     public class Context {
@@ -568,7 +573,7 @@ public class GrammarAST {
             } else {
                 ret = new Union(name, false);
                 map.put(name, ret);
-                nt.buildIntoPreallocatedUnion(this, nt, nt.drop(this), ret);
+                nt.buildIntoPreallocatedUnion(this, nt, nt.isDropped(this), ret);
             }
             return ret;
         }