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 Atom toAtom(Context cx) {
68             Atom ret = null;
69             for(Seq[] ss : sequences)
70                 for(Seq s : ss)
71                     ret = ret==null ? s.toAtom(cx) : (Atom)ret.union(s.toAtom(cx));
72             return ret;
73         }
74         public void build(Context cx, Union u, NonTerminalNode cnt) {
75             HashSet<Sequence> bad2 = new HashSet<Sequence>();
76             for(int i=0; i<sequences.length; i++) {
77                 Seq[] group = sequences[i];
78                 Union u2 = new Union(null, false);
79                 if (sequences.length==1) u2 = u;
80                 for(int j=0; j<group.length; j++) {
81                     group[j].build(cx, u2, cnt);
82                 }
83                 if (sequences.length==1) break;
84                 Sequence seq = Sequence.create(u2);
85                 for(Sequence s : bad2) seq = seq.not(s);
86                 u.add(seq);
87                 bad2.add(Sequence.create(u2));
88             }
89         }
90     }
91
92     public static @bind.as("#import") GrammarNode poundimport(String fileName, String as) {
93         if (as==null) as = "";
94         else if ("".equals(as)) { }
95         else as = as +".";
96
97         try {
98             Tree t = new CharParser(MetaGrammar.newInstance()).parse(new FileInputStream("tests/"+fileName)).expand1();
99             TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
100             String oldprefix = prefix;
101             prefix = as;
102             GrammarNode gn = (GrammarNode)red.invoke(t);
103             prefix = oldprefix;
104             return gn;
105         } catch (Exception e) {
106             e.printStackTrace();
107             throw new RuntimeException(e);
108         }
109     }
110
111     public static class NonTerminalNode extends UnionNode {
112         public boolean rep;
113         public String  name = null;
114         public String sep = null;
115         public NonTerminalNode[] getNonTerminals() { return new NonTerminalNode[] { this }; }
116         public @bind.as("NonTerminal") NonTerminalNode(@bind.arg String name, @bind.arg Seq[][] sequences) {
117             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 = sep==null?null:(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(null, false);
131             urep.add(Sequence.create());
132             if (sep != null)
133                 urep.add(Sequence.create(new Element[] { cx.get(sep), u }, 1));
134             else
135                 urep.add(Sequence.create(new Element[] { u }, 0));
136
137             for(int i=0; i<sequences.length; i++) {
138                 Seq[] group = sequences[i];
139                 Union u2 = new Union(null, false);
140                 if (sequences.length==1) u2 = u;
141                 for(int j=0; j<group.length; j++) {
142                     Union u3 = new Union(null, false);
143                     group[j].build(cx, u3, this);
144                     Sequence s = Sequence.create(cx.rm.repeatTag(),
145                                                  new Element[] { u3, urep },
146                                                  new boolean[] { false, false },
147                                                  true);
148                     u2.add(s);
149                 }
150                 if (sequences.length==1) break;
151                 Sequence seq = Sequence.create(u2);
152                 for(Sequence s : bad2) seq = seq.not(s);
153                 u.add(seq);
154                 bad2.add(Sequence.create(u2));
155             }
156         }
157     }
158
159     public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg Seq[][] sequences) {
160         return new NonTerminalNode(name, sequences, true); }
161     public static @bind.as("=") NonTerminalNode go(@bind.arg String name, @bind.arg String sep, @bind.arg Seq[][] sequences) {
162         return new NonTerminalNode(name, sequences, true, sep); }
163
164     public static class AnonUnionNode extends UnionNode {
165         public @bind.as("(") AnonUnionNode(Seq[][] sequences) {
166             this.sequences = sequences;
167         }
168         public Element build(Context cx, NonTerminalNode cnt) {
169             Union ret = new Union(null, false);
170             build(cx, ret, cnt);
171             return ret;
172         }
173     }
174
175     public static class Range {
176         public @bind Range(char only) { first = only; last = only; }
177         public @bind Range(char first, char last) { this.first = first; this.last = last; }
178         public char first;
179         public char last;
180     }
181
182     public static /*abstract*/ class Seq {
183         HashSet<Seq> and = new HashSet<Seq>();
184         HashSet<Seq> not = new HashSet<Seq>();
185         ElementNode[] elements;
186         ElementNode follow;
187         String tag = null;
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 Atom toAtom(Context cx) {
197             if (elements.length != 1) throw new Error("FIXME");
198             return elements[0].toAtom(cx);
199         }
200         public Seq tag(String tag) { this.tag = prefix+tag; return this; }
201         public Seq follow(ElementNode follow) {
202             this.follow = follow;
203             return this;
204         }
205         public Seq dup() {
206             Seq ret = new Seq(elements);
207             ret.and.addAll(and);
208             ret.not.addAll(not);
209             ret.follow = follow;
210             ret.tag = prefix+tag;
211             return ret;
212         }
213         public Seq and(Seq s) { and.add(s); return this; }
214         public Seq andnot(Seq s) { not.add(s); return this; }
215         public Seq separate(ElementNode sep) {
216             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
217             for(int i=0; i<this.elements.length; i++) {
218                 elements[i*2]   = this.elements[i];
219                 if (i<this.elements.length-1)
220                     elements[i*2+1] = new Drop(sep);
221             }
222             this.elements = elements;
223             return this;
224         }
225         public Sequence build(Context cx, Union u, NonTerminalNode cnt) {
226             Sequence ret = build0(cx, cnt);
227             for(Seq s : and) { Sequence dork = s.build(cx, u, cnt); ret = ret.and(dork); }
228             for(Seq s : not) { Sequence dork = s.build(cx, u, cnt); ret = ret.not(dork); }
229             u.add(ret);
230             return ret;
231         }
232         public Sequence build0(Context cx, NonTerminalNode cnt) {
233             boolean[] drops = new boolean[elements.length];
234             Element[] els = new Element[elements.length];
235             for(int i=0; i<elements.length; i++) {
236                 drops[i]  = elements[i].drop();
237                 els[i] = elements[i].build(cx, cnt);
238                 if (elements[i].getOwnerTag() != null)
239                     tag = elements[i].getOwnerTag();
240             }
241             Sequence ret = null;
242             Production prod = new Production(tag, (cnt==null?null:cnt.name), els, drops);
243             ret = cx.rm.createSequence(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.create(els, null));
250                 if (idx != -1) ret = Sequence.create(els, idx);
251                 else           ret = Sequence.create(els, null);
252             }
253             if (this.follow != null)
254                 ret = ret.followedBy(this.follow.toAtom(cx));
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(epsilon); }
270
271     private static Union epsilon = new Union("()");
272     static { epsilon.add(Sequence.create()); }
273
274     public static class NonTerminalReferenceNode extends ElementNode {
275         public String nonTerminal;
276         public NonTerminalReferenceNode() { }
277         public @bind.as("NonTerminalReference") NonTerminalReferenceNode(String nonTerminal) {
278             this.nonTerminal = prefix + nonTerminal;
279         }
280         public Atom toAtom(Context cx) {
281             return cx.grammar.get(nonTerminal).toAtom(cx);
282         }
283         public Element build(Context cx, NonTerminalNode cnt) {
284             if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
285             Element ret = cx.get(nonTerminal);
286             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
287             return ret;
288         }
289     }
290
291     public static class Literal extends Constant {
292         private String string;
293         public @bind Literal(@bind.arg String string) {
294             super(CharAtom.string(string));
295             this.string = string;
296         }
297         public boolean drop() { return true; }
298         public Atom toAtom(Context cx) {
299             if (string.length()!=1) return super.toAtom(cx);
300             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
301             set.add(string.charAt(0), string.charAt(0));
302             return CharAtom.set(set);
303         }
304     }
305
306     public static                     class CharClass            extends ElementNode {
307         Range[] ranges;
308         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
309         public Atom toAtom(Context cx) {
310             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
311             for(Range r : ranges)
312                 set.add(r.first, r.last);
313             return CharAtom.set(set);
314         }
315         public Element build(Context cx, NonTerminalNode cnt) {
316             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
317             for(Range r : ranges)
318                 set.add(r.first, r.last);
319             return CharAtom.set(set);
320         }
321     }
322
323     public static @bind.as("{")           class XTree                 extends ElementNode {
324         public @bind.arg Seq body;
325         public Element build(Context cx, NonTerminalNode cnt) {
326             Union u = new Union(null, false);
327             Sequence s = body.build(cx, u, null);
328             Union u2 = new Union(null, false);
329             u2.add(Sequence.create(new Element[] {
330                 CharAtom.leftBrace,
331                 cx.get("ws"),
332                 u,
333                 cx.get("ws"),
334                 CharAtom.rightBrace
335             }, 2));
336             return u2;
337         }
338     }
339
340     public static class Rep extends ElementNode {
341         public ElementNode e, sep;
342         public boolean zero, many, max;
343         public Rep(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
344             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
345         public Atom toAtom(Context cx) {
346             if (sep != null) return super.toAtom(cx);
347             return e.toAtom(cx);
348         }
349         public Element build(Context cx, NonTerminalNode cnt) {
350             return (!max)
351                 ? Repeat.repeat(e.build(cx, null), zero, many, sep==null ? null : sep.build(cx, null), cx.rm.repeatTag())
352                 : sep==null
353                 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, cx.rm.repeatTag())
354                 : Repeat.repeatMaximal(e.build(cx, null), zero, many, sep.toAtom(cx), cx.rm.repeatTag());
355         }
356     }
357
358     // FIXME: it would be nice if we could hoist this into "Rep"
359     public static @bind.as("++")  ElementNode plusmax(final ElementNode e)                     
360     { return new Rep(e, null, false, true, true); }
361     public static @bind.as("+")   ElementNode plus(final ElementNode e)                        
362     { return new Rep(e, null, false, true, false); }
363     public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep) 
364     { return new Rep(e, sep,  false, true, true); }
365     public static @bind.as("+/")  ElementNode plusfollow(final ElementNode e, final ElementNode sep)    
366     { return new Rep(e, sep,  false, true, false); }
367     public static @bind.as("**")  ElementNode starmax(final ElementNode e)                     
368     { return new Rep(e, null, true,  true, true); }
369     public static @bind.as("*")   ElementNode star(final ElementNode e)                        
370     { return new Rep(e, null, true,  true, false); }
371     public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep) 
372     { return new Rep(e, sep,  true,  true, true); }
373     public static @bind.as("*/")  ElementNode starfollow(final ElementNode e, final ElementNode sep)    
374     { return new Rep(e, sep,  true,  true, false); }
375     public static @bind.as("?")   ElementNode question(final ElementNode e)                    
376     { return new Rep(e, null, true,  true, false); }
377     public static @bind.as("!")   ElementNode bang(final ElementNode e)                        
378     { return new Drop(e); }
379
380     public static @bind.as("^")   ElementNode caret(final String s) {
381         final String thePrefix = prefix;
382         return new Constant(CharAtom.string(s)) {
383                 public String getOwnerTag() { return thePrefix+s; }
384                 public boolean drop() { return true; }
385             };
386     }
387
388     public static @bind.as("~")   ElementNode tilde(final ElementNode e) {
389         return new ElementNodeWrapper(e) {
390                 public Atom toAtom(Context cx) {
391                     return infer((Topology<Character>)e.toAtom(cx).complement().minus(CharAtom.braces));
392                 }
393                 public Element build(Context cx, NonTerminalNode cnt) {
394                     return infer((Topology<Character>)e.toAtom(cx).complement().minus(CharAtom.braces));
395                 } }; }
396
397     public static @bind.as("Word")        String word(String s) { return s; }
398     public static @bind.as("Quoted")      String quoted(String s) { return s; }
399     public static @bind.as("escaped")     String c(char c) { return c+""; }
400     public static @bind.as("EmptyString") String emptystring() { return ""; }
401     public static @bind.as("\n")          String retur() { return "\n"; }
402     public static @bind.as("\r")          String lf() { return "\r"; }
403
404     //static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
405     static Atom infer(Object t) { return (Atom)t; }
406
407     public static class Context {
408         public HashMap<String,Union> map = new HashMap<String,Union>();
409         public GrammarNode grammar;
410         public String cnt = null;
411         public Grammar.Bindings rm;
412         public Context(GrammarNode g, Grammar.Bindings rm) {
413             this.grammar = g;
414             this.rm = rm;
415         }
416         public Union build() {
417             Union ret = null;
418             for(NonTerminalNode nt : grammar.values()) {
419                 Union u = get(nt.name);
420                 if ("s".equals(nt.name))
421                     ret = u;
422             }
423             return ret;
424         }
425         public Context(Tree t, Grammar.Bindings rm) {
426             this.rm = rm;
427             TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
428             this.grammar = (GrammarNode)red.invoke(t);
429         }
430         public Union peek(String name) { return map.get(name); }
431         public void  put(String name, Union u) { map.put(name, u); }
432         public Union get(String name) {
433             Union ret = map.get(name);
434             if (ret != null) return ret;
435             ret = new Union(name);
436             map.put(name, ret);
437             NonTerminalNode nt = grammar.get(name);
438             if (nt==null) {
439                 throw new Error("warning could not find " + name);
440             } else {
441                 String old = cnt;
442                 cnt = name;
443                 nt.build(this, ret, nt);
444                 cnt = old;
445             }
446             return ret;
447         }
448
449     }
450
451     public static abstract class ElementNode {
452         public String getLabel() { return null; }
453         public String getOwnerTag() { return null; }
454         public boolean drop() { return false; }
455         public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom"); }
456         public abstract Element build(Context cx, NonTerminalNode cnt);
457     }
458
459     public static abstract class ElementNodeWrapper extends ElementNode {
460         protected ElementNode _e;
461         public ElementNodeWrapper(ElementNode e) { this._e = e; }
462         public String getLabel() { return _e.getLabel(); }
463         public String getOwnerTag() { return _e.getOwnerTag(); }
464         public boolean drop() { return _e.drop(); }
465         public Atom toAtom(Context cx) { return _e.toAtom(cx); }
466         public Element build(Context cx, NonTerminalNode cnt) { return _e.build(cx, cnt); }
467     }
468
469     public static class Constant extends ElementNode {
470         Element constant;
471         public Constant(Element constant) { this.constant = constant; }
472         public Element build(Context cx, NonTerminalNode cnt) { return constant; }
473         public Atom toAtom(Context cx) {
474             if (constant instanceof Atom) return ((Atom)constant);
475             return super.toAtom(cx);
476         }
477     }
478
479     public abstract static class PostProcess extends ElementNodeWrapper {
480         public PostProcess(ElementNode e) { super(e); }
481         public Element build(Context cx, NonTerminalNode cnt) { return postProcess(_e.build(cx, cnt)); }
482         public abstract Element postProcess(Element e);
483     }
484
485     public static class Drop extends ElementNodeWrapper {
486         public Drop(ElementNode e) { super(e); }
487         public boolean drop() { return true; }
488     }
489
490     public static class Label extends ElementNodeWrapper {
491         public String label;
492         public Label(String label, ElementNode e) { super(e); this.label = label; }
493         public String getLabel() { return label; }
494     }
495
496     /*
497     static class Invert extends Atom {
498         private final Atom a;
499         public Invert(Atom a) { this.a = a; }
500         public Topology top() { return a.complement(); }
501         public String toString() { return "~"+a; }
502     }
503     */
504 }