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