src/Pure/Thy/thy_info.ML
author wenzelm
Mon May 14 22:22:47 2018 +0200 (13 months ago)
changeset 68184 6c693b2700b3
parent 68182 fa3cf61121ee
child 68491 f0f83ce0badd
permissions -rw-r--r--
support for dynamic document output while editing;
     1 (*  Title:      Pure/Thy/thy_info.ML
     2     Author:     Markus Wenzel, TU Muenchen
     3 
     4 Global theory info database, with auto-loading according to theory and
     5 file dependencies.
     6 *)
     7 
     8 signature THY_INFO =
     9 sig
    10   type presentation_context =
    11     {options: Options.T, file_pos: Position.T, adjust_pos: Position.T -> Position.T,
    12       segments: Thy_Output.segment list}
    13   val apply_presentation: presentation_context -> theory -> unit
    14   val add_presentation: (presentation_context -> theory -> unit) -> theory -> theory
    15   val get_names: unit -> string list
    16   val lookup_theory: string -> theory option
    17   val get_theory: string -> theory
    18   val master_directory: string -> Path.T
    19   val remove_thy: string -> unit
    20   type context =
    21     {options: Options.T,
    22      symbols: HTML.symbols,
    23      bibtex_entries: string list,
    24      last_timing: Toplevel.transition -> Time.time}
    25   val use_theories: context -> string -> Path.T -> (string * Position.T) list -> unit
    26   val use_thy: string -> unit
    27   val script_thy: Position.T -> string -> theory -> theory
    28   val register_thy: theory -> unit
    29   val finish: unit -> unit
    30 end;
    31 
    32 structure Thy_Info: THY_INFO =
    33 struct
    34 
    35 (** presentation of consolidated theory **)
    36 
    37 type presentation_context =
    38   {options: Options.T, file_pos: Position.T, adjust_pos: Position.T -> Position.T,
    39     segments: Thy_Output.segment list};
    40 
    41 structure Presentation = Theory_Data
    42 (
    43   type T = ((presentation_context -> theory -> unit) * stamp) list;
    44   val empty = [];
    45   val extend = I;
    46   fun merge data : T = Library.merge (eq_snd op =) data;
    47 );
    48 
    49 fun apply_presentation (context: presentation_context) thy =
    50   ignore (Presentation.get thy |> Par_List.map (fn (f, _) => f context thy));
    51 
    52 fun add_presentation f = Presentation.map (cons (f, stamp ()));
    53 
    54 val _ =
    55   Theory.setup (add_presentation (fn {options, file_pos, segments, ...} => fn thy =>
    56     if exists (Toplevel.is_skipped_proof o #state) segments then ()
    57     else
    58       let
    59         val body = Thy_Output.present_thy thy segments;
    60         val option = Present.document_option options;
    61       in
    62         if #disabled option then ()
    63         else
    64           let
    65             val latex = Latex.isabelle_body (Context.theory_name thy) body;
    66             val output = [Latex.output_text latex, Latex.output_positions file_pos latex];
    67             val _ = Export.export thy "document.tex" output;
    68             val _ = if #enabled option then Present.theory_output thy output else ();
    69           in () end
    70       end));
    71 
    72 
    73 
    74 (** thy database **)
    75 
    76 (* messages *)
    77 
    78 val show_path = space_implode " via " o map quote;
    79 
    80 fun cycle_msg names = "Cyclic dependency of " ^ show_path names;
    81 
    82 
    83 (* derived graph operations *)
    84 
    85 fun add_deps name parents G = String_Graph.add_deps_acyclic (name, parents) G
    86   handle String_Graph.CYCLES namess => error (cat_lines (map cycle_msg namess));
    87 
    88 fun new_entry name parents entry =
    89   String_Graph.new_node (name, entry) #> add_deps name parents;
    90 
    91 
    92 (* global thys *)
    93 
    94 type deps =
    95  {master: (Path.T * SHA1.digest),  (*master dependencies for thy file*)
    96   imports: (string * Position.T) list};  (*source specification of imports (partially qualified)*)
    97 
    98 fun make_deps master imports : deps = {master = master, imports = imports};
    99 
   100 fun master_dir_deps (d: deps option) =
   101   the_default Path.current (Option.map (Path.dir o #1 o #master) d);
   102 
   103 local
   104   val global_thys =
   105     Synchronized.var "Thy_Info.thys"
   106       (String_Graph.empty: (deps option * theory option) String_Graph.T);
   107 in
   108   fun get_thys () = Synchronized.value global_thys;
   109   fun change_thys f = Synchronized.change global_thys f;
   110 end;
   111 
   112 fun get_names () = String_Graph.topological_order (get_thys ());
   113 
   114 
   115 (* access thy *)
   116 
   117 fun lookup thys name = try (String_Graph.get_node thys) name;
   118 fun lookup_thy name = lookup (get_thys ()) name;
   119 
   120 fun get thys name =
   121   (case lookup thys name of
   122     SOME thy => thy
   123   | NONE => error ("Theory loader: nothing known about theory " ^ quote name));
   124 
   125 fun get_thy name = get (get_thys ()) name;
   126 
   127 
   128 (* access deps *)
   129 
   130 val lookup_deps = Option.map #1 o lookup_thy;
   131 
   132 val master_directory = master_dir_deps o #1 o get_thy;
   133 
   134 
   135 (* access theory *)
   136 
   137 fun lookup_theory name =
   138   (case lookup_thy name of
   139     SOME (_, SOME theory) => SOME theory
   140   | _ => NONE);
   141 
   142 fun get_theory name =
   143   (case lookup_theory name of
   144     SOME theory => theory
   145   | _ => error ("Theory loader: undefined entry for theory " ^ quote name));
   146 
   147 val get_imports = Resources.imports_of o get_theory;
   148 
   149 
   150 
   151 (** thy operations **)
   152 
   153 (* remove *)
   154 
   155 fun remove name thys =
   156   (case lookup thys name of
   157     NONE => thys
   158   | SOME (NONE, _) => error ("Cannot update finished theory " ^ quote name)
   159   | SOME _ =>
   160       let
   161         val succs = String_Graph.all_succs thys [name];
   162         val _ = writeln ("Theory loader: removing " ^ commas_quote succs);
   163       in fold String_Graph.del_node succs thys end);
   164 
   165 val remove_thy = change_thys o remove;
   166 
   167 
   168 (* update *)
   169 
   170 fun update deps theory thys =
   171   let
   172     val name = Context.theory_long_name theory;
   173     val parents = map Context.theory_long_name (Theory.parents_of theory);
   174 
   175     val thys' = remove name thys;
   176     val _ = map (get thys') parents;
   177   in new_entry name parents (SOME deps, SOME theory) thys' end;
   178 
   179 fun update_thy deps theory = change_thys (update deps theory);
   180 
   181 
   182 (* context *)
   183 
   184 type context =
   185   {options: Options.T,
   186    symbols: HTML.symbols,
   187    bibtex_entries: string list,
   188    last_timing: Toplevel.transition -> Time.time};
   189 
   190 fun default_context (): context =
   191   {options = Options.default (),
   192    symbols = HTML.no_symbols,
   193    bibtex_entries = [],
   194    last_timing = K Time.zeroTime};
   195 
   196 
   197 (* scheduling loader tasks *)
   198 
   199 datatype result =
   200   Result of {theory: theory, exec_id: Document_ID.exec,
   201     present: unit -> unit, commit: unit -> unit, weight: int};
   202 
   203 fun theory_result theory =
   204   Result {theory = theory, exec_id = Document_ID.none, present = I, commit = I, weight = 0};
   205 
   206 fun result_theory (Result {theory, ...}) = theory;
   207 fun result_present (Result {present, ...}) = present;
   208 fun result_commit (Result {commit, ...}) = commit;
   209 fun result_ord (Result {weight = i, ...}, Result {weight = j, ...}) = int_ord (j, i);
   210 
   211 fun join_theory (Result {theory, exec_id, ...}) =
   212   let
   213     val _ = Execution.join [exec_id];
   214     val res = Exn.capture Thm.consolidate_theory theory;
   215     val exns = maps Task_Queue.group_status (Execution.peek exec_id);
   216   in res :: map Exn.Exn exns end;
   217 
   218 datatype task =
   219   Task of string list * (theory list -> result) |
   220   Finished of theory;
   221 
   222 fun task_finished (Task _) = false
   223   | task_finished (Finished _) = true;
   224 
   225 fun task_parents deps (parents: string list) = map (the o AList.lookup (op =) deps) parents;
   226 
   227 val schedule_seq =
   228   String_Graph.schedule (fn deps => fn (_, task) =>
   229     (case task of
   230       Task (parents, body) =>
   231         let
   232           val result = body (task_parents deps parents);
   233           val _ = Par_Exn.release_all (join_theory result);
   234           val _ = result_present result ();
   235           val _ = result_commit result ();
   236         in result_theory result end
   237     | Finished thy => thy)) #> ignore;
   238 
   239 val schedule_futures = Thread_Attributes.uninterruptible (fn _ => fn tasks =>
   240   let
   241     val futures = tasks
   242       |> String_Graph.schedule (fn deps => fn (name, task) =>
   243         (case task of
   244           Task (parents, body) =>
   245             (singleton o Future.forks)
   246               {name = "theory:" ^ name, group = NONE,
   247                 deps = map (Future.task_of o #2) deps, pri = 0, interrupts = true}
   248               (fn () =>
   249                 (case filter (not o can Future.join o #2) deps of
   250                   [] => body (map (result_theory o Future.join) (task_parents deps parents))
   251                 | bad =>
   252                     error
   253                       ("Failed to load theory " ^ quote name ^
   254                         " (unresolved " ^ commas_quote (map #1 bad) ^ ")")))
   255         | Finished theory => Future.value (theory_result theory)));
   256 
   257     val results1 = futures
   258       |> maps (fn future =>
   259           (case Future.join_result future of
   260             Exn.Res result => join_theory result
   261           | Exn.Exn exn => [Exn.Exn exn]));
   262 
   263     val results2 = futures
   264       |> map_filter (Exn.get_res o Future.join_result)
   265       |> sort result_ord
   266       |> Par_List.map (fn result => Exn.capture (result_present result) ());
   267 
   268     (* FIXME more precise commit order (!?) *)
   269     val results3 = futures
   270       |> map (fn future => Exn.capture (fn () => result_commit (Future.join future) ()) ());
   271 
   272     (* FIXME avoid global Execution.reset (!??) *)
   273     val results4 = map Exn.Exn (maps Task_Queue.group_status (Execution.reset ()));
   274 
   275     val _ = Par_Exn.release_all (results1 @ results2 @ results3 @ results4);
   276   in () end);
   277 
   278 
   279 (* eval theory *)
   280 
   281 fun excursion keywords master_dir last_timing init elements =
   282   let
   283     fun prepare_span st span =
   284       Command_Span.content span
   285       |> Command.read keywords (Command.read_thy st) master_dir init ([], ~1)
   286       |> (fn tr => Toplevel.put_timing (last_timing tr) tr);
   287 
   288     fun element_result span_elem (st, _) =
   289       let
   290         val elem = Thy_Syntax.map_element (prepare_span st) span_elem;
   291         val (results, st') = Toplevel.element_result keywords elem st;
   292         val pos' = Toplevel.pos_of (Thy_Syntax.last_element elem);
   293       in (results, (st', pos')) end;
   294 
   295     val (results, (end_state, end_pos)) =
   296       fold_map element_result elements (Toplevel.toplevel, Position.none);
   297 
   298     val thy = Toplevel.end_theory end_pos end_state;
   299   in (results, thy) end;
   300 
   301 fun eval_thy (context: context) update_time master_dir header text_pos text parents =
   302   let
   303     val {options, symbols, bibtex_entries, last_timing} = context;
   304     val (name, _) = #name header;
   305     val keywords =
   306       fold (curry Keyword.merge_keywords o Thy_Header.get_keywords) parents
   307         (Keyword.add_keywords (#keywords header) Keyword.empty_keywords);
   308 
   309     val spans = Outer_Syntax.parse_spans (Token.explode keywords text_pos text);
   310     val elements = Thy_Syntax.parse_elements keywords spans;
   311 
   312     fun init () =
   313       Resources.begin_theory master_dir header parents
   314       |> Present.begin_theory bibtex_entries update_time
   315         (fn () => implode (map (HTML.present_span symbols keywords) spans));
   316 
   317     val (results, thy) =
   318       cond_timeit true ("theory " ^ quote name)
   319         (fn () => excursion keywords master_dir last_timing init elements);
   320 
   321     fun present () =
   322       let
   323         val segments = (spans ~~ maps Toplevel.join_results results)
   324           |> map (fn (span, (tr, st')) => {span = span, command = tr, state = st'});
   325         val context: presentation_context =
   326           {options = options, file_pos = text_pos, adjust_pos = I, segments = segments};
   327       in apply_presentation context thy end;
   328   in (thy, present, size text) end;
   329 
   330 
   331 (* require_thy -- checking database entries wrt. the file-system *)
   332 
   333 local
   334 
   335 fun required_by _ [] = ""
   336   | required_by s initiators = s ^ "(required by " ^ show_path (rev initiators) ^ ")";
   337 
   338 fun load_thy context initiators update_time deps text (name, pos) keywords parents =
   339   let
   340     val _ = remove_thy name;
   341     val _ = writeln ("Loading theory " ^ quote name ^ required_by " " initiators);
   342     val _ = Output.try_protocol_message (Markup.loading_theory name) [];
   343 
   344     val {master = (thy_path, _), imports} = deps;
   345     val dir = Path.dir thy_path;
   346     val header = Thy_Header.make (name, pos) imports keywords;
   347 
   348     val _ = Position.reports (map #2 imports ~~ map Theory.get_markup parents);
   349 
   350     val exec_id = Document_ID.make ();
   351     val _ =
   352       Execution.running Document_ID.none exec_id [] orelse
   353         raise Fail ("Failed to register execution: " ^ Document_ID.print exec_id);
   354 
   355     val timing_start = Timing.start ();
   356 
   357     val text_pos = Position.put_id (Document_ID.print exec_id) (Path.position thy_path);
   358     val (theory, present, weight) =
   359       eval_thy context update_time dir header text_pos text
   360         (if name = Context.PureN then [Context.the_global_context ()] else parents);
   361 
   362     val timing_result = Timing.result timing_start;
   363     val timing_props = [Markup.theory_timing, (Markup.nameN, name)];
   364     val _  = Output.try_protocol_message (timing_props @ Markup.timing_properties timing_result) []
   365 
   366     fun commit () = update_thy deps theory;
   367   in
   368     Result {theory = theory, exec_id = exec_id, present = present, commit = commit, weight = weight}
   369   end;
   370 
   371 fun check_deps dir name =
   372   (case lookup_deps name of
   373     SOME NONE => (true, NONE, Position.none, get_imports name, [])
   374   | NONE =>
   375       let val {master, text, theory_pos, imports, keywords} = Resources.check_thy dir name
   376       in (false, SOME (make_deps master imports, text), theory_pos, imports, keywords) end
   377   | SOME (SOME {master, ...}) =>
   378       let
   379         val {master = master', text = text', theory_pos = theory_pos', imports = imports',
   380           keywords = keywords'} = Resources.check_thy dir name;
   381         val deps' = SOME (make_deps master' imports', text');
   382         val current =
   383           #2 master = #2 master' andalso
   384             (case lookup_theory name of
   385               NONE => false
   386             | SOME theory => Resources.loaded_files_current theory);
   387       in (current, deps', theory_pos', imports', keywords') end);
   388 
   389 in
   390 
   391 fun require_thys context initiators qualifier dir strs tasks =
   392       fold_map (require_thy context initiators qualifier dir) strs tasks |>> forall I
   393 and require_thy context initiators qualifier dir (s, require_pos) tasks =
   394   let
   395     val {master_dir, theory_name, ...} = Resources.import_name qualifier dir s;
   396   in
   397     (case try (String_Graph.get_node tasks) theory_name of
   398       SOME task => (task_finished task, tasks)
   399     | NONE =>
   400         let
   401           val _ = member (op =) initiators theory_name andalso error (cycle_msg initiators);
   402 
   403           val (current, deps, theory_pos, imports, keywords) = check_deps master_dir theory_name
   404             handle ERROR msg =>
   405               cat_error msg
   406                 ("The error(s) above occurred for theory " ^ quote theory_name ^
   407                   Position.here require_pos ^ required_by "\n" initiators);
   408 
   409           val qualifier' = Resources.theory_qualifier theory_name;
   410           val dir' = Path.append dir (master_dir_deps (Option.map #1 deps));
   411 
   412           val parents = map (#theory_name o Resources.import_name qualifier' dir' o #1) imports;
   413           val (parents_current, tasks') =
   414             require_thys context (theory_name :: initiators) qualifier' dir' imports tasks;
   415 
   416           val all_current = current andalso parents_current;
   417           val task =
   418             if all_current then Finished (get_theory theory_name)
   419             else
   420               (case deps of
   421                 NONE => raise Fail "Malformed deps"
   422               | SOME (dep, text) =>
   423                   let
   424                     val update_time = serial ();
   425                     val load =
   426                       load_thy context initiators update_time
   427                         dep text (theory_name, theory_pos) keywords;
   428                   in Task (parents, load) end);
   429 
   430           val tasks'' = new_entry theory_name parents task tasks';
   431         in (all_current, tasks'') end)
   432   end;
   433 
   434 end;
   435 
   436 
   437 (* use theories *)
   438 
   439 fun use_theories context qualifier master_dir imports =
   440   let val (_, tasks) = require_thys context [] qualifier master_dir imports String_Graph.empty
   441   in if Multithreading.max_threads () > 1 then schedule_futures tasks else schedule_seq tasks end;
   442 
   443 fun use_thy name =
   444   use_theories (default_context ()) Resources.default_qualifier
   445     Path.current [(name, Position.none)];
   446 
   447 
   448 (* toplevel scripting -- without maintaining database *)
   449 
   450 fun script_thy pos txt thy =
   451   let
   452     val trs =
   453       Outer_Syntax.parse thy pos txt
   454       |> map (Toplevel.modify_init (K thy));
   455     val end_pos = if null trs then pos else Toplevel.pos_of (List.last trs);
   456     val end_state = fold (Toplevel.command_exception true) trs Toplevel.toplevel;
   457   in Toplevel.end_theory end_pos end_state end;
   458 
   459 
   460 (* register theory *)
   461 
   462 fun register_thy theory =
   463   let
   464     val name = Context.theory_long_name theory;
   465     val {master, ...} = Resources.check_thy (Resources.master_directory theory) name;
   466     val imports = Resources.imports_of theory;
   467   in
   468     change_thys (fn thys =>
   469       let
   470         val thys' = remove name thys;
   471         val _ = writeln ("Registering theory " ^ quote name);
   472       in update (make_deps master imports) theory thys' end)
   473   end;
   474 
   475 
   476 (* finish all theories *)
   477 
   478 fun finish () = change_thys (String_Graph.map (fn _ => fn (_, entry) => (NONE, entry)));
   479 
   480 end;
   481 
   482 fun use_thy name = Runtime.toplevel_program (fn () => Thy_Info.use_thy name);