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 edu.berkeley.sbp.bind.*;
6 import java.util.*;
7 import java.lang.annotation.*;
8 import java.lang.reflect.*;
9 import java.io.*;
10
11 public class Demo {
12     
13     public static boolean harsh = false;
14
15     public static void main(String[] s) throws Exception {
16
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);
21
22         Union meta = mgf.get("s").build(bc);
23         Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
24
25         Union u = Demo.make(t, "s");
26
27         System.err.println();
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());
31
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());
35     }
36
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) {
40             return null; }
41         public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
42             return Sequence.rewritingSequence(tag, els, labels, drops);
43         }
44     }
45
46     public static class ReflectiveMeta extends MetaGrammar.Meta {
47         private final Class _cl;
48         private final Class[] _inner;
49         public ReflectiveMeta() {
50             this(MG.class);
51         }
52         public ReflectiveMeta(Class c) {
53             this._cl = c;
54             this._inner = c.getDeclaredClasses();
55         }
56         public ReflectiveMeta(Class c, Class[] inner) {
57             this._cl = c;
58             this._inner = inner;
59         }
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;
65             return false;
66         }
67         /*
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;
72             return false;
73         }
74         */
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;
78             return false;
79         }
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;
84             return false;
85         }
86         public Object repeatTag() {
87             return new Tree.ArrayBuildingTreeFunctor<Object>();
88         }
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);
94             for(Class c : _inner)
95                 for(Constructor con : c.getConstructors())
96                     if (new Target(con).isCompatible(p))
97                         return new Target(con).makeSequence(p);
98             for(Class c : _inner)
99                 if (new Target(c).isCompatible(p))
100                     return new Target(c).makeSequence(p);
101             return null;
102         }
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";
108             if (harsh) {
109                 throw new RuntimeException(message);
110             } else {
111                 System.err.println(message);
112                 return Sequence.rewritingSequence(tag, els, labels, drops);
113             }
114         }
115     }
116
117    
118     public static class Production {
119         public String tag;
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) {
126             this.tag = tag;
127             this.elements = elements;
128             this.nonTerminal = nonTerminal;
129             this.labels = labels;
130             this.drops = drops;
131             for(int i=0; i<drops.length; i++)
132                 if (!drops[i])
133                     count++;
134         }
135     }
136
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;
143             int ofs = 0;
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);
150         }
151         private Bindable _bindable;
152
153         public Target(Object o) { this(Bindable.create(o)); }
154         public Target(Bindable b) { this._bindable = b; }
155
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); }
161
162         public boolean isCompatible(Production p) {
163             bind.as t = getBindAs();
164             if (t != null &&
165                 (t.value().equals(p.tag) ||
166                  (t.value().equals("") && getName().equals(p.tag))))
167                 return buildSequence(p)!=null;
168
169             bind.as n = getBindAs();
170             if (n != null &&
171                 (n.value().equals(p.nonTerminal) ||
172                  (n.value().equals("") && getName().equals(p.nonTerminal))))
173                 return buildSequence(p)!=null;
174
175             return false;
176         }
177
178         public int[] buildSequence(Production p, String[] names, bind.arg[] argtags) {
179             int argTagged = 0;
180             for(int i=0; i<argtags.length; i++)
181                 if (argtags[i] != null)
182                     argTagged++;
183
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;
188                 return ret;
189             } else if (argTagged==p.count) {
190                 int[] ret = new int[argtags.length];
191                 int j = 0;
192                 for(int i=0; i<argtags.length; i++)
193                     ret[i] = argtags[i]==null ? -1 : (j++);
194                 return ret;
195             } else {
196                 return null;
197             }
198         }
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);
202         }
203
204     }
205
206     public static class TargetReducer implements Tree.TreeFunctor<Object,Object> {
207         private int[] map;
208         private String name;
209         private Bindable _bindable;
210         private boolean _israw;
211         public TargetReducer(Production p, int[] map, String name, Bindable b, boolean raw) {
212             this.map = map;
213             this.name = name;
214             this._bindable = b;
215             this._israw = raw;
216         }
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();
221             for(Tree tc : t) {
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)
225                     ret.add(tc.head());
226                 else {
227                     System.err.println("FIXME: don't know what to do about " + tc);
228                     ret.add(null);
229                 }
230             }
231             System.err.println("input tree: " + t);
232             Object[] o = (Object[])ret.toArray(new Object[0]);
233             int max = 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);
238         }
239     }
240
241
242     public static Union cached = null;
243     public static Union make() {
244         if (cached != null) return cached;
245         try {
246             ReflectiveMeta m = new ReflectiveMeta();
247             Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
248             MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
249             MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
250             Union meta = mgf.get("s").build(bc);
251             Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
252             return cached = make(t, "s");
253         } catch (Exception e) {
254             throw new RuntimeException(e);
255         }
256     }
257     public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
258     public static Union make(Tree t, String s, ReflectiveMeta rm) {
259         Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
260         MG.Grammar g = (MG.Grammar)red.invoke(t.children());
261         Context cx = new Context(g,rm);
262         Union u = null;
263         for(MG.NonTerminal nt : g.nonterminals) {
264             System.out.println(nt.name);
265             Union el = (Union)cx.get(nt.name);
266             StringBuffer st = new StringBuffer();
267             el.toString(st);
268             System.err.println(st);
269             if (nt.name.equals(s)) u = el;
270         }
271         return u;
272     }
273
274
275
276     public static class MG {
277         public static @bind.as("grammar") class Grammar {
278             public NonTerminal get(String s) {
279                 for(NonTerminal nt : nonterminals)
280                     if (nt.name.equals(s))
281                         return nt;
282                 return null;
283             }
284             public @bind.arg("NonTerminal") NonTerminal[] nonterminals;
285             public String toString() {
286                 String ret = "[ ";
287                 for(NonTerminal nt : nonterminals) ret += nt + ", ";
288                 return ret + " ]";
289             }
290         }
291         public abstract static class Un extends El {
292             public Seq[][] sequences;
293             public void build(Context cx, Union u) {
294                 HashSet<Sequence> bad2 = new HashSet<Sequence>();
295                 for(int i=0; i<sequences.length; i++) {
296                     Seq[] group = sequences[i];
297                     Union u2 = new Union();
298                     if (sequences.length==1) u2 = u;
299                     for(int j=0; j<group.length; j++) {
300                         group[j].build(cx, u2, false);
301                     }
302                     if (sequences.length==1) break;
303                     Sequence seq = Sequence.singleton(u2);
304                     for(Sequence s : bad2) {
305                         s.lame = true;
306                         seq = seq.not(s);
307                     }
308                     u.add(seq);
309                     bad2.add(Sequence.singleton(u2));
310                 }
311             }
312         }
313         public static class NonTerminal extends Un {
314             public String  name = null;
315             public @bind.as("=") NonTerminal(@bind.arg("Word") String name,
316                                          @bind.arg("RHS") Seq[][] sequences) {
317                 this.name = name;
318                 this.sequences = sequences;
319             }
320             public Element build(Context cx) { return cx.get(name); }
321         }
322
323         public static class AnonUn extends Un {
324             public @bind.as("(") AnonUn(Seq[][] sequences) {
325                 this.sequences = sequences;
326             }
327             public Element build(Context cx) {
328                 Union ret = new Union();
329                 build(cx, ret);
330                 return ret;
331             }
332         }
333
334         //public static @bind.as void range(char c) { }
335         public static class Range {
336             public @bind.as("range") Range(char only) { first = only; last = only; }
337             public @bind.as("-")     Range(char first, char last) { this.first = first; this.last = last; }
338             public char first;
339             public char last;
340         }
341         public static abstract class El {
342             public String getLabel() { return null; }
343             public String getOwnerTag() { return null; }
344             public boolean drop() { return false; }
345             public abstract Element build(Context cx);
346         }
347         public static class Drop extends El {
348             public El e;
349             public Drop(El e) { this.e = e; }
350             public String getLabel() { return null; }
351             public boolean drop() { return true; }
352             public String getOwnerTag() { return e.getOwnerTag(); }
353             public Element build(Context cx) { return e.build(cx); }
354         }
355         public static class Label extends El {
356             public String label;
357             public El e;
358             public Label(String label, El e) { this.e = e; this.label = label; }
359             public String getLabel() { return label; }
360             public String getOwnerTag() { return e.getOwnerTag(); }
361             public Element build(Context cx) { return e.build(cx); }
362         }
363         public static /*abstract*/ class Seq {
364             HashSet<Seq> and = new HashSet<Seq>();
365             HashSet<Seq> not = new HashSet<Seq>();
366             El[] elements;
367             El follow;
368             String tag = null;
369             boolean lame;
370             public Seq(El e) { this(new El[] { e }); }
371             public Seq(El[] elements) { this.elements = elements; }
372             public Seq tag(String tag) { this.tag = tag; return this; }
373             public Seq follow(El follow) { this.follow = follow; return this; }
374             public Seq dup() {
375                 Seq ret = new Seq(elements);
376                 ret.and.addAll(and);
377                 ret.not.addAll(not);
378                 ret.follow = follow;
379                 ret.tag = tag;
380                 return ret;
381             }
382             public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
383             public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
384             public Seq separate(El sep) {
385                 El[] elements = new El[this.elements.length * 2 - 1];
386                 for(int i=0; i<this.elements.length; i++) {
387                     elements[i*2]   = this.elements[i];
388                     if (i<this.elements.length-1)
389                         elements[i*2+1] = new Drop(sep);
390                 }
391                 this.elements = elements;
392                 return this;
393             }
394             public Sequence build(Context cx, Union u, boolean lame) {
395                 Sequence ret = build0(cx, lame || this.lame);
396                 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
397                 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
398                 u.add(ret);
399                 ret.lame = lame;
400                 return ret;
401             }
402             public Sequence build0(Context cx, boolean lame) {
403                 boolean unwrap = false;
404                 boolean dropAll = lame;
405                 if (tag!=null && tag.equals("[]")) unwrap  = true;
406                 if (tag!=null && "()".equals(tag)) dropAll = true;
407                 Object[] labels = new Object[elements.length];
408                 boolean[] drops = new boolean[elements.length];
409                 Element[] els = new Element[elements.length];
410                 for(int i=0; i<elements.length; i++) {
411                     labels[i] = elements[i].getLabel();
412                     drops[i]  = elements[i].drop();
413                     els[i] = elements[i].build(cx);
414                     if (elements[i].getOwnerTag() != null)
415                         tag = elements[i].getOwnerTag();
416                 }
417                 Sequence ret = null;
418                 if (dropAll)     ret = Sequence.drop(els, false);
419                 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
420                 else if (tag!=null) {
421                     ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
422                 } else {
423                     int idx = -1;
424                     for(int i=0; i<els.length; i++)
425                         if (!drops[i])
426                             if (idx==-1) idx = i;
427                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
428                     if (idx != -1) ret = Sequence.singleton(els, idx);
429                     else           ret = Sequence.drop(els, false);
430                 }
431                 if (this.follow != null)
432                     ret.follow = MetaGrammar.infer(this.follow.build(cx));
433                 ret.lame = this.lame;
434                 return ret;
435             }
436         }
437         public static @bind.as("&")   Seq  and(Seq s,         El[] elements) { return s.and(seq(elements)); }
438         public static @bind.as("&~")  Seq  andnot(Seq s,      El[] elements) { return s.andnot(seq(elements)); }
439         public static @bind.as("->")  Seq  arrow(Seq s, El e)                { return s.follow(e); }
440         public static @bind.as("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
441         public static @bind.as("/")   Seq  slash(Seq s, El e)                { return s.separate(e); }
442
443         public static @bind.as("ps")  Seq  seq(El[] elements)                { return new Seq(elements); }
444         public static @bind.as        Seq  psx(Seq s)                        { return s; }
445         public static @bind.as(":")   El   colon(String s, El e)             { return new Label(s, e); }
446         public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
447         public static @bind.as("()")  El   epsilon()                         { return new Constant(Union.epsilon); }
448
449         public static @bind.as("nonTerminal") class NonTerminalReference extends El {
450             public @bind.arg String nonTerminal;
451             public Element build(Context cx) {
452                 return cx.get(nonTerminal);
453             }
454         }
455
456         public static class StringLiteral        extends Constant {
457             public @bind.as("literal") StringLiteral(String string) { super(CharRange.string(string)); }
458             public boolean drop() { return true; }
459         }
460
461         public static                     class CharClass            extends El {
462             Range[] ranges;
463             public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
464             public Element build(Context cx) {
465                 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
466                 for(Range r : ranges)
467                         set.add(r.first, r.last);
468                 return CharRange.set(set);
469             }
470         }
471
472         public static @bind.as("{")           class XTree                 extends El {
473             public @bind.arg Seq body;
474             public Element build(Context cx) {
475                 throw new Error();
476             }
477         }
478
479         public static class Rep extends El {
480             public El e, sep;
481             public boolean zero, many, max;
482             public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
483                 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
484             public Element build(Context cx) {
485                 return (!max)
486                     ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
487                     : sep==null
488                     ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many,                                   cx.rm.repeatTag())
489                     : Sequence.repeatMaximal(e.build(cx),                    zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
490             }
491         }
492         public static class Constant extends El {
493             Element constant;
494             public Constant(Element constant) { this.constant = constant; }
495             public Element build(Context cx) { return constant; }
496         }
497         public abstract static class PostProcess extends El {
498             El e;
499             public PostProcess(El e) { this.e = e; }
500             public Element build(Context cx) { return postProcess(e.build(cx)); }
501             public abstract Element postProcess(Element e);
502         }
503
504         // FIXME: it would be nice if we could hoist this into "Rep"
505         public static @bind.as("++")  El plusmax(final El e)                     { return new Rep(e, null, false, true, true); }
506         public static @bind.as("+")   El plus(final El e)                        { return new Rep(e, null, false, true, false); }
507         public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep,  false, true, true); }
508         public static @bind.as("+/")  El plusfollow(final El e, final El sep)    { return new Rep(e, sep,  false, true, false); }
509         public static @bind.as("**")  El starmax(final El e)                     { return new Rep(e, null, true,  true, true); }
510         public static @bind.as("*")   El star(final El e)                        { return new Rep(e, null, true,  true, false); }
511         public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep,  true,  true, true); }
512         public static @bind.as("*/")  El starfollow(final El e, final El sep)    { return new Rep(e, sep,  true,  true, false); }
513         public static @bind.as("?")   El question(final El e)                    { return new Rep(e, null, true,  true, false); }
514
515         public static @bind.as("!")   El bang(final El e)                        { return new Drop(e); }
516
517         public static @bind.as("^")   El caret(final String s) {
518             return new Drop(new Constant(CharRange.string(s)) {
519                     public String getOwnerTag() { return s; }
520                 });
521         }
522
523         public static @bind.as("~")   El tilde(final El e) {
524             return new PostProcess(e) {
525                     public Element postProcess(Element e) {
526                         return MetaGrammar.infer((Topology<Character>)Atom.toAtom(e).complement()); 
527                     } }; }
528
529         public static @bind.as("^^")  void doublecaret(final El e)                 { throw new Error("not implemented"); }
530
531         //public static @bind.as("(")   El subexpression(Seq[][] rhs)                { return new NonTerminal(rhs); }
532
533         public static @bind.as("Word")    String word(String s) { return s; }
534         public static @bind.as("Quoted")  String quoted(String s) { return s; }
535         public static @bind.as("escaped") String c(char c) { return c+""; }
536         public static @bind.as("\"\"")    String emptystring() { return ""; }
537         public static @bind.as("\n")      String retur() { return "\n"; }
538         public static @bind.as("\r")      String lf() { return "\r"; }
539
540     }
541     public static class Context {
542         HashMap<String,Union> map = new HashMap<String,Union>();
543         private MG.Grammar grammar;
544         public String cnt = null;
545         private ReflectiveMeta rm;
546         public Context(MG.Grammar g, ReflectiveMeta rm) {
547             this.grammar = g;
548             this.rm = rm;
549         }
550         public Union build() {
551             Union ret = null;
552             for(MG.NonTerminal nt : grammar.nonterminals) {
553                 Union u = get(nt.name);
554                 if ("s".equals(nt.name))
555                     ret = u;
556             }
557             return ret;
558         }
559         public Context(Tree t, ReflectiveMeta rm) {
560             this.rm = rm;
561             Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
562             this.grammar = (MG.Grammar)red.invoke(t.children());
563         }
564         public Union peek(String name) { return map.get(name); }
565         public void  put(String name, Union u) { map.put(name, u); }
566         public Union get(String name) {
567             Union ret = map.get(name);
568             if (ret != null) return ret;
569             ret = new Union(name);
570             map.put(name, ret);
571             MG.NonTerminal nt = grammar.get(name);
572             if (nt==null) {
573                 System.err.println("*** warning could not find " + name);
574             } else {
575                 String old = cnt;
576                 cnt = name;
577                 nt.build(this, ret);
578                 cnt = old;
579             }
580             return ret;
581         }
582
583     }
584 }