checkpoint
[sbp.git] / src / edu / berkeley / sbp / misc / MetaGrammar.java
1 package edu.berkeley.sbp.misc;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import java.util.*;
6 import java.io.*;
7
8 public class MetaGrammar extends StringWalker {
9
10     public static Object repeatTag = null;
11
12     /** an atom which tracks the possible tokenset of some element, provided that element can only match single-token sequences */
13     public static class Infer<T extends Input> extends Atom<T> {
14         private final Element e;
15         public Infer(Element e) { this.e = e; }
16         public Topology<T> top() { return (Topology<T>)toAtom(e); }
17         public String toString() { return e.toString(); }
18     }
19
20     /** an atom which tracks the inverse of some other atom */
21     public static class Invert<T extends Input> extends Atom<T> {
22         private final Atom<T> a;
23         public Invert(Atom<T> a) { this.a = a; }
24         public Topology<T> top() { return a.complement(); }
25         public String toString() { return "~"+a; }
26     }
27
28     public static class Hack<T extends Input> extends Atom<T> {
29         private final Atom<T> a;
30         static final Topology leftright = CharRange.rightBrace.union(CharRange.leftBrace);
31         public Hack(Atom<T> a) { this.a = a; }
32         public Topology<T> top() { return a.minus(leftright); }
33         public String toString() { return a.toString(); }
34     }
35
36     public static Union make() throws Exception { return make(MetaGrammarTree.meta, "s"); }
37     public static Union make(Tree<String> tree, String nt) throws Exception {
38         Meta.MetaGrammarFile mgf = new MetaGrammar.Meta.MetaGrammarFile(tree);
39         BuildContext bc = new BuildContext(mgf);
40         return mgf.get(nt).build(bc);
41     }
42
43     ////////////////////////////////////////////////////////////////////////////////
44
45     private static boolean strings;
46     private static Element  set(Range.Set r) { if (strings) throw new Error(); return CharRange.set(r); }
47     private static Element  string(String s) { return strings ? StringInput.string(s) : CharRange.string(s); }
48
49     private MetaGrammar() { }
50
51     public static String string(Iterable<Tree<String>> children) {
52         String ret = "";
53         for(Tree<String> t : children) ret += string(t);
54         return ret;
55     }
56     public static String string(Tree<String> tree) {
57         String ret = "";
58         if (tree.head()!=null) ret += tree.head();
59         ret += string(tree.children());
60         return ret;
61     }
62
63     public static class BuildContext extends HashMap<String,Union> {
64         private final Meta.MetaGrammarFile mgf;
65         public BuildContext(Meta.MetaGrammarFile mgf) { this.mgf = mgf; }
66         public Union build(String s) {
67             Union ret = get(s);
68             if (ret != null) return ret;
69             Meta.MetaNonterminal mnt = mgf.get(s);
70             if (mnt==null) throw new Error("undeclared nonterminal \""+s+"\"");
71             return mnt.build(this);
72         }
73     }
74
75     public static class Meta {
76         public static class MetaGrammarFile extends HashMap<String,MetaNonterminal> {
77             public MetaGrammarFile(Tree<String> tree) {
78                 if (!tree.head().equals("grammar")) throw new Error();
79                 for(Tree<String> nt : tree.child(0))
80                     add(new MetaNonterminal(nt));
81             }
82             private void add(MetaNonterminal mnt) {
83                 if (this.get(mnt.name)!=null) throw new Error("duplicate definition of nonterminal \""+mnt.name+"\"");
84                 this.put(mnt.name, mnt);
85             }
86             public String toString() {
87                 String ret = "";
88                 for(MetaNonterminal mnt : this.values()) ret += mnt + "\n";
89                 return ret;
90             }
91         }
92         public static class MetaNonterminal {
93             public String    name;
94             public MetaUnion rhs;
95             public MetaNonterminal(Tree<String> tree) {
96                 name = string(tree.child(0));
97                 rhs = rhs(tree.child(1));
98             }
99             public String toString() { return name + " = " + rhs; }
100             public Union build(BuildContext bc) { return rhs.build(bc, name); }
101         }
102         public static MetaUnion rhs(Tree<String> t) {
103             return t.numChildren()==1
104                 ? new MetaUnion(t.child(0), false)
105                 : new MetaUnion(t, true);
106         }
107         public static class MetaUnion implements MetaSequence {
108             public boolean prioritized;
109             public MetaSequence[] sequences;
110             public Sequence buildSequence(BuildContext bc) {
111                 return Sequence.singleton(new Element[] { buildAnon(bc) }, 0);
112             }
113             public Union buildAnon(BuildContext bc) {
114                 String s = "";
115                 for(int i=0; i<sequences.length; i++)
116                     s += (i>0?"\n                "+(prioritized?">":"|")+" ":"")+sequences[i].buildSequence(bc);
117                 return build(bc, s);
118             }
119             public Union build(BuildContext bc, String name) {
120                 Union u = bc.get(name);
121                 if (u != null) return u;
122                 u = new Union(name);
123                 bc.put(name, u);
124                 HashSet<Sequence> seqs = new HashSet<Sequence>();
125                 for(MetaSequence s : sequences) {
126                     Sequence seq = s.buildSequence(bc);
127                     if (seq != null) {
128                         Sequence oseq = seq;
129                         if (prioritized)
130                             for(Sequence seqprev : seqs)
131                                 seq = seq.not(seqprev);
132                         u.add(seq);
133                         seqs.add(seq);
134                     }
135                 }
136                 return u;
137             }
138             public MetaUnion(Tree<String> t, boolean prioritized) {
139                 //System.err.println("metaunion: " + t);
140                 this.prioritized = prioritized;
141                 int i = 0;
142                 this.sequences = new MetaSequence[t.numChildren()];
143                 for(Tree<String> tt : t)
144                     sequences[i++] = prioritized
145                         ? new MetaUnion(tt, false)
146                         : makeMetaSequence(tt);
147             }
148             public String toString() {
149                 String ret = "\n     ";
150                 for(int i=0; i<sequences.length; i++) {
151                     ret += sequences[i];
152                     if (i<sequences.length-1)
153                         ret += (prioritized ? "\n    > " : "\n    | ");
154                 }
155                 return ret;
156             }
157         }
158
159         public interface MetaSequence {
160             public abstract Sequence buildSequence(BuildContext bc);
161         }
162
163         public static MetaSequence makeMetaSequence(Tree<String> t) {
164             if ("psx".equals(t.head())) return MetaConjunct.make(t.child(0));
165             if (t.head().equals("&"))  return new MetaAnd(makeMetaSequence(t.child(0)), MetaConjunct.make(t.child(1)), false);
166             if (t.head().equals("&~")) return new MetaAnd(makeMetaSequence(t.child(0)), MetaConjunct.make(t.child(1)), true);
167             return null;
168         }
169
170         public static class MetaAnd implements MetaSequence {
171             boolean not;
172             MetaSequence left;
173             MetaSequence right;
174             public Sequence buildSequence(BuildContext bc) {
175                 Union u = new Union(toString());
176                 Sequence ret = left.buildSequence(bc);
177                 Sequence rs = right.buildSequence(bc);
178                 rs.lame = true;
179                 if (not) ret = ret.not(rs);
180                 else     ret = ret.and(rs);
181                 u.add(rs);
182                 u.add(ret);
183                 return Sequence.singleton(u);
184             }
185             public MetaAnd(MetaSequence left, MetaSequence right, boolean not) {
186                 this.left = left;
187                 this.right = right;
188                 this.not = not;
189             }
190             public String toString() { return left + " &"+(not?"~":"")+" "+right; }
191         }
192
193         public static class MetaConjunct implements MetaSequence {
194             public boolean negated = false;
195             public MetaClause[] elements;
196             public MetaClause followedBy = null;
197             public String tag;
198             public MetaClause separator;
199             public Sequence buildSequence(BuildContext bc) {
200                 Element[] els = new Element[elements.length + (separator==null?0:(elements.length-1))];
201                 boolean[] drops = new boolean[elements.length + (separator==null?0:(elements.length-1))];
202                 boolean unwrap = false;
203                 boolean dropAll = false;
204                 if (tag!=null && tag.equals("[]")) unwrap = true;
205                 if (tag!=null && "()".equals(tag)) dropAll=true;
206                 for(int i=0; i<elements.length; i++) {
207                     int j = separator==null ? i : i*2;
208                     els[j] = elements[i].build(bc);
209                     drops[j] = elements[i].drop;
210                     if (separator!=null && i<elements.length-1) {
211                         els[j+1] = separator.build(bc);
212                         drops[j+1] = true;
213                     }
214                 }
215                 Sequence ret = null;
216                 if (dropAll)     ret = Sequence.drop(els, false);
217                 else if (unwrap) ret = Sequence.unwrap(els, /*repeatTag FIXME*/null, drops);
218                 else if (tag!=null) ret = Sequence.rewritingSequence(tag, els, new Object[els.length], drops);
219                 else {
220                     int idx = -1;
221                     for(int i=0; i<els.length; i++)
222                         if (!drops[i])
223                             if (idx==-1) idx = i;
224                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
225                     if (idx != -1) ret = Sequence.singleton(els, idx);
226                     else           ret = Sequence.drop(els, false);
227                 }
228                 if (this.followedBy != null) ret.follow = new Hack(new Infer(this.followedBy.build(bc)));
229                 return ret;
230             }
231             private MetaConjunct(Tree<String> t) {
232                 //System.err.println("MetaConjunct("+t+")");
233                 elements = new MetaClause[t.numChildren()];
234                 int i = 0; for(Tree<String> tt : t)
235                     elements[i++] = MetaClause.make(tt, this);
236             }
237             public String toString() {
238                 String ret = (tag==null ? "" : (tag+":: ")) + (negated ? "~" : "");
239                 if (elements.length > 1) ret += "(";
240                 for(MetaClause mc : elements) ret += (" " + mc + " ");
241                 if (separator != null) ret += " /" + separator;
242                 if (followedBy != null) ret += " -> " + followedBy;
243                 if (elements.length > 1) ret += ")";
244                 return ret;
245             }
246             public static MetaConjunct make(Tree<String> t) {
247                 //System.err.println("MetaConjunct.make("+t+")");
248                 if ("/".equals(t.head())) {
249                     MetaConjunct ret = make(t.child(0));
250                     ret.separator = MetaClause.make(t.child(1), ret);
251                     return ret;
252                 }
253                 if ("->".equals(t.head())) {
254                     MetaConjunct ret = make(t.child(0));
255                     ret.followedBy = MetaClause.make(t.child(1), ret);
256                     return ret;
257                 }
258                 if ("::".equals(t.head())) {
259                     MetaConjunct ret = make(t.child(1));
260                     ret.tag = string(t.child(0));
261                     return ret;
262                 }
263                 if ("ps".equals(t.head())) {
264                     return new MetaConjunct(t.child(0));
265                 }
266                 return new MetaConjunct(t);
267             }
268         }
269
270         public static abstract class MetaClause {
271             public String label = null;
272             public boolean drop = false;
273             public boolean lift = false;
274             public abstract Element build(BuildContext bc);
275             public static MetaClause make(Tree<String> t, MetaConjunct c) {
276                 //System.err.println("MetaClause.make("+t+")");
277                 if (t==null) return new MetaEpsilon();
278                 if (t.head()==null) return new MetaEpsilon();
279                 if (t.head().equals("{")) throw new Error("metatree: " + t);
280                 if (t.head().equals("*")) return new MetaRepeat(make(t.child(0), c), false, null, true, true);
281                 if (t.head().equals("+")) return new MetaRepeat(make(t.child(0), c), false, null, false, true);
282                 if (t.head().equals("?")) return new MetaRepeat(make(t.child(0), c), false, null, true, false);
283                 if (t.head().equals("**")) return new MetaRepeat(make(t.child(0), c), true, null, true, true);
284                 if (t.head().equals("++")) return new MetaRepeat(make(t.child(0), c), true, null, false, true);
285                 if (t.head().equals("*/")) return new MetaRepeat(make(t.child(0), c), false, make(t.child(1), c), true, true);
286                 if (t.head().equals("+/")) return new MetaRepeat(make(t.child(0), c), false, make(t.child(1), c), false, true);
287                 if (t.head().equals("**/")) return new MetaRepeat(make(t.child(0), c), true, make(t.child(1), c), true, true);
288                 if (t.head().equals("++/")) return new MetaRepeat(make(t.child(0), c), true, make(t.child(1), c), false, true);
289                 if (t.head().equals("()")) return new MetaEpsilon();
290                 if (t.head().equals("[")) return new MetaRange(t.child(0));
291                 if (t.head().equals("literal")) return new MetaStringLiteral(t.child(0));
292                 if (t.head().equals("nonTerminal")) return new MetaNonterminalReference(t.child(0));
293                 if (t.head().equals(")")) return new MetaSelfReference();
294                 if (t.head().equals("(")) return new MetaParens(t.child(0));
295                 if (t.head().equals("~")) return new MetaInvert(t.child(0), c);
296                 if (t.head().equals("!")) { MetaClause mc = make(t.child(0), c); mc.drop = true; return mc; }
297                 if (t.head().equals("^")) { c.tag = string(t.child(0)); return new MetaStringLiteral(t.child(0)); }
298                 if (t.head().equals("^^")) throw new Error("carets: " + t);
299                 throw new Error("unknown: " + t);
300             }
301             public static class MetaRepeat extends MetaClause {
302                 public MetaClause element, separator;
303                 public boolean maximal, zero, many;
304                 public Element build(BuildContext bc) {
305                     return new Repeat(element.build(bc), zero, many, separator==null?null:separator.build(bc), maximal);
306                 }
307                 public MetaRepeat(MetaClause element, boolean maximal, MetaClause separator, boolean zero, boolean many) {
308                     this.separator = separator;
309                     this.element = element;
310                     this.maximal = maximal;
311                     this.zero = zero;
312                     this.many = many;
313                 }
314                 public String toString() {
315                     return element+
316                         ((zero&&!many)?"?":zero?"*":"+")+
317                         (!maximal?"":zero?"*":"+")+
318                         (separator==null?"":(" /"+separator));
319                 }
320             }
321             public static class MetaParens extends MetaClause {
322                 public MetaUnion body;
323                 public MetaParens(Tree<String> t) { this.body = rhs(t); }
324                 public String toString() { return "( " + body + " )"; }
325                 public Element build(BuildContext bc) { return body.buildAnon(bc); }
326             }
327             /*
328             public static class MetaTree extends MetaClause {
329                 public MetaConjunct body;
330                 public MetaTree(Tree<String> t) { this.body = MetaConjunct.make(t); }
331                 public String toString() { return "{ " + body + " }"; }
332                 public Element build(BuildContext bc) {
333                     return new Union("{}");// body.buildSequence();
334                 }
335             }
336             */
337             public static class MetaEpsilon extends MetaClause {
338                 public String toString() { return "()"; }
339                 public Element build(BuildContext bc) { return Union.epsilon; }
340             }
341             public static class MetaRange extends MetaClause {
342                 Range.Set range = new Range.Set();
343                 public String toString() { return range.toString(); }
344                 public Element build(BuildContext bc) { return set(range); }
345                 public MetaRange(Tree<String> t) {
346                     for(Tree<String> tt : t) {
347                         if (tt.head().equals("range")) {
348                             range.add(tt.child(0).head().charAt(0));
349                         } else if (tt.head().equals("-")) {
350                             range.add(new Range(string(tt.child(0)).charAt(0),
351                                                 string(tt.child(1)).charAt(0)));
352                         }
353                     }
354                 }
355             }
356             public static class MetaStringLiteral extends MetaClause {
357                 public String literal;
358                 public Element build(BuildContext bc) { return string(literal); }
359                 public MetaStringLiteral(Tree<String> literal) { this.literal = string(literal); this.drop = true; }
360                 public String toString() { return "\""+StringUtil.escapify(literal, "\"\r\n\\")+"\""; }
361             }
362             public static class MetaNonterminalReference extends MetaClause {
363                 public String name;
364                 public MetaNonterminalReference(Tree<String> name) { this.name = string(name); }
365                 public Element build(BuildContext bc) { return bc.build(name); }
366                 public String toString() { return name; } 
367             }
368             public static class MetaSelfReference extends MetaClause {
369                 public String toString() { return "(*)"; } 
370                 public Element build(BuildContext bc) { return new Union("(*)"); /* FIXME */ }
371             }
372             public static class MetaInvert extends MetaClause {
373                 public MetaClause element;
374                 public MetaInvert(Tree<String> t, MetaConjunct c) { this.element = make(t, c); }
375                 public String toString() { return "~"+element; }
376                 public Element build(BuildContext bc) { return new Hack(new Invert(new Infer(element.build(bc)))); }
377             }
378         }
379
380     }
381
382     public static void main(String[] args) throws Exception {
383         if (args.length != 2) {
384             System.err.println("usage: java " + MetaGrammar.class.getName() + " grammarfile.g com.yourdomain.package.ClassName");
385             System.exit(-1);
386         }
387         //StringBuffer sbs = new StringBuffer();
388         //((MetaGrammar)new MetaGrammar().walk(meta)).nt.get("e").toString(sbs);
389         //System.err.println(sbs);
390         String className   = args[1].substring(args[1].lastIndexOf('.')+1);
391         String packageName = args[1].substring(0, args[1].lastIndexOf('.'));
392         String fileName    = packageName.replace('.', '/') + "/" + className + ".java";
393
394         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
395         StringBuffer out = new StringBuffer();
396
397         boolean skip = false;
398         for(String s = br.readLine(); s != null; s = br.readLine()) {
399             if (s.indexOf("DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) skip = true;
400             if (s.indexOf("DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) break;
401             if (!skip) out.append(s+"\n");
402         }
403
404         out.append("\n        // DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED\n");
405         Tree<String> ts = new CharParser(MetaGrammar.make()).parse(new FileInputStream(args[0])).expand1();
406
407         //Forest<String> fs = new CharParser(make()).parse(new FileInputStream(args[0]));
408         //System.out.println(fs.expand1());
409
410         //GraphViz gv = new GraphViz();
411         //fs.toGraphViz(gv);
412         //FileOutputStream fox = new FileOutputStream("out.dot");
413         //gv.dump(fox);
414         //fox.close();
415
416         ts.toJava(out);
417         out.append("\n        // DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED\n");
418
419         for(String s = br.readLine(); s != null; s = br.readLine()) out.append(s+"\n");
420         br.close();
421
422         OutputStream os = new FileOutputStream(fileName);
423         PrintWriter p = new PrintWriter(new OutputStreamWriter(os));
424         p.println(out.toString());
425         p.flush();
426         os.close();
427     }
428 }