1 // Copyright 2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
5 package edu.berkeley.sbp.tib;
6 import edu.berkeley.sbp.*;
7 import edu.berkeley.sbp.misc.*;
8 import edu.berkeley.sbp.util.*;
9 import edu.berkeley.sbp.chr.*;
15 public static class Doc {
19 public static class kv { public String key; public Text[] val; }
20 public static class Header {
21 public void attrs(kv[] kvs) {
22 for(int i=0; i<kvs.length; i++)
23 System.out.println("key="+kvs[i].key+" val="+kvs[i].val);
26 public static class Body {
29 public static class Section { }
30 public static abstract class Text {
31 public static final Class[] subclasses = new Class[] { Chars.class, URL.class, Email.class };
33 public static class Chars extends Text { String chars; }
34 public static class Symbol extends Text { String chars; }
35 public static class Email extends Text { String user; Host host; }
36 public static interface Host { }
37 public static class DNS implements Host { String[] part; }
38 public static class IP implements Host { int a, b, c, d; }
39 public static class URL extends Text { String method; Host host; int port; String path; }
40 public static class Italic extends Text { Text body; }
42 public static void main(String[] s) throws Exception {
44 System.out.println("parsing " + s[0]);
45 Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
46 MetaGrammar gram = new Tib.Grammar(TibDoc.class);
47 gram = (MetaGrammar)gram.walk(res);
48 //System.out.println(gram);
49 Union mg = gram.done();
51 System.out.println("\nparsing " + s[1]);
52 Forest f = new CharParser(mg).parse(new Tib(new FileInputStream(s[1])));
53 //((Tree)new StringifyWalker().walk(f.expand1())).toPrettyString()
55 Doc doc = (Doc)new ReflectiveGrammar(TibDoc.class).build(f.expand1());
56 System.out.println(doc);
58 String st = new HTMLWalker().walk(f.expand1()).toString();
59 System.out.println(st);
60 FileOutputStream fos = new FileOutputStream("out.html");
61 PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
66 } catch (Ambiguous a) {
67 FileOutputStream fos = new FileOutputStream("/Users/megacz/Desktop/out.dot");
68 PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
69 GraphViz gv = new GraphViz();
70 a.ambiguity.toGraphViz(gv);
76 } catch (Exception e) {
81 public static class StringifyWalker extends ReflectiveWalker {
82 public Object walk(String head, Object[] children) {
83 if ("stringify".equals(head)) {
84 StringBuffer ret = new StringBuffer();
85 for(Tree<String> t : (Tree<String>)children[0]) ret.append(t);
86 return new Tree<String>(null, ret.toString());
88 if (children.length==0) return new Tree<String>(null, head, new Tree[0]);
89 return new Tree<String>(null, head, (Tree<String>[])Reflection.lub(children));
93 public static String join(String[] sa, String sep) {
94 StringBuffer ret = new StringBuffer();
97 if (!first) ret.append(sep);
101 return ret.toString();
104 public static class HTMLWalker extends ReflectiveWalker {
105 //public void header() { throw new Error(); }
106 public String li(Object o) { return "<li>"+o+"</li>"; }
107 public String li(Object a, Object o) { return "<li>"+o+"</li>"; }
108 public String ul(String[] li) { return "<ul>"+join(li,"")+"</ul>"; }
109 public String ol(String[] li) { return "<ol>"+join(li,"")+"</ol>"; }
110 public String hr() { return "\n<hr/>\n"; }
111 public String br() { return "\n<br/>\n"; }
112 public String it(Object o) { return "<i>"+o+"</i>"; }
113 public String tt(Object o) { return "<tt>"+o+"</tt>"; }
114 public String underline(Object o) { return "<ul>"+o+"</ul>"; }
115 public String p(Object o) { return "<p>"+o+"</p>"; }
116 public String smallcap(Object o) { return "<span style='font-variant: small-caps'>"+o+"</span>"; }
117 public String blockquote(Object o) { return "<blockquote>"+o+"</blockquote>"; }
118 public String superscript(Object o) { return "<sup>"+o+"</sup>"; }
119 public String subscript(Object o) { return "<sub>"+o+"</sub>"; }
120 public String bold(Object o) { return "<b>"+o+"</b>"; }
121 public String strikethrough(Object o) { throw new Error();/*return "<b>"+o+"</b>";*/ }
122 public Object top(Object o) { return "<html><body>"+o+"</body></html>"; }
123 public Object doc(Object header, Object body) { return body; }
124 public String text(Object[] body) {
125 StringBuffer ret = new StringBuffer();
126 for(Object o : body) { ret.append(o); ret.append(" "); }
127 return ret.toString();
129 public String body(String[] sections) { return join(sections, "\n\n"); }
130 public String domain(String[] parts) { return join(parts, "."); }
131 public String ip(String[] parts) { return join(parts, "."); }
132 public String emailaddr(String user, String host) {
133 return link(user+"@"+host, "mailto:"+user+"@"+host);
135 //public String url(String method) {
136 public String link(Object text, Object target) {
137 return "<a href='"+target+"'>"+text+"</a>";
139 public String section(Object header, Object[] body) {
140 StringBuffer ret = new StringBuffer();
143 for(Object o : body) ret.append(o);
144 return ret.toString();
146 private String escapify(Object o) {
147 String s = o==null ? "" : o.toString();
148 StringBuffer sb = new StringBuffer();
149 for(int i=0; i<s.length(); i++) {
150 switch(s.charAt(i)) {
151 case '&': sb.append("&"); break;
152 case '<': sb.append("<"); break;
153 case '>': sb.append(">"); break;
154 case '\'': sb.append("'"); break;
155 case '\"': sb.append("""); break;
156 default: sb.append(s.charAt(i)); break;
159 return sb.toString();
161 private Tree<String> lone(String s) {
162 return new Tree<String>(null, s, new Tree[0]);
164 public Object walk(Tree<String> t) {
165 String head = t.head();
166 if ("stringify".equals(head)) {
167 StringBuffer ret = new StringBuffer();
168 for(Tree<String> child : t.child(0)) ret.append(child);
169 return ret.toString();
171 return super.walk(t);
173 protected Object defaultWalk(String head, Object[] children) {
174 Tree<String>[] kids = new Tree[children.length];
175 for(int i=0; i<children.length; i++) {
176 if (children[i]==null) kids[i]=null;
177 else if (children[i] instanceof String) kids[i] = lone(escapify((String)children[i]));
178 else if (children[i] instanceof Tree) kids[i] = (Tree<String>)children[i];
179 else kids[i] = lone(children[i].toString());
181 return new Tree<String>(null, head, kids);
186 public static enum Style { H, UL, TT, SO, IT, Q, B, PRE, LIST, EMDASH; }
188 public static AST h(AST a) { return new Gather(a, Style.H); }
189 public static AST ul(AST a) { return new Gather(a, Style.UL); }
190 public static AST tt(AST a) { return new Gather(a, Style.TT); }
191 public static AST so(AST a) { return new Gather(a, Style.SO); }
192 public static AST it(AST a) { return new Gather(a, Style.IT); }
193 public static AST q(AST a) { return new Gather(a, Style.Q); }
194 public static AST b(AST a) { return new Gather(a, Style.B); }
195 public static AST pre(AST a) { return new Gather(a, Style.PRE); }
196 public static AST list(AST a) { return new Gather(a, Style.LIST); }
197 public static AST emdash() { return new Gather(Style.EMDASH); }
199 public static AST seq(AST a) { return new Gather(a); }
201 public static class Latex {
202 public static void emit(PrintWriter p, AST a) {
207 public static void emit2(PrintWriter p, AST ast, String head) {
208 for(AST a = ast.getFirstChild(); a != null; a = a.getNextSibling()) emit(p, a, head);
210 public static void emit(PrintWriter p, AST ast, String head) {
211 if (!(ast instanceof Gather)) {
212 if (ast.getNumberOfChildren()==0) {
213 p.print(ast.getText());
219 Gather a = (Gather)ast;
225 case H: p.println(); p.println(); p.print("\\"+head+"section{"); emit2(p, a, "sub"+head); p.println("}"); break;
226 case B: p.print("{\\bf{"); emit2(p, a, head); p.print("}}"); break;
227 case UL: p.print("{\\ul{"); emit2(p, a, head); p.print("}}"); break;
228 case IT: p.print("{\\it{"); emit2(p, a, head); p.print("}}"); break;
229 case TT: p.print("{\\tt{"); emit2(p, a, head); p.print("}}"); break;
230 case SO: p.print("{\\overstrike{"); emit2(p, a, head); p.print("}}"); break;
231 case Q: p.print("``"); emit2(p, a, head); p.print("''"); break;
232 case EMDASH: p.print(" \\emdash "); break;
233 case LIST: p.println(); p.println("\\startitemize[symbol]"); emit2(p, a, head); p.println("\\stopitemize"); break;
235 if (a.getFirstChild() != null) {
237 p.println("\\begin{verbatim}");
238 p.println(a.getFirstChild().getText());
239 p.println("\\end{verbatim}");
243 public static void prefix(PrintWriter p) {
244 p.println("% generated by TIBDOC");
245 for(int i=0; i<packages.length; i++) p.println("\\usemodule["+packages[i]+"]");
246 p.println("\\setuppapersize[letter]");
247 p.println("\\setuppagenumbering[location=]");
248 p.println("\\setupcolors[state=start]");
249 //"\\setupinteraction[title={Title},author={Me},"++
250 //"subtitle={Deez Nutz},keywords={blargh},color=blue]\n" ++
251 //"\\setuppublications[database={me},numbering=yes,sort=author]\n" ++
252 p.println("\\setuphead[section][style={\\ss\\bfa},number=no,before=\\blank\\hairline\\nowhitespace]");
253 p.println("\\definelayout[mypage][backspace=1.75in,cutspace=1.75in,width=5in]");
254 p.println("\\setuplayout[mypage]");
255 p.println("\\definetypeface[myface][rm][Xserif][Warnock Pro]");
256 p.println("\\definetypeface[myface][tt][Xmono][CMU Typewriter Text Regular][default]");
257 p.println("\\definetypeface[myface][ss][Xsans][Myriad Pro][default]");
258 p.println("\\usesymbols[uni]");
259 p.println("\\definesymbol[1][{\\USymbCharZapf{39}{164}}]");
260 p.println("\\setupbodyfont[myface, 11pt]");
261 p.println("\\setupwhitespace[7pt]");
262 p.println("\\def\\MyDroppedCaps%");
263 p.println(" {\\DroppedCaps");
264 p.println(" {} {Serif} {2\\baselineskip} {2pt} {1\\baselineskip} {2}}");
265 p.println("\\starttext");
266 p.println("\\switchtobodyfont[16pt]\\midaligned{\\ss\\bfa{Title}}\\switchtobodyfont[10pt]");
267 p.println("\\midaligned{Adam Megacz}\n\n\\nowhitespace\\midaligned{\\tt{adam@megacz.com}}");
268 p.println("\\blank[1cm,force]");
269 //p.println("\\defineparagraphs[mypar][n=2,before={\\blank},after={\\blank}");
270 //p.println("\\setupparagraphs[mypar][1][width=.45\\textwidth");
271 //p.println("\\setupparagraphs[mypar][2][width=.55\\textwidth");
272 //p.println("\\startmypa");
273 //p.println("\\switchtobodyfont[sma");
276 public static void suffix(PrintWriter p) {
277 p.println("\\stoptext");
279 static String[] packages = new String[] { "supp-fun", "bib", "href" };
285 import Data.Array.IArray
293 toContex ll = prefix ++ (concatMap tl ll) ++ suffix
295 packages = [ "[supp-fun]",
298 prefix = (concatMap (\x -> "\\usemodule"++x++"\n") packages) ++
299 "\\setuppapersize[letter]\n" ++
300 "\\setuppagenumbering[location=]\n" ++
301 "\\setupcolors[state=start]\n" ++
302 --"\\setupinteraction[title={Title},author={Me},"++
303 --"subtitle={Deez Nutz},keywords={blargh},color=blue]\n" ++
304 --"\\setuppublications[database={me},numbering=yes,sort=author]\n" ++
305 "\\setuphead[section][style={\\ss\\bfa},\n" ++
307 " before=\\blank\\hairline\\nowhitespace,\n" ++
309 "\\definelayout[mypage][\n" ++
310 " backspace=1.75in, % the space for margin notes\n" ++
311 " cutspace=1.75in, % the space for right margin notes\n" ++
314 "\\setuplayout[mypage]\n" ++
315 "\\definetypeface[myface][rm][Xserif][Warnock Pro]\n" ++
316 "\\definetypeface[myface][tt][Xmono][CMU Typewriter Text Regular][default]\n" ++
317 "\\definetypeface[myface][ss][Xsans][Myriad Pro][default]\n" ++
318 "\\usesymbols[uni]\n" ++
319 "\\definesymbol[1][{\\USymbCharZapf{39}{164}}]\n" ++
320 "\\setupbodyfont[myface, 11pt]\n" ++
321 "\\setupwhitespace[7pt]\n" ++
322 "\\def\\MyDroppedCaps%\n" ++
323 " {\\DroppedCaps\n" ++
324 " {} {Serif} {2\\baselineskip} {2pt} {1\\baselineskip} {2}}\n" ++
326 "\\switchtobodyfont[16pt]\\midaligned{\\ss\\bfa{Hi5 Replicated Server Infrastructure}}\\switchtobodyfont[10pt]\n"++
327 "\\midaligned{Adam Megacz}\n\n\\nowhitespace\\midaligned{\\tt{adam@megacz.com}}\n\n"++
328 "\\blank[1cm,force]\n" ++
329 "\\defineparagraphs[mypar][n=2,before={\\blank},after={\\blank}]\n"++
330 "\\setupparagraphs[mypar][1][width=.45\\textwidth]\n"++
331 "\\setupparagraphs[mypar][2][width=.55\\textwidth]\n"++
333 "\\switchtobodyfont[small]\n"
334 suffix = "\n\\stoptext\n"
335 addItem i = "\\item " ++ (striptrail $ boost 8 $ wrap $ striplead $ tl i)
337 escapify ('%':t) = '\\':'%':(escapify t)
338 escapify ('$':t) = '\\':'$':(escapify t)
339 escapify (h:t) = h:(escapify t)
341 tl (Special _ BulletList l) = "\\startitemize[symbol]\n" ++ (concatMap addItem l) ++ "\\stopitemize\n"
342 tl (Special _ NumberList l) = "\\startitemize[symbol]\n" ++ (concatMap addItem l) ++ "\\stopitemize\n"
343 tl (Special _ Section (h:t)) = "\\section{"++(tl h)++"}\n"++(concatMap tl t)
344 tl (Special _ NumberedSection (h:t)) = "\\section{"++(tl h)++"}\n"++(concatMap tl t)
345 tl (Special _ (Glyph EmDash) []) = "{\\emdash}"
346 --tl (Special _ Superscript l) =
347 --tl (Special _ Subscript l) =
348 --tl (Special _ (Image u) l) =
349 --tl (Special _ (Cite u) l) =
350 tl (Special _ BlockQuote l) = "\n\n\\startquote\n "++
351 (striptrail $ boost 4 $ wrap $ striplead $ concatMap tl l)++"\n\\stopquote\n\n"
352 tl (Special _ HorizontalRule []) = "\\\\\\rule{4in}{0.5pt}\\\\"
353 tl (Special _ Italic l) = "{\\it{"++(concatMap tl l)++"}}"
354 tl (Special _ Bold l) = "{\\bf{"++(concatMap tl l)++"}}"
355 tl (Special _ DropCap (h:t)) = "\\MyDroppedCaps{"++(tl h)++"}{\\sc "++(concatMap tl t)++"}"
356 tl (Special _ Typewriter l) = "{\\tt{"++(concatMap tl l)++"}}"
357 tl (Special _ StrikeThrough l) = "" --"\\sout{"++(concatMap tl l)++"}"
358 tl (Special _ Quotes l) = "``"++(concatMap tl l)++"''"
359 tl (Special _ Underline l) = "" --"\\uline{"++(concatMap tl l)++"}"
360 tl (Special _ Underline2 l) = "" --"\\uuline{"++(concatMap tl l)++"}"
361 tl (Special _ (Math s) []) = "\\placeformula\n$$\n" ++ (escapeMath s) ++ "\n$$\n"
362 tl (Special _ Footnote l) = "\\footnote{"++(concatMap tl l)++"}"
363 tl (Special _ Float l) = "" --"\n\n\\begin{wrapfigure}{r}{0.4\\textwidth} \\framebox[0.4\\textwidth]{"++
364 --(concatMap tl l)++"} \\label{x}\\end{wrapfigure}\n\n"
365 --tl (Special _ Figure l) = "\\placefigure[][fig:church]{}{"++(concatMap tl l)++"}"
366 tl (Special _ Figure l) = "\\startnarrower\n"++(concatMap tl l)++"\n\\stopnarrower\n"
367 tl (Special _ (Link u) l) = "\\href{"++(escapify u)++"}{"++(concatMap tl l)++"}"
368 tl (Special _ (Verbatim s) []) = "\\starttyping\n"++s++"\n\\stoptyping\n"
369 -- tl (Special _ TwoColumn l) = "\\startcolumns[n=2]\n"++(concatMap tl l)++"\\stopcolumns"
370 -- tl (Special _ Title l) = ""--"\\title{"++(concatMap tl l)++"}\n\\maketitle\n\n\n"
371 tl (Special _ Abstract l) =
372 "\\midaligned{\\ss\\bfa Abstract}\\par\n " ++
373 "\n\n"++(concatMap tl l)++"\\mypar" ++
374 "\\switchtobodyfont[8pt]{\\ss{\\placecontent}}\\switchtobodyfont[normal]\\stopmypar\n\n\\blank[1cm,force]"
375 tl (Special _ (Command c) l) = "\\"++c++"["++(concatMap tl l)++"]"
376 tl (Special _ t l) = error $ "formatting code "++(show t)++" not supported on {"++(concatMap show l)++"})"
378 tl (BlankLine _) = "\n\n"
379 tl (Block _ l) = concatMap tl l
380 tl (Letter _ c) = escapify [c]