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