checkpoint
[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 Text emdash() { return new Entity("mdash"); }
18     public static char urlescape(int a, int b) { return (char)(10*a+b); }
19
20
21     // Template Classes //////////////////////////////////////////////////////////////////////////////
22
23     public static abstract class Text implements ToHTML {
24         public static final Class[] subclasses = new Class[] { Chars.class, URL.class, Email.class };
25         public void toHTML(ToHTML.HTML sb) { }
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
39     // Structural //////////////////////////////////////////////////////////////////////////////
40
41     public static class Doc implements ToHTML {
42         public Header head;
43         public Body   body;
44         public void toHTML(ToHTML.HTML sb) { sb.tag("html", body); }
45         public static class Header extends HashMap<String, Text[]> {
46             public static class kv { public String key; public Text[] val; }
47             public void attrs(kv[] kvs) { for(int i=0; i<kvs.length; i++) this.put(kvs[i].key, kvs[i].val); }
48         }
49         public static class Body implements ToHTML {
50             public Section[] sections;
51             public void toHTML(ToHTML.HTML sb) { sb.append(sections); }
52             public static class Section implements ToHTML {
53                 public Text header;
54                 public Paragraph[] paragraphs;
55                 public void toHTML(ToHTML.HTML sb) {
56                     sb.tag("h3", header);
57                     sb.append(paragraphs);
58                 }
59             }
60         }
61     }
62
63
64     // Paragraph //////////////////////////////////////////////////////////////////////////////
65
66     public static interface Paragraph extends ToHTML {
67         public static final Class[] subclasses = new Class[] { Blockquote.class, P.class, HR.class };
68         public static class HR                                implements Paragraph { public void toHTML(ToHTML.HTML sb) { sb.append("\n<hr>\n"); } }
69         public static class P          extends Text.TextArray implements Paragraph { public String tag() { return "p"; } }
70         public static class Blockquote extends Text.TextArray implements Paragraph { public String tag() { return "blockquote"; } }
71     }
72
73     public static abstract class List extends Text {
74         public Text[][] points;
75         public abstract String tag();
76         public void toHTML(ToHTML.HTML sb) {
77             sb.append("<"+tag()+">\n");
78             for(Text[] t : points) sb.tag("li", t);
79             sb.append("</"+tag()+">\n");
80         }
81     }
82     public static class OL extends List { public String tag() { return "ol"; } }
83     public static class UL extends List { public String tag() { return "ul"; } }
84
85
86
87     // Tags //////////////////////////////////////////////////////////////////////////////
88
89     public static class Chars         extends Text.TextString { }
90     public static class Symbol        extends Text.TextString { }
91     public static class Keyword       extends Text.TextString { public String tag() { return "tt"; } }
92     public static class Subscript     extends Text.TextString { public String tag() { return "sub"; } }
93     public static class Superscript   extends Text.TextString { public String tag() { return "super"; } }
94     public static class Bold          extends Text.TextArray  { public String tag() { return "b"; } }
95     public static class Smallcap      extends Text.TextArray  { public String tag() { return "sc"; } }
96     public static class Strikethrough extends Text.TextArray  { public String tag() { return "strike"; } }
97     public static class TT            extends Text.TextArray  { public String tag() { return "tt"; } }
98     public static class Underline     extends Text.TextArray  { public String tag() { return "u"; } }
99     public static class Italic        extends Text.TextArray  { public String tag() { return "i"; } }
100     public static class Citation      extends Text.TextArray  { /* FIXME */ }
101     public static class Footnote      extends Text.TextArray  { /* FIXME */ }
102     public static class LineBreak     extends Text            { public void toHTML(ToHTML.HTML sb) { sb.tag("br"); } }
103     public static class Today         extends Text            { }
104     public static class Euro          extends Text            { public void toHTML(ToHTML.HTML sb) { sb.entity(8364); } }
105     public static class Link          extends Text {
106         public Text[] text;
107         public URI href;
108         public void toHTML(ToHTML.HTML sb) { sb.tag("a", new Object[] { "href", href }, text); }
109     }
110     public static class Entity        extends Text {
111         public final String entity;
112         public Entity(String entity) { this.entity = entity; }
113         public void toHTML(ToHTML.HTML sb) { sb.entity(entity); }
114     }
115
116
117     // Network //////////////////////////////////////////////////////////////////////////////
118
119     public static interface Host extends ToHTML {
120         public static class DNS implements Host {
121             public String[] part;
122             public void toHTML(ToHTML.HTML sb) {
123                 for(int i=0; i<part.length; i++)
124                     sb.append((i==0 ? "" : ".")+part[i]);
125             }
126         }
127         public static class IP  implements Host {
128             public int a, b, c, d;
129             public void toHTML(ToHTML.HTML sb) { sb.append(a+"."+b+"."+c+"."+d); }
130         }
131     }
132
133     public static interface URI extends ToHTML {
134         public static final Class[] subclasses = new Class[] { URL.class, Email.class };
135     }
136     public static class URL extends Text    implements URI {
137         public String method;
138         public Login login;
139         public Host host;
140         public int port;
141         public String path;
142         public void toHTML(ToHTML.HTML sb) {
143             sb.append(method);
144             sb.append("://");
145             // login.toHTML(sb);   FIXME
146             host.toHTML(sb);
147             // sb.append(":");     FIXME
148             // sb.append(port);
149             sb.append("/");
150             sb.append(path);
151         }
152     }
153     public static class Email extends Text  implements URI {
154         public String user;
155         public Host host;
156         public void toHTML(ToHTML.HTML sb) {
157             sb.append(user);
158             sb.append('@');
159             host.toHTML(sb);
160         }
161     }
162
163     public static class Login {
164         public String username;
165         public String password;
166         public void toHTML(ToHTML.HTML sb) {
167             sb.append(username);
168             sb.append(':');
169             sb.append(password);
170             sb.append('@');
171         }        
172     }
173
174
175
176     // Main //////////////////////////////////////////////////////////////////////////////
177
178     public static void main(String[] s) throws Exception {
179         try {
180             System.out.println("parsing " + s[0]);
181             Tree<String> res = new CharParser(MetaGrammar.make()).parse(new FileInputStream(s[0])).expand1();
182             MetaGrammar gram = new Tib.Grammar(TibDoc.class);
183             gram = (MetaGrammar)gram.walk(res);
184             System.out.println("\nparsing " + s[1]);
185             Forest f = new CharParser(gram.done()).parse(new Tib(new FileInputStream(s[1])));
186             System.out.println();
187             System.out.println(f.expand1().toPrettyString());
188             System.out.println();
189             Doc doc = (Doc)new ReflectiveGrammar(TibDoc.class).build(f.expand1());
190             System.out.println(doc);
191             System.out.println();
192             System.out.println();
193             System.out.println();
194             System.out.println();
195             StringBuffer sb = new StringBuffer();
196             doc.toHTML(new ToHTML.HTML(sb));
197             System.out.println(sb);
198
199             FileOutputStream fos = new FileOutputStream("out.html");
200             PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
201             p.println(sb);
202             p.flush();
203             p.close();
204
205         } catch (Ambiguous a) {
206             FileOutputStream fos = new FileOutputStream("/Users/megacz/Desktop/out.dot");
207             PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
208             GraphViz gv = new GraphViz();
209             a.ambiguity.toGraphViz(gv);
210             gv.dump(p);
211             p.flush();
212             p.close();
213             a.printStackTrace();
214             
215         } catch (Exception e) {
216             e.printStackTrace();
217         }
218     }
219
220     /*
221         public static void prefix(PrintWriter p) {
222             p.println("% generated by TIBDOC");
223             for(int i=0; i<packages.length; i++) p.println("\\usemodule["+packages[i]+"]");
224             p.println("\\setuppapersize[letter]");
225             p.println("\\setuppagenumbering[location=]");
226             p.println("\\setupcolors[state=start]");
227             //"\\setupinteraction[title={Title},author={Me},"++
228             //"subtitle={Deez Nutz},keywords={blargh},color=blue]\n" ++
229             //"\\setuppublications[database={me},numbering=yes,sort=author]\n" ++
230             p.println("\\setuphead[section][style={\\ss\\bfa},number=no,before=\\blank\\hairline\\nowhitespace]");
231             p.println("\\definelayout[mypage][backspace=1.75in,cutspace=1.75in,width=5in]");
232             p.println("\\setuplayout[mypage]");
233             p.println("\\definetypeface[myface][rm][Xserif][Warnock Pro]");
234             p.println("\\definetypeface[myface][tt][Xmono][CMU Typewriter Text Regular][default]");
235             p.println("\\definetypeface[myface][ss][Xsans][Myriad Pro][default]");
236             p.println("\\usesymbols[uni]");
237             p.println("\\definesymbol[1][{\\USymbCharZapf{39}{164}}]");
238             p.println("\\setupbodyfont[myface, 11pt]");
239             p.println("\\setupwhitespace[7pt]");
240             p.println("\\def\\MyDroppedCaps%");
241             p.println("    {\\DroppedCaps");
242             p.println("        {} {Serif} {2\\baselineskip} {2pt} {1\\baselineskip} {2}}");
243             p.println("\\starttext");
244             p.println("\\switchtobodyfont[16pt]\\midaligned{\\ss\\bfa{Title}}\\switchtobodyfont[10pt]");
245             p.println("\\midaligned{Adam Megacz}\n\n\\nowhitespace\\midaligned{\\tt{adam@megacz.com}}");
246             p.println("\\blank[1cm,force]");
247             //p.println("\\defineparagraphs[mypar][n=2,before={\\blank},after={\\blank}");
248             //p.println("\\setupparagraphs[mypar][1][width=.45\\textwidth");
249             //p.println("\\setupparagraphs[mypar][2][width=.55\\textwidth");
250             //p.println("\\startmypa");
251             //p.println("\\switchtobodyfont[sma");
252         }
253
254         public static void suffix(PrintWriter p) {
255             p.println("\\stoptext");
256         }
257         static String[] packages = new String[] { "supp-fun", "bib", "href" };
258     }
259
260     // ConTex
261
262 module Contex where
263 import Data.Array.IArray
264 import Data.Char
265 import Util
266 import Lexer
267 import IR
268 import Data.List
269 import Beautify
270
271 toContex ll = prefix ++ (concatMap tl ll) ++ suffix
272  where
273   packages                         = [ "[supp-fun]",
274                                        "[bib]",
275                                        "[href]" ]
276   prefix                           = (concatMap (\x -> "\\usemodule"++x++"\n") packages) ++
277                                      "\\setuppapersize[letter]\n" ++
278                                      "\\setuppagenumbering[location=]\n" ++
279                                      "\\setupcolors[state=start]\n" ++
280                                      --"\\setupinteraction[title={Title},author={Me},"++
281                                      --"subtitle={Deez Nutz},keywords={blargh},color=blue]\n" ++
282                                      --"\\setuppublications[database={me},numbering=yes,sort=author]\n" ++
283                                      "\\setuphead[section][style={\\ss\\bfa},\n" ++
284                                      "                     number=no,\n" ++
285                                      "                     before=\\blank\\hairline\\nowhitespace,\n" ++
286                                      "                     ]\n" ++
287                                      "\\definelayout[mypage][\n" ++
288                                      " backspace=1.75in, % the space for margin notes\n" ++
289                                      " cutspace=1.75in, % the space for right margin notes\n" ++
290                                      " width=5in" ++
291                                      "]\n" ++
292                                      "\\setuplayout[mypage]\n" ++
293                                      "\\definetypeface[myface][rm][Xserif][Warnock Pro]\n" ++
294                                      "\\definetypeface[myface][tt][Xmono][CMU Typewriter Text Regular][default]\n" ++
295                                      "\\definetypeface[myface][ss][Xsans][Myriad Pro][default]\n" ++
296                                      "\\usesymbols[uni]\n" ++
297                                      "\\definesymbol[1][{\\USymbCharZapf{39}{164}}]\n" ++
298                                      "\\setupbodyfont[myface, 11pt]\n" ++
299                                      "\\setupwhitespace[7pt]\n" ++
300                                      "\\def\\MyDroppedCaps%\n" ++
301                                      "    {\\DroppedCaps\n" ++
302                                      "        {} {Serif} {2\\baselineskip} {2pt} {1\\baselineskip} {2}}\n" ++
303                                      "\\starttext\n" ++
304                                      "\\switchtobodyfont[16pt]\\midaligned{\\ss\\bfa{Hi5 Replicated Server Infrastructure}}\\switchtobodyfont[10pt]\n"++ 
305                                      "\\midaligned{Adam Megacz}\n\n\\nowhitespace\\midaligned{\\tt{adam@megacz.com}}\n\n"++
306                                      "\\blank[1cm,force]\n" ++
307                                      "\\defineparagraphs[mypar][n=2,before={\\blank},after={\\blank}]\n"++
308                                      "\\setupparagraphs[mypar][1][width=.45\\textwidth]\n"++
309                                      "\\setupparagraphs[mypar][2][width=.55\\textwidth]\n"++
310                                      "\\startmypar"++
311                                      "\\switchtobodyfont[small]\n"
312   suffix                           = "\n\\stoptext\n"
313   addItem i                        = "\\item " ++ (striptrail $ boost 8 $ wrap $ striplead $ tl i)
314   escapify []                      = []
315   escapify ('%':t)                 = '\\':'%':(escapify t)
316   escapify ('$':t)                 = '\\':'$':(escapify t)
317   escapify (h:t)                   = h:(escapify t)
318   escapeMath s                     = s
319   tl (Special _ BulletList l)      = "\\startitemize[symbol]\n" ++ (concatMap addItem l) ++ "\\stopitemize\n"
320   tl (Special _ NumberList l)      = "\\startitemize[symbol]\n" ++ (concatMap addItem l) ++ "\\stopitemize\n"
321   tl (Special _ Section (h:t))     = "\\section{"++(tl h)++"}\n"++(concatMap tl t)
322   tl (Special _ NumberedSection (h:t)) = "\\section{"++(tl h)++"}\n"++(concatMap tl t)
323   tl (Special _ (Glyph EmDash) []) = "{\\emdash}"
324 --tl (Special _ Superscript l)     = 
325 --tl (Special _ Subscript l)       = 
326 --tl (Special _ (Image u) l)       = 
327 --tl (Special _ (Cite u) l)        = 
328   tl (Special _ BlockQuote l)      = "\n\n\\startquote\n     "++
329                                      (striptrail $ boost 4 $ wrap $ striplead $ concatMap tl l)++"\n\\stopquote\n\n"
330   tl (Special _ HorizontalRule []) = "\\\\\\rule{4in}{0.5pt}\\\\"
331   tl (Special _ Italic l)          = "{\\it{"++(concatMap tl l)++"}}"
332   tl (Special _ Bold l)            = "{\\bf{"++(concatMap tl l)++"}}"
333   tl (Special _ DropCap (h:t))     = "\\MyDroppedCaps{"++(tl h)++"}{\\sc "++(concatMap tl t)++"}"
334   tl (Special _ Typewriter l)      = "{\\tt{"++(concatMap tl l)++"}}"
335   tl (Special _ StrikeThrough l)   = "" --"\\sout{"++(concatMap tl l)++"}"
336   tl (Special _ Quotes l)          = "``"++(concatMap tl l)++"''"
337   tl (Special _ Underline l)       = "" --"\\uline{"++(concatMap tl l)++"}"
338   tl (Special _ Underline2 l)      = "" --"\\uuline{"++(concatMap tl l)++"}"
339   tl (Special _ (Math s) [])       = "\\placeformula\n$$\n" ++ (escapeMath s) ++ "\n$$\n"
340   tl (Special _ Footnote l)        = "\\footnote{"++(concatMap tl l)++"}"
341   tl (Special _ Float l)           = "" --"\n\n\\begin{wrapfigure}{r}{0.4\\textwidth} \\framebox[0.4\\textwidth]{"++
342                                      --(concatMap tl l)++"} \\label{x}\\end{wrapfigure}\n\n"
343 --tl (Special _ Figure l)          = "\\placefigure[][fig:church]{}{"++(concatMap tl l)++"}"
344   tl (Special _ Figure l)          = "\\startnarrower\n"++(concatMap tl l)++"\n\\stopnarrower\n"
345   tl (Special _ (Link u) l)        = "\\href{"++(escapify u)++"}{"++(concatMap tl l)++"}"
346   tl (Special _ (Verbatim s) [])   = "\\starttyping\n"++s++"\n\\stoptyping\n"
347 --  tl (Special _ TwoColumn l)       = "\\startcolumns[n=2]\n"++(concatMap tl l)++"\\stopcolumns"
348 --  tl (Special _ Title l)           = ""--"\\title{"++(concatMap tl l)++"}\n\\maketitle\n\n\n"
349   tl (Special _ Abstract l) =
350       "\\midaligned{\\ss\\bfa Abstract}\\par\n " ++
351       "\n\n"++(concatMap tl l)++"\\mypar" ++
352       "\\switchtobodyfont[8pt]{\\ss{\\placecontent}}\\switchtobodyfont[normal]\\stopmypar\n\n\\blank[1cm,force]"
353   tl (Special _ (Command c) l)     = "\\"++c++"["++(concatMap tl l)++"]"
354   tl (Special _ t l)               = error $ "formatting code "++(show t)++" not supported on {"++(concatMap show l)++"})"
355   tl (WS _)                        = " "
356   tl (BlankLine _)                 = "\n\n"
357   tl (Block _ l)                   = concatMap tl l
358   tl (Letter _ c)                  = escapify [c]
359   tl z                             = (show z)
360
361
362
363
364     */
365 }
366