checkpoint
[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         public Object repeatTag() {
101             return new Tree.ArrayBuildingTreeFunctor<Object>();
102         }
103         public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
104             Production p = new Production(tag, nonTerminalName, els, labels, drops);
105             for(Method m : _cl.getMethods())
106                 if (new Target(m).isCompatible(p))
107                     return new Target(m).makeSequence(p);
108             for(Class c : _inner)
109                 for(Constructor con : c.getConstructors())
110                     if (new Target(con).isCompatible(p))
111                         return new Target(con).makeSequence(p);
112             for(Class c : _inner)
113                 if (new Target(c).isCompatible(p))
114                     return new Target(c).makeSequence(p);
115             return null;
116         }
117         public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
118             Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
119             if (ret != null) return ret;
120             String message = "could not find a Java method/class/ctor matching tag \""+tag+
121                 "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
122             if (harsh) {
123                 throw new RuntimeException(message);
124             } else {
125                 System.err.println(message);
126                 return Sequence.rewritingSequence(tag, els, labels, drops);
127             }
128         }
129     }
130
131    
132     public static class Production {
133         public String tag;
134         public String nonTerminal;
135         public Object[] labels;
136         public boolean[] drops;
137         public Element[] elements;
138         public int count = 0;
139         public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
140             this.tag = tag;
141             this.elements = elements;
142             this.nonTerminal = nonTerminal;
143             this.labels = labels;
144             this.drops = drops;
145             for(int i=0; i<drops.length; i++)
146                 if (!drops[i])
147                     count++;
148         }
149     }
150
151     public static class Target {
152         public int[] buildSequence(Production p) {
153             Annotation[][] annotations = _bindable.getArgAnnotations();
154             String[]       names       = _bindable.getArgNames();
155             String name = _bindable.getSimpleName();
156             int len = annotations.length;
157             int ofs = 0;
158             bind.arg[] argtags  = new bind.arg[len];
159             for(int i=0; i<names.length; i++)
160                 for(Annotation a : annotations[i+ofs])
161                     if (a instanceof bind.arg)
162                         argtags[i+ofs] = (bind.arg)a;
163             return Target.this.buildSequence(p, names, argtags);
164         }
165         private Bindable _bindable;
166
167         public Target(Object o) { this(Bindable.create(o)); }
168         public Target(Bindable b) { this._bindable = b; }
169
170         public String getName() { return _bindable.getSimpleName(); }
171         public bind getBind() {
172             return (bind)_bindable.getAnnotation(bind.class); }
173         public bind.as getBindAs() {
174             return (bind.as)_bindable.getAnnotation(bind.as.class); }
175         //public nonterminal getNonTerminal() { return (nonterminal)_bindable.getAnnotation(bind.as.class); }
176         public String toString() { return _bindable.getSimpleName(); }
177         public boolean isRaw() { return _bindable.isAnnotationPresent(bind.raw.class); }
178
179         public boolean isCompatible(Production p) {
180             bind.as t = getBindAs();
181             if (t != null &&
182                 (t.value().equals(p.tag) ||
183                  (t.value().equals("") && getName().equals(p.tag))))
184                 return buildSequence(p)!=null;
185
186             bind b = getBind();
187             System.out.println(_bindable.getClass().getSimpleName() + ": " + _bindable.getSimpleName());
188             if (b != null && getName().equals(p.tag))
189                 return buildSequence(p)!=null;
190
191             bind.as n = getBindAs();
192             if (n != null &&
193                 (n.value().equals(p.nonTerminal) ||
194                  (n.value().equals("") && getName().equals(p.nonTerminal))))
195                 return buildSequence(p)!=null;
196
197             if (b != null && getName().equals(p.nonTerminal))
198                 return buildSequence(p)!=null;
199
200             return false;
201         }
202
203         public int[] buildSequence(Production p, String[] names, bind.arg[] argtags) {
204             int argTagged = 0;
205             for(int i=0; i<argtags.length; i++)
206                 if (argtags[i] != null)
207                     argTagged++;
208
209             // FIXME: can be smarter here
210             if (names.length==p.count) {
211                 int[] ret = new int[p.count];
212                 for(int i=0; i<p.count; i++) ret[i] = i;
213                 return ret;
214             } else if (argTagged==p.count) {
215                 int[] ret = new int[argtags.length];
216                 int j = 0;
217                 for(int i=0; i<argtags.length; i++)
218                     ret[i] = argtags[i]==null ? -1 : (j++);
219                 return ret;
220             } else {
221                 return null;
222             }
223         }
224         public Sequence makeSequence(Production p) {
225             return Sequence.rewritingSequence(new TargetReducer(buildSequence(p), _bindable, isRaw()),
226                                               p.elements, p.labels, p.drops);
227         }
228
229     }
230
231     public static class TargetReducer implements Tree.TreeFunctor<Object,Object>, ToJava {
232         private int[] map;
233         private Bindable _bindable;
234         private boolean _israw;
235
236         public void toJava(StringBuffer sb) {
237             sb.append("new MetaGrammar.TargetReducer(new int[] {");
238             for(int i=0; i<map.length; i++)
239                 sb.append((i+"")+(i<map.length-1 ? "," : ""));
240             sb.append("}, ");
241             _bindable.toJava(sb);
242             sb.append(", ");
243             sb.append(_israw ? "true" : "false");
244             sb.append(")");
245         }
246         
247         public TargetReducer(int[] map, Bindable b, boolean raw) {
248             this.map = map;
249             this._bindable = b;
250             this._israw = raw;
251         }
252         public String toString() { return "reducer-"+_bindable.toString(); }
253         public Object invoke(Iterable<Tree<Object>> t) {
254             if (_israw) return _bindable.impose(new Object[] { 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 _bindable.impose(o2);
273         }
274     }
275
276
277     public static Union cached = null;
278     public static Union make() {
279         /*
280         if (cached != null) return cached;
281         try {
282             ReflectiveMeta m = new ReflectiveMeta();
283             Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
284             MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
285             MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
286             Union meta = mgf.get("s").build(bc);
287             Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
288             return cached = make(t, "s");
289         } catch (Exception e) {
290             throw new RuntimeException(e);
291         }
292         */
293         return make(MetaGrammarTree.meta, "s");
294     }
295     public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
296     public static Union make(Tree t, String s, ReflectiveMeta rm) {
297         System.out.println("Head: " + t.head());
298         Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
299         MG.Grammar g = (MG.Grammar)red.invoke(t.children());
300         Context cx = new Context(g,rm);
301         Union u = null;
302         for(MG.NonTerminal nt : g.nonterminals) {
303             System.out.println(nt.name);
304             Union el = (Union)cx.get(nt.name);
305             StringBuffer st = new StringBuffer();
306             el.toString(st);
307             System.err.println(st);
308             if (nt.name.equals(s)) u = el;
309         }
310         return u;
311     }
312
313
314
315     public static class MG {
316         public static @bind class Grammar {
317             public NonTerminal get(String s) {
318                 for(NonTerminal nt : nonterminals)
319                     if (nt.name.equals(s))
320                         return nt;
321                 return null;
322             }
323             public @bind.arg NonTerminal[] nonterminals;
324             public String toString() {
325                 String ret = "[ ";
326                 for(NonTerminal nt : nonterminals) ret += nt + ", ";
327                 return ret + " ]";
328             }
329         }
330         public abstract static class Un extends El {
331             public Seq[][] sequences;
332             public void build(Context cx, Union u) {
333                 HashSet<Sequence> bad2 = new HashSet<Sequence>();
334                 for(int i=0; i<sequences.length; i++) {
335                     Seq[] group = sequences[i];
336                     Union u2 = new Union();
337                     if (sequences.length==1) u2 = u;
338                     for(int j=0; j<group.length; j++) {
339                         group[j].build(cx, u2, false);
340                     }
341                     if (sequences.length==1) break;
342                     Sequence seq = Sequence.singleton(u2);
343                     for(Sequence s : bad2) {
344                         s.lame = true;
345                         seq = seq.not(s);
346                     }
347                     u.add(seq);
348                     bad2.add(Sequence.singleton(u2));
349                 }
350             }
351         }
352         public static class NonTerminal extends Un {
353             public String  name = null;
354             public @bind.as("NonTerminal") NonTerminal(@bind.arg("Word") String name,
355                                          @bind.arg("RHS") Seq[][] sequences) {
356                 this.name = name;
357                 this.sequences = sequences;
358             }
359             public Element build(Context cx) { return cx.get(name); }
360         }
361
362         public static class AnonUn extends Un {
363             public @bind.as("(") AnonUn(Seq[][] sequences) {
364                 this.sequences = sequences;
365             }
366             public Element build(Context cx) {
367                 Union ret = new Union();
368                 build(cx, ret);
369                 return ret;
370             }
371         }
372
373         //public static @bind.as void range(char c) { }
374         public static class Range {
375             public @bind.as("range") Range(char only) { first = only; last = only; }
376             public @bind.as("-")     Range(char first, char last) { this.first = first; this.last = last; }
377             public char first;
378             public char last;
379         }
380         public static abstract class El {
381             public String getLabel() { return null; }
382             public String getOwnerTag() { return null; }
383             public boolean drop() { return false; }
384             public abstract Element build(Context cx);
385         }
386         public static class Drop extends El {
387             public El e;
388             public Drop(El e) { this.e = e; }
389             public String getLabel() { return null; }
390             public boolean drop() { return true; }
391             public String getOwnerTag() { return e.getOwnerTag(); }
392             public Element build(Context cx) { return e.build(cx); }
393         }
394         public static class Label extends El {
395             public String label;
396             public El e;
397             public Label(String label, El e) { this.e = e; this.label = label; }
398             public String getLabel() { return label; }
399             public String getOwnerTag() { return e.getOwnerTag(); }
400             public Element build(Context cx) { return e.build(cx); }
401         }
402         public static /*abstract*/ class Seq {
403             HashSet<Seq> and = new HashSet<Seq>();
404             HashSet<Seq> not = new HashSet<Seq>();
405             El[] elements;
406             El follow;
407             String tag = null;
408             boolean lame;
409             public Seq(El e) { this(new El[] { e }); }
410             public Seq(El[] elements) { this.elements = elements; }
411             public Seq tag(String tag) { this.tag = tag; return this; }
412             public Seq follow(El follow) { this.follow = follow; return this; }
413             public Seq dup() {
414                 Seq ret = new Seq(elements);
415                 ret.and.addAll(and);
416                 ret.not.addAll(not);
417                 ret.follow = follow;
418                 ret.tag = tag;
419                 return ret;
420             }
421             public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
422             public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
423             public Seq separate(El sep) {
424                 El[] elements = new El[this.elements.length * 2 - 1];
425                 for(int i=0; i<this.elements.length; i++) {
426                     elements[i*2]   = this.elements[i];
427                     if (i<this.elements.length-1)
428                         elements[i*2+1] = new Drop(sep);
429                 }
430                 this.elements = elements;
431                 return this;
432             }
433             public Sequence build(Context cx, Union u, boolean lame) {
434                 Sequence ret = build0(cx, lame || this.lame);
435                 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
436                 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
437                 u.add(ret);
438                 ret.lame = lame;
439                 return ret;
440             }
441             public Sequence build0(Context cx, boolean lame) {
442                 boolean unwrap = false;
443                 boolean dropAll = lame;
444                 if (tag!=null && tag.equals("[]")) unwrap  = true;
445                 if (tag!=null && "()".equals(tag)) dropAll = true;
446                 Object[] labels = new Object[elements.length];
447                 boolean[] drops = new boolean[elements.length];
448                 Element[] els = new Element[elements.length];
449                 for(int i=0; i<elements.length; i++) {
450                     labels[i] = elements[i].getLabel();
451                     drops[i]  = elements[i].drop();
452                     els[i] = elements[i].build(cx);
453                     if (elements[i].getOwnerTag() != null)
454                         tag = elements[i].getOwnerTag();
455                 }
456                 Sequence ret = null;
457                 if (dropAll)     ret = Sequence.drop(els, false);
458                 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
459                 else if (tag!=null) {
460                     ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
461                 } else {
462                     ret = cx.rm.tryResolveTag(tag, cx.cnt, els, labels, drops);
463                     if (ret == null) {
464                         int idx = -1;
465                         for(int i=0; i<els.length; i++)
466                             if (!drops[i])
467                                 if (idx==-1) idx = i;
468                                 else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
469                         if (idx != -1) ret = Sequence.singleton(els, idx);
470                         else           ret = Sequence.drop(els, false);
471                     }
472                 }
473                 if (this.follow != null)
474                     ret.follow = infer(this.follow.build(cx));
475                 ret.lame = this.lame;
476                 return ret;
477             }
478         }
479         public static @bind.as("&")   Seq  and(Seq s,         El[] elements) { return s.and(seq(elements)); }
480         public static @bind.as("&~")  Seq  andnot(Seq s,      El[] elements) { return s.andnot(seq(elements)); }
481         public static @bind.as("->")  Seq  arrow(Seq s, El e)                { return s.follow(e); }
482         public static @bind.as("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
483         public static @bind.as("/")   Seq  slash(Seq s, El e)                { return s.separate(e); }
484
485         public static @bind.as("ps")  Seq  seq(El[] elements)                { return new Seq(elements); }
486         public static @bind.as        Seq  psx(Seq s)                        { return s; }
487         public static @bind.as(":")   El   colon(String s, El e)             { return new Label(s, e); }
488         public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
489         public static @bind.as("()")  El   epsilon()                         { return new Constant(Union.epsilon); }
490
491         public static @bind.as("nonTerminal") class NonTerminalReference extends El {
492             public @bind.arg String nonTerminal;
493             public Element build(Context cx) {
494                 return cx.get(nonTerminal);
495             }
496         }
497
498         public static class StringLiteral        extends Constant {
499             public @bind.as("literal") StringLiteral(String string) { super(CharRange.string(string)); }
500             public boolean drop() { return true; }
501         }
502
503         public static                     class CharClass            extends El {
504             Range[] ranges;
505             public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
506             public Element build(Context cx) {
507                 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
508                 for(Range r : ranges)
509                         set.add(r.first, r.last);
510                 return CharRange.set(set);
511             }
512         }
513
514         public static @bind.as("{")           class XTree                 extends El {
515             public @bind.arg Seq body;
516             public Element build(Context cx) {
517                 throw new Error();
518             }
519         }
520
521         public static class Rep extends El {
522             public El e, sep;
523             public boolean zero, many, max;
524             public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
525                 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
526             public Element build(Context cx) {
527                 return (!max)
528                     ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
529                     : sep==null
530                     ? Sequence.repeatMaximal(infer(e.build(cx)), zero, many,                                   cx.rm.repeatTag())
531                     : Sequence.repeatMaximal(e.build(cx),                    zero, many, infer(sep.build(cx)), cx.rm.repeatTag());
532             }
533         }
534         public static class Constant extends El {
535             Element constant;
536             public Constant(Element constant) { this.constant = constant; }
537             public Element build(Context cx) { return constant; }
538         }
539         public abstract static class PostProcess extends El {
540             El e;
541             public PostProcess(El e) { this.e = e; }
542             public Element build(Context cx) { return postProcess(e.build(cx)); }
543             public abstract Element postProcess(Element e);
544         }
545
546         // FIXME: it would be nice if we could hoist this into "Rep"
547         public static @bind.as("++")  El plusmax(final El e)                     { return new Rep(e, null, false, true, true); }
548         public static @bind.as("+")   El plus(final El e)                        { return new Rep(e, null, false, true, false); }
549         public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep,  false, true, true); }
550         public static @bind.as("+/")  El plusfollow(final El e, final El sep)    { return new Rep(e, sep,  false, true, false); }
551         public static @bind.as("**")  El starmax(final El e)                     { return new Rep(e, null, true,  true, true); }
552         public static @bind.as("*")   El star(final El e)                        { return new Rep(e, null, true,  true, false); }
553         public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep,  true,  true, true); }
554         public static @bind.as("*/")  El starfollow(final El e, final El sep)    { return new Rep(e, sep,  true,  true, false); }
555         public static @bind.as("?")   El question(final El e)                    { return new Rep(e, null, true,  true, false); }
556
557         public static @bind.as("!")   El bang(final El e)                        { return new Drop(e); }
558
559         public static @bind.as("^")   El caret(final String s) {
560             return new Drop(new Constant(CharRange.string(s)) {
561                     public String getOwnerTag() { return s; }
562                 });
563         }
564
565         public static @bind.as("~")   El tilde(final El e) {
566             return new PostProcess(e) {
567                     public Element postProcess(Element e) {
568                         return infer((Topology<Character>)Atom.toAtom(e).complement()); 
569                     } }; }
570
571         public static @bind.as("^^")  void doublecaret(final El e)                 { throw new Error("not implemented"); }
572
573         //public static @bind.as("(")   El subexpression(Seq[][] rhs)                { return new NonTerminal(rhs); }
574
575         public static @bind.as("Word")    String word(String s) { return s; }
576         public static @bind.as("Quoted")  String quoted(String s) { return s; }
577         public static @bind.as("escaped") String c(char c) { return c+""; }
578         public static @bind.as("\"\"")    String emptystring() { return ""; }
579         public static @bind.as("\n")      String retur() { return "\n"; }
580         public static @bind.as("\r")      String lf() { return "\r"; }
581
582     }
583     public static class Context {
584         HashMap<String,Union> map = new HashMap<String,Union>();
585         private MG.Grammar grammar;
586         public String cnt = null;
587         private ReflectiveMeta rm;
588         public Context(MG.Grammar g, ReflectiveMeta rm) {
589             this.grammar = g;
590             this.rm = rm;
591         }
592         public Union build() {
593             Union ret = null;
594             for(MG.NonTerminal nt : grammar.nonterminals) {
595                 Union u = get(nt.name);
596                 if ("s".equals(nt.name))
597                     ret = u;
598             }
599             return ret;
600         }
601         public Context(Tree t, ReflectiveMeta rm) {
602             this.rm = rm;
603             Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
604             this.grammar = (MG.Grammar)red.invoke(t.children());
605         }
606         public Union peek(String name) { return map.get(name); }
607         public void  put(String name, Union u) { map.put(name, u); }
608         public Union get(String name) {
609             Union ret = map.get(name);
610             if (ret != null) return ret;
611             ret = new Union(name);
612             map.put(name, ret);
613             MG.NonTerminal nt = grammar.get(name);
614             if (nt==null) {
615                 System.err.println("*** warning could not find " + name);
616             } else {
617                 String old = cnt;
618                 cnt = name;
619                 nt.build(this, ret);
620                 cnt = old;
621             }
622             return ret;
623         }
624
625     }
626     /*private*/ static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
627     /*private*/ static Atom infer(Topology<Character> t) { return new CharRange(new CharTopology(t)); }
628 }