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