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