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