ecde37241de91b71b6b0bd80c64bc3fba955a1eb
[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, 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         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
158     public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg Seq[][] sequences) {
159         return new NonTerminalNode(name, sequences, true); }
160     public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg String sep, @bind.arg Seq[][] sequences) {
161         return new NonTerminalNode(name, sequences, true, sep); }
162
163     public static class AnonUnionNode extends UnionNode {
164         public @bind.as("(") AnonUnionNode(Seq[][] sequences) {
165             this.sequences = sequences;
166         }
167         public Element build(Context cx, NonTerminalNode cnt) {
168             Union ret = new Union();
169             build(cx, ret, cnt);
170             return ret;
171         }
172     }
173
174     public static class Range {
175         public @bind Range(char only) { first = only; last = only; }
176         public @bind Range(char first, char last) { this.first = first; this.last = last; }
177         public char first;
178         public char last;
179     }
180
181     public static /*abstract*/ class Seq {
182         HashSet<Seq> and = new HashSet<Seq>();
183         HashSet<Seq> not = new HashSet<Seq>();
184         ElementNode[] elements;
185         ElementNode follow;
186         String tag = null;
187         boolean lame;
188         public void append(ElementNode e) {
189             ElementNode[] elements = new ElementNode[this.elements.length+1];
190             System.arraycopy(this.elements, 0, elements, 0, this.elements.length);
191             this.elements = elements;
192             elements[elements.length-1] = e;
193         }
194         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
195         public Seq(ElementNode[] elements) { this.elements = elements; }
196         public Seq tag(String tag) { this.tag = prefix+tag; return this; }
197         public Seq follow(ElementNode follow) { this.follow = follow; return this; }
198         public Seq dup() {
199             Seq ret = new Seq(elements);
200             ret.and.addAll(and);
201             ret.not.addAll(not);
202             ret.follow = follow;
203             ret.tag = prefix+tag;
204             return ret;
205         }
206         public Seq and(Seq s) { and.add(s); s.lame = true; return this; }
207         public Seq andnot(Seq s) { not.add(s); s.lame = true; return this; }
208         public Seq separate(ElementNode sep) {
209             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
210             for(int i=0; i<this.elements.length; i++) {
211                 elements[i*2]   = this.elements[i];
212                 if (i<this.elements.length-1)
213                     elements[i*2+1] = new Drop(sep);
214             }
215             this.elements = elements;
216             return this;
217         }
218         public Sequence build(Context cx, Union u, boolean lame, NonTerminalNode cnt) {
219             Sequence ret = build0(cx, lame || this.lame, cnt);
220             for(Seq s : and) { Sequence dork = s.build(cx, u, true, cnt); ret = ret.and(dork); }
221             for(Seq s : not) { Sequence dork = s.build(cx, u, true, cnt); ret = ret.not(dork); }
222             u.add(ret);
223             ret.lame = lame;
224             return ret;
225         }
226         public Sequence build0(Context cx, boolean lame, NonTerminalNode cnt) {
227             boolean dropAll = lame;
228             if (tag!=null && tag.endsWith("()")) dropAll = true;
229             boolean[] drops = new boolean[elements.length];
230             Element[] els = new Element[elements.length];
231             for(int i=0; i<elements.length; i++) {
232                 drops[i]  = elements[i].drop();
233                 els[i] = elements[i].build(cx, cnt);
234                 if (elements[i].getOwnerTag() != null)
235                     tag = elements[i].getOwnerTag();
236             }
237             Sequence ret = null;
238             if (dropAll)     ret = Sequence.drop(els, false);
239             else {
240                 Production prod = new Production(tag, (cnt==null?null:cnt.name), els, drops);
241                 ret = cx.rm.tryResolveTag(prod);
242                 if (ret == null) {
243                     int idx = -1;
244                     for(int i=0; i<els.length; i++)
245                         if (!drops[i])
246                             if (idx==-1) idx = i;
247                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
248                     if (idx != -1) ret = Sequence.singleton(els, idx);
249                     else           ret = Sequence.drop(els, false);
250                 }
251             }
252             if (this.follow != null)
253                 ret.follow = infer(this.follow.build(cx, null));
254             ret.lame = this.lame;
255             return ret;
256         }
257     }
258     public static @bind.as("&")   Seq  and2(Seq s,        Seq a) { return s.and(a); }
259     public static @bind.as("&~")  Seq  andnot2(Seq s,     Seq a) { return s.andnot(a); }
260     public static @bind.as("->")  Seq  arrow(Seq s, ElementNode e)                { return s.follow(e); }
261     public static @bind.as("::")  Seq  tag(String tagname, Seq s)        { return s.tag(tagname); }
262     public static @bind.as("/")   Seq  slash(Seq s, ElementNode e)                { return s.separate(e); }
263
264     public static Seq  seq(ElementNode[] elements)               { return new Seq(elements); }
265     public static @bind.as("Elements")  Seq  seq2(ElementNode[] elements)               { return new Seq(elements); }
266     public static @bind.as        Seq  psx(Seq s)                        { return s; }
267     public static @bind.as(":")   ElementNode   colon(String s, ElementNode e)             { return new Label(s, e); }
268     public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
269     public static @bind.as("()")  ElementNode   epsilon()                         { return new Constant(Union.epsilon); }
270
271     public static class NonTerminalReferenceNode extends ElementNode {
272         public String nonTerminal;
273         public NonTerminalReferenceNode() { }
274         public @bind.as("NonTerminalReference") NonTerminalReferenceNode(String nonTerminal) {
275             this.nonTerminal = prefix + nonTerminal;
276         }
277         public Element build(Context cx, NonTerminalNode cnt) {
278             if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
279             Element ret = cx.get(nonTerminal);
280             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
281             return ret;
282         }
283     }
284
285     public static class Literal extends Constant {
286         public @bind Literal(@bind.arg String string) { super(CharRange.string(string)); }
287         public boolean drop() { return true; }
288     }
289
290     public static                     class CharClass            extends ElementNode {
291         Range[] ranges;
292         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
293         public Element build(Context cx, NonTerminalNode cnt) {
294             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
295             for(Range r : ranges)
296                 set.add(r.first, r.last);
297             return CharRange.set(set);
298         }
299     }
300
301     public static @bind.as("{")           class XTree                 extends ElementNode {
302         public @bind.arg Seq body;
303         public Element build(Context cx, NonTerminalNode cnt) {
304             Union u = new Union();
305             Sequence s = body.build(cx, u, false, null);
306             Union u2 = new Union();
307             u2.add(Sequence.singleton(new Element[] {
308                 CharRange.leftBrace,
309                 cx.get("ws"),
310                 u,
311                 cx.get("ws"),
312                 CharRange.rightBrace
313             }, 2));
314             return u2;
315         }
316     }
317
318     public static class Rep extends ElementNode {
319         public ElementNode e, sep;
320         public boolean zero, many, max;
321         public Rep(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
322             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
323         public Element build(Context cx, NonTerminalNode cnt) {
324             return (!max)
325                 ? Sequence.repeat(e.build(cx, null),        zero, many, sep==null ? null : sep.build(cx, null), cx.rm.repeatTag())
326                 : sep==null
327                 ? Sequence.repeatMaximal(infer(e.build(cx, null)), zero, many,                                   cx.rm.repeatTag())
328                 : Sequence.repeatMaximal(e.build(cx, null),                    zero, many, infer(sep.build(cx, null)), cx.rm.repeatTag());
329         }
330     }
331
332     // FIXME: it would be nice if we could hoist this into "Rep"
333     public static @bind.as("++")  ElementNode plusmax(final ElementNode e)                     
334     { return new Rep(e, null, false, true, true); }
335     public static @bind.as("+")   ElementNode plus(final ElementNode e)                        
336     { return new Rep(e, null, false, true, false); }
337     public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep) 
338     { return new Rep(e, sep,  false, true, true); }
339     public static @bind.as("+/")  ElementNode plusfollow(final ElementNode e, final ElementNode sep)    
340     { return new Rep(e, sep,  false, true, false); }
341     public static @bind.as("**")  ElementNode starmax(final ElementNode e)                     
342     { return new Rep(e, null, true,  true, true); }
343     public static @bind.as("*")   ElementNode star(final ElementNode e)                        
344     { return new Rep(e, null, true,  true, false); }
345     public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep) 
346     { return new Rep(e, sep,  true,  true, true); }
347     public static @bind.as("*/")  ElementNode starfollow(final ElementNode e, final ElementNode sep)    
348     { return new Rep(e, sep,  true,  true, false); }
349     public static @bind.as("?")   ElementNode question(final ElementNode e)                    
350     { return new Rep(e, null, true,  true, false); }
351     public static @bind.as("!")   ElementNode bang(final ElementNode e)                        
352     { return new Drop(e); }
353
354     public static @bind.as("^")   ElementNode caret(final String s) {
355         final String thePrefix = prefix;
356         return new Drop(new Constant(CharRange.string(s)) {
357                 public String getOwnerTag() { return thePrefix+s; }
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                 //System.err.println("*** warning could not find " + name);
410                 throw new Error("warning could not find " + name);
411             } else {
412                 String old = cnt;
413                 cnt = name;
414                 nt.build(this, ret, nt);
415                 cnt = old;
416             }
417             return ret;
418         }
419
420     }
421
422     public static class Constant extends ElementNode {
423         Element constant;
424         public Constant(Element constant) { this.constant = constant; }
425         public Element build(Context cx, NonTerminalNode cnt) { return constant; }
426     }
427     public abstract static class PostProcess extends ElementNode {
428         ElementNode e;
429         public PostProcess(ElementNode e) { this.e = e; }
430         public Element build(Context cx, NonTerminalNode cnt) { return postProcess(e.build(cx, cnt)); }
431         public abstract Element postProcess(Element e);
432     }
433     public static abstract class ElementNode {
434         public String getLabel() { return null; }
435         public String getOwnerTag() { return null; }
436         public boolean drop() { return false; }
437         public abstract Element build(Context cx, NonTerminalNode cnt);
438     }
439
440     public static class Drop extends ElementNode {
441         public ElementNode e;
442         public Drop(ElementNode e) { this.e = e; }
443         public String getLabel() { return null; }
444         public boolean drop() { return true; }
445         public String getOwnerTag() { return e.getOwnerTag(); }
446         public Element build(Context cx, NonTerminalNode cnt) { return e.build(cx, cnt); }
447     }
448
449     public static class Label extends ElementNode {
450         public String label;
451         public ElementNode e;
452         public Label(String label, ElementNode e) { this.e = e; this.label = label; }
453         public String getLabel() { return label; }
454         public String getOwnerTag() { return e.getOwnerTag(); }
455         public Element build(Context cx, NonTerminalNode cnt) { return e.build(cx, cnt); }
456     }
457 }