more accurate positions in CharInput
[sbp.git] / src / edu / berkeley / sbp / meta / GrammarBuilder.java
1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
2
3 package edu.berkeley.sbp.meta;
4 import edu.berkeley.sbp.util.*;
5 import edu.berkeley.sbp.*;
6 import edu.berkeley.sbp.chr.*;
7 import edu.berkeley.sbp.misc.*;
8 import java.util.*;
9 import java.lang.annotation.*;
10 import java.lang.reflect.*;
11 import java.io.*;
12
13 // FIXME: deal with question-marks
14
15 // FIXME: put back in associativity: ^")"
16 //            A = A "->" (A)
17 //        means that the FIRST "A" cannot match the SAME sequence in
18 //        which the (A) occurs
19 //        -- and add a test case
20
21 // FIXME: make it so that we can have multi-result nonterminals
22 //        so long as they always appear under double-colons?
23 //        auto-insert the unwrap?
24
25 // FIXME: put associativity back in
26
27 // FIXME: "flat" sequences (no subtrees contain "::"s?)
28
29 // freezing problem is related to comments in grammar files
30
31 /** The java classes typically used to represent a parsed grammar AST; each inner class is a type of AST node. */
32 public class GrammarBuilder {
33
34     /**
35      *  Create a grammar from a parse tree and binding resolver
36      * 
37      *  @param t   a tree produced by parsing a grammar using the metagrammar
38      *  @param s   the name of the "start symbol"
39      *  @param gbr a GrammarBindingResolver that resolves grammatical reductions into tree-node-heads
40      */
41     public static Union buildFromAST(Tree grammarAST, String startingNonterminal, File[] includes) {
42         return new GrammarBuilder(includes, "").buildGrammar(grammarAST, startingNonterminal);
43     }
44
45     public static Object illegalTag = ""; // this is the tag that should never appear in the non-dropped output FIXME
46
47     private final String prefix;
48     private final File[] includes;
49
50     //public GrammarBuilder(String path) { this(path, ""); }
51     public GrammarBuilder(File[] includes, String prefix) {
52         this.prefix = prefix;
53         this.includes = includes;
54     }
55
56     public Union buildGrammar(Tree t, String rootNonTerminal) {
57         return ((GrammarBuilder.GrammarNode)walk(t)).build(rootNonTerminal);
58     }
59
60     private ElementNode epsilon = new LiteralNode("");
61
62     public Object[] walkChildren(Tree t) {
63         Object[] ret = new Object[t.size()];
64         for(int i=0; i<ret.length; i++) {
65             ret[i] = walk(t.child(i));
66             if (ret[i] instanceof Object[])
67                 ret[i] = Reflection.lub((Object[])ret[i]);
68         }
69         return Reflection.lub(ret);
70     }
71     public String stringifyChildren(Tree t) {
72         StringBuffer sb = new StringBuffer();
73         for(int i=0; i<t.size(); i++) {
74             sb.append(t.child(i).head());
75             sb.append(stringifyChildren(t.child(i)));
76         }
77         return sb.toString();
78     }
79     public String unescape(Tree t) {
80         StringBuffer sb = new StringBuffer();
81         for(int i=0; i<t.size(); i++)
82             sb.append(t.child(i).head()+stringifyChildren(t.child(i)));
83         return sb.toString();
84     }
85
86     public Object walk(Tree t) {
87         String head = (String)t.head();
88         while(head.indexOf('.') != -1) head = head.substring(head.indexOf('.')+1);
89         if (head==null) throw new RuntimeException("head is null: " + t);
90         if (head.equals("|")) return walkChildren(t);
91         if (head.equals("RHS")) return walkChildren(t);
92         if (head.equals("Grammar")) return new GrammarNode(walkChildren(t));
93         if (head.equals("(")) return new UnionNode((Seq[][])walkChildren(t.child(0)));
94         if (head.equals("Word")) return stringifyChildren(t);
95         if (head.equals("Elements")) return seq2((ElementNode[])Reflection.rebuild(walkChildren(t), ElementNode[].class));
96         if (head.equals("NonTerminalReference")) return new ReferenceNode(stringifyChildren(t.child(0)));
97         //if (head.equals(")")) return new ReferenceNode(stringifyChildren(t.child(0)));
98         if (head.equals("{")) return new XTree((Seq)walk(t.child(0)));
99         if (head.equals("::")) return tag((String)walk(t.child(0)), (Seq)walk(t.child(1)));
100         if (head.equals("++")) return plusmax((ElementNode)walk(t.child(0)));
101         if (head.equals("+")) return plus((ElementNode)walk(t.child(0)));
102         if (head.equals("++/")) return plusmaxfollow((ElementNode)walk(t.child(0)), (ElementNode)walk(t.child(1)));
103         if (head.equals("+/")) return plusfollow((ElementNode)walk(t.child(0)), (ElementNode)walk(t.child(1)));
104         if (head.equals("**")) return starmax((ElementNode)walk(t.child(0)));
105         if (head.equals("*")) return star((ElementNode)walk(t.child(0)));
106         if (head.equals("**/")) return starmaxfollow((ElementNode)walk(t.child(0)), (ElementNode)walk(t.child(1)));
107         if (head.equals("*/")) return starfollow((ElementNode)walk(t.child(0)), (ElementNode)walk(t.child(1)));
108         if (head.equals("?")) return question((ElementNode)walk(t.child(0)));
109         if (head.equals("!")) return new DropNode((ElementNode)walk(t.child(0)));
110         if (head.equals("^")) return new LiteralNode((String)walk(t.child(0)), true);
111         if (head.equals("Quoted")) return stringifyChildren(t);
112         if (head.equals("Literal")) return new LiteralNode((String)walk(t.child(0)));
113         if (head.equals("->")) return arrow((Seq)walk(t.child(0)), (ElementNode)walk(t.child(1)));
114         if (head.equals("DropNT")) return new NonTerminalNode((String)walk(t.child(0)), (Seq[][])walkChildren(t.child(1)), false, null, true);
115         if (head.equals("=") && t.size()==2) return new NonTerminalNode((String)walk(t.child(0)), (Seq[][])walk(t.child(1)), true, null, false);
116         if (head.equals("=")) return new NonTerminalNode((String)walk(t.child(0)), (Seq[][])walk(t.child(2)), true, (String)walk(t.child(1)), false);
117         if (head.equals("&")) return and2((Seq)walk(t.child(0)), (Seq)walk(t.child(1)));
118         if (head.equals("&~")) return andnot2((Seq)walk(t.child(0)), (Seq)walk(t.child(1)));
119         if (head.equals("/")) return ((Seq)walk(t.child(0))).separate((ElementNode)walk(t.child(1)));
120         if (head.equals("()")) return epsilon;
121         if (head.equals("[")) return new AtomNode((AtomNodeRange[])Reflection.rebuild(walkChildren(t), AtomNodeRange[].class));
122         if (head.equals("\\{")) return new DropNode(new AtomNode(new AtomNodeRange(CharAtom.left, CharAtom.left)));
123         if (head.equals("\\}")) return new DropNode(new AtomNode(new AtomNodeRange(CharAtom.right, CharAtom.right)));
124         if (head.equals("~")) return new TildeNode((ElementNode)walk(t.child(0)));
125         if (head.equals("Range") && t.size()==1) return new AtomNodeRange(unescape(t).charAt(0));
126         if (head.equals("Range")) return new AtomNodeRange(unescape(t).charAt(0), unescape(t).charAt(1));
127         if (head.equals("\"\"")) return "";
128         if (head.equals("\n")) return "\n";
129         if (head.equals("\r")) return "\r";
130         if (head.equals("grammar.Grammar")) return walkChildren(t);
131         if (head.equals("SubGrammar")) return GrammarBuilder.buildFromAST(t.child(0), "s", includes);
132         if (head.equals("NonTerminal"))
133             return new NonTerminalNode((String)walk(t.child(0)),
134                                        (Seq[][])walkChildren(t.child(1)), false, null, false);
135         if (head.equals("Colons")) {
136             String tag = (String)walk(t.child(0));
137             Seq[][] seqs = (Seq[][])walk(t.child(1));
138             for(Seq[] seq : seqs)
139                 for(int i=0; i<seq.length; i++)
140                     seq[i] = tag(tag, seq[i]);
141             return new NonTerminalNode(tag, seqs, false, null, false);
142         }
143         if (head.equals("TestCase"))
144             return new RegressionTests.TestCase((String)walk(t.child(0)),
145                                                 (String)walk(t.child(1)),
146                                                 (String[])Reflection.coerce(walkChildren(t.child(2)), String[].class),
147                                                 (Union)walk(t.child(3)),
148                                                 false,
149                                                 false);
150         if (head.equals("#import")) {
151             String fileName = (String)stringifyChildren(t.child(0));
152             for(File f : includes) {
153                 File file = new File(f.getAbsolutePath()+File.separatorChar+fileName);
154                 if (!file.exists()) continue;
155                 try {
156                     String newPrefix = (String)walk(t.child(1));
157                     if (newPrefix.length() > 0) newPrefix += ".";
158                     FileInputStream fis = new FileInputStream(file);
159                     Tree tr = new CharParser(MetaGrammar.newInstance()).parse(fis).expand1();
160                     return (GrammarNode)new GrammarBuilder(includes, newPrefix).walk(tr);
161                 } catch (Exception e) {
162                     throw new RuntimeException("while parsing " + file, e);
163                 }
164             }
165             throw new RuntimeException("unable to find #include file \""+fileName+"\"");
166         }
167         throw new RuntimeException("unknown head: " + head + "\n"+t);
168     }
169     
170     /** A grammar (a set of nonterminals) */
171     public class GrammarNode extends HashMap<String,NonTerminalNode> {
172         public GrammarNode(NonTerminalNode[] nonterminals) {
173             for(NonTerminalNode nt : nonterminals) {
174                 if (nt==null) continue;
175                 if (this.get(nt.name)!=null)
176                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
177                 this.put(nt.name, nt);
178             }
179         }
180         public  GrammarNode(Object[] nt) { add(nt); }
181         private void add(Object o) {
182             if (o==null) return;
183             else if (o instanceof Object[]) for(Object o2 : (Object[])o) add(o2);
184             else if (o instanceof NonTerminalNode) {
185                 NonTerminalNode nt = (NonTerminalNode)o;
186                 if (this.get(nt.name)!=null)
187                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
188                 this.put(nt.name, nt);
189             }
190             else if (o instanceof GrammarNode)
191                 for(NonTerminalNode n : ((GrammarNode)o).values())
192                     add(n);
193         }
194         public String toString() {
195             String ret = "[ ";
196             for(NonTerminalNode nt : values()) ret += nt + ", ";
197             return ret + " ]";
198         }
199         public Union build(String rootNonterminal) {
200             Context cx = new Context(this);
201             Union u = null;
202             for(GrammarBuilder.NonTerminalNode nt : values())
203                 if (nt.name.equals(rootNonterminal))
204                     return (Union)cx.get(nt.name);
205             return null;
206         }
207     }
208
209     public class UnionNode extends ElementNode {
210         public Seq[][] sequences;
211         public String  sep = null;
212         public boolean rep;
213         public UnionNode(Seq[][] sequences) { this(sequences, false, null); }
214         public UnionNode(Seq[][] sequences, boolean rep, String sep) {
215             this.sequences = sequences;
216             this.rep = rep;
217             this.sep = sep;
218         }
219         public Atom toAtom(Context cx) {
220             Atom ret = null;
221             for(Seq[] ss : sequences)
222                 for(Seq s : ss)
223                     ret = ret==null ? s.toAtom(cx) : (Atom)ret.union(s.toAtom(cx));
224             return ret;
225         }
226         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
227             return buildIntoPreallocatedUnion(cx, cnt, dropall, new Union(null, false)); }
228         public Element buildIntoPreallocatedUnion(Context cx, NonTerminalNode cnt, boolean dropall, Union u) {
229             Union urep = null;
230             if (rep) {
231                 urep = new Union(null, false);
232                 urep.add(Sequence.create(new Element[0], cnt.name));
233                 urep.add(sep==null
234                          ? Sequence.create(new Element[] { u }, 0)
235                          : Sequence.create(new Element[] { cx.get(sep), u }, 1));
236             }
237             HashSet<Sequence> bad2 = new HashSet<Sequence>();
238             for(int i=0; i<sequences.length; i++) {
239                 Seq[] group = sequences[i];
240                 Union u2 = new Union(null, false);
241                 if (sequences.length==1) u2 = u;
242                 for(int j=0; j<group.length; j++)
243                     if (!rep)
244                         group[j].build(cx, u2, cnt, dropall);
245                     else {
246                         Union u3 = new Union(null, false);
247                         group[j].build(cx, u3, cnt, dropall);
248                         Sequence s = Sequence.create(cnt.name,
249                                                      new Element[] { u3, urep },
250                                                      new boolean[] { false, false },
251                                                      true);
252                         u2.add(s);
253                     }
254                 if (sequences.length==1) break;
255                 Sequence seq = Sequence.create(u2);
256                 for(Sequence s : bad2) seq = seq.andnot(s);
257                 u.add(seq);
258                 bad2.add(Sequence.create(u2));
259             }
260             return u;
261         }
262     }
263
264     public class NonTerminalNode extends UnionNode {
265         public boolean alwaysDrop;
266         public String  name = null;
267         public boolean drop(Context cx) { return alwaysDrop; }
268         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep, boolean alwaysDrop) {
269             super(sequences, rep, sep==null?null:(prefix + sep));
270             this.name = prefix + name;
271             this.alwaysDrop = alwaysDrop;
272         }
273         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return cx.get(name); }
274     }
275
276     public class Seq {
277         public boolean alwaysDrop = false;
278         public boolean drop(Context cx) { return alwaysDrop; }
279         HashSet<Seq> and = new HashSet<Seq>();
280         HashSet<Seq> not = new HashSet<Seq>();
281         ElementNode[] elements;
282         ElementNode follow;
283         String tag = null;
284         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
285         public Seq(ElementNode[] elements) {
286             this.elements = elements;
287             for(int i=0; i<elements.length; i++)
288                 if (elements[i]==null)
289                     throw new RuntimeException();
290         }
291         public Atom toAtom(Context cx) {
292             if (elements.length != 1)
293                 throw new Error("you attempted to use ->, **, ++, or a similar character-class"+
294                                 " operator on a [potentially] multicharacter production");
295             return elements[0].toAtom(cx);
296         }
297         public Seq tag(String tag) { this.tag = tag; return this; }
298         public Seq follow(ElementNode follow) { this.follow = follow; return this; }
299         public Seq and(Seq s) { and.add(s); return this; }
300         public Seq andnot(Seq s) { not.add(s); return this; }
301         public Seq dup() {
302             Seq ret = new Seq(elements);
303             ret.and.addAll(and);
304             ret.not.addAll(not);
305             ret.follow = follow;
306             ret.tag = tag;
307             return ret;
308         }
309         public Seq separate(ElementNode sep) {
310             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
311             for(int i=0; i<this.elements.length; i++) {
312                 elements[i*2] = this.elements[i];
313                 if (i<this.elements.length-1)
314                     elements[i*2+1] = new DropNode(sep);
315             }
316             this.elements = elements;
317             return this;
318         }
319         public Sequence build(Context cx, Union u, NonTerminalNode cnt, boolean dropall) {
320             Sequence ret = build0(cx, cnt, dropall);
321             for(Seq s : and) ret = ret.and(s.build(cx, null, cnt, true));
322             for(Seq s : not) ret = ret.andnot(s.build(cx, null, cnt, true));
323             if (u!=null) u.add(ret);
324             return ret;
325         }
326         public Sequence build0(Context cx, NonTerminalNode cnt, boolean dropall) {
327             boolean[] drops = new boolean[elements.length];
328             Element[] els = new Element[elements.length];
329             dropall |= drop(cx);
330             for(int i=0; i<elements.length; i++) {
331                 if (dropall) drops[i] = true;
332                 else         drops[i] = elements[i].drop(cx);
333                 if (elements[i].getOwnerTag() != null)
334                     tag = elements[i].getOwnerTag();
335             }
336             Sequence ret = null;
337             int idx = -1;
338             boolean multiNonDrop = false;
339             for(int i=0; i<drops.length; i++)
340                 if (!drops[i])
341                     if (idx==-1) idx = i;
342                     else multiNonDrop = true;
343             for(int i=0; i<elements.length; i++) {
344                 if (!multiNonDrop && i==idx && tag!=null && elements[i] instanceof RepeatNode) {
345                     els[i] = ((RepeatNode)elements[i]).build(cx, cnt, dropall, tag);
346                     tag = null;
347                 } else
348                     els[i] = elements[i].build(cx, cnt, dropall);
349             }
350             if (tag==null && multiNonDrop)
351                 throw new RuntimeException("multiple non-dropped elements in sequence: " + Sequence.create(els, ""));
352             if (!multiNonDrop) {
353                 if (idx == -1) 
354                     ret = tag==null
355                         ? Sequence.create(els, illegalTag)
356                         : Sequence.create(tag, els, drops, false);
357                 else if (tag==null) ret = Sequence.create(els, idx);
358                 else ret = Sequence.create(tag, els, drops, false);
359             }
360             if (multiNonDrop)
361                 ret = Sequence.create(tag, els, drops, false);
362             if (this.follow != null)
363                 ret = ret.followedBy(this.follow.toAtom(cx));
364             return ret;
365         }
366     }
367
368     public class ReferenceNode extends ElementNode {
369         public String nonTerminal;
370         public ReferenceNode() { }
371         public NonTerminalNode resolve(Context cx) { return cx.grammar.get(nonTerminal); }
372         public ReferenceNode(String nonTerminal) { this.nonTerminal = prefix + nonTerminal; }
373         public Atom toAtom(Context cx) { return cx.grammar.get(nonTerminal).toAtom(cx); }
374         public boolean drop(Context cx) { return resolve(cx).drop(cx); }
375         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
376             if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
377             Element ret = cx.get(nonTerminal);
378             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
379             return ret;
380         }
381     }
382
383     public class LiteralNode extends ElementNode {
384         private String string;
385         private final String thePrefix = prefix;
386         private boolean caret;
387         public LiteralNode(String string) { this(string, false); }
388         public LiteralNode(String string, boolean caret) {
389             this.string = string;
390             this.caret = caret;
391         }
392         public String getOwnerTag() { return caret ? thePrefix+string : super.getOwnerTag(); }
393         public String toString() { return "\""+string+"\""; }
394         public boolean drop(Context cx) { return true; }
395         public Atom toAtom(Context cx) {
396             if (string.length()!=1) return super.toAtom(cx);
397             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
398             set.add(string.charAt(0), string.charAt(0));
399             return CharAtom.set(set);
400         }
401         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return CharAtom.string(string); }
402     }
403
404     public class AtomNode extends ElementNode {
405         AtomNodeRange[] ranges;
406         public AtomNode(AtomNodeRange[] ranges) { this.ranges = ranges; }
407         public AtomNode(AtomNodeRange range) { this.ranges = new AtomNodeRange[] { range }; }
408         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
409         public Atom toAtom(Context cx) {
410             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
411             for(AtomNodeRange r : ranges) set.add(r.first, r.last);
412             return CharAtom.set(set);
413         }
414     }
415     public class AtomNodeRange {
416         public char first;
417         public char last;
418         public AtomNodeRange(char only) { first = only; last = only; }
419         public AtomNodeRange(char first, char last) { this.first = first; this.last = last; }
420     }
421
422     public class RepeatNode extends ElementNode {
423         public ElementNode e, sep;
424         public final boolean zero, many, max;
425         public RepeatNode(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
426             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;
427         }
428         public Atom toAtom(Context cx) { return sep==null ? e.toAtom(cx) : super.toAtom(cx); }
429         public boolean drop(Context cx) { return e.drop(cx); }
430         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
431             Element ret = build(cx, cnt, dropall, illegalTag);
432             String must = "must be tagged unless they appear within a dropped expression or their contents are dropped: ";
433             if (!dropall && !drop(cx) && !e.drop(cx))
434                 if (!many)      throw new RuntimeException("options (?) " + must + ret);
435                 else if (zero)  throw new RuntimeException("zero-or-more repetitions (*) " + must + ret);
436                 else            throw new RuntimeException("one-or-more repetitions (+) " + must + ret);
437             return ret;
438         }
439         public Element build(Context cx, NonTerminalNode cnt, boolean dropall, Object repeatTag) {
440             return (!max)
441                 ? Repeat.repeat(e.build(cx, null, dropall), zero, many, sep==null ? null : sep.build(cx, null, dropall), repeatTag)
442                 : sep==null
443                 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, repeatTag)
444                 : Repeat.repeatMaximal(e.build(cx, null, dropall), zero, many, sep.toAtom(cx), repeatTag);
445         }
446     }
447
448     public abstract class ElementNode {
449         public String getOwnerTag() { return null; }
450         public boolean drop(Context cx) { return false; }
451         public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom: " + this); }
452         public abstract Element build(Context cx, NonTerminalNode cnt, boolean dropall);
453     }
454
455     public abstract class ElementNodeWrapper extends ElementNode {
456         protected ElementNode _e;
457         public ElementNodeWrapper(ElementNode e) { this._e = e; }
458         public String getOwnerTag() { return _e.getOwnerTag(); }
459         public boolean drop(Context cx) { return _e.drop(cx); }
460         public Atom toAtom(Context cx) { return _e.toAtom(cx); }
461         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return _e.build(cx, cnt, dropall); }
462     }
463
464     public class TildeNode extends ElementNodeWrapper {
465         public TildeNode(ElementNode e) { super(e); }
466         public Atom toAtom(Context cx) { return (Atom)((Topology<Character>)_e.toAtom(cx).complement()); }
467         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
468     }
469
470     public class DropNode extends ElementNodeWrapper {
471         public DropNode(ElementNode e) { super(e); }
472         public boolean drop(Context cx) { return true; }
473     }
474
475     public    Seq  and2(Seq s,        Seq a)   { a.alwaysDrop = true;  return s.and(a); }
476     public   Seq  andnot2(Seq s,     Seq a)   { a.alwaysDrop = true; return s.andnot(a); }
477     public   Seq  arrow(Seq s, ElementNode e) { return s.follow(e); }
478     public   Seq  tag(String tagname, Seq s)  { return s.tag(tagname); }
479     public Seq  seq(ElementNode[] elements)               { return new Seq(elements); }
480     public   Seq  seq2(ElementNode[] elements)               { return new Seq(elements); }
481     public   ElementNode plusmax(final ElementNode e)                         { return new RepeatNode(e, null, false, true, true); }
482     public    ElementNode plus(final ElementNode e)                            { return new RepeatNode(e, null, false, true, false); }
483     public  ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep)     { return new RepeatNode(e, sep,  false, true, true); }
484     public   ElementNode plusfollow(final ElementNode e, final ElementNode sep)        { return new RepeatNode(e, sep,  false, true, false); }
485     public   ElementNode starmax(final ElementNode e)                         { return new RepeatNode(e, null, true,  true, true); }
486     public    ElementNode star(final ElementNode e)                            { return new RepeatNode(e, null, true,  true, false); }
487     public  ElementNode starmaxfollow(final ElementNode e, final ElementNode sep)     { return new RepeatNode(e, sep,  true,  true, true); }
488     public   ElementNode starfollow(final ElementNode e, final ElementNode sep)        { return new RepeatNode(e, sep,  true,  true, false); }
489     public    ElementNode question(final ElementNode e)                        { return new RepeatNode(e, null, true,  false, false); }
490
491     //////////////////////////////////////////////////////////////////////////////
492
493     public class Context {
494         public HashMap<String,Union> map = new HashMap<String,Union>();
495         public GrammarNode grammar;
496         public Context(Tree t) { }
497         public Context(GrammarNode g) { this.grammar = g; }
498         public Union build() {
499             Union ret = null;
500             for(NonTerminalNode nt : grammar.values()) {
501                 Union u = get(nt.name);
502                 if ("s".equals(nt.name))
503                     ret = u;
504             }
505             return ret;
506         }
507         public Union peek(String name) { return map.get(name); }
508         public void  put(String name, Union u) { map.put(name, u); }
509         public Union get(String name) {
510             Union ret = map.get(name);
511             if (ret != null) return ret;
512             NonTerminalNode nt = grammar.get(name);
513             if (nt==null) {
514                 throw new Error("warning could not find " + name);
515             } else {
516                 ret = new Union(name, false);
517                 map.put(name, ret);
518                 nt.buildIntoPreallocatedUnion(this, nt, nt.drop(this), ret);
519             }
520             return ret;
521         }
522
523     }
524
525     public class XTree extends ElementNode {
526         public Seq body;
527         public XTree(Seq seq) { this.body = seq; }
528         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
529             Union u = new Union(null, false);
530             Sequence s = body.build(cx, u, null, dropall);
531             Union u2 = new Union(null, false);
532             u2.add(Sequence.create(new Element[] {
533                 CharAtom.leftBrace,
534                 cx.get("ws"),
535                 u,
536                 cx.get("ws"),
537                 CharAtom.rightBrace
538             }, 2));
539             return u2;
540         }
541     }
542 }