remove XTree
[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('.') > 0)
89             head = head.substring(head.indexOf('.')+1);
90         if (head==null) throw new RuntimeException("head is null: " + t);
91         if (head.equals("|")) return walkChildren(t);
92         if (head.equals("RHS")) return walkChildren(t);
93         if (head.equals("Grammar")) return new GrammarNode(walkChildren(t));
94         if (head.equals("(")) return new UnionNode((Seq[][])walkChildren(t.child(0)));
95         if (head.equals("Word")) return stringifyChildren(t);
96         if (head.equals("Elements")) return seq2((ElementNode[])Reflection.rebuild(walkChildren(t), ElementNode[].class));
97         if (head.equals("NonTerminalReference")) return new ReferenceNode(stringifyChildren(t.child(0)));
98         //if (head.equals(")")) return new ReferenceNode(stringifyChildren(t.child(0)));
99         if (head.equals("{")) return new XTree((Seq)walk(t.child(0)));
100         if (head.equals("::")) return tag((String)walk(t.child(0)), (Seq)walk(t.child(1)));
101         if (head.equals("++")) return plusmax((ElementNode)walk(t.child(0)));
102         if (head.equals("...")) return star(new TildeNode(new AtomNode()));
103         if (head.equals("+")) return plus((ElementNode)walk(t.child(0)));
104         if (head.equals("++/")) return plusmaxfollow((ElementNode)walk(t.child(0)), (ElementNode)walk(t.child(1)));
105         if (head.equals("+/")) return plusfollow((ElementNode)walk(t.child(0)), (ElementNode)walk(t.child(1)));
106         if (head.equals("**")) return starmax((ElementNode)walk(t.child(0)));
107         if (head.equals("*")) return star((ElementNode)walk(t.child(0)));
108         if (head.equals("**/")) return starmaxfollow((ElementNode)walk(t.child(0)), (ElementNode)walk(t.child(1)));
109         if (head.equals("*/")) return starfollow((ElementNode)walk(t.child(0)), (ElementNode)walk(t.child(1)));
110         if (head.equals("?")) return question((ElementNode)walk(t.child(0)));
111         if (head.equals("!")) return new DropNode((ElementNode)walk(t.child(0)));
112         if (head.equals("^")) return new LiteralNode((String)walk(t.child(0)), true);
113         if (head.equals("`")) {
114             ElementNode ret = (ElementNode)walk(t.child(0));
115             ret.lifted = true;
116             return ret;
117         }
118         if (head.equals("Quoted")) return stringifyChildren(t);
119         if (head.equals("Literal")) return new LiteralNode((String)walk(t.child(0)));
120         if (head.equals("->")) return arrow((Seq)walk(t.child(0)), (ElementNode)walk(t.child(1)));
121         if (head.equals("DropNT")) return new NonTerminalNode((String)walk(t.child(0)), (Seq[][])walkChildren(t.child(1)), false, null, true);
122         if (head.equals("=") && t.size()==2) return new NonTerminalNode((String)walk(t.child(0)), (Seq[][])walk(t.child(1)), true, null, false);
123         if (head.equals("=")) return new NonTerminalNode((String)walk(t.child(0)), (Seq[][])walk(t.child(2)), true, (String)walk(t.child(1)), false);
124         if (head.equals("&")) return and2((Seq)walk(t.child(0)), (Seq)walk(t.child(1)));
125         if (head.equals("&~")) return andnot2((Seq)walk(t.child(0)), (Seq)walk(t.child(1)));
126         if (head.equals("/")) return ((Seq)walk(t.child(0))).separate((ElementNode)walk(t.child(1)));
127         if (head.equals("()")) return epsilon;
128         if (head.equals("[")) return new AtomNode((AtomNodeRange[])Reflection.rebuild(walkChildren(t), AtomNodeRange[].class));
129         if (head.equals("\\{")) return new DropNode(new AtomNode(new AtomNodeRange(CharAtom.left, CharAtom.left)));
130         if (head.equals("\\}")) return new DropNode(new AtomNode(new AtomNodeRange(CharAtom.right, CharAtom.right)));
131         if (head.equals("~")) return new TildeNode((ElementNode)walk(t.child(0)));
132         if (head.equals("~~")) {
133             Seq seq = new Seq(star(new TildeNode(new AtomNode())));
134             return seq.andnot((Seq)walk(t.child(0)));
135         }
136         if (head.equals("Range") && t.size()==1) return new AtomNodeRange(unescape(t).charAt(0));
137         if (head.equals("Range")) return new AtomNodeRange(unescape(t).charAt(0), unescape(t).charAt(1));
138         if (head.equals("\"\"")) return "";
139         if (head.equals("\n")) return "\n";
140         if (head.equals("\r")) return "\r";
141         if (head.equals("grammar.Grammar")) return walkChildren(t);
142         if (head.equals("SubGrammar")) return GrammarBuilder.buildFromAST(t.child(0), "s", includes);
143         if (head.equals("NonTerminal"))
144             return new NonTerminalNode((String)walk(t.child(0)),
145                                        (Seq[][])walkChildren(t.child(1)), false, null, false);
146         if (head.equals("Colons")) {
147             String tag = (String)walk(t.child(0));
148             Seq[][] seqs = (Seq[][])walk(t.child(1));
149             for(Seq[] seq : seqs)
150                 for(int i=0; i<seq.length; i++)
151                     seq[i] = tag(tag, seq[i]);
152             return new NonTerminalNode(tag, seqs, false, null, false);
153         }
154         if (head.equals("TestCase"))
155             return new RegressionTests.TestCase((String)walk(t.child(0)),
156                                                 (String)walk(t.child(1)),
157                                                 (String[])Reflection.coerce(walkChildren(t.child(2)), String[].class),
158                                                 (Union)walk(t.child(3)),
159                                                 false,
160                                                 false);
161         if (head.equals("#import")) {
162             String fileName = (String)stringifyChildren(t.child(0));
163             for(File f : includes) {
164                 File file = new File(f.getAbsolutePath()+File.separatorChar+fileName);
165                 if (!file.exists()) continue;
166                 try {
167                     String newPrefix = t.size()<2 ? "" : ((String)walk(t.child(1))+".");
168                     FileInputStream fis = new FileInputStream(file);
169                     Tree tr = new CharParser(MetaGrammar.newInstance()).parse(fis).expand1();
170                     return (GrammarNode)new GrammarBuilder(includes, newPrefix).walk(tr);
171                 } catch (Exception e) {
172                     throw new RuntimeException("while parsing " + file, e);
173                 }
174             }
175             throw new RuntimeException("unable to find #include file \""+fileName+"\"");
176         }
177         throw new RuntimeException("unknown head: \"" + head + "\" => " + (head.equals("...")));
178     }
179     
180     /** A grammar (a set of nonterminals) */
181     public class GrammarNode extends HashMap<String,NonTerminalNode> {
182         public GrammarNode(NonTerminalNode[] nonterminals) {
183             for(NonTerminalNode nt : nonterminals) {
184                 if (nt==null) continue;
185                 if (this.get(nt.name)!=null)
186                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
187                 this.put(nt.name, nt);
188             }
189         }
190         public  GrammarNode(Object[] nt) { add(nt); }
191         private void add(Object o) {
192             if (o==null) return;
193             else if (o instanceof Object[]) for(Object o2 : (Object[])o) add(o2);
194             else if (o instanceof NonTerminalNode) {
195                 NonTerminalNode nt = (NonTerminalNode)o;
196                 if (this.get(nt.name)!=null)
197                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
198                 this.put(nt.name, nt);
199             }
200             else if (o instanceof GrammarNode)
201                 for(NonTerminalNode n : ((GrammarNode)o).values())
202                     add(n);
203         }
204         public String toString() {
205             String ret = "[ ";
206             for(NonTerminalNode nt : values()) ret += nt + ", ";
207             return ret + " ]";
208         }
209         public Union build(String rootNonterminal) {
210             Context cx = new Context(this);
211             Union u = null;
212             for(GrammarBuilder.NonTerminalNode nt : values())
213                 if (nt.name.equals(rootNonterminal))
214                     return (Union)cx.get(nt.name);
215             return null;
216         }
217     }
218
219     public class UnionNode extends ElementNode {
220         public Seq[][] sequences;
221         public String  sep = null;
222         public boolean rep;
223         public UnionNode(Seq[][] sequences) { this(sequences, false, null); }
224         public UnionNode(Seq[][] sequences, boolean rep, String sep) {
225             this.sequences = sequences;
226             this.rep = rep;
227             this.sep = sep;
228         }
229         public Atom toAtom(Context cx) {
230             Atom ret = null;
231             for(Seq[] ss : sequences)
232                 for(Seq s : ss)
233                     ret = ret==null ? s.toAtom(cx) : (Atom)ret.union(s.toAtom(cx));
234             return ret;
235         }
236         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
237             return buildIntoPreallocatedUnion(cx, cnt, dropall, new Union(null, false)); }
238         public Element buildIntoPreallocatedUnion(Context cx, NonTerminalNode cnt, boolean dropall, Union u) {
239             Union urep = null;
240             if (rep) {
241                 urep = new Union(null, false);
242                 urep.add(Sequence.create(new Element[0], cnt.name));
243                 urep.add(sep==null
244                          ? Sequence.create(new Element[] { u }, 0)
245                          : Sequence.create(new Element[] { cx.get(sep), u }, 1));
246             }
247             HashSet<Sequence> bad2 = new HashSet<Sequence>();
248             for(int i=0; i<sequences.length; i++) {
249                 Seq[] group = sequences[i];
250                 Union u2 = new Union(null, false);
251                 if (sequences.length==1) u2 = u;
252                 for(int j=0; j<group.length; j++)
253                     if (!rep)
254                         group[j].build(cx, u2, cnt, dropall);
255                     else {
256                         Union u3 = new Union(null, false);
257                         group[j].build(cx, u3, cnt, dropall);
258                         Sequence s = Sequence.create(cnt.name,
259                                                      new Element[] { u3, urep },
260                                                      new boolean[] { false, false },
261                                                      true);
262                         u2.add(s);
263                     }
264                 if (sequences.length==1) break;
265                 Sequence seq = Sequence.create(u2);
266                 for(Sequence s : bad2) seq = seq.andnot(s);
267                 u.add(seq);
268                 bad2.add(Sequence.create(u2));
269             }
270             return u;
271         }
272     }
273
274     public class NonTerminalNode extends UnionNode {
275         public boolean alwaysDrop;
276         public String  name = null;
277         public boolean drop(Context cx) { return alwaysDrop; }
278         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep, boolean alwaysDrop) {
279             super(sequences, rep, sep==null?null:(prefix + sep));
280             this.name = prefix + name;
281             this.alwaysDrop = alwaysDrop;
282         }
283         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return cx.get(name); }
284     }
285
286     public class Seq {
287         public boolean alwaysDrop = false;
288         public boolean drop(Context cx) { return alwaysDrop; }
289         HashSet<Seq> and = new HashSet<Seq>();
290         HashSet<Seq> not = new HashSet<Seq>();
291         ElementNode[] elements;
292         ElementNode follow;
293         String tag = null;
294         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
295         public Seq(ElementNode[] elements) {
296             this.elements = elements;
297             for(int i=0; i<elements.length; i++)
298                 if (elements[i]==null)
299                     throw new RuntimeException();
300         }
301         public Atom toAtom(Context cx) {
302             if (elements.length != 1)
303                 throw new Error("you attempted to use ->, **, ++, or a similar character-class"+
304                                 " operator on a [potentially] multicharacter production");
305             return elements[0].toAtom(cx);
306         }
307         public Seq tag(String tag) { this.tag = tag; return this; }
308         public Seq follow(ElementNode follow) { this.follow = follow; return this; }
309         public Seq and(Seq s) { and.add(s); return this; }
310         public Seq andnot(Seq s) { not.add(s); return this; }
311         public Seq dup() {
312             Seq ret = new Seq(elements);
313             ret.and.addAll(and);
314             ret.not.addAll(not);
315             ret.follow = follow;
316             ret.tag = tag;
317             return ret;
318         }
319         public Seq separate(ElementNode sep) {
320             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
321             for(int i=0; i<this.elements.length; i++) {
322                 elements[i*2] = this.elements[i];
323                 if (i<this.elements.length-1)
324                     elements[i*2+1] = new DropNode(sep);
325             }
326             this.elements = elements;
327             return this;
328         }
329         public Sequence build(Context cx, Union u, NonTerminalNode cnt, boolean dropall) {
330             Sequence ret = build0(cx, cnt, dropall);
331             for(Seq s : and) ret = ret.and(s.build(cx, null, cnt, true));
332             for(Seq s : not) ret = ret.andnot(s.build(cx, null, cnt, true));
333             if (u!=null) u.add(ret);
334             return ret;
335         }
336         public Sequence build0(Context cx, NonTerminalNode cnt, boolean dropall) {
337             boolean[] drops = new boolean[elements.length];
338             Element[] els = new Element[elements.length];
339             dropall |= drop(cx);
340             for(int i=0; i<elements.length; i++) {
341                 if (dropall) drops[i] = true;
342                 else         drops[i] = elements[i].drop(cx);
343                 if (elements[i].getOwnerTag() != null)
344                     tag = elements[i].getOwnerTag();
345             }
346             Sequence ret = null;
347             int idx = -1;
348             boolean multiNonDrop = false;
349             for(int i=0; i<drops.length; i++)
350                 if (!drops[i])
351                     if (idx==-1) idx = i;
352                     else multiNonDrop = true;
353             for(int i=0; i<elements.length; i++) {
354                 if (!multiNonDrop && i==idx && tag!=null && elements[i] instanceof RepeatNode) {
355                     els[i] = ((RepeatNode)elements[i]).build(cx, cnt, dropall, tag);
356                     tag = null;
357                 } else
358                     els[i] = elements[i].build(cx, cnt, dropall);
359             }
360             if (tag==null && multiNonDrop)
361                 throw new RuntimeException("multiple non-dropped elements in sequence: " + Sequence.create(els, ""));
362             boolean lift = false;
363             if (elements.length > 0 && elements[0].lifted)
364                 lift = true;
365             if (!multiNonDrop) {
366                 if (idx == -1) 
367                     ret = tag==null
368                         ? Sequence.create(els, illegalTag)
369                         : Sequence.createLeft(tag, els, drops, lift);
370                 else if (tag==null) ret = Sequence.create(els, idx);
371                 else ret = Sequence.createLeft(tag, els, drops, lift);
372             }
373             if (multiNonDrop)
374                 ret = Sequence.createLeft(tag, els, drops, lift);
375             if (this.follow != null)
376                 ret = ret.followedBy(this.follow.toAtom(cx));
377             return ret;
378         }
379     }
380
381     public class ReferenceNode extends ElementNode {
382         public String nonTerminal;
383         public ReferenceNode() { }
384         public NonTerminalNode resolve(Context cx) {
385             NonTerminalNode ret = cx.grammar.get(nonTerminal);
386             if (ret==null) throw new RuntimeException("undefined nonterminal: " + nonTerminal);
387             return ret;
388         }
389         public ReferenceNode(String nonTerminal) { this.nonTerminal = prefix + nonTerminal; }
390         public Atom toAtom(Context cx) { return cx.grammar.get(nonTerminal).toAtom(cx); }
391         public boolean drop(Context cx) { return resolve(cx).drop(cx); }
392         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
393             if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
394             Element ret = cx.get(nonTerminal);
395             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
396             return ret;
397         }
398     }
399
400     public class LiteralNode extends ElementNode {
401         private String string;
402         private final String thePrefix = prefix;
403         private boolean caret;
404         public LiteralNode(String string) { this(string, false); }
405         public LiteralNode(String string, boolean caret) {
406             this.string = string;
407             this.caret = caret;
408         }
409         public String getOwnerTag() { return caret ? thePrefix+string : super.getOwnerTag(); }
410         public String toString() { return "\""+string+"\""; }
411         public boolean drop(Context cx) { return true; }
412         public Atom toAtom(Context cx) {
413             if (string.length()!=1) return super.toAtom(cx);
414             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
415             set.add(string.charAt(0), string.charAt(0));
416             return CharAtom.set(set);
417         }
418         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return CharAtom.string(string); }
419     }
420
421     public class AtomNode extends ElementNode {
422         AtomNodeRange[] ranges;
423         public AtomNode() { this(new AtomNodeRange[0]); }
424         public AtomNode(AtomNodeRange[] ranges) { this.ranges = ranges; }
425         public AtomNode(AtomNodeRange range) { this.ranges = new AtomNodeRange[] { range }; }
426         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
427         public Atom toAtom(Context cx) {
428             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
429             for(AtomNodeRange r : ranges) set.add(r.first, r.last);
430             return CharAtom.set(set);
431         }
432     }
433     public class AtomNodeRange {
434         public char first;
435         public char last;
436         public AtomNodeRange(char only) { first = only; last = only; }
437         public AtomNodeRange(char first, char last) { this.first = first; this.last = last; }
438     }
439
440     public class RepeatNode extends ElementNode {
441         public ElementNode e, sep;
442         public final boolean zero, many, max;
443         public RepeatNode(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
444             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;
445         }
446         public Atom toAtom(Context cx) { return sep==null ? e.toAtom(cx) : super.toAtom(cx); }
447         public boolean drop(Context cx) { return e.drop(cx); }
448         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
449             Element ret = build(cx, cnt, dropall, illegalTag);
450             String must = "must be tagged unless they appear within a dropped expression or their contents are dropped: ";
451             if (!dropall && !drop(cx) && !e.drop(cx))
452                 if (!many)      throw new RuntimeException("options (?) " + must + ret);
453                 else if (zero)  throw new RuntimeException("zero-or-more repetitions (*) " + must + ret);
454                 else            throw new RuntimeException("one-or-more repetitions (+) " + must + ret);
455             return ret;
456         }
457         public Element build(Context cx, NonTerminalNode cnt, boolean dropall, Object repeatTag) {
458             return (!max)
459                 ? Repeat.repeat(e.build(cx, null, dropall), zero, many, sep==null ? null : sep.build(cx, null, dropall), repeatTag)
460                 : sep==null
461                 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, repeatTag)
462                 : Repeat.repeatMaximal(e.build(cx, null, dropall), zero, many, sep.toAtom(cx), repeatTag);
463         }
464     }
465
466     public abstract class ElementNode {
467         public boolean lifted = false;
468         public String getOwnerTag() { return null; }
469         public boolean drop(Context cx) { return false; }
470         public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom: " + this); }
471         public abstract Element build(Context cx, NonTerminalNode cnt, boolean dropall);
472     }
473
474     public abstract class ElementNodeWrapper extends ElementNode {
475         protected ElementNode _e;
476         public ElementNodeWrapper(ElementNode e) { this._e = e; }
477         public String getOwnerTag() { return _e.getOwnerTag(); }
478         public boolean drop(Context cx) { return _e.drop(cx); }
479         public Atom toAtom(Context cx) { return _e.toAtom(cx); }
480         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return _e.build(cx, cnt, dropall); }
481     }
482
483     public class TildeNode extends ElementNodeWrapper {
484         public TildeNode(ElementNode e) { super(e); }
485         public Atom toAtom(Context cx) { return (Atom)((Topology<Character>)_e.toAtom(cx).complement()); }
486         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
487     }
488
489     public class DropNode extends ElementNodeWrapper {
490         public DropNode(ElementNode e) { super(e); }
491         public boolean drop(Context cx) { return true; }
492     }
493
494     public    Seq  and2(Seq s,        Seq a)   { a.alwaysDrop = true;  return s.and(a); }
495     public   Seq  andnot2(Seq s,     Seq a)   { a.alwaysDrop = true; return s.andnot(a); }
496     public   Seq  arrow(Seq s, ElementNode e) { return s.follow(e); }
497     public   Seq  tag(String tagname, Seq s)  { return s.tag(tagname); }
498     public Seq  seq(ElementNode[] elements)               { return new Seq(elements); }
499     public   Seq  seq2(ElementNode[] elements)               { return new Seq(elements); }
500     public   ElementNode plusmax(final ElementNode e)                         { return new RepeatNode(e, null, false, true, true); }
501     public    ElementNode plus(final ElementNode e)                            { return new RepeatNode(e, null, false, true, false); }
502     public  ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep)     { return new RepeatNode(e, sep,  false, true, true); }
503     public   ElementNode plusfollow(final ElementNode e, final ElementNode sep)        { return new RepeatNode(e, sep,  false, true, false); }
504     public   ElementNode starmax(final ElementNode e)                         { return new RepeatNode(e, null, true,  true, true); }
505     public    ElementNode star(final ElementNode e)                            { return new RepeatNode(e, null, true,  true, false); }
506     public  ElementNode starmaxfollow(final ElementNode e, final ElementNode sep)     { return new RepeatNode(e, sep,  true,  true, true); }
507     public   ElementNode starfollow(final ElementNode e, final ElementNode sep)        { return new RepeatNode(e, sep,  true,  true, false); }
508     public    ElementNode question(final ElementNode e)                        { return new RepeatNode(e, null, true,  false, false); }
509
510     //////////////////////////////////////////////////////////////////////////////
511
512     public class Context {
513         public HashMap<String,Union> map = new HashMap<String,Union>();
514         public GrammarNode grammar;
515         public Context(Tree t) { }
516         public Context(GrammarNode g) { this.grammar = g; }
517         public Union build() {
518             Union ret = null;
519             for(NonTerminalNode nt : grammar.values()) {
520                 Union u = get(nt.name);
521                 if ("s".equals(nt.name))
522                     ret = u;
523             }
524             return ret;
525         }
526         public Union peek(String name) { return map.get(name); }
527         public void  put(String name, Union u) { map.put(name, u); }
528         public Union get(String name) {
529             Union ret = map.get(name);
530             if (ret != null) return ret;
531             NonTerminalNode nt = grammar.get(name);
532             if (nt==null) {
533                 throw new Error("warning could not find " + name);
534             } else {
535                 ret = new Union(name, false);
536                 map.put(name, ret);
537                 nt.buildIntoPreallocatedUnion(this, nt, nt.drop(this), ret);
538             }
539             return ret;
540         }
541
542     }
543
544 }