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