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.*;
11 public static void main(String[] s) throws Exception {
12 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
15 new ReflectiveMeta(MG.class,
22 MG.NonTerminalReference.class,
23 MG.StringLiteral.class,
28 MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
29 MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
30 Union meta = mgf.get("s").build(bc);
32 System.err.println("parsing " + s[1]);
33 Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
35 System.out.println(t.toPrettyString());
36 Reducer red = (Reducer)t.head();
37 System.out.println(red.reduce(t));
40 public static class ReflectiveMeta extends MetaGrammar.Meta {
41 private final Class _cl;
42 private final Class[] _inner;
43 public ReflectiveMeta(Class c, Class[] inner) {
47 private boolean match(Method m, String s) { return match(m.getAnnotation(tag.class), null, s); }
48 private boolean match(tag t, Class c, String s) {
49 if (t==null) return false;
50 if (t.value().equals(s)) return true;
51 if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
54 private boolean match(nonterminal t, Class c, String s) {
55 if (t==null) return false;
56 if (t.value().equals(s)) return true;
57 if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
60 private boolean match(Class c, String s, String nonTerminalName) {
61 if (match((tag)c.getAnnotation(tag.class), c, s)) return true;
62 if (match((nonterminal)c.getAnnotation(nonterminal.class), c, nonTerminalName)) return true;
65 public boolean match(Constructor con, String s, String nonTerminalName) {
66 Class c = con.getDeclaringClass();
67 if (match((tag)con.getAnnotation(tag.class), null, s)) return true;
68 if (match((nonterminal)con.getAnnotation(nonterminal.class), c, s)) return true;
71 public Object repeatTag() {
72 return new Reducer() {
73 public String toString() { return "[**]"; }
74 public Object reduce(Tree t) {
75 Object[] ret = new Object[t.numChildren()];
76 for(int i=0; i<t.numChildren(); i++) {
78 if (tc.head() != null && tc.head() instanceof Reducer)
79 ret[i] = ((Reducer)tc.head()).reduce(tc);
80 else if (tc.numChildren() == 0)
83 System.err.println("FIXME: don't know what to do about " + tc);
91 public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
92 Production p = new Production(tag, nonTerminalName, els, labels, drops);
93 for(Method m : _cl.getMethods())
94 if (new TargetMethod(m).isCompatible(p))
95 return new TargetMethod(m).makeSequence(p);
97 for(Constructor con : c.getConstructors())
98 if (new TargetConstructor(con).isCompatible(p))
99 return new TargetConstructor(con).makeSequence(p);
100 for(Class c : _inner)
101 if (new TargetClass(c).isCompatible(p))
102 return new TargetClass(c).makeSequence(p);
103 throw new RuntimeException("could not find a Java method/class/ctor matching tag \""+tag+"\", nonterminal \""+nonTerminalName+"\"");
107 public static Object makeFlattener(final Method m, final Element[] els, final Object[] labels, final boolean[] drops) {
108 return new Reducer() {
109 public Object reduce(Tree t) {
110 Object[] o = new Object[m.getParameterTypes()];
112 for(int i=0; i<els.length; i++)
120 * Constructors, classes, and methods with this attribute will
121 * match every production of the nonterminal called "value()"
122 * that is arg-compatible. If value() is undefined, then the
123 * class/constructor/method name is used.
125 @Retention(RetentionPolicy.RUNTIME) public static @interface nonterminal { String value() default ""; }
128 * Constructors, classes, and methods with this attribute will
129 * match every tree tagged with "value()" that is arg-compatible.
130 * If value() is undefined, then the class/constructor/method
133 @Retention(RetentionPolicy.RUNTIME) public static @interface tag { String value() default ""; }
136 * If any parameter to a method or field in a class has a named
137 * arg-tag, that parameter/field matches the child of the tree
138 * which either has that label or else is a reference to a
139 * nonterminal with the corresponding name.
141 * The remaining non-named arg-tags match the remaining children
142 * of the tree in sequential order.
144 * If any arg-tagged parameters/fields remain, the match fails.
145 * If there were no arg-tagged parameters-fields, it is as if all
146 * of them were non-named and arg-tagged.
148 * A method/constructor is arg-compatible if all of its arguments
149 * are arg-compatible.
151 * A class is arg-compatible if all of its fields are
152 * arg-compatible, or if one of its constructors is arg-compatible.
155 @Retention(RetentionPolicy.RUNTIME) public static @interface arg { String value() default ""; }
157 public static class Production {
159 public String nonTerminal;
160 public Object[] labels;
161 public boolean[] drops;
162 public Element[] elements;
163 public int count = 0;
164 public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
166 this.elements = elements; // FIXME: use this
167 this.nonTerminal = nonTerminal;
168 this.labels = labels;
170 for(int i=0; i<drops.length; i++)
176 public static abstract class Target {
177 public abstract String getName();
178 public abstract tag getTag();
179 public abstract nonterminal getNonTerminal();
180 public abstract int[] buildSequence(Production p);
181 public boolean isCompatible(Production p) {
184 (t.value().equals(p.tag) ||
185 (t.value().equals("") && p.tag.equals(getName()))))
186 return buildSequence(p)!=null;
188 nonterminal n = getNonTerminal();
190 (n.value().equals(p.nonTerminal) ||
191 (n.value().equals("") && p.nonTerminal.equals(getName()))))
192 return buildSequence(p)!=null;
196 public int[] buildSequence(Production p, String[] names, arg[] argtags) {
198 for(int i=0; i<argtags.length; i++)
199 if (argtags[i] != null)
202 // FIXME: can be smarter here
203 if (names.length==p.count) {
204 int[] ret = new int[p.count];
205 for(int i=0; i<p.count; i++) ret[i] = i;
207 } else if (argTagged==p.count) {
208 int[] ret = new int[argtags.length];
210 for(int i=0; i<argtags.length; i++)
211 ret[i] = argtags[i]==null ? -1 : (j++);
217 public Sequence makeSequence(Production p) {
218 return Sequence.rewritingSequence(new TargetReducer(p), p.elements, p.labels, p.drops);
220 public abstract Object plant(Object[] fields, int[] map);
221 public class TargetReducer implements Reducer {
222 private Production p;
224 public TargetReducer(Production p) {
226 this.map = buildSequence(p);
228 public String toString() { return "reducer-"+Target.this; }
229 public Object reduce(Tree t) {
230 Object[] objects = new Object[t.numChildren()];
231 for(int i=0; i<t.numChildren(); i++) {
232 Tree tc = t.child(i);
233 if (tc.head() != null && tc.head() instanceof Reducer)
234 objects[i] = ((Reducer)tc.head()).reduce(tc);
235 else if (tc.numChildren() == 0)
236 objects[i] = tc.head();
237 else if (t.numChildren()==1) {
239 objects[i] = reduce(t.child(0));
241 System.err.println("FIXME: don't know what to do about " + tc);
245 return plant(objects, map);
250 public static interface Reducer {
251 public Object reduce(Tree t);
254 public static class TargetClass extends Target {
255 public final Class _class;
256 public TargetClass(Class _class) { this._class = _class; }
257 public String getName() { return _class.getSimpleName(); }
258 public tag getTag() { return (tag)_class.getAnnotation(tag.class); }
259 public nonterminal getNonTerminal() { return (nonterminal)_class.getAnnotation(nonterminal.class); }
260 public String toString() { return _class.getSimpleName(); }
261 public int[] buildSequence(Production p) {
262 Field[] f = _class.getDeclaredFields();
263 String[] names = new String[f.length];
264 arg[] argtags = new arg[f.length];
265 for(int i=0; i<f.length; i++) {
266 names[i] = f[i].getName();
267 argtags[i] = f[i].getAnnotation(arg.class);
269 int[] ret = buildSequence(p, names, argtags);
270 if (ret!=null) return ret;
271 for(Constructor c : _class.getConstructors())
272 if (new TargetConstructor(c).buildSequence(p)!=null)
273 return new TargetConstructor(c).buildSequence(p);
276 public Object plant(Object[] fields, int[] map) {
278 Object ret = _class.newInstance();
279 Field[] f = _class.getFields();
281 for(int i=0; i<f.length; i++)
283 Object tgt = Reflection.lub(fields[map[i]]);
284 if (f[i].getType() == String.class) tgt = stringify(tgt);
286 tgt = coerce(tgt, f[i].getType());
287 System.err.println("setting a " + f[i].getType().getName() + " to " + Reflection.show(tgt));
291 } catch (Exception e) {
293 throw new RuntimeException(e);
298 public static String stringify(Object o) {
299 if (o==null) return "";
300 if (!(o instanceof Object[])) return o.toString();
301 Object[] arr = (Object[])o;
302 StringBuffer ret = new StringBuffer();
303 for(int i=0; i<arr.length; i++)
305 return ret.toString();
308 public static class TargetConstructor extends Target {
309 public final Constructor _ctor;
310 public TargetConstructor(Constructor _ctor) { this._ctor = _ctor; }
311 public String getName() { return _ctor.getName(); }
312 public tag getTag() { return (tag)_ctor.getAnnotation(tag.class); }
313 public nonterminal getNonTerminal() { return (nonterminal)_ctor.getAnnotation(nonterminal.class); }
314 public String toString() { return _ctor.getName(); }
315 public int[] buildSequence(Production p) {
316 Annotation[][] annotations = _ctor.getParameterAnnotations();
317 int len = annotations.length;
319 String name = _ctor.getDeclaringClass().getName();
321 if (name.indexOf('$') > name.lastIndexOf('.')) {
326 String[] names = new String[len];
327 arg[] argtags = new arg[len];
328 for(int i=0; i<names.length; i++)
329 for(Annotation a : annotations[i+ofs])
330 if (a instanceof arg)
331 argtags[i+ofs] = (arg)a;
332 return buildSequence(p, names, argtags);
334 public Object plant(Object[] fields, int[] map) {
336 Class[] argTypes = _ctor.getParameterTypes();
337 Object[] args = new Object[argTypes.length];
339 for(int i=0; i<args.length; i++)
341 Object tgt = Reflection.lub(fields[map[i]]);
342 if (argTypes[i] == String.class) tgt = stringify(tgt);
344 tgt = coerce(tgt, argTypes[i]);
345 System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
348 return _ctor.newInstance(args);
349 } catch (Exception e) {
350 throw new RuntimeException(e);
354 public static class TargetMethod extends Target {
355 public final Method _method;
356 public TargetMethod(Method _method) { this._method = _method; }
357 public String getName() { return _method.getName(); }
358 public String toString() { return _method.getName(); }
359 public tag getTag() { return (tag)_method.getAnnotation(tag.class); }
360 public nonterminal getNonTerminal() { return (nonterminal)_method.getAnnotation(nonterminal.class); }
361 public int[] buildSequence(Production p) {
362 Annotation[][] annotations = _method.getParameterAnnotations();
363 String[] names = new String[annotations.length];
364 arg[] argtags = new arg[annotations.length];
365 for(int i=0; i<names.length; i++)
366 for(Annotation a : annotations[i])
367 if (a instanceof arg)
369 int[] ret = buildSequence(p, names, argtags);
372 public Object plant(Object[] fields, int[] map) {
374 Class[] argTypes = _method.getParameterTypes();
375 Object[] args = new Object[argTypes.length];
377 for(int i=0; i<args.length; i++)
379 Object tgt = Reflection.lub(fields[map[i]]);
380 if (argTypes[i] == String.class) tgt = stringify(tgt);
382 tgt = coerce(tgt, argTypes[i]);
383 System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
386 return _method.invoke(null, args);
387 } catch (Exception e) {
388 throw new RuntimeException(e);
393 public static Object coerce(Object o, Class c) {
394 if (o==null) return null;
395 if (c.isInstance(o)) return o;
396 if (c == char.class) {
397 return o.toString().charAt(0);
399 if (c.isArray() && (c.getComponentType().isInstance(o))) {
400 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
404 if (o.getClass().isArray() && c.isArray()) {
406 for(int i=0; i<((Object[])o).length; i++) {
407 Object ob = (((Object[])o)[i]);
409 System.err.println("no hit with " + c.getComponentType().getName() + " on " + Reflection.show(((Object[])o)[i]));
414 System.err.println("hit with " + c.getComponentType().getName());
415 return Array.newInstance(c.getComponentType(), ((Object[])o).length);
421 public static class MG {
422 public static @tag Grammar grammar(Grammar g) { return g; }
423 public static @nonterminal class Grammar {
424 public @arg("NonTerminal") NonTerminal[] nonterminals;
425 public String toString() {
427 for(NonTerminal nt : nonterminals) ret += nt + ", ";
431 public static @nonterminal class NonTerminal extends El {
432 public @arg("Word") String name;
433 public @arg("RHS") Seq[][] sequences;
436 public static @tag void range(char c) { }
437 public static class Range extends El {
438 public @tag("range") Range(char only) { first = only; last = only; }
439 public @tag("-") Range(char first, char last) { this.first = first; this.last = last; }
443 public static class El { }
444 public static /*abstract*/ @nonterminal("Sequence") class Seq extends El { }
445 public static @tag("&") Seq and(Sequence s, El[] elements) { return new Seq(); }
446 public static @tag("&~") Seq andnot(Sequence s, El[] elements) { return new Seq(); }
447 public static @tag Seq ps(El[] elements) { return new Seq(); }
448 public static @tag Seq psx(Seq s) { return s; }
449 public static @tag("::") Seq tag(String tagname, Seq seq) { return new Seq(); }
450 public static @tag(":") void colon(String s, El e) { }
451 public static @tag(")") void close(String foo) { }
452 public static @tag("/") Seq slash(Seq s, El e) { return new Seq(); }
453 public static @tag("->") Seq arrow(Seq s, El e) { return new Seq(); }
455 public static @tag("nonTerminal") class NonTerminalReference extends El { public @arg String nonTerminal; }
456 public static @tag("literal") class StringLiteral extends El { public @arg String string; }
457 public static @tag("()") class Epsilon extends El { }
458 public static @tag("{") class Tree extends El { public @arg Seq body; }
459 public static class CharClass extends El { public @tag("[") CharClass(Range[] ranges) { } }
461 public static @tag("++") void plusmax(El e) { }
462 public static @tag("+") void plus(El e) { }
463 public static @tag("++/") void plusmaxfollow(El e, El sep) { }
464 public static @tag("+/") void plusfollow(El e, El sep) { }
465 public static @tag("**") void starmax(El e) { }
466 public static @tag("*") void star(El e) { }
467 public static @tag("**/") void starmaxfollow(El e, El sep) { }
468 public static @tag("*/") void starfollow(El e, El sep) { }
469 public static @tag("!") void bang(El e) { }
470 public static @tag("?") void question(El e) { }
471 public static @tag("^") void caret(String s) { }
472 public static @tag("~") void tilde(El e) { }
473 public static @tag("^^") void doublecaret(El e) { }
474 public static @tag("(") void subexpression(Seq[][] rhs) { }
476 public static @nonterminal("Word") String word(String s) { return null; }
477 public static @nonterminal("Quoted") String quoted(String s) { return null; }
478 public static @nonterminal("escaped") String c(char c) { return null; }
479 public static @tag("\"\"") String emptystring() { return null; }
480 public static @tag("\r") String lf() { return null; }
481 public static @tag("\n") String cr() { return null; }