66e832320af0a84119af556d5bc30d4a35bb74a8
[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 new LabelNode(stringifyChildren(t.child(0)), walkElement(t.child(1)));
100         if (head.equals("::"))  return walkSeq(t.child(1)).tag(walkString(t.child(0)));
101         if (head.equals("...")) return new DropNode(new RepeatNode(new TildeNode(new AtomNode()), null, true,  true,  false));
102
103         if (head.equals("++"))  return new RepeatNode(walkElement(t.child(0)), null,                      false, true,  true);
104         if (head.equals("+"))   return new RepeatNode(walkElement(t.child(0)), null,                      false, true,  false);
105         if (head.equals("++/")) return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)),   false, true,  true);
106         if (head.equals("+/"))  return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)),   false, true,  false);
107         if (head.equals("**"))  return new RepeatNode(walkElement(t.child(0)), null,                      true,  true,  true);
108         if (head.equals("*"))   return new RepeatNode(walkElement(t.child(0)), null,                      true,  true,  false);
109         if (head.equals("**/")) return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)),   true,  true,  true);
110         if (head.equals("*/"))  return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)),   true,  true,  false);
111         if (head.equals("?"))   return new RepeatNode(walkElement(t.child(0)), null,                      true,  false, false);
112
113         if (head.equals("!"))   return new DropNode(walkElement(t.child(0)));
114         if (head.equals("^"))   return new LiteralNode(walkString(t.child(0)), true);
115         if (head.equals("`"))   return new BacktickNode(walkElement(t.child(0)));
116         if (head.equals("Quoted")) return stringifyChildren(t);
117         if (head.equals("Literal")) return new LiteralNode(walkString(t.child(0)));
118         if (head.equals("->")) return walkSeq(t.child(0)).follow(walkElement(t.child(1)));
119         if (head.equals("DropNT")) return new NonTerminalNode(walkString(t.child(0)), (Seq[][])walkChildren(t.child(1)), false, null, true);
120         if (head.equals("=")) return new NonTerminalNode(walkString(t.child(0)), (Seq[][])walk(t.child(2)),
121                                                          true, t.size()==2 ? null : walkString(t.child(1)), false);
122         if (head.equals("&"))   return walkSeq(t.child(0)).and(walkSeq(t.child(1)));
123         if (head.equals("&~"))  return walkSeq(t.child(0)).andnot(walkSeq(t.child(1)));
124         if (head.equals("/"))   return (walkSeq(t.child(0))).separate(walkElement(t.child(1)));
125         if (head.equals("()"))  return new LiteralNode("");
126         if (head.equals("["))   return new AtomNode((char[][])Reflection.rebuild(walkChildren(t), char[][].class));
127         if (head.equals("\\{")) return new DropNode(new AtomNode(new char[] { CharAtom.left, CharAtom.left }));
128         if (head.equals("\\}")) return new DropNode(new AtomNode(new char[] { CharAtom.right, CharAtom.right }));
129         if (head.equals(">>"))  return new DropNode(new AtomNode(new char[] { CharAtom.left, CharAtom.left }));
130         if (head.equals("<<"))  return new DropNode(new AtomNode(new char[] { CharAtom.right, CharAtom.right }));
131         if (head.equals("~"))   return new TildeNode(walkElement(t.child(0)));
132         if (head.equals("~~"))  return new Seq(new RepeatNode(new TildeNode(new AtomNode()), null, true,  true,  false)).andnot(walkSeq(t.child(0)));
133         if (head.equals("Range")) {
134             if (t.size()==2 && ">".equals(t.child(0).head())) return new char[] { CharAtom.left, CharAtom.left };
135             if (t.size()==2 && "<".equals(t.child(0).head())) return new char[] { CharAtom.right, CharAtom.right };
136             if (t.size()==1) return new char[] { unescape(t).charAt(0), unescape(t).charAt(0) };
137             return new char[] { unescape(t).charAt(0), unescape(t).charAt(1) };
138         }
139         if (head.equals("\"\"")) return "";
140         if (head.equals("\n"))   return "\n";
141         if (head.equals("\t"))   return "\t";
142         if (head.equals("\r"))   return "\r";
143         if (head.equals("SubGrammar")) return GrammarAST.buildFromAST(t.child(0), "s", resolver);
144         if (head.equals("NonTerminal"))
145             return new NonTerminalNode(walkString(t.child(0)),
146                                        (Seq[][])walkChildren(t.child(1)), false, null, false);
147         if (head.equals("Colons")) {
148             String tag = walkString(t.child(0));
149             Seq[][] seqs = (Seq[][])walk(t.child(1));
150             for(Seq[] seq : seqs)
151                 for(int i=0; i<seq.length; i++)
152                     seq[i] = seq[i].tag(tag);
153             return new NonTerminalNode(tag, seqs, false, null, false);
154         }
155         if (head.equals("#import")) {
156             if (resolver != null) {
157                 String fileName = (String)stringifyChildren(t.child(0));
158                 try {
159                     String newPrefix = t.size()<2 ? "" : (walkString(t.child(1))+".");
160                     InputStream fis = resolver.getImportStream(fileName);
161                     if (fis==null)
162                         throw new RuntimeException("unable to find #include file \""+fileName+"\"");
163                     Tree tr = new CharParser(getMetaGrammar()).parse(fis).expand1();
164                     return (GrammarNode)new GrammarAST(resolver, newPrefix).walk(tr);
165                 } catch (Exception e) {
166                     throw new RuntimeException("while parsing " + fileName, e);
167                 }
168             } else {
169                 throw new RuntimeException("no resolver given");
170             }
171         }
172         throw new RuntimeException("unknown head: \"" + head + "\" => " + (head.equals("...")));
173     }
174
175     
176     // Nodes //////////////////////////////////////////////////////////////////////////////
177
178     /** Root node of a grammar's AST; a set of named nonterminals */
179     private class GrammarNode extends HashMap<String,NonTerminalNode> {
180         public GrammarNode(NonTerminalNode[] nonterminals) {
181             for(NonTerminalNode nt : nonterminals) {
182                 if (nt==null) continue;
183                 if (this.get(nt.name)!=null)
184                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
185                 this.put(nt.name, nt);
186             }
187         }
188         public  GrammarNode(Object[] nt) { add(nt); }
189         private void add(Object o) {
190             if (o==null) return;
191             else if (o instanceof Object[]) for(Object o2 : (Object[])o) add(o2);
192             else if (o instanceof NonTerminalNode) {
193                 NonTerminalNode nt = (NonTerminalNode)o;
194                 if (this.get(nt.name)!=null)
195                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
196                 this.put(nt.name, nt);
197             }
198             else if (o instanceof GrammarNode)
199                 for(NonTerminalNode n : ((GrammarNode)o).values())
200                     add(n);
201         }
202         public String toString() {
203             String ret = "[ ";
204             for(NonTerminalNode nt : values()) ret += nt + ", ";
205             return ret + " ]";
206         }
207         public Union build(String rootNonterminal) {
208             Context cx = new Context(this);
209             Union u = null;
210             for(GrammarAST.NonTerminalNode nt : values())
211                 if (nt.name.equals(rootNonterminal))
212                     return (Union)cx.get(nt.name);
213             return null;
214         }
215     }
216
217     /** a NonTerminal is always a union at the top level */
218     private class NonTerminalNode {
219         public final boolean alwaysDrop;
220         public final String  name;
221         public final ElementNode elementNode;
222         public final UnionNode unionNode;
223         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep, boolean alwaysDrop) {
224             this.name = prefix + name;
225             this.alwaysDrop = alwaysDrop;
226             this.unionNode = new UnionNode(sequences, rep, sep==null?null:(prefix + sep));
227             this.elementNode = alwaysDrop ? new DropNode(unionNode) : unionNode;
228         }
229         public boolean isDropped(Context cx) { return alwaysDrop; }
230         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return cx.get(name); }
231         public ElementNode getElementNode() { return elementNode; }
232         public UnionNode   getUnionNode() { return unionNode; }
233     }
234
235     /** a sequence */
236     private class Seq {
237         /** elements of the sequence */
238         ElementNode[] elements;
239         /** follow-set, if explicit */
240         ElementNode follow;
241         /** tag to add when building the AST */
242         String tag = null;
243         /** positive conjuncts */
244         HashSet<Seq> and = new HashSet<Seq>();
245         /** negative conjuncts */
246         HashSet<Seq> not = new HashSet<Seq>();
247         public boolean alwaysDrop = false;
248         public boolean isDropped(Context cx) {
249             if (alwaysDrop) return true;
250             if (tag!=null) return false;
251             for(int i=0; i<elements.length; i++)
252                 if (!elements[i].isDropped(cx) || ((elements[i] instanceof LiteralNode) && ((LiteralNode)elements[i]).caret))
253                     return false;
254             return true;
255         }
256         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
257         public Seq(ElementNode[] elements) { this(elements, true); }
258         public Seq(ElementNode[] el, boolean check) {
259             this.elements = new ElementNode[el.length];
260             System.arraycopy(el, 0, elements, 0, el.length);
261             for(int i=0; i<elements.length; i++) {
262                 if (elements[i]==null)
263                     throw new RuntimeException();
264             }
265             // FIXME: this whole mechanism is sketchy
266             if (check)
267                 for(int i=0; i<elements.length; i++) {
268                     if ((elements[i] instanceof ReferenceNode) && ((ReferenceNode)elements[i]).parenthesized) {
269                         ReferenceNode rn = (ReferenceNode)elements[i];
270                         ElementNode replace = null;
271                         for(int j=0; j<elements.length; j++) {
272                             if (!(elements[j] instanceof ReferenceNode)) continue;
273                             ReferenceNode rn2 = (ReferenceNode)elements[j];
274                             if (rn2.nonTerminal.equals(rn.nonTerminal) && !rn2.parenthesized) {
275                                 if (replace == null) {
276                                     replace = new UnionNode(new Seq(rn2).andnot(new Seq(elements, false)));
277                                 }
278                                 elements[j] = replace;
279                             }
280                         }
281                     }
282                 }
283         }
284         public Atom toAtom(Context cx) {
285             if (elements.length != 1)
286                 throw new Error("you attempted to use ->, **, ++, or a similar character-class"+
287                                 " operator on a [potentially] multicharacter production");
288             return elements[0].toAtom(cx);
289         }
290         public Seq tag(String tag) { this.tag = tag; return this; }
291         public Seq follow(ElementNode follow) { this.follow = follow; return this; }
292         public Seq and(Seq s) { and.add(s); s.alwaysDrop = true; return this; }
293         public Seq andnot(Seq s) { not.add(s); s.alwaysDrop = true; return this; }
294         public Seq separate(ElementNode sep) {
295             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
296             for(int i=0; i<this.elements.length; i++) {
297                 elements[i*2] = this.elements[i];
298                 if (i<this.elements.length-1)
299                     elements[i*2+1] = new DropNode(sep);
300             }
301             this.elements = elements;
302             return this;
303         }
304         public Sequence build(Context cx, Union u, NonTerminalNode cnt, boolean dropall) {
305             Sequence ret = build0(cx, cnt, dropall);
306             for(Seq s : and) ret = ret.and(s.build(cx, null, cnt, true));
307             for(Seq s : not) ret = ret.andnot(s.build(cx, null, cnt, true));
308             if (u!=null) u.add(ret);
309             return ret;
310         }
311         public Sequence build0(Context cx, NonTerminalNode cnt, boolean dropall) {
312             boolean[] drops = new boolean[elements.length];
313             Element[] els = new Element[elements.length];
314             dropall |= isDropped(cx);
315             for(int i=0; i<elements.length; i++) {
316                 if (dropall) drops[i] = true;
317                 else         drops[i] = elements[i].isDropped(cx);
318                 if (elements[i] instanceof LiteralNode && ((LiteralNode)elements[i]).caret) {
319                     if (tag != null) throw new RuntimeException("cannot have multiple tags in a sequence: " + this);
320                     tag = ((LiteralNode)elements[i]).getLiteralTag();
321                 }
322             }
323             Sequence ret = null;
324             int idx = -1;
325             boolean multiNonDrop = false;
326             for(int i=0; i<drops.length; i++)
327                 if (!drops[i])
328                     if (idx==-1) idx = i;
329                     else multiNonDrop = true;
330             for(int i=0; i<elements.length; i++) {
331                 if (!multiNonDrop && i==idx && tag!=null && elements[i] instanceof RepeatNode) {
332                     els[i] = ((RepeatNode)elements[i]).build(cx, cnt, dropall, tag);
333                     tag = null;
334                 } else
335                     els[i] = elements[i].build(cx, cnt, dropall);
336             }
337             if (tag==null && multiNonDrop)
338                 throw new RuntimeException("multiple non-dropped elements in sequence: " + Sequence.create("", els));
339             boolean[] lifts = new boolean[elements.length];
340             for(int i=0; i<elements.length; i++)
341                 lifts[i] = elements[i].isLifted();
342             if (!multiNonDrop) {
343                 if (idx == -1) 
344                     ret = tag==null
345                         ? Sequence.create(illegalTag, els)
346                         : Sequence.create(tag, els, drops, lifts);
347                 else if (tag==null) ret = Sequence.create(els, idx);
348                 else ret = Sequence.create(tag, els, drops, lifts);
349             }
350             if (multiNonDrop)
351                 ret = Sequence.create(tag, els, drops, lifts);
352             if (this.follow != null)
353                 ret = ret.followedBy(this.follow.toAtom(cx));
354             return ret;
355         }
356     }
357
358     /** a node in the AST which is resolved into an Element */
359     private abstract class ElementNode {
360         /** the field name to be used when synthesizing AST classes; null if none suggested */
361         public String getFieldName() { return null; }
362         public boolean isLifted() { return false; }
363         public boolean isDropped(Context cx) { return false; }
364         public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom: " + this); }
365         public abstract Element build(Context cx, NonTerminalNode cnt, boolean dropall);
366     }
367
368     /** a union, produced by a ( .. | .. | .. ) construct */
369     private class UnionNode extends ElementNode {
370
371         /** each component of a union is a sequence */
372         public Seq[][] sequences;
373
374         /** if the union is a NonTerminal specified as Foo*=..., this is true */
375         public boolean rep;
376
377         /** if the union is a NonTerminal specified as Foo* /ws=..., then this is "ws" */
378         public String  sep = null;
379
380         public UnionNode(Seq seq) { this(new Seq[][] { new Seq[] { seq } }); }
381         public UnionNode(Seq[][] sequences) { this(sequences, false, null); }
382         public UnionNode(Seq[][] sequences, boolean rep, String sep) {
383             this.sequences = sequences;
384             this.rep = rep;
385             this.sep = sep;
386         }
387         public String getFieldName() { return null; }
388         public boolean isLifted() { return false; }
389         public boolean isDropped(Context cx) {
390             for(Seq[] seqs : sequences)
391                 for(Seq seq : seqs)
392                     if (!seq.isDropped(cx))
393                         return false;
394             return true;
395         }
396         public Atom toAtom(Context cx) {
397             Atom ret = null;
398             for(Seq[] ss : sequences)
399                 for(Seq s : ss)
400                     ret = ret==null ? s.toAtom(cx) : (Atom)ret.union(s.toAtom(cx));
401             return ret;
402         }
403
404         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
405             return buildIntoPreallocatedUnion(cx, cnt, dropall, new Union(null, false)); }
406         public Element buildIntoPreallocatedUnion(Context cx, NonTerminalNode cnt, boolean dropall, Union u) {
407             Union urep = null;
408             if (rep) {
409                 urep = new Union(null, false);
410                 urep.add(Sequence.create(cnt.name, new Element[0]));
411                 urep.add(sep==null
412                          ? Sequence.create(new Element[] { u }, 0)
413                          : Sequence.create(new Element[] { cx.get(sep), u }, 1));
414             }
415             HashSet<Sequence> bad2 = new HashSet<Sequence>();
416             for(int i=0; i<sequences.length; i++) {
417                 Seq[] group = sequences[i];
418                 Union u2 = new Union(null, false);
419                 if (sequences.length==1) u2 = u;
420                 for(int j=0; j<group.length; j++)
421                     if (!rep)
422                         group[j].build(cx, u2, cnt, dropall);
423                     else {
424                         Union u3 = new Union(null, false);
425                         group[j].build(cx, u3, cnt, dropall);
426                         Sequence s = Sequence.create(cnt.name,
427                                                      new Element[] { u3, urep },
428                                                      new boolean[] { false, false },
429                                                      new boolean[] { false, true});
430                         u2.add(s);
431                     }
432                 if (sequences.length==1) break;
433                 Sequence seq = Sequence.create(u2);
434                 for(Sequence s : bad2) seq = seq.andnot(s);
435                 u.add(seq);
436                 bad2.add(Sequence.create(u2));
437             }
438             return u;
439         }
440     }
441
442     /** reference to a NonTerminal by name */
443     private class ReferenceNode extends ElementNode {
444         public String nonTerminal;
445         public boolean parenthesized;
446         public ReferenceNode() { }
447         public ReferenceNode(String nonTerminal) { this(nonTerminal, false); }
448         public ReferenceNode(String nonTerminal, boolean parenthesized) {
449             this.nonTerminal = nonTerminal.indexOf('.')==-1 ? (prefix + nonTerminal) : nonTerminal;
450             this.parenthesized = parenthesized;
451         }
452         public NonTerminalNode resolve(Context cx) {
453             NonTerminalNode ret = cx.grammar.get(nonTerminal);
454             if (ret==null) throw new RuntimeException("undefined nonterminal: " + nonTerminal);
455             return ret;
456         }
457         public Atom toAtom(Context cx) {
458             ElementNode ret = cx.grammar.get(nonTerminal).getElementNode();
459             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
460             return ret.toAtom(cx);
461         }
462         public boolean isDropped(Context cx) { return resolve(cx).isDropped(cx); }
463         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
464             Element ret = cx.get(nonTerminal);
465             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
466             return ret;
467         }
468         public String getFieldName() { return StringUtil.uncapitalize(nonTerminal); }
469     }
470
471     /** a literal string */
472     private class LiteralNode extends ElementNode {
473         private String string;
474         private final String thePrefix = prefix;
475         private boolean caret;
476         public LiteralNode(String string) { this(string, false); }
477         public LiteralNode(String string, boolean caret) {
478             this.string = string;
479             this.caret = caret;
480         }
481         public String getLiteralTag() { return caret ? thePrefix+string : null; }
482         public String toString() { return "\""+string+"\""; }
483         public boolean isDropped(Context cx) { return true; }
484         public Atom toAtom(Context cx) {
485             if (string.length()!=1) return super.toAtom(cx);
486             Range.Set set = new Range.Set();
487             set.add(string.charAt(0), string.charAt(0));
488             return CharAtom.set(set);
489         }
490         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return CharAtom.string(string); }
491     }
492
493     /** an atom (usually a character class) */
494     private class AtomNode extends ElementNode {
495         char[][] ranges;
496         public AtomNode() { this(new char[0][]); }
497         public AtomNode(char[][] ranges) { this.ranges = ranges; }
498         public AtomNode(char[] range) { this.ranges = new char[][] { range }; }
499         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
500         public Atom toAtom(Context cx) {
501             Range.Set set = new Range.Set();
502             for(char[] r : ranges) set.add(r[0], r[1]);
503             return CharAtom.set(set);
504         }
505     }
506
507     /** a repetition */
508     private class RepeatNode extends ElementNode {
509         public ElementNode e, sep;
510         public final boolean zero, many, max;
511         public RepeatNode(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
512             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;
513         }
514         public Atom toAtom(Context cx) { return sep==null ? e.toAtom(cx) : super.toAtom(cx); }
515         public boolean isDropped(Context cx) { return e.isDropped(cx); }
516         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
517             Element ret = build(cx, cnt, dropall, illegalTag);
518             String must = "must be tagged unless they appear within a dropped expression or their contents are dropped: ";
519             if (!dropall && !isDropped(cx) && !e.isDropped(cx))
520                 if (!many)      throw new RuntimeException("options (?) " + must + ret);
521                 else if (zero)  throw new RuntimeException("zero-or-more repetitions (*) " + must + ret);
522                 else            throw new RuntimeException("one-or-more repetitions (+) " + must + ret);
523             return ret;
524         }
525         public Element build(Context cx, NonTerminalNode cnt, boolean dropall, Object repeatTag) {
526             return (!max)
527                 ? Repeat.repeat(e.build(cx, null, dropall), zero, many, sep==null ? null : sep.build(cx, null, dropall), repeatTag)
528                 : sep==null
529                 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, repeatTag)
530                 : Repeat.repeatMaximal(e.build(cx, null, dropall), zero, many, sep.toAtom(cx), repeatTag);
531         }
532     }
533
534     /** helper class for syntactic constructs that wrap another construct */
535     private abstract class ElementNodeWrapper extends ElementNode {
536         protected ElementNode _e;
537         public ElementNodeWrapper(ElementNode e) { this._e = e; }
538         public boolean isDropped(Context cx) { return _e.isDropped(cx); }
539         public Atom toAtom(Context cx) { return _e.toAtom(cx); }
540         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return _e.build(cx, cnt, dropall); }
541         public String getFieldName() { return _e.getFieldName(); }
542     }
543
544     /** a backtick node indicating that, when building the AST, the node's children should be inserted here */
545     private class BacktickNode extends ElementNodeWrapper {
546         public BacktickNode(ElementNode e) { super(e); }
547         public boolean isLifted() { return true; }
548     }
549
550     /** negation */
551     private class TildeNode extends ElementNodeWrapper {
552         public TildeNode(ElementNode e) { super(e); }
553         public Atom toAtom(Context cx) { return (Atom)((Topology<Character>)_e.toAtom(cx).complement()); }
554         public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
555     }
556
557     private class DropNode extends ElementNodeWrapper {
558         public DropNode(ElementNode e) { super(e); }
559         public boolean isDropped(Context cx) { return true; }
560     }
561
562     /** provides a label on the fields of a Seq */
563     private class LabelNode extends ElementNodeWrapper {
564         public final String label;
565         public LabelNode(String label, ElementNode e) { super(e); this.label = label; }
566         public String getFieldName() { return label; }
567     }
568
569     //////////////////////////////////////////////////////////////////////////////
570
571     public class Context {
572         public HashMap<String,Union> map = new HashMap<String,Union>();
573         public GrammarNode grammar;
574         public Context(Tree t) { }
575         public Context(GrammarNode g) { this.grammar = g; }
576         public Union build() {
577             Union ret = null;
578             for(NonTerminalNode nt : grammar.values()) {
579                 Union u = get(nt.name);
580                 if ("s".equals(nt.name))
581                     ret = u;
582             }
583             return ret;
584         }
585         public Union peek(String name) { return map.get(name); }
586         public void  put(String name, Union u) { map.put(name, u); }
587         public Union get(String name) {
588             Union ret = map.get(name);
589             if (ret != null) return ret;
590             NonTerminalNode nt = grammar.get(name);
591             if (nt==null) {
592                 throw new Error("warning could not find " + name);
593             } else {
594                 ret = new Union(name, false);
595                 map.put(name, ret);
596                 nt.getUnionNode().buildIntoPreallocatedUnion(this, nt, nt.isDropped(this), ret);
597             }
598             return ret;
599         }
600
601     }
602
603 }