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