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