1 // Copyright 2006-2007 all rights reserved; see LICENSE file for BSD-style license
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.*;
9 import java.lang.annotation.*;
10 import java.lang.reflect.*;
14 * The inner classes of this class represent nodes in the Abstract
15 * Syntax Tree of a grammar.
17 public class GrammarAST {
20 * Create a grammar from a parse tree and binding resolver
22 * @param t a tree produced by parsing a grammar using the metagrammar
23 * @param s the name of the "start symbol"
24 * @param gbr a GrammarBindingResolver that resolves grammatical reductions into tree-node-heads
26 public static Union buildFromAST(Tree grammarAST, String startingNonterminal, File[] includes) {
27 return new GrammarAST(includes, "").buildGrammar(grammarAST, startingNonterminal);
30 private static Object illegalTag = ""; // this is the tag that should never appear in the non-dropped output FIXME
32 // Instance //////////////////////////////////////////////////////////////////////////////
34 private final String prefix;
35 private final File[] includes;
37 public GrammarAST(File[] includes, String prefix) {
39 this.includes = includes;
42 // Methods //////////////////////////////////////////////////////////////////////////////
44 private Union buildGrammar(Tree t, String rootNonTerminal) {
46 if (o instanceof Union) return (Union)o;
47 return ((GrammarAST.GrammarNode)o).build(rootNonTerminal);
50 private Object[] walkChildren(Tree t) {
51 Object[] ret = new Object[t.size()];
52 for(int i=0; i<ret.length; i++)
53 ret[i] = walk(t.child(i));
54 return Reflection.lub(ret);
56 private static String stringifyChildren(Tree t) {
57 StringBuffer sb = new StringBuffer();
58 for(int i=0; i<t.size(); i++) {
59 sb.append(t.child(i).head());
60 sb.append(stringifyChildren(t.child(i)));
64 private static String unescape(Tree t) {
65 StringBuffer sb = new StringBuffer();
66 for(int i=0; i<t.size(); i++)
67 sb.append(t.child(i).head()+stringifyChildren(t.child(i)));
71 private ElementNode walkElement(Tree t) { return (ElementNode)walk(t); }
72 private String walkString(Tree t) { return (String)walk(t); }
73 private Seq walkSeq(Tree t) { return (Seq)walk(t); }
74 private Object walk(Tree t) {
75 String head = (String)t.head();
76 while(head.indexOf('.') > 0)
77 head = head.substring(head.indexOf('.')+1);
78 if (head==null) throw new RuntimeException("head is null: " + t);
79 if (head.equals("|")) return walkChildren(t);
80 if (head.equals("RHS")) return walkChildren(t);
81 if (head.equals("Grammar")) return new GrammarNode(walkChildren(t));
82 if (head.equals("(")) return new UnionNode((Seq[][])walkChildren(t.child(0)));
83 if (head.equals("Word")) return stringifyChildren(t);
84 if (head.equals("Elements")) return new Seq((ElementNode[])Reflection.rebuild(walkChildren(t), ElementNode[].class));
85 if (head.equals("NonTerminalReference")) return new ReferenceNode(stringifyChildren(t.child(0)));
86 if (head.equals(")")) return new ReferenceNode(stringifyChildren(t.child(0)), true);
87 if (head.equals("{")) return new BracedNode(walkSeq(t.child(0)));
88 if (head.equals("::")) return walkSeq(t.child(1)).tag(walkString(t.child(0)));
89 if (head.equals("...")) return new DropNode(new RepeatNode(new TildeNode(new AtomNode()), null, true, true, false));
91 if (head.equals("++")) return new RepeatNode(walkElement(t.child(0)), null, false, true, true);
92 if (head.equals("+")) return new RepeatNode(walkElement(t.child(0)), null, false, true, false);
93 if (head.equals("++/")) return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)), false, true, true);
94 if (head.equals("+/")) return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)), false, true, false);
95 if (head.equals("**")) return new RepeatNode(walkElement(t.child(0)), null, true, true, true);
96 if (head.equals("*")) return new RepeatNode(walkElement(t.child(0)), null, true, true, false);
97 if (head.equals("**/")) return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)), true, true, true);
98 if (head.equals("*/")) return new RepeatNode(walkElement(t.child(0)), walkElement(t.child(1)), true, true, false);
99 if (head.equals("?")) return new RepeatNode(walkElement(t.child(0)), null, true, false, false);
101 if (head.equals("!")) return new DropNode(walkElement(t.child(0)));
102 if (head.equals("^")) return new LiteralNode(walkString(t.child(0)), true);
103 if (head.equals("`")) return walkElement(t.child(0)).lifted();
104 if (head.equals("Quoted")) return stringifyChildren(t);
105 if (head.equals("Literal")) return new LiteralNode(walkString(t.child(0)));
106 if (head.equals("->")) return walkSeq(t.child(0)).follow(walkElement(t.child(1)));
107 if (head.equals("DropNT")) return new NonTerminalNode(walkString(t.child(0)), (Seq[][])walkChildren(t.child(1)), false, null, true);
108 if (head.equals("=")) return new NonTerminalNode(walkString(t.child(0)), (Seq[][])walk(t.child(2)),
109 true, t.size()==2 ? null : walkString(t.child(1)), false);
110 if (head.equals("&")) return and2(walkSeq(t.child(0)), walkSeq(t.child(1)));
111 if (head.equals("&~")) return andnot2(walkSeq(t.child(0)), walkSeq(t.child(1)));
112 if (head.equals("/")) return (walkSeq(t.child(0))).separate(walkElement(t.child(1)));
113 if (head.equals("()")) return new LiteralNode("");
114 if (head.equals("[")) return new AtomNode((char[][])Reflection.rebuild(walkChildren(t), char[][].class));
115 if (head.equals("\\{")) return new DropNode(new AtomNode(new char[] { CharAtom.left, CharAtom.left }));
116 if (head.equals("\\}")) return new DropNode(new AtomNode(new char[] { CharAtom.right, CharAtom.right }));
117 if (head.equals(">>")) return new DropNode(new AtomNode(new char[] { CharAtom.left, CharAtom.left }));
118 if (head.equals("<<")) return new DropNode(new AtomNode(new char[] { CharAtom.right, CharAtom.right }));
119 if (head.equals("~")) return new TildeNode(walkElement(t.child(0)));
120 if (head.equals("~~")) return new Seq(new RepeatNode(new TildeNode(new AtomNode()), null, true, true, false)).andnot(walkSeq(t.child(0)));
121 if (head.equals("Range")) {
122 if (t.size()==2 && ">".equals(t.child(0).head())) return new char[] { CharAtom.left, CharAtom.left };
123 if (t.size()==2 && "<".equals(t.child(0).head())) return new char[] { CharAtom.right, CharAtom.right };
124 if (t.size()==1) return new char[] { unescape(t).charAt(0), unescape(t).charAt(0) };
125 return new char[] { unescape(t).charAt(0), unescape(t).charAt(1) };
127 if (head.equals("\"\"")) return "";
128 if (head.equals("\n")) return "\n";
129 if (head.equals("\r")) return "\r";
130 if (head.equals("SubGrammar")) return GrammarAST.buildFromAST(t.child(0), "s", includes);
131 if (head.equals("NonTerminal"))
132 return new NonTerminalNode(walkString(t.child(0)),
133 (Seq[][])walkChildren(t.child(1)), false, null, false);
134 if (head.equals("Colons")) {
135 String tag = walkString(t.child(0));
136 Seq[][] seqs = (Seq[][])walk(t.child(1));
137 for(Seq[] seq : seqs)
138 for(int i=0; i<seq.length; i++)
139 seq[i] = seq[i].tag(tag);
140 return new NonTerminalNode(tag, seqs, false, null, false);
142 if (head.equals("#import")) {
143 String fileName = (String)stringifyChildren(t.child(0));
144 for(File f : includes) {
145 File file = new File(f.getAbsolutePath()+File.separatorChar+fileName);
146 if (!file.exists()) continue;
148 String newPrefix = t.size()<2 ? "" : (walkString(t.child(1))+".");
149 FileInputStream fis = new FileInputStream(file);
150 Tree tr = new CharParser(MetaGrammar.newInstance()).parse(fis).expand1();
151 return (GrammarNode)new GrammarAST(includes, newPrefix).walk(tr);
152 } catch (Exception e) {
153 throw new RuntimeException("while parsing " + file, e);
156 throw new RuntimeException("unable to find #include file \""+fileName+"\"");
158 throw new RuntimeException("unknown head: \"" + head + "\" => " + (head.equals("...")));
162 // Nodes //////////////////////////////////////////////////////////////////////////////
164 /** Root node of a grammar's AST; a set of named nonterminals */
165 private class GrammarNode extends HashMap<String,NonTerminalNode> {
166 public GrammarNode(NonTerminalNode[] nonterminals) {
167 for(NonTerminalNode nt : nonterminals) {
168 if (nt==null) continue;
169 if (this.get(nt.name)!=null)
170 throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
171 this.put(nt.name, nt);
174 public GrammarNode(Object[] nt) { add(nt); }
175 private void add(Object o) {
177 else if (o instanceof Object[]) for(Object o2 : (Object[])o) add(o2);
178 else if (o instanceof NonTerminalNode) {
179 NonTerminalNode nt = (NonTerminalNode)o;
180 if (this.get(nt.name)!=null)
181 throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
182 this.put(nt.name, nt);
184 else if (o instanceof GrammarNode)
185 for(NonTerminalNode n : ((GrammarNode)o).values())
188 public String toString() {
190 for(NonTerminalNode nt : values()) ret += nt + ", ";
193 public Union build(String rootNonterminal) {
194 Context cx = new Context(this);
196 for(GrammarAST.NonTerminalNode nt : values())
197 if (nt.name.equals(rootNonterminal))
198 return (Union)cx.get(nt.name);
203 private class UnionNode extends ElementNode {
204 public Seq[][] sequences;
205 public String sep = null;
207 public UnionNode(Seq seq) { this(new Seq[][] { new Seq[] { seq } }); }
208 public UnionNode(Seq[][] sequences) { this(sequences, false, null); }
209 public UnionNode(Seq[][] sequences, boolean rep, String sep) {
210 this.sequences = sequences;
214 public boolean drop(Context cx) {
215 for(Seq[] seqs : sequences)
221 public Atom toAtom(Context cx) {
223 for(Seq[] ss : sequences)
225 ret = ret==null ? s.toAtom(cx) : (Atom)ret.union(s.toAtom(cx));
228 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
229 return buildIntoPreallocatedUnion(cx, cnt, dropall, new Union(null, false)); }
230 public Element buildIntoPreallocatedUnion(Context cx, NonTerminalNode cnt, boolean dropall, Union u) {
233 urep = new Union(null, false);
234 urep.add(Sequence.create(cnt.name, new Element[0]));
236 ? Sequence.create(new Element[] { u }, 0)
237 : Sequence.create(new Element[] { cx.get(sep), u }, 1));
239 HashSet<Sequence> bad2 = new HashSet<Sequence>();
240 for(int i=0; i<sequences.length; i++) {
241 Seq[] group = sequences[i];
242 Union u2 = new Union(null, false);
243 if (sequences.length==1) u2 = u;
244 for(int j=0; j<group.length; j++)
246 group[j].build(cx, u2, cnt, dropall);
248 Union u3 = new Union(null, false);
249 group[j].build(cx, u3, cnt, dropall);
250 Sequence s = Sequence.create(cnt.name,
251 new Element[] { u3, urep },
252 new boolean[] { false, false },
253 new boolean[] { false, true});
256 if (sequences.length==1) break;
257 Sequence seq = Sequence.create(u2);
258 for(Sequence s : bad2) seq = seq.andnot(s);
260 bad2.add(Sequence.create(u2));
266 private class NonTerminalNode extends UnionNode {
267 public boolean alwaysDrop;
268 public String name = null;
269 public boolean drop(Context cx) { return alwaysDrop; }
270 public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep, boolean alwaysDrop) {
271 super(sequences, rep, sep==null?null:(prefix + sep));
272 this.name = prefix + name;
273 this.alwaysDrop = alwaysDrop;
275 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return cx.get(name); }
279 public boolean alwaysDrop = false;
280 public boolean drop(Context cx) {
281 if (alwaysDrop) return true;
282 if (tag!=null) return false;
283 for(int i=0; i<elements.length; i++)
284 if (!elements[i].drop(cx))
288 HashSet<Seq> and = new HashSet<Seq>();
289 HashSet<Seq> not = new HashSet<Seq>();
290 ElementNode[] elements;
293 public Seq(ElementNode e) { this(new ElementNode[] { e }); }
294 public Seq(ElementNode[] elements) { this(elements, true); }
295 public Seq(ElementNode[] el, boolean check) {
296 this.elements = new ElementNode[el.length];
297 System.arraycopy(el, 0, elements, 0, el.length);
298 for(int i=0; i<elements.length; i++) {
299 if (elements[i]==null)
300 throw new RuntimeException();
301 elements[i].ownerSeq = this;
303 // FIXME: this whole mechanism is sketchy
305 for(int i=0; i<elements.length; i++) {
306 if ((elements[i] instanceof ReferenceNode) && ((ReferenceNode)elements[i]).parenthesized) {
307 ReferenceNode rn = (ReferenceNode)elements[i];
308 ElementNode replace = null;
309 for(int j=0; j<elements.length; j++) {
310 if (!(elements[j] instanceof ReferenceNode)) continue;
311 ReferenceNode rn2 = (ReferenceNode)elements[j];
312 if (rn2.nonTerminal.equals(rn.nonTerminal) && !rn2.parenthesized) {
313 if (replace == null) {
314 replace = new UnionNode(new Seq(rn2).andnot(new Seq(elements, false)));
316 elements[j] = replace;
322 public Atom toAtom(Context cx) {
323 if (elements.length != 1)
324 throw new Error("you attempted to use ->, **, ++, or a similar character-class"+
325 " operator on a [potentially] multicharacter production");
326 return elements[0].toAtom(cx);
328 public Seq tag(String tag) { this.tag = tag; return this; }
329 public Seq follow(ElementNode follow) { this.follow = follow; return this; }
330 public Seq and(Seq s) { and.add(s); return this; }
331 public Seq andnot(Seq s) { not.add(s); return this; }
332 public Seq separate(ElementNode sep) {
333 ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
334 for(int i=0; i<this.elements.length; i++) {
335 elements[i*2] = this.elements[i];
336 if (i<this.elements.length-1)
337 elements[i*2+1] = new DropNode(sep);
339 this.elements = elements;
342 public Sequence build(Context cx, Union u, NonTerminalNode cnt, boolean dropall) {
343 Sequence ret = build0(cx, cnt, dropall);
344 for(Seq s : and) ret = ret.and(s.build(cx, null, cnt, true));
345 for(Seq s : not) ret = ret.andnot(s.build(cx, null, cnt, true));
346 if (u!=null) u.add(ret);
349 public Sequence build0(Context cx, NonTerminalNode cnt, boolean dropall) {
350 boolean[] drops = new boolean[elements.length];
351 Element[] els = new Element[elements.length];
353 for(int i=0; i<elements.length; i++) {
354 if (dropall) drops[i] = true;
355 else drops[i] = elements[i].drop(cx);
356 if (elements[i].getOwnerTag() != null)
357 tag = elements[i].getOwnerTag();
361 boolean multiNonDrop = false;
362 for(int i=0; i<drops.length; i++)
364 if (idx==-1) idx = i;
365 else multiNonDrop = true;
366 for(int i=0; i<elements.length; i++) {
367 if (!multiNonDrop && i==idx && tag!=null && elements[i] instanceof RepeatNode) {
368 els[i] = ((RepeatNode)elements[i]).build(cx, cnt, dropall, tag);
371 els[i] = elements[i].build(cx, cnt, dropall);
373 if (tag==null && multiNonDrop)
374 throw new RuntimeException("multiple non-dropped elements in sequence: " + Sequence.create("", els));
375 boolean[] lifts = new boolean[elements.length];
376 for(int i=0; i<elements.length; i++)
377 lifts[i] = elements[i].lifted;
381 ? Sequence.create(illegalTag, els)
382 : Sequence.create(tag, els, drops, lifts);
383 else if (tag==null) ret = Sequence.create(els, idx);
384 else ret = Sequence.create(tag, els, drops, lifts);
387 ret = Sequence.create(tag, els, drops, lifts);
388 if (this.follow != null)
389 ret = ret.followedBy(this.follow.toAtom(cx));
394 private class ReferenceNode extends ElementNode {
395 public String nonTerminal;
396 public boolean parenthesized;
397 public ReferenceNode() { }
398 public ReferenceNode(String nonTerminal) { this(nonTerminal, false); }
399 public ReferenceNode(String nonTerminal, boolean parenthesized) {
400 this.nonTerminal = nonTerminal.indexOf('.')==-1 ? (prefix + nonTerminal) : nonTerminal;
401 this.parenthesized = parenthesized;
403 public NonTerminalNode resolve(Context cx) {
404 NonTerminalNode ret = cx.grammar.get(nonTerminal);
405 if (ret==null) throw new RuntimeException("undefined nonterminal: " + nonTerminal);
408 public Atom toAtom(Context cx) {
409 ElementNode ret = cx.grammar.get(nonTerminal);
410 if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
411 return ret.toAtom(cx);
413 public boolean drop(Context cx) { return resolve(cx).drop(cx); }
414 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
416 if (!this.nonTerminal.startsWith(prefix))
417 nonTerminal = prefix + nonTerminal;
419 Element ret = cx.get(nonTerminal);
420 if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
425 private class LiteralNode extends ElementNode {
426 private String string;
427 private final String thePrefix = prefix;
428 private boolean caret;
429 public LiteralNode(String string) { this(string, false); }
430 public LiteralNode(String string, boolean caret) {
431 this.string = string;
434 public String getOwnerTag() { return caret ? thePrefix+string : super.getOwnerTag(); }
435 public String toString() { return "\""+string+"\""; }
436 public boolean drop(Context cx) { return true; }
437 public Atom toAtom(Context cx) {
438 if (string.length()!=1) return super.toAtom(cx);
439 Range.Set set = new Range.Set();
440 set.add(string.charAt(0), string.charAt(0));
441 return CharAtom.set(set);
443 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return CharAtom.string(string); }
446 private class AtomNode extends ElementNode {
448 public AtomNode() { this(new char[0][]); }
449 public AtomNode(char[][] ranges) { this.ranges = ranges; }
450 public AtomNode(char[] range) { this.ranges = new char[][] { range }; }
451 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
452 public Atom toAtom(Context cx) {
453 Range.Set set = new Range.Set();
454 for(char[] r : ranges) set.add(r[0], r[1]);
455 return CharAtom.set(set);
459 private class RepeatNode extends ElementNode {
460 public ElementNode e, sep;
461 public final boolean zero, many, max;
462 public RepeatNode(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
463 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;
465 public Atom toAtom(Context cx) { return sep==null ? e.toAtom(cx) : super.toAtom(cx); }
466 public boolean drop(Context cx) { return e.drop(cx); }
467 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
468 Element ret = build(cx, cnt, dropall, illegalTag);
469 String must = "must be tagged unless they appear within a dropped expression or their contents are dropped: ";
470 if (!dropall && !drop(cx) && !e.drop(cx))
471 if (!many) throw new RuntimeException("options (?) " + must + ret);
472 else if (zero) throw new RuntimeException("zero-or-more repetitions (*) " + must + ret);
473 else throw new RuntimeException("one-or-more repetitions (+) " + must + ret);
476 public Element build(Context cx, NonTerminalNode cnt, boolean dropall, Object repeatTag) {
478 ? Repeat.repeat(e.build(cx, null, dropall), zero, many, sep==null ? null : sep.build(cx, null, dropall), repeatTag)
480 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, repeatTag)
481 : Repeat.repeatMaximal(e.build(cx, null, dropall), zero, many, sep.toAtom(cx), repeatTag);
485 private abstract class ElementNode {
486 public boolean lifted = false;
487 public Seq ownerSeq = null;
488 public String getOwnerTag() { return null; }
489 public ElementNode lifted() { this.lifted = true; return this; }
490 public boolean drop(Context cx) { return false; }
491 public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom: " + this); }
492 public abstract Element build(Context cx, NonTerminalNode cnt, boolean dropall);
495 private abstract class ElementNodeWrapper extends ElementNode {
496 protected ElementNode _e;
497 public ElementNodeWrapper(ElementNode e) { this._e = e; }
498 public String getOwnerTag() { return _e.getOwnerTag(); }
499 public boolean drop(Context cx) { return _e.drop(cx); }
500 public Atom toAtom(Context cx) { return _e.toAtom(cx); }
501 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return _e.build(cx, cnt, dropall); }
504 private class TildeNode extends ElementNodeWrapper {
505 public TildeNode(ElementNode e) { super(e); }
506 public Atom toAtom(Context cx) { return (Atom)((Topology<Character>)_e.toAtom(cx).complement()); }
507 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) { return toAtom(cx); }
510 private class DropNode extends ElementNodeWrapper {
511 public DropNode(ElementNode e) { super(e); }
512 public boolean drop(Context cx) { return true; }
515 // FIXME: doesn't this require a tag?
516 private class BracedNode extends ElementNode {
518 public BracedNode(Seq seq) { this.body = seq; }
519 public Element build(Context cx, NonTerminalNode cnt, boolean dropall) {
520 Union u = new Union(null, false);
521 Sequence s = body.build(cx, u, null, dropall);
522 Union u2 = new Union(null, false);
523 u2.add(Sequence.create(new Element[] {
532 public Seq and2(Seq s, Seq a) { a.alwaysDrop = true; return s.and(a); }
533 public Seq andnot2(Seq s, Seq a) { a.alwaysDrop = true; return s.andnot(a); }
535 //////////////////////////////////////////////////////////////////////////////
537 public class Context {
538 public HashMap<String,Union> map = new HashMap<String,Union>();
539 public GrammarNode grammar;
540 public Context(Tree t) { }
541 public Context(GrammarNode g) { this.grammar = g; }
542 public Union build() {
544 for(NonTerminalNode nt : grammar.values()) {
545 Union u = get(nt.name);
546 if ("s".equals(nt.name))
551 public Union peek(String name) { return map.get(name); }
552 public void put(String name, Union u) { map.put(name, u); }
553 public Union get(String name) {
554 Union ret = map.get(name);
555 if (ret != null) return ret;
556 NonTerminalNode nt = grammar.get(name);
558 throw new Error("warning could not find " + name);
560 ret = new Union(name, false);
562 nt.buildIntoPreallocatedUnion(this, nt, nt.drop(this), ret);