a caretized LiteralNode does not get dropped
[sbp.git] / src / edu / berkeley / sbp / meta / GrammarAST.java
1 // Copyright 2006-2007 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 /**
14  *  The inner classes of this class represent nodes in the Abstract
15  *  Syntax Tree of a grammar.
16  */
17 public class GrammarAST {
18
19     public static interface ImportResolver {
20         public InputStream getImportStream(String importname);
21     }
22
23     /**
24      *  Returns a Union representing the metagrammar (<tt>meta.g</tt>); the Tree produced by
25      *  parsing with this Union should be provided to <tt>buildFromAST</tt>
26      */
27     public static Union getMetaGrammar() {
28         return buildFromAST(MetaGrammar.meta, "s", null);
29     }
30
31     /**
32      *  Create a grammar from a parse tree and binding resolver
33      * 
34      *  @param t   a tree produced by parsing a grammar using the metagrammar
35      *  @param s   the name of the "start symbol"
36      *  @param gbr a GrammarBindingResolver that resolves grammatical reductions into tree-node-heads
37      */
38     public static Union buildFromAST(Tree grammarAST, String startingNonterminal, ImportResolver resolver) {
39         return new GrammarAST(resolver, "").buildGrammar(grammarAST, startingNonterminal);
40     }
41
42     private static Object illegalTag = ""; // this is the tag that should never appear in the non-dropped output FIXME
43
44     // Instance //////////////////////////////////////////////////////////////////////////////
45
46     private final String prefix;
47     private final ImportResolver resolver;
48
49     public GrammarAST(ImportResolver resolver, String prefix) {
50         this.prefix = prefix;
51         this.resolver = resolver;
52     }
53
54     // Methods //////////////////////////////////////////////////////////////////////////////
55
56     private Union buildGrammar(Tree t, String rootNonTerminal) {
57         Object o = walk(t);
58         if (o instanceof Union) return (Union)o;
59         return ((GrammarAST.GrammarNode)o).build(rootNonTerminal);
60     }
61
62     private 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         return Reflection.lub(ret);
67     }
68     private static String stringifyChildren(Tree t) {
69         StringBuffer sb = new StringBuffer();
70         for(int i=0; i<t.size(); i++) {
71             sb.append(t.child(i).head());
72             sb.append(stringifyChildren(t.child(i)));
73         }
74         return sb.toString();
75     }
76     private static String unescape(Tree t) {
77         StringBuffer sb = new StringBuffer();
78         for(int i=0; i<t.size(); i++)
79             sb.append(t.child(i).head()+stringifyChildren(t.child(i)));
80         return sb.toString();
81     }
82
83     private ElementNode walkElement(Tree t) { return (ElementNode)walk(t); }
84     private String      walkString(Tree t) { return (String)walk(t); }
85     private Seq         walkSeq(Tree t) { return (Seq)walk(t); }
86     private 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 new Seq((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)), true);
99         if (head.equals("::"))  return walkSeq(t.child(1)).tag(walkString(t.child(0)));
100         if (head.equals("...")) return new DropNode(new RepeatNode(new TildeNode(new AtomNode()), null, true,  true,  false));
101
102         if (head.equals("++"))  return new RepeatNode(walkElement(t.child(0)), null,                      false, true,  true);
103         if (head.equals("+"))   return new RepeatNode(walkElement(t.child(0)), null,                      false, true,  false);
104         if (head.equals("++/")) return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)),   false, true,  true);
105         if (head.equals("+/"))  return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)),   false, true,  false);
106         if (head.equals("**"))  return new RepeatNode(walkElement(t.child(0)), null,                      true,  true,  true);
107         if (head.equals("*"))   return new RepeatNode(walkElement(t.child(0)), null,                      true,  true,  false);
108         if (head.equals("**/")) return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)),   true,  true,  true);
109         if (head.equals("*/"))  return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)),   true,  true,  false);
110         if (head.equals("?"))   return new RepeatNode(walkElement(t.child(0)), null,                      true,  false, false);
111
112         if (head.equals("!"))   return new DropNode(walkElement(t.child(0)));
113         if (head.equals("^"))   return new LiteralNode(walkString(t.child(0)), true);
114         if (head.equals("`"))   return new BacktickNode(walkElement(t.child(0)));
115         if (head.equals("Quoted")) return stringifyChildren(t);
116         if (head.equals("Literal")) return new LiteralNode(walkString(t.child(0)));
117         if (head.equals("->")) return walkSeq(t.child(0)).follow(walkElement(t.child(1)));
118         if (head.equals("DropNT")) return new NonTerminalNode(walkString(t.child(0)), (Seq[][])walkChildren(t.child(1)), false, null, true);
119         if (head.equals("=")) return new NonTerminalNode(walkString(t.child(0)), (Seq[][])walk(t.child(2)),
120                                                          true, t.size()==2 ? null : walkString(t.child(1)), false);
121         if (head.equals("&"))   return walkSeq(t.child(0)).and(walkSeq(t.child(1)));
122         if (head.equals("&~"))  return walkSeq(t.child(0)).andnot(walkSeq(t.child(1)));
123         if (head.equals("/"))   return (walkSeq(t.child(0))).separate(walkElement(t.child(1)));
124         if (head.equals("()"))  return new LiteralNode("");
125         if (head.equals("["))   return new AtomNode((char[][])Reflection.rebuild(walkChildren(t), char[][].class));
126         if (head.equals("\\{")) return new DropNode(new AtomNode(new char[] { CharAtom.left, CharAtom.left }));
127         if (head.equals("\\}")) return new DropNode(new AtomNode(new char[] { CharAtom.right, CharAtom.right }));
128         if (head.equals(">>"))  return new DropNode(new AtomNode(new char[] { CharAtom.left, CharAtom.left }));
129         if (head.equals("<<"))  return new DropNode(new AtomNode(new char[] { CharAtom.right, CharAtom.right }));
130         if (head.equals("~"))   return new TildeNode(walkElement(t.child(0)));
131         if (head.equals("~~"))  return new Seq(new RepeatNode(new TildeNode(new AtomNode()), null, true,  true,  false)).andnot(walkSeq(t.child(0)));
132         if (head.equals("Range")) {
133             if (t.size()==2 && ">".equals(t.child(0).head())) return new char[] { CharAtom.left, CharAtom.left };
134             if (t.size()==2 && "<".equals(t.child(0).head())) return new char[] { CharAtom.right, CharAtom.right };
135             if (t.size()==1) return new char[] { unescape(t).charAt(0), unescape(t).charAt(0) };
136             return new char[] { unescape(t).charAt(0), unescape(t).charAt(1) };
137         }
138         if (head.equals("\"\"")) return "";
139         if (head.equals("\n"))   return "\n";
140         if (head.equals("\r"))   return "\r";
141         if (head.equals("SubGrammar")) return GrammarAST.buildFromAST(t.child(0), "s", resolver);
142         if (head.equals("NonTerminal"))
143             return new NonTerminalNode(walkString(t.child(0)),
144                                        (Seq[][])walkChildren(t.child(1)), false, null, false);
145         if (head.equals("Colons")) {
146             String tag = walkString(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] = seq[i].tag(tag);
151             return new NonTerminalNode(tag, seqs, false, null, false);
152         }
153         if (head.equals("#import")) {
154             if (resolver != null) {
155                 String fileName = (String)stringifyChildren(t.child(0));
156                 try {
157                     String newPrefix = t.size()<2 ? "" : (walkString(t.child(1))+".");
158                     InputStream fis = resolver.getImportStream(fileName);
159                     if (fis==null)
160                         throw new RuntimeException("unable to find #include file \""+fileName+"\"");
161                     Tree tr = new CharParser(getMetaGrammar()).parse(fis).expand1();
162                     return (GrammarNode)new GrammarAST(resolver, newPrefix).walk(tr);
163                 } catch (Exception e) {
164                     throw new RuntimeException("while parsing " + fileName, e);
165                 }
166             } else {
167                 throw new RuntimeException("no resolver given");
168             }
169         }
170         throw new RuntimeException("unknown head: \"" + head + "\" => " + (head.equals("...")));
171     }
172
173     
174     // Nodes //////////////////////////////////////////////////////////////////////////////
175
176     /** Root node of a grammar's AST; a set of named nonterminals */
177     private class GrammarNode extends HashMap<String,NonTerminalNode> {
178         public GrammarNode(NonTerminalNode[] nonterminals) {
179             for(NonTerminalNode nt : nonterminals) {
180                 if (nt==null) continue;
181                 if (this.get(nt.name)!=null)
182                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
183                 this.put(nt.name, nt);
184             }
185         }
186         public  GrammarNode(Object[] nt) { add(nt); }
187         private void add(Object o) {
188             if (o==null) return;
189             else if (o instanceof Object[]) for(Object o2 : (Object[])o) add(o2);
190             else if (o instanceof NonTerminalNode) {
191                 NonTerminalNode nt = (NonTerminalNode)o;
192                 if (this.get(nt.name)!=null)
193                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
194                 this.put(nt.name, nt);
195             }
196             else if (o instanceof GrammarNode)
197                 for(NonTerminalNode n : ((GrammarNode)o).values())
198                     add(n);
199         }
200         public String toString() {
201             String ret = "[ ";
202             for(NonTerminalNode nt : values()) ret += nt + ", ";
203             return ret + " ]";
204         }
205         public Union build(String rootNonterminal) {
206             Context cx = new Context(this);
207             Union u = null;
208             for(GrammarAST.NonTerminalNode nt : values())
209                 if (nt.name.equals(rootNonterminal))
210                     return (Union)cx.get(nt.name);
211             return null;
212         }
213     }
214
215     /** a node in the AST which is resolved into an Element */
216     private abstract class ElementNode {
217         public boolean isLifted() { return false; }
218         public boolean isDropped(Context cx) { return false; }
219         public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom: " + this); }
220         public abstract Element build(Context cx, NonTerminalNode cnt, boolean dropall);
221     }
222
223     private class UnionNode extends ElementNode {
224         public Seq[][] sequences;
225         public String  sep = null;
226         public boolean rep;
227         public UnionNode(Seq seq) { this(new Seq[][] { new Seq[] { seq } }); }
228         public UnionNode(Seq[][] sequences) { this(sequences, false, null); }
229         public UnionNode(Seq[][] sequences, boolean rep, String sep) {
230             this.sequences = sequences;
231             this.rep = rep;
232             this.sep = sep;
233         }
234         public boolean isDropped(Context cx) {
235             for(Seq[] seqs : sequences)
236                 for(Seq seq : seqs)
237                     if (!seq.isDropped(cx))
238                         return false;
239             return true;
240         }
241         public Atom toAtom(Context cx) {
242             Atom ret = null;
243             for(Seq[] ss : sequences)
244                 for(Seq s : ss)
245                     ret = ret==null ? s.toAtom(cx) : (Atom)ret.union(s.toAtom(cx));
246             return ret;
247         }
248         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
249             return buildIntoPreallocatedUnion(cx, cnt, dropall, new Union(null, false)); }
250         public Element buildIntoPreallocatedUnion(Context cx, NonTerminalNode cnt, boolean dropall, Union u) {
251             Union urep = null;
252             if (rep) {
253                 urep = new Union(null, false);
254                 urep.add(Sequence.create(cnt.name, new Element[0]));
255                 urep.add(sep==null
256                          ? Sequence.create(new Element[] { u }, 0)
257                          : Sequence.create(new Element[] { cx.get(sep), u }, 1));
258             }
259             HashSet<Sequence> bad2 = new HashSet<Sequence>();
260             for(int i=0; i<sequences.length; i++) {
261                 Seq[] group = sequences[i];
262                 Union u2 = new Union(null, false);
263                 if (sequences.length==1) u2 = u;
264                 for(int j=0; j<group.length; j++)
265                     if (!rep)
266                         group[j].build(cx, u2, cnt, dropall);
267                     else {
268                         Union u3 = new Union(null, false);
269                         group[j].build(cx, u3, cnt, dropall);
270                         Sequence s = Sequence.create(cnt.name,
271                                                      new Element[] { u3, urep },
272                                                      new boolean[] { false, false },
273                                                      new boolean[] { false, true});
274                         u2.add(s);
275                     }
276                 if (sequences.length==1) break;
277                 Sequence seq = Sequence.create(u2);
278                 for(Sequence s : bad2) seq = seq.andnot(s);
279                 u.add(seq);
280                 bad2.add(Sequence.create(u2));
281             }
282             return u;
283         }
284     }
285
286     private class NonTerminalNode extends UnionNode {
287         public boolean alwaysDrop;
288         public String  name = null;
289         public boolean isDropped(Context cx) { return alwaysDrop; }
290         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep, boolean alwaysDrop) {
291             super(sequences, rep, sep==null?null:(prefix + sep));
292             this.name = prefix + name;
293             this.alwaysDrop = alwaysDrop;
294         }
295         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return cx.get(name); }
296     }
297
298     private class Seq {
299         public boolean alwaysDrop = false;
300         public boolean isDropped(Context cx) {
301             if (alwaysDrop) return true;
302             if (tag!=null) return false;
303             for(int i=0; i<elements.length; i++)
304                 if (!elements[i].isDropped(cx) || ((elements[i] instanceof LiteralNode) && ((LiteralNode)elements[i]).caret))
305                     return false;
306             return true;
307         }
308         HashSet<Seq> and = new HashSet<Seq>();
309         HashSet<Seq> not = new HashSet<Seq>();
310         ElementNode[] elements;
311         ElementNode follow;
312         String tag = null;
313         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
314         public Seq(ElementNode[] elements) { this(elements, true); }
315         public Seq(ElementNode[] el, boolean check) {
316             this.elements = new ElementNode[el.length];
317             System.arraycopy(el, 0, elements, 0, el.length);
318             for(int i=0; i<elements.length; i++) {
319                 if (elements[i]==null)
320                     throw new RuntimeException();
321             }
322             // FIXME: this whole mechanism is sketchy
323             if (check)
324                 for(int i=0; i<elements.length; i++) {
325                     if ((elements[i] instanceof ReferenceNode) && ((ReferenceNode)elements[i]).parenthesized) {
326                         ReferenceNode rn = (ReferenceNode)elements[i];
327                         ElementNode replace = null;
328                         for(int j=0; j<elements.length; j++) {
329                             if (!(elements[j] instanceof ReferenceNode)) continue;
330                             ReferenceNode rn2 = (ReferenceNode)elements[j];
331                             if (rn2.nonTerminal.equals(rn.nonTerminal) && !rn2.parenthesized) {
332                                 if (replace == null) {
333                                     replace = new UnionNode(new Seq(rn2).andnot(new Seq(elements, false)));
334                                 }
335                                 elements[j] = replace;
336                             }
337                         }
338                     }
339                 }
340         }
341         public Atom toAtom(Context cx) {
342             if (elements.length != 1)
343                 throw new Error("you attempted to use ->, **, ++, or a similar character-class"+
344                                 " operator on a [potentially] multicharacter production");
345             return elements[0].toAtom(cx);
346         }
347         public Seq tag(String tag) { this.tag = tag; return this; }
348         public Seq follow(ElementNode follow) { this.follow = follow; return this; }
349         public Seq and(Seq s) { and.add(s); s.alwaysDrop = true; return this; }
350         public Seq andnot(Seq s) { not.add(s); s.alwaysDrop = true; return this; }
351         public Seq separate(ElementNode sep) {
352             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
353             for(int i=0; i<this.elements.length; i++) {
354                 elements[i*2] = this.elements[i];
355                 if (i<this.elements.length-1)
356                     elements[i*2+1] = new DropNode(sep);
357             }
358             this.elements = elements;
359             return this;
360         }
361         public Sequence build(Context cx, Union u, NonTerminalNode cnt, boolean dropall) {
362             Sequence ret = build0(cx, cnt, dropall);
363             for(Seq s : and) ret = ret.and(s.build(cx, null, cnt, true));
364             for(Seq s : not) ret = ret.andnot(s.build(cx, null, cnt, true));
365             if (u!=null) u.add(ret);
366             return ret;
367         }
368         public Sequence build0(Context cx, NonTerminalNode cnt, boolean dropall) {
369             boolean[] drops = new boolean[elements.length];
370             Element[] els = new Element[elements.length];
371             dropall |= isDropped(cx);
372             for(int i=0; i<elements.length; i++) {
373                 if (dropall) drops[i] = true;
374                 else         drops[i] = elements[i].isDropped(cx);
375                 if (elements[i] instanceof LiteralNode && ((LiteralNode)elements[i]).caret) {
376                     if (tag != null) throw new RuntimeException("cannot have multiple tags in a sequence: " + this);
377                     tag = ((LiteralNode)elements[i]).getLiteralTag();
378                 }
379             }
380             Sequence ret = null;
381             int idx = -1;
382             boolean multiNonDrop = false;
383             for(int i=0; i<drops.length; i++)
384                 if (!drops[i])
385                     if (idx==-1) idx = i;
386                     else multiNonDrop = true;
387             for(int i=0; i<elements.length; i++) {
388                 if (!multiNonDrop && i==idx && tag!=null && elements[i] instanceof RepeatNode) {
389                     els[i] = ((RepeatNode)elements[i]).build(cx, cnt, dropall, tag);
390                     tag = null;
391                 } else
392                     els[i] = elements[i].build(cx, cnt, dropall);
393             }
394             if (tag==null && multiNonDrop)
395                 throw new RuntimeException("multiple non-dropped elements in sequence: " + Sequence.create("", els));
396             boolean[] lifts = new boolean[elements.length];
397             for(int i=0; i<elements.length; i++)
398                 lifts[i] = elements[i].isLifted();
399             if (!multiNonDrop) {
400                 if (idx == -1) 
401                     ret = tag==null
402                         ? Sequence.create(illegalTag, els)
403                         : Sequence.create(tag, els, drops, lifts);
404                 else if (tag==null) ret = Sequence.create(els, idx);
405                 else ret = Sequence.create(tag, els, drops, lifts);
406             }
407             if (multiNonDrop)
408                 ret = Sequence.create(tag, els, drops, lifts);
409             if (this.follow != null)
410                 ret = ret.followedBy(this.follow.toAtom(cx));
411             return ret;
412         }
413     }
414
415     private class ReferenceNode extends ElementNode {
416         public String nonTerminal;
417         public boolean parenthesized;
418         public ReferenceNode() { }
419         public ReferenceNode(String nonTerminal) { this(nonTerminal, false); }
420         public ReferenceNode(String nonTerminal, boolean parenthesized) {
421             this.nonTerminal = nonTerminal.indexOf('.')==-1 ? (prefix + nonTerminal) : nonTerminal;
422             this.parenthesized = parenthesized;
423         }
424         public NonTerminalNode resolve(Context cx) {
425             NonTerminalNode ret = cx.grammar.get(nonTerminal);
426             if (ret==null) throw new RuntimeException("undefined nonterminal: " + nonTerminal);
427             return ret;
428         }
429         public Atom toAtom(Context cx) {
430             ElementNode ret = cx.grammar.get(nonTerminal);
431             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
432             return ret.toAtom(cx);
433         }
434         public boolean isDropped(Context cx) { return resolve(cx).isDropped(cx); }
435         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
436             Element ret = cx.get(nonTerminal);
437             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
438             return ret;
439         }
440     }
441
442     private class LiteralNode extends ElementNode {
443         private String string;
444         private final String thePrefix = prefix;
445         private boolean caret;
446         public LiteralNode(String string) { this(string, false); }
447         public LiteralNode(String string, boolean caret) {
448             this.string = string;
449             this.caret = caret;
450         }
451         public String getLiteralTag() { return caret ? thePrefix+string : null; }
452         public String toString() { return "\""+string+"\""; }
453         public boolean isDropped(Context cx) { return true; }
454         public Atom toAtom(Context cx) {
455             if (string.length()!=1) return super.toAtom(cx);
456             Range.Set set = new Range.Set();
457             set.add(string.charAt(0), string.charAt(0));
458             return CharAtom.set(set);
459         }
460         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return CharAtom.string(string); }
461     }
462
463     private class AtomNode extends ElementNode {
464         char[][] ranges;
465         public AtomNode() { this(new char[0][]); }
466         public AtomNode(char[][] ranges) { this.ranges = ranges; }
467         public AtomNode(char[] range) { this.ranges = new char[][] { range }; }
468         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
469         public Atom toAtom(Context cx) {
470             Range.Set set = new Range.Set();
471             for(char[] r : ranges) set.add(r[0], r[1]);
472             return CharAtom.set(set);
473         }
474     }
475
476     private class RepeatNode extends ElementNode {
477         public ElementNode e, sep;
478         public final boolean zero, many, max;
479         public RepeatNode(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
480             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;
481         }
482         public Atom toAtom(Context cx) { return sep==null ? e.toAtom(cx) : super.toAtom(cx); }
483         public boolean isDropped(Context cx) { return e.isDropped(cx); }
484         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
485             Element ret = build(cx, cnt, dropall, illegalTag);
486             String must = "must be tagged unless they appear within a dropped expression or their contents are dropped: ";
487             if (!dropall && !isDropped(cx) && !e.isDropped(cx))
488                 if (!many)      throw new RuntimeException("options (?) " + must + ret);
489                 else if (zero)  throw new RuntimeException("zero-or-more repetitions (*) " + must + ret);
490                 else            throw new RuntimeException("one-or-more repetitions (+) " + must + ret);
491             return ret;
492         }
493         public Element build(Context cx, NonTerminalNode cnt, boolean dropall, Object repeatTag) {
494             return (!max)
495                 ? Repeat.repeat(e.build(cx, null, dropall), zero, many, sep==null ? null : sep.build(cx, null, dropall), repeatTag)
496                 : sep==null
497                 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, repeatTag)
498                 : Repeat.repeatMaximal(e.build(cx, null, dropall), zero, many, sep.toAtom(cx), repeatTag);
499         }
500     }
501
502     private abstract class ElementNodeWrapper extends ElementNode {
503         protected ElementNode _e;
504         public ElementNodeWrapper(ElementNode e) { this._e = e; }
505         public boolean isDropped(Context cx) { return _e.isDropped(cx); }
506         public Atom toAtom(Context cx) { return _e.toAtom(cx); }
507         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return _e.build(cx, cnt, dropall); }
508     }
509
510     private class BacktickNode extends ElementNodeWrapper {
511         public BacktickNode(ElementNode e) { super(e); }
512         public boolean isLifted() { return true; }
513     }
514
515     private class TildeNode extends ElementNodeWrapper {
516         public TildeNode(ElementNode e) { super(e); }
517         public Atom toAtom(Context cx) { return (Atom)((Topology<Character>)_e.toAtom(cx).complement()); }
518         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
519     }
520
521     private class DropNode extends ElementNodeWrapper {
522         public DropNode(ElementNode e) { super(e); }
523         public boolean isDropped(Context cx) { return true; }
524     }
525
526     //////////////////////////////////////////////////////////////////////////////
527
528     public class Context {
529         public HashMap<String,Union> map = new HashMap<String,Union>();
530         public GrammarNode grammar;
531         public Context(Tree t) { }
532         public Context(GrammarNode g) { this.grammar = g; }
533         public Union build() {
534             Union ret = null;
535             for(NonTerminalNode nt : grammar.values()) {
536                 Union u = get(nt.name);
537                 if ("s".equals(nt.name))
538                     ret = u;
539             }
540             return ret;
541         }
542         public Union peek(String name) { return map.get(name); }
543         public void  put(String name, Union u) { map.put(name, u); }
544         public Union get(String name) {
545             Union ret = map.get(name);
546             if (ret != null) return ret;
547             NonTerminalNode nt = grammar.get(name);
548             if (nt==null) {
549                 throw new Error("warning could not find " + name);
550             } else {
551                 ret = new Union(name, false);
552                 map.put(name, ret);
553                 nt.buildIntoPreallocatedUnion(this, nt, nt.isDropped(this), ret);
554             }
555             return ret;
556         }
557
558     }
559
560 }