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