checkpoint
[sbp.git] / src / edu / berkeley / sbp / misc / Demo.java
1 package edu.berkeley.sbp.misc;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import java.util.*;
6 import java.lang.annotation.*;
7 import java.lang.reflect.*;
8 import java.io.*;
9
10 public class Demo {
11     
12     public static boolean harsh = false;
13
14     public static void main(String[] s) throws Exception {
15
16         ReflectiveMeta m = new ReflectiveMeta();
17         Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
18         MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
19         MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
20
21         Union meta = mgf.get("s").build(bc);
22         Tree t = new CharParser(meta).parse(new FileInputStream(s[1])).expand1();
23
24         Union u = Demo.make(t, "s");
25
26         System.err.println();
27         System.err.println("== parsing with parsed grammar =================================================================================");
28         t = new CharParser((Union)u).parse(new FileInputStream(s[1])).expand1();
29         System.out.println(t.toPrettyString());
30
31         System.err.println("== parsing with parsed-parsed grammar ==========================================================================");
32         t = new CharParser(new Context(t, m).build()).parse(new FileInputStream(s[1])).expand1();
33         System.out.println(t.toPrettyString());
34     }
35
36     public static class ReflectiveMetaPlain extends ReflectiveMeta {
37         public Object repeatTag() { return null; }
38         public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
39             return null; }
40         public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
41             return Sequence.rewritingSequence(tag, els, labels, drops);
42         }
43     }
44
45     public static class ReflectiveMeta extends MetaGrammar.Meta {
46         private final Class _cl;
47         private final Class[] _inner;
48         public ReflectiveMeta() {
49             this(MG.class,
50                  new Class[] {
51                      MG.Grammar.class,
52                      MG.NonTerminal.class,
53                      MG.AnonUn.class,
54                      MG.Range.class,
55                      MG.El.class,
56                      MG.Seq.class,
57                      MG.NonTerminalReference.class,
58                      MG.StringLiteral.class,
59                      MG.XTree.class,
60                      MG.CharClass.class
61                  });
62         }
63         public ReflectiveMeta(Class c, Class[] inner) {
64             this._cl = c;
65             this._inner = inner;
66         }
67         private boolean match(Method m, String s) { return match(m.getAnnotation(tag.class), null, s); }
68         private boolean match(tag t, Class c, String s) {
69             if (t==null) return false;
70             if (t.value().equals(s)) return true;
71             if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
72             return false;
73         }
74         private boolean match(nonterminal t, Class c, String s) {
75             if (t==null) return false;
76             if (t.value().equals(s)) return true;
77             if (c != null && t.equals("") && c.getSimpleName().equals(s)) return true;
78             return false;
79         }
80         private boolean match(Class c, String s, String nonTerminalName) {
81             if (match((tag)c.getAnnotation(tag.class), c, s)) return true;
82             if (match((nonterminal)c.getAnnotation(nonterminal.class), c, nonTerminalName)) return true;
83             return false;
84         }
85         public boolean match(Constructor con, String s, String nonTerminalName) {
86             Class c = con.getDeclaringClass();
87             if (match((tag)con.getAnnotation(tag.class), null, s)) return true;
88             if (match((nonterminal)con.getAnnotation(nonterminal.class), c, s)) return true;
89             return false;
90         }
91         public Object repeatTag() {
92             return new Functor<Iterable<Tree>,Object>() {
93                     public String toString() { return ""; }
94                     public Object invoke(Iterable<Tree> t) {
95                         ArrayList ret = new ArrayList();
96                         for(Tree tc : t) {
97                             if (tc.head() != null && tc.head() instanceof Functor)
98                                 ret.add(((Functor<Iterable<Tree>,Object>)tc.head()).invoke(tc.children()));
99                             else if (tc.numChildren() == 0)
100                                 ret.add(tc.head());
101                             else {
102                                 System.err.println("FIXME: don't know what to do about " + tc);
103                                 ret.add(null);
104                             }
105                         }
106                         return ret.toArray(new Object[0]);
107                     }
108                 };
109         }
110         public Sequence tryResolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
111             Production p = new Production(tag, nonTerminalName, els, labels, drops);
112             for(Method m : _cl.getMethods())
113                 if (new TargetMethod(m).isCompatible(p))
114                     return new TargetMethod(m).makeSequence(p);
115             for(Class c : _inner)
116                 for(Constructor con : c.getConstructors())
117                     if (new TargetConstructor(con).isCompatible(p))
118                         return new TargetConstructor(con).makeSequence(p);
119             for(Class c : _inner)
120                 if (new TargetClass(c).isCompatible(p))
121                     return new TargetClass(c).makeSequence(p);
122             return null;
123         }
124         public Sequence resolveTag(String tag, String nonTerminalName, Element[] els, Object[] labels, boolean[] drops) {
125             Sequence ret = tryResolveTag(tag, nonTerminalName, els, labels, drops);
126             if (ret != null) return ret;
127             String message = "could not find a Java method/class/ctor matching tag \""+tag+
128                 "\", nonterminal \""+nonTerminalName+"\" with " + els.length + " arguments";
129             if (harsh) {
130                 throw new RuntimeException(message);
131             } else {
132                 System.err.println(message);
133                 return Sequence.rewritingSequence(tag, els, labels, drops);
134             }
135         }
136     }
137
138     
139     /**
140      *  Constructors, classes, and methods with this attribute will
141      *  match every production of the nonterminal called "value()"
142      *  that is arg-compatible.  If value() is undefined, then the
143      *  class/constructor/method name is used.
144      */ 
145     @Retention(RetentionPolicy.RUNTIME) public static @interface nonterminal { String value() default ""; }
146
147     @Retention(RetentionPolicy.RUNTIME) public static @interface raw { }
148
149     /**
150      *  Constructors, classes, and methods with this attribute will
151      *  match every tree tagged with "value()" that is arg-compatible.
152      *  If value() is undefined, then the class/constructor/method
153      *  name is used.
154      */ 
155     @Retention(RetentionPolicy.RUNTIME) public static @interface tag         { String value() default ""; }
156
157     /**
158      *  If any parameter to a method or field in a class has a named
159      *  arg-tag, that parameter/field matches the child of the tree
160      *  which either has that label or else is a reference to a
161      *  nonterminal with the corresponding name.
162      *  
163      *  The remaining non-named arg-tags match the remaining children
164      *  of the tree in sequential order.
165      *
166      *  If any arg-tagged parameters/fields remain, the match fails.
167      *  If there were no arg-tagged parameters-fields, it is as if all
168      *  of them were non-named and arg-tagged.
169      *
170      *  A method/constructor is arg-compatible if all of its arguments
171      *  are arg-compatible.
172      *
173      *  A class is arg-compatible if all of its fields are
174      *  arg-compatible, or if one of its constructors is arg-compatible.
175      *
176      */
177     @Retention(RetentionPolicy.RUNTIME) public static @interface arg         { String value() default ""; }
178
179     public static class Production {
180         public String tag;
181         public String nonTerminal;
182         public Object[] labels;
183         public boolean[] drops;
184         public Element[] elements;
185         public int count = 0;
186         public Production(String tag, String nonTerminal, Element[] elements, Object[] labels, boolean[] drops) {
187             this.tag = tag;
188             this.elements = elements;
189             this.nonTerminal = nonTerminal;
190             this.labels = labels;
191             this.drops = drops;
192             for(int i=0; i<drops.length; i++)
193                 if (!drops[i])
194                     count++;
195         }
196     }
197
198     public static abstract class Target {
199         public abstract String getName();
200         public abstract tag getTag();
201         public abstract nonterminal getNonTerminal();
202         public abstract int[] buildSequence(Production p);
203         public boolean isCompatible(Production p) {
204             tag t = getTag();
205             if (t != null &&
206                 (t.value().equals(p.tag) ||
207                  (t.value().equals("") && getName().equals(p.tag))))
208                 return buildSequence(p)!=null;
209
210             nonterminal n = getNonTerminal();
211             if (n != null &&
212                 (n.value().equals(p.nonTerminal) ||
213                  (n.value().equals("") && getName().equals(p.nonTerminal))))
214                 return buildSequence(p)!=null;
215
216             return false;
217         }
218         public int[] buildSequence(Production p, String[] names, arg[] argtags) {
219             int argTagged = 0;
220             for(int i=0; i<argtags.length; i++)
221                 if (argtags[i] != null)
222                     argTagged++;
223
224             // FIXME: can be smarter here
225             if (names.length==p.count) {
226                 int[] ret = new int[p.count];
227                 for(int i=0; i<p.count; i++) ret[i] = i;
228                 return ret;
229             } else if (argTagged==p.count) {
230                 int[] ret = new int[argtags.length];
231                 int j = 0;
232                 for(int i=0; i<argtags.length; i++)
233                     ret[i] = argtags[i]==null ? -1 : (j++);
234                 return ret;
235             } else {
236                 return null;
237             }
238         }
239         public Sequence makeSequence(Production p) {
240             return Sequence.rewritingSequence(new TargetReducer(p, buildSequence(p), "reducer-"+this), p.elements, p.labels, p.drops);
241         }
242         public abstract Object plant(Object[] fields, int[] map);
243         public boolean isRaw() { return false; }
244         public Object invokeRaw(Iterable<Tree> t) { return null; }
245         public class TargetReducer implements Functor<Iterable<Tree>,Object> {
246             private Production p;
247             private int[] map;
248             private String name;
249             public TargetReducer(Production p, int[] map, String name) {
250                 this.p = p;
251                 this.map = map;
252                 this.name = name;
253             }
254             public String toString() { return name; }
255             public Object invoke(Iterable<Tree> t) {
256                 if (isRaw()) return invokeRaw(t);
257                 ArrayList ret = new ArrayList();
258                 for(Tree tc : t) {
259                     if (tc.head() != null && tc.head() instanceof Functor)
260                         ret.add(((Functor<Iterable<Tree>,Object>)tc.head()).invoke(tc.children()));
261                     else if (tc.numChildren() == 0)
262                         ret.add(tc.head());
263                     else {
264                         System.err.println("FIXME: don't know what to do about " + tc);
265                         ret.add(null);
266                     }
267                 }
268                 System.err.println("input tree: " + t);
269                 return plant(ret.toArray(new Object[0]), map);
270             }
271         }
272     }
273
274     public static class TargetClass extends Target {
275         public final Class _class;
276         public TargetClass(Class _class) { this._class = _class; }
277         public String getName() { return _class.getSimpleName(); }
278         public tag getTag() { return (tag)_class.getAnnotation(tag.class); }
279         public nonterminal getNonTerminal() { return (nonterminal)_class.getAnnotation(nonterminal.class); }
280         public String toString() { return _class.getSimpleName(); }
281         public int[] buildSequence(Production p) {
282             Field[]  f       = _class.getDeclaredFields();
283             String[] names   = new String[f.length];
284             arg[]    argtags = new arg[f.length];
285             for(int i=0; i<f.length; i++) {
286                 names[i]   = f[i].getName();
287                 argtags[i] = f[i].getAnnotation(arg.class);
288             }
289             int[] ret = buildSequence(p, names, argtags);
290             if (ret!=null) return ret;
291             for(Constructor c : _class.getConstructors())
292                 if (new TargetConstructor(c).buildSequence(p)!=null)
293                     return new TargetConstructor(c).buildSequence(p);
294             return null;
295         }
296         public Object plant(Object[] fields, int[] map) {
297             try {
298                 Object ret = _class.newInstance();
299                 Field[] f = _class.getFields();
300                 int j = 0;
301                 for(int i=0; i<f.length; i++)
302                     if (map[i] != -1) {
303                         Object tgt = Reflection.lub(fields[map[i]]);
304                         if (f[i].getType() == String.class) tgt = stringify(tgt);
305                         // FUGLY
306                         tgt = coerce(tgt, f[i].getType());
307                         System.err.println("setting a " + f[i].getType().getName() + " to " + Reflection.show(tgt));
308                         f[i].set(ret, tgt);
309                     }
310                 return ret;
311             } catch (Exception e) {
312                 e.printStackTrace();
313                 throw new RuntimeException(e);
314             }
315         }
316     }
317
318     public static String stringify(Object o) {
319         if (o==null) return "";
320         if (!(o instanceof Object[])) return o.toString();
321         Object[] arr = (Object[])o;
322         StringBuffer ret = new StringBuffer();
323         for(int i=0; i<arr.length; i++)
324             ret.append(arr[i]);
325         return ret.toString();
326     }
327
328     public static class TargetConstructor extends Target {
329         public final Constructor _ctor;
330         public TargetConstructor(Constructor _ctor) { this._ctor = _ctor; }
331         public String getName() { return _ctor.getName(); }
332         public tag getTag() { return (tag)_ctor.getAnnotation(tag.class); }
333         public nonterminal getNonTerminal() { return (nonterminal)_ctor.getAnnotation(nonterminal.class); }
334         public String toString() { return _ctor.getName(); }
335         public int[] buildSequence(Production p) {
336             Annotation[][] annotations = _ctor.getParameterAnnotations();
337             int len = annotations.length;
338             int ofs = 0;
339             String name = _ctor.getDeclaringClass().getName();
340             /*
341             if (name.indexOf('$') > name.lastIndexOf('.')) {
342                 len--;
343                 ofs++;
344             }
345             */
346             String[] names   = new String[len];
347             arg[]    argtags = new arg[len];
348             for(int i=0; i<names.length; i++)
349                 for(Annotation a : annotations[i+ofs])
350                     if (a instanceof arg)
351                         argtags[i+ofs] = (arg)a;
352             return buildSequence(p, names, argtags);
353         }
354         public Object plant(Object[] fields, int[] map) {
355             try {
356                 Class[] argTypes = _ctor.getParameterTypes();
357                 Object[] args = new Object[argTypes.length];
358                 int j = 0;
359                 for(int i=0; i<args.length; i++)
360                     if (map[i] != -1) {
361                         Object tgt = Reflection.lub(fields[map[i]]);
362                         if (argTypes[i] == String.class) tgt = stringify(tgt);
363                         // FUGLY
364                         tgt = coerce(tgt, argTypes[i]);
365                         System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
366                         args[i] = tgt;
367                     }
368                 return _ctor.newInstance(args);
369             } catch (Exception e) {
370                 throw new RuntimeException(e);
371             }
372         }
373     }
374     public static class TargetMethod extends Target {
375         public final Method _method;
376         public TargetMethod(Method _method) { this._method = _method; }
377         public String getName() { return _method.getName(); }
378         public String toString() { return _method.getName(); }
379         public tag getTag() { return (tag)_method.getAnnotation(tag.class); }
380         public nonterminal getNonTerminal() { return (nonterminal)_method.getAnnotation(nonterminal.class); }
381         public int[] buildSequence(Production p) {
382             Annotation[][] annotations = _method.getParameterAnnotations();
383             String[] names   = new String[annotations.length];
384             arg[]    argtags = new arg[annotations.length];
385             for(int i=0; i<names.length; i++)
386                 for(Annotation a : annotations[i])
387                     if (a instanceof arg)
388                         argtags[i] = (arg)a;
389             int[] ret = buildSequence(p, names, argtags);
390             return ret;
391         }
392         public boolean isRaw() { return _method.isAnnotationPresent(raw.class); }
393         public Object invokeRaw(Iterable<Tree> t) {
394             try {
395                 return _method.invoke(null, new Object[] { t });
396             } catch (Exception e) {
397                 throw new RuntimeException(e);
398             }
399         }
400         public Object plant(Object[] fields, int[] map) {
401             try {
402                 Class[] argTypes = _method.getParameterTypes();
403                 Object[] args = new Object[argTypes.length];
404                 int j = 0;
405                 for(int i=0; i<args.length; i++)
406                     if (map[i] != -1) {
407                         Object tgt = Reflection.lub(fields[map[i]]);
408                         if (argTypes[i] == String.class) tgt = stringify(tgt);
409                         // FUGLY
410                         tgt = coerce(tgt, argTypes[i]);
411                         System.err.println("setting a " + argTypes[i].getName() + " to " + Reflection.show(tgt));
412                         args[i] = tgt;
413                     }
414                 System.err.println("invoking " + _method + " with " + Reflection.show(args));
415                 return _method.invoke(null, args);
416             } catch (Exception e) {
417                 throw new RuntimeException(e);
418             }
419         }
420     }
421
422     public static Object coerce(Object o, Class c) {
423         if (o==null) return null;
424         if (c.isInstance(o)) return o;
425         if (c == char.class) {
426             return o.toString().charAt(0);
427         }
428
429         if (o.getClass().isArray() &&
430             o.getClass().getComponentType().isArray() &&
431             o.getClass().getComponentType().getComponentType() == String.class &&
432             c.isArray() &&
433             c.getComponentType() == String.class) {
434             String[] ret = new String[((Object[])o).length];
435             for(int i=0; i<ret.length; i++) {
436                 StringBuffer sb = new StringBuffer();
437                 for(Object ob : (Object[])(((Object[])o)[i]))
438                     sb.append(ob);
439                 ret[i] = sb.toString();
440             }
441             return ret;
442         }
443
444         if (c.isArray() && (c.getComponentType().isInstance(o))) {
445             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
446             ret[0] = o;
447             return ret;
448         }
449
450         if (o.getClass().isArray() && c.isArray()) {
451             boolean ok = true;
452             for(int i=0; i<((Object[])o).length; i++) {
453                 Object ob = (((Object[])o)[i]);
454                 if (ob != null) {
455                     System.err.println("no hit with " + c.getComponentType().getName() + " on " + Reflection.show(((Object[])o)[i]));
456                     ok = false;
457                 }
458             }
459             if (ok) {
460                 System.err.println("hit with " + c.getComponentType().getName());
461                 return Array.newInstance(c.getComponentType(), ((Object[])o).length);
462             }
463         }
464         return o;
465     }
466
467     public static Union cached = null;
468     public static Union make() {
469         if (cached != null) return cached;
470         try {
471             ReflectiveMeta m = new ReflectiveMeta();
472             Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream("tests/meta.g")).expand1();
473             MetaGrammar.Meta.MetaGrammarFile mgf = m.new MetaGrammarFile(res);
474             MetaGrammar.BuildContext bc = new MetaGrammar.BuildContext(mgf);
475             Union meta = mgf.get("s").build(bc);
476             Tree t = new CharParser(meta).parse(new FileInputStream("tests/meta.g")).expand1();
477             return cached = make(t, "s");
478         } catch (Exception e) {
479             throw new RuntimeException(e);
480         }
481     }
482     public static Union make(Tree t, String s) { return make(t, s, new ReflectiveMeta()); }
483     public static Union make(Tree t, String s, ReflectiveMeta rm) {
484         Functor<Iterable<Tree>,Object> red = (Functor<Iterable<Tree>,Object>)t.head();
485         MG.Grammar g = (MG.Grammar)red.invoke(t.children());
486         Context cx = new Context(g,rm);
487         Union u = null;
488         for(MG.NonTerminal nt : g.nonterminals) {
489             System.out.println(nt.name);
490             Union el = (Union)cx.get(nt.name);
491             StringBuffer st = new StringBuffer();
492             el.toString(st);
493             System.err.println(st);
494             if (nt.name.equals(s)) u = el;
495         }
496         return u;
497     }
498
499     public static class MG {
500         public static @tag("grammar") class Grammar {
501             public NonTerminal get(String s) {
502                 for(NonTerminal nt : nonterminals)
503                     if (nt.name.equals(s))
504                         return nt;
505                 return null;
506             }
507             public @arg("NonTerminal") NonTerminal[] nonterminals;
508             public String toString() {
509                 String ret = "[ ";
510                 for(NonTerminal nt : nonterminals) ret += nt + ", ";
511                 return ret + " ]";
512             }
513         }
514         public abstract static class Un extends El {
515             public Seq[][] sequences;
516             public void build(Context cx, Union u) {
517                 HashSet<Sequence> bad2 = new HashSet<Sequence>();
518                 for(int i=0; i<sequences.length; i++) {
519                     Seq[] group = sequences[i];
520                     Union u2 = new Union();
521                     if (sequences.length==1) u2 = u;
522                     for(int j=0; j<group.length; j++) {
523                         group[j].build(cx, u2, false);
524                     }
525                     if (sequences.length==1) break;
526                     Sequence seq = Sequence.singleton(u2);
527                     for(Sequence s : bad2) {
528                         s.lame = true;
529                         seq = seq.not(s);
530                     }
531                     u.add(seq);
532                     bad2.add(Sequence.singleton(u2));
533                 }
534             }
535         }
536         public static class NonTerminal extends Un {
537             public String  name = null;
538             public @nonterminal("NonTerminal") NonTerminal(@arg("Word") String name,
539                                                            @arg("RHS") Seq[][] sequences) {
540                 this.name = name;
541                 this.sequences = sequences;
542             }
543             public Element build(Context cx) { return cx.get(name); }
544         }
545
546         public static class AnonUn extends Un {
547             public @tag("(") AnonUn(Seq[][] sequences) {
548                 this.sequences = sequences;
549             }
550             public Element build(Context cx) {
551                 Union ret = new Union();
552                 build(cx, ret);
553                 return ret;
554             }
555         }
556
557         //public static @tag void range(char c) { }
558         public static class Range {
559             public @tag("range") Range(char only) { first = only; last = only; }
560             public @tag("-")     Range(char first, char last) { this.first = first; this.last = last; }
561             public char first;
562             public char last;
563         }
564         public static abstract class El {
565             public String getLabel() { return null; }
566             public String getOwnerTag() { return null; }
567             public boolean drop() { return false; }
568             public abstract Element build(Context cx);
569         }
570         public static class Drop extends El {
571             public El e;
572             public Drop(El e) { this.e = e; }
573             public String getLabel() { return null; }
574             public boolean drop() { return true; }
575             public String getOwnerTag() { return e.getOwnerTag(); }
576             public Element build(Context cx) { return e.build(cx); }
577         }
578         public static class Label extends El {
579             public String label;
580             public El e;
581             public Label(String label, El e) { this.e = e; this.label = label; }
582             public String getLabel() { return label; }
583             public String getOwnerTag() { return e.getOwnerTag(); }
584             public Element build(Context cx) { return e.build(cx); }
585         }
586         public static /*abstract*/ class Seq {
587             HashSet<Seq> and = new HashSet<Seq>();
588             HashSet<Seq> not = new HashSet<Seq>();
589             El[] elements;
590             El follow;
591             String tag = null;
592             boolean lame;
593             public Seq(El e) { this(new El[] { e }); }
594             public Seq(El[] elements) { this.elements = elements; }
595             public Seq tag(String tag) { this.tag = tag; return this; }
596             public Seq follow(El follow) { this.follow = follow; return this; }
597             public Seq dup() {
598                 Seq ret = new Seq(elements);
599                 ret.and.addAll(and);
600                 ret.not.addAll(not);
601                 ret.follow = follow;
602                 ret.tag = tag;
603                 return ret;
604             }
605             public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
606             public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
607             public Seq separate(El sep) {
608                 El[] elements = new El[this.elements.length * 2 - 1];
609                 for(int i=0; i<this.elements.length; i++) {
610                     elements[i*2]   = this.elements[i];
611                     if (i<this.elements.length-1)
612                         elements[i*2+1] = new Drop(sep);
613                 }
614                 this.elements = elements;
615                 return this;
616             }
617             public Sequence build(Context cx, Union u, boolean lame) {
618                 Sequence ret = build0(cx, lame || this.lame);
619                 for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
620                 for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
621                 u.add(ret);
622                 ret.lame = lame;
623                 return ret;
624             }
625             public Sequence build0(Context cx, boolean lame) {
626                 boolean unwrap = false;
627                 boolean dropAll = lame;
628                 if (tag!=null && tag.equals("[]")) unwrap  = true;
629                 if (tag!=null && "()".equals(tag)) dropAll = true;
630                 Object[] labels = new Object[elements.length];
631                 boolean[] drops = new boolean[elements.length];
632                 Element[] els = new Element[elements.length];
633                 for(int i=0; i<elements.length; i++) {
634                     labels[i] = elements[i].getLabel();
635                     drops[i]  = elements[i].drop();
636                     els[i] = elements[i].build(cx);
637                     if (elements[i].getOwnerTag() != null)
638                         tag = elements[i].getOwnerTag();
639                 }
640                 Sequence ret = null;
641                 if (dropAll)     ret = Sequence.drop(els, false);
642                 else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
643                 else if (tag!=null) {
644                     ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
645                 } else {
646                     int idx = -1;
647                     for(int i=0; i<els.length; i++)
648                         if (!drops[i])
649                             if (idx==-1) idx = i;
650                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
651                     if (idx != -1) ret = Sequence.singleton(els, idx);
652                     else           ret = Sequence.drop(els, false);
653                 }
654                 if (this.follow != null)
655                     ret.follow = MetaGrammar.infer(this.follow.build(cx));
656                 ret.lame = this.lame;
657                 return ret;
658             }
659         }
660         public static @tag("&")   Seq  and(Seq s,         El[] elements) { return s.and(seq(elements)); }
661         public static @tag("&~")  Seq  andnot(Seq s,      El[] elements) { return s.andnot(seq(elements)); }
662         public static @tag("->")  Seq  arrow(Seq s, El e)                { return s.follow(e); }
663         public static @tag("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
664         public static @tag("/")   Seq  slash(Seq s, El e)                { return s.separate(e); }
665
666         public static @tag("ps")  Seq  seq(El[] elements)                { return new Seq(elements); }
667         public static @tag        Seq  psx(Seq s)                        { return s; }
668         public static @tag(":")   El   colon(String s, El e)             { return new Label(s, e); }
669         public static @tag(")")   void close(String foo)                 { throw new Error("not supported"); }
670         public static @tag("()")  El   epsilon()                         { return new Constant(Union.epsilon); }
671
672         public static @tag("nonTerminal") class NonTerminalReference extends El {
673             public @arg String nonTerminal;
674             public Element build(Context cx) {
675                 return cx.get(nonTerminal);
676             }
677         }
678
679         public static class StringLiteral        extends Constant {
680             public @tag("literal") StringLiteral(String string) { super(CharRange.string(string)); }
681             public boolean drop() { return true; }
682         }
683
684         public static                     class CharClass            extends El {
685             Range[] ranges;
686             public @tag("[") CharClass(Range[] ranges) { this.ranges = ranges; }
687             public Element build(Context cx) {
688                 edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
689                 for(Range r : ranges)
690                         set.add(r.first, r.last);
691                 return CharRange.set(set);
692             }
693         }
694
695         public static @tag("{")           class XTree                 extends El {
696             public @arg Seq body;
697             public Element build(Context cx) {
698                 throw new Error();
699             }
700         }
701
702         public static class Rep extends El {
703             public El e, sep;
704             public boolean zero, many, max;
705             public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
706                 this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
707             public Element build(Context cx) {
708                 return (!max)
709                     ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
710                     : sep==null
711                     ? Sequence.repeatMaximal(MetaGrammar.infer(e.build(cx)), zero, many,                                   cx.rm.repeatTag())
712                     : Sequence.repeatMaximal(e.build(cx),                    zero, many, MetaGrammar.infer(sep.build(cx)), cx.rm.repeatTag());
713             }
714         }
715         public static class Constant extends El {
716             Element constant;
717             public Constant(Element constant) { this.constant = constant; }
718             public Element build(Context cx) { return constant; }
719         }
720         public abstract static class PostProcess extends El {
721             El e;
722             public PostProcess(El e) { this.e = e; }
723             public Element build(Context cx) { return postProcess(e.build(cx)); }
724             public abstract Element postProcess(Element e);
725         }
726
727         // FIXME: it would be nice if we could hoist this into "Rep"
728         public static @tag("++")  El plusmax(final El e)                     { return new Rep(e, null, false, true, true); }
729         public static @tag("+")   El plus(final El e)                        { return new Rep(e, null, false, true, false); }
730         public static @tag("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep,  false, true, true); }
731         public static @tag("+/")  El plusfollow(final El e, final El sep)    { return new Rep(e, sep,  false, true, false); }
732         public static @tag("**")  El starmax(final El e)                     { return new Rep(e, null, true,  true, true); }
733         public static @tag("*")   El star(final El e)                        { return new Rep(e, null, true,  true, false); }
734         public static @tag("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep,  true,  true, true); }
735         public static @tag("*/")  El starfollow(final El e, final El sep)    { return new Rep(e, sep,  true,  true, false); }
736         public static @tag("?")   El question(final El e)                    { return new Rep(e, null, true,  true, false); }
737
738         public static @tag("!")   El bang(final El e)                        { return new Drop(e); }
739
740         public static @tag("^")   El caret(final String s) {
741             return new Drop(new Constant(CharRange.string(s)) {
742                     public String getOwnerTag() { return s; }
743                 });
744         }
745
746         public static @tag("~")   El tilde(final El e) {
747             return new PostProcess(e) {
748                     public Element postProcess(Element e) {
749                         return MetaGrammar.infer((Topology<Character>)Atom.toAtom(e).complement()); 
750                     } }; }
751
752         public static @tag("^^")  void doublecaret(final El e)                 { throw new Error("not implemented"); }
753
754         //public static @tag("(")   El subexpression(Seq[][] rhs)                { return new NonTerminal(rhs); }
755
756         public static @nonterminal("Word")    String word(String s) { return s; }
757         public static @nonterminal("Quoted")  String quoted(String s) { return s; }
758         public static @nonterminal("escaped") String c(char c) { return c+""; }
759         public static @tag("\"\"")            String emptystring() { return ""; }
760         public static @tag("\n")              String retur() { return "\n"; }
761         public static @tag("\r")              String lf() { return "\r"; }
762
763     }
764     public static class Context {
765         HashMap<String,Union> map = new HashMap<String,Union>();
766         private MG.Grammar grammar;
767         public String cnt = null;
768         private ReflectiveMeta rm;
769         public Context(MG.Grammar g, ReflectiveMeta rm) {
770             this.grammar = g;
771             this.rm = rm;
772         }
773         public Union build() {
774             Union ret = null;
775             for(MG.NonTerminal nt : grammar.nonterminals) {
776                 Union u = get(nt.name);
777                 if ("s".equals(nt.name))
778                     ret = u;
779             }
780             return ret;
781         }
782         public Context(Tree t, ReflectiveMeta rm) {
783             this.rm = rm;
784             Functor<Iterable<Tree>,Object> red = (Functor<Iterable<Tree>,Object>)t.head();
785             this.grammar = (MG.Grammar)red.invoke(t.children());
786         }
787         public Union peek(String name) { return map.get(name); }
788         public void  put(String name, Union u) { map.put(name, u); }
789         public Union get(String name) {
790             Union ret = map.get(name);
791             if (ret != null) return ret;
792             ret = new Union(name);
793             map.put(name, ret);
794             MG.NonTerminal nt = grammar.get(name);
795             if (nt==null) {
796                 System.err.println("*** warning could not find " + name);
797             } else {
798                 String old = cnt;
799                 cnt = name;
800                 nt.build(this, ret);
801                 cnt = old;
802             }
803             return ret;
804         }
805
806     }
807 }