73c6fdd4fcfceea9e90ae4218ace94fcd4e328dd
[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                     System.err.println("resolvetag " + tag + " => " + ret);
214                 } else {
215                     int idx = -1;
216                     for(int i=0; i<els.length; i++)
217                         if (!drops[i])
218                             if (idx==-1) idx = i;
219                             else throw new Error("multiple non-dropped elements in sequence: " + Sequence.drop(els,false));
220                     if (idx != -1) ret = Sequence.singleton(els, idx);
221                     else           ret = Sequence.drop(els, false);
222                 }
223                 if (this.followedBy != null)
224                     ret.follow = infer(this.followedBy.build(bc));
225                 return ret;
226             }
227             private Conjunct(Tree<String> t) {
228                 elements = new MetaClause[t.numChildren()];
229                 int i = 0; for(Tree<String> tt : t)
230                     elements[i++] = makeMetaClause(tt, this);
231             }
232             public String toString() {
233                 String ret = (tag==null ? "" : (tag+":: ")) + (negated ? "~" : "");
234                 if (elements.length > 1) ret += "(";
235                 for(MetaClause mc : elements) ret += (" " + mc + " ");
236                 if (separator != null) ret += " /" + separator;
237                 if (followedBy != null) ret += " -> " + followedBy;
238                 if (elements.length > 1) ret += ")";
239                 return ret;
240             }
241         }
242             public Conjunct makeConjunct(Tree<String> t) {
243                 //System.err.println("makeConjunct("+t+")");
244                 if ("/".equals(t.head())) {
245                     Conjunct ret = makeConjunct(t.child(0));
246                     ret.separator = makeMetaClause(t.child(1), ret);
247                     return ret;
248                 }
249                 if ("->".equals(t.head())) {
250                     Conjunct ret = makeConjunct(t.child(0));
251                     ret.followedBy = makeMetaClause(t.child(1), ret);
252                     return ret;
253                 }
254                 if ("::".equals(t.head())) {
255                     Conjunct ret = makeConjunct(t.child(1));
256                     ret.tag = string(t.child(0));
257                     return ret;
258                 }
259                 if ("ps".equals(t.head())) {
260                     return new Conjunct(t.child(0));
261                 }
262                 return new Conjunct(t);
263             }
264
265             public MetaClause makeMetaClause(Tree<String> t, Conjunct c) {
266                 //System.err.println("MetaClause.makeMetaClause("+t+")");
267                 if (t==null) return new Epsilon();
268                 if (t.head()==null) return new Epsilon();
269                 if (t.head().equals("{")) throw new Error("metatree: " + t);
270                 if (t.head().equals("*")) return new MetaRepeat(makeMetaClause(t.child(0), c), false, null, true, true);
271                 if (t.head().equals("+")) return new MetaRepeat(makeMetaClause(t.child(0), c), false, null, false, true);
272                 if (t.head().equals("?")) return new MetaRepeat(makeMetaClause(t.child(0), c), false, null, true, false);
273                 if (t.head().equals("**")) return new MetaRepeat(makeMetaClause(t.child(0), c), true, null, true, true);
274                 if (t.head().equals("++")) return new MetaRepeat(makeMetaClause(t.child(0), c), true, null, false, true);
275                 if (t.head().equals("*/")) return new MetaRepeat(makeMetaClause(t.child(0), c), false, makeMetaClause(t.child(1), c), true, true);
276                 if (t.head().equals("+/")) return new MetaRepeat(makeMetaClause(t.child(0), c), false, makeMetaClause(t.child(1), c), false, true);
277                 if (t.head().equals("**/")) return new MetaRepeat(makeMetaClause(t.child(0), c), true, makeMetaClause(t.child(1), c), true, true);
278                 if (t.head().equals("++/")) return new MetaRepeat(makeMetaClause(t.child(0), c), true, makeMetaClause(t.child(1), c), false, true);
279                 if (t.head().equals("()")) return new Epsilon();
280                 if (t.head().equals("[")) return new MetaRange(t.child(0));
281                 if (t.head().equals("literal")) return new StringLiteral(t.child(0));
282                 if (t.head().equals("nonTerminal")) return new NonTerminalReference(t.child(0));
283                 if (t.head().equals(")")) return new SelfReference();
284                 if (t.head().equals("(")) return new Parens(t.child(0));
285                 if (t.head().equals("~")) return new MetaInvert(t.child(0), c);
286                 if (t.head().equals("!")) { MetaClause mc = makeMetaClause(t.child(0), c); mc.drop = true; return mc; }
287                 if (t.head().equals("^")) { c.tag = string(t.child(0)); return new StringLiteral(t.child(0)); }
288                 if (t.head().equals("^^")) throw new Error("carets: " + t);
289                 if (t.head().equals(":")) {
290                     String name = string(t.child(0));
291                     MetaClause clause = makeMetaClause(t.child(1), c);
292                     c.addNamedClause(name, clause);
293                     return clause;
294                 }
295                 throw new Error("unknown: " + t);
296             }
297
298         public abstract class MetaClause {
299             public String label = null;
300             public boolean drop = false;
301             public boolean lift = false;
302             public abstract Element build(BuildContext bc);
303         }
304             public class MetaRepeat extends MetaClause {
305                 public MetaClause element, separator;
306                 public boolean maximal, zero, many;
307                 public Element build(BuildContext bc) {
308                     return !maximal
309                         ? (separator==null
310                            ? Sequence.repeat(element.build(bc), zero, many, null, repeatTag())
311                            : Sequence.repeat(element.build(bc), zero, many, separator.build(bc), repeatTag()))
312                         : (separator==null
313                            ? Sequence.repeatMaximal(infer(element.build(bc)), zero, many, repeatTag())
314                            : Sequence.repeatMaximal(element.build(bc), zero, many, infer(separator.build(bc)), repeatTag()));
315                 }
316                 public MetaRepeat(MetaClause element, boolean maximal, MetaClause separator, boolean zero, boolean many) {
317                     this.separator = separator;
318                     this.element = element;
319                     this.maximal = maximal;
320                     this.zero = zero;
321                     this.many = many;
322                 }
323                 public String toString() {
324                     return element+
325                         ((zero&&!many)?"?":zero?"*":"+")+
326                         (!maximal?"":zero?"*":"+")+
327                         (separator==null?"":(" /"+separator));
328                 }
329             }
330         public class Epsilon extends MetaClause {
331             public String toString() { return "()"; }
332             public Element build(BuildContext bc) { return Union.epsilon; }
333         }
334             public class Parens extends MetaClause {
335                 public MetaUnion body;
336                 public Parens(Tree<String> t) { this.body = rhs(t); }
337                 public String toString() { return "( " + body + " )"; }
338                 public Element build(BuildContext bc) { return body.buildAnon(bc); }
339             }
340             /*
341             public static class MetaTree extends MetaClause {
342                 public Conjunct body;
343                 public MetaTree(Tree<String> t) { this.body = makeConjunct(t); }
344                 public String toString() { return "{ " + body + " }"; }
345                 public Element build(BuildContext bc) {
346                     return new Union("{}");// body.buildSequence();
347                 }
348             }
349             */
350             public class MetaRange extends MetaClause {
351                 Range.Set range = new Range.Set();
352                 public String toString() { return range.toString(); }
353                 public Element build(BuildContext bc) { return set(range); }
354                 public MetaRange(Tree<String> t) {
355                     for(Tree<String> tt : t) {
356                         if (tt.head().equals("range")) {
357                             range.add(tt.child(0).head().charAt(0));
358                         } else if (tt.head().equals("-")) {
359                             range.add(new Range(string(tt.child(0)).charAt(0),
360                                                 string(tt.child(1)).charAt(0)));
361                         }
362                     }
363                 }
364             }
365             public class StringLiteral extends MetaClause {
366                 public String literal;
367                 public Element build(BuildContext bc) { return string(literal); }
368                 public StringLiteral(Tree<String> literal) { this.literal = string(literal); this.drop = true; }
369                 public String toString() { return "\""+StringUtil.escapify(literal, "\"\r\n\\")+"\""; }
370             }
371             public class NonTerminalReference extends MetaClause {
372                 public String name;
373                 public NonTerminalReference(Tree<String> name) { this.name = string(name); }
374                 public Element build(BuildContext bc) { return bc.build(name); }
375                 public String toString() { return name; } 
376             }
377             public class SelfReference extends MetaClause {
378                 public String toString() { return "(*)"; } 
379                 public Element build(BuildContext bc) { return new Union("(*)"); /* FIXME */ }
380             }
381             public class MetaInvert extends MetaClause {
382                 public MetaClause element;
383                 public MetaInvert(Tree<String> t, Conjunct c) { this.element = makeMetaClause(t, c); }
384                 public String toString() { return "~"+element; }
385                 public Element build(BuildContext bc) { return infer((Topology<Character>)Atom.toAtom(element.build(bc)).complement()); }
386             }
387
388     }
389
390     public static void main(String[] args) throws Exception {
391         if (args.length != 2) {
392             System.err.println("usage: java " + MetaGrammar.class.getName() + " grammarfile.g com.yourdomain.package.ClassName");
393             System.exit(-1);
394         }
395         //StringBuffer sbs = new StringBuffer();
396         //((MetaGrammar)new MetaGrammar().walk(meta)).nt.get("e").toString(sbs);
397         //System.err.println(sbs);
398         String className   = args[1].substring(args[1].lastIndexOf('.')+1);
399         String packageName = args[1].substring(0, args[1].lastIndexOf('.'));
400         String fileName    = packageName.replace('.', '/') + "/" + className + ".java";
401
402         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
403         StringBuffer out = new StringBuffer();
404
405         boolean skip = false;
406         for(String s = br.readLine(); s != null; s = br.readLine()) {
407             if (s.indexOf("DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) skip = true;
408             if (s.indexOf("DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) break;
409             if (!skip) out.append(s+"\n");
410         }
411
412         out.append("\n        // DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED\n");
413         Tree<String> ts = new CharParser(MetaGrammar.make()).parse(new FileInputStream(args[0])).expand1();
414
415         //Forest<String> fs = new CharParser(make()).parse(new FileInputStream(args[0]));
416         //System.out.println(fs.expand1());
417
418         //GraphViz gv = new GraphViz();
419         //fs.toGraphViz(gv);
420         //FileOutputStream fox = new FileOutputStream("out.dot");
421         //gv.dump(fox);
422         //fox.close();
423
424         ts.toJava(out);
425         out.append("\n        // DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED\n");
426
427         for(String s = br.readLine(); s != null; s = br.readLine()) out.append(s+"\n");
428         br.close();
429
430         OutputStream os = new FileOutputStream(fileName);
431         PrintWriter p = new PrintWriter(new OutputStreamWriter(os));
432         p.println(out.toString());
433         p.flush();
434         os.close();
435     }
436
437 }