4ae0393fd93655c3f044ceaaefe4b5c4459dd7d8
[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("you attempted to use ->, **, ++, or a similar character-class operator on a [potentially] multicharacter production");
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, null, cnt); ret = ret.and(dork); }
229             for(Seq s : not) { Sequence dork = s.build(cx, null, cnt); ret = ret.andnot(dork); }
230             if (u!=null) 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(")")   void close(String foo)                 { throw new Error("not supported"); }
270     public static @bind.as("()")  ElementNode   epsilon()                         { return new Constant(epsilon); }
271
272     private static Union epsilon = new Union("()");
273     static { epsilon.add(Sequence.create()); }
274
275     public static class NonTerminalReferenceNode extends ElementNode {
276         public String nonTerminal;
277         public NonTerminalReferenceNode() { }
278         public @bind.as("NonTerminalReference") NonTerminalReferenceNode(String nonTerminal) {
279             this.nonTerminal = prefix + nonTerminal;
280         }
281         public Atom toAtom(Context cx) {
282             return cx.grammar.get(nonTerminal).toAtom(cx);
283         }
284         public Element build(Context cx, NonTerminalNode cnt) {
285             if (!this.nonTerminal.startsWith(prefix)) nonTerminal = prefix + nonTerminal;
286             Element ret = cx.get(nonTerminal);
287             if (ret == null) throw new RuntimeException("unknown nonterminal \""+nonTerminal+"\"");
288             return ret;
289         }
290     }
291
292     public static class Literal extends Constant {
293         private String string;
294         public @bind Literal(@bind.arg String string) {
295             super(CharAtom.string(string));
296             this.string = string;
297         }
298         public boolean drop() { return true; }
299         public Atom toAtom(Context cx) {
300             if (string.length()!=1) return super.toAtom(cx);
301             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
302             set.add(string.charAt(0), string.charAt(0));
303             return CharAtom.set(set);
304         }
305     }
306
307     public static                     class CharClass            extends ElementNode {
308         Range[] ranges;
309         public @bind.as("[") CharClass(Range[] ranges) { this.ranges = ranges; }
310         public Atom toAtom(Context cx) {
311             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
312             for(Range r : ranges)
313                 set.add(r.first, r.last);
314             return CharAtom.set(set);
315         }
316         public Element build(Context cx, NonTerminalNode cnt) {
317             edu.berkeley.sbp.util.Range.Set set = new edu.berkeley.sbp.util.Range.Set();
318             for(Range r : ranges)
319                 set.add(r.first, r.last);
320             return CharAtom.set(set);
321         }
322     }
323
324     public static @bind.as("{")           class XTree                 extends ElementNode {
325         public @bind.arg Seq body;
326         public Element build(Context cx, NonTerminalNode cnt) {
327             Union u = new Union(null, false);
328             Sequence s = body.build(cx, u, null);
329             Union u2 = new Union(null, false);
330             u2.add(Sequence.create(new Element[] {
331                 CharAtom.leftBrace,
332                 cx.get("ws"),
333                 u,
334                 cx.get("ws"),
335                 CharAtom.rightBrace
336             }, 2));
337             return u2;
338         }
339     }
340
341     public static class Rep extends ElementNode {
342         public ElementNode e, sep;
343         public boolean zero, many, max;
344         public Rep(ElementNode e, ElementNode sep, boolean zero, boolean many, boolean max) {
345             this.e = e; this.sep = sep; this.zero = zero; this.many = many; this.max = max;}
346         public Atom toAtom(Context cx) {
347             if (sep != null) return super.toAtom(cx);
348             return e.toAtom(cx);
349         }
350         public Element build(Context cx, NonTerminalNode cnt) {
351             return (!max)
352                 ? Repeat.repeat(e.build(cx, null), zero, many, sep==null ? null : sep.build(cx, null), cx.rm.repeatTag())
353                 : sep==null
354                 ? Repeat.repeatMaximal(e.toAtom(cx), zero, many, cx.rm.repeatTag())
355                 : Repeat.repeatMaximal(e.build(cx, null), zero, many, sep.toAtom(cx), cx.rm.repeatTag());
356         }
357     }
358
359     // FIXME: it would be nice if we could hoist this into "Rep"
360     public static @bind.as("++")  ElementNode plusmax(final ElementNode e)                     
361     { return new Rep(e, null, false, true, true); }
362     public static @bind.as("+")   ElementNode plus(final ElementNode e)                        
363     { return new Rep(e, null, false, true, false); }
364     public static @bind.as("++/") ElementNode plusmaxfollow(final ElementNode e, final ElementNode sep) 
365     { return new Rep(e, sep,  false, true, true); }
366     public static @bind.as("+/")  ElementNode plusfollow(final ElementNode e, final ElementNode sep)    
367     { return new Rep(e, sep,  false, true, false); }
368     public static @bind.as("**")  ElementNode starmax(final ElementNode e)                     
369     { return new Rep(e, null, true,  true, true); }
370     public static @bind.as("*")   ElementNode star(final ElementNode e)                        
371     { return new Rep(e, null, true,  true, false); }
372     public static @bind.as("**/") ElementNode starmaxfollow(final ElementNode e, final ElementNode sep) 
373     { return new Rep(e, sep,  true,  true, true); }
374     public static @bind.as("*/")  ElementNode starfollow(final ElementNode e, final ElementNode sep)    
375     { return new Rep(e, sep,  true,  true, false); }
376     public static @bind.as("?")   ElementNode question(final ElementNode e)                    
377     { return new Rep(e, null, true,  true, false); }
378     public static @bind.as("!")   ElementNode bang(final ElementNode e)                        
379     { return new Drop(e); }
380
381     public static @bind.as("^")   ElementNode caret(final String s) {
382         final String thePrefix = prefix;
383         return new Constant(CharAtom.string(s)) {
384                 public String getOwnerTag() { return thePrefix+s; }
385                 public boolean drop() { return true; }
386             };
387     }
388
389     public static @bind.as("~")   ElementNode tilde(final ElementNode e) {
390         return new ElementNodeWrapper(e) {
391                 public Atom toAtom(Context cx) {
392                     return infer((Topology<Character>)e.toAtom(cx).complement()/*.minus(CharAtom.braces)*/);
393                 }
394                 public Element build(Context cx, NonTerminalNode cnt) {
395                     return infer((Topology<Character>)e.toAtom(cx).complement()/*.minus(CharAtom.braces)*/);
396                 } }; }
397
398     public static @bind.as("Word")        String word(String s) { return s; }
399     public static @bind.as("Quoted")      String quoted(String s) { return s; }
400     public static @bind.as("escaped")     String c(char c) {
401         if (c=='{') return CharAtom.left+"";
402         if (c=='}') return CharAtom.right+"";
403         return c+"";
404     }
405     public static @bind.as("EmptyString") String emptystring() { return ""; }
406     public static @bind.as("\n")          String retur() { return "\n"; }
407     public static @bind.as("\r")          String lf() { return "\r"; }
408
409     //static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
410     static Atom infer(Object t) { return (Atom)t; }
411
412     public static class Context {
413         public HashMap<String,Union> map = new HashMap<String,Union>();
414         public GrammarNode grammar;
415         public String cnt = null;
416         public Grammar.Bindings rm;
417         public Context(GrammarNode g, Grammar.Bindings rm) {
418             this.grammar = g;
419             this.rm = rm;
420         }
421         public Union build() {
422             Union ret = null;
423             for(NonTerminalNode nt : grammar.values()) {
424                 Union u = get(nt.name);
425                 if ("s".equals(nt.name))
426                     ret = u;
427             }
428             return ret;
429         }
430         public Context(Tree t, Grammar.Bindings rm) {
431             this.rm = rm;
432             TreeFunctor<Object,Object> red = (TreeFunctor<Object,Object>)t.head();
433             this.grammar = (GrammarNode)red.invoke(t);
434         }
435         public Union peek(String name) { return map.get(name); }
436         public void  put(String name, Union u) { map.put(name, u); }
437         public Union get(String name) {
438             Union ret = map.get(name);
439             if (ret != null) return ret;
440             ret = new Union(name);
441             map.put(name, ret);
442             NonTerminalNode nt = grammar.get(name);
443             if (nt==null) {
444                 throw new Error("warning could not find " + name);
445             } else {
446                 String old = cnt;
447                 cnt = name;
448                 nt.build(this, ret, nt);
449                 cnt = old;
450             }
451             return ret;
452         }
453
454     }
455
456     public static abstract class ElementNode {
457         public String getLabel() { return null; }
458         public String getOwnerTag() { return null; }
459         public boolean drop() { return false; }
460         public Atom toAtom(Context cx) { throw new Error("can't convert a " + this.getClass().getName() + " to an atom"); }
461         public abstract Element build(Context cx, NonTerminalNode cnt);
462     }
463
464     public static abstract class ElementNodeWrapper extends ElementNode {
465         protected ElementNode _e;
466         public ElementNodeWrapper(ElementNode e) { this._e = e; }
467         public String getLabel() { return _e.getLabel(); }
468         public String getOwnerTag() { return _e.getOwnerTag(); }
469         public boolean drop() { return _e.drop(); }
470         public Atom toAtom(Context cx) { return _e.toAtom(cx); }
471         public Element build(Context cx, NonTerminalNode cnt) { return _e.build(cx, cnt); }
472     }
473
474     public static class Constant extends ElementNode {
475         Element constant;
476         public Constant(Element constant) { this.constant = constant; }
477         public Element build(Context cx, NonTerminalNode cnt) { return constant; }
478         public Atom toAtom(Context cx) {
479             if (constant instanceof Atom) return ((Atom)constant);
480             return super.toAtom(cx);
481         }
482     }
483
484     public abstract static class PostProcess extends ElementNodeWrapper {
485         public PostProcess(ElementNode e) { super(e); }
486         public Element build(Context cx, NonTerminalNode cnt) { return postProcess(_e.build(cx, cnt)); }
487         public abstract Element postProcess(Element e);
488     }
489
490     public static class Drop extends ElementNodeWrapper {
491         public Drop(ElementNode e) { super(e); }
492         public boolean drop() { return true; }
493     }
494
495     public static class Label extends ElementNodeWrapper {
496         public String label;
497         public Label(String label, ElementNode e) { super(e); this.label = label; }
498         public String getLabel() { return label; }
499     }
500
501     /*
502     static class Invert extends Atom {
503         private final Atom a;
504         public Invert(Atom a) { this.a = a; }
505         public Topology top() { return a.complement(); }
506         public String toString() { return "~"+a; }
507     }
508     */
509 }