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