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