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.*;
11 public class MetaGrammar {
13 public static boolean harsh = true;
15 public static void main(String[] args) throws Exception {
16 if (args.length != 2) {
17 System.err.println("usage: java " + MetaGrammar.class.getName() + " grammarfile.g com.yourdomain.package.ClassName");
20 //StringBuffer sbs = new StringBuffer();
21 //((MetaGrammar)new MetaGrammar().walk(meta)).nt.get("e").toString(sbs);
22 //System.err.println(sbs);
23 String className = args[1].substring(args[1].lastIndexOf('.')+1);
24 String packageName = args[1].substring(0, args[1].lastIndexOf('.'));
25 String fileName = packageName.replace('.', '/') + "/" + className + ".java";
27 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
28 StringBuffer out = new StringBuffer();
31 for(String s = br.readLine(); s != null; s = br.readLine()) {
32 if (s.indexOf("DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) skip = true;
33 if (s.indexOf("DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) break;
34 if (!skip) out.append(s+"\n");
37 out.append("\n // DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED\n");
40 ReflectiveMeta m = new ReflectiveMeta();
41 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(args[0])).expand1();
42 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
43 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
45 Union meta = mgf.get("s").build(bc);
46 Tree t = new CharParser(meta).parse(new FileInputStream(args[0])).expand1();
48 Tree t = MetaGrammarTree.meta;
49 Union u = MetaGrammar.make(t, "s");
52 System.err.println("== parsing with parsed grammar =================================================================================");
53 t = new CharParser((Union)u).parse(new FileInputStream(args[0])).expand1();
54 System.out.println(t.toPrettyString());
55 //Forest<String> fs = new CharParser(make()).parse(new FileInputStream(args[0]));
56 //System.out.println(fs.expand1());
58 //GraphViz gv = new GraphViz();
60 //FileOutputStream fox = new FileOutputStream("out.dot");
65 out.append("\n // DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED\n");
67 for(String s = br.readLine(); s != null; s = br.readLine()) out.append(s+"\n");
70 OutputStream os = new FileOutputStream(fileName);
71 PrintWriter p = new PrintWriter(new OutputStreamWriter(os));
72 p.println(out.toString());
77 public static class ReflectiveMetaPlain extends ReflectiveMeta {
78 public Object repeatTag() { return null; }
79 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
81 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
82 return Sequence.rewritingSequence(tag, els, labels, drops);
86 public static class ReflectiveMeta /*extends MetaGrammar.Meta*/ {
87 private final Class _cl;
88 private final Class[] _inner;
89 public ReflectiveMeta() {
92 public ReflectiveMeta(Class c) {
94 this._inner = c.getDeclaredClasses();
96 public ReflectiveMeta(Class c, Class[] inner) {
100 public Object repeatTag() {
101 return new Tree.ArrayBuildingTreeFunctor<Object>();
103 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
104 Production p = new Production(tag, nonTerminalName, els, labels, drops);
105 for(Method m : _cl.getMethods())
106 if (new Target(m).isCompatible(p))
107 return new Target(m).makeSequence(p);
108 for(Class c : _inner)
109 for(Constructor con : c.getConstructors())
110 if (new Target(con).isCompatible(p))
111 return new Target(con).makeSequence(p);
112 for(Class c : _inner)
113 if (new Target(c).isCompatible(p))
114 return new Target(c).makeSequence(p);
117 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
118 Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
119 if (ret != null) return ret;
120 String message = "could not find a Java method/class/ctor matching tag \""+tag+
121 "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
123 throw new RuntimeException(message);
125 System.err.println(message);
126 return Sequence.rewritingSequence(tag, els, labels, drops);
132 public static class Production {
134 public String nonTerminal;
135 public Object[] labels;
136 public boolean[] drops;
137 public Element[] elements;
138 public int count = 0;
139 public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
141 this.elements = elements;
142 this.nonTerminal = nonTerminal;
143 this.labels = labels;
145 for(int i=0; i<drops.length; i++)
151 public static class Target {
152 public int[] buildSequence(Production p) {
153 Annotation[][] annotations = _bindable.getArgAnnotations();
154 String[] names = _bindable.getArgNames();
155 String name = _bindable.getSimpleName();
156 int len = annotations.length;
158 bind.arg[] argtags = new bind.arg[len];
159 for(int i=0; i<names.length; i++)
160 for(Annotation a : annotations[i+ofs])
161 if (a instanceof bind.arg)
162 argtags[i+ofs] = (bind.arg)a;
163 return Target.this.buildSequence(p, names, argtags);
165 private Bindable _bindable;
167 public Target(Object o) { this(Bindable.create(o)); }
168 public Target(Bindable b) { this._bindable = b; }
170 public String getName() { return _bindable.getSimpleName(); }
171 public bind getBind() {
172 return (bind)_bindable.getAnnotation(bind.class); }
173 public bind.as getBindAs() {
174 return (bind.as)_bindable.getAnnotation(bind.as.class); }
175 //public nonterminal getNonTerminal() { return (nonterminal)_bindable.getAnnotation(bind.as.class); }
176 public String toString() { return _bindable.getSimpleName(); }
177 public boolean isRaw() { return _bindable.isAnnotationPresent(bind.raw.class); }
179 public boolean isCompatible(Production p) {
180 bind.as t = getBindAs();
182 (t.value().equals(p.tag) ||
183 (t.value().equals("") && getName().equals(p.tag))))
184 return buildSequence(p)!=null;
187 System.out.println(_bindable.getClass().getSimpleName() + ": " + _bindable.getSimpleName());
188 if (b != null && getName().equals(p.tag))
189 return buildSequence(p)!=null;
191 bind.as n = getBindAs();
193 (n.value().equals(p.nonTerminal) ||
194 (n.value().equals("") && getName().equals(p.nonTerminal))))
195 return buildSequence(p)!=null;
197 if (b != null && getName().equals(p.nonTerminal))
198 return buildSequence(p)!=null;
203 public int[] buildSequence(Production p, String[] names, bind.arg[] argtags) {
205 for(int i=0; i<argtags.length; i++)
206 if (argtags[i] != null)
209 // FIXME: can be smarter here
210 if (names.length==p.count) {
211 int[] ret = new int[p.count];
212 for(int i=0; i<p.count; i++) ret[i] = i;
214 } else if (argTagged==p.count) {
215 int[] ret = new int[argtags.length];
217 for(int i=0; i<argtags.length; i++)
218 ret[i] = argtags[i]==null ? -1 : (j++);
224 public Sequence makeSequence(Production p) {
225 return Sequence.rewritingSequence(new TargetReducer(buildSequence(p), _bindable, isRaw()),
226 p.elements, p.labels, p.drops);
231 public static class TargetReducer implements Tree.TreeFunctor<Object,Object>, ToJava {
233 private Bindable _bindable;
234 private boolean _israw;
236 public void toJava(StringBuffer sb) {
237 sb.append("new MetaGrammar.TargetReducer(new int[] {");
238 for(int i=0; i<map.length; i++)
239 sb.append((i+"")+(i<map.length-1 ? "," : ""));
241 _bindable.toJava(sb);
243 sb.append(_israw ? "true" : "false");
247 public TargetReducer(int[] map, Bindable b, boolean raw) {
252 public String toString() { return "reducer-"+_bindable.toString(); }
253 public Object invoke(Iterable<Tree<Object>> t) {
254 if (_israw) return _bindable.impose(new Object[] { t });
255 ArrayList ret = new ArrayList();
257 if (tc.head() != null && tc.head() instanceof Functor)
258 ret.add(((Tree.TreeFunctor<Object,Object>)tc.head()).invoke(tc.children()));
259 else if (tc.numChildren() == 0)
262 System.err.println("FIXME: don't know what to do about " + tc);
266 System.err.println("input tree: " + t);
267 Object[] o = (Object[])ret.toArray(new Object[0]);
269 for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
270 Object[] o2 = new Object[max+1];
271 for(int i=0; i<o.length; i++) o2[map[i]] = o[i];
272 return _bindable.impose(o2);
277 public static Union cached = null;
278 public static Union make() {
280 if (cached != null) return cached;
282 ReflectiveMeta m = new ReflectiveMeta();
283 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
284 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
285 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
286 Union meta = mgf.get("s").build(bc);
287 Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
288 return cached = make(t, "s");
289 } catch (Exception e) {
290 throw new RuntimeException(e);
293 return make(MetaGrammarTree.meta, "s");
295 public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
296 public static Union make(Tree t, String s, ReflectiveMeta rm) {
297 System.out.println("Head: " + t.head());
298 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
299 MG.Grammar g = (MG.Grammar)red.invoke(t.children());
300 Context cx = new Context(g,rm);
302 for(MG.NonTerminal nt : g.nonterminals) {
303 System.out.println(nt.name);
304 Union el = (Union)cx.get(nt.name);
305 StringBuffer st = new StringBuffer();
307 System.err.println(st);
308 if (nt.name.equals(s)) u = el;
315 public static class MG {
316 public static @bind class Grammar {
317 public NonTerminal get(String s) {
318 for(NonTerminal nt : nonterminals)
319 if (nt.name.equals(s))
323 public @bind.arg NonTerminal[] nonterminals;
324 public String toString() {
326 for(NonTerminal nt : nonterminals) ret += nt + ", ";
330 public abstract static class Un extends El {
331 public Seq[][] sequences;
332 public void build(Context cx, Union u) {
333 HashSet<Sequence> bad2 = new HashSet<Sequence>();
334 for(int i=0; i<sequences.length; i++) {
335 Seq[] group = sequences[i];
336 Union u2 = new Union();
337 if (sequences.length==1) u2 = u;
338 for(int j=0; j<group.length; j++) {
339 group[j].build(cx, u2, false);
341 if (sequences.length==1) break;
342 Sequence seq = Sequence.singleton(u2);
343 for(Sequence s : bad2) {
348 bad2.add(Sequence.singleton(u2));
352 public static class NonTerminal extends Un {
353 public String name = null;
354 public @bind.as("NonTerminal") NonTerminal(@bind.arg("Word") String name,
355 @bind.arg("RHS") Seq[][] sequences) {
357 this.sequences = sequences;
359 public Element build(Context cx) { return cx.get(name); }
362 public static class AnonUn extends Un {
363 public @bind.as("(") AnonUn(Seq[][] sequences) {
364 this.sequences = sequences;
366 public Element build(Context cx) {
367 Union ret = new Union();
373 //public static @bind.as void range(char c) { }
374 public static class Range {
375 public @bind.as("range") Range(char only) { first = only; last = only; }
376 public @bind.as("-") Range(char first, char last) { this.first = first; this.last = last; }
380 public static abstract class El {
381 public String getLabel() { return null; }
382 public String getOwnerTag() { return null; }
383 public boolean drop() { return false; }
384 public abstract Element build(Context cx);
386 public static class Drop extends El {
388 public Drop(El e) { this.e = e; }
389 public String getLabel() { return null; }
390 public boolean drop() { return true; }
391 public String getOwnerTag() { return e.getOwnerTag(); }
392 public Element build(Context cx) { return e.build(cx); }
394 public static class Label extends El {
397 public Label(String label, El e) { this.e = e; this.label = label; }
398 public String getLabel() { return label; }
399 public String getOwnerTag() { return e.getOwnerTag(); }
400 public Element build(Context cx) { return e.build(cx); }
402 public static /*abstract*/ class Seq {
403 HashSet<Seq> and = new HashSet<Seq>();
404 HashSet<Seq> not = new HashSet<Seq>();
409 public Seq(El e) { this(new El[] { e }); }
410 public Seq(El[] elements) { this.elements = elements; }
411 public Seq tag(String tag) { this.tag = tag; return this; }
412 public Seq follow(El follow) { this.follow = follow; return this; }
414 Seq ret = new Seq(elements);
421 public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
422 public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
423 public Seq separate(El sep) {
424 El[] elements = new El[this.elements.length * 2 - 1];
425 for(int i=0; i<this.elements.length; i++) {
426 elements[i*2] = this.elements[i];
427 if (i<this.elements.length-1)
428 elements[i*2+1] = new Drop(sep);
430 this.elements = elements;
433 public Sequence build(Context cx, Union u, boolean lame) {
434 Sequence ret = build0(cx, lame || this.lame);
435 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
436 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
441 public Sequence build0(Context cx, boolean lame) {
442 boolean unwrap = false;
443 boolean dropAll = lame;
444 if (tag!=null && tag.equals("[]")) unwrap = true;
445 if (tag!=null && "()".equals(tag)) dropAll = true;
446 Object[] labels = new Object[elements.length];
447 boolean[] drops = new boolean[elements.length];
448 Element[] els = new Element[elements.length];
449 for(int i=0; i<elements.length; i++) {
450 labels[i] = elements[i].getLabel();
451 drops[i] = elements[i].drop();
452 els[i] = elements[i].build(cx);
453 if (elements[i].getOwnerTag() != null)
454 tag = elements[i].getOwnerTag();
457 if (dropAll) ret = Sequence.drop(els, false);
458 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
459 else if (tag!=null) {
460 ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
462 ret = cx.rm.tryResolveTag(tag, cx.cnt, els, labels, drops);
465 for(int i=0; i<els.length; i++)
467 if (idx==-1) idx = i;
468 else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
469 if (idx != -1) ret = Sequence.singleton(els, idx);
470 else ret = Sequence.drop(els, false);
473 if (this.follow != null)
474 ret.follow = infer(this.follow.build(cx));
475 ret.lame = this.lame;
479 public static @bind.as("&") Seq and(Seq s, El[] elements) { return s.and(seq(elements)); }
480 public static @bind.as("&~") Seq andnot(Seq s, El[] elements) { return s.andnot(seq(elements)); }
481 public static @bind.as("->") Seq arrow(Seq s, El e) { return s.follow(e); }
482 public static @bind.as("::") Seq tag(String tagname, Seq s) { return s.tag(tagname); }
483 public static @bind.as("/") Seq slash(Seq s, El e) { return s.separate(e); }
485 public static @bind.as("ps") Seq seq(El[] elements) { return new Seq(elements); }
486 public static @bind.as Seq psx(Seq s) { return s; }
487 public static @bind.as(":") El colon(String s, El e) { return new Label(s, e); }
488 public static @bind.as(")") void close(String foo) { throw new Error("not supported"); }
489 public static @bind.as("()") El epsilon() { return new Constant(Union.epsilon); }
491 public static @bind.as("nonTerminal") class NonTerminalReference extends El {
492 public @bind.arg String nonTerminal;
493 public Element build(Context cx) {
494 return cx.get(nonTerminal);
498 public static class StringLiteral extends Constant {
499 public @bind.as("literal") StringLiteral(String string) { super(CharRange.string(string)); }
500 public boolean drop() { return true; }
503 public static class CharClass extends El {
505 public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
506 public Element build(Context cx) {
507 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
508 for(Range r : ranges)
509 set.add(r.first, r.last);
510 return CharRange.set(set);
514 public static @bind.as("{") class XTree extends El {
515 public @bind.arg Seq body;
516 public Element build(Context cx) {
521 public static class Rep extends El {
523 public boolean zero, many, max;
524 public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
525 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
526 public Element build(Context cx) {
528 ? Sequence.repeat(e.build(cx), zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
530 ? Sequence.repeatMaximal(infer(e.build(cx)), zero, many, cx.rm.repeatTag())
531 : Sequence.repeatMaximal(e.build(cx), zero, many, infer(sep.build(cx)), cx.rm.repeatTag());
534 public static class Constant extends El {
536 public Constant(Element constant) { this.constant = constant; }
537 public Element build(Context cx) { return constant; }
539 public abstract static class PostProcess extends El {
541 public PostProcess(El e) { this.e = e; }
542 public Element build(Context cx) { return postProcess(e.build(cx)); }
543 public abstract Element postProcess(Element e);
546 // FIXME: it would be nice if we could hoist this into "Rep"
547 public static @bind.as("++") El plusmax(final El e) { return new Rep(e, null, false, true, true); }
548 public static @bind.as("+") El plus(final El e) { return new Rep(e, null, false, true, false); }
549 public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep, false, true, true); }
550 public static @bind.as("+/") El plusfollow(final El e, final El sep) { return new Rep(e, sep, false, true, false); }
551 public static @bind.as("**") El starmax(final El e) { return new Rep(e, null, true, true, true); }
552 public static @bind.as("*") El star(final El e) { return new Rep(e, null, true, true, false); }
553 public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep, true, true, true); }
554 public static @bind.as("*/") El starfollow(final El e, final El sep) { return new Rep(e, sep, true, true, false); }
555 public static @bind.as("?") El question(final El e) { return new Rep(e, null, true, true, false); }
557 public static @bind.as("!") El bang(final El e) { return new Drop(e); }
559 public static @bind.as("^") El caret(final String s) {
560 return new Drop(new Constant(CharRange.string(s)) {
561 public String getOwnerTag() { return s; }
565 public static @bind.as("~") El tilde(final El e) {
566 return new PostProcess(e) {
567 public Element postProcess(Element e) {
568 return infer((Topology<Character>)Atom.toAtom(e).complement());
571 public static @bind.as("^^") void doublecaret(final El e) { throw new Error("not implemented"); }
573 //public static @bind.as("(") El subexpression(Seq[][] rhs) { return new NonTerminal(rhs); }
575 public static @bind.as("Word") String word(String s) { return s; }
576 public static @bind.as("Quoted") String quoted(String s) { return s; }
577 public static @bind.as("escaped") String c(char c) { return c+""; }
578 public static @bind.as("\"\"") String emptystring() { return ""; }
579 public static @bind.as("\n") String retur() { return "\n"; }
580 public static @bind.as("\r") String lf() { return "\r"; }
583 public static class Context {
584 HashMap<String,Union> map = new HashMap<String,Union>();
585 private MG.Grammar grammar;
586 public String cnt = null;
587 private ReflectiveMeta rm;
588 public Context(MG.Grammar g, ReflectiveMeta rm) {
592 public Union build() {
594 for(MG.NonTerminal nt : grammar.nonterminals) {
595 Union u = get(nt.name);
596 if ("s".equals(nt.name))
601 public Context(Tree t, ReflectiveMeta rm) {
603 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
604 this.grammar = (MG.Grammar)red.invoke(t.children());
606 public Union peek(String name) { return map.get(name); }
607 public void put(String name, Union u) { map.put(name, u); }
608 public Union get(String name) {
609 Union ret = map.get(name);
610 if (ret != null) return ret;
611 ret = new Union(name);
613 MG.NonTerminal nt = grammar.get(name);
615 System.err.println("*** warning could not find " + name);
626 /*private*/ static Atom infer(Element e) { return infer((Topology<Character>)Atom.toAtom(e)); }
627 /*private*/ static Atom infer(Topology<Character> t) { return new CharRange(new CharTopology(t)); }