src/Pure/Thy/present.ML
author wenzelm
Sun Mar 20 19:47:26 2011 +0100 (2011-03-20)
changeset 42008 7423e833a880
parent 42007 2142883ec29f
child 42009 b008525c4399
permissions -rw-r--r--
Present.init/finish/no_document are not thread-safe -- eliminated futile CRITICAL sections;
tuned;
     1 (*  Title:      Pure/Thy/present.ML
     2     Author:     Markus Wenzel and Stefan Berghofer, TU Muenchen
     3 
     4 Theory presentation: HTML, graph files, (PDF)LaTeX documents.
     5 *)
     6 
     7 signature BASIC_PRESENT =
     8 sig
     9   val no_document: ('a -> 'b) -> 'a -> 'b  (*not thread-safe!*)
    10 end;
    11 
    12 signature PRESENT =
    13 sig
    14   include BASIC_PRESENT
    15   val session_name: theory -> string
    16   val write_graph: {name: string, ID: string, dir: string, unfold: bool,
    17    path: string, parents: string list} list -> Path.T -> unit
    18   val display_graph: {name: string, ID: string, dir: string, unfold: bool,
    19    path: string, parents: string list} list -> unit
    20   val init: bool -> bool -> string -> bool -> string list -> string list ->
    21     string -> (bool * Path.T) option -> Url.T option * bool -> bool ->
    22     theory list -> unit  (*not thread-safe!*)
    23   val finish: unit -> unit  (*not thread-safe!*)
    24   val init_theory: string -> unit
    25   val theory_source: string -> (unit -> HTML.text) -> unit
    26   val theory_output: string -> string -> unit
    27   val begin_theory: int -> Path.T -> (Path.T * bool) list -> theory -> theory
    28   val drafts: string -> Path.T list -> Path.T
    29 end;
    30 
    31 structure Present: PRESENT =
    32 struct
    33 
    34 
    35 (** paths **)
    36 
    37 val output_path = Path.variable "ISABELLE_BROWSER_INFO";
    38 
    39 val tex_ext = Path.ext "tex";
    40 val tex_path = tex_ext o Path.basic;
    41 val html_ext = Path.ext "html";
    42 val html_path = html_ext o Path.basic;
    43 val index_path = Path.basic "index.html";
    44 val readme_html_path = Path.basic "README.html";
    45 val readme_path = Path.basic "README";
    46 val documentN = "document";
    47 val document_path = Path.basic documentN;
    48 val doc_indexN = "session";
    49 val graph_path = Path.basic "session.graph";
    50 val graph_pdf_path = Path.basic "session_graph.pdf";
    51 val graph_eps_path = Path.basic "session_graph.eps";
    52 
    53 val session_path = Path.basic ".session";
    54 val session_entries_path = Path.explode ".session/entries";
    55 val pre_index_path = Path.explode ".session/pre-index";
    56 
    57 fun mk_rel_path [] ys = Path.make ys
    58   | mk_rel_path xs [] = Path.appends (replicate (length xs) Path.parent)
    59   | mk_rel_path (ps as x :: xs) (qs as y :: ys) = if x = y then mk_rel_path xs ys else
    60       Path.appends (replicate (length ps) Path.parent @ [Path.make qs]);
    61 
    62 fun show_path path = Path.implode (Path.append (File.pwd ()) path);
    63 
    64 
    65 
    66 (** additional theory data **)
    67 
    68 structure Browser_Info = Theory_Data
    69 (
    70   type T = {name: string, session: string list, is_local: bool};
    71   val empty = {name = "", session = [], is_local = false}: T;
    72   fun extend _ = empty;
    73   fun merge _ = empty;
    74 );
    75 
    76 val put_info = Browser_Info.put;
    77 val get_info = Browser_Info.get;
    78 val session_name = #name o get_info;
    79 
    80 
    81 
    82 (** graphs **)
    83 
    84 type graph_node =
    85   {name: string, ID: string, dir: string, unfold: bool,
    86    path: string, parents: string list};
    87 
    88 fun write_graph gr path =
    89   File.write path (cat_lines (map (fn {name, ID, dir, unfold, path, parents} =>
    90     "\"" ^ name ^ "\" \"" ^ ID ^ "\" \"" ^ dir ^ (if unfold then "\" + \"" else "\" \"") ^
    91     path ^ "\" > " ^ space_implode " " (map quote parents) ^ " ;") gr));
    92 
    93 fun display_graph gr =
    94   let
    95     val _ = writeln "Displaying graph ...";
    96     val path = File.tmp_path (Path.explode "tmp.graph");
    97     val _ = write_graph gr path;
    98     val _ = Isabelle_System.isabelle_tool "browser" ("-c " ^ File.shell_path path ^ " &");
    99   in () end;
   100 
   101 
   102 fun ID_of sess s = space_implode "/" (sess @ [s]);
   103 fun ID_of_thy thy = ID_of (#session (get_info thy)) (Context.theory_name thy);
   104 
   105 
   106 (*retrieve graph data from initial collection of theories*)
   107 fun init_graph remote_path curr_sess = rev o map (fn thy =>
   108   let
   109     val name = Context.theory_name thy;
   110     val {name = sess_name, session, is_local} = get_info thy;
   111     val path' = Path.append (Path.make session) (html_path name);
   112     val entry =
   113      {name = name, ID = ID_of session name, dir = sess_name,
   114       path =
   115         if null session then "" else
   116         if is_some remote_path andalso not is_local then
   117           Url.implode (Url.append (the remote_path) (Url.File
   118             (Path.append (Path.make session) (html_path name))))
   119         else Path.implode (Path.append (mk_rel_path curr_sess session) (html_path name)),
   120       unfold = false,
   121       parents = map ID_of_thy (Theory.parents_of thy)};
   122   in (0, entry) end);
   123 
   124 fun ins_graph_entry (i, entry as {ID, ...}) (gr: (int * graph_node) list) =
   125   (i, entry) :: filter_out (fn (_, entry') => #ID entry' = ID) gr;
   126 
   127 
   128 
   129 (** global browser info state **)
   130 
   131 (* type theory_info *)
   132 
   133 type theory_info = {tex_source: Buffer.T, html_source: Buffer.T, html: Buffer.T};
   134 
   135 fun make_theory_info (tex_source, html_source, html) =
   136   {tex_source = tex_source, html_source = html_source, html = html}: theory_info;
   137 
   138 val empty_theory_info = make_theory_info (Buffer.empty, Buffer.empty, Buffer.empty);
   139 
   140 fun map_theory_info f {tex_source, html_source, html} =
   141   make_theory_info (f (tex_source, html_source, html));
   142 
   143 
   144 (* type browser_info *)
   145 
   146 type browser_info = {theories: theory_info Symtab.table, files: (Path.T * string) list,
   147   tex_index: (int * string) list, html_index: (int * string) list, graph: (int * graph_node) list};
   148 
   149 fun make_browser_info (theories, files, tex_index, html_index, graph) =
   150   {theories = theories, files = files, tex_index = tex_index, html_index = html_index,
   151     graph = graph}: browser_info;
   152 
   153 val empty_browser_info = make_browser_info (Symtab.empty, [], [], [], []);
   154 
   155 fun init_browser_info remote_path curr_sess thys = make_browser_info
   156   (Symtab.empty, [], [], [], init_graph remote_path curr_sess thys);
   157 
   158 fun map_browser_info f {theories, files, tex_index, html_index, graph} =
   159   make_browser_info (f (theories, files, tex_index, html_index, graph));
   160 
   161 
   162 (* state *)
   163 
   164 val browser_info = Unsynchronized.ref empty_browser_info;
   165 fun change_browser_info f =
   166   CRITICAL (fn () => Unsynchronized.change browser_info (map_browser_info f));
   167 
   168 val suppress_tex_source = Unsynchronized.ref false;
   169 fun no_document f x = Unsynchronized.setmp suppress_tex_source true f x;
   170 
   171 fun init_theory_info name info =
   172   change_browser_info (fn (theories, files, tex_index, html_index, graph) =>
   173     (Symtab.update (name, info) theories, files, tex_index, html_index, graph));
   174 
   175 fun change_theory_info name f =
   176   change_browser_info (fn (info as (theories, files, tex_index, html_index, graph)) =>
   177     (case Symtab.lookup theories name of
   178       NONE => error ("Browser info: cannot access theory document " ^ quote name)
   179     | SOME info => (Symtab.update (name, map_theory_info f info) theories, files,
   180         tex_index, html_index, graph)));
   181 
   182 
   183 fun add_file file =
   184   change_browser_info (fn (theories, files, tex_index, html_index, graph) =>
   185     (theories, file :: files, tex_index, html_index, graph));
   186 
   187 fun add_tex_index txt =
   188   change_browser_info (fn (theories, files, tex_index, html_index, graph) =>
   189     (theories, files, txt :: tex_index, html_index, graph));
   190 
   191 fun add_html_index txt =
   192   change_browser_info (fn (theories, files, tex_index, html_index, graph) =>
   193     (theories, files, tex_index, txt :: html_index, graph));
   194 
   195 fun add_graph_entry entry =
   196   change_browser_info (fn (theories, files, tex_index, html_index, graph) =>
   197     (theories, files, tex_index, html_index, ins_graph_entry entry graph));
   198 
   199 fun add_tex_source name txt =
   200   if ! suppress_tex_source then ()
   201   else change_theory_info name (fn (tex_source, html_source, html) =>
   202     (Buffer.add txt tex_source, html_source, html));
   203 
   204 fun add_html_source name txt = change_theory_info name (fn (tex_source, html_source, html) =>
   205   (tex_source, Buffer.add txt html_source, html));
   206 
   207 fun add_html name txt = change_theory_info name (fn (tex_source, html_source, html) =>
   208   (tex_source, html_source, Buffer.add txt html));
   209 
   210 
   211 
   212 (** global session state **)
   213 
   214 (* session_info *)
   215 
   216 type session_info =
   217   {name: string, parent: string, session: string, path: string list, html_prefix: Path.T,
   218     info: bool, doc_format: string, doc_graph: bool, documents: (string * string) list,
   219     dump_prefix: (bool * Path.T) option, remote_path: Url.T option, verbose: bool,
   220     readme: Path.T option};
   221 
   222 fun make_session_info
   223   (name, parent, session, path, html_prefix, info, doc_format, doc_graph, documents,
   224     dump_prefix, remote_path, verbose, readme) =
   225   {name = name, parent = parent, session = session, path = path, html_prefix = html_prefix,
   226     info = info, doc_format = doc_format, doc_graph = doc_graph, documents = documents,
   227     dump_prefix = dump_prefix, remote_path = remote_path, verbose = verbose,
   228     readme = readme}: session_info;
   229 
   230 
   231 (* state *)
   232 
   233 val session_info = Unsynchronized.ref (NONE: session_info option);
   234 
   235 fun with_session x f = (case ! session_info of NONE => x | SOME info => f info);
   236 
   237 
   238 
   239 (** document preparation **)
   240 
   241 (* maintain index *)
   242 
   243 val session_entries =
   244   HTML.session_entries o
   245     map (fn name => (Url.File (Path.append (Path.basic name) index_path), name));
   246 
   247 fun get_entries dir =
   248   split_lines (File.read (Path.append dir session_entries_path));
   249 
   250 fun put_entries entries dir =
   251   File.write (Path.append dir session_entries_path) (cat_lines entries);
   252 
   253 
   254 fun create_index dir =
   255   File.read (Path.append dir pre_index_path) ^
   256     session_entries (get_entries dir) ^ HTML.end_document
   257   |> File.write (Path.append dir index_path);
   258 
   259 fun update_index dir name =
   260   (case try get_entries dir of
   261     NONE => warning ("Browser info: cannot access session index of " ^ Path.print dir)
   262   | SOME es => (put_entries ((remove (op =) name es) @ [name]) dir; create_index dir));
   263 
   264 
   265 (* document variants *)
   266 
   267 fun read_variant str =
   268   (case space_explode "=" str of
   269     [name] => (name, "")
   270   | [name, tags] => (name, tags)
   271   | _ => error ("Malformed document variant specification: " ^ quote str));
   272 
   273 fun read_variants strs =
   274   rev (distinct (eq_fst (op =)) (rev ((documentN, "") :: map read_variant strs)))
   275   |> filter_out (fn (_, s) => s = "-");
   276 
   277 
   278 (* init session *)
   279 
   280 fun name_of_session elems = space_implode "/" ("Isabelle" :: elems);
   281 
   282 fun init build info doc doc_graph doc_variants path name dump_prefix
   283     (remote_path, first_time) verbose thys =
   284   if not build andalso not info andalso doc = "" andalso is_none dump_prefix then
   285     (browser_info := empty_browser_info; session_info := NONE)
   286   else
   287     let
   288       val parent_name = name_of_session (take (length path - 1) path);
   289       val session_name = name_of_session path;
   290       val sess_prefix = Path.make path;
   291       val html_prefix = Path.append (Path.expand output_path) sess_prefix;
   292 
   293       val documents =
   294         if doc = "" then []
   295         else if not (can File.check_dir document_path) then
   296           (if verbose then Output.raw_stderr "Warning: missing document directory\n" else (); [])
   297         else read_variants doc_variants;
   298 
   299       val parent_index_path = Path.append Path.parent index_path;
   300       val index_up_lnk =
   301         if first_time then
   302           Url.append (the remote_path) (Url.File (Path.append sess_prefix parent_index_path))
   303         else Url.File parent_index_path;
   304       val readme =
   305         if File.exists readme_html_path then SOME readme_html_path
   306         else if File.exists readme_path then SOME readme_path
   307         else NONE;
   308 
   309       val docs =
   310         (case readme of NONE => [] | SOME p => [(Url.File p, "README")]) @
   311           map (fn (name, _) => (Url.File (Path.ext doc (Path.basic name)), name)) documents;
   312       val index_text = HTML.begin_index (index_up_lnk, parent_name)
   313         (Url.File index_path, session_name) docs (Url.explode "medium.html");
   314     in
   315       session_info :=
   316         SOME (make_session_info (name, parent_name, session_name, path, html_prefix,
   317           info, doc, doc_graph, documents, dump_prefix, remote_path, verbose, readme));
   318       browser_info := init_browser_info remote_path path thys;
   319       add_html_index (0, index_text)
   320     end;
   321 
   322 
   323 (* isabelle tool wrappers *)
   324 
   325 fun isabelle_document verbose format name tags path result_path =
   326   let
   327     val s = "\"$ISABELLE_TOOL\" document -c -o '" ^ format ^ "' \
   328       \-n '" ^ name ^ "' -t '" ^ tags ^ "' " ^ File.shell_path path ^ " 2>&1";
   329     val doc_path = Path.append result_path (Path.ext format (Path.basic name));
   330     val _ = if verbose then writeln s else ();
   331     val (out, rc) = bash_output s;
   332     val _ =
   333       if not (File.exists doc_path) orelse rc <> 0 then
   334         cat_error out ("Failed to build document " ^ quote (show_path doc_path))
   335       else if verbose then writeln out
   336       else ();
   337   in doc_path end;
   338 
   339 fun isabelle_browser graph =
   340   let
   341     val pdf_path = File.tmp_path graph_pdf_path;
   342     val eps_path = File.tmp_path graph_eps_path;
   343     val gr_path = File.tmp_path graph_path;
   344     val args = "-o " ^ File.shell_path pdf_path ^ " " ^ File.shell_path gr_path;
   345   in
   346     write_graph graph gr_path;
   347     if Isabelle_System.isabelle_tool "browser" args <> 0 orelse
   348       not (File.exists eps_path) orelse not (File.exists pdf_path)
   349     then error "Failed to prepare dependency graph"
   350     else
   351       let val pdf = File.read pdf_path and eps = File.read eps_path
   352       in File.rm pdf_path; File.rm eps_path; File.rm gr_path; (pdf, eps) end
   353   end;
   354 
   355 
   356 (* finish session -- output all generated text *)
   357 
   358 fun sorted_index index = map snd (sort (int_ord o pairself fst) (rev index));
   359 fun index_buffer index = Buffer.add (implode (sorted_index index)) Buffer.empty;
   360 
   361 fun write_tex src name path =
   362   File.write_buffer (Path.append path (tex_path name)) src;
   363 
   364 fun write_tex_index tex_index path =
   365   write_tex (index_buffer tex_index |> Buffer.add Latex.tex_trailer) doc_indexN path;
   366 
   367 
   368 fun finish () =
   369   with_session () (fn {name, info, html_prefix, doc_format,
   370     doc_graph, documents, dump_prefix, path, verbose, readme, ...} =>
   371   let
   372     val {theories, files, tex_index, html_index, graph} = ! browser_info;
   373     val thys = Symtab.dest theories;
   374     val parent_html_prefix = Path.append html_prefix Path.parent;
   375 
   376     fun finish_tex path (a, {tex_source, ...}: theory_info) = write_tex tex_source a path;
   377     fun finish_html (a, {html, ...}: theory_info) =
   378       File.write_buffer (Path.append html_prefix (html_path a)) (Buffer.add HTML.end_document html);
   379 
   380     val sorted_graph = sorted_index graph;
   381     val opt_graphs =
   382       if doc_graph andalso (not (null documents) orelse is_some dump_prefix) then
   383         SOME (isabelle_browser sorted_graph)
   384       else NONE;
   385 
   386     fun prepare_sources cp path =
   387      (Isabelle_System.mkdirs path;
   388       if cp then Isabelle_System.copy_dir document_path path else ();
   389       Isabelle_System.isabelle_tool "latex"
   390         ("-o sty " ^ File.shell_path (Path.append path (Path.basic "root.tex")));
   391       (case opt_graphs of NONE => () | SOME (pdf, eps) =>
   392         (File.write (Path.append path graph_pdf_path) pdf;
   393           File.write (Path.append path graph_eps_path) eps));
   394       write_tex_index tex_index path;
   395       List.app (finish_tex path) thys);
   396     val _ =
   397       if info then
   398        (Isabelle_System.mkdirs (Path.append html_prefix session_path);
   399         File.write_buffer (Path.append html_prefix pre_index_path) (index_buffer html_index);
   400         File.write (Path.append html_prefix session_entries_path) "";
   401         create_index html_prefix;
   402         if length path > 1 then update_index parent_html_prefix name else ();
   403         (case readme of NONE => () | SOME path => File.copy path html_prefix);
   404         write_graph sorted_graph (Path.append html_prefix graph_path);
   405         Isabelle_System.isabelle_tool "browser" "-b";
   406         File.copy (Path.explode "~~/lib/browser/GraphBrowser.jar") html_prefix;
   407         List.app (fn (a, txt) => File.write (Path.append html_prefix (Path.basic a)) txt)
   408           (HTML.applet_pages name (Url.File index_path, name));
   409         File.copy (Path.explode "~~/lib/html/isabelle.css") html_prefix;
   410         List.app finish_html thys;
   411         List.app (uncurry File.write) files;
   412         if verbose then Output.raw_stderr ("Browser info at " ^ show_path html_prefix ^ "\n")
   413         else ())
   414       else ();
   415 
   416     val _ =
   417       (case dump_prefix of NONE => () | SOME (cp, path) =>
   418        (prepare_sources cp path;
   419         if verbose then Output.raw_stderr ("Document sources at " ^ show_path path ^ "\n")
   420         else ()));
   421 
   422     val doc_paths =
   423       documents |> map (fn (name, tags) =>
   424         let
   425           val path = Path.append html_prefix document_path;
   426           val _ = prepare_sources true path;
   427         in isabelle_document true doc_format name tags path html_prefix end);
   428     val _ =
   429       if verbose then
   430         doc_paths |> List.app (fn doc => Output.raw_stderr ("Document at " ^ show_path doc ^ "\n"))
   431       else ();
   432   in
   433     browser_info := empty_browser_info;
   434     session_info := NONE
   435   end);
   436 
   437 
   438 (* theory elements *)
   439 
   440 fun init_theory name = with_session () (fn _ => init_theory_info name empty_theory_info);
   441 
   442 fun theory_source name mk_text =
   443   with_session () (fn _ => add_html_source name (HTML.theory_source (mk_text ())));
   444 
   445 fun theory_output name s =
   446   with_session () (fn _ => add_tex_source name (Latex.isabelle_file name s));
   447 
   448 
   449 fun parent_link remote_path curr_session thy =
   450   let
   451     val {name = _, session, is_local} = get_info thy;
   452     val name = Context.theory_name thy;
   453     val link =
   454       if null session then NONE
   455       else SOME
   456        (if is_some remote_path andalso not is_local then
   457          Url.append (the remote_path) (Url.File (Path.append (Path.make session) (html_path name)))
   458         else Url.File (Path.append (mk_rel_path curr_session session) (html_path name)));
   459   in (link, name) end;
   460 
   461 fun begin_theory update_time dir files thy =
   462     with_session thy (fn {name = sess_name, session, path, html_prefix, remote_path, ...} =>
   463   let
   464     val name = Context.theory_name thy;
   465     val parents = Theory.parents_of thy;
   466     val parent_specs = map (parent_link remote_path path) parents;
   467 
   468     val files_html = files |> map (fn (raw_path, loadit) =>
   469       let
   470         val path = Thy_Load.check_file dir raw_path;
   471         val base = Path.base path;
   472         val base_html = html_ext base;
   473         val _ = add_file (Path.append html_prefix base_html,
   474           HTML.external_file (Url.File base) (File.read path));
   475       in (Url.File base_html, Url.File raw_path, loadit) end);
   476 
   477     fun prep_html_source (tex_source, html_source, html) =
   478       let
   479         val txt = HTML.begin_theory (Url.File index_path, session)
   480           name parent_specs files_html (Buffer.content html_source)
   481       in (tex_source, Buffer.empty, Buffer.add txt html) end;
   482 
   483     val entry =
   484      {name = name, ID = ID_of path name, dir = sess_name, unfold = true,
   485       path = Path.implode (html_path name),
   486       parents = map ID_of_thy parents};
   487   in
   488     change_theory_info name prep_html_source;
   489     add_graph_entry (update_time, entry);
   490     add_html_index (update_time, HTML.theory_entry (Url.File (html_path name), name));
   491     add_tex_index (update_time, Latex.theory_entry name);
   492     put_info {name = sess_name, session = path, is_local = is_some remote_path} thy
   493   end);
   494 
   495 
   496 
   497 (** draft document output **)  (* FIXME doc_path etc. not thread-safe *)
   498 
   499 fun drafts doc_format src_paths =
   500   let
   501     fun prep_draft path i =
   502       let
   503         val base = Path.base path;
   504         val name =
   505           (case Path.implode (#1 (Path.split_ext base)) of
   506             "" => "DUMMY" ^ serial_string ()
   507           | s => s);
   508       in
   509         if File.exists path then
   510           (((name, base, File.read path), (i, Latex.theory_entry name)), i + 1)
   511         else error ("Bad file: " ^ Path.print path)
   512       end;
   513     val (srcs, tex_index) = split_list (fst (fold_map prep_draft src_paths 0));
   514 
   515     val doc_path = File.tmp_path document_path;
   516     val result_path = Path.append doc_path Path.parent;
   517     val _ = Isabelle_System.mkdirs doc_path;
   518     val root_path = Path.append doc_path (Path.basic "root.tex");
   519     val _ = File.copy (Path.explode "~~/lib/texinputs/draft.tex") root_path;
   520     val _ = Isabelle_System.isabelle_tool "latex" ("-o sty " ^ File.shell_path root_path);
   521     val _ = Isabelle_System.isabelle_tool "latex" ("-o syms " ^ File.shell_path root_path);
   522 
   523     fun known name =
   524       let val ss = split_lines (File.read (Path.append doc_path (Path.basic name)))
   525       in member (op =) ss end;
   526     val known_syms = known "syms.lst";
   527     val known_ctrls = known "ctrls.lst";
   528 
   529     val _ = srcs |> List.app (fn (name, base, txt) =>
   530       Symbol.explode txt
   531       |> Latex.symbol_source (known_syms, known_ctrls) (Path.implode base)
   532       |> File.write (Path.append doc_path (tex_path name)));
   533     val _ = write_tex_index tex_index doc_path;
   534   in isabelle_document false doc_format documentN "" doc_path result_path end;
   535 
   536 
   537 end;
   538 
   539 structure Basic_Present: BASIC_PRESENT = Present;
   540 open Basic_Present;