1 package edu.berkeley.sbp.misc;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
8 public class MetaGrammar extends StringWalker {
10 public static Object repeatTag = null;
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(); }
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; }
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(); }
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);
43 ////////////////////////////////////////////////////////////////////////////////
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); }
49 private MetaGrammar() { }
51 public static String string(Iterable<Tree<String>> children) {
53 for(Tree<String> t : children) ret += string(t);
56 public static String string(Tree<String> tree) {
58 if (tree.head()!=null) ret += tree.head();
59 ret += string(tree.children());
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) {
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);
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));
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);
86 public String toString() {
88 for(MetaNonterminal mnt : this.values()) ret += mnt + "\n";
92 public static class MetaNonterminal {
95 public MetaNonterminal(Tree<String> tree) {
96 name = string(tree.child(0));
97 rhs = rhs(tree.child(1));
99 public String toString() { return name + " = " + rhs; }
100 public Union build(BuildContext bc) { return rhs.build(bc, name); }
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);
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);
113 public Union buildAnon(BuildContext bc) {
115 for(int i=0; i<sequences.length; i++)
116 s += (i>0?"\n "+(prioritized?">":"|")+" ":"")+sequences[i].buildSequence(bc);
119 public Union build(BuildContext bc, String name) {
120 Union u = bc.get(name);
121 if (u != null) return u;
124 HashSet<Sequence> seqs = new HashSet<Sequence>();
125 for(MetaSequence s : sequences) {
126 Sequence seq = s.buildSequence(bc);
130 for(Sequence seqprev : seqs)
131 seq = seq.not(seqprev);
138 public MetaUnion(Tree<String> t, boolean prioritized) {
139 //System.err.println("metaunion: " + t);
140 this.prioritized = prioritized;
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);
148 public String toString() {
150 for(int i=0; i<sequences.length; i++) {
152 if (i<sequences.length-1)
153 ret += (prioritized ? "\n > " : "\n | ");
159 public interface MetaSequence {
160 public abstract Sequence buildSequence(BuildContext bc);
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);
170 public static class MetaAnd implements MetaSequence {
174 public Sequence buildSequence(BuildContext bc) {
175 Union u = new Union(toString());
176 Sequence ret = left.buildSequence(bc);
177 Sequence rs = right.buildSequence(bc);
179 if (not) ret = ret.not(rs);
180 else ret = ret.and(rs);
183 return Sequence.singleton(u);
185 public MetaAnd(MetaSequence left, MetaSequence right, boolean not) {
190 public String toString() { return left + " &"+(not?"~":"")+" "+right; }
193 public static class MetaConjunct implements MetaSequence {
194 public boolean negated = false;
195 public MetaClause[] elements;
196 public MetaClause followedBy = null;
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);
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);
221 for(int i=0; i<els.length; 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);
228 if (this.followedBy != null) ret.follow = new Hack(new Infer(this.followedBy.build(bc)));
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);
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 += ")";
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);
253 if ("->".equals(t.head())) {
254 MetaConjunct ret = make(t.child(0));
255 ret.followedBy = MetaClause.make(t.child(1), ret);
258 if ("::".equals(t.head())) {
259 MetaConjunct ret = make(t.child(1));
260 ret.tag = string(t.child(0));
263 if ("ps".equals(t.head())) {
264 return new MetaConjunct(t.child(0));
266 return new MetaConjunct(t);
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);
301 public static class MetaRepeat extends MetaClause {
302 public MetaClause element, separator;
303 public boolean maximal, zero, many;
304 public Element build(BuildContext bc) {
306 ? new Repeat(element.build(bc), zero, many, separator==null?null:separator.build(bc), null)
308 ? new Repeat.Maximal(element.build(bc), zero, many, null)
309 : new Repeat.Maximal(element.build(bc), zero, many, separator.build(bc), null);
311 public MetaRepeat(MetaClause element, boolean maximal, MetaClause separator, boolean zero, boolean many) {
312 this.separator = separator;
313 this.element = element;
314 this.maximal = maximal;
318 public String toString() {
320 ((zero&&!many)?"?":zero?"*":"+")+
321 (!maximal?"":zero?"*":"+")+
322 (separator==null?"":(" /"+separator));
325 public static class MetaParens extends MetaClause {
326 public MetaUnion body;
327 public MetaParens(Tree<String> t) { this.body = rhs(t); }
328 public String toString() { return "( " + body + " )"; }
329 public Element build(BuildContext bc) { return body.buildAnon(bc); }
332 public static class MetaTree extends MetaClause {
333 public MetaConjunct body;
334 public MetaTree(Tree<String> t) { this.body = MetaConjunct.make(t); }
335 public String toString() { return "{ " + body + " }"; }
336 public Element build(BuildContext bc) {
337 return new Union("{}");// body.buildSequence();
341 public static class MetaEpsilon extends MetaClause {
342 public String toString() { return "()"; }
343 public Element build(BuildContext bc) { return Union.epsilon; }
345 public static class MetaRange extends MetaClause {
346 Range.Set range = new Range.Set();
347 public String toString() { return range.toString(); }
348 public Element build(BuildContext bc) { return set(range); }
349 public MetaRange(Tree<String> t) {
350 for(Tree<String> tt : t) {
351 if (tt.head().equals("range")) {
352 range.add(tt.child(0).head().charAt(0));
353 } else if (tt.head().equals("-")) {
354 range.add(new Range(string(tt.child(0)).charAt(0),
355 string(tt.child(1)).charAt(0)));
360 public static class MetaStringLiteral extends MetaClause {
361 public String literal;
362 public Element build(BuildContext bc) { return string(literal); }
363 public MetaStringLiteral(Tree<String> literal) { this.literal = string(literal); this.drop = true; }
364 public String toString() { return "\""+StringUtil.escapify(literal, "\"\r\n\\")+"\""; }
366 public static class MetaNonterminalReference extends MetaClause {
368 public MetaNonterminalReference(Tree<String> name) { this.name = string(name); }
369 public Element build(BuildContext bc) { return bc.build(name); }
370 public String toString() { return name; }
372 public static class MetaSelfReference extends MetaClause {
373 public String toString() { return "(*)"; }
374 public Element build(BuildContext bc) { return new Union("(*)"); /* FIXME */ }
376 public static class MetaInvert extends MetaClause {
377 public MetaClause element;
378 public MetaInvert(Tree<String> t, MetaConjunct c) { this.element = make(t, c); }
379 public String toString() { return "~"+element; }
380 public Element build(BuildContext bc) { return new Hack(new Invert(new Infer(element.build(bc)))); }
386 public static void main(String[] args) throws Exception {
387 if (args.length != 2) {
388 System.err.println("usage: java " + MetaGrammar.class.getName() + " grammarfile.g com.yourdomain.package.ClassName");
391 //StringBuffer sbs = new StringBuffer();
392 //((MetaGrammar)new MetaGrammar().walk(meta)).nt.get("e").toString(sbs);
393 //System.err.println(sbs);
394 String className = args[1].substring(args[1].lastIndexOf('.')+1);
395 String packageName = args[1].substring(0, args[1].lastIndexOf('.'));
396 String fileName = packageName.replace('.', '/') + "/" + className + ".java";
398 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
399 StringBuffer out = new StringBuffer();
401 boolean skip = false;
402 for(String s = br.readLine(); s != null; s = br.readLine()) {
403 if (s.indexOf("DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) skip = true;
404 if (s.indexOf("DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) break;
405 if (!skip) out.append(s+"\n");
408 out.append("\n // DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED\n");
409 Tree<String> ts = new CharParser(MetaGrammar.make()).parse(new FileInputStream(args[0])).expand1();
411 //Forest<String> fs = new CharParser(make()).parse(new FileInputStream(args[0]));
412 //System.out.println(fs.expand1());
414 //GraphViz gv = new GraphViz();
416 //FileOutputStream fox = new FileOutputStream("out.dot");
421 out.append("\n // DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED\n");
423 for(String s = br.readLine(); s != null; s = br.readLine()) out.append(s+"\n");
426 OutputStream os = new FileOutputStream(fileName);
427 PrintWriter p = new PrintWriter(new OutputStreamWriter(os));
428 p.println(out.toString());