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 */
13 public class MetaGrammarBindings {
14
15     /** A grammar (a set of nonterminals) */
16     public static class Grammar extends HashMap<String,NonTerminal> {
17         public @bind Grammar(NonTerminal[] nonterminals) {
18             for(NonTerminal nt : nonterminals) this.put(nt.name, nt); }
19         public String toString() {
20             String ret = "[ ";
21             for(NonTerminal nt : values()) ret += nt + ", ";
22             return ret + " ]";
23         }
24     }
25
26     public abstract static class Un extends El {
27         public Seq[][] sequences;
28         public void build(MetaGrammar.Context cx, Union u) {
29             HashSet<Sequence> bad2 = new HashSet<Sequence>();
30             for(int i=0; i<sequences.length; i++) {
31                 Seq[] group = sequences[i];
32                 Union u2 = new Union();
33                 if (sequences.length==1) u2 = u;
34                 for(int j=0; j<group.length; j++) {
35                     group[j].build(cx, u2, false);
36                 }
37                 if (sequences.length==1) break;
38                 Sequence seq = Sequence.singleton(u2);
39                 for(Sequence s : bad2) {
40                     s.lame = true;
41                     seq = seq.not(s);
42                 }
43                 u.add(seq);
44                 bad2.add(Sequence.singleton(u2));
45             }
46         }
47     }
48
49     public static class NonTerminal extends Un {
50         public boolean rep;
51         public String  name = null;
52         public String sep = null;
53         public @bind NonTerminal(@bind.arg String name, @bind.arg Seq[][] sequences) { this(name, sequences, false); }
54         public NonTerminal(String name, Seq[][] sequences, boolean rep) { this(name, sequences, rep, null); }
55         public NonTerminal(String name, Seq[][] sequences, boolean rep, String sep) {
56             this.name = name;
57             this.sequences = sequences;
58             this.rep = rep;
59             this.sep = sep;
60         }
61         public Element build(MetaGrammar.Context cx) { return cx.get(name); }
62     }
63     public static @bind.as("=") NonTerminal go(@bind.arg String name, @bind.arg Seq[][] sequences) { return new NonTerminal(name, sequences, true); }
64     public static @bind.as("=") NonTerminal go(@bind.arg String name, @bind.arg String sep, @bind.arg Seq[][] sequences) {
65         return new NonTerminal(name, sequences, true, sep);
66     }
67
68     public static class AnonUn extends Un {
69         public @bind.as("(") AnonUn(Seq[][] sequences) {
70             this.sequences = sequences;
71         }
72         public Element build(MetaGrammar.Context cx) {
73             Union ret = new Union();
74             build(cx, ret);
75             return ret;
76         }
77     }
78
79     public static class Range {
80         public @bind Range(char only) { first = only; last = only; }
81         public @bind Range(char first, char last) { this.first = first; this.last = last; }
82         public char first;
83         public char last;
84     }
85     public static abstract class El {
86         public String getLabel() { return null; }
87         public String getOwnerTag() { return null; }
88         public boolean drop() { return false; }
89         public abstract Element build(MetaGrammar.Context cx);
90     }
91     public static class Drop extends El {
92         public El e;
93         public Drop(El e) { this.e = e; }
94         public String getLabel() { return null; }
95         public boolean drop() { return true; }
96         public String getOwnerTag() { return e.getOwnerTag(); }
97         public Element build(MetaGrammar.Context cx) { return e.build(cx); }
98     }
99     public static class Label extends El {
100         public String label;
101         public El e;
102         public Label(String label, El e) { this.e = e; this.label = label; }
103         public String getLabel() { return label; }
104         public String getOwnerTag() { return e.getOwnerTag(); }
105         public Element build(MetaGrammar.Context cx) { return e.build(cx); }
106     }
107     public static /*abstract*/ class Seq {
108         HashSet<Seq> and = new HashSet<Seq>();
109         HashSet<Seq> not = new HashSet<Seq>();
110         El[] elements;
111         El follow;
112         String tag = null;
113         boolean lame;
114         public Seq(El e) { this(new El[] { e }); }
115         public Seq(El[] elements) { this.elements = elements; }
116         public Seq tag(String tag) { this.tag = tag; return this; }
117         public Seq follow(El follow) { this.follow = follow; return this; }
118         public Seq dup() {
119             Seq ret = new Seq(elements);
120             ret.and.addAll(and);
121             ret.not.addAll(not);
122             ret.follow = follow;
123             ret.tag = tag;
124             return ret;
125         }
126         public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
127         public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
128         public Seq separate(El sep) {
129             El[] elements = new El[this.elements.length * 2 - 1];
130             for(int i=0; i<this.elements.length; i++) {
131                 elements[i*2]   = this.elements[i];
132                 if (i<this.elements.length-1)
133                     elements[i*2+1] = new Drop(sep);
134             }
135             this.elements = elements;
136             return this;
137         }
138         public Sequence build(MetaGrammar.Context cx, Union u, boolean lame) {
139             Sequence ret = build0(cx, lame || this.lame);
140             for(Seq s : and) { Sequence dork = s.build(cx, u, true); ret = ret.and(dork); }
141             for(Seq s : not) { Sequence dork = s.build(cx, u, true); ret = ret.not(dork); }
142             u.add(ret);
143             ret.lame = lame;
144             return ret;
145         }
146         public Sequence build0(MetaGrammar.Context cx, boolean lame) {
147             boolean unwrap = false;
148             boolean dropAll = lame;
149             if (tag!=null && tag.equals("[]")) unwrap  = true;
150             if (tag!=null && "()".equals(tag)) dropAll = true;
151             Object[] labels = new Object[elements.length];
152             boolean[] drops = new boolean[elements.length];
153             Element[] els = new Element[elements.length];
154             for(int i=0; i<elements.length; i++) {
155                 labels[i] = elements[i].getLabel();
156                 drops[i]  = elements[i].drop();
157                 els[i] = elements[i].build(cx);
158                 if (elements[i].getOwnerTag() != null)
159                     tag = elements[i].getOwnerTag();
160             }
161             Sequence ret = null;
162             if (dropAll)     ret = Sequence.drop(els, false);
163             else if (unwrap) ret = Sequence.unwrap(els, cx.rm.repeatTag(), drops);
164             else if (tag!=null) {
165                 ret = cx.rm.resolveTag(tag, cx.cnt, els, labels, drops);
166             } else {
167                 ret = cx.rm.tryResolveTag(tag, cx.cnt, els, labels, drops);
168                 if (ret == null) {
169                     int idx = -1;
170                     for(int i=0; i<els.length; i++)
171                         if (!drops[i])
172                             if (idx==-1) idx = i;
173                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
174                     if (idx != -1) ret = Sequence.singleton(els, idx);
175                     else           ret = Sequence.drop(els, false);
176                 }
177             }
178             if (this.follow != null)
179                 ret.follow = infer(this.follow.build(cx));
180             ret.lame = this.lame;
181             return ret;
182         }
183     }
184     public static @bind.as("&")   Seq  and2(Seq s,        Seq a) { return s.and(a); }
185     public static @bind.as("&~")  Seq  andnot2(Seq s,     Seq a) { return s.andnot(a); }
186     public static @bind.as("->")  Seq  arrow(Seq s, El e)                { return s.follow(e); }
187     public static @bind.as("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
188     public static @bind.as("/")   Seq  slash(Seq s, El e)                { return s.separate(e); }
189
190     public static Seq  seq(El[] elements)               { return new Seq(elements); }
191     public static @bind.as("Elements")  Seq  seq2(El[] elements)               { return new Seq(elements); }
192     public static @bind.as        Seq  psx(Seq s)                        { return s; }
193     public static @bind.as(":")   El   colon(String s, El e)             { return new Label(s, e); }
194     public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
195     public static @bind.as("()")  El   epsilon()                         { return new Constant(Union.epsilon); }
196
197     public static @bind class NonTerminalReference extends El {
198         public @bind.arg String nonTerminal;
199         public Element build(MetaGrammar.Context cx) { return cx.get(nonTerminal); }
200     }
201
202     public static class Literal extends Constant {
203         public @bind Literal(@bind.arg String string) { super(CharRange.string(string)); }
204         public boolean drop() { return true; }
205     }
206
207     public static                     class CharClass            extends El {
208         Range[] ranges;
209         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
210         public Element build(MetaGrammar.Context cx) {
211             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
212             for(Range r : ranges)
213                 set.add(r.first, r.last);
214             return CharRange.set(set);
215         }
216     }
217
218     public static @bind.as("{")           class XTree                 extends El {
219         public @bind.arg Seq body;
220         public Element build(MetaGrammar.Context cx) {
221             Union u = new Union();
222             Sequence s = body.build(cx, u, false);
223             Union u2 = new Union();
224             u2.add(Sequence.singleton(new Element[] {
225                 CharRange.leftBrace,
226                 cx.get("ws"),
227                 u,
228                 cx.get("ws"),
229                 CharRange.rightBrace
230             }, 2));
231             return u2;
232         }
233     }
234
235     public static class Rep extends El {
236         public El e, sep;
237         public boolean zero, many, max;
238         public Rep(El e, El sep, boolean zero, boolean many, boolean max) {
239             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
240         public Element build(MetaGrammar.Context cx) {
241             return (!max)
242                 ? Sequence.repeat(e.build(cx),        zero, many, sep==null ? null : sep.build(cx), cx.rm.repeatTag())
243                 : sep==null
244                 ? Sequence.repeatMaximal(infer(e.build(cx)), zero, many,                                   cx.rm.repeatTag())
245                 : Sequence.repeatMaximal(e.build(cx),                    zero, many, infer(sep.build(cx)), cx.rm.repeatTag());
246         }
247     }
248     public static class Constant extends El {
249         Element constant;
250         public Constant(Element constant) { this.constant = constant; }
251         public Element build(MetaGrammar.Context cx) { return constant; }
252     }
253     public abstract static class PostProcess extends El {
254         El e;
255         public PostProcess(El e) { this.e = e; }
256         public Element build(MetaGrammar.Context cx) { return postProcess(e.build(cx)); }
257         public abstract Element postProcess(Element e);
258     }
259
260     // FIXME: it would be nice if we could hoist this into "Rep"
261     public static @bind.as("++")  El plusmax(final El e)                     { return new Rep(e, null, false, true, true); }
262     public static @bind.as("+")   El plus(final El e)                        { return new Rep(e, null, false, true, false); }
263     public static @bind.as("++/") El plusmaxfollow(final El e, final El sep) { return new Rep(e, sep,  false, true, true); }
264     public static @bind.as("+/")  El plusfollow(final El e, final El sep)    { return new Rep(e, sep,  false, true, false); }
265     public static @bind.as("**")  El starmax(final El e)                     { return new Rep(e, null, true,  true, true); }
266     public static @bind.as("*")   El star(final El e)                        { return new Rep(e, null, true,  true, false); }
267     public static @bind.as("**/") El starmaxfollow(final El e, final El sep) { return new Rep(e, sep,  true,  true, true); }
268     public static @bind.as("*/")  El starfollow(final El e, final El sep)    { return new Rep(e, sep,  true,  true, false); }
269     public static @bind.as("?")   El question(final El e)                    { return new Rep(e, null, true,  true, false); }
270
271     public static @bind.as("!")   El bang(final El e)                        { return new Drop(e); }
272
273     public static @bind.as("^")   El caret(final String s) {
274         return new Drop(new Constant(CharRange.string(s)) {
275                 public String getOwnerTag() { return s; }
276             });
277     }
278
279     public static @bind.as("~")   El tilde(final El e) {
280         return new PostProcess(e) {
281                 public Element postProcess(Element e) {
282                     return infer((Topology<Character>)Atom.toAtom(e).complement()); 
283                 } }; }
284
285     public static @bind.as("^^")  void doublecaret(final El e)                 { throw new Error("not implemented"); }
286
287     //public static @bind.as("(")   El subexpression(Seq[][] rhs)                { return new NonTerminal(rhs); }
288
289     public static @bind.as("Word")        String word(String s) { return s; }
290     public static @bind.as("Quoted")      String quoted(String s) { return s; }
291     public static @bind.as("escaped")     String c(char c) { return c+""; }
292     public static @bind.as("EmptyString") String emptystring() { return ""; }
293     public static @bind.as("\n")          String retur() { return "\n"; }
294     public static @bind.as("\r")          String lf() { return "\r"; }
295
296     static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
297     static Atom infer(Topology<Character> t) { return new CharRange(new CharTopology(t)); }
298 }