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 Reflection.Bindable _bindable;
153 public Target(Object o) { this(Reflection.Bindable.create(o)); }
154 public Target(Reflection.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);
204 public static class TargetReducer implements Tree.TreeFunctor<Object,Object> {
205 private Production p;
208 private Reflection.Bindable _bindable;
209 private boolean _israw;
210 public TargetReducer(Production p, int[] map, String name, Reflection.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);
244 public static Union cached = null;
245 public static Union make() {
246 if (cached != null) return cached;
248 ReflectiveMeta m = new ReflectiveMeta();
249 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
250 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
251 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
252 Union meta = mgf.get("s").build(bc);
253 Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
254 return cached = make(t, "s");
255 } catch (Exception e) {
256 throw new RuntimeException(e);
259 public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
260 public static Union make(Tree t, String s, ReflectiveMeta rm) {
261 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
262 MG.Grammar g = (MG.Grammar)red.invoke(t.children());
263 Context cx = new Context(g,rm);
265 for(MG.NonTerminal nt : g.nonterminals) {
266 System.out.println(nt.name);
267 Union el = (Union)cx.get(nt.name);
268 StringBuffer st = new StringBuffer();
270 System.err.println(st);
271 if (nt.name.equals(s)) u = el;
278 public static class MG {
279 public static @bind.as("grammar") class Grammar {
280 public NonTerminal get(String s) {
281 for(NonTerminal nt : nonterminals)
282 if (nt.name.equals(s))
286 public @bind.arg("NonTerminal") NonTerminal[] nonterminals;
287 public String toString() {
289 for(NonTerminal nt : nonterminals) ret += nt + ", ";
293 public abstract static class Un extends El {
294 public Seq[][] sequences;
295 public void build(Context cx, Union u) {
296 HashSet<Sequence> bad2 = new HashSet<Sequence>();
297 for(int i=0; i<sequences.length; i++) {
298 Seq[] group = sequences[i];
299 Union u2 = new Union();
300 if (sequences.length==1) u2 = u;
301 for(int j=0; j<group.length; j++) {
302 group[j].build(cx, u2, false);
304 if (sequences.length==1) break;
305 Sequence seq = Sequence.singleton(u2);
306 for(Sequence s : bad2) {
311 bad2.add(Sequence.singleton(u2));
315 public static class NonTerminal extends Un {
316 public String name = null;
317 public @bind.as("=") NonTerminal(@bind.arg("Word") String name,
318 @bind.arg("RHS") Seq[][] sequences) {
320 this.sequences = sequences;
322 public Element build(Context cx) { return cx.get(name); }
325 public static class AnonUn extends Un {
326 public @bind.as("(") AnonUn(Seq[][] sequences) {
327 this.sequences = sequences;
329 public Element build(Context cx) {
330 Union ret = new Union();
336 //public static @bind.as void range(char c) { }
337 public static class Range {
338 public @bind.as("range") Range(char only) { first = only; last = only; }
339 public @bind.as("-") Range(char first, char last) { this.first = first; this.last = last; }
343 public static abstract class El {
344 public String getLabel() { return null; }
345 public String getOwnerTag() { return null; }
346 public boolean drop() { return false; }
347 public abstract Element build(Context cx);
349 public static class Drop extends El {
351 public Drop(El e) { this.e = e; }
352 public String getLabel() { return null; }
353 public boolean drop() { return true; }
354 public String getOwnerTag() { return e.getOwnerTag(); }
355 public Element build(Context cx) { return e.build(cx); }
357 public static class Label extends El {
360 public Label(String label, El e) { this.e = e; this.label = label; }
361 public String getLabel() { return label; }
362 public String getOwnerTag() { return e.getOwnerTag(); }
363 public Element build(Context cx) { return e.build(cx); }
365 public static /*abstract*/ class Seq {
366 HashSet<Seq> and = new HashSet<Seq>();
367 HashSet<Seq> not = new HashSet<Seq>();
372 public Seq(El e) { this(new El[] { e }); }
373 public Seq(El[] elements) { this.elements = elements; }
374 public Seq tag(String tag) { this.tag = tag; return this; }
375 public Seq follow(El follow) { this.follow = follow; return this; }
377 Seq ret = new Seq(elements);
384 public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
385 public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
386 public Seq separate(El sep) {
387 El[] elements = new El[this.elements.length * 2 - 1];
388 for(int i=0; i<this.elements.length; i++) {
389 elements[i*2] = this.elements[i];
390 if (i<this.elements.length-1)
391 elements[i*2+1] = new Drop(sep);
393 this.elements = elements;
396 public Sequence build(Context cx, Union u, boolean lame) {
397 Sequence ret = build0(cx, lame || this.lame);
398 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
399 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
404 public Sequence build0(Context cx, boolean lame) {
405 boolean unwrap = false;
406 boolean dropAll = lame;
407 if (tag!=null && tag.equals("[]")) unwrap = true;
408 if (tag!=null && "()".equals(tag)) dropAll = true;
409 Object[] labels = new Object[elements.length];
410 boolean[] drops = new boolean[elements.length];
411 Element[] els = new Element[elements.length];
412 for(int i=0; i<elements.length; i++) {
413 labels[i] = elements[i].getLabel();
414 drops[i] = elements[i].drop();
415 els[i] = elements[i].build(cx);
416 if (elements[i].getOwnerTag() != null)
417 tag = elements[i].getOwnerTag();
420 if (dropAll) ret = Sequence.drop(els, false);
421 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
422 else if (tag!=null) {
423 ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
426 for(int i=0; i<els.length; i++)
428 if (idx==-1) idx = i;
429 else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
430 if (idx != -1) ret = Sequence.singleton(els, idx);
431 else ret = Sequence.drop(els, false);
433 if (this.follow != null)
434 ret.follow = MetaGrammar.infer(this.follow.build(cx));
435 ret.lame = this.lame;
439 public static @bind.as("&") Seq and(Seq s, El[] elements) { return s.and(seq(elements)); }
440 public static @bind.as("&~") Seq andnot(Seq s, El[] elements) { return s.andnot(seq(elements)); }
441 public static @bind.as("->") Seq arrow(Seq s, El e) { return s.follow(e); }
442 public static @bind.as("::") Seq tag(String tagname, Seq s) { return s.tag(tagname); }
443 public static @bind.as("/") Seq slash(Seq s, El e) { return s.separate(e); }
445 public static @bind.as("ps") Seq seq(El[] elements) { return new Seq(elements); }
446 public static @bind.as Seq psx(Seq s) { return s; }
447 public static @bind.as(":") El colon(String s, El e) { return new Label(s, e); }
448 public static @bind.as(")") void close(String foo) { throw new Error("not supported"); }
449 public static @bind.as("()") El epsilon() { return new Constant(Union.epsilon); }
451 public static @bind.as("nonTerminal") class NonTerminalReference extends El {
452 public @bind.arg String nonTerminal;
453 public Element build(Context cx) {
454 return cx.get(nonTerminal);
458 public static class StringLiteral extends Constant {
459 public @bind.as("literal") StringLiteral(String string) { super(CharRange.string(string)); }
460 public boolean drop() { return true; }
463 public static class CharClass extends El {
465 public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
466 public Element build(Context cx) {
467 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
468 for(Range r : ranges)
469 set.add(r.first, r.last);
470 return CharRange.set(set);
474 public static @bind.as("{") class XTree extends El {
475 public @bind.arg Seq body;
476 public Element build(Context cx) {
481 public static class Rep extends El {
483 public boolean zero, many, max;
484 public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
485 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
486 public Element build(Context cx) {
488 ? Sequence.repeat(e.build(cx), zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
490 ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many, cx.rm.repeatTag())
491 : Sequence.repeatMaximal(e.build(cx), zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
494 public static class Constant extends El {
496 public Constant(Element constant) { this.constant = constant; }
497 public Element build(Context cx) { return constant; }
499 public abstract static class PostProcess extends El {
501 public PostProcess(El e) { this.e = e; }
502 public Element build(Context cx) { return postProcess(e.build(cx)); }
503 public abstract Element postProcess(Element e);
506 // FIXME: it would be nice if we could hoist this into "Rep"
507 public static @bind.as("++") El plusmax(final El e) { return new Rep(e, null, false, true, true); }
508 public static @bind.as("+") El plus(final El e) { return new Rep(e, null, false, true, false); }
509 public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep, false, true, true); }
510 public static @bind.as("+/") El plusfollow(final El e, final El sep) { return new Rep(e, sep, false, true, false); }
511 public static @bind.as("**") El starmax(final El e) { return new Rep(e, null, true, true, true); }
512 public static @bind.as("*") El star(final El e) { return new Rep(e, null, true, true, false); }
513 public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep, true, true, true); }
514 public static @bind.as("*/") El starfollow(final El e, final El sep) { return new Rep(e, sep, true, true, false); }
515 public static @bind.as("?") El question(final El e) { return new Rep(e, null, true, true, false); }
517 public static @bind.as("!") El bang(final El e) { return new Drop(e); }
519 public static @bind.as("^") El caret(final String s) {
520 return new Drop(new Constant(CharRange.string(s)) {
521 public String getOwnerTag() { return s; }
525 public static @bind.as("~") El tilde(final El e) {
526 return new PostProcess(e) {
527 public Element postProcess(Element e) {
528 return MetaGrammar.infer((Topology<Character>)Atom.toAtom(e).complement());
531 public static @bind.as("^^") void doublecaret(final El e) { throw new Error("not implemented"); }
533 //public static @bind.as("(") El subexpression(Seq[][] rhs) { return new NonTerminal(rhs); }
535 public static @bind.as("Word") String word(String s) { return s; }
536 public static @bind.as("Quoted") String quoted(String s) { return s; }
537 public static @bind.as("escaped") String c(char c) { return c+""; }
538 public static @bind.as("\"\"") String emptystring() { return ""; }
539 public static @bind.as("\n") String retur() { return "\n"; }
540 public static @bind.as("\r") String lf() { return "\r"; }
543 public static class Context {
544 HashMap<String,Union> map = new HashMap<String,Union>();
545 private MG.Grammar grammar;
546 public String cnt = null;
547 private ReflectiveMeta rm;
548 public Context(MG.Grammar g, ReflectiveMeta rm) {
552 public Union build() {
554 for(MG.NonTerminal nt : grammar.nonterminals) {
555 Union u = get(nt.name);
556 if ("s".equals(nt.name))
561 public Context(Tree t, ReflectiveMeta rm) {
563 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
564 this.grammar = (MG.Grammar)red.invoke(t.children());
566 public Union peek(String name) { return map.get(name); }
567 public void put(String name, Union u) { map.put(name, u); }
568 public Union get(String name) {
569 Union ret = map.get(name);
570 if (ret != null) return ret;
571 ret = new Union(name);
573 MG.NonTerminal nt = grammar.get(name);
575 System.err.println("*** warning could not find " + name);