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