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