1 package edu.berkeley.sbp.meta;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import edu.berkeley.sbp.misc.*;
6 import edu.berkeley.sbp.bind.*;
8 import java.lang.annotation.*;
9 import java.lang.reflect.*;
12 public class MetaGrammar {
14 public static boolean harsh = true;
16 public static void main(String[] args) throws Exception {
17 if (args.length != 2) {
18 System.err.println("usage: java " + MetaGrammar.class.getName() + " grammarfile.g com.yourdomain.package.ClassName");
21 //StringBuffer sbs = new StringBuffer();
22 //((MetaGrammar)new MetaGrammar().walk(meta)).nt.get("e").toString(sbs);
23 //System.err.println(sbs);
24 String className = args[1].substring(args[1].lastIndexOf('.')+1);
25 String packageName = args[1].substring(0, args[1].lastIndexOf('.'));
26 String fileName = packageName.replace('.', '/') + "/" + className + ".java";
28 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
29 StringBuffer out = new StringBuffer();
32 for(String s = br.readLine(); s != null; s = br.readLine()) {
33 if (s.indexOf("DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) skip = true;
34 if (s.indexOf("DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) break;
35 if (!skip) out.append(s+"\n");
38 out.append("\n // DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED\n");
41 ReflectiveMeta m = new ReflectiveMeta();
42 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(args[0])).expand1();
43 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
44 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
46 Union meta = mgf.get("s").build(bc);
47 Tree t = new CharParser(meta).parse(new FileInputStream(args[0])).expand1();
49 Tree t = MetaGrammarTree.meta;
50 Union u = MetaGrammar.make(t, "s");
53 System.err.println("== parsing with parsed grammar =================================================================================");
54 t = new CharParser((Union)u).parse(new FileInputStream(args[0])).expand1();
55 System.out.println(t.toPrettyString());
56 //Forest<String> fs = new CharParser(make()).parse(new FileInputStream(args[0]));
57 //System.out.println(fs.expand1());
59 //GraphViz gv = new GraphViz();
61 //FileOutputStream fox = new FileOutputStream("out.dot");
66 out.append("\n // DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED\n");
68 for(String s = br.readLine(); s != null; s = br.readLine()) out.append(s+"\n");
71 OutputStream os = new FileOutputStream(fileName);
72 PrintWriter p = new PrintWriter(new OutputStreamWriter(os));
73 p.println(out.toString());
78 public static class ReflectiveMetaPlain extends ReflectiveMeta {
79 public Object repeatTag() { return null; }
80 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
82 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
83 return Sequence.rewritingSequence(tag, els, labels, drops);
87 public static class ReflectiveMeta /*extends MetaGrammar.Meta*/ {
88 private final Class _cl;
89 private final Class[] _inner;
90 public ReflectiveMeta() {
93 public ReflectiveMeta(Class c) {
95 this._inner = c.getDeclaredClasses();
97 public ReflectiveMeta(Class c, Class[] inner) {
101 public Object repeatTag() {
102 return new Tree.ArrayBuildingTreeFunctor<Object>();
104 public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
105 Production p = new Production(tag, nonTerminalName, els, labels, drops);
106 for(Method m : _cl.getMethods())
107 if (new Target(m).isCompatible(p))
108 return new Target(m).makeSequence(p);
109 for(Class c : _inner)
110 for(Constructor con : c.getConstructors())
111 if (new Target(con).isCompatible(p))
112 return new Target(con).makeSequence(p);
113 for(Class c : _inner)
114 if (new Target(c).isCompatible(p))
115 return new Target(c).makeSequence(p);
118 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
119 Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
120 if (ret != null) return ret;
121 String message = "could not find a Java method/class/ctor matching tag \""+tag+
122 "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
124 throw new RuntimeException(message);
126 System.err.println(message);
127 return Sequence.rewritingSequence(tag, els, labels, drops);
133 public static class Production {
135 public String nonTerminal;
136 public Object[] labels;
137 public boolean[] drops;
138 public Element[] elements;
139 public int count = 0;
140 public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
142 this.elements = elements;
143 this.nonTerminal = nonTerminal;
144 this.labels = labels;
146 for(int i=0; i<drops.length; i++)
152 public static class Target {
153 public int[] buildSequence(Production p) {
154 Annotation[][] annotations = _bindable.getArgAnnotations();
155 String[] names = _bindable.getArgNames();
156 String name = _bindable.getSimpleName();
157 int len = annotations.length;
159 bind.arg[] argtags = new bind.arg[len];
160 for(int i=0; i<names.length; i++)
161 for(Annotation a : annotations[i+ofs])
162 if (a instanceof bind.arg)
163 argtags[i+ofs] = (bind.arg)a;
164 return Target.this.buildSequence(p, names, argtags);
166 private Bindable _bindable;
168 public Target(Object o) { this(Bindable.create(o)); }
169 public Target(Bindable b) { this._bindable = b; }
171 public String getName() { return _bindable.getSimpleName(); }
172 public bind getBind() { return (bind)_bindable.getAnnotation(bind.class); }
173 public bind.as getBindAs() { return (bind.as)_bindable.getAnnotation(bind.as.class); }
174 public String toString() { return _bindable.getSimpleName(); }
175 public boolean isRaw() { return _bindable.isAnnotationPresent(bind.raw.class); }
177 public boolean isCompatible(Production p) {
178 bind.as t = getBindAs();
180 (t.value().equals(p.tag) ||
181 (t.value().equals("") && getName().equals(p.tag))))
182 return buildSequence(p)!=null;
185 System.out.println(_bindable.getClass().getSimpleName() + ": " + _bindable.getSimpleName());
186 if (b != null && getName().equals(p.tag))
187 return buildSequence(p)!=null;
189 bind.as n = getBindAs();
191 (n.value().equals(p.nonTerminal) ||
192 (n.value().equals("") && getName().equals(p.nonTerminal))))
193 return buildSequence(p)!=null;
195 if (b != null && getName().equals(p.nonTerminal))
196 return buildSequence(p)!=null;
201 public int[] buildSequence(Production p, String[] names, bind.arg[] argtags) {
203 for(int i=0; i<argtags.length; i++)
204 if (argtags[i] != null)
207 // FIXME: can be smarter here
208 if (names.length==p.count) {
209 int[] ret = new int[p.count];
210 for(int i=0; i<p.count; i++) ret[i] = i;
212 } else if (argTagged==p.count) {
213 int[] ret = new int[argtags.length];
215 for(int i=0; i<argtags.length; i++)
216 ret[i] = argtags[i]==null ? -1 : (j++);
222 public Sequence makeSequence(Production p) {
223 return Sequence.rewritingSequence(new TargetReducer(buildSequence(p), _bindable, isRaw()),
224 p.elements, p.labels, p.drops);
229 public static class TargetReducer implements Tree.TreeFunctor<Object,Object>, ToJava {
231 private Bindable _bindable;
232 private boolean _israw;
234 public void toJava(StringBuffer sb) {
235 sb.append("new MetaGrammar.TargetReducer(new int[] {");
236 for(int i=0; i<map.length; i++)
237 sb.append((i+"")+(i<map.length-1 ? "," : ""));
239 _bindable.toJava(sb);
241 sb.append(_israw ? "true" : "false");
245 public TargetReducer(int[] map, Bindable b, boolean raw) {
250 public String toString() { return "reducer-"+_bindable.toString(); }
251 public Object invoke(Iterable<Tree<Object>> t) {
252 if (_israw) return _bindable.impose(new Object[] { t });
253 ArrayList ret = new ArrayList();
255 if (tc.head() != null && tc.head() instanceof Functor)
256 ret.add(((Tree.TreeFunctor<Object,Object>)tc.head()).invoke(tc.children()));
257 else if (tc.numChildren() == 0)
260 System.err.println("FIXME: don't know what to do about " + tc);
264 System.err.println("input tree: " + t);
265 Object[] o = (Object[])ret.toArray(new Object[0]);
267 for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
268 Object[] o2 = new Object[max+1];
269 for(int i=0; i<o.length; i++) o2[map[i]] = o[i];
270 return _bindable.impose(o2);
275 public static Union cached = null;
276 public static Union make() {
278 if (cached != null) return cached;
280 ReflectiveMeta m = new ReflectiveMeta();
281 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
282 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
283 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
284 Union meta = mgf.get("s").build(bc);
285 Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
286 return cached = make(t, "s");
287 } catch (Exception e) {
288 throw new RuntimeException(e);
291 return make(MetaGrammarTree.meta, "s");
293 public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
294 public static Union make(Tree t, String s, ReflectiveMeta rm) {
295 System.out.println("Head: " + t.head());
296 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
297 MG.Grammar g = (MG.Grammar)red.invoke(t.children());
298 Context cx = new Context(g,rm);
300 for(MG.NonTerminal nt : g.nonterminals) {
301 System.out.println(nt.name);
302 Union el = (Union)cx.get(nt.name);
303 StringBuffer st = new StringBuffer();
305 System.err.println(st);
306 if (nt.name.equals(s)) u = el;
313 public static class MG {
314 public static @bind class Grammar {
315 public NonTerminal get(String s) {
316 for(NonTerminal nt : nonterminals)
317 if (nt.name.equals(s)) return nt;
320 public @bind.arg NonTerminal[] nonterminals;
321 public String toString() {
323 for(NonTerminal nt : nonterminals) ret += nt + ", ";
327 public abstract static class Un extends El {
328 public Seq[][] sequences;
329 public void build(Context cx, Union u) {
330 HashSet<Sequence> bad2 = new HashSet<Sequence>();
331 for(int i=0; i<sequences.length; i++) {
332 Seq[] group = sequences[i];
333 Union u2 = new Union();
334 if (sequences.length==1) u2 = u;
335 for(int j=0; j<group.length; j++) {
336 group[j].build(cx, u2, false);
338 if (sequences.length==1) break;
339 Sequence seq = Sequence.singleton(u2);
340 for(Sequence s : bad2) {
345 bad2.add(Sequence.singleton(u2));
349 public static class NonTerminal extends Un {
350 public String name = null;
351 public @bind NonTerminal(@bind.arg("Word") String name,
352 @bind.arg("RHS") Seq[][] sequences) {
354 this.sequences = sequences;
356 public Element build(Context cx) { return cx.get(name); }
359 public static class AnonUn extends Un {
360 public @bind.as("(") AnonUn(Seq[][] sequences) {
361 this.sequences = sequences;
363 public Element build(Context cx) {
364 Union ret = new Union();
370 //public static @bind.as void range(char c) { }
371 public static class Range {
372 public @bind.as("range") Range(char only) { first = only; last = only; }
373 public @bind.as("-") Range(char first, char last) { this.first = first; this.last = last; }
377 public static abstract class El {
378 public String getLabel() { return null; }
379 public String getOwnerTag() { return null; }
380 public boolean drop() { return false; }
381 public abstract Element build(Context cx);
383 public static class Drop extends El {
385 public Drop(El e) { this.e = e; }
386 public String getLabel() { return null; }
387 public boolean drop() { return true; }
388 public String getOwnerTag() { return e.getOwnerTag(); }
389 public Element build(Context cx) { return e.build(cx); }
391 public static class Label extends El {
394 public Label(String label, El e) { this.e = e; this.label = label; }
395 public String getLabel() { return label; }
396 public String getOwnerTag() { return e.getOwnerTag(); }
397 public Element build(Context cx) { return e.build(cx); }
399 public static /*abstract*/ class Seq {
400 HashSet<Seq> and = new HashSet<Seq>();
401 HashSet<Seq> not = new HashSet<Seq>();
406 public Seq(El e) { this(new El[] { e }); }
407 public Seq(El[] elements) { this.elements = elements; }
408 public Seq tag(String tag) { this.tag = tag; return this; }
409 public Seq follow(El follow) { this.follow = follow; return this; }
411 Seq ret = new Seq(elements);
418 public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
419 public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
420 public Seq separate(El sep) {
421 El[] elements = new El[this.elements.length * 2 - 1];
422 for(int i=0; i<this.elements.length; i++) {
423 elements[i*2] = this.elements[i];
424 if (i<this.elements.length-1)
425 elements[i*2+1] = new Drop(sep);
427 this.elements = elements;
430 public Sequence build(Context cx, Union u, boolean lame) {
431 Sequence ret = build0(cx, lame || this.lame);
432 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
433 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
438 public Sequence build0(Context cx, boolean lame) {
439 boolean unwrap = false;
440 boolean dropAll = lame;
441 if (tag!=null && tag.equals("[]")) unwrap = true;
442 if (tag!=null && "()".equals(tag)) dropAll = true;
443 Object[] labels = new Object[elements.length];
444 boolean[] drops = new boolean[elements.length];
445 Element[] els = new Element[elements.length];
446 for(int i=0; i<elements.length; i++) {
447 labels[i] = elements[i].getLabel();
448 drops[i] = elements[i].drop();
449 els[i] = elements[i].build(cx);
450 if (elements[i].getOwnerTag() != null)
451 tag = elements[i].getOwnerTag();
454 if (dropAll) ret = Sequence.drop(els, false);
455 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
456 else if (tag!=null) {
457 ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
459 ret = cx.rm.tryResolveTag(tag, cx.cnt, els, labels, drops);
462 for(int i=0; i<els.length; i++)
464 if (idx==-1) idx = i;
465 else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
466 if (idx != -1) ret = Sequence.singleton(els, idx);
467 else ret = Sequence.drop(els, false);
470 if (this.follow != null)
471 ret.follow = infer(this.follow.build(cx));
472 ret.lame = this.lame;
476 public static @bind.as("&") Seq and(Seq s, El[] elements) { return s.and(seq(elements)); }
477 public static @bind.as("&~") Seq andnot(Seq s, El[] elements) { return s.andnot(seq(elements)); }
478 public static @bind.as("->") Seq arrow(Seq s, El e) { return s.follow(e); }
479 public static @bind.as("::") Seq tag(String tagname, Seq s) { return s.tag(tagname); }
480 public static @bind.as("/") Seq slash(Seq s, El e) { return s.separate(e); }
482 public static @bind.as("ps") Seq seq(El[] elements) { return new Seq(elements); }
483 public static @bind.as Seq psx(Seq s) { return s; }
484 public static @bind.as(":") El colon(String s, El e) { return new Label(s, e); }
485 public static @bind.as(")") void close(String foo) { throw new Error("not supported"); }
486 public static @bind.as("()") El epsilon() { return new Constant(Union.epsilon); }
488 public static @bind.as("nonTerminal") class NonTerminalReference extends El {
489 public @bind.arg String nonTerminal;
490 public Element build(Context cx) {
491 return cx.get(nonTerminal);
495 public static class StringLiteral extends Constant {
496 public @bind.as("literal") StringLiteral(String string) { super(CharRange.string(string)); }
497 public boolean drop() { return true; }
500 public static class CharClass extends El {
502 public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
503 public Element build(Context cx) {
504 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
505 for(Range r : ranges)
506 set.add(r.first, r.last);
507 return CharRange.set(set);
511 public static @bind.as("{") class XTree extends El {
512 public @bind.arg Seq body;
513 public Element build(Context cx) {
518 public static class Rep extends El {
520 public boolean zero, many, max;
521 public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
522 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
523 public Element build(Context cx) {
525 ? Sequence.repeat(e.build(cx), zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
527 ? Sequence.repeatMaximal(infer(e.build(cx)), zero, many, cx.rm.repeatTag())
528 : Sequence.repeatMaximal(e.build(cx), zero, many, infer(sep.build(cx)), cx.rm.repeatTag());
531 public static class Constant extends El {
533 public Constant(Element constant) { this.constant = constant; }
534 public Element build(Context cx) { return constant; }
536 public abstract static class PostProcess extends El {
538 public PostProcess(El e) { this.e = e; }
539 public Element build(Context cx) { return postProcess(e.build(cx)); }
540 public abstract Element postProcess(Element e);
543 // FIXME: it would be nice if we could hoist this into "Rep"
544 public static @bind.as("++") El plusmax(final El e) { return new Rep(e, null, false, true, true); }
545 public static @bind.as("+") El plus(final El e) { return new Rep(e, null, false, true, false); }
546 public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep, false, true, true); }
547 public static @bind.as("+/") El plusfollow(final El e, final El sep) { return new Rep(e, sep, false, true, false); }
548 public static @bind.as("**") El starmax(final El e) { return new Rep(e, null, true, true, true); }
549 public static @bind.as("*") El star(final El e) { return new Rep(e, null, true, true, false); }
550 public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep, true, true, true); }
551 public static @bind.as("*/") El starfollow(final El e, final El sep) { return new Rep(e, sep, true, true, false); }
552 public static @bind.as("?") El question(final El e) { return new Rep(e, null, true, true, false); }
554 public static @bind.as("!") El bang(final El e) { return new Drop(e); }
556 public static @bind.as("^") El caret(final String s) {
557 return new Drop(new Constant(CharRange.string(s)) {
558 public String getOwnerTag() { return s; }
562 public static @bind.as("~") El tilde(final El e) {
563 return new PostProcess(e) {
564 public Element postProcess(Element e) {
565 return infer((Topology<Character>)Atom.toAtom(e).complement());
568 public static @bind.as("^^") void doublecaret(final El e) { throw new Error("not implemented"); }
570 //public static @bind.as("(") El subexpression(Seq[][] rhs) { return new NonTerminal(rhs); }
572 public static @bind.as("Word") String word(String s) { return s; }
573 public static @bind.as("Quoted") String quoted(String s) { return s; }
574 public static @bind.as("escaped") String c(char c) { return c+""; }
575 public static @bind.as("\"\"") String emptystring() { return ""; }
576 public static @bind.as("\n") String retur() { return "\n"; }
577 public static @bind.as("\r") String lf() { return "\r"; }
580 public static class Context {
581 HashMap<String,Union> map = new HashMap<String,Union>();
582 private MG.Grammar grammar;
583 public String cnt = null;
584 private ReflectiveMeta rm;
585 public Context(MG.Grammar g, ReflectiveMeta rm) {
589 public Union build() {
591 for(MG.NonTerminal nt : grammar.nonterminals) {
592 Union u = get(nt.name);
593 if ("s".equals(nt.name))
598 public Context(Tree t, ReflectiveMeta rm) {
600 Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
601 this.grammar = (MG.Grammar)red.invoke(t.children());
603 public Union peek(String name) { return map.get(name); }
604 public void put(String name, Union u) { map.put(name, u); }
605 public Union get(String name) {
606 Union ret = map.get(name);
607 if (ret != null) return ret;
608 ret = new Union(name);
610 MG.NonTerminal nt = grammar.get(name);
612 System.err.println("*** warning could not find " + name);
623 /*private*/ static Atom infer(Element e) { return infer((Topology<Character>)Atom.toAtom(e)); }
624 /*private*/ static Atom infer(Topology<Character> t) { return new CharRange(new CharTopology(t)); }