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