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 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);
17 ////////////////////////////////////////////////////////////////////////////////
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)); }
24 private MetaGrammar() { }
26 public static String string(Iterable<Tree<String>> children) {
28 for(Tree<String> t : children) ret += string(t);
31 public static String string(Tree<String> tree) {
33 if (tree.head()!=null) ret += tree.head();
34 ret += string(tree.children());
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) {
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);
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);
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));
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);
66 public String toString() {
68 for(NonTerminal mnt : this.values()) ret += mnt + "\n";
72 public class NonTerminal {
75 public NonTerminal(Tree<String> tree) {
76 name = string(tree.child(0));
77 rhs = rhs(tree.child(1));
79 public String toString() { return name + " = " + rhs; }
80 public Union build(BuildContext bc) {
81 NonTerminal ont = bc.currentNonTerminal;
82 bc.currentNonTerminal = this;
84 return rhs.build(bc, name);
86 bc.currentNonTerminal = ont;
90 public MetaUnion rhs(Tree<String> t) {
91 return t.numChildren()==1
92 ? new MetaUnion(t.child(0), false)
93 : new MetaUnion(t, true);
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);
101 public Union buildAnon(BuildContext bc) {
103 for(int i=0; i<sequences.length; i++)
104 s += (i>0?"\n "+(prioritized?">":"|")+" ":"")+sequences[i].buildSequence(bc);
107 public Union build(BuildContext bc, String name) {
108 Union u = bc.get(name);
109 if (u != null) return u;
112 HashSet<Sequence> seqs = new HashSet<Sequence>();
113 for(MetaSequence s : sequences) {
114 Sequence seq = s.buildSequence(bc);
118 for(Sequence seqprev : seqs)
119 seq = seq.not(seqprev);
126 public MetaUnion(Tree<String> t, boolean prioritized) {
127 this.prioritized = prioritized;
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);
135 public String toString() {
137 for(int i=0; i<sequences.length; i++) {
139 if (i<sequences.length-1)
140 ret += (prioritized ? "\n > " : "\n | ");
146 public interface MetaSequence {
147 public abstract Sequence buildSequence(BuildContext bc);
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);
157 public class MetaAnd implements MetaSequence {
161 public Sequence buildSequence(BuildContext bc) {
162 Union u = new Union(toString());
163 Sequence ret = left.buildSequence(bc);
164 Sequence rs = right.buildSequence(bc);
166 if (not) ret = ret.not(rs);
167 else ret = ret.and(rs);
170 return Sequence.singleton(u);
172 public MetaAnd(MetaSequence left, MetaSequence right, boolean not) {
177 public String toString() { return left + " &"+(not?"~":"")+" "+right; }
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;
186 public MetaClause separator;
187 public void addNamedClause(String name, MetaClause mc) {
188 labelMap.put(mc, name);
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);
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);
215 for(int i=0; i<els.length; 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);
222 if (this.followedBy != null)
223 ret.follow = infer(this.followedBy.build(bc));
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);
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 += ")";
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);
248 if ("->".equals(t.head())) {
249 Conjunct ret = makeConjunct(t.child(0));
250 ret.followedBy = makeMetaClause(t.child(1), ret);
253 if ("::".equals(t.head())) {
254 Conjunct ret = makeConjunct(t.child(1));
255 ret.tag = string(t.child(0));
258 if ("ps".equals(t.head())) {
259 return new Conjunct(t.child(0));
261 return new Conjunct(t);
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);
294 throw new Error("unknown: " + t);
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);
303 public class MetaRepeat extends MetaClause {
304 public MetaClause element, separator;
305 public boolean maximal, zero, many;
306 public Element build(BuildContext bc) {
309 ? Sequence.repeat(element.build(bc), zero, many, null, repeatTag())
310 : Sequence.repeat(element.build(bc), zero, many, separator.build(bc), repeatTag()))
312 ? Sequence.repeatMaximal(infer(element.build(bc)), zero, many, repeatTag())
313 : Sequence.repeatMaximal(element.build(bc), zero, many, infer(separator.build(bc)), repeatTag()));
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;
322 public String toString() {
324 ((zero&&!many)?"?":zero?"*":"+")+
325 (!maximal?"":zero?"*":"+")+
326 (separator==null?"":(" /"+separator));
329 public class Epsilon extends MetaClause {
330 public String toString() { return "()"; }
331 public Element build(BuildContext bc) { return Union.epsilon; }
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); }
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();
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)));
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\\")+"\""; }
370 public class NonTerminalReference extends MetaClause {
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; }
376 public class SelfReference extends MetaClause {
377 public String toString() { return "(*)"; }
378 public Element build(BuildContext bc) { return new Union("(*)"); /* FIXME */ }
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()); }
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");
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";
401 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
402 StringBuffer out = new StringBuffer();
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");
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();
414 //Forest<String> fs = new CharParser(make()).parse(new FileInputStream(args[0]));
415 //System.out.println(fs.expand1());
417 //GraphViz gv = new GraphViz();
419 //FileOutputStream fox = new FileOutputStream("out.dot");
424 out.append("\n // DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED\n");
426 for(String s = br.readLine(); s != null; s = br.readLine()) out.append(s+"\n");
429 OutputStream os = new FileOutputStream(fileName);
430 PrintWriter p = new PrintWriter(new OutputStreamWriter(os));
431 p.println(out.toString());