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