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() {
57 MG.NonTerminalReference.class,
58 MG.StringLiteral.class,
63 public ReflectiveMeta(Class c, Class[] inner) {
67 private boolean match(Method m, String s) { return match(m.getAnnotation(tag.class), null, s); }
68 private boolean match(tag t, Class c, String s) {
69 if (t==null) return false;
70 if (t.value().equals(s)) return true;
71 if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
74 private boolean match(nonterminal t, Class c, String s) {
75 if (t==null) return false;
76 if (t.value().equals(s)) return true;
77 if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
80 private boolean match(Class c, String s, String nonTerminalName) {
81 if (match((tag)c.getAnnotation(tag.class), c, s)) return true;
82 if (match((nonterminal)c.getAnnotation(nonterminal.class), c, nonTerminalName)) return true;
85 public boolean match(Constructor con, String s, String nonTerminalName) {
86 Class c = con.getDeclaringClass();
87 if (match((tag)con.getAnnotation(tag.class), null, s)) return true;
88 if (match((nonterminal)con.getAnnotation(nonterminal.class), c, s)) return true;
91 public Object repeatTag() {
92 return new Tree.ArrayBuildingTreeFunctor<Object>();
94 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
95 Production p = new Production(tag, nonTerminalName, els, labels, drops);
96 for(Method m : _cl.getMethods())
97 if (new TargetMethod(m).isCompatible(p))
98 return new TargetMethod(m).makeSequence(p);
100 for(Constructor con : c.getConstructors())
101 if (new TargetConstructor(con).isCompatible(p))
102 return new TargetConstructor(con).makeSequence(p);
103 for(Class c : _inner)
104 if (new TargetClass(c).isCompatible(p))
105 return new TargetClass(c).makeSequence(p);
108 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
109 Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
110 if (ret != null) return ret;
111 String message = "could not find a Java method/class/ctor matching tag \""+tag+
112 "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
114 throw new RuntimeException(message);
116 System.err.println(message);
117 return Sequence.rewritingSequence(tag, els, labels, drops);
124 * Constructors, classes, and methods with this attribute will
125 * match every production of the nonterminal called "value()"
126 * that is arg-compatible. If value() is undefined, then the
127 * class/constructor/method name is used.
129 @Retention(RetentionPolicy.RUNTIME) public static @interface nonterminal { String value() default ""; }
131 @Retention(RetentionPolicy.RUNTIME) public static @interface raw { }
134 * Constructors, classes, and methods with this attribute will
135 * match every tree tagged with "value()" that is arg-compatible.
136 * If value() is undefined, then the class/constructor/method
139 @Retention(RetentionPolicy.RUNTIME) public static @interface tag { String value() default ""; }
142 * If any parameter to a method or field in a class has a named
143 * arg-tag, that parameter/field matches the child of the tree
144 * which either has that label or else is a reference to a
145 * nonterminal with the corresponding name.
147 * The remaining non-named arg-tags match the remaining children
148 * of the tree in sequential order.
150 * If any arg-tagged parameters/fields remain, the match fails.
151 * If there were no arg-tagged parameters-fields, it is as if all
152 * of them were non-named and arg-tagged.
154 * A method/constructor is arg-compatible if all of its arguments
155 * are arg-compatible.
157 * A class is arg-compatible if all of its fields are
158 * arg-compatible, or if one of its constructors is arg-compatible.
161 @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 abstract int[] buildSequence(Production p);
184 private Reflection.Bindable _bindable;
185 public Target(Reflection.Bindable b) { this._bindable = b; }
187 public String getName() { return _bindable.getSimpleName(); }
188 public tag getTag() { return (tag)_bindable.getAnnotation(tag.class); }
189 public nonterminal getNonTerminal() { return (nonterminal)_bindable.getAnnotation(nonterminal.class); }
190 public String toString() { return _bindable.getSimpleName(); }
191 public Object plant(Object[] fields) { return _bindable.impose(fields); }
192 public boolean isRaw() { return _bindable.isAnnotationPresent(raw.class); }
193 public Object invokeRaw(Iterable<Tree<Object>> t) { return _bindable.impose(new Object[] { t }); }
195 public boolean isCompatible(Production p) {
198 (t.value().equals(p.tag) ||
199 (t.value().equals("") && getName().equals(p.tag))))
200 return buildSequence(p)!=null;
202 nonterminal n = getNonTerminal();
204 (n.value().equals(p.nonTerminal) ||
205 (n.value().equals("") && getName().equals(p.nonTerminal))))
206 return buildSequence(p)!=null;
211 public int[] buildSequence(Production p, String[] names, arg[] argtags) {
213 for(int i=0; i<argtags.length; i++)
214 if (argtags[i] != null)
217 // FIXME: can be smarter here
218 if (names.length==p.count) {
219 int[] ret = new int[p.count];
220 for(int i=0; i<p.count; i++) ret[i] = i;
222 } else if (argTagged==p.count) {
223 int[] ret = new int[argtags.length];
225 for(int i=0; i<argtags.length; i++)
226 ret[i] = argtags[i]==null ? -1 : (j++);
232 public Sequence makeSequence(Production p) {
233 return Sequence.rewritingSequence(new TargetReducer(p, buildSequence(p), "reducer-"+this),
234 p.elements, p.labels, p.drops);
237 public class TargetReducer implements Tree.TreeFunctor<Object,Object> {
238 private Production p;
241 public TargetReducer(Production p, int[] map, String name) {
246 public String toString() { return name; }
247 public Object invoke(Iterable<Tree<Object>> t) {
248 if (isRaw()) return invokeRaw(t);
249 ArrayList ret = new ArrayList();
251 if (tc.head() != null && tc.head() instanceof Functor)
252 ret.add(((Tree.TreeFunctor<Object,Object>)tc.head()).invoke(tc.children()));
253 else if (tc.numChildren() == 0)
256 System.err.println("FIXME: don't know what to do about " + tc);
260 System.err.println("input tree: " + t);
261 Object[] o = (Object[])ret.toArray(new Object[0]);
263 for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
264 Object[] o2 = new Object[max+1];
265 for(int i=0; i<o.length; i++) o2[map[i]] = o[i];
271 public static class TargetClass extends Target {
272 public final Class _class;
273 public TargetClass(Class _class) { super(Reflection.Bindable.create(_class)); this._class = _class; }
274 public int[] buildSequence(Production p) {
275 Field[] f = _class.getDeclaredFields();
276 String[] names = new String[f.length];
277 arg[] argtags = new arg[f.length];
278 for(int i=0; i<f.length; i++) {
279 names[i] = f[i].getName();
280 argtags[i] = f[i].getAnnotation(arg.class);
282 int[] ret = buildSequence(p, names, argtags);
283 if (ret!=null) return ret;
284 for(Constructor c : _class.getConstructors())
285 if (new TargetConstructor(c).buildSequence(p)!=null)
286 return new TargetConstructor(c).buildSequence(p);
291 public static class TargetConstructor extends Target {
292 public final Constructor _ctor;
293 public TargetConstructor(Constructor _ctor) { super(Reflection.Bindable.create(_ctor)); this._ctor = _ctor; }
294 public int[] buildSequence(Production p) {
295 Annotation[][] annotations = _ctor.getParameterAnnotations();
296 int len = annotations.length;
298 String name = _ctor.getDeclaringClass().getName();
300 if (name.indexOf('$') > name.lastIndexOf('.')) {
305 String[] names = new String[len];
306 arg[] argtags = new arg[len];
307 for(int i=0; i<names.length; i++)
308 for(Annotation a : annotations[i+ofs])
309 if (a instanceof arg)
310 argtags[i+ofs] = (arg)a;
311 return buildSequence(p, names, argtags);
314 public static class TargetMethod extends Target {
315 public final Method _method;
316 public TargetMethod(Method _method) { super(Reflection.Bindable.create(_method)); this._method = _method; }
317 public int[] buildSequence(Production p) {
318 Annotation[][] annotations = _method.getParameterAnnotations();
319 String[] names = new String[annotations.length];
320 arg[] argtags = new arg[annotations.length];
321 for(int i=0; i<names.length; i++)
322 for(Annotation a : annotations[i])
323 if (a instanceof arg)
325 int[] ret = buildSequence(p, names, argtags);
330 public static Union cached = null;
331 public static Union make() {
332 if (cached != null) return cached;
334 ReflectiveMeta m = new ReflectiveMeta();
335 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
336 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
337 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
338 Union meta = mgf.get("s").build(bc);
339 Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
340 return cached = make(t, "s");
341 } catch (Exception e) {
342 throw new RuntimeException(e);
345 public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
346 public static Union make(Tree t, String s, ReflectiveMeta rm) {
347 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
348 MG.Grammar g = (MG.Grammar)red.invoke(t.children());
349 Context cx = new Context(g,rm);
351 for(MG.NonTerminal nt : g.nonterminals) {
352 System.out.println(nt.name);
353 Union el = (Union)cx.get(nt.name);
354 StringBuffer st = new StringBuffer();
356 System.err.println(st);
357 if (nt.name.equals(s)) u = el;
362 public static class MG {
363 public static @tag("grammar") class Grammar {
364 public NonTerminal get(String s) {
365 for(NonTerminal nt : nonterminals)
366 if (nt.name.equals(s))
370 public @arg("NonTerminal") NonTerminal[] nonterminals;
371 public String toString() {
373 for(NonTerminal nt : nonterminals) ret += nt + ", ";
377 public abstract static class Un extends El {
378 public Seq[][] sequences;
379 public void build(Context cx, Union u) {
380 HashSet<Sequence> bad2 = new HashSet<Sequence>();
381 for(int i=0; i<sequences.length; i++) {
382 Seq[] group = sequences[i];
383 Union u2 = new Union();
384 if (sequences.length==1) u2 = u;
385 for(int j=0; j<group.length; j++) {
386 group[j].build(cx, u2, false);
388 if (sequences.length==1) break;
389 Sequence seq = Sequence.singleton(u2);
390 for(Sequence s : bad2) {
395 bad2.add(Sequence.singleton(u2));
399 public static class NonTerminal extends Un {
400 public String name = null;
401 public @nonterminal("NonTerminal") NonTerminal(@arg("Word") String name,
402 @arg("RHS") Seq[][] sequences) {
404 this.sequences = sequences;
406 public Element build(Context cx) { return cx.get(name); }
409 public static class AnonUn extends Un {
410 public @tag("(") AnonUn(Seq[][] sequences) {
411 this.sequences = sequences;
413 public Element build(Context cx) {
414 Union ret = new Union();
420 //public static @tag void range(char c) { }
421 public static class Range {
422 public @tag("range") Range(char only) { first = only; last = only; }
423 public @tag("-") Range(char first, char last) { this.first = first; this.last = last; }
427 public static abstract class El {
428 public String getLabel() { return null; }
429 public String getOwnerTag() { return null; }
430 public boolean drop() { return false; }
431 public abstract Element build(Context cx);
433 public static class Drop extends El {
435 public Drop(El e) { this.e = e; }
436 public String getLabel() { return null; }
437 public boolean drop() { return true; }
438 public String getOwnerTag() { return e.getOwnerTag(); }
439 public Element build(Context cx) { return e.build(cx); }
441 public static class Label extends El {
444 public Label(String label, El e) { this.e = e; this.label = label; }
445 public String getLabel() { return label; }
446 public String getOwnerTag() { return e.getOwnerTag(); }
447 public Element build(Context cx) { return e.build(cx); }
449 public static /*abstract*/ class Seq {
450 HashSet<Seq> and = new HashSet<Seq>();
451 HashSet<Seq> not = new HashSet<Seq>();
456 public Seq(El e) { this(new El[] { e }); }
457 public Seq(El[] elements) { this.elements = elements; }
458 public Seq tag(String tag) { this.tag = tag; return this; }
459 public Seq follow(El follow) { this.follow = follow; return this; }
461 Seq ret = new Seq(elements);
468 public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
469 public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
470 public Seq separate(El sep) {
471 El[] elements = new El[this.elements.length * 2 - 1];
472 for(int i=0; i<this.elements.length; i++) {
473 elements[i*2] = this.elements[i];
474 if (i<this.elements.length-1)
475 elements[i*2+1] = new Drop(sep);
477 this.elements = elements;
480 public Sequence build(Context cx, Union u, boolean lame) {
481 Sequence ret = build0(cx, lame || this.lame);
482 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
483 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
488 public Sequence build0(Context cx, boolean lame) {
489 boolean unwrap = false;
490 boolean dropAll = lame;
491 if (tag!=null && tag.equals("[]")) unwrap = true;
492 if (tag!=null && "()".equals(tag)) dropAll = true;
493 Object[] labels = new Object[elements.length];
494 boolean[] drops = new boolean[elements.length];
495 Element[] els = new Element[elements.length];
496 for(int i=0; i<elements.length; i++) {
497 labels[i] = elements[i].getLabel();
498 drops[i] = elements[i].drop();
499 els[i] = elements[i].build(cx);
500 if (elements[i].getOwnerTag() != null)
501 tag = elements[i].getOwnerTag();
504 if (dropAll) ret = Sequence.drop(els, false);
505 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
506 else if (tag!=null) {
507 ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
510 for(int i=0; i<els.length; i++)
512 if (idx==-1) idx = i;
513 else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
514 if (idx != -1) ret = Sequence.singleton(els, idx);
515 else ret = Sequence.drop(els, false);
517 if (this.follow != null)
518 ret.follow = MetaGrammar.infer(this.follow.build(cx));
519 ret.lame = this.lame;
523 public static @tag("&") Seq and(Seq s, El[] elements) { return s.and(seq(elements)); }
524 public static @tag("&~") Seq andnot(Seq s, El[] elements) { return s.andnot(seq(elements)); }
525 public static @tag("->") Seq arrow(Seq s, El e) { return s.follow(e); }
526 public static @tag("::") Seq tag(String tagname, Seq s) { return s.tag(tagname); }
527 public static @tag("/") Seq slash(Seq s, El e) { return s.separate(e); }
529 public static @tag("ps") Seq seq(El[] elements) { return new Seq(elements); }
530 public static @tag Seq psx(Seq s) { return s; }
531 public static @tag(":") El colon(String s, El e) { return new Label(s, e); }
532 public static @tag(")") void close(String foo) { throw new Error("not supported"); }
533 public static @tag("()") El epsilon() { return new Constant(Union.epsilon); }
535 public static @tag("nonTerminal") class NonTerminalReference extends El {
536 public @arg String nonTerminal;
537 public Element build(Context cx) {
538 return cx.get(nonTerminal);
542 public static class StringLiteral extends Constant {
543 public @tag("literal") StringLiteral(String string) { super(CharRange.string(string)); }
544 public boolean drop() { return true; }
547 public static class CharClass extends El {
549 public @tag("[") CharClass(Range[] ranges) { this.ranges = ranges; }
550 public Element build(Context cx) {
551 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
552 for(Range r : ranges)
553 set.add(r.first, r.last);
554 return CharRange.set(set);
558 public static @tag("{") class XTree extends El {
559 public @arg Seq body;
560 public Element build(Context cx) {
565 public static class Rep extends El {
567 public boolean zero, many, max;
568 public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
569 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
570 public Element build(Context cx) {
572 ? Sequence.repeat(e.build(cx), zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
574 ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many, cx.rm.repeatTag())
575 : Sequence.repeatMaximal(e.build(cx), zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
578 public static class Constant extends El {
580 public Constant(Element constant) { this.constant = constant; }
581 public Element build(Context cx) { return constant; }
583 public abstract static class PostProcess extends El {
585 public PostProcess(El e) { this.e = e; }
586 public Element build(Context cx) { return postProcess(e.build(cx)); }
587 public abstract Element postProcess(Element e);
590 // FIXME: it would be nice if we could hoist this into "Rep"
591 public static @tag("++") El plusmax(final El e) { return new Rep(e, null, false, true, true); }
592 public static @tag("+") El plus(final El e) { return new Rep(e, null, false, true, false); }
593 public static @tag("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep, false, true, true); }
594 public static @tag("+/") El plusfollow(final El e, final El sep) { return new Rep(e, sep, false, true, false); }
595 public static @tag("**") El starmax(final El e) { return new Rep(e, null, true, true, true); }
596 public static @tag("*") El star(final El e) { return new Rep(e, null, true, true, false); }
597 public static @tag("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep, true, true, true); }
598 public static @tag("*/") El starfollow(final El e, final El sep) { return new Rep(e, sep, true, true, false); }
599 public static @tag("?") El question(final El e) { return new Rep(e, null, true, true, false); }
601 public static @tag("!") El bang(final El e) { return new Drop(e); }
603 public static @tag("^") El caret(final String s) {
604 return new Drop(new Constant(CharRange.string(s)) {
605 public String getOwnerTag() { return s; }
609 public static @tag("~") El tilde(final El e) {
610 return new PostProcess(e) {
611 public Element postProcess(Element e) {
612 return MetaGrammar.infer((Topology<Character>)Atom.toAtom(e).complement());
615 public static @tag("^^") void doublecaret(final El e) { throw new Error("not implemented"); }
617 //public static @tag("(") El subexpression(Seq[][] rhs) { return new NonTerminal(rhs); }
619 public static @nonterminal("Word") String word(String s) { return s; }
620 public static @nonterminal("Quoted") String quoted(String s) { return s; }
621 public static @nonterminal("escaped") String c(char c) { return c+""; }
622 public static @tag("\"\"") String emptystring() { return ""; }
623 public static @tag("\n") String retur() { return "\n"; }
624 public static @tag("\r") String lf() { return "\r"; }
627 public static class Context {
628 HashMap<String,Union> map = new HashMap<String,Union>();
629 private MG.Grammar grammar;
630 public String cnt = null;
631 private ReflectiveMeta rm;
632 public Context(MG.Grammar g, ReflectiveMeta rm) {
636 public Union build() {
638 for(MG.NonTerminal nt : grammar.nonterminals) {
639 Union u = get(nt.name);
640 if ("s".equals(nt.name))
645 public Context(Tree t, ReflectiveMeta rm) {
647 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
648 this.grammar = (MG.Grammar)red.invoke(t.children());
650 public Union peek(String name) { return map.get(name); }
651 public void put(String name, Union u) { map.put(name, u); }
652 public Union get(String name) {
653 Union ret = map.get(name);
654 if (ret != null) return ret;
655 ret = new Union(name);
657 MG.NonTerminal nt = grammar.get(name);
659 System.err.println("*** warning could not find " + name);