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