checkpoint
[sbp.git] / src / edu / berkeley / sbp / meta / MetaGrammarBindings.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 /** The java classes typically used to represent a parsed grammar AST; each inner class is a type of AST node. */
13 public class MetaGrammarBindings {
14
15     /** A grammar (a set of nonterminals) */
16     public static class GrammarNode extends HashMap<String,NonTerminalNode> {
17         public @bind.as("Grammar") GrammarNode(NonTerminalNode[] nonterminals) {
18             for(NonTerminalNode nt : nonterminals) {
19                 if (this.get(nt.name)!=null)
20                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
21                 this.put(nt.name, nt);
22             }
23         }
24         public String toString() {
25             String ret = "[ ";
26             for(NonTerminalNode nt : values()) ret += nt + ", ";
27             return ret + " ]";
28         }
29         public Union build(String s, GrammarBindingResolver rm) {
30             Context cx = new Context(this,rm);
31             Union u = null;
32             for(MetaGrammarBindings.NonTerminalNode nt : values()) {
33                 Union el = (Union)cx.get(nt.name);
34                 StringBuffer st = new StringBuffer();
35                 el.toString(st);
36                 if (nt.name.equals(s)) u = el;
37             }
38             return u;
39         }
40     }
41
42     public abstract static class UnionNode extends ElementNode {
43         public Seq[][] sequences;
44         public void build(Context cx, Union u, NonTerminalNode cnt) {
45             HashSet<Sequence> bad2 = new HashSet<Sequence>();
46             for(int i=0; i<sequences.length; i++) {
47                 Seq[] group = sequences[i];
48                 Union u2 = new Union();
49                 if (sequences.length==1) u2 = u;
50                 for(int j=0; j<group.length; j++) {
51                     group[j].build(cx, u2, false, cnt);
52                 }
53                 if (sequences.length==1) break;
54                 Sequence seq = Sequence.singleton(u2);
55                 for(Sequence s : bad2) {
56                     s.lame = true;
57                     seq = seq.not(s);
58                 }
59                 u.add(seq);
60                 bad2.add(Sequence.singleton(u2));
61             }
62         }
63     }
64
65     public static class NonTerminalNode extends UnionNode {
66         public boolean rep;
67         public String  name = null;
68         public String sep = null;
69         public @bind.as("NonTerminal") NonTerminalNode(@bind.arg String name, @bind.arg Seq[][] sequences) { this(name, sequences, false); }
70         public NonTerminalNode(String name, Seq[][] sequences, boolean rep) { this(name, sequences, rep, null); }
71         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep) {
72             this.name = name;
73             this.sequences = sequences;
74             this.rep = rep;
75             this.sep = sep;
76         }
77         public Element build(Context cx, NonTerminalNode cnt) { return cx.get(name); }
78         public void build(Context cx, Union u, NonTerminalNode cnt) {
79             if (!rep) { super.build(cx, u, this); return; }
80             HashSet<Sequence> bad2 = new HashSet<Sequence>();
81
82             Union urep = new Union();
83             urep.add(Sequence.empty);
84             urep.add(Sequence.singleton(new Element[] { cx.get(sep), u }, 1));
85
86             for(int i=0; i<sequences.length; i++) {
87                 Seq[] group = sequences[i];
88                 Union u2 = new Union();
89                 if (sequences.length==1) u2 = u;
90                 for(int j=0; j<group.length; j++) {
91                     Union u3 = new Union();
92                     group[j].build(cx, u3, false, this);
93                     Sequence s = Sequence.unwrap(new Element[] { u3, urep },
94                                                  cx.rm.repeatTag(),
95                                                  new boolean[] { false, false });
96                     u2.add(s);
97                 }
98                 if (sequences.length==1) break;
99                 Sequence seq = Sequence.singleton(u2);
100                 for(Sequence s : bad2) {
101                     s.lame = true;
102                     seq = seq.not(s);
103                 }
104                 u.add(seq);
105                 bad2.add(Sequence.singleton(u2));
106             }
107         }
108     }
109     public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg Seq[][] sequences) { return new NonTerminalNode(name, sequences, true); }
110     public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg String sep, @bind.arg Seq[][] sequences) {
111         return new NonTerminalNode(name, sequences, true, sep);
112     }
113
114     public static class AnonUnionNode extends UnionNode {
115         public @bind.as("(") AnonUnionNode(Seq[][] sequences) {
116             this.sequences = sequences;
117         }
118         public Element build(Context cx, NonTerminalNode cnt) {
119             Union ret = new Union();
120             build(cx, ret, cnt);
121             return ret;
122         }
123     }
124
125     public static class Range {
126         public @bind Range(char only) { first = only; last = only; }
127         public @bind Range(char first, char last) { this.first = first; this.last = last; }
128         public char first;
129         public char last;
130     }
131
132     public static abstract class ElementNode {
133         public String getLabel() { return null; }
134         public String getOwnerTag() { return null; }
135         public boolean drop() { return false; }
136         public abstract Element build(Context cx, NonTerminalNode cnt);
137     }
138
139     public static class Drop extends ElementNode {
140         public ElementNode e;
141         public Drop(ElementNode e) { this.e = e; }
142         public String getLabel() { return null; }
143         public boolean drop() { return true; }
144         public String getOwnerTag() { return e.getOwnerTag(); }
145         public Element build(Context cx, NonTerminalNode cnt) { return e.build(cx, cnt); }
146     }
147
148     public static class Label extends ElementNode {
149         public String label;
150         public ElementNode e;
151         public Label(String label, ElementNode e) { this.e = e; this.label = label; }
152         public String getLabel() { return label; }
153         public String getOwnerTag() { return e.getOwnerTag(); }
154         public Element build(Context cx, NonTerminalNode cnt) { return e.build(cx, cnt); }
155     }
156
157     public static /*abstract*/ class Seq {
158         HashSet<Seq> and = new HashSet<Seq>();
159         HashSet<Seq> not = new HashSet<Seq>();
160         ElementNode[] elements;
161         ElementNode follow;
162         String tag = null;
163         boolean lame;
164         public void append(ElementNode e) {
165             ElementNode[] elements = new ElementNode[this.elements.length+1];
166             System.arraycopy(this.elements, 0, elements, 0, this.elements.length);
167             this.elements = elements;
168             elements[elements.length-1] = e;
169         }
170         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
171         public Seq(ElementNode[] elements) { this.elements = elements; }
172         public Seq tag(String tag) { this.tag = tag; return this; }
173         public Seq follow(ElementNode follow) { this.follow = follow; return this; }
174         public Seq dup() {
175             Seq ret = new Seq(elements);
176             ret.and.addAll(and);
177             ret.not.addAll(not);
178             ret.follow = follow;
179             ret.tag = tag;
180             return ret;
181         }
182         public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
183         public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
184         public Seq separate(ElementNode sep) {
185             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
186             for(int i=0; i<this.elements.length; i++) {
187                 elements[i*2]   = this.elements[i];
188                 if (i<this.elements.length-1)
189                     elements[i*2+1] = new Drop(sep);
190             }
191             this.elements = elements;
192             return this;
193         }
194         public Sequence build(Context cx, Union u, boolean lame, NonTerminalNode cnt) {
195             Sequence ret = build0(cx, lame || this.lame, cnt);
196             for(Seq s : and) { Sequence dork = s.build(cx, u, true, cnt); ret = ret.and(dork); }
197             for(Seq s : not) { Sequence dork = s.build(cx, u, true, cnt); ret = ret.not(dork); }
198             u.add(ret);
199             ret.lame = lame;
200             return ret;
201         }
202         public Sequence build0(Context cx, boolean lame, NonTerminalNode cnt) {
203             boolean dropAll = lame;
204             if (tag!=null && "()".equals(tag)) dropAll = true;
205             boolean[] drops = new boolean[elements.length];
206             Element[] els = new Element[elements.length];
207             for(int i=0; i<elements.length; i++) {
208                 drops[i]  = elements[i].drop();
209                 els[i] = elements[i].build(cx, cnt);
210                 if (elements[i].getOwnerTag() != null)
211                     tag = elements[i].getOwnerTag();
212             }
213             Sequence ret = null;
214             if (dropAll)     ret = Sequence.drop(els, false);
215             else {
216                 ret = cx.rm.tryResolveTag(tag, cnt==null?null:cnt.name, els, drops);
217                 if (ret == null) {
218                     int idx = -1;
219                     for(int i=0; i<els.length; i++)
220                         if (!drops[i])
221                             if (idx==-1) idx = i;
222                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
223                     if (idx != -1) ret = Sequence.singleton(els, idx);
224                     else           ret = Sequence.drop(els, false);
225                 }
226             }
227             if (this.follow != null)
228                 ret.follow = infer(this.follow.build(cx, null));
229             ret.lame = this.lame;
230             return ret;
231         }
232     }
233     public static @bind.as("&")   Seq  and2(Seq s,        Seq a) { return s.and(a); }
234     public static @bind.as("&~")  Seq  andnot2(Seq s,     Seq a) { return s.andnot(a); }
235     public static @bind.as("->")  Seq  arrow(Seq s, ElementNode e)                { return s.follow(e); }
236     public static @bind.as("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
237     public static @bind.as("/")   Seq  slash(Seq s, ElementNode e)                { return s.separate(e); }
238
239     public static Seq  seq(ElementNode[] elements)               { return new Seq(elements); }
240     public static @bind.as("Elements")  Seq  seq2(ElementNode[] elements)               { return new Seq(elements); }
241     public static @bind.as        Seq  psx(Seq s)                        { return s; }
242     public static @bind.as(":")   ElementNode   colon(String s, ElementNode e)             { return new Label(s, e); }
243     public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
244     public static @bind.as("()")  ElementNode   epsilon()                         { return new Constant(Union.epsilon); }
245
246     public static @bind.as("NonTerminalReference") class NonTerminalReferenceNode extends ElementNode {
247         public @bind.arg String nonTerminal;
248         public Element build(Context cx, NonTerminalNode cnt) {
249             Element ret = cx.get(nonTerminal);
250             if (ret == null) throw new RuntimeException("unkown nonterminal \""+nonTerminal+"\"");
251             return ret;
252         }
253     }
254
255     public static class Literal extends Constant {
256         public @bind Literal(@bind.arg String string) { super(CharRange.string(string)); }
257         public boolean drop() { return true; }
258     }
259
260     public static                     class CharClass            extends ElementNode {
261         Range[] ranges;
262         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
263         public Element build(Context cx, NonTerminalNode cnt) {
264             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
265             for(Range r : ranges)
266                 set.add(r.first, r.last);
267             return CharRange.set(set);
268         }
269     }
270
271     public static @bind.as("{")           class XTree                 extends ElementNode {
272         public @bind.arg Seq body;
273         public Element build(Context cx, NonTerminalNode cnt) {
274             Union u = new Union();
275             Sequence s = body.build(cx, u, false, null);
276             Union u2 = new Union();
277             u2.add(Sequence.singleton(new Element[] {
278                 CharRange.leftBrace,
279                 cx.get("ws"),
280                 u,
281                 cx.get("ws"),
282                 CharRange.rightBrace
283             }, 2));
284             return u2;
285         }
286     }
287
288     public static class Rep extends ElementNode {
289         public ElementNode e, sep;
290         public boolean zero, many, max;
291         public Rep(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
292             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
293         public Element build(Context cx, NonTerminalNode cnt) {
294             return (!max)
295                 ? Sequence.repeat(e.build(cx, null),        zero, many, sep==null ? null : sep.build(cx, null), cx.rm.repeatTag())
296                 : sep==null
297                 ? Sequence.repeatMaximal(infer(e.build(cx, null)), zero, many,                                   cx.rm.repeatTag())
298                 : Sequence.repeatMaximal(e.build(cx, null),                    zero, many, infer(sep.build(cx, null)), cx.rm.repeatTag());
299         }
300     }
301     public static class Constant extends ElementNode {
302         Element constant;
303         public Constant(Element constant) { this.constant = constant; }
304         public Element build(Context cx, NonTerminalNode cnt) { return constant; }
305     }
306     public abstract static class PostProcess extends ElementNode {
307         ElementNode e;
308         public PostProcess(ElementNode e) { this.e = e; }
309         public Element build(Context cx, NonTerminalNode cnt) { return postProcess(e.build(cx, cnt)); }
310         public abstract Element postProcess(Element e);
311     }
312
313     // FIXME: it would be nice if we could hoist this into "Rep"
314     public static @bind.as("++")  ElementNode plusmax(final ElementNode e)                     { return new Rep(e, null, false, true, true); }
315     public static @bind.as("+")   ElementNode plus(final ElementNode e)                        { return new Rep(e, null, false, true, false); }
316     public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep) { return new Rep(e, sep,  false, true, true); }
317     public static @bind.as("+/")  ElementNode plusfollow(final ElementNode e, final ElementNode sep)    { return new Rep(e, sep,  false, true, false); }
318     public static @bind.as("**")  ElementNode starmax(final ElementNode e)                     { return new Rep(e, null, true,  true, true); }
319     public static @bind.as("*")   ElementNode star(final ElementNode e)                        { return new Rep(e, null, true,  true, false); }
320     public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep) { return new Rep(e, sep,  true,  true, true); }
321     public static @bind.as("*/")  ElementNode starfollow(final ElementNode e, final ElementNode sep)    { return new Rep(e, sep,  true,  true, false); }
322     public static @bind.as("?")   ElementNode question(final ElementNode e)                    { return new Rep(e, null, true,  true, false); }
323
324     public static @bind.as("!")   ElementNode bang(final ElementNode e)                        { return new Drop(e); }
325
326     public static @bind.as("^")   ElementNode caret(final String s) {
327         return new Drop(new Constant(CharRange.string(s)) {
328                 public String getOwnerTag() { return s; }
329             });
330     }
331
332     public static @bind.as("~")   ElementNode tilde(final ElementNode e) {
333         return new PostProcess(e) {
334                 public Element postProcess(Element e) {
335                     return infer((Topology<Character>)Atom.toAtom(e).complement().minus(CharRange.braces));
336                 } }; }
337
338     public static @bind.as("Word")        String word(String s) { return s; }
339     public static @bind.as("Quoted")      String quoted(String s) { return s; }
340     public static @bind.as("escaped")     String c(char c) { return c+""; }
341     public static @bind.as("EmptyString") String emptystring() { return ""; }
342     public static @bind.as("\n")          String retur() { return "\n"; }
343     public static @bind.as("\r")          String lf() { return "\r"; }
344
345     static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
346     static Atom infer(Topology<Character> t) { return new CharRange(new CharTopology(t)); }
347
348     public static class Context {
349         public HashMap<String,Union> map = new HashMap<String,Union>();
350         public GrammarNode grammar;
351         public String cnt = null;
352         public GrammarBindingResolver rm;
353         public Context(GrammarNode g, GrammarBindingResolver rm) {
354             this.grammar = g;
355             this.rm = rm;
356         }
357         public Union build() {
358             Union ret = null;
359             for(NonTerminalNode nt : grammar.values()) {
360                 Union u = get(nt.name);
361                 if ("s".equals(nt.name))
362                     ret = u;
363             }
364             return ret;
365         }
366         public Context(Tree t, GrammarBindingResolver rm) {
367             this.rm = rm;
368             Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
369             this.grammar = (GrammarNode)red.invoke(t.children());
370         }
371         public Union peek(String name) { return map.get(name); }
372         public void  put(String name, Union u) { map.put(name, u); }
373         public Union get(String name) {
374             Union ret = map.get(name);
375             if (ret != null) return ret;
376             ret = new Union(name);
377             map.put(name, ret);
378             NonTerminalNode nt = grammar.get(name);
379             if (nt==null) {
380                 System.err.println("*** warning could not find " + name);
381             } else {
382                 String old = cnt;
383                 cnt = name;
384                 nt.build(this, ret, nt);
385                 cnt = old;
386             }
387             return ret;
388         }
389
390     }
391
392 }