1 // Copyright 2006 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.*;
8 import edu.berkeley.sbp.bind.*;
10 import java.lang.annotation.*;
11 import java.lang.reflect.*;
14 /** The java classes typically used to represent a parsed grammar AST; each inner class is a type of AST node. */
15 public class MetaGrammarBindings extends AnnotationGrammarBindings {
17 public MetaGrammarBindings() { super(MetaGrammarBindings.class); }
19 // FIXME ugly ugly ugly scary dangerous
20 public static String prefix = "";
22 /** A grammar (a set of nonterminals) */
23 public static class GrammarNode extends HashMap<String,NonTerminalNode> {
24 public NonTerminalNode[] getNonTerminals() {
25 return (NonTerminalNode[])values().toArray(new NonTerminalNode[0]);
27 public GrammarNode(NonTerminalNode[] nonterminals) {
28 for(NonTerminalNode nt : nonterminals) {
29 if (nt==null) continue;
30 if (this.get(nt.name)!=null)
31 throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
32 this.put(nt.name, nt);
35 public @bind.as("Grammar") GrammarNode(Object[] nt) { add(nt); }
36 private void add(Object[] obs) {
38 if (o==null) continue;
39 else if (o instanceof Object[]) add((Object[])o);
40 else if (o instanceof NonTerminalNode) {
41 NonTerminalNode nt = (NonTerminalNode)o;
42 if (this.get(nt.name)!=null)
43 throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
44 this.put(nt.name, nt);
46 else if (o instanceof GrammarNode) add(((GrammarNode)o).getNonTerminals());
49 public String toString() {
51 for(NonTerminalNode nt : values()) ret += nt + ", ";
54 public Union build(String s, Grammar.Bindings rm) {
55 Context cx = new Context(this,rm);
57 for(MetaGrammarBindings.NonTerminalNode nt : values()) {
58 Union el = (Union)cx.get(nt.name);
59 StringBuffer st = new StringBuffer();
61 if (nt.name.equals(s)) u = el;
67 public abstract static class UnionNode extends ElementNode {
68 public Seq[][] sequences;
69 public Atom toAtom(Context cx) {
71 for(Seq[] ss : sequences)
73 ret = ret==null ? s.toAtom(cx) : (Atom)ret.union(s.toAtom(cx));
76 public void build(Context cx, Union u, NonTerminalNode cnt) {
77 HashSet<Sequence> bad2 = new HashSet<Sequence>();
78 for(int i=0; i<sequences.length; i++) {
79 Seq[] group = sequences[i];
80 Union u2 = new Union(null, false);
81 if (sequences.length==1) u2 = u;
82 for(int j=0; j<group.length; j++)
83 group[j].build(cx, u2, cnt);
84 if (sequences.length==1) break;
85 Sequence seq = Sequence.create(u2);
86 for(Sequence s : bad2) seq = seq.andnot(s);
88 bad2.add(Sequence.create(u2));
93 public static @bind.as("#import") GrammarNode poundimport(String fileName, String as) {
94 if (as==null) as = "";
95 else if ("".equals(as)) { }
99 Tree t = new CharParser(MetaGrammar.newInstance()).parse(new FileInputStream("tests/"+fileName)).expand1();
100 TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
101 String oldprefix = prefix;
103 GrammarNode gn = (GrammarNode)red.invoke(t);
106 } catch (Exception e) {
108 throw new RuntimeException(e);
112 public static class NonTerminalNode extends UnionNode {
114 public String name = null;
115 public String sep = null;
116 public NonTerminalNode[] getNonTerminals() { return new NonTerminalNode[] { this }; }
117 public @bind.as("NonTerminal") NonTerminalNode(@bind.arg String name, @bind.arg Seq[][] sequences) {
118 this(name, sequences, false); }
119 public NonTerminalNode(String name, Seq[][] sequences, boolean rep) { this(name, sequences, rep, null); }
120 public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep) {
121 this.name = prefix + name;
122 this.sequences = sequences;
124 this.sep = sep==null?null:(prefix + sep);
126 public Element build(Context cx, NonTerminalNode cnt) { return cx.get(name); }
127 public void build(Context cx, Union u, NonTerminalNode cnt) {
128 if (!rep) { super.build(cx, u, this); return; }
129 HashSet<Sequence> bad2 = new HashSet<Sequence>();
131 Union urep = new Union(null, false);
132 urep.add(Sequence.create());
134 urep.add(Sequence.create(new Element[] { cx.get(sep), u }, 1));
136 urep.add(Sequence.create(new Element[] { u }, 0));
138 for(int i=0; i<sequences.length; i++) {
139 Seq[] group = sequences[i];
140 Union u2 = new Union(null, false);
141 if (sequences.length==1) u2 = u;
142 for(int j=0; j<group.length; j++) {
143 Union u3 = new Union(null, false);
144 group[j].build(cx, u3, this);
145 Sequence s = Sequence.create(cx.rm.repeatTag(),
146 new Element[] { u3, urep },
147 new boolean[] { false, false },
151 if (sequences.length==1) break;
152 Sequence seq = Sequence.create(u2);
153 for(Sequence s : bad2) seq = seq.andnot(s);
155 bad2.add(Sequence.create(u2));
160 public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg Seq[][] sequences) {
161 return new NonTerminalNode(name, sequences, true); }
162 public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg String sep, @bind.arg Seq[][] sequences) {
163 return new NonTerminalNode(name, sequences, true, sep); }
165 public static class AnonUnionNode extends UnionNode {
166 public @bind.as("(") AnonUnionNode(Seq[][] sequences) {
167 this.sequences = sequences;
169 public Element build(Context cx, NonTerminalNode cnt) {
170 Union ret = new Union(null, false);
176 public static class Range {
177 public @bind Range(char only) { first = only; last = only; }
178 public @bind Range(char first, char last) { this.first = first; this.last = last; }
183 public static /*abstract*/ class Seq {
184 HashSet<Seq> and = new HashSet<Seq>();
185 HashSet<Seq> not = new HashSet<Seq>();
186 ElementNode[] elements;
189 public void append(ElementNode e) {
190 ElementNode[] elements = new ElementNode[this.elements.length+1];
191 System.arraycopy(this.elements, 0, elements, 0, this.elements.length);
192 this.elements = elements;
193 elements[elements.length-1] = e;
195 public Seq(ElementNode e) { this(new ElementNode[] { e }); }
196 public Seq(ElementNode[] elements) { this.elements = elements; }
197 public Atom toAtom(Context cx) {
198 if (elements.length != 1) throw new Error("you attempted to use ->, **, ++, or a similar character-class operator on a [potentially] multicharacter production");
199 return elements[0].toAtom(cx);
201 public Seq tag(String tag) { this.tag = prefix+tag; return this; }
202 public Seq follow(ElementNode follow) {
203 this.follow = follow;
207 Seq ret = new Seq(elements);
211 ret.tag = prefix+tag;
214 public Seq and(Seq s) { and.add(s); return this; }
215 public Seq andnot(Seq s) { not.add(s); return this; }
216 public Seq separate(ElementNode sep) {
217 ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
218 for(int i=0; i<this.elements.length; i++) {
219 elements[i*2] = this.elements[i];
220 if (i<this.elements.length-1)
221 elements[i*2+1] = new Drop(sep);
223 this.elements = elements;
226 public Sequence build(Context cx, Union u, NonTerminalNode cnt) {
227 Sequence ret = build0(cx, cnt);
228 for(Seq s : and) { Sequence dork = s.build(cx, u, cnt); ret = ret.and(dork); }
229 for(Seq s : not) { Sequence dork = s.build(cx, u, cnt); ret = ret.andnot(dork); }
233 public Sequence build0(Context cx, NonTerminalNode cnt) {
234 boolean[] drops = new boolean[elements.length];
235 Element[] els = new Element[elements.length];
236 for(int i=0; i<elements.length; i++) {
237 drops[i] = elements[i].drop();
238 els[i] = elements[i].build(cx, cnt);
239 if (elements[i].getOwnerTag() != null)
240 tag = elements[i].getOwnerTag();
243 Production prod = new Production(tag, (cnt==null?null:cnt.name), els, drops);
244 ret = cx.rm.createSequence(prod);
247 for(int i=0; i<els.length; i++)
249 if (idx==-1) idx = i;
250 else throw new Error("multiple non-dropped elements in sequence: " + Sequence.create(els, null));
251 if (idx != -1) ret = Sequence.create(els, idx);
252 else ret = Sequence.create(els, null);
254 if (this.follow != null)
255 ret = ret.followedBy(this.follow.toAtom(cx));
259 public static @bind.as("&") Seq and2(Seq s, Seq a) { return s.and(a); }
260 public static @bind.as("&~") Seq andnot2(Seq s, Seq a) { return s.andnot(a); }
261 public static @bind.as("->") Seq arrow(Seq s, ElementNode e) { return s.follow(e); }
262 public static @bind.as("::") Seq tag(String tagname, Seq s) { return s.tag(tagname); }
263 public static @bind.as("/") Seq slash(Seq s, ElementNode e) { return s.separate(e); }
265 public static Seq seq(ElementNode[] elements) { return new Seq(elements); }
266 public static @bind.as("Elements") Seq seq2(ElementNode[] elements) { return new Seq(elements); }
267 public static @bind.as Seq psx(Seq s) { return s; }
268 public static @bind.as(":") ElementNode colon(String s, ElementNode e) { return new Label(s, e); }
269 public static @bind.as("{") ElementNode leftBrace() {
270 return new Drop(new CharClass(new Range[] { new Range(CharAtom.left, CharAtom.left) })); }
271 public static @bind.as("}") ElementNode rightBrace() {
272 return new Drop(new CharClass(new Range[] { new Range(CharAtom.right, CharAtom.right) })); }
273 public static @bind.as(")") void close(String foo) { throw new Error("not supported"); }
274 public static @bind.as("()") ElementNode epsilon() { return new Constant(epsilon); }
276 private static Union epsilon = new Union("()");
277 static { epsilon.add(Sequence.create()); }
279 public static class NonTerminalReferenceNode extends ElementNode {
280 public String nonTerminal;
281 public NonTerminalReferenceNode() { }
282 public @bind.as("NonTerminalReference") NonTerminalReferenceNode(String nonTerminal) {
283 this.nonTerminal = prefix + nonTerminal;
285 public Atom toAtom(Context cx) {
286 return cx.grammar.get(nonTerminal).toAtom(cx);
288 public Element build(Context cx, NonTerminalNode cnt) {
289 if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
290 Element ret = cx.get(nonTerminal);
291 if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
296 public static class Literal extends Constant {
297 private String string;
298 public @bind Literal(@bind.arg String string) {
299 super(CharAtom.string(string));
300 this.string = string;
302 public boolean drop() { return true; }
303 public Atom toAtom(Context cx) {
304 if (string.length()!=1) return super.toAtom(cx);
305 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
306 set.add(string.charAt(0), string.charAt(0));
307 return CharAtom.set(set);
311 public static class CharClass extends ElementNode {
313 public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
314 public Atom toAtom(Context cx) {
315 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
316 for(Range r : ranges)
317 set.add(r.first, r.last);
318 return CharAtom.set(set);
320 public Element build(Context cx, NonTerminalNode cnt) {
321 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
322 for(Range r : ranges)
323 set.add(r.first, r.last);
324 return CharAtom.set(set);
328 public static @bind.as("{") class XTree extends ElementNode {
329 public @bind.arg Seq body;
330 public Element build(Context cx, NonTerminalNode cnt) {
331 Union u = new Union(null, false);
332 Sequence s = body.build(cx, u, null);
333 Union u2 = new Union(null, false);
334 u2.add(Sequence.create(new Element[] {
345 public static class Rep extends ElementNode {
346 public ElementNode e, sep;
347 public boolean zero, many, max;
348 public Rep(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
349 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
350 public Atom toAtom(Context cx) {
351 if (sep != null) return super.toAtom(cx);
354 public Element build(Context cx, NonTerminalNode cnt) {
356 ? Repeat.repeat(e.build(cx, null), zero, many, sep==null ? null : sep.build(cx, null), cx.rm.repeatTag())
358 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, cx.rm.repeatTag())
359 : Repeat.repeatMaximal(e.build(cx, null), zero, many, sep.toAtom(cx), cx.rm.repeatTag());
363 // FIXME: it would be nice if we could hoist this into "Rep"
364 public static @bind.as("++") ElementNode plusmax(final ElementNode e)
365 { return new Rep(e, null, false, true, true); }
366 public static @bind.as("+") ElementNode plus(final ElementNode e)
367 { return new Rep(e, null, false, true, false); }
368 public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep)
369 { return new Rep(e, sep, false, true, true); }
370 public static @bind.as("+/") ElementNode plusfollow(final ElementNode e, final ElementNode sep)
371 { return new Rep(e, sep, false, true, false); }
372 public static @bind.as("**") ElementNode starmax(final ElementNode e)
373 { return new Rep(e, null, true, true, true); }
374 public static @bind.as("*") ElementNode star(final ElementNode e)
375 { return new Rep(e, null, true, true, false); }
376 public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep)
377 { return new Rep(e, sep, true, true, true); }
378 public static @bind.as("*/") ElementNode starfollow(final ElementNode e, final ElementNode sep)
379 { return new Rep(e, sep, true, true, false); }
380 public static @bind.as("?") ElementNode question(final ElementNode e)
381 { return new Rep(e, null, true, true, false); }
382 public static @bind.as("!") ElementNode bang(final ElementNode e)
383 { return new Drop(e); }
385 public static @bind.as("^") ElementNode caret(final String s) {
386 final String thePrefix = prefix;
387 return new Constant(CharAtom.string(s)) {
388 public String getOwnerTag() { return thePrefix+s; }
389 public boolean drop() { return true; }
393 public static @bind.as("~") ElementNode tilde(final ElementNode e) {
394 return new ElementNodeWrapper(e) {
395 public Atom toAtom(Context cx) {
396 return infer((Topology<Character>)e.toAtom(cx).complement()/*.minus(CharAtom.braces)*/);
398 public Element build(Context cx, NonTerminalNode cnt) {
399 return infer((Topology<Character>)e.toAtom(cx).complement()/*.minus(CharAtom.braces)*/);
402 public static @bind.as("Word") String word(String s) { return s; }
403 public static @bind.as("Quoted") String quoted(String s) { return s; }
404 public static @bind.as("escaped") String c(char c) {
405 if (c=='{') return CharAtom.left+"";
406 if (c=='}') return CharAtom.right+"";
409 public static @bind.as("EmptyString") String emptystring() { return ""; }
410 public static @bind.as("\n") String retur() { return "\n"; }
411 public static @bind.as("\r") String lf() { return "\r"; }
413 //static Atom infer(Element e) { return infer((Topology<Character>)Atom.toAtom(e)); }
414 static Atom infer(Object t) { return (Atom)t; }
416 public static class Context {
417 public HashMap<String,Union> map = new HashMap<String,Union>();
418 public GrammarNode grammar;
419 public String cnt = null;
420 public Grammar.Bindings rm;
421 public Context(GrammarNode g, Grammar.Bindings rm) {
425 public Union build() {
427 for(NonTerminalNode nt : grammar.values()) {
428 Union u = get(nt.name);
429 if ("s".equals(nt.name))
434 public Context(Tree t, Grammar.Bindings rm) {
436 TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
437 this.grammar = (GrammarNode)red.invoke(t);
439 public Union peek(String name) { return map.get(name); }
440 public void put(String name, Union u) { map.put(name, u); }
441 public Union get(String name) {
442 Union ret = map.get(name);
443 if (ret != null) return ret;
444 ret = new Union(name);
446 NonTerminalNode nt = grammar.get(name);
448 throw new Error("warning could not find " + name);
452 nt.build(this, ret, nt);
460 public static abstract class ElementNode {
461 public String getLabel() { return null; }
462 public String getOwnerTag() { return null; }
463 public boolean drop() { return false; }
464 public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom"); }
465 public abstract Element build(Context cx, NonTerminalNode cnt);
468 public static abstract class ElementNodeWrapper extends ElementNode {
469 protected ElementNode _e;
470 public ElementNodeWrapper(ElementNode e) { this._e = e; }
471 public String getLabel() { return _e.getLabel(); }
472 public String getOwnerTag() { return _e.getOwnerTag(); }
473 public boolean drop() { return _e.drop(); }
474 public Atom toAtom(Context cx) { return _e.toAtom(cx); }
475 public Element build(Context cx, NonTerminalNode cnt) { return _e.build(cx, cnt); }
478 public static class Constant extends ElementNode {
480 public Constant(Element constant) { this.constant = constant; }
481 public Element build(Context cx, NonTerminalNode cnt) { return constant; }
482 public Atom toAtom(Context cx) {
483 if (constant instanceof Atom) return ((Atom)constant);
484 return super.toAtom(cx);
488 public abstract static class PostProcess extends ElementNodeWrapper {
489 public PostProcess(ElementNode e) { super(e); }
490 public Element build(Context cx, NonTerminalNode cnt) { return postProcess(_e.build(cx, cnt)); }
491 public abstract Element postProcess(Element e);
494 public static class Drop extends ElementNodeWrapper {
495 public Drop(ElementNode e) { super(e); }
496 public boolean drop() { return true; }
499 public static class Label extends ElementNodeWrapper {
501 public Label(String label, ElementNode e) { super(e); this.label = label; }
502 public String getLabel() { return label; }
506 static class Invert extends Atom {
507 private final Atom a;
508 public Invert(Atom a) { this.a = a; }
509 public Topology top() { return a.complement(); }
510 public String toString() { return "~"+a; }