dc35dfc3180c5ecf84e1ffaee147a4652d8784a9
[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) {
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);
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) { return cx.get(name); }
73         public void build(Context cx, Union u) {
74             if (!rep) { super.build(cx, u); 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);
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) {
114             Union ret = new Union();
115             build(cx, ret);
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);
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) { return e.build(cx); }
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) { return e.build(cx); }
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) {
190             Sequence ret = build0(cx, lame || this.lame);
191             for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
192             for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
193             u.add(ret);
194             ret.lame = lame;
195             return ret;
196         }
197         public Sequence build0(Context cx, boolean lame) {
198             boolean dropAll = lame;
199             if (tag!=null && "()".equals(tag)) dropAll = true;
200             Object[] labels = new Object[elements.length];
201             boolean[] drops = new boolean[elements.length];
202             Element[] els = new Element[elements.length];
203             for(int i=0; i<elements.length; i++) {
204                 labels[i] = elements[i].getLabel();
205                 drops[i]  = elements[i].drop();
206                 els[i] = elements[i].build(cx);
207                 if (elements[i].getOwnerTag() != null)
208                     tag = elements[i].getOwnerTag();
209             }
210             Sequence ret = null;
211             if (dropAll)     ret = Sequence.drop(els, false);
212             else {
213                 ret = cx.rm.tryResolveTag(tag, cx.cnt, els, labels, drops);
214                 if (ret == null) {
215                     int idx = -1;
216                     for(int i=0; i<els.length; i++)
217                         if (!drops[i])
218                             if (idx==-1) idx = i;
219                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
220                     if (idx != -1) ret = Sequence.singleton(els, idx);
221                     else           ret = Sequence.drop(els, false);
222                 }
223             }
224             if (this.follow != null)
225                 ret.follow = infer(this.follow.build(cx));
226             ret.lame = this.lame;
227             return ret;
228         }
229     }
230     public static @bind.as("&")   Seq  and2(Seq s,        Seq a) { return s.and(a); }
231     public static @bind.as("&~")  Seq  andnot2(Seq s,     Seq a) { return s.andnot(a); }
232     public static @bind.as("->")  Seq  arrow(Seq s, ElementNode e)                { return s.follow(e); }
233     public static @bind.as("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
234     public static @bind.as("/")   Seq  slash(Seq s, ElementNode e)                { return s.separate(e); }
235
236     public static Seq  seq(ElementNode[] elements)               { return new Seq(elements); }
237     public static @bind.as("Elements")  Seq  seq2(ElementNode[] elements)               { return new Seq(elements); }
238     public static @bind.as        Seq  psx(Seq s)                        { return s; }
239     public static @bind.as(":")   ElementNode   colon(String s, ElementNode e)             { return new Label(s, e); }
240     public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
241     public static @bind.as("()")  ElementNode   epsilon()                         { return new Constant(Union.epsilon); }
242
243     public static @bind.as("NonTerminalReference") class NonTerminalReferenceNode extends ElementNode {
244         public @bind.arg String nonTerminal;
245         public Element build(Context cx) { return cx.get(nonTerminal); }
246     }
247
248     public static class Literal extends Constant {
249         public @bind Literal(@bind.arg String string) { super(CharRange.string(string)); }
250         public boolean drop() { return true; }
251     }
252
253     public static                     class CharClass            extends ElementNode {
254         Range[] ranges;
255         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
256         public Element build(Context cx) {
257             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
258             for(Range r : ranges)
259                 set.add(r.first, r.last);
260             return CharRange.set(set);
261         }
262     }
263
264     public static @bind.as("{")           class XTree                 extends ElementNode {
265         public @bind.arg Seq body;
266         public Element build(Context cx) {
267             Union u = new Union();
268             Sequence s = body.build(cx, u, false);
269             Union u2 = new Union();
270             u2.add(Sequence.singleton(new Element[] {
271                 CharRange.leftBrace,
272                 cx.get("ws"),
273                 u,
274                 cx.get("ws"),
275                 CharRange.rightBrace
276             }, 2));
277             return u2;
278         }
279     }
280
281     public static class Rep extends ElementNode {
282         public ElementNode e, sep;
283         public boolean zero, many, max;
284         public Rep(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
285             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
286         public Element build(Context cx) {
287             return (!max)
288                 ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
289                 : sep==null
290                 ? Sequence.repeatMaximal(infer(e.build(cx)), zero, many,                                   cx.rm.repeatTag())
291                 : Sequence.repeatMaximal(e.build(cx),                    zero, many, infer(sep.build(cx)), cx.rm.repeatTag());
292         }
293     }
294     public static class Constant extends ElementNode {
295         Element constant;
296         public Constant(Element constant) { this.constant = constant; }
297         public Element build(Context cx) { return constant; }
298     }
299     public abstract static class PostProcess extends ElementNode {
300         ElementNode e;
301         public PostProcess(ElementNode e) { this.e = e; }
302         public Element build(Context cx) { return postProcess(e.build(cx)); }
303         public abstract Element postProcess(Element e);
304     }
305
306     // FIXME: it would be nice if we could hoist this into "Rep"
307     public static @bind.as("++")  ElementNode plusmax(final ElementNode e)                     { return new Rep(e, null, false, true, true); }
308     public static @bind.as("+")   ElementNode plus(final ElementNode e)                        { return new Rep(e, null, false, true, false); }
309     public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep) { return new Rep(e, sep,  false, true, true); }
310     public static @bind.as("+/")  ElementNode plusfollow(final ElementNode e, final ElementNode sep)    { return new Rep(e, sep,  false, true, false); }
311     public static @bind.as("**")  ElementNode starmax(final ElementNode e)                     { return new Rep(e, null, true,  true, true); }
312     public static @bind.as("*")   ElementNode star(final ElementNode e)                        { return new Rep(e, null, true,  true, false); }
313     public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep) { return new Rep(e, sep,  true,  true, true); }
314     public static @bind.as("*/")  ElementNode starfollow(final ElementNode e, final ElementNode sep)    { return new Rep(e, sep,  true,  true, false); }
315     public static @bind.as("?")   ElementNode question(final ElementNode e)                    { return new Rep(e, null, true,  true, false); }
316
317     public static @bind.as("!")   ElementNode bang(final ElementNode e)                        { return new Drop(e); }
318
319     public static @bind.as("^")   ElementNode caret(final String s) {
320         return new Drop(new Constant(CharRange.string(s)) {
321                 public String getOwnerTag() { return s; }
322             });
323     }
324
325     public static @bind.as("~")   ElementNode tilde(final ElementNode e) {
326         return new PostProcess(e) {
327                 public Element postProcess(Element e) {
328                     return infer((Topology<Character>)Atom.toAtom(e).complement()); 
329                 } }; }
330
331     public static @bind.as("Word")        String word(String s) { return s; }
332     public static @bind.as("Quoted")      String quoted(String s) { return s; }
333     public static @bind.as("escaped")     String c(char c) { return c+""; }
334     public static @bind.as("EmptyString") String emptystring() { return ""; }
335     public static @bind.as("\n")          String retur() { return "\n"; }
336     public static @bind.as("\r")          String lf() { return "\r"; }
337
338     static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
339     static Atom infer(Topology<Character> t) { return new CharRange(new CharTopology(t)); }
340
341     public static class Context {
342         public HashMap<String,Union> map = new HashMap<String,Union>();
343         public GrammarNode grammar;
344         public String cnt = null;
345         public GrammarBindingResolver rm;
346         public Context(GrammarNode g, GrammarBindingResolver rm) {
347             this.grammar = g;
348             this.rm = rm;
349         }
350         public Union build() {
351             Union ret = null;
352             for(NonTerminalNode nt : grammar.values()) {
353                 Union u = get(nt.name);
354                 if ("s".equals(nt.name))
355                     ret = u;
356             }
357             return ret;
358         }
359         public Context(Tree t, GrammarBindingResolver rm) {
360             this.rm = rm;
361             Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
362             this.grammar = (GrammarNode)red.invoke(t.children());
363         }
364         public Union peek(String name) { return map.get(name); }
365         public void  put(String name, Union u) { map.put(name, u); }
366         public Union get(String name) {
367             Union ret = map.get(name);
368             if (ret != null) return ret;
369             ret = new Union(name);
370             map.put(name, ret);
371             NonTerminalNode nt = grammar.get(name);
372             if (nt==null) {
373                 System.err.println("*** warning could not find " + name);
374             } else {
375                 String old = cnt;
376                 cnt = name;
377                 nt.build(this, ret);
378                 cnt = old;
379             }
380             return ret;
381         }
382
383     }
384
385 }