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 org.ibex.util.*;
7 //import org.ibex.io.*;
8 import edu.berkeley.sbp.*;
9 import edu.berkeley.sbp.misc.*;
10 import edu.berkeley.sbp.util.*;
11 import java.util.*;
12 import java.io.*;
13
14 public class TibDoc {
15     
16     public static void main(String[] s) throws Exception {
17         System.out.println("parsing " + s[0]);
18         Tree<String> res = new CharToken.CharToStringParser(MetaGrammar.make()).parse(new CharToken.Stream(new FileInputStream(s[0]))).expand1();
19         MetaGrammar gram = (MetaGrammar)new Tib.Grammar().walk(res);
20         //System.out.println(gram);
21         Union mg = gram.done();
22         
23         System.out.println("\nparsing " + s[1]);
24         Forest f = new CharToken.CharToStringParser(mg).parse(new Tib(new FileInputStream(s[1])));
25
26         System.out.println();
27         System.out.println(f);
28         System.out.println();
29         System.out.println(((Tree)new StringifyWalker().walk(f.expand1())).toPrettyString());
30
31         String st = new HTMLWalker().walk(f.expand1()).toString();
32         System.out.println(st);
33         FileOutputStream fos = new FileOutputStream("out.html");
34         PrintWriter p = new PrintWriter(new OutputStreamWriter(fos));
35         p.println(st);
36         p.flush();
37         p.close();
38     }
39
40     public static class StringifyWalker extends ReflectiveWalker {
41         public Object walk(String head, Object[] children) {
42             if ("stringify".equals(head)) {
43                 StringBuffer ret = new StringBuffer();
44                 for(Tree<String> t : (Tree<String>)children[0]) ret.append(t);
45                 return new Tree<String>(null, ret.toString());
46             }
47             if (children.length==0) return new Tree<String>(null, head, new Tree[0]);
48             return new Tree<String>(null, head, (Tree<String>[])Reflection.lub(children));
49         }
50     }
51
52     public static String join(String[] sa, String sep) {
53         StringBuffer ret = new StringBuffer();
54         boolean first = true;
55         for(String s : sa) {
56             if (!first) ret.append(sep);
57             first = false;
58             ret.append(s);
59         }
60         return ret.toString();
61     }
62
63     public static class HTMLWalker extends ReflectiveWalker {
64         //public void header() { throw new Error(); }
65         public String li(Object o) { return "<li>"+o+"</li>"; }
66         public String ul(String[] li) { return "<ul>"+join(li,"")+"</ul>"; }
67         public String ol(String[] li) { return "<ol>"+join(li,"")+"</ol>"; }
68         public String hr() { return "\n<hr/>\n"; }
69         public String it(Object o) { return "<i>"+o+"</i>"; }
70         public String tt(Object o) { return "<tt>"+o+"</tt>"; }
71         public String underline(Object o) { return "<ul>"+o+"</ul>"; }
72         public String p(Object o) { return "<p>"+o+"</p>"; }
73         public String smallcap(Object o) { return "<span style='font-variant: small-caps'>"+o+"</span>"; }
74         public String blockquote(Object o) { return "<blockquote>"+o+"</blockquote>"; }
75         public String superscript(Object o) { return "<sup>"+o+"</sup>"; }
76         public String subscript(Object o) { return "<sub>"+o+"</sub>"; }
77         public String bold(Object o) { return "<b>"+o+"</b>"; }
78         public String strikethrough(Object o) { throw new Error();/*return "<b>"+o+"</b>";*/ }
79         public Object top(Object o) { return "<html><body>"+o+"</body></html>"; }
80         public Object doc(Object header, Object body) { return body; }
81         public String text(Object[] body) {
82             StringBuffer ret = new StringBuffer();
83             for(Object o : body) { ret.append(o); ret.append(" "); }
84             return ret.toString();
85         }
86         public String body(String[] sections) { return join(sections, "\n\n"); }
87         public String domain(String[] parts) { return join(parts, "."); }
88         public String ip(String[] parts) { return join(parts, "."); }
89         public String emailaddr(String user, String host) {
90             return link(user+"@"+host, "mailto:"+user+"@"+host);
91         }
92         //public String url(String method) {
93         public String link(Object text, Object target) {
94             return "<a href='"+target+"'>"+text+"</a>";
95         }
96         public String section(Object header, Object[] body) {
97             StringBuffer ret = new StringBuffer();
98             ret.append(header);
99             ret.append(" ");
100             for(Object o : body) ret.append(o);
101             return ret.toString();
102         }
103         private String escapify(Object o) {
104             String s = o==null ? "" : o.toString();
105             StringBuffer sb = new StringBuffer();
106             for(int i=0; i<s.length(); i++) {
107                 switch(s.charAt(i)) {
108                     case '&':  sb.append("&amp;"); break;
109                     case '<':  sb.append("&lt;"); break;
110                     case '>':  sb.append("&gt;"); break;
111                     case '\'': sb.append("&apos;"); break;
112                     case '\"': sb.append("&quot;"); break;
113                     default:   sb.append(s.charAt(i)); break;
114                 }
115             }
116             return sb.toString();
117         }
118         private Tree<String> lone(String s) {
119             return new Tree<String>(null, s, new Tree[0]);
120         }
121         public Object walk(Tree<String> t) {
122             String head = t.head();
123             if ("stringify".equals(head)) {
124                 StringBuffer ret = new StringBuffer();
125                 for(Tree<String> child : t.child(0)) ret.append(child);
126                 return ret.toString();
127             }
128             return super.walk(t);
129         }
130         protected Object defaultWalk(String head, Object[] children) {
131             Tree<String>[] kids = new Tree[children.length];
132             for(int i=0; i<children.length; i++) {
133                 if (children[i]==null) kids[i]=null;
134                 else if (children[i] instanceof String) kids[i] = lone(escapify((String)children[i]));
135                 else if (children[i] instanceof Tree) kids[i] = (Tree<String>)children[i];
136                 else kids[i] = lone(children[i].toString());
137             }
138             return new Tree<String>(null, head, kids);
139         }
140     }
141
142     /*
143     public static enum Style { H, UL, TT, SO, IT, Q, B, PRE, LIST, EMDASH; }
144
145     public static AST h(AST a)      { return new Gather(a, Style.H); }
146     public static AST ul(AST a)     { return new Gather(a, Style.UL); }
147     public static AST tt(AST a)     { return new Gather(a, Style.TT); }
148     public static AST so(AST a)     { return new Gather(a, Style.SO); }
149     public static AST it(AST a)     { return new Gather(a, Style.IT); }
150     public static AST q(AST a)      { return new Gather(a, Style.Q); }
151     public static AST b(AST a)      { return new Gather(a, Style.B); }
152     public static AST pre(AST a)    { return new Gather(a, Style.PRE); }
153     public static AST list(AST a)   { return new Gather(a, Style.LIST); }
154     public static AST emdash()      { return new Gather(Style.EMDASH); }
155
156     public static AST seq(AST a) { return new Gather(a); }
157
158     public static class Latex {
159         public static void emit(PrintWriter p, AST a) {
160             prefix(p);
161             emit(p, a, "");
162             suffix(p);
163         }
164         public static void emit2(PrintWriter p, AST ast, String head) {
165             for(AST a = ast.getFirstChild(); a != null; a = a.getNextSibling()) emit(p, a, head);
166         }
167         public static void emit(PrintWriter p, AST ast, String head) {
168             if (!(ast instanceof Gather)) {
169                 if (ast.getNumberOfChildren()==0) {
170                     p.print(ast.getText());
171                 } else {
172                     emit2(p, ast, head);
173                 }
174                 return;
175             }
176             Gather a = (Gather)ast;
177             if (a.style==null) {
178                 emit2(p, a, head);
179                 return;
180             }
181             switch(a.style) {
182                 case H:    p.println(); p.println(); p.print("\\"+head+"section{"); emit2(p, a, "sub"+head); p.println("}"); break;
183                 case B:    p.print("{\\bf{");                          emit2(p, a, head); p.print("}}"); break;
184                 case UL:   p.print("{\\ul{");                          emit2(p, a, head); p.print("}}"); break;
185                 case IT:   p.print("{\\it{");                          emit2(p, a, head); p.print("}}"); break;
186                 case TT:   p.print("{\\tt{");                          emit2(p, a, head); p.print("}}"); break;
187                 case SO:   p.print("{\\overstrike{");                  emit2(p, a, head); p.print("}}"); break;
188                 case Q:    p.print("``");                              emit2(p, a, head); p.print("''"); break;
189                 case EMDASH: p.print(" \\emdash "); break;
190                 case LIST: p.println(); p.println("\\startitemize[symbol]"); emit2(p, a, head); p.println("\\stopitemize"); break;
191                 case PRE:
192                     if (a.getFirstChild() != null) {
193                         p.println();
194                         p.println("\\begin{verbatim}");
195                         p.println(a.getFirstChild().getText());
196                         p.println("\\end{verbatim}");
197                     }
198             }
199         }
200         public static void prefix(PrintWriter p) {
201             p.println("% generated by TIBDOC");
202             for(int i=0; i<packages.length; i++) p.println("\\usemodule["+packages[i]+"]");
203             p.println("\\setuppapersize[letter]");
204             p.println("\\setuppagenumbering[location=]");
205             p.println("\\setupcolors[state=start]");
206             //"\\setupinteraction[title={Title},author={Me},"++
207             //"subtitle={Deez Nutz},keywords={blargh},color=blue]\n" ++
208             //"\\setuppublications[database={me},numbering=yes,sort=author]\n" ++
209             p.println("\\setuphead[section][style={\\ss\\bfa},number=no,before=\\blank\\hairline\\nowhitespace]");
210             p.println("\\definelayout[mypage][backspace=1.75in,cutspace=1.75in,width=5in]");
211             p.println("\\setuplayout[mypage]");
212             p.println("\\definetypeface[myface][rm][Xserif][Warnock Pro]");
213             p.println("\\definetypeface[myface][tt][Xmono][CMU Typewriter Text Regular][default]");
214             p.println("\\definetypeface[myface][ss][Xsans][Myriad Pro][default]");
215             p.println("\\usesymbols[uni]");
216             p.println("\\definesymbol[1][{\\USymbCharZapf{39}{164}}]");
217             p.println("\\setupbodyfont[myface, 11pt]");
218             p.println("\\setupwhitespace[7pt]");
219             p.println("\\def\\MyDroppedCaps%");
220             p.println("    {\\DroppedCaps");
221             p.println("        {} {Serif} {2\\baselineskip} {2pt} {1\\baselineskip} {2}}");
222             p.println("\\starttext");
223             p.println("\\switchtobodyfont[16pt]\\midaligned{\\ss\\bfa{Title}}\\switchtobodyfont[10pt]");
224             p.println("\\midaligned{Adam Megacz}\n\n\\nowhitespace\\midaligned{\\tt{adam@megacz.com}}");
225             p.println("\\blank[1cm,force]");
226             //p.println("\\defineparagraphs[mypar][n=2,before={\\blank},after={\\blank}");
227             //p.println("\\setupparagraphs[mypar][1][width=.45\\textwidth");
228             //p.println("\\setupparagraphs[mypar][2][width=.55\\textwidth");
229             //p.println("\\startmypa");
230             //p.println("\\switchtobodyfont[sma");
231         }
232
233         public static void suffix(PrintWriter p) {
234             p.println("\\stoptext");
235         }
236         static String[] packages = new String[] { "supp-fun", "bib", "href" };
237     }
238
239     // ConTex
240
241 module Contex where
242 import Data.Array.IArray
243 import Data.Char
244 import Util
245 import Lexer
246 import IR
247 import Data.List
248 import Beautify
249
250 toContex ll = prefix ++ (concatMap tl ll) ++ suffix
251  where
252   packages                         = [ "[supp-fun]",
253                                        "[bib]",
254                                        "[href]" ]
255   prefix                           = (concatMap (\x -> "\\usemodule"++x++"\n") packages) ++
256                                      "\\setuppapersize[letter]\n" ++
257                                      "\\setuppagenumbering[location=]\n" ++
258                                      "\\setupcolors[state=start]\n" ++
259                                      --"\\setupinteraction[title={Title},author={Me},"++
260                                      --"subtitle={Deez Nutz},keywords={blargh},color=blue]\n" ++
261                                      --"\\setuppublications[database={me},numbering=yes,sort=author]\n" ++
262                                      "\\setuphead[section][style={\\ss\\bfa},\n" ++
263                                      "                     number=no,\n" ++
264                                      "                     before=\\blank\\hairline\\nowhitespace,\n" ++
265                                      "                     ]\n" ++
266                                      "\\definelayout[mypage][\n" ++
267                                      " backspace=1.75in, % the space for margin notes\n" ++
268                                      " cutspace=1.75in, % the space for right margin notes\n" ++
269                                      " width=5in" ++
270                                      "]\n" ++
271                                      "\\setuplayout[mypage]\n" ++
272                                      "\\definetypeface[myface][rm][Xserif][Warnock Pro]\n" ++
273                                      "\\definetypeface[myface][tt][Xmono][CMU Typewriter Text Regular][default]\n" ++
274                                      "\\definetypeface[myface][ss][Xsans][Myriad Pro][default]\n" ++
275                                      "\\usesymbols[uni]\n" ++
276                                      "\\definesymbol[1][{\\USymbCharZapf{39}{164}}]\n" ++
277                                      "\\setupbodyfont[myface, 11pt]\n" ++
278                                      "\\setupwhitespace[7pt]\n" ++
279                                      "\\def\\MyDroppedCaps%\n" ++
280                                      "    {\\DroppedCaps\n" ++
281                                      "        {} {Serif} {2\\baselineskip} {2pt} {1\\baselineskip} {2}}\n" ++
282                                      "\\starttext\n" ++
283                                      "\\switchtobodyfont[16pt]\\midaligned{\\ss\\bfa{Hi5 Replicated Server Infrastructure}}\\switchtobodyfont[10pt]\n"++ 
284                                      "\\midaligned{Adam Megacz}\n\n\\nowhitespace\\midaligned{\\tt{adam@megacz.com}}\n\n"++
285                                      "\\blank[1cm,force]\n" ++
286                                      "\\defineparagraphs[mypar][n=2,before={\\blank},after={\\blank}]\n"++
287                                      "\\setupparagraphs[mypar][1][width=.45\\textwidth]\n"++
288                                      "\\setupparagraphs[mypar][2][width=.55\\textwidth]\n"++
289                                      "\\startmypar"++
290                                      "\\switchtobodyfont[small]\n"
291   suffix                           = "\n\\stoptext\n"
292   addItem i                        = "\\item " ++ (striptrail $ boost 8 $ wrap $ striplead $ tl i)
293   escapify []                      = []
294   escapify ('%':t)                 = '\\':'%':(escapify t)
295   escapify ('$':t)                 = '\\':'$':(escapify t)
296   escapify (h:t)                   = h:(escapify t)
297   escapeMath s                     = s
298   tl (Special _ BulletList l)      = "\\startitemize[symbol]\n" ++ (concatMap addItem l) ++ "\\stopitemize\n"
299   tl (Special _ NumberList l)      = "\\startitemize[symbol]\n" ++ (concatMap addItem l) ++ "\\stopitemize\n"
300   tl (Special _ Section (h:t))     = "\\section{"++(tl h)++"}\n"++(concatMap tl t)
301   tl (Special _ NumberedSection (h:t)) = "\\section{"++(tl h)++"}\n"++(concatMap tl t)
302   tl (Special _ (Glyph EmDash) []) = "{\\emdash}"
303 --tl (Special _ Superscript l)     = 
304 --tl (Special _ Subscript l)       = 
305 --tl (Special _ (Image u) l)       = 
306 --tl (Special _ (Cite u) l)        = 
307   tl (Special _ BlockQuote l)      = "\n\n\\startquote\n     "++
308                                      (striptrail $ boost 4 $ wrap $ striplead $ concatMap tl l)++"\n\\stopquote\n\n"
309   tl (Special _ HorizontalRule []) = "\\\\\\rule{4in}{0.5pt}\\\\"
310   tl (Special _ Italic l)          = "{\\it{"++(concatMap tl l)++"}}"
311   tl (Special _ Bold l)            = "{\\bf{"++(concatMap tl l)++"}}"
312   tl (Special _ DropCap (h:t))     = "\\MyDroppedCaps{"++(tl h)++"}{\\sc "++(concatMap tl t)++"}"
313   tl (Special _ Typewriter l)      = "{\\tt{"++(concatMap tl l)++"}}"
314   tl (Special _ StrikeThrough l)   = "" --"\\sout{"++(concatMap tl l)++"}"
315   tl (Special _ Quotes l)          = "``"++(concatMap tl l)++"''"
316   tl (Special _ Underline l)       = "" --"\\uline{"++(concatMap tl l)++"}"
317   tl (Special _ Underline2 l)      = "" --"\\uuline{"++(concatMap tl l)++"}"
318   tl (Special _ (Math s) [])       = "\\placeformula\n$$\n" ++ (escapeMath s) ++ "\n$$\n"
319   tl (Special _ Footnote l)        = "\\footnote{"++(concatMap tl l)++"}"
320   tl (Special _ Float l)           = "" --"\n\n\\begin{wrapfigure}{r}{0.4\\textwidth} \\framebox[0.4\\textwidth]{"++
321                                      --(concatMap tl l)++"} \\label{x}\\end{wrapfigure}\n\n"
322 --tl (Special _ Figure l)          = "\\placefigure[][fig:church]{}{"++(concatMap tl l)++"}"
323   tl (Special _ Figure l)          = "\\startnarrower\n"++(concatMap tl l)++"\n\\stopnarrower\n"
324   tl (Special _ (Link u) l)        = "\\href{"++(escapify u)++"}{"++(concatMap tl l)++"}"
325   tl (Special _ (Verbatim s) [])   = "\\starttyping\n"++s++"\n\\stoptyping\n"
326 --  tl (Special _ TwoColumn l)       = "\\startcolumns[n=2]\n"++(concatMap tl l)++"\\stopcolumns"
327 --  tl (Special _ Title l)           = ""--"\\title{"++(concatMap tl l)++"}\n\\maketitle\n\n\n"
328   tl (Special _ Abstract l) =
329       "\\midaligned{\\ss\\bfa Abstract}\\par\n " ++
330       "\n\n"++(concatMap tl l)++"\\mypar" ++
331       "\\switchtobodyfont[8pt]{\\ss{\\placecontent}}\\switchtobodyfont[normal]\\stopmypar\n\n\\blank[1cm,force]"
332   tl (Special _ (Command c) l)     = "\\"++c++"["++(concatMap tl l)++"]"
333   tl (Special _ t l)               = error $ "formatting code "++(show t)++" not supported on {"++(concatMap show l)++"})"
334   tl (WS _)                        = " "
335   tl (BlankLine _)                 = "\n\n"
336   tl (Block _ l)                   = concatMap tl l
337   tl (Letter _ c)                  = escapify [c]
338   tl z                             = (show z)
339
340
341
342
343     */
344 }
345