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