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