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