1 package edu.berkeley.sbp.misc;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import edu.berkeley.sbp.bind.*;
7 import java.lang.annotation.*;
8 import java.lang.reflect.*;
13 public static boolean harsh = false;
15 public static void main(String[] s) throws Exception {
17 ReflectiveMeta m = new ReflectiveMeta();
18 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
19 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
20 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
22 Union meta = mgf.get("s").build(bc);
23 Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
25 Union u = Demo.make(t, "s");
28 System.err.println("== parsing with parsed grammar =================================================================================");
29 t = new CharParser((Union)u).parse(new FileInputStream(s[1])).expand1();
30 System.out.println(t.toPrettyString());
32 System.err.println("== parsing with parsed-parsed grammar ==========================================================================");
33 t = new CharParser(new Context(t, m).build()).parse(new FileInputStream(s[1])).expand1();
34 System.out.println(t.toPrettyString());
37 public static class ReflectiveMetaPlain extends ReflectiveMeta {
38 public Object repeatTag() { return null; }
39 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
41 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
42 return Sequence.rewritingSequence(tag, els, labels, drops);
46 public static class ReflectiveMeta extends MetaGrammar.Meta {
47 private final Class _cl;
48 private final Class[] _inner;
49 public ReflectiveMeta() {
52 public ReflectiveMeta(Class c) {
54 this._inner = c.getDeclaredClasses();
56 public ReflectiveMeta(Class c, Class[] inner) {
60 private boolean match(Method m, String s) { return match(m.getAnnotation(bind.as.class), null, s); }
61 private boolean match(bind.as t, Class c, String s) {
62 if (t==null) return false;
63 if (t.value().equals(s)) return true;
64 if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
68 private boolean match(nonterminal 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;
75 private boolean match(Class c, String s, String nonTerminalName) {
76 if (match((bind.as)c.getAnnotation(bind.as.class), c, s)) return true;
77 //if (match((nonterminal)c.getAnnotation(bind.as.class), c, nonTerminalName)) return true;
80 public boolean match(Constructor con, String s, String nonTerminalName) {
81 Class c = con.getDeclaringClass();
82 if (match((bind.as)con.getAnnotation(bind.as.class), null, s)) return true;
83 //if (match((nonterminal)con.getAnnotation(bind.as.class), c, s)) return true;
86 public Object repeatTag() {
87 return new Tree.ArrayBuildingTreeFunctor<Object>();
89 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
90 Production p = new Production(tag, nonTerminalName, els, labels, drops);
91 for(Method m : _cl.getMethods())
92 if (new Target(m).isCompatible(p))
93 return new Target(m).makeSequence(p);
95 for(Constructor con : c.getConstructors())
96 if (new Target(con).isCompatible(p))
97 return new Target(con).makeSequence(p);
99 if (new Target(c).isCompatible(p))
100 return new Target(c).makeSequence(p);
103 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
104 Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
105 if (ret != null) return ret;
106 String message = "could not find a Java method/class/ctor matching tag \""+tag+
107 "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
109 throw new RuntimeException(message);
111 System.err.println(message);
112 return Sequence.rewritingSequence(tag, els, labels, drops);
118 public static class Production {
120 public String nonTerminal;
121 public Object[] labels;
122 public boolean[] drops;
123 public Element[] elements;
124 public int count = 0;
125 public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
127 this.elements = elements;
128 this.nonTerminal = nonTerminal;
129 this.labels = labels;
131 for(int i=0; i<drops.length; i++)
137 public static class Target {
138 public int[] buildSequence(Production p) {
139 Annotation[][] annotations = _bindable.getArgAnnotations();
140 String[] names = _bindable.getArgNames();
141 String name = _bindable.getSimpleName();
142 int len = annotations.length;
144 bind.arg[] argtags = new bind.arg[len];
145 for(int i=0; i<names.length; i++)
146 for(Annotation a : annotations[i+ofs])
147 if (a instanceof bind.arg)
148 argtags[i+ofs] = (bind.arg)a;
149 return Target.this.buildSequence(p, names, argtags);
151 private Bindable _bindable;
153 public Target(Object o) { this(Bindable.create(o)); }
154 public Target(Bindable b) { this._bindable = b; }
156 public String getName() { return _bindable.getSimpleName(); }
157 public bind.as getBindAs() { return (bind.as)_bindable.getAnnotation(bind.as.class); }
158 //public nonterminal getNonTerminal() { return (nonterminal)_bindable.getAnnotation(bind.as.class); }
159 public String toString() { return _bindable.getSimpleName(); }
160 public boolean isRaw() { return _bindable.isAnnotationPresent(bind.raw.class); }
162 public boolean isCompatible(Production p) {
163 bind.as t = getBindAs();
165 (t.value().equals(p.tag) ||
166 (t.value().equals("") && getName().equals(p.tag))))
167 return buildSequence(p)!=null;
169 bind.as n = getBindAs();
171 (n.value().equals(p.nonTerminal) ||
172 (n.value().equals("") && getName().equals(p.nonTerminal))))
173 return buildSequence(p)!=null;
178 public int[] buildSequence(Production p, String[] names, bind.arg[] argtags) {
180 for(int i=0; i<argtags.length; i++)
181 if (argtags[i] != null)
184 // FIXME: can be smarter here
185 if (names.length==p.count) {
186 int[] ret = new int[p.count];
187 for(int i=0; i<p.count; i++) ret[i] = i;
189 } else if (argTagged==p.count) {
190 int[] ret = new int[argtags.length];
192 for(int i=0; i<argtags.length; i++)
193 ret[i] = argtags[i]==null ? -1 : (j++);
199 public Sequence makeSequence(Production p) {
200 return Sequence.rewritingSequence(new TargetReducer(p, buildSequence(p), "reducer-"+this, _bindable, isRaw()),
201 p.elements, p.labels, p.drops);
206 public static class TargetReducer implements Tree.TreeFunctor<Object,Object> {
209 private Bindable _bindable;
210 private boolean _israw;
211 public TargetReducer(Production p, int[] map, String name, Bindable b, boolean raw) {
217 public String toString() { return name; }
218 public Object invoke(Iterable<Tree<Object>> t) {
219 if (_israw) return _bindable.impose(new Object[] { t });
220 ArrayList ret = new ArrayList();
222 if (tc.head() != null && tc.head() instanceof Functor)
223 ret.add(((Tree.TreeFunctor<Object,Object>)tc.head()).invoke(tc.children()));
224 else if (tc.numChildren() == 0)
227 System.err.println("FIXME: don't know what to do about " + tc);
231 System.err.println("input tree: " + t);
232 Object[] o = (Object[])ret.toArray(new Object[0]);
234 for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
235 Object[] o2 = new Object[max+1];
236 for(int i=0; i<o.length; i++) o2[map[i]] = o[i];
237 return _bindable.impose(o2);
242 public static Union cached = null;
243 public static Union make() {
244 if (cached != null) return cached;
246 ReflectiveMeta m = new ReflectiveMeta();
247 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
248 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
249 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
250 Union meta = mgf.get("s").build(bc);
251 Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
252 return cached = make(t, "s");
253 } catch (Exception e) {
254 throw new RuntimeException(e);
257 public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
258 public static Union make(Tree t, String s, ReflectiveMeta rm) {
259 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
260 MG.Grammar g = (MG.Grammar)red.invoke(t.children());
261 Context cx = new Context(g,rm);
263 for(MG.NonTerminal nt : g.nonterminals) {
264 System.out.println(nt.name);
265 Union el = (Union)cx.get(nt.name);
266 StringBuffer st = new StringBuffer();
268 System.err.println(st);
269 if (nt.name.equals(s)) u = el;
276 public static class MG {
277 public static @bind.as("grammar") class Grammar {
278 public NonTerminal get(String s) {
279 for(NonTerminal nt : nonterminals)
280 if (nt.name.equals(s))
284 public @bind.arg("NonTerminal") NonTerminal[] nonterminals;
285 public String toString() {
287 for(NonTerminal nt : nonterminals) ret += nt + ", ";
291 public abstract static class Un extends El {
292 public Seq[][] sequences;
293 public void build(Context cx, Union u) {
294 HashSet<Sequence> bad2 = new HashSet<Sequence>();
295 for(int i=0; i<sequences.length; i++) {
296 Seq[] group = sequences[i];
297 Union u2 = new Union();
298 if (sequences.length==1) u2 = u;
299 for(int j=0; j<group.length; j++) {
300 group[j].build(cx, u2, false);
302 if (sequences.length==1) break;
303 Sequence seq = Sequence.singleton(u2);
304 for(Sequence s : bad2) {
309 bad2.add(Sequence.singleton(u2));
313 public static class NonTerminal extends Un {
314 public String name = null;
315 public @bind.as("=") NonTerminal(@bind.arg("Word") String name,
316 @bind.arg("RHS") Seq[][] sequences) {
318 this.sequences = sequences;
320 public Element build(Context cx) { return cx.get(name); }
323 public static class AnonUn extends Un {
324 public @bind.as("(") AnonUn(Seq[][] sequences) {
325 this.sequences = sequences;
327 public Element build(Context cx) {
328 Union ret = new Union();
334 //public static @bind.as void range(char c) { }
335 public static class Range {
336 public @bind.as("range") Range(char only) { first = only; last = only; }
337 public @bind.as("-") Range(char first, char last) { this.first = first; this.last = last; }
341 public static abstract class El {
342 public String getLabel() { return null; }
343 public String getOwnerTag() { return null; }
344 public boolean drop() { return false; }
345 public abstract Element build(Context cx);
347 public static class Drop extends El {
349 public Drop(El e) { this.e = e; }
350 public String getLabel() { return null; }
351 public boolean drop() { return true; }
352 public String getOwnerTag() { return e.getOwnerTag(); }
353 public Element build(Context cx) { return e.build(cx); }
355 public static class Label extends El {
358 public Label(String label, El e) { this.e = e; this.label = label; }
359 public String getLabel() { return label; }
360 public String getOwnerTag() { return e.getOwnerTag(); }
361 public Element build(Context cx) { return e.build(cx); }
363 public static /*abstract*/ class Seq {
364 HashSet<Seq> and = new HashSet<Seq>();
365 HashSet<Seq> not = new HashSet<Seq>();
370 public Seq(El e) { this(new El[] { e }); }
371 public Seq(El[] elements) { this.elements = elements; }
372 public Seq tag(String tag) { this.tag = tag; return this; }
373 public Seq follow(El follow) { this.follow = follow; return this; }
375 Seq ret = new Seq(elements);
382 public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
383 public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
384 public Seq separate(El sep) {
385 El[] elements = new El[this.elements.length * 2 - 1];
386 for(int i=0; i<this.elements.length; i++) {
387 elements[i*2] = this.elements[i];
388 if (i<this.elements.length-1)
389 elements[i*2+1] = new Drop(sep);
391 this.elements = elements;
394 public Sequence build(Context cx, Union u, boolean lame) {
395 Sequence ret = build0(cx, lame || this.lame);
396 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
397 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
402 public Sequence build0(Context cx, boolean lame) {
403 boolean unwrap = false;
404 boolean dropAll = lame;
405 if (tag!=null && tag.equals("[]")) unwrap = true;
406 if (tag!=null && "()".equals(tag)) dropAll = true;
407 Object[] labels = new Object[elements.length];
408 boolean[] drops = new boolean[elements.length];
409 Element[] els = new Element[elements.length];
410 for(int i=0; i<elements.length; i++) {
411 labels[i] = elements[i].getLabel();
412 drops[i] = elements[i].drop();
413 els[i] = elements[i].build(cx);
414 if (elements[i].getOwnerTag() != null)
415 tag = elements[i].getOwnerTag();
418 if (dropAll) ret = Sequence.drop(els, false);
419 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
420 else if (tag!=null) {
421 ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
424 for(int i=0; i<els.length; i++)
426 if (idx==-1) idx = i;
427 else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
428 if (idx != -1) ret = Sequence.singleton(els, idx);
429 else ret = Sequence.drop(els, false);
431 if (this.follow != null)
432 ret.follow = MetaGrammar.infer(this.follow.build(cx));
433 ret.lame = this.lame;
437 public static @bind.as("&") Seq and(Seq s, El[] elements) { return s.and(seq(elements)); }
438 public static @bind.as("&~") Seq andnot(Seq s, El[] elements) { return s.andnot(seq(elements)); }
439 public static @bind.as("->") Seq arrow(Seq s, El e) { return s.follow(e); }
440 public static @bind.as("::") Seq tag(String tagname, Seq s) { return s.tag(tagname); }
441 public static @bind.as("/") Seq slash(Seq s, El e) { return s.separate(e); }
443 public static @bind.as("ps") Seq seq(El[] elements) { return new Seq(elements); }
444 public static @bind.as Seq psx(Seq s) { return s; }
445 public static @bind.as(":") El colon(String s, El e) { return new Label(s, e); }
446 public static @bind.as(")") void close(String foo) { throw new Error("not supported"); }
447 public static @bind.as("()") El epsilon() { return new Constant(Union.epsilon); }
449 public static @bind.as("nonTerminal") class NonTerminalReference extends El {
450 public @bind.arg String nonTerminal;
451 public Element build(Context cx) {
452 return cx.get(nonTerminal);
456 public static class StringLiteral extends Constant {
457 public @bind.as("literal") StringLiteral(String string) { super(CharRange.string(string)); }
458 public boolean drop() { return true; }
461 public static class CharClass extends El {
463 public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
464 public Element build(Context cx) {
465 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
466 for(Range r : ranges)
467 set.add(r.first, r.last);
468 return CharRange.set(set);
472 public static @bind.as("{") class XTree extends El {
473 public @bind.arg Seq body;
474 public Element build(Context cx) {
479 public static class Rep extends El {
481 public boolean zero, many, max;
482 public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
483 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
484 public Element build(Context cx) {
486 ? Sequence.repeat(e.build(cx), zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
488 ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many, cx.rm.repeatTag())
489 : Sequence.repeatMaximal(e.build(cx), zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
492 public static class Constant extends El {
494 public Constant(Element constant) { this.constant = constant; }
495 public Element build(Context cx) { return constant; }
497 public abstract static class PostProcess extends El {
499 public PostProcess(El e) { this.e = e; }
500 public Element build(Context cx) { return postProcess(e.build(cx)); }
501 public abstract Element postProcess(Element e);
504 // FIXME: it would be nice if we could hoist this into "Rep"
505 public static @bind.as("++") El plusmax(final El e) { return new Rep(e, null, false, true, true); }
506 public static @bind.as("+") El plus(final El e) { return new Rep(e, null, false, true, false); }
507 public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep, false, true, true); }
508 public static @bind.as("+/") El plusfollow(final El e, final El sep) { return new Rep(e, sep, false, true, false); }
509 public static @bind.as("**") El starmax(final El e) { return new Rep(e, null, true, true, true); }
510 public static @bind.as("*") El star(final El e) { return new Rep(e, null, true, true, false); }
511 public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep, true, true, true); }
512 public static @bind.as("*/") El starfollow(final El e, final El sep) { return new Rep(e, sep, true, true, false); }
513 public static @bind.as("?") El question(final El e) { return new Rep(e, null, true, true, false); }
515 public static @bind.as("!") El bang(final El e) { return new Drop(e); }
517 public static @bind.as("^") El caret(final String s) {
518 return new Drop(new Constant(CharRange.string(s)) {
519 public String getOwnerTag() { return s; }
523 public static @bind.as("~") El tilde(final El e) {
524 return new PostProcess(e) {
525 public Element postProcess(Element e) {
526 return MetaGrammar.infer((Topology<Character>)Atom.toAtom(e).complement());
529 public static @bind.as("^^") void doublecaret(final El e) { throw new Error("not implemented"); }
531 //public static @bind.as("(") El subexpression(Seq[][] rhs) { return new NonTerminal(rhs); }
533 public static @bind.as("Word") String word(String s) { return s; }
534 public static @bind.as("Quoted") String quoted(String s) { return s; }
535 public static @bind.as("escaped") String c(char c) { return c+""; }
536 public static @bind.as("\"\"") String emptystring() { return ""; }
537 public static @bind.as("\n") String retur() { return "\n"; }
538 public static @bind.as("\r") String lf() { return "\r"; }
541 public static class Context {
542 HashMap<String,Union> map = new HashMap<String,Union>();
543 private MG.Grammar grammar;
544 public String cnt = null;
545 private ReflectiveMeta rm;
546 public Context(MG.Grammar g, ReflectiveMeta rm) {
550 public Union build() {
552 for(MG.NonTerminal nt : grammar.nonterminals) {
553 Union u = get(nt.name);
554 if ("s".equals(nt.name))
559 public Context(Tree t, ReflectiveMeta rm) {
561 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
562 this.grammar = (MG.Grammar)red.invoke(t.children());
564 public Union peek(String name) { return map.get(name); }
565 public void put(String name, Union u) { map.put(name, u); }
566 public Union get(String name) {
567 Union ret = map.get(name);
568 if (ret != null) return ret;
569 ret = new Union(name);
571 MG.NonTerminal nt = grammar.get(name);
573 System.err.println("*** warning could not find " + name);