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