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     
12     public static boolean harsh = false;
13
14     public static void main(String[] s) throws Exception {
15
16         ReflectiveMeta m = new ReflectiveMeta();
17         Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
18         MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
19         MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
20         Union meta = mgf.get("s").build(bc);
21         System.err.println("parsing " + s[1]);
22         Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
23         System.out.println("tree:\n" + t.toPrettyString());
24
25         Reducer red = (Reducer)t.head();
26         MG.Grammar g = (MG.Grammar)red.reduce(t);
27         System.out.println(g);
28         
29         Context cx = new Context(g,m);
30         Element u = null;
31         for(MG.NonTerminal nt : g.nonterminals) {
32             Union el = (Union)cx.get(nt.name);
33             StringBuffer st = new StringBuffer();
34             el.toString(st);
35             System.err.println(st);
36             if (nt.name.equals("s")) u = el;
37         }
38         System.err.println();
39
40         System.err.println("== parsing with parsed grammar =================================================================================");
41         t = new CharParser((Union)u).parse(new FileInputStream(s[1])).expand1();
42         System.out.println(t.toPrettyString());
43
44         System.err.println("== parsing with parsed-parsed grammar ==========================================================================");
45         t = new CharParser(new Context(t, m).build()).parse(new FileInputStream(s[1])).expand1();
46         System.out.println(t.toPrettyString());
47     }
48
49     public static class ReflectiveMeta extends MetaGrammar.Meta {
50         private final Class _cl;
51         private final Class[] _inner;
52         public ReflectiveMeta() {
53             this(MG.class,
54                  new Class[] {
55                      MG.Grammar.class,
56                      MG.NonTerminal.class,
57                      MG.AnonUn.class,
58                      MG.Range.class,
59                      MG.El.class,
60                      MG.Seq.class,
61                      MG.NonTerminalReference.class,
62                      MG.StringLiteral.class,
63                      MG.Tree.class,
64                      MG.CharClass.class
65                  });
66         }
67         public ReflectiveMeta(Class c, Class[] inner) {
68             this._cl = c;
69             this._inner = inner;
70         }
71         private boolean match(Method m, String s) { return match(m.getAnnotation(tag.class), null, s); }
72         private boolean match(tag t, Class c, String s) {
73             if (t==null) return false;
74             if (t.value().equals(s)) return true;
75             if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
76             return false;
77         }
78         private boolean match(nonterminal t, Class c, String s) {
79             if (t==null) return false;
80             if (t.value().equals(s)) return true;
81             if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
82             return false;
83         }
84         private boolean match(Class c, String s, String nonTerminalName) {
85             if (match((tag)c.getAnnotation(tag.class), c, s)) return true;
86             if (match((nonterminal)c.getAnnotation(nonterminal.class), c, nonTerminalName)) return true;
87             return false;
88         }
89         public boolean match(Constructor con, String s, String nonTerminalName) {
90             Class c = con.getDeclaringClass();
91             if (match((tag)con.getAnnotation(tag.class), null, s)) return true;
92             if (match((nonterminal)con.getAnnotation(nonterminal.class), c, s)) return true;
93             return false;
94         }
95         public Object repeatTag() {
96             return new Reducer() {
97                     public String toString() { return ""; }
98                     public Object reduce(Tree t) {
99                         Object[] ret = new Object[t.numChildren()];
100                         for(int i=0; i<t.numChildren(); i++) {
101                             Tree tc = t.child(i);
102                             if (tc.head() != null && tc.head() instanceof Reducer)
103                                 ret[i] = ((Reducer)tc.head()).reduce(tc);
104                             else if (tc.numChildren() == 0)
105                                 ret[i] = tc.head();
106                             else {
107                                 System.err.println("FIXME: don't know what to do about " + tc);
108                                 ret[i] = null;
109                             }
110                         }
111                         return ret;
112                     }
113                 };
114         }
115         public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
116             Production p = new Production(tag, nonTerminalName, els, labels, drops);
117             for(Method m : _cl.getMethods())
118                 if (new TargetMethod(m).isCompatible(p))
119                     return new TargetMethod(m).makeSequence(p);
120             for(Class c : _inner)
121                 for(Constructor con : c.getConstructors())
122                     if (new TargetConstructor(con).isCompatible(p))
123                         return new TargetConstructor(con).makeSequence(p);
124             for(Class c : _inner)
125                 if (new TargetClass(c).isCompatible(p))
126                     return new TargetClass(c).makeSequence(p);
127             return null;
128         }
129         public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
130             Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
131             if (ret != null) return ret;
132             String message = "could not find a Java method/class/ctor matching tag \""+tag+
133                 "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
134             if (harsh) {
135                 throw new RuntimeException(message);
136             } else {
137                 System.err.println(message);
138                 return Sequence.rewritingSequence(tag, els, labels, drops);
139             }
140         }
141     }
142
143     
144     /**
145      *  Constructors, classes, and methods with this attribute will
146      *  match every production of the nonterminal called "value()"
147      *  that is arg-compatible.  If value() is undefined, then the
148      *  class/constructor/method name is used.
149      */ 
150     @Retention(RetentionPolicy.RUNTIME) public static @interface nonterminal { String value() default ""; }
151
152     /**
153      *  Constructors, classes, and methods with this attribute will
154      *  match every tree tagged with "value()" that is arg-compatible.
155      *  If value() is undefined, then the class/constructor/method
156      *  name is used.
157      */ 
158     @Retention(RetentionPolicy.RUNTIME) public static @interface tag         { String value() default ""; }
159
160     /**
161      *  If any parameter to a method or field in a class has a named
162      *  arg-tag, that parameter/field matches the child of the tree
163      *  which either has that label or else is a reference to a
164      *  nonterminal with the corresponding name.
165      *  
166      *  The remaining non-named arg-tags match the remaining children
167      *  of the tree in sequential order.
168      *
169      *  If any arg-tagged parameters/fields remain, the match fails.
170      *  If there were no arg-tagged parameters-fields, it is as if all
171      *  of them were non-named and arg-tagged.
172      *
173      *  A method/constructor is arg-compatible if all of its arguments
174      *  are arg-compatible.
175      *
176      *  A class is arg-compatible if all of its fields are
177      *  arg-compatible, or if one of its constructors is arg-compatible.
178      *
179      */
180     @Retention(RetentionPolicy.RUNTIME) public static @interface arg         { String value() default ""; }
181
182     public static class Production {
183         public String tag;
184         public String nonTerminal;
185         public Object[] labels;
186         public boolean[] drops;
187         public Element[] elements;
188         public int count = 0;
189         public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
190             this.tag = tag;
191             this.elements = elements;
192             this.nonTerminal = nonTerminal;
193             this.labels = labels;
194             this.drops = drops;
195             for(int i=0; i<drops.length; i++)
196                 if (!drops[i])
197                     count++;
198         }
199     }
200
201     public static abstract class Target {
202         public abstract String getName();
203         public abstract tag getTag();
204         public abstract nonterminal getNonTerminal();
205         public abstract int[] buildSequence(Production p);
206         public boolean isCompatible(Production p) {
207             tag t = getTag();
208             if (t != null &&
209                 (t.value().equals(p.tag) ||
210                  (t.value().equals("") && getName().equals(p.tag))))
211                 return buildSequence(p)!=null;
212
213             nonterminal n = getNonTerminal();
214             if (n != null &&
215                 (n.value().equals(p.nonTerminal) ||
216                  (n.value().equals("") && getName().equals(p.nonTerminal))))
217                 return buildSequence(p)!=null;
218
219             return false;
220         }
221         public int[] buildSequence(Production p, String[] names, arg[] argtags) {
222             int argTagged = 0;
223             for(int i=0; i<argtags.length; i++)
224                 if (argtags[i] != null)
225                     argTagged++;
226
227             // FIXME: can be smarter here
228             if (names.length==p.count) {
229                 int[] ret = new int[p.count];
230                 for(int i=0; i<p.count; i++) ret[i] = i;
231                 return ret;
232             } else if (argTagged==p.count) {
233                 int[] ret = new int[argtags.length];
234                 int j = 0;
235                 for(int i=0; i<argtags.length; i++)
236                     ret[i] = argtags[i]==null ? -1 : (j++);
237                 return ret;
238             } else {
239                 return null;
240             }
241         }
242         public Sequence makeSequence(Production p) {
243             return Sequence.rewritingSequence(new TargetReducer(p), p.elements, p.labels, p.drops);
244         }
245         public abstract Object plant(Object[] fields, int[] map);
246         public class TargetReducer implements Reducer {
247             private Production p;
248             private int[] map;
249             public TargetReducer(Production p) {
250                 this.p = p;
251                 this.map = buildSequence(p);
252             }
253             public String toString() { return "reducer-"+Target.this; }
254             public Object reduce(Tree t) {
255                 Object[] objects = new Object[t.numChildren()];
256                 for(int i=0; i<t.numChildren(); i++) {
257                     Tree tc = t.child(i);
258                     if (tc.head() != null && tc.head() instanceof Reducer)
259                         objects[i] = ((Reducer)tc.head()).reduce(tc);
260                     else if (tc.numChildren() == 0)
261                         objects[i] = tc.head();
262                     else {
263                         System.err.println("FIXME: don't know what to do about " + tc);
264                         objects[i] = null;
265                     }
266                 }
267                 System.err.println("input tree: " + t);
268                 return plant(objects, map);
269             }
270         }
271     }
272
273     public static interface Reducer {
274         public Object reduce(Tree t);
275     }
276
277     public static class TargetClass extends Target {
278         public final Class _class;
279         public TargetClass(Class _class) { this._class = _class; }
280         public String getName() { return _class.getSimpleName(); }
281         public tag getTag() { return (tag)_class.getAnnotation(tag.class); }
282         public nonterminal getNonTerminal() { return (nonterminal)_class.getAnnotation(nonterminal.class); }
283         public String toString() { return _class.getSimpleName(); }
284         public int[] buildSequence(Production p) {
285             Field[]  f       = _class.getDeclaredFields();
286             String[] names   = new String[f.length];
287             arg[]    argtags = new arg[f.length];
288             for(int i=0; i<f.length; i++) {
289                 names[i]   = f[i].getName();
290                 argtags[i] = f[i].getAnnotation(arg.class);
291             }
292             int[] ret = buildSequence(p, names, argtags);
293             if (ret!=null) return ret;
294             for(Constructor c : _class.getConstructors())
295                 if (new TargetConstructor(c).buildSequence(p)!=null)
296                     return new TargetConstructor(c).buildSequence(p);
297             return null;
298         }
299         public Object plant(Object[] fields, int[] map) {
300             try {
301                 Object ret = _class.newInstance();
302                 Field[] f = _class.getFields();
303                 int j = 0;
304                 for(int i=0; i<f.length; i++)
305                     if (map[i] != -1) {
306                         Object tgt = Reflection.lub(fields[map[i]]);
307                         if (f[i].getType() == String.class) tgt = stringify(tgt);
308                         // FUGLY
309                         tgt = coerce(tgt, f[i].getType());
310                         System.err.println("setting a " + f[i].getType().getName() + " to " + Reflection.show(tgt));
311                         f[i].set(ret, tgt);
312                     }
313                 return ret;
314             } catch (Exception e) {
315                 e.printStackTrace();
316                 throw new RuntimeException(e);
317             }
318         }
319     }
320
321     public static String stringify(Object o) {
322         if (o==null) return "";
323         if (!(o instanceof Object[])) return o.toString();
324         Object[] arr = (Object[])o;
325         StringBuffer ret = new StringBuffer();
326         for(int i=0; i<arr.length; i++)
327             ret.append(arr[i]);
328         return ret.toString();
329     }
330
331     public static class TargetConstructor extends Target {
332         public final Constructor _ctor;
333         public TargetConstructor(Constructor _ctor) { this._ctor = _ctor; }
334         public String getName() { return _ctor.getName(); }
335         public tag getTag() { return (tag)_ctor.getAnnotation(tag.class); }
336         public nonterminal getNonTerminal() { return (nonterminal)_ctor.getAnnotation(nonterminal.class); }
337         public String toString() { return _ctor.getName(); }
338         public int[] buildSequence(Production p) {
339             Annotation[][] annotations = _ctor.getParameterAnnotations();
340             int len = annotations.length;
341             int ofs = 0;
342             String name = _ctor.getDeclaringClass().getName();
343             /*
344             if (name.indexOf('$') > name.lastIndexOf('.')) {
345                 len--;
346                 ofs++;
347             }
348             */
349             String[] names   = new String[len];
350             arg[]    argtags = new arg[len];
351             for(int i=0; i<names.length; i++)
352                 for(Annotation a : annotations[i+ofs])
353                     if (a instanceof arg)
354                         argtags[i+ofs] = (arg)a;
355             return buildSequence(p, names, argtags);
356         }
357         public Object plant(Object[] fields, int[] map) {
358             try {
359                 Class[] argTypes = _ctor.getParameterTypes();
360                 Object[] args = new Object[argTypes.length];
361                 int j = 0;
362                 for(int i=0; i<args.length; i++)
363                     if (map[i] != -1) {
364                         Object tgt = Reflection.lub(fields[map[i]]);
365                         if (argTypes[i] == String.class) tgt = stringify(tgt);
366                         // FUGLY
367                         tgt = coerce(tgt, argTypes[i]);
368                         System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
369                         args[i] = tgt;
370                     }
371                 return _ctor.newInstance(args);
372             } catch (Exception e) {
373                 throw new RuntimeException(e);
374             }
375         }
376     }
377     public static class TargetMethod extends Target {
378         public final Method _method;
379         public TargetMethod(Method _method) { this._method = _method; }
380         public String getName() { return _method.getName(); }
381         public String toString() { return _method.getName(); }
382         public tag getTag() { return (tag)_method.getAnnotation(tag.class); }
383         public nonterminal getNonTerminal() { return (nonterminal)_method.getAnnotation(nonterminal.class); }
384         public int[] buildSequence(Production p) {
385             Annotation[][] annotations = _method.getParameterAnnotations();
386             String[] names   = new String[annotations.length];
387             arg[]    argtags = new arg[annotations.length];
388             for(int i=0; i<names.length; i++)
389                 for(Annotation a : annotations[i])
390                     if (a instanceof arg)
391                         argtags[i] = (arg)a;
392             int[] ret = buildSequence(p, names, argtags);
393             return ret;
394         }
395         public Object plant(Object[] fields, int[] map) {
396             try {
397                 Class[] argTypes = _method.getParameterTypes();
398                 Object[] args = new Object[argTypes.length];
399                 int j = 0;
400                 for(int i=0; i<args.length; i++)
401                     if (map[i] != -1) {
402                         Object tgt = Reflection.lub(fields[map[i]]);
403                         if (argTypes[i] == String.class) tgt = stringify(tgt);
404                         // FUGLY
405                         tgt = coerce(tgt, argTypes[i]);
406                         System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
407                         args[i] = tgt;
408                     }
409                 System.err.println("invoking " + _method + " with " + Reflection.show(args));
410                 return _method.invoke(null, args);
411             } catch (Exception e) {
412                 throw new RuntimeException(e);
413             }
414         }
415     }
416
417     public static Object coerce(Object o, Class c) {
418         if (o==null) return null;
419         if (c.isInstance(o)) return o;
420         if (c == char.class) {
421             return o.toString().charAt(0);
422         }
423         if (c.isArray() && (c.getComponentType().isInstance(o))) {
424             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
425             ret[0] = o;
426             return ret;
427         }
428         if (o.getClass().isArray() && c.isArray()) {
429             boolean ok = true;
430             for(int i=0; i<((Object[])o).length; i++) {
431                 Object ob = (((Object[])o)[i]);
432                 if (ob != null) {
433                     System.err.println("no hit with " + c.getComponentType().getName() + " on " + Reflection.show(((Object[])o)[i]));
434                     ok = false;
435                 }
436             }
437             if (ok) {
438                 System.err.println("hit with " + c.getComponentType().getName());
439                 return Array.newInstance(c.getComponentType(), ((Object[])o).length);
440             }
441         }
442         return o;
443     }
444
445     public static class MG {
446         public static @tag("grammar") class Grammar {
447             public NonTerminal get(String s) {
448                 for(NonTerminal nt : nonterminals)
449                     if (nt.name.equals(s))
450                         return nt;
451                 return null;
452             }
453             public @arg("NonTerminal") NonTerminal[] nonterminals;
454             public String toString() {
455                 String ret = "[ ";
456                 for(NonTerminal nt : nonterminals) ret += nt + ", ";
457                 return ret + " ]";
458             }
459         }
460         public abstract static class Un extends El {
461             public Seq[][] sequences;
462             public void build(Context cx, Union u) {
463                 HashSet<Sequence> bad2 = new HashSet<Sequence>();
464                 for(int i=0; i<sequences.length; i++) {
465                     Seq[] group = sequences[i];
466                     Union u2 = new Union();
467                     if (sequences.length==1) u2 = u;
468                     for(int j=0; j<group.length; j++) {
469                         group[j].build(cx, u2, false);
470                     }
471                     if (sequences.length==1) break;
472                     Sequence seq = Sequence.singleton(u2);
473                     for(Sequence s : bad2) {
474                         s.lame = true;
475                         seq = seq.not(s);
476                     }
477                     u.add(seq);
478                     bad2.add(Sequence.singleton(u2));
479                 }
480             }
481         }
482         public static class NonTerminal extends Un {
483             public String  name = null;
484             public @nonterminal("NonTerminal") NonTerminal(@arg("Word") String name,
485                                                            @arg("RHS") Seq[][] sequences) {
486                 this.name = name;
487                 this.sequences = sequences;
488             }
489             public Element build(Context cx) { return cx.get(name); }
490         }
491
492         public static class AnonUn extends Un {
493             public @tag("(") AnonUn(Seq[][] sequences) {
494                 this.sequences = sequences;
495             }
496             public Element build(Context cx) {
497                 Union ret = new Union();
498                 build(cx, ret);
499                 return ret;
500             }
501         }
502
503         //public static @tag void range(char c) { }
504         public static class Range {
505             public @tag("range") Range(char only) { first = only; last = only; }
506             public @tag("-")     Range(char first, char last) { this.first = first; this.last = last; }
507             public char first;
508             public char last;
509         }
510         public static abstract class El {
511             public String getLabel() { return null; }
512             public String getOwnerTag() { return null; }
513             public boolean drop() { return false; }
514             public abstract Element build(Context cx);
515         }
516         public static class Drop extends El {
517             public El e;
518             public Drop(El e) { this.e = e; }
519             public String getLabel() { return null; }
520             public boolean drop() { return true; }
521             public String getOwnerTag() { return e.getOwnerTag(); }
522             public Element build(Context cx) { return e.build(cx); }
523         }
524         public static class Label extends El {
525             public String label;
526             public El e;
527             public Label(String label, El e) { this.e = e; this.label = label; }
528             public String getLabel() { return label; }
529             public String getOwnerTag() { return e.getOwnerTag(); }
530             public Element build(Context cx) { return e.build(cx); }
531         }
532         public static /*abstract*/ class Seq {
533             HashSet<Seq> and = new HashSet<Seq>();
534             HashSet<Seq> not = new HashSet<Seq>();
535             El[] elements;
536             El follow;
537             String tag = null;
538             boolean lame;
539             public Seq(El e) { this(new El[] { e }); }
540             public Seq(El[] elements) { this.elements = elements; }
541             public Seq tag(String tag) { this.tag = tag; return this; }
542             public Seq follow(El follow) { this.follow = follow; return this; }
543             public Seq dup() {
544                 Seq ret = new Seq(elements);
545                 ret.and.addAll(and);
546                 ret.not.addAll(not);
547                 ret.follow = follow;
548                 ret.tag = tag;
549                 return ret;
550             }
551             public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
552             public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
553             public Seq separate(El sep) {
554                 El[] elements = new El[this.elements.length * 2 - 1];
555                 for(int i=0; i<this.elements.length; i++) {
556                     elements[i*2]   = this.elements[i];
557                     if (i<this.elements.length-1)
558                         elements[i*2+1] = new Drop(sep);
559                 }
560                 this.elements = elements;
561                 return this;
562             }
563             public Sequence build(Context cx, Union u, boolean lame) {
564                 Sequence ret = build0(cx, lame || this.lame);
565                 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
566                 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
567                 u.add(ret);
568                 ret.lame = lame;
569                 return ret;
570             }
571             public Sequence build0(Context cx, boolean lame) {
572                 boolean unwrap = false;
573                 boolean dropAll = lame;
574                 if (tag!=null && tag.equals("[]")) unwrap  = true;
575                 if (tag!=null && "()".equals(tag)) dropAll = true;
576                 Object[] labels = new Object[elements.length];
577                 boolean[] drops = new boolean[elements.length];
578                 Element[] els = new Element[elements.length];
579                 for(int i=0; i<elements.length; i++) {
580                     labels[i] = elements[i].getLabel();
581                     drops[i]  = elements[i].drop();
582                     els[i] = elements[i].build(cx);
583                     if (elements[i].getOwnerTag() != null)
584                         tag = elements[i].getOwnerTag();
585                 }
586                 Sequence ret = null;
587                 if (dropAll)     ret = Sequence.drop(els, false);
588                 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
589                 else if (tag!=null) {
590                     ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
591                 } else {
592                     int idx = -1;
593                     for(int i=0; i<els.length; i++)
594                         if (!drops[i])
595                             if (idx==-1) idx = i;
596                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
597                     if (idx != -1) ret = Sequence.singleton(els, idx);
598                     else           ret = Sequence.drop(els, false);
599                 }
600                 if (this.follow != null)
601                     ret.follow = MetaGrammar.infer(this.follow.build(cx));
602                 ret.lame = this.lame;
603                 return ret;
604             }
605         }
606         public static @tag("&")   Seq  and(Seq s,         El[] elements) { return s.and(seq(elements)); }
607         public static @tag("&~")  Seq  andnot(Seq s,      El[] elements) { return s.andnot(seq(elements)); }
608         public static @tag("->")  Seq  arrow(Seq s, El e)                { return s.follow(e); }
609         public static @tag("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
610         public static @tag("/")   Seq  slash(Seq s, El e)                { return s.separate(e); }
611
612         public static @tag("ps")  Seq  seq(El[] elements)                { return new Seq(elements); }
613         public static @tag        Seq  psx(Seq s)                        { return s; }
614         public static @tag(":")   El   colon(String s, El e)             { return new Label(s, e); }
615         public static @tag(")")   void close(String foo)                 { throw new Error("not supported"); }
616         public static @tag("()")  El   epsilon()                         { return new Constant(Union.epsilon); }
617
618         public static @tag("nonTerminal") class NonTerminalReference extends El {
619             public @arg String nonTerminal;
620             public Element build(Context cx) {
621                 return cx.get(nonTerminal);
622             }
623         }
624         public static class StringLiteral        extends Constant {
625             public @tag("literal") StringLiteral(String string) { super(CharRange.string(string)); }
626             public boolean drop() { return true; }
627         }
628         public static                     class CharClass            extends El {
629             Range[] ranges;
630             public @tag("[") CharClass(Range[] ranges) { this.ranges = ranges; }
631             public Element build(Context cx) {
632                 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
633                 for(Range r : ranges)
634                         set.add(r.first, r.last);
635                 return CharRange.set(set);
636             }
637         }
638
639         public static @tag("{")           class Tree                 extends El {
640             public @arg Seq body;
641             public Element build(Context cx) {
642                 throw new Error();
643             }
644         }
645
646         public static class Rep extends El {
647             public El e, sep;
648             public boolean zero, many, max;
649             public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
650                 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
651             public Element build(Context cx) {
652                 return (!max)
653                     ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
654                     : sep==null
655                     ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many,                                   cx.rm.repeatTag())
656                     : Sequence.repeatMaximal(e.build(cx),                    zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
657             }
658         }
659         public static class Constant extends El {
660             Element constant;
661             public Constant(Element constant) { this.constant = constant; }
662             public Element build(Context cx) { return constant; }
663         }
664         public abstract static class PostProcess extends El {
665             El e;
666             public PostProcess(El e) { this.e = e; }
667             public Element build(Context cx) { return postProcess(e.build(cx)); }
668             public abstract Element postProcess(Element e);
669         }
670
671         // FIXME: it would be nice if we could hoist this into "Rep"
672         public static @tag("++")  El plusmax(final El e)                     { return new Rep(e, null, false, true, true); }
673         public static @tag("+")   El plus(final El e)                        { return new Rep(e, null, false, true, false); }
674         public static @tag("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep,  false, true, true); }
675         public static @tag("+/")  El plusfollow(final El e, final El sep)    { return new Rep(e, sep,  false, true, false); }
676         public static @tag("**")  El starmax(final El e)                     { return new Rep(e, null, true,  true, true); }
677         public static @tag("*")   El star(final El e)                        { return new Rep(e, null, true,  true, false); }
678         public static @tag("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep,  true,  true, true); }
679         public static @tag("*/")  El starfollow(final El e, final El sep)    { return new Rep(e, sep,  true,  true, false); }
680         public static @tag("?")   El question(final El e)                    { return new Rep(e, null, true,  true, false); }
681
682         public static @tag("!")   El bang(final El e)                        { return new Drop(e); }
683
684         public static @tag("^")   El caret(final String s) {
685             return new Drop(new Constant(CharRange.string(s)) {
686                     public String getOwnerTag() { return s; }
687                 });
688         }
689
690         public static @tag("~")   El tilde(final El e) {
691             return new PostProcess(e) {
692                     public Element postProcess(Element e) {
693                         return MetaGrammar.infer((Topology<Character>)Atom.toAtom(e).complement()); 
694                     } }; }
695
696         public static @tag("^^")  void doublecaret(final El e)                 { throw new Error("not implemented"); }
697
698         //public static @tag("(")   El subexpression(Seq[][] rhs)                { return new NonTerminal(rhs); }
699
700         public static @nonterminal("Word")    String word(String s) { return s; }
701         public static @nonterminal("Quoted")  String quoted(String s) { return s; }
702         public static @nonterminal("escaped") String c(char c) { return c+""; }
703         public static @tag("\"\"")            String emptystring() { return ""; }
704         public static @tag("\n")              String retur() { return "\n"; }
705         public static @tag("\r")              String lf() { return "\r"; }
706
707     }
708     public static class Context {
709         HashMap<String,Union> map = new HashMap<String,Union>();
710         private MG.Grammar grammar;
711         public String cnt = null;
712         private ReflectiveMeta rm;
713         public Context(MG.Grammar g, ReflectiveMeta rm) {
714             this.grammar = g;
715             this.rm = rm;
716         }
717         public Union build() {
718             Union ret = null;
719             for(MG.NonTerminal nt : grammar.nonterminals) {
720                 Union u = get(nt.name);
721                 if ("s".equals(nt.name))
722                     ret = u;
723             }
724             return ret;
725         }
726         public Context(Tree t, ReflectiveMeta rm) {
727             this.rm = rm;
728             Reducer red = (Reducer)t.head();
729             this.grammar = (MG.Grammar)red.reduce(t);
730         }
731         public Union peek(String name) { return map.get(name); }
732         public void  put(String name, Union u) { map.put(name, u); }
733         public Union get(String name) {
734             Union ret = map.get(name);
735             if (ret != null) return ret;
736             ret = new Union(name);
737             map.put(name, ret);
738             MG.NonTerminal nt = grammar.get(name);
739             if (nt==null) {
740                 System.err.println("*** warning could not find " + name);
741             } else {
742                 String old = cnt;
743                 cnt = name;
744                 nt.build(this, ret);
745                 cnt = old;
746             }
747             return ret;
748         }
749
750     }
751 }