checkpoint
[sbp.git] / src / edu / berkeley / sbp / misc / Demo.java
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 java.util.*;
6 import java.lang.annotation.*;
7 import java.lang.reflect.*;
8 import java.io.*;
9
10 public class Demo {
11     public static void main(String[] s) throws Exception {
12         Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
13         
14         MetaGrammar.Meta m =
15             new ReflectiveMeta(MG.class,
16                                new Class[] {
17                                    MG.Grammar.class,
18                                    MG.NonTerminal.class,
19                                    MG.Range.class,
20                                    MG.El.class,
21                                    MG.Seq.class,
22                                    MG.NonTerminalReference.class,
23                                    MG.StringLiteral.class,
24                                    MG.Epsilon.class,
25                                    MG.Tree.class,
26                                    MG.CharClass.class
27                                });
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);
31
32         System.err.println("parsing " + s[1]);
33         Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
34
35         System.out.println(t.toPrettyString());
36         Reducer red = (Reducer)t.head();
37         System.out.println(red.reduce(t));
38     }
39
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) {
44             this._cl = c;
45             this._inner = inner;
46         }
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;
52             return false;
53         }
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;
58             return false;
59         }
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;
63             return false;
64         }
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;
69             return false;
70         }
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++) {
77                             Tree tc = t.child(i);
78                             if (tc.head() != null && tc.head() instanceof Reducer)
79                                 ret[i] = ((Reducer)tc.head()).reduce(tc);
80                             else if (tc.numChildren() == 0)
81                                 ret[i] = tc.head();
82                             else {
83                                 System.err.println("FIXME: don't know what to do about " + tc);
84                                 ret[i] = null;
85                             }
86                         }
87                         return ret;
88                     }
89                 };
90         }
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);
96             for(Class c : _inner)
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+"\"");
104         }
105     }
106     /*
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()];
111                     int j = 0;
112                     for(int i=0; i<els.length; i++)
113                 }
114             };
115     }
116     */
117
118     
119     /**
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.
124      */ 
125     @Retention(RetentionPolicy.RUNTIME) public static @interface nonterminal { String value() default ""; }
126
127     /**
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
131      *  name is used.
132      */ 
133     @Retention(RetentionPolicy.RUNTIME) public static @interface tag         { String value() default ""; }
134
135     /**
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.
140      *  
141      *  The remaining non-named arg-tags match the remaining children
142      *  of the tree in sequential order.
143      *
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.
147      *
148      *  A method/constructor is arg-compatible if all of its arguments
149      *  are arg-compatible.
150      *
151      *  A class is arg-compatible if all of its fields are
152      *  arg-compatible, or if one of its constructors is arg-compatible.
153      *
154      */
155     @Retention(RetentionPolicy.RUNTIME) public static @interface arg         { String value() default ""; }
156
157     public static class Production {
158         public String tag;
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) {
165             this.tag = tag;
166             this.elements = elements; // FIXME: use this
167             this.nonTerminal = nonTerminal;
168             this.labels = labels;
169             this.drops = drops;
170             for(int i=0; i<drops.length; i++)
171                 if (!drops[i])
172                     count++;
173         }
174     }
175
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) {
182             tag t = getTag();
183             if (t != null &&
184                 (t.value().equals(p.tag) ||
185                  (t.value().equals("") && p.tag.equals(getName()))))
186                 return buildSequence(p)!=null;
187
188             nonterminal n = getNonTerminal();
189             if (n != null &&
190                 (n.value().equals(p.nonTerminal) ||
191                  (n.value().equals("") && p.nonTerminal.equals(getName()))))
192                 return buildSequence(p)!=null;
193
194             return false;
195         }
196         public int[] buildSequence(Production p, String[] names, arg[] argtags) {
197             int argTagged = 0;
198             for(int i=0; i<argtags.length; i++)
199                 if (argtags[i] != null)
200                     argTagged++;
201
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;
206                 return ret;
207             } else if (argTagged==p.count) {
208                 int[] ret = new int[argtags.length];
209                 int j = 0;
210                 for(int i=0; i<argtags.length; i++)
211                     ret[i] = argtags[i]==null ? -1 : (j++);
212                 return ret;
213             } else {
214                 return null;
215             }
216         }
217         public Sequence makeSequence(Production p) {
218             return Sequence.rewritingSequence(new TargetReducer(p), p.elements, p.labels, p.drops);
219         }
220         public abstract Object plant(Object[] fields, int[] map);
221         public class TargetReducer implements Reducer {
222             private Production p;
223             private int[] map;
224             public TargetReducer(Production p) {
225                 this.p = p;
226                 this.map = buildSequence(p);
227             }
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) {
238                         //FIXME: EVIL!!
239                         objects[i] = reduce(t.child(0));
240                     } else {
241                         System.err.println("FIXME: don't know what to do about " + tc);
242                         objects[i] = null;
243                     }
244                 }
245                 System.err.println("input tree: " + t);
246                 return plant(objects, map);
247             }
248         }
249     }
250
251     public static interface Reducer {
252         public Object reduce(Tree t);
253     }
254
255     public static class TargetClass extends Target {
256         public final Class _class;
257         public TargetClass(Class _class) { this._class = _class; }
258         public String getName() { return _class.getSimpleName(); }
259         public tag getTag() { return (tag)_class.getAnnotation(tag.class); }
260         public nonterminal getNonTerminal() { return (nonterminal)_class.getAnnotation(nonterminal.class); }
261         public String toString() { return _class.getSimpleName(); }
262         public int[] buildSequence(Production p) {
263             Field[]  f       = _class.getDeclaredFields();
264             String[] names   = new String[f.length];
265             arg[]    argtags = new arg[f.length];
266             for(int i=0; i<f.length; i++) {
267                 names[i]   = f[i].getName();
268                 argtags[i] = f[i].getAnnotation(arg.class);
269             }
270             int[] ret = buildSequence(p, names, argtags);
271             if (ret!=null) return ret;
272             for(Constructor c : _class.getConstructors())
273                 if (new TargetConstructor(c).buildSequence(p)!=null)
274                     return new TargetConstructor(c).buildSequence(p);
275             return null;
276         }
277         public Object plant(Object[] fields, int[] map) {
278             try {
279                 Object ret = _class.newInstance();
280                 Field[] f = _class.getFields();
281                 int j = 0;
282                 for(int i=0; i<f.length; i++)
283                     if (map[i] != -1) {
284                         Object tgt = Reflection.lub(fields[map[i]]);
285                         if (f[i].getType() == String.class) tgt = stringify(tgt);
286                         // FUGLY
287                         tgt = coerce(tgt, f[i].getType());
288                         System.err.println("setting a " + f[i].getType().getName() + " to " + Reflection.show(tgt));
289                         f[i].set(ret, tgt);
290                     }
291                 return ret;
292             } catch (Exception e) {
293                 e.printStackTrace();
294                 throw new RuntimeException(e);
295             }
296         }
297     }
298
299     public static String stringify(Object o) {
300         if (o==null) return "";
301         if (!(o instanceof Object[])) return o.toString();
302         Object[] arr = (Object[])o;
303         StringBuffer ret = new StringBuffer();
304         for(int i=0; i<arr.length; i++)
305             ret.append(arr[i]);
306         return ret.toString();
307     }
308
309     public static class TargetConstructor extends Target {
310         public final Constructor _ctor;
311         public TargetConstructor(Constructor _ctor) { this._ctor = _ctor; }
312         public String getName() { return _ctor.getName(); }
313         public tag getTag() { return (tag)_ctor.getAnnotation(tag.class); }
314         public nonterminal getNonTerminal() { return (nonterminal)_ctor.getAnnotation(nonterminal.class); }
315         public String toString() { return _ctor.getName(); }
316         public int[] buildSequence(Production p) {
317             Annotation[][] annotations = _ctor.getParameterAnnotations();
318             int len = annotations.length;
319             int ofs = 0;
320             String name = _ctor.getDeclaringClass().getName();
321             /*
322             if (name.indexOf('$') > name.lastIndexOf('.')) {
323                 len--;
324                 ofs++;
325             }
326             */
327             String[] names   = new String[len];
328             arg[]    argtags = new arg[len];
329             for(int i=0; i<names.length; i++)
330                 for(Annotation a : annotations[i+ofs])
331                     if (a instanceof arg)
332                         argtags[i+ofs] = (arg)a;
333             return buildSequence(p, names, argtags);
334         }
335         public Object plant(Object[] fields, int[] map) {
336             try {
337                 Class[] argTypes = _ctor.getParameterTypes();
338                 Object[] args = new Object[argTypes.length];
339                 int j = 0;
340                 for(int i=0; i<args.length; i++)
341                     if (map[i] != -1) {
342                         Object tgt = Reflection.lub(fields[map[i]]);
343                         if (argTypes[i] == String.class) tgt = stringify(tgt);
344                         // FUGLY
345                         tgt = coerce(tgt, argTypes[i]);
346                         System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
347                         args[i] = tgt;
348                     }
349                 return _ctor.newInstance(args);
350             } catch (Exception e) {
351                 throw new RuntimeException(e);
352             }
353         }
354     }
355     public static class TargetMethod extends Target {
356         public final Method _method;
357         public TargetMethod(Method _method) { this._method = _method; }
358         public String getName() { return _method.getName(); }
359         public String toString() { return _method.getName(); }
360         public tag getTag() { return (tag)_method.getAnnotation(tag.class); }
361         public nonterminal getNonTerminal() { return (nonterminal)_method.getAnnotation(nonterminal.class); }
362         public int[] buildSequence(Production p) {
363             Annotation[][] annotations = _method.getParameterAnnotations();
364             String[] names   = new String[annotations.length];
365             arg[]    argtags = new arg[annotations.length];
366             for(int i=0; i<names.length; i++)
367                 for(Annotation a : annotations[i])
368                     if (a instanceof arg)
369                         argtags[i] = (arg)a;
370             int[] ret = buildSequence(p, names, argtags);
371             return ret;
372         }
373         public Object plant(Object[] fields, int[] map) {
374             try {
375                 Class[] argTypes = _method.getParameterTypes();
376                 Object[] args = new Object[argTypes.length];
377                 int j = 0;
378                 for(int i=0; i<args.length; i++)
379                     if (map[i] != -1) {
380                         Object tgt = Reflection.lub(fields[map[i]]);
381                         if (argTypes[i] == String.class) tgt = stringify(tgt);
382                         // FUGLY
383                         tgt = coerce(tgt, argTypes[i]);
384                         System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
385                         args[i] = tgt;
386                     }
387                 System.err.println("invoking " + _method + " with " + Reflection.show(args));
388                 return _method.invoke(null, args);
389             } catch (Exception e) {
390                 throw new RuntimeException(e);
391             }
392         }
393     }
394
395     public static Object coerce(Object o, Class c) {
396         if (o==null) return null;
397         if (c.isInstance(o)) return o;
398         if (c == char.class) {
399             return o.toString().charAt(0);
400         }
401         if (c.isArray() && (c.getComponentType().isInstance(o))) {
402             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
403             ret[0] = o;
404             return ret;
405         }
406         if (o.getClass().isArray() && c.isArray()) {
407             boolean ok = true;
408             for(int i=0; i<((Object[])o).length; i++) {
409                 Object ob = (((Object[])o)[i]);
410                 if (ob != null) {
411                     System.err.println("no hit with " + c.getComponentType().getName() + " on " + Reflection.show(((Object[])o)[i]));
412                     ok = false;
413                 }
414             }
415             if (ok) {
416                 System.err.println("hit with " + c.getComponentType().getName());
417                 return Array.newInstance(c.getComponentType(), ((Object[])o).length);
418             }
419         }
420         return o;
421     }
422
423     public static class MG {
424         //public static @tag Grammar grammar(Grammar g) { return g; }
425         public static @tag("grammar") class Grammar {
426             public @arg("NonTerminal") NonTerminal[] nonterminals;
427             public String toString() {
428                 String ret = "[ ";
429                 for(NonTerminal nt : nonterminals) ret += nt + ", ";
430                 return ret + " ]";
431             }
432         }
433         public static @nonterminal class NonTerminal extends El {
434             public @arg("Word") String  name;
435             public @arg("RHS")  Seq[][] sequences;
436         }
437
438         public static @tag void range(char c) { }
439         public static class Range extends El {
440             public @tag("range") Range(char only) { first = only; last = only; }
441             public @tag("-")     Range(char first, char last) { this.first = first; this.last = last; }
442             public char first;
443             public char last;
444         }
445         public static class El { }
446         public static /*abstract*/ @nonterminal("Sequence") class Seq extends El { }
447         public static @tag("&")   Seq and(Sequence s,    El[] elements) { return new Seq(); }
448         public static @tag("&~")  Seq andnot(Sequence s, El[] elements) { return new Seq(); }
449         public static @tag        Seq ps(El[] elements) { return new Seq(); }
450         public static @tag        Seq psx(Seq s) { return s; }
451         public static @tag("::")  Seq tag(String tagname, Seq seq) { return new Seq(); }
452         public static @tag(":")   void colon(String s, El e) { }
453         public static @tag(")")   void close(String foo) { }
454         public static @tag("/")   Seq slash(Seq s, El e) { return new Seq(); }
455         public static @tag("->")  Seq arrow(Seq s, El e) { return new Seq(); }
456
457         public static @tag("nonTerminal") class NonTerminalReference extends El { public @arg String nonTerminal; }
458         public static @tag("literal")     class StringLiteral        extends El { public @arg String string; }
459         public static @tag("()")          class Epsilon              extends El { }
460         public static @tag("{")           class Tree                 extends El { public @arg Seq body; }
461         public static                     class CharClass            extends El { public @tag("[") CharClass(Range[] ranges) { } }
462
463         public static @tag("++")  void plusmax(El e) { }
464         public static @tag("+")   void plus(El e) { }
465         public static @tag("++/") void plusmaxfollow(El e, El sep) { }
466         public static @tag("+/")  void plusfollow(El e, El sep) { }
467         public static @tag("**")  void starmax(El e) { }
468         public static @tag("*")   void star(El e) { }
469         public static @tag("**/") void starmaxfollow(El e, El sep) { }
470         public static @tag("*/")  void starfollow(El e, El sep) { }
471         public static @tag("!")   void bang(El e) { }
472         public static @tag("?")   void question(El e) { }
473         public static @tag("^")   void caret(String s) { }
474         public static @tag("~")   void tilde(El e) { }
475         public static @tag("^^")  void doublecaret(El e) { }
476         public static @tag("(")   void subexpression(Seq[][] rhs) { }
477
478         public static @nonterminal("Word")    String word(String s) { return null; }
479         public static @nonterminal("Quoted")  String quoted(String s) { return null; }
480         public static @nonterminal("escaped") String c(char c) { return c+""; }
481         public static @tag("\"\"")            String emptystring() { return ""; }
482         public static @tag("\n")              String retur() { return "\n"; }
483         public static @tag("\r")              String lf() { return "\r"; }
484     }
485
486 }