3a53cf24029593c07eedba07461c8d33cdbe1413
[sbp.git] / src / edu / berkeley / sbp / tib / TibDoc.java
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.
4
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.*;
10 import java.util.*;
11 import java.io.*;
12
13 public class TibDoc {
14
15     public static Text lf() { Chars ret = new Chars(); ret.text = "\n"; return ret; }
16     public static Text cr() { Chars ret = new Chars(); ret.text = "\r"; return ret; }
17     public static char urlescape(int a, int b) { return (char)(10*a+b); }
18
19
20     // Template Classes //////////////////////////////////////////////////////////////////////////////
21
22     public static abstract class Text implements ToHTML {
23         public static final Class[] subclasses = new Class[] { Chars.class, URL.class, Email.class };
24         public void toHTML(ToHTML.HTML sb) { }
25     }
26     public static class TextString extends Text {
27         public String text;
28         public String tag() { return null; }
29         public void toHTML(ToHTML.HTML sb) { sb.tag(tag(), text); }
30     }
31     public static class TextArray extends Text {
32         public Text[] t;
33         public String tag() { return null; }
34         public void toHTML(ToHTML.HTML sb) { sb.tag(tag(), t); }
35     }
36
37
38     // Structural //////////////////////////////////////////////////////////////////////////////
39
40     public static class Doc implements ToHTML {
41         public Header head;
42         public Body   body;
43         public void toHTML(ToHTML.HTML sb) { sb.tag("html", body); }
44         public static class Header extends HashMap<String, Text[]> {
45             public static class kv { public String key; public Text[] val; }
46             public void attrs(kv[] kvs) { for(int i=0; i<kvs.length; i++) this.put(kvs[i].key, kvs[i].val); }
47         }
48         public static class Body implements ToHTML {
49             public Section[] sections;
50             public void toHTML(ToHTML.HTML sb) { sb.append(sections); }
51             public static class Section implements ToHTML {
52                 public Text header;
53                 public Paragraph[] paragraphs;
54                 public void toHTML(ToHTML.HTML sb) {
55                     sb.tag("h3", header);
56                     sb.append(paragraphs);
57                 }
58             }
59         }
60     }
61
62     // Tags //////////////////////////////////////////////////////////////////////////////
63
64     public static class Keyword       extends TextString { public String tag() { return "tt"; } }
65     public static class Bold          extends TextArray  { public String tag() { return "b"; } }
66     public static class Smallcap      extends TextArray  { public String tag() { return "sc"; } }
67     public static class Subscript     extends TextString { public String tag() { return "sub"; } }
68     public static class Superscript   extends TextString { public String tag() { return "super"; } }
69     public static class Strikethrough extends TextArray  { public String tag() { return "strike"; } }
70     public static class TT            extends TextArray  { public String tag() { return "tt"; } }
71     public static class Underline     extends TextArray  { public String tag() { return "u"; } }
72     public static class Citation      extends TextArray  { /* FIXME */ }
73     public static class Footnote      extends TextArray  { /* FIXME */ }
74
75     public static class Chars extends TextString { }
76     public static class Symbol extends TextString { }
77
78     public static interface Host extends ToHTML { }
79     public static class DNS implements Host {
80         public String[] part;
81         public void toHTML(ToHTML.HTML sb) {
82             sb.append("<tt>");
83             for(int i=0; i<part.length; i++)
84                 sb.append((i==0 ? "" : ".")+part[i]);
85             sb.append("</tt>");
86         }
87     }
88     public static class IP  implements Host {
89         public int a, b, c, d;
90         public void toHTML(ToHTML.HTML sb) { sb.append("<tt>"+a+"."+b+"."+c+"."+d+"</tt>"); }
91     }
92
93     public static interface URI extends ToHTML {
94         public static final Class[] subclasses = new Class[] { URL.class, Email.class };
95     }
96     public static class URL extends Text    implements URI {
97         public String method;
98         public Login login;
99         public Host host;
100         public int port;
101         public String path;
102         public void toHTML(ToHTML.HTML sb) {
103             sb.append(method);
104             sb.append("://");
105             // login.toHTML(sb);   FIXME
106             host.toHTML(sb);
107             // sb.append(":");     FIXME
108             // sb.append(port);
109             sb.append("/");
110             sb.append(path);
111         }
112     }
113     public static class Email extends Text  implements URI {
114         public String user;
115         public Host host;
116         public void toHTML(ToHTML.HTML sb) {
117             sb.append(user);
118             sb.append('@');
119             host.toHTML(sb);
120         }
121     }
122
123     public static class Login               {
124         public String username;
125         public String password;
126         public void toHTML(ToHTML.HTML sb) {
127             sb.append(username);
128             sb.append(':');
129             sb.append(password);
130             sb.append('@');
131         }        
132     }
133     public static class Italic extends Text {
134         public Text[] body;
135         public void toHTML(ToHTML.HTML sb) {
136             sb.append("<i>");
137             sb.append(body);
138             sb.append("</i>");
139         }
140     }
141
142     public static class LineBreak extends Text {
143         public void toHTML(ToHTML.HTML sb) {
144             sb.append("<br/>");
145         }
146     }
147     public static class Today extends Text { }
148     public static class Euro extends Text {
149         public void toHTML(ToHTML.HTML sb) {
150             sb.append("&#8364;");
151         }
152     }
153     public static class Link extends Text {
154         public static final Class[] subclasses = new Class[] { LinkWord.class, LinkText.class };
155         public static class LinkWord extends Link {
156             public String word;
157             public URI href;
158             public void toHTML(ToHTML.HTML sb) {
159                 sb.append("<a href='");
160                 href.toHTML(sb);
161                 sb.append("'>");
162                 sb.append(word);
163                 sb.append("</a>");
164             }
165         }
166         public static class LinkText extends Link {
167             public Text[] text;
168             public URI href;
169             public void toHTML(ToHTML.HTML sb) {
170                 sb.append("<a href='");
171                 href.toHTML(sb);
172                 sb.append("'>");
173                 sb.append(text);
174                 sb.append("</a>");
175             }
176         }
177     }
178
179
180     // Paragraph //////////////////////////////////////////////////////////////////////////////
181
182     public static interface Paragraph extends ToHTML {
183         public static final Class[] subclasses = new Class[] { Blockquote.class, P.class, HR.class };
184         public static class HR implements Paragraph {
185             public void toHTML(ToHTML.HTML sb) { sb.append("\n<hr>\n"); }
186         }
187         public static class P extends TextArray implements Paragraph {
188             public void toHTML(ToHTML.HTML sb) {
189                 sb.append("\n<p> ");
190                 super.toHTML(sb);
191                 sb.append(" </p>\n");
192             }
193         }
194         public static class Blockquote extends TextArray implements Paragraph {
195             public String tag() { return "blockquote"; }
196         }
197     }
198
199
200     // Lists //////////////////////////////////////////////////////////////////////////////
201
202     public static abstract class List extends Text {
203         public Text[][] points;
204         public abstract String tag();
205         public void toHTML(ToHTML.HTML sb) {
206             sb.append("<"+tag()+">\n");
207             for(Text[] t : points) {
208                 sb.append("  <li> ");
209                 sb.append(t);
210                 sb.append("  </li>\n");
211             }
212             sb.append("</"+tag()+">\n");
213         }
214     }
215     public static class OL extends List { public String tag() { return "ol"; } }
216     public static class UL extends List { public String tag() { return "ul"; } }
217
218
219     // Main //////////////////////////////////////////////////////////////////////////////
220
221     public static void main(String[] s) throws Exception {
222         try {
223             System.out.println("parsing " + s[0]);
224             Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
225             MetaGrammar gram = new Tib.Grammar(TibDoc.class);
226             gram = (MetaGrammar)gram.walk(res);
227             //System.out.println(gram);
228             Union mg = gram.done();
229             
230             System.out.println("\nparsing " + s[1]);
231             Forest f = new CharParser(mg).parse(new Tib(new FileInputStream(s[1])));
232             //((Tree)new StringifyWalker().walk(f.expand1())).toPrettyString()
233             System.out.println();
234             System.out.println(f.expand1().toPrettyString());
235             System.out.println();
236             Doc doc = (Doc)new ReflectiveGrammar(TibDoc.class).build(f.expand1());
237             System.out.println(doc);
238             System.out.println();
239             System.out.println();
240             System.out.println();
241             System.out.println();
242             StringBuffer sb = new StringBuffer();
243             doc.toHTML(new ToHTML.HTML(sb));
244             System.out.println(sb);
245             /*
246             String st = new HTMLWalker().walk(f.expand1()).toString();
247             System.out.println(st);
248             FileOutputStream fos = new FileOutputStream("out.html");
249             PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
250             p.println(st);
251             p.flush();
252             p.close();
253             */
254         } catch (Ambiguous a) {
255             FileOutputStream fos = new FileOutputStream("/Users/megacz/Desktop/out.dot");
256             PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
257             GraphViz gv = new GraphViz();
258             a.ambiguity.toGraphViz(gv);
259             gv.dump(p);
260             p.flush();
261             p.close();
262             a.printStackTrace();
263             
264         } catch (Exception e) {
265             e.printStackTrace();
266         }
267     }
268
269
270     /*
271     public static enum Style { H, UL, TT, SO, IT, Q, B, PRE, LIST, EMDASH; }
272
273     public static AST h(AST a)      { return new Gather(a, Style.H); }
274     public static AST ul(AST a)     { return new Gather(a, Style.UL); }
275     public static AST tt(AST a)     { return new Gather(a, Style.TT); }
276     public static AST so(AST a)     { return new Gather(a, Style.SO); }
277     public static AST it(AST a)     { return new Gather(a, Style.IT); }
278     public static AST q(AST a)      { return new Gather(a, Style.Q); }
279     public static AST b(AST a)      { return new Gather(a, Style.B); }
280     public static AST pre(AST a)    { return new Gather(a, Style.PRE); }
281     public static AST list(AST a)   { return new Gather(a, Style.LIST); }
282     public static AST emdash()      { return new Gather(Style.EMDASH); }
283
284     public static AST seq(AST a) { return new Gather(a); }
285
286     public static class Latex {
287         public static void emit(PrintWriter p, AST a) {
288             prefix(p);
289             emit(p, a, "");
290             suffix(p);
291         }
292         public static void emit2(PrintWriter p, AST ast, String head) {
293             for(AST a = ast.getFirstChild(); a != null; a = a.getNextSibling()) emit(p, a, head);
294         }
295         public static void emit(PrintWriter p, AST ast, String head) {
296             if (!(ast instanceof Gather)) {
297                 if (ast.getNumberOfChildren()==0) {
298                     p.print(ast.getText());
299                 } else {
300                     emit2(p, ast, head);
301                 }
302                 return;
303             }
304             Gather a = (Gather)ast;
305             if (a.style==null) {
306                 emit2(p, a, head);
307                 return;
308             }
309             switch(a.style) {
310                 case H:    p.println(); p.println(); p.print("\\"+head+"section{"); emit2(p, a, "sub"+head); p.println("}"); break;
311                 case B:    p.print("{\\bf{");                          emit2(p, a, head); p.print("}}"); break;
312                 case UL:   p.print("{\\ul{");                          emit2(p, a, head); p.print("}}"); break;
313                 case IT:   p.print("{\\it{");                          emit2(p, a, head); p.print("}}"); break;
314                 case TT:   p.print("{\\tt{");                          emit2(p, a, head); p.print("}}"); break;
315                 case SO:   p.print("{\\overstrike{");                  emit2(p, a, head); p.print("}}"); break;
316                 case Q:    p.print("``");                              emit2(p, a, head); p.print("''"); break;
317                 case EMDASH: p.print(" \\emdash "); break;
318                 case LIST: p.println(); p.println("\\startitemize[symbol]"); emit2(p, a, head); p.println("\\stopitemize"); break;
319                 case PRE:
320                     if (a.getFirstChild() != null) {
321                         p.println();
322                         p.println("\\begin{verbatim}");
323                         p.println(a.getFirstChild().getText());
324                         p.println("\\end{verbatim}");
325                     }
326             }
327         }
328         public static void prefix(PrintWriter p) {
329             p.println("% generated by TIBDOC");
330             for(int i=0; i<packages.length; i++) p.println("\\usemodule["+packages[i]+"]");
331             p.println("\\setuppapersize[letter]");
332             p.println("\\setuppagenumbering[location=]");
333             p.println("\\setupcolors[state=start]");
334             //"\\setupinteraction[title={Title},author={Me},"++
335             //"subtitle={Deez Nutz},keywords={blargh},color=blue]\n" ++
336             //"\\setuppublications[database={me},numbering=yes,sort=author]\n" ++
337             p.println("\\setuphead[section][style={\\ss\\bfa},number=no,before=\\blank\\hairline\\nowhitespace]");
338             p.println("\\definelayout[mypage][backspace=1.75in,cutspace=1.75in,width=5in]");
339             p.println("\\setuplayout[mypage]");
340             p.println("\\definetypeface[myface][rm][Xserif][Warnock Pro]");
341             p.println("\\definetypeface[myface][tt][Xmono][CMU Typewriter Text Regular][default]");
342             p.println("\\definetypeface[myface][ss][Xsans][Myriad Pro][default]");
343             p.println("\\usesymbols[uni]");
344             p.println("\\definesymbol[1][{\\USymbCharZapf{39}{164}}]");
345             p.println("\\setupbodyfont[myface, 11pt]");
346             p.println("\\setupwhitespace[7pt]");
347             p.println("\\def\\MyDroppedCaps%");
348             p.println("    {\\DroppedCaps");
349             p.println("        {} {Serif} {2\\baselineskip} {2pt} {1\\baselineskip} {2}}");
350             p.println("\\starttext");
351             p.println("\\switchtobodyfont[16pt]\\midaligned{\\ss\\bfa{Title}}\\switchtobodyfont[10pt]");
352             p.println("\\midaligned{Adam Megacz}\n\n\\nowhitespace\\midaligned{\\tt{adam@megacz.com}}");
353             p.println("\\blank[1cm,force]");
354             //p.println("\\defineparagraphs[mypar][n=2,before={\\blank},after={\\blank}");
355             //p.println("\\setupparagraphs[mypar][1][width=.45\\textwidth");
356             //p.println("\\setupparagraphs[mypar][2][width=.55\\textwidth");
357             //p.println("\\startmypa");
358             //p.println("\\switchtobodyfont[sma");
359         }
360
361         public static void suffix(PrintWriter p) {
362             p.println("\\stoptext");
363         }
364         static String[] packages = new String[] { "supp-fun", "bib", "href" };
365     }
366
367     // ConTex
368
369 module Contex where
370 import Data.Array.IArray
371 import Data.Char
372 import Util
373 import Lexer
374 import IR
375 import Data.List
376 import Beautify
377
378 toContex ll = prefix ++ (concatMap tl ll) ++ suffix
379  where
380   packages                         = [ "[supp-fun]",
381                                        "[bib]",
382                                        "[href]" ]
383   prefix                           = (concatMap (\x -> "\\usemodule"++x++"\n") packages) ++
384                                      "\\setuppapersize[letter]\n" ++
385                                      "\\setuppagenumbering[location=]\n" ++
386                                      "\\setupcolors[state=start]\n" ++
387                                      --"\\setupinteraction[title={Title},author={Me},"++
388                                      --"subtitle={Deez Nutz},keywords={blargh},color=blue]\n" ++
389                                      --"\\setuppublications[database={me},numbering=yes,sort=author]\n" ++
390                                      "\\setuphead[section][style={\\ss\\bfa},\n" ++
391                                      "                     number=no,\n" ++
392                                      "                     before=\\blank\\hairline\\nowhitespace,\n" ++
393                                      "                     ]\n" ++
394                                      "\\definelayout[mypage][\n" ++
395                                      " backspace=1.75in, % the space for margin notes\n" ++
396                                      " cutspace=1.75in, % the space for right margin notes\n" ++
397                                      " width=5in" ++
398                                      "]\n" ++
399                                      "\\setuplayout[mypage]\n" ++
400                                      "\\definetypeface[myface][rm][Xserif][Warnock Pro]\n" ++
401                                      "\\definetypeface[myface][tt][Xmono][CMU Typewriter Text Regular][default]\n" ++
402                                      "\\definetypeface[myface][ss][Xsans][Myriad Pro][default]\n" ++
403                                      "\\usesymbols[uni]\n" ++
404                                      "\\definesymbol[1][{\\USymbCharZapf{39}{164}}]\n" ++
405                                      "\\setupbodyfont[myface, 11pt]\n" ++
406                                      "\\setupwhitespace[7pt]\n" ++
407                                      "\\def\\MyDroppedCaps%\n" ++
408                                      "    {\\DroppedCaps\n" ++
409                                      "        {} {Serif} {2\\baselineskip} {2pt} {1\\baselineskip} {2}}\n" ++
410                                      "\\starttext\n" ++
411                                      "\\switchtobodyfont[16pt]\\midaligned{\\ss\\bfa{Hi5 Replicated Server Infrastructure}}\\switchtobodyfont[10pt]\n"++ 
412                                      "\\midaligned{Adam Megacz}\n\n\\nowhitespace\\midaligned{\\tt{adam@megacz.com}}\n\n"++
413                                      "\\blank[1cm,force]\n" ++
414                                      "\\defineparagraphs[mypar][n=2,before={\\blank},after={\\blank}]\n"++
415                                      "\\setupparagraphs[mypar][1][width=.45\\textwidth]\n"++
416                                      "\\setupparagraphs[mypar][2][width=.55\\textwidth]\n"++
417                                      "\\startmypar"++
418                                      "\\switchtobodyfont[small]\n"
419   suffix                           = "\n\\stoptext\n"
420   addItem i                        = "\\item " ++ (striptrail $ boost 8 $ wrap $ striplead $ tl i)
421   escapify []                      = []
422   escapify ('%':t)                 = '\\':'%':(escapify t)
423   escapify ('$':t)                 = '\\':'$':(escapify t)
424   escapify (h:t)                   = h:(escapify t)
425   escapeMath s                     = s
426   tl (Special _ BulletList l)      = "\\startitemize[symbol]\n" ++ (concatMap addItem l) ++ "\\stopitemize\n"
427   tl (Special _ NumberList l)      = "\\startitemize[symbol]\n" ++ (concatMap addItem l) ++ "\\stopitemize\n"
428   tl (Special _ Section (h:t))     = "\\section{"++(tl h)++"}\n"++(concatMap tl t)
429   tl (Special _ NumberedSection (h:t)) = "\\section{"++(tl h)++"}\n"++(concatMap tl t)
430   tl (Special _ (Glyph EmDash) []) = "{\\emdash}"
431 --tl (Special _ Superscript l)     = 
432 --tl (Special _ Subscript l)       = 
433 --tl (Special _ (Image u) l)       = 
434 --tl (Special _ (Cite u) l)        = 
435   tl (Special _ BlockQuote l)      = "\n\n\\startquote\n     "++
436                                      (striptrail $ boost 4 $ wrap $ striplead $ concatMap tl l)++"\n\\stopquote\n\n"
437   tl (Special _ HorizontalRule []) = "\\\\\\rule{4in}{0.5pt}\\\\"
438   tl (Special _ Italic l)          = "{\\it{"++(concatMap tl l)++"}}"
439   tl (Special _ Bold l)            = "{\\bf{"++(concatMap tl l)++"}}"
440   tl (Special _ DropCap (h:t))     = "\\MyDroppedCaps{"++(tl h)++"}{\\sc "++(concatMap tl t)++"}"
441   tl (Special _ Typewriter l)      = "{\\tt{"++(concatMap tl l)++"}}"
442   tl (Special _ StrikeThrough l)   = "" --"\\sout{"++(concatMap tl l)++"}"
443   tl (Special _ Quotes l)          = "``"++(concatMap tl l)++"''"
444   tl (Special _ Underline l)       = "" --"\\uline{"++(concatMap tl l)++"}"
445   tl (Special _ Underline2 l)      = "" --"\\uuline{"++(concatMap tl l)++"}"
446   tl (Special _ (Math s) [])       = "\\placeformula\n$$\n" ++ (escapeMath s) ++ "\n$$\n"
447   tl (Special _ Footnote l)        = "\\footnote{"++(concatMap tl l)++"}"
448   tl (Special _ Float l)           = "" --"\n\n\\begin{wrapfigure}{r}{0.4\\textwidth} \\framebox[0.4\\textwidth]{"++
449                                      --(concatMap tl l)++"} \\label{x}\\end{wrapfigure}\n\n"
450 --tl (Special _ Figure l)          = "\\placefigure[][fig:church]{}{"++(concatMap tl l)++"}"
451   tl (Special _ Figure l)          = "\\startnarrower\n"++(concatMap tl l)++"\n\\stopnarrower\n"
452   tl (Special _ (Link u) l)        = "\\href{"++(escapify u)++"}{"++(concatMap tl l)++"}"
453   tl (Special _ (Verbatim s) [])   = "\\starttyping\n"++s++"\n\\stoptyping\n"
454 --  tl (Special _ TwoColumn l)       = "\\startcolumns[n=2]\n"++(concatMap tl l)++"\\stopcolumns"
455 --  tl (Special _ Title l)           = ""--"\\title{"++(concatMap tl l)++"}\n\\maketitle\n\n\n"
456   tl (Special _ Abstract l) =
457       "\\midaligned{\\ss\\bfa Abstract}\\par\n " ++
458       "\n\n"++(concatMap tl l)++"\\mypar" ++
459       "\\switchtobodyfont[8pt]{\\ss{\\placecontent}}\\switchtobodyfont[normal]\\stopmypar\n\n\\blank[1cm,force]"
460   tl (Special _ (Command c) l)     = "\\"++c++"["++(concatMap tl l)++"]"
461   tl (Special _ t l)               = error $ "formatting code "++(show t)++" not supported on {"++(concatMap show l)++"})"
462   tl (WS _)                        = " "
463   tl (BlankLine _)                 = "\n\n"
464   tl (Block _ l)                   = concatMap tl l
465   tl (Letter _ c)                  = escapify [c]
466   tl z                             = (show z)
467
468
469
470
471     */
472 }
473