1 package edu.berkeley.sbp.misc;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
6 import java.lang.annotation.*;
7 import java.lang.reflect.*;
12 public static boolean harsh = false;
14 public static void main(String[] s) throws Exception {
16 ReflectiveMeta m = new ReflectiveMeta();
17 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
18 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
19 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
21 Union meta = mgf.get("s").build(bc);
22 Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
24 Union u = Demo.make(t, "s");
27 System.err.println("== parsing with parsed grammar =================================================================================");
28 t = new CharParser((Union)u).parse(new FileInputStream(s[1])).expand1();
29 System.out.println(t.toPrettyString());
31 System.err.println("== parsing with parsed-parsed grammar ==========================================================================");
32 t = new CharParser(new Context(t, m).build()).parse(new FileInputStream(s[1])).expand1();
33 System.out.println(t.toPrettyString());
36 public static class ReflectiveMetaPlain extends ReflectiveMeta {
37 public Object repeatTag() { return null; }
38 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
40 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
41 return Sequence.rewritingSequence(tag, els, labels, drops);
45 public static class ReflectiveMeta extends MetaGrammar.Meta {
46 private final Class _cl;
47 private final Class[] _inner;
48 public ReflectiveMeta() {
51 public ReflectiveMeta(Class c) {
53 this._inner = c.getDeclaredClasses();
55 public ReflectiveMeta(Class c, Class[] inner) {
59 private boolean match(Method m, String s) { return match(m.getAnnotation(bind.as.class), null, s); }
60 private boolean match(bind.as t, Class c, String s) {
61 if (t==null) return false;
62 if (t.value().equals(s)) return true;
63 if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
67 private boolean match(nonterminal t, Class c, String s) {
68 if (t==null) return false;
69 if (t.value().equals(s)) return true;
70 if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
74 private boolean match(Class c, String s, String nonTerminalName) {
75 if (match((bind.as)c.getAnnotation(bind.as.class), c, s)) return true;
76 //if (match((nonterminal)c.getAnnotation(bind.as.class), c, nonTerminalName)) return true;
79 public boolean match(Constructor con, String s, String nonTerminalName) {
80 Class c = con.getDeclaringClass();
81 if (match((bind.as)con.getAnnotation(bind.as.class), null, s)) return true;
82 //if (match((nonterminal)con.getAnnotation(bind.as.class), c, s)) return true;
85 public Object repeatTag() {
86 return new Tree.ArrayBuildingTreeFunctor<Object>();
88 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
89 Production p = new Production(tag, nonTerminalName, els, labels, drops);
90 for(Method m : _cl.getMethods())
91 if (new TargetMethod(m).isCompatible(p))
92 return new TargetMethod(m).makeSequence(p);
94 for(Constructor con : c.getConstructors())
95 if (new TargetConstructor(con).isCompatible(p))
96 return new TargetConstructor(con).makeSequence(p);
98 if (new TargetClass(c).isCompatible(p))
99 return new TargetClass(c).makeSequence(p);
102 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
103 Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
104 if (ret != null) return ret;
105 String message = "could not find a Java method/class/ctor matching tag \""+tag+
106 "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
108 throw new RuntimeException(message);
110 System.err.println(message);
111 return Sequence.rewritingSequence(tag, els, labels, drops);
117 public static class bind {
119 * Constructors, classes, and methods with this attribute will
120 * match every production of the nonterminal called "value()"
121 * that is arg-compatible. If value() is undefined, then the
122 * class/constructor/method name is used.
125 @Retention(RetentionPolicy.RUNTIME) public static @interface nonterminal { String value() default ""; }
128 @Retention(RetentionPolicy.RUNTIME) public static @interface raw { }
131 * Constructors, classes, and methods with this attribute will
132 * match every tree tagged with "value()" that is arg-compatible.
133 * If value() is undefined, then the class/constructor/method
137 @Retention(RetentionPolicy.RUNTIME) public static @interface as { String value() default ""; }
141 * If any parameter to a method or field in a class has a named
142 * arg-tag, that parameter/field matches the child of the tree
143 * which either has that label or else is a reference to a
144 * nonterminal with the corresponding name.
146 * The remaining non-named arg-tags match the remaining children
147 * of the tree in sequential order.
149 * If any arg-tagged parameters/fields remain, the match fails.
150 * If there were no arg-tagged parameters-fields, it is as if all
151 * of them were non-named and arg-tagged.
153 * A method/constructor is arg-compatible if all of its arguments
154 * are arg-compatible.
156 * A class is arg-compatible if all of its fields are
157 * arg-compatible, or if one of its constructors is arg-compatible.
160 @Retention(RetentionPolicy.RUNTIME) public static @interface arg { String value() default ""; }
163 public static class Production {
165 public String nonTerminal;
166 public Object[] labels;
167 public boolean[] drops;
168 public Element[] elements;
169 public int count = 0;
170 public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
172 this.elements = elements;
173 this.nonTerminal = nonTerminal;
174 this.labels = labels;
176 for(int i=0; i<drops.length; i++)
182 public static abstract class Target {
183 public int[] buildSequence(Production p) {
184 Annotation[][] annotations = _bindable.getArgAnnotations();
185 String[] names = _bindable.getArgNames();
186 String name = _bindable.getSimpleName();
187 int len = annotations.length;
189 bind.arg[] argtags = new bind.arg[len];
190 for(int i=0; i<names.length; i++)
191 for(Annotation a : annotations[i+ofs])
192 if (a instanceof bind.arg)
193 argtags[i+ofs] = (bind.arg)a;
194 return Target.this.buildSequence(p, names, argtags);
196 private Reflection.Bindable _bindable;
197 public Target(Reflection.Bindable b) { this._bindable = b; }
199 public String getName() { return _bindable.getSimpleName(); }
200 public bind.as getBindAs() { return (bind.as)_bindable.getAnnotation(bind.as.class); }
201 //public nonterminal getNonTerminal() { return (nonterminal)_bindable.getAnnotation(bind.as.class); }
202 public String toString() { return _bindable.getSimpleName(); }
203 public Object plant(Object[] fields) { return _bindable.impose(fields); }
204 public boolean isRaw() { return _bindable.isAnnotationPresent(bind.raw.class); }
205 public Object invokeRaw(Iterable<Tree<Object>> t) { return _bindable.impose(new Object[] { t }); }
207 public boolean isCompatible(Production p) {
208 bind.as t = getBindAs();
210 (t.value().equals(p.tag) ||
211 (t.value().equals("") && getName().equals(p.tag))))
212 return buildSequence(p)!=null;
214 bind.as n = getBindAs();
216 (n.value().equals(p.nonTerminal) ||
217 (n.value().equals("") && getName().equals(p.nonTerminal))))
218 return buildSequence(p)!=null;
223 public int[] buildSequence(Production p, String[] names, bind.arg[] argtags) {
225 for(int i=0; i<argtags.length; i++)
226 if (argtags[i] != null)
229 // FIXME: can be smarter here
230 if (names.length==p.count) {
231 int[] ret = new int[p.count];
232 for(int i=0; i<p.count; i++) ret[i] = i;
234 } else if (argTagged==p.count) {
235 int[] ret = new int[argtags.length];
237 for(int i=0; i<argtags.length; i++)
238 ret[i] = argtags[i]==null ? -1 : (j++);
244 public Sequence makeSequence(Production p) {
245 return Sequence.rewritingSequence(new TargetReducer(p, buildSequence(p), "reducer-"+this),
246 p.elements, p.labels, p.drops);
249 public class TargetReducer implements Tree.TreeFunctor<Object,Object> {
250 private Production p;
253 public TargetReducer(Production p, int[] map, String name) {
258 public String toString() { return name; }
259 public Object invoke(Iterable<Tree<Object>> t) {
260 if (isRaw()) return invokeRaw(t);
261 ArrayList ret = new ArrayList();
263 if (tc.head() != null && tc.head() instanceof Functor)
264 ret.add(((Tree.TreeFunctor<Object,Object>)tc.head()).invoke(tc.children()));
265 else if (tc.numChildren() == 0)
268 System.err.println("FIXME: don't know what to do about " + tc);
272 System.err.println("input tree: " + t);
273 Object[] o = (Object[])ret.toArray(new Object[0]);
275 for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
276 Object[] o2 = new Object[max+1];
277 for(int i=0; i<o.length; i++) o2[map[i]] = o[i];
283 public static class TargetClass extends Target {
284 public final Class _class;
285 public TargetClass(Class _class) { super(Reflection.Bindable.create(_class)); this._class = _class; }
288 public static class TargetConstructor extends Target {
289 public final Constructor _ctor;
290 public TargetConstructor(Constructor _ctor) { super(Reflection.Bindable.create(_ctor)); this._ctor = _ctor; }
292 public static class TargetMethod extends Target {
293 public final Method _method;
294 public TargetMethod(Method _method) { super(Reflection.Bindable.create(_method)); this._method = _method; }
297 public static Union cached = null;
298 public static Union make() {
299 if (cached != null) return cached;
301 ReflectiveMeta m = new ReflectiveMeta();
302 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
303 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
304 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
305 Union meta = mgf.get("s").build(bc);
306 Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
307 return cached = make(t, "s");
308 } catch (Exception e) {
309 throw new RuntimeException(e);
312 public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
313 public static Union make(Tree t, String s, ReflectiveMeta rm) {
314 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
315 MG.Grammar g = (MG.Grammar)red.invoke(t.children());
316 Context cx = new Context(g,rm);
318 for(MG.NonTerminal nt : g.nonterminals) {
319 System.out.println(nt.name);
320 Union el = (Union)cx.get(nt.name);
321 StringBuffer st = new StringBuffer();
323 System.err.println(st);
324 if (nt.name.equals(s)) u = el;
329 public static class MG {
330 public static @bind.as("grammar") class Grammar {
331 public NonTerminal get(String s) {
332 for(NonTerminal nt : nonterminals)
333 if (nt.name.equals(s))
337 public @bind.arg("NonTerminal") NonTerminal[] nonterminals;
338 public String toString() {
340 for(NonTerminal nt : nonterminals) ret += nt + ", ";
344 public abstract static class Un extends El {
345 public Seq[][] sequences;
346 public void build(Context cx, Union u) {
347 HashSet<Sequence> bad2 = new HashSet<Sequence>();
348 for(int i=0; i<sequences.length; i++) {
349 Seq[] group = sequences[i];
350 Union u2 = new Union();
351 if (sequences.length==1) u2 = u;
352 for(int j=0; j<group.length; j++) {
353 group[j].build(cx, u2, false);
355 if (sequences.length==1) break;
356 Sequence seq = Sequence.singleton(u2);
357 for(Sequence s : bad2) {
362 bad2.add(Sequence.singleton(u2));
366 public static class NonTerminal extends Un {
367 public String name = null;
368 public @bind.as("=") NonTerminal(@bind.arg("Word") String name,
369 @bind.arg("RHS") Seq[][] sequences) {
371 this.sequences = sequences;
373 public Element build(Context cx) { return cx.get(name); }
376 public static class AnonUn extends Un {
377 public @bind.as("(") AnonUn(Seq[][] sequences) {
378 this.sequences = sequences;
380 public Element build(Context cx) {
381 Union ret = new Union();
387 //public static @bind.as void range(char c) { }
388 public static class Range {
389 public @bind.as("range") Range(char only) { first = only; last = only; }
390 public @bind.as("-") Range(char first, char last) { this.first = first; this.last = last; }
394 public static abstract class El {
395 public String getLabel() { return null; }
396 public String getOwnerTag() { return null; }
397 public boolean drop() { return false; }
398 public abstract Element build(Context cx);
400 public static class Drop extends El {
402 public Drop(El e) { this.e = e; }
403 public String getLabel() { return null; }
404 public boolean drop() { return true; }
405 public String getOwnerTag() { return e.getOwnerTag(); }
406 public Element build(Context cx) { return e.build(cx); }
408 public static class Label extends El {
411 public Label(String label, El e) { this.e = e; this.label = label; }
412 public String getLabel() { return label; }
413 public String getOwnerTag() { return e.getOwnerTag(); }
414 public Element build(Context cx) { return e.build(cx); }
416 public static /*abstract*/ class Seq {
417 HashSet<Seq> and = new HashSet<Seq>();
418 HashSet<Seq> not = new HashSet<Seq>();
423 public Seq(El e) { this(new El[] { e }); }
424 public Seq(El[] elements) { this.elements = elements; }
425 public Seq tag(String tag) { this.tag = tag; return this; }
426 public Seq follow(El follow) { this.follow = follow; return this; }
428 Seq ret = new Seq(elements);
435 public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
436 public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
437 public Seq separate(El sep) {
438 El[] elements = new El[this.elements.length * 2 - 1];
439 for(int i=0; i<this.elements.length; i++) {
440 elements[i*2] = this.elements[i];
441 if (i<this.elements.length-1)
442 elements[i*2+1] = new Drop(sep);
444 this.elements = elements;
447 public Sequence build(Context cx, Union u, boolean lame) {
448 Sequence ret = build0(cx, lame || this.lame);
449 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
450 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
455 public Sequence build0(Context cx, boolean lame) {
456 boolean unwrap = false;
457 boolean dropAll = lame;
458 if (tag!=null && tag.equals("[]")) unwrap = true;
459 if (tag!=null && "()".equals(tag)) dropAll = true;
460 Object[] labels = new Object[elements.length];
461 boolean[] drops = new boolean[elements.length];
462 Element[] els = new Element[elements.length];
463 for(int i=0; i<elements.length; i++) {
464 labels[i] = elements[i].getLabel();
465 drops[i] = elements[i].drop();
466 els[i] = elements[i].build(cx);
467 if (elements[i].getOwnerTag() != null)
468 tag = elements[i].getOwnerTag();
471 if (dropAll) ret = Sequence.drop(els, false);
472 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
473 else if (tag!=null) {
474 ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
477 for(int i=0; i<els.length; i++)
479 if (idx==-1) idx = i;
480 else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
481 if (idx != -1) ret = Sequence.singleton(els, idx);
482 else ret = Sequence.drop(els, false);
484 if (this.follow != null)
485 ret.follow = MetaGrammar.infer(this.follow.build(cx));
486 ret.lame = this.lame;
490 public static @bind.as("&") Seq and(Seq s, El[] elements) { return s.and(seq(elements)); }
491 public static @bind.as("&~") Seq andnot(Seq s, El[] elements) { return s.andnot(seq(elements)); }
492 public static @bind.as("->") Seq arrow(Seq s, El e) { return s.follow(e); }
493 public static @bind.as("::") Seq tag(String tagname, Seq s) { return s.tag(tagname); }
494 public static @bind.as("/") Seq slash(Seq s, El e) { return s.separate(e); }
496 public static @bind.as("ps") Seq seq(El[] elements) { return new Seq(elements); }
497 public static @bind.as Seq psx(Seq s) { return s; }
498 public static @bind.as(":") El colon(String s, El e) { return new Label(s, e); }
499 public static @bind.as(")") void close(String foo) { throw new Error("not supported"); }
500 public static @bind.as("()") El epsilon() { return new Constant(Union.epsilon); }
502 public static @bind.as("nonTerminal") class NonTerminalReference extends El {
503 public @bind.arg String nonTerminal;
504 public Element build(Context cx) {
505 return cx.get(nonTerminal);
509 public static class StringLiteral extends Constant {
510 public @bind.as("literal") StringLiteral(String string) { super(CharRange.string(string)); }
511 public boolean drop() { return true; }
514 public static class CharClass extends El {
516 public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
517 public Element build(Context cx) {
518 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
519 for(Range r : ranges)
520 set.add(r.first, r.last);
521 return CharRange.set(set);
525 public static @bind.as("{") class XTree extends El {
526 public @bind.arg Seq body;
527 public Element build(Context cx) {
532 public static class Rep extends El {
534 public boolean zero, many, max;
535 public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
536 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
537 public Element build(Context cx) {
539 ? Sequence.repeat(e.build(cx), zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
541 ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many, cx.rm.repeatTag())
542 : Sequence.repeatMaximal(e.build(cx), zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
545 public static class Constant extends El {
547 public Constant(Element constant) { this.constant = constant; }
548 public Element build(Context cx) { return constant; }
550 public abstract static class PostProcess extends El {
552 public PostProcess(El e) { this.e = e; }
553 public Element build(Context cx) { return postProcess(e.build(cx)); }
554 public abstract Element postProcess(Element e);
557 // FIXME: it would be nice if we could hoist this into "Rep"
558 public static @bind.as("++") El plusmax(final El e) { return new Rep(e, null, false, true, true); }
559 public static @bind.as("+") El plus(final El e) { return new Rep(e, null, false, true, false); }
560 public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep, false, true, true); }
561 public static @bind.as("+/") El plusfollow(final El e, final El sep) { return new Rep(e, sep, false, true, false); }
562 public static @bind.as("**") El starmax(final El e) { return new Rep(e, null, true, true, true); }
563 public static @bind.as("*") El star(final El e) { return new Rep(e, null, true, true, false); }
564 public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep, true, true, true); }
565 public static @bind.as("*/") El starfollow(final El e, final El sep) { return new Rep(e, sep, true, true, false); }
566 public static @bind.as("?") El question(final El e) { return new Rep(e, null, true, true, false); }
568 public static @bind.as("!") El bang(final El e) { return new Drop(e); }
570 public static @bind.as("^") El caret(final String s) {
571 return new Drop(new Constant(CharRange.string(s)) {
572 public String getOwnerTag() { return s; }
576 public static @bind.as("~") El tilde(final El e) {
577 return new PostProcess(e) {
578 public Element postProcess(Element e) {
579 return MetaGrammar.infer((Topology<Character>)Atom.toAtom(e).complement());
582 public static @bind.as("^^") void doublecaret(final El e) { throw new Error("not implemented"); }
584 //public static @bind.as("(") El subexpression(Seq[][] rhs) { return new NonTerminal(rhs); }
586 public static @bind.as("Word") String word(String s) { return s; }
587 public static @bind.as("Quoted") String quoted(String s) { return s; }
588 public static @bind.as("escaped") String c(char c) { return c+""; }
589 public static @bind.as("\"\"") String emptystring() { return ""; }
590 public static @bind.as("\n") String retur() { return "\n"; }
591 public static @bind.as("\r") String lf() { return "\r"; }
594 public static class Context {
595 HashMap<String,Union> map = new HashMap<String,Union>();
596 private MG.Grammar grammar;
597 public String cnt = null;
598 private ReflectiveMeta rm;
599 public Context(MG.Grammar g, ReflectiveMeta rm) {
603 public Union build() {
605 for(MG.NonTerminal nt : grammar.nonterminals) {
606 Union u = get(nt.name);
607 if ("s".equals(nt.name))
612 public Context(Tree t, ReflectiveMeta rm) {
614 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
615 this.grammar = (MG.Grammar)red.invoke(t.children());
617 public Union peek(String name) { return map.get(name); }
618 public void put(String name, Union u) { map.put(name, u); }
619 public Union get(String name) {
620 Union ret = map.get(name);
621 if (ret != null) return ret;
622 ret = new Union(name);
624 MG.NonTerminal nt = grammar.get(name);
626 System.err.println("*** warning could not find " + name);