checkpoint
[sbp.git] / src / edu / berkeley / sbp / meta / MetaGrammarBindings.java
1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
2
3 package edu.berkeley.sbp.meta;
4 import edu.berkeley.sbp.util.*;
5 import edu.berkeley.sbp.*;
6 import edu.berkeley.sbp.chr.*;
7 import edu.berkeley.sbp.misc.*;
8 import edu.berkeley.sbp.bind.*;
9 import java.util.*;
10 import java.lang.annotation.*;
11 import java.lang.reflect.*;
12 import java.io.*;
13
14 /** The java classes typically used to represent a parsed grammar AST; each inner class is a type of AST node. */
15 public class MetaGrammarBindings extends AnnotationGrammarBindings {
16
17     public MetaGrammarBindings() { super(MetaGrammarBindings.class); }
18
19     // FIXME ugly ugly ugly scary dangerous
20     public static String prefix = "";
21     
22     /** A grammar (a set of nonterminals) */
23     public static class GrammarNode extends HashMap<String,NonTerminalNode> {
24         public NonTerminalNode[] getNonTerminals() {
25             return (NonTerminalNode[])values().toArray(new NonTerminalNode[0]);
26         }
27         public GrammarNode(NonTerminalNode[] nonterminals) {
28             for(NonTerminalNode nt : nonterminals) {
29                 if (nt==null) continue;
30                 if (this.get(nt.name)!=null)
31                     throw new RuntimeException("duplicate definition of nonterminal \""+nt.name+"\"");
32                 this.put(nt.name, nt);
33             }
34         }
35         public @bind.as("Grammar") GrammarNode(Object[] nt) { add(nt); }
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 GrammarNode) add(((GrammarNode)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 Atom toAtom(Context cx) {
70             Atom ret = null;
71             for(Seq[] ss : sequences)
72                 for(Seq s : ss)
73                     ret = ret==null ? s.toAtom(cx) : (Atom)ret.union(s.toAtom(cx));
74             return ret;
75         }
76         public void build(Context cx, Union u, NonTerminalNode cnt) {
77             HashSet<Sequence> bad2 = new HashSet<Sequence>();
78             for(int i=0; i<sequences.length; i++) {
79                 Seq[] group = sequences[i];
80                 Union u2 = new Union(null, false);
81                 if (sequences.length==1) u2 = u;
82                 for(int j=0; j<group.length; j++)
83                     group[j].build(cx, u2, cnt);
84                 if (sequences.length==1) break;
85                 Sequence seq = Sequence.create(u2);
86                 for(Sequence s : bad2) seq = seq.andnot(s);
87                 u.add(seq);
88                 bad2.add(Sequence.create(u2));
89             }
90         }
91     }
92
93     public static @bind.as("#import") GrammarNode poundimport(String fileName, String as) {
94         if (as==null) as = "";
95         else if ("".equals(as)) { }
96         else as = as +".";
97
98         try {
99             Tree t = new CharParser(MetaGrammar.newInstance()).parse(new FileInputStream("tests/"+fileName)).expand1();
100             TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
101             String oldprefix = prefix;
102             prefix = as;
103             GrammarNode gn = (GrammarNode)red.invoke(t);
104             prefix = oldprefix;
105             return gn;
106         } catch (Exception e) {
107             e.printStackTrace();
108             throw new RuntimeException(e);
109         }
110     }
111
112     public static class NonTerminalNode extends UnionNode {
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) {
118             this(name, sequences, false); }
119         public NonTerminalNode(String name, Seq[][] sequences, boolean rep) { this(name, sequences, rep, null); }
120         public NonTerminalNode(String name, Seq[][] sequences, boolean rep, String sep) {
121             this.name = prefix + name;
122             this.sequences = sequences;
123             this.rep = rep;
124             this.sep = sep==null?null:(prefix + sep);
125         }
126         public Element build(Context cx, NonTerminalNode cnt) { return cx.get(name); }
127         public void build(Context cx, Union u, NonTerminalNode cnt) {
128             if (!rep) { super.build(cx, u, this); return; }
129             HashSet<Sequence> bad2 = new HashSet<Sequence>();
130
131             Union urep = new Union(null, false);
132             urep.add(Sequence.create());
133             if (sep != null)
134                 urep.add(Sequence.create(new Element[] { cx.get(sep), u }, 1));
135             else
136                 urep.add(Sequence.create(new Element[] { u }, 0));
137
138             for(int i=0; i<sequences.length; i++) {
139                 Seq[] group = sequences[i];
140                 Union u2 = new Union(null, false);
141                 if (sequences.length==1) u2 = u;
142                 for(int j=0; j<group.length; j++) {
143                     Union u3 = new Union(null, false);
144                     group[j].build(cx, u3, this);
145                     Sequence s = Sequence.create(cx.rm.repeatTag(),
146                                                  new Element[] { u3, urep },
147                                                  new boolean[] { false, false },
148                                                  true);
149                     u2.add(s);
150                 }
151                 if (sequences.length==1) break;
152                 Sequence seq = Sequence.create(u2);
153                 for(Sequence s : bad2) seq = seq.andnot(s);
154                 u.add(seq);
155                 bad2.add(Sequence.create(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(null, false);
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         public void append(ElementNode e) {
190             ElementNode[] elements = new ElementNode[this.elements.length+1];
191             System.arraycopy(this.elements, 0, elements, 0, this.elements.length);
192             this.elements = elements;
193             elements[elements.length-1] = e;
194         }
195         public Seq(ElementNode e) { this(new ElementNode[] { e }); }
196         public Seq(ElementNode[] elements) { this.elements = elements; }
197         public Atom toAtom(Context cx) {
198             if (elements.length != 1) throw new Error("FIXME");
199             return elements[0].toAtom(cx);
200         }
201         public Seq tag(String tag) { this.tag = prefix+tag; return this; }
202         public Seq follow(ElementNode follow) {
203             this.follow = follow;
204             return this;
205         }
206         public Seq dup() {
207             Seq ret = new Seq(elements);
208             ret.and.addAll(and);
209             ret.not.addAll(not);
210             ret.follow = follow;
211             ret.tag = prefix+tag;
212             return ret;
213         }
214         public Seq and(Seq s) { and.add(s); return this; }
215         public Seq andnot(Seq s) { not.add(s); return this; }
216         public Seq separate(ElementNode sep) {
217             ElementNode[] elements = new ElementNode[this.elements.length * 2 - 1];
218             for(int i=0; i<this.elements.length; i++) {
219                 elements[i*2]   = this.elements[i];
220                 if (i<this.elements.length-1)
221                     elements[i*2+1] = new Drop(sep);
222             }
223             this.elements = elements;
224             return this;
225         }
226         public Sequence build(Context cx, Union u, NonTerminalNode cnt) {
227             Sequence ret = build0(cx, cnt);
228             for(Seq s : and) { Sequence dork = s.build(cx, u, cnt); ret = ret.and(dork); }
229             for(Seq s : not) { Sequence dork = s.build(cx, u, cnt); ret = ret.andnot(dork); }
230             u.add(ret);
231             return ret;
232         }
233         public Sequence build0(Context cx, NonTerminalNode cnt) {
234             boolean[] drops = new boolean[elements.length];
235             Element[] els = new Element[elements.length];
236             for(int i=0; i<elements.length; i++) {
237                 drops[i]  = elements[i].drop();
238                 els[i] = elements[i].build(cx, cnt);
239                 if (elements[i].getOwnerTag() != null)
240                     tag = elements[i].getOwnerTag();
241             }
242             Sequence ret = null;
243             Production prod = new Production(tag, (cnt==null?null:cnt.name), els, drops);
244             ret = cx.rm.createSequence(prod);
245             if (ret == null) {
246                 int idx = -1;
247                 for(int i=0; i<els.length; i++)
248                     if (!drops[i])
249                         if (idx==-1) idx = i;
250                         else throw new Error("multiple non-dropped elements in sequence: " + Sequence.create(els, null));
251                 if (idx != -1) ret = Sequence.create(els, idx);
252                 else           ret = Sequence.create(els, null);
253             }
254             if (this.follow != null)
255                 ret = ret.followedBy(this.follow.toAtom(cx));
256             return ret;
257         }
258     }
259     public static @bind.as("&")   Seq  and2(Seq s,        Seq a)   { return s.and(a); }
260     public static @bind.as("&~")  Seq  andnot2(Seq s,     Seq a)   { return s.andnot(a); }
261     public static @bind.as("->")  Seq  arrow(Seq s, ElementNode e) { return s.follow(e); }
262     public static @bind.as("::")  Seq  tag(String tagname, Seq s)  { return s.tag(tagname); }
263     public static @bind.as("/")   Seq  slash(Seq s, ElementNode e) { return s.separate(e); }
264
265     public static Seq  seq(ElementNode[] elements)               { return new Seq(elements); }
266     public static @bind.as("Elements")  Seq  seq2(ElementNode[] elements)               { return new Seq(elements); }
267     public static @bind.as        Seq  psx(Seq s)                        { return s; }
268     public static @bind.as(":")   ElementNode   colon(String s, ElementNode e)             { return new Label(s, e); }
269     public static @bind.as("{") ElementNode   leftBrace() {
270         return new Drop(new CharClass(new Range[] { new Range(CharAtom.left, CharAtom.left) })); }
271     public static @bind.as("}") ElementNode   rightBrace() {
272         return new Drop(new CharClass(new Range[] { new Range(CharAtom.right, CharAtom.right) })); }
273     public static @bind.as(")")   void close(String foo)                 { throw new Error("not supported"); }
274     public static @bind.as("()")  ElementNode   epsilon()                         { return new Constant(epsilon); }
275
276     private static Union epsilon = new Union("()");
277     static { epsilon.add(Sequence.create()); }
278
279     public static class NonTerminalReferenceNode extends ElementNode {
280         public String nonTerminal;
281         public NonTerminalReferenceNode() { }
282         public @bind.as("NonTerminalReference") NonTerminalReferenceNode(String nonTerminal) {
283             this.nonTerminal = prefix + nonTerminal;
284         }
285         public Atom toAtom(Context cx) {
286             return cx.grammar.get(nonTerminal).toAtom(cx);
287         }
288         public Element build(Context cx, NonTerminalNode cnt) {
289             if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
290             Element ret = cx.get(nonTerminal);
291             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
292             return ret;
293         }
294     }
295
296     public static class Literal extends Constant {
297         private String string;
298         public @bind Literal(@bind.arg String string) {
299             super(CharAtom.string(string));
300             this.string = string;
301         }
302         public boolean drop() { return true; }
303         public Atom toAtom(Context cx) {
304             if (string.length()!=1) return super.toAtom(cx);
305             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
306             set.add(string.charAt(0), string.charAt(0));
307             return CharAtom.set(set);
308         }
309     }
310
311     public static                     class CharClass            extends ElementNode {
312         Range[] ranges;
313         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
314         public Atom toAtom(Context cx) {
315             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
316             for(Range r : ranges)
317                 set.add(r.first, r.last);
318             return CharAtom.set(set);
319         }
320         public Element build(Context cx, NonTerminalNode cnt) {
321             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
322             for(Range r : ranges)
323                 set.add(r.first, r.last);
324             return CharAtom.set(set);
325         }
326     }
327
328     public static @bind.as("{")           class XTree                 extends ElementNode {
329         public @bind.arg Seq body;
330         public Element build(Context cx, NonTerminalNode cnt) {
331             Union u = new Union(null, false);
332             Sequence s = body.build(cx, u, null);
333             Union u2 = new Union(null, false);
334             u2.add(Sequence.create(new Element[] {
335                 CharAtom.leftBrace,
336                 cx.get("ws"),
337                 u,
338                 cx.get("ws"),
339                 CharAtom.rightBrace
340             }, 2));
341             return u2;
342         }
343     }
344
345     public static class Rep extends ElementNode {
346         public ElementNode e, sep;
347         public boolean zero, many, max;
348         public Rep(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
349             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
350         public Atom toAtom(Context cx) {
351             if (sep != null) return super.toAtom(cx);
352             return e.toAtom(cx);
353         }
354         public Element build(Context cx, NonTerminalNode cnt) {
355             return (!max)
356                 ? Repeat.repeat(e.build(cx, null), zero, many, sep==null ? null : sep.build(cx, null), cx.rm.repeatTag())
357                 : sep==null
358                 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, cx.rm.repeatTag())
359                 : Repeat.repeatMaximal(e.build(cx, null), zero, many, sep.toAtom(cx), cx.rm.repeatTag());
360         }
361     }
362
363     // FIXME: it would be nice if we could hoist this into "Rep"
364     public static @bind.as("++")  ElementNode plusmax(final ElementNode e)                     
365     { return new Rep(e, null, false, true, true); }
366     public static @bind.as("+")   ElementNode plus(final ElementNode e)                        
367     { return new Rep(e, null, false, true, false); }
368     public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep) 
369     { return new Rep(e, sep,  false, true, true); }
370     public static @bind.as("+/")  ElementNode plusfollow(final ElementNode e, final ElementNode sep)    
371     { return new Rep(e, sep,  false, true, false); }
372     public static @bind.as("**")  ElementNode starmax(final ElementNode e)                     
373     { return new Rep(e, null, true,  true, true); }
374     public static @bind.as("*")   ElementNode star(final ElementNode e)                        
375     { return new Rep(e, null, true,  true, false); }
376     public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep) 
377     { return new Rep(e, sep,  true,  true, true); }
378     public static @bind.as("*/")  ElementNode starfollow(final ElementNode e, final ElementNode sep)    
379     { return new Rep(e, sep,  true,  true, false); }
380     public static @bind.as("?")   ElementNode question(final ElementNode e)                    
381     { return new Rep(e, null, true,  true, false); }
382     public static @bind.as("!")   ElementNode bang(final ElementNode e)                        
383     { return new Drop(e); }
384
385     public static @bind.as("^")   ElementNode caret(final String s) {
386         final String thePrefix = prefix;
387         return new Constant(CharAtom.string(s)) {
388                 public String getOwnerTag() { return thePrefix+s; }
389                 public boolean drop() { return true; }
390             };
391     }
392
393     public static @bind.as("~")   ElementNode tilde(final ElementNode e) {
394         return new ElementNodeWrapper(e) {
395                 public Atom toAtom(Context cx) {
396                     return infer((Topology<Character>)e.toAtom(cx).complement()/*.minus(CharAtom.braces)*/);
397                 }
398                 public Element build(Context cx, NonTerminalNode cnt) {
399                     return infer((Topology<Character>)e.toAtom(cx).complement()/*.minus(CharAtom.braces)*/);
400                 } }; }
401
402     public static @bind.as("Word")        String word(String s) { return s; }
403     public static @bind.as("Quoted")      String quoted(String s) { return s; }
404     public static @bind.as("escaped")     String c(char c) {
405         if (c=='{') return CharAtom.left+"";
406         if (c=='}') return CharAtom.right+"";
407         return c+"";
408     }
409     public static @bind.as("EmptyString") String emptystring() { return ""; }
410     public static @bind.as("\n")          String retur() { return "\n"; }
411     public static @bind.as("\r")          String lf() { return "\r"; }
412
413     //static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
414     static Atom infer(Object t) { return (Atom)t; }
415
416     public static class Context {
417         public HashMap<String,Union> map = new HashMap<String,Union>();
418         public GrammarNode grammar;
419         public String cnt = null;
420         public Grammar.Bindings rm;
421         public Context(GrammarNode g, Grammar.Bindings rm) {
422             this.grammar = g;
423             this.rm = rm;
424         }
425         public Union build() {
426             Union ret = null;
427             for(NonTerminalNode nt : grammar.values()) {
428                 Union u = get(nt.name);
429                 if ("s".equals(nt.name))
430                     ret = u;
431             }
432             return ret;
433         }
434         public Context(Tree t, Grammar.Bindings rm) {
435             this.rm = rm;
436             TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
437             this.grammar = (GrammarNode)red.invoke(t);
438         }
439         public Union peek(String name) { return map.get(name); }
440         public void  put(String name, Union u) { map.put(name, u); }
441         public Union get(String name) {
442             Union ret = map.get(name);
443             if (ret != null) return ret;
444             ret = new Union(name);
445             map.put(name, ret);
446             NonTerminalNode nt = grammar.get(name);
447             if (nt==null) {
448                 throw new Error("warning could not find " + name);
449             } else {
450                 String old = cnt;
451                 cnt = name;
452                 nt.build(this, ret, nt);
453                 cnt = old;
454             }
455             return ret;
456         }
457
458     }
459
460     public static abstract class ElementNode {
461         public String getLabel() { return null; }
462         public String getOwnerTag() { return null; }
463         public boolean drop() { return false; }
464         public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom"); }
465         public abstract Element build(Context cx, NonTerminalNode cnt);
466     }
467
468     public static abstract class ElementNodeWrapper extends ElementNode {
469         protected ElementNode _e;
470         public ElementNodeWrapper(ElementNode e) { this._e = e; }
471         public String getLabel() { return _e.getLabel(); }
472         public String getOwnerTag() { return _e.getOwnerTag(); }
473         public boolean drop() { return _e.drop(); }
474         public Atom toAtom(Context cx) { return _e.toAtom(cx); }
475         public Element build(Context cx, NonTerminalNode cnt) { return _e.build(cx, cnt); }
476     }
477
478     public static class Constant extends ElementNode {
479         Element constant;
480         public Constant(Element constant) { this.constant = constant; }
481         public Element build(Context cx, NonTerminalNode cnt) { return constant; }
482         public Atom toAtom(Context cx) {
483             if (constant instanceof Atom) return ((Atom)constant);
484             return super.toAtom(cx);
485         }
486     }
487
488     public abstract static class PostProcess extends ElementNodeWrapper {
489         public PostProcess(ElementNode e) { super(e); }
490         public Element build(Context cx, NonTerminalNode cnt) { return postProcess(_e.build(cx, cnt)); }
491         public abstract Element postProcess(Element e);
492     }
493
494     public static class Drop extends ElementNodeWrapper {
495         public Drop(ElementNode e) { super(e); }
496         public boolean drop() { return true; }
497     }
498
499     public static class Label extends ElementNodeWrapper {
500         public String label;
501         public Label(String label, ElementNode e) { super(e); this.label = label; }
502         public String getLabel() { return label; }
503     }
504
505     /*
506     static class Invert extends Atom {
507         private final Atom a;
508         public Invert(Atom a) { this.a = a; }
509         public Topology top() { return a.complement(); }
510         public String toString() { return "~"+a; }
511     }
512     */
513 }