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