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