467ff383bee67704bc12019c5a85b79ffde6e5cb
[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 Reflection.Bindable _bindable;
152
153         public Target(Object o) { this(Reflection.Bindable.create(o)); }
154         public Target(Reflection.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         public static class TargetReducer implements Tree.TreeFunctor<Object,Object> {
205             private Production p;
206             private int[] map;
207             private String name;
208             private Reflection.Bindable _bindable;
209             private boolean _israw;
210             public TargetReducer(Production p, int[] map, String name, Reflection.Bindable b, boolean raw) {
211                 this.p = p;
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
243
244     public static Union cached = null;
245     public static Union make() {
246         if (cached != null) return cached;
247         try {
248             ReflectiveMeta m = new ReflectiveMeta();
249             Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
250             MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
251             MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
252             Union meta = mgf.get("s").build(bc);
253             Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
254             return cached = make(t, "s");
255         } catch (Exception e) {
256             throw new RuntimeException(e);
257         }
258     }
259     public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
260     public static Union make(Tree t, String s, ReflectiveMeta rm) {
261         Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
262         MG.Grammar g = (MG.Grammar)red.invoke(t.children());
263         Context cx = new Context(g,rm);
264         Union u = null;
265         for(MG.NonTerminal nt : g.nonterminals) {
266             System.out.println(nt.name);
267             Union el = (Union)cx.get(nt.name);
268             StringBuffer st = new StringBuffer();
269             el.toString(st);
270             System.err.println(st);
271             if (nt.name.equals(s)) u = el;
272         }
273         return u;
274     }
275
276
277
278     public static class MG {
279         public static @bind.as("grammar") class Grammar {
280             public NonTerminal get(String s) {
281                 for(NonTerminal nt : nonterminals)
282                     if (nt.name.equals(s))
283                         return nt;
284                 return null;
285             }
286             public @bind.arg("NonTerminal") NonTerminal[] nonterminals;
287             public String toString() {
288                 String ret = "[ ";
289                 for(NonTerminal nt : nonterminals) ret += nt + ", ";
290                 return ret + " ]";
291             }
292         }
293         public abstract static class Un extends El {
294             public Seq[][] sequences;
295             public void build(Context cx, Union u) {
296                 HashSet<Sequence> bad2 = new HashSet<Sequence>();
297                 for(int i=0; i<sequences.length; i++) {
298                     Seq[] group = sequences[i];
299                     Union u2 = new Union();
300                     if (sequences.length==1) u2 = u;
301                     for(int j=0; j<group.length; j++) {
302                         group[j].build(cx, u2, false);
303                     }
304                     if (sequences.length==1) break;
305                     Sequence seq = Sequence.singleton(u2);
306                     for(Sequence s : bad2) {
307                         s.lame = true;
308                         seq = seq.not(s);
309                     }
310                     u.add(seq);
311                     bad2.add(Sequence.singleton(u2));
312                 }
313             }
314         }
315         public static class NonTerminal extends Un {
316             public String  name = null;
317             public @bind.as("=") NonTerminal(@bind.arg("Word") String name,
318                                          @bind.arg("RHS") Seq[][] sequences) {
319                 this.name = name;
320                 this.sequences = sequences;
321             }
322             public Element build(Context cx) { return cx.get(name); }
323         }
324
325         public static class AnonUn extends Un {
326             public @bind.as("(") AnonUn(Seq[][] sequences) {
327                 this.sequences = sequences;
328             }
329             public Element build(Context cx) {
330                 Union ret = new Union();
331                 build(cx, ret);
332                 return ret;
333             }
334         }
335
336         //public static @bind.as void range(char c) { }
337         public static class Range {
338             public @bind.as("range") Range(char only) { first = only; last = only; }
339             public @bind.as("-")     Range(char first, char last) { this.first = first; this.last = last; }
340             public char first;
341             public char last;
342         }
343         public static abstract class El {
344             public String getLabel() { return null; }
345             public String getOwnerTag() { return null; }
346             public boolean drop() { return false; }
347             public abstract Element build(Context cx);
348         }
349         public static class Drop extends El {
350             public El e;
351             public Drop(El e) { this.e = e; }
352             public String getLabel() { return null; }
353             public boolean drop() { return true; }
354             public String getOwnerTag() { return e.getOwnerTag(); }
355             public Element build(Context cx) { return e.build(cx); }
356         }
357         public static class Label extends El {
358             public String label;
359             public El e;
360             public Label(String label, El e) { this.e = e; this.label = label; }
361             public String getLabel() { return label; }
362             public String getOwnerTag() { return e.getOwnerTag(); }
363             public Element build(Context cx) { return e.build(cx); }
364         }
365         public static /*abstract*/ class Seq {
366             HashSet<Seq> and = new HashSet<Seq>();
367             HashSet<Seq> not = new HashSet<Seq>();
368             El[] elements;
369             El follow;
370             String tag = null;
371             boolean lame;
372             public Seq(El e) { this(new El[] { e }); }
373             public Seq(El[] elements) { this.elements = elements; }
374             public Seq tag(String tag) { this.tag = tag; return this; }
375             public Seq follow(El follow) { this.follow = follow; return this; }
376             public Seq dup() {
377                 Seq ret = new Seq(elements);
378                 ret.and.addAll(and);
379                 ret.not.addAll(not);
380                 ret.follow = follow;
381                 ret.tag = tag;
382                 return ret;
383             }
384             public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
385             public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
386             public Seq separate(El sep) {
387                 El[] elements = new El[this.elements.length * 2 - 1];
388                 for(int i=0; i<this.elements.length; i++) {
389                     elements[i*2]   = this.elements[i];
390                     if (i<this.elements.length-1)
391                         elements[i*2+1] = new Drop(sep);
392                 }
393                 this.elements = elements;
394                 return this;
395             }
396             public Sequence build(Context cx, Union u, boolean lame) {
397                 Sequence ret = build0(cx, lame || this.lame);
398                 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
399                 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
400                 u.add(ret);
401                 ret.lame = lame;
402                 return ret;
403             }
404             public Sequence build0(Context cx, boolean lame) {
405                 boolean unwrap = false;
406                 boolean dropAll = lame;
407                 if (tag!=null && tag.equals("[]")) unwrap  = true;
408                 if (tag!=null && "()".equals(tag)) dropAll = true;
409                 Object[] labels = new Object[elements.length];
410                 boolean[] drops = new boolean[elements.length];
411                 Element[] els = new Element[elements.length];
412                 for(int i=0; i<elements.length; i++) {
413                     labels[i] = elements[i].getLabel();
414                     drops[i]  = elements[i].drop();
415                     els[i] = elements[i].build(cx);
416                     if (elements[i].getOwnerTag() != null)
417                         tag = elements[i].getOwnerTag();
418                 }
419                 Sequence ret = null;
420                 if (dropAll)     ret = Sequence.drop(els, false);
421                 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
422                 else if (tag!=null) {
423                     ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
424                 } else {
425                     int idx = -1;
426                     for(int i=0; i<els.length; i++)
427                         if (!drops[i])
428                             if (idx==-1) idx = i;
429                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
430                     if (idx != -1) ret = Sequence.singleton(els, idx);
431                     else           ret = Sequence.drop(els, false);
432                 }
433                 if (this.follow != null)
434                     ret.follow = MetaGrammar.infer(this.follow.build(cx));
435                 ret.lame = this.lame;
436                 return ret;
437             }
438         }
439         public static @bind.as("&")   Seq  and(Seq s,         El[] elements) { return s.and(seq(elements)); }
440         public static @bind.as("&~")  Seq  andnot(Seq s,      El[] elements) { return s.andnot(seq(elements)); }
441         public static @bind.as("->")  Seq  arrow(Seq s, El e)                { return s.follow(e); }
442         public static @bind.as("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
443         public static @bind.as("/")   Seq  slash(Seq s, El e)                { return s.separate(e); }
444
445         public static @bind.as("ps")  Seq  seq(El[] elements)                { return new Seq(elements); }
446         public static @bind.as        Seq  psx(Seq s)                        { return s; }
447         public static @bind.as(":")   El   colon(String s, El e)             { return new Label(s, e); }
448         public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
449         public static @bind.as("()")  El   epsilon()                         { return new Constant(Union.epsilon); }
450
451         public static @bind.as("nonTerminal") class NonTerminalReference extends El {
452             public @bind.arg String nonTerminal;
453             public Element build(Context cx) {
454                 return cx.get(nonTerminal);
455             }
456         }
457
458         public static class StringLiteral        extends Constant {
459             public @bind.as("literal") StringLiteral(String string) { super(CharRange.string(string)); }
460             public boolean drop() { return true; }
461         }
462
463         public static                     class CharClass            extends El {
464             Range[] ranges;
465             public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
466             public Element build(Context cx) {
467                 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
468                 for(Range r : ranges)
469                         set.add(r.first, r.last);
470                 return CharRange.set(set);
471             }
472         }
473
474         public static @bind.as("{")           class XTree                 extends El {
475             public @bind.arg Seq body;
476             public Element build(Context cx) {
477                 throw new Error();
478             }
479         }
480
481         public static class Rep extends El {
482             public El e, sep;
483             public boolean zero, many, max;
484             public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
485                 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
486             public Element build(Context cx) {
487                 return (!max)
488                     ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
489                     : sep==null
490                     ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many,                                   cx.rm.repeatTag())
491                     : Sequence.repeatMaximal(e.build(cx),                    zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
492             }
493         }
494         public static class Constant extends El {
495             Element constant;
496             public Constant(Element constant) { this.constant = constant; }
497             public Element build(Context cx) { return constant; }
498         }
499         public abstract static class PostProcess extends El {
500             El e;
501             public PostProcess(El e) { this.e = e; }
502             public Element build(Context cx) { return postProcess(e.build(cx)); }
503             public abstract Element postProcess(Element e);
504         }
505
506         // FIXME: it would be nice if we could hoist this into "Rep"
507         public static @bind.as("++")  El plusmax(final El e)                     { return new Rep(e, null, false, true, true); }
508         public static @bind.as("+")   El plus(final El e)                        { return new Rep(e, null, false, true, false); }
509         public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep,  false, true, true); }
510         public static @bind.as("+/")  El plusfollow(final El e, final El sep)    { return new Rep(e, sep,  false, true, false); }
511         public static @bind.as("**")  El starmax(final El e)                     { return new Rep(e, null, true,  true, true); }
512         public static @bind.as("*")   El star(final El e)                        { return new Rep(e, null, true,  true, false); }
513         public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep,  true,  true, true); }
514         public static @bind.as("*/")  El starfollow(final El e, final El sep)    { return new Rep(e, sep,  true,  true, false); }
515         public static @bind.as("?")   El question(final El e)                    { return new Rep(e, null, true,  true, false); }
516
517         public static @bind.as("!")   El bang(final El e)                        { return new Drop(e); }
518
519         public static @bind.as("^")   El caret(final String s) {
520             return new Drop(new Constant(CharRange.string(s)) {
521                     public String getOwnerTag() { return s; }
522                 });
523         }
524
525         public static @bind.as("~")   El tilde(final El e) {
526             return new PostProcess(e) {
527                     public Element postProcess(Element e) {
528                         return MetaGrammar.infer((Topology<Character>)Atom.toAtom(e).complement()); 
529                     } }; }
530
531         public static @bind.as("^^")  void doublecaret(final El e)                 { throw new Error("not implemented"); }
532
533         //public static @bind.as("(")   El subexpression(Seq[][] rhs)                { return new NonTerminal(rhs); }
534
535         public static @bind.as("Word")    String word(String s) { return s; }
536         public static @bind.as("Quoted")  String quoted(String s) { return s; }
537         public static @bind.as("escaped") String c(char c) { return c+""; }
538         public static @bind.as("\"\"")    String emptystring() { return ""; }
539         public static @bind.as("\n")      String retur() { return "\n"; }
540         public static @bind.as("\r")      String lf() { return "\r"; }
541
542     }
543     public static class Context {
544         HashMap<String,Union> map = new HashMap<String,Union>();
545         private MG.Grammar grammar;
546         public String cnt = null;
547         private ReflectiveMeta rm;
548         public Context(MG.Grammar g, ReflectiveMeta rm) {
549             this.grammar = g;
550             this.rm = rm;
551         }
552         public Union build() {
553             Union ret = null;
554             for(MG.NonTerminal nt : grammar.nonterminals) {
555                 Union u = get(nt.name);
556                 if ("s".equals(nt.name))
557                     ret = u;
558             }
559             return ret;
560         }
561         public Context(Tree t, ReflectiveMeta rm) {
562             this.rm = rm;
563             Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
564             this.grammar = (MG.Grammar)red.invoke(t.children());
565         }
566         public Union peek(String name) { return map.get(name); }
567         public void  put(String name, Union u) { map.put(name, u); }
568         public Union get(String name) {
569             Union ret = map.get(name);
570             if (ret != null) return ret;
571             ret = new Union(name);
572             map.put(name, ret);
573             MG.NonTerminal nt = grammar.get(name);
574             if (nt==null) {
575                 System.err.println("*** warning could not find " + name);
576             } else {
577                 String old = cnt;
578                 cnt = name;
579                 nt.build(this, ret);
580                 cnt = old;
581             }
582             return ret;
583         }
584
585     }
586 }