3420ad5ca328f4c2b9692489313a1c39304a43e0
[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     public static Union make() throws Exception { return make(MetaGrammarTree.meta, "s"); }
13     public static Union make(Tree<String> tree, String nt) throws Exception {
14         Meta.MetaGrammarFile mgf = new Meta().new MetaGrammarFile(tree);
15         BuildContext bc = new BuildContext(mgf);
16         return mgf.get(nt).build(bc);
17     }
18
19     ////////////////////////////////////////////////////////////////////////////////
20
21     private static Element  set(Range.Set r) { return CharRange.set(r); }
22     private static Element  string(String s) { return CharRange.string(s); }
23     private static Atom infer(Element e)  { return infer((Topology<Character>)Atom.toAtom(e)); }
24     private static Atom infer(Topology<Character> t) { return new CharRange(new CharTopology(t)); }
25
26     private MetaGrammar() { }
27
28     public static String string(Iterable<Tree<String>> children) {
29         String ret = "";
30         for(Tree<String> t : children) ret += string(t);
31         return ret;
32     }
33     public static String string(Tree<String> tree) {
34         String ret = "";
35         if (tree.head()!=null) ret += tree.head();
36         ret += string(tree.children());
37         return ret;
38     }
39
40     public static class BuildContext extends HashMap<String,Union> {
41         private final Meta.MetaGrammarFile mgf;
42         public Meta.NonTerminal currentNonTerminal;
43         public BuildContext(Meta.MetaGrammarFile mgf) { this.mgf = mgf; }
44         public Union build(String s) {
45             Union ret = get(s);
46             if (ret != null) return ret;
47             Meta.NonTerminal mnt = mgf.get(s);
48             if (mnt==null) throw new Error("undeclared nonterminal \""+s+"\"");
49             return mnt.build(this);
50         }
51     }
52
53     public static class Meta {
54         public Sequence resolveTag(String s, String nonTerminalName, Element[] els, Object[] labels, boolean [] drops) {
55             return Sequence.rewritingSequence(s, els, labels, drops);
56         }
57         public class MetaGrammarFile extends HashMap<String,NonTerminal> {
58             public MetaGrammarFile(Tree<String> tree) {
59                 if (!tree.head().equals("grammar")) throw new Error();
60                 for(Tree<String> nt : tree.child(0))
61                     add(new NonTerminal(nt));
62             }
63             private void add(NonTerminal mnt) {
64                 if (this.get(mnt.name)!=null) throw new Error("duplicate definition of nonterminal \""+mnt.name+"\"");
65                 this.put(mnt.name, mnt);
66             }
67             public String toString() {
68                 String ret = "";
69                 for(NonTerminal mnt : this.values()) ret += mnt + "\n";
70                 return ret;
71             }
72         }
73         public class NonTerminal {
74             public String    name;
75             public MetaUnion rhs;
76             public NonTerminal(Tree<String> tree) {
77                 name = string(tree.child(0));
78                 rhs = rhs(tree.child(1));
79             }
80             public String toString() { return name + " = " + rhs; }
81             public Union build(BuildContext bc) {
82                 NonTerminal ont = bc.currentNonTerminal;
83                 bc.currentNonTerminal = this;
84                 try {
85                     return rhs.build(bc, name);
86                 } finally {
87                     bc.currentNonTerminal = ont;
88                 }
89             }
90         }
91         public MetaUnion rhs(Tree<String> t) {
92             return t.numChildren()==1
93                 ? new MetaUnion(t.child(0), false)
94                 : new MetaUnion(t, true);
95         }
96         public class MetaUnion implements MetaSequence {
97             public boolean prioritized;
98             public MetaSequence[] sequences;
99             public Sequence buildSequence(BuildContext bc) {
100                 return Sequence.singleton(new Element[] { buildAnon(bc) }, 0);
101             }
102             public Union buildAnon(BuildContext bc) {
103                 String s = "";
104                 for(int i=0; i<sequences.length; i++)
105                     s += (i>0?"\n                "+(prioritized?">":"|")+" ":"")+sequences[i].buildSequence(bc);
106                 return build(bc, s);
107             }
108             public Union build(BuildContext bc, String name) {
109                 Union u = bc.get(name);
110                 if (u != null) return u;
111                 u = new Union(name);
112                 bc.put(name, u);
113                 HashSet<Sequence> seqs = new HashSet<Sequence>();
114                 for(MetaSequence s : sequences) {
115                     Sequence seq = s.buildSequence(bc);
116                     if (seq != null) {
117                         Sequence oseq = seq;
118                         if (prioritized)
119                             for(Sequence seqprev : seqs)
120                                 seq = seq.not(seqprev);
121                         u.add(seq);
122                         seqs.add(seq);
123                     }
124                 }
125                 return u;
126             }
127             public MetaUnion(Tree<String> t, boolean prioritized) {
128                 this.prioritized = prioritized;
129                 int i = 0;
130                 this.sequences = new MetaSequence[t.numChildren()];
131                 for(Tree<String> tt : t)
132                     sequences[i++] = prioritized
133                         ? new MetaUnion(tt, false)
134                         : makeMetaSequence(tt);
135             }
136             public String toString() {
137                 String ret = "\n     ";
138                 for(int i=0; i<sequences.length; i++) {
139                     ret += sequences[i];
140                     if (i<sequences.length-1)
141                         ret += (prioritized ? "\n    > " : "\n    | ");
142                 }
143                 return ret;
144             }
145         }
146
147         public interface MetaSequence {
148             public abstract Sequence buildSequence(BuildContext bc);
149         }
150
151         public MetaSequence makeMetaSequence(Tree<String> t) {
152             if ("psx".equals(t.head())) return makeConjunct(t.child(0));
153             if (t.head().equals("&"))  return new MetaAnd(makeMetaSequence(t.child(0)), makeConjunct(t.child(1)), false);
154             if (t.head().equals("&~")) return new MetaAnd(makeMetaSequence(t.child(0)), makeConjunct(t.child(1)), true);
155             return null;
156         }
157
158         public class MetaAnd implements MetaSequence {
159             boolean not;
160             MetaSequence left;
161             MetaSequence right;
162             public Sequence buildSequence(BuildContext bc) {
163                 Union u = new Union(toString());
164                 Sequence ret = left.buildSequence(bc);
165                 Sequence rs = right.buildSequence(bc);
166                 rs.lame = true;
167                 if (not) ret = ret.not(rs);
168                 else     ret = ret.and(rs);
169                 u.add(rs);
170                 u.add(ret);
171                 return Sequence.singleton(u);
172             }
173             public MetaAnd(MetaSequence left, MetaSequence right, boolean not) {
174                 this.left = left;
175                 this.right = right;
176                 this.not = not;
177             }
178             public String toString() { return left + " &"+(not?"~":"")+" "+right; }
179         }
180
181         public class Conjunct implements MetaSequence {
182             public boolean negated = false;
183             public MetaClause[] elements;
184             public HashMap<MetaClause,String> labelMap = new HashMap<MetaClause,String>();
185             public MetaClause followedBy = null;
186             public String tag;
187             public MetaClause separator;
188             public void addNamedClause(String name, MetaClause mc) {
189                 labelMap.put(mc, name);
190             }
191             public Sequence buildSequence(BuildContext bc) {
192                 Element[] els = new Element[elements.length + (separator==null?0:(elements.length-1))];
193                 boolean[] drops = new boolean[elements.length + (separator==null?0:(elements.length-1))];
194                 Object[] labels = new Object[els.length];
195                 boolean unwrap = false;
196                 boolean dropAll = false;
197                 if (tag!=null && tag.equals("[]")) unwrap = true;
198                 if (tag!=null && "()".equals(tag)) dropAll=true;
199                 for(int i=0; i<elements.length; i++) {
200                     int j = separator==null ? i : i*2;
201                     els[j] = elements[i].build(bc);
202                     labels[j] = labelMap.get(elements[i]);
203                     drops[j] = elements[i].drop;
204                     if (separator!=null && i<elements.length-1) {
205                         els[j+1] = separator.build(bc);
206                         drops[j+1] = true;
207                     }
208                 }
209                 Sequence ret = null;
210                 if (dropAll)     ret = Sequence.drop(els, false);
211                 else if (unwrap) ret = Sequence.unwrap(els, /*repeatTag FIXME*/null, drops);
212                 else if (tag!=null) {
213                     ret = resolveTag(tag, bc.currentNonTerminal==null ? null : bc.currentNonTerminal.name, els, labels, drops);
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, null)
311                            : Sequence.repeat(element.build(bc), zero, many, separator.build(bc), null))
312                         : (separator==null
313                            ? Sequence.repeatMaximal(infer(element.build(bc)), zero, many, null)
314                            : Sequence.repeatMaximal(element.build(bc), zero, many, infer(separator.build(bc)), null));
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 }