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