1 (* Title: Pure/Thy/thy_info.ML
2 Author: Markus Wenzel, TU Muenchen
4 Main part of theory loader database, including handling of theory and
10 datatype action = Update | Outdate | Remove
11 val str_of_action: action -> string
12 val add_hook: (action -> string -> unit) -> unit
13 val get_names: unit -> string list
14 val known_thy: string -> bool
15 val check_known_thy: string -> bool
16 val if_known_thy: (string -> unit) -> string -> unit
17 val lookup_theory: string -> theory option
18 val get_theory: string -> theory
19 val the_theory: string -> theory -> theory
20 val is_finished: string -> bool
21 val master_directory: string -> Path.T
22 val loaded_files: string -> Path.T list
23 val get_parents: string -> string list
24 val touch_thy: string -> unit
25 val touch_child_thys: string -> unit
26 val thy_ord: theory * theory -> order
27 val remove_thy: string -> unit
28 val kill_thy: string -> unit
29 val provide_file: Path.T -> string -> unit
30 val load_file: bool -> Path.T -> unit
31 val exec_file: bool -> Path.T -> Context.generic -> Context.generic
32 val use: string -> unit
33 val time_use: string -> unit
34 val use_thys: string list -> unit
35 val use_thy: string -> unit
36 val time_use_thy: string -> unit
37 val begin_theory: string -> string list -> (Path.T * bool) list -> bool -> theory
38 val end_theory: theory -> unit
39 val register_thy: string -> unit
40 val register_theory: theory -> unit
41 val finish: unit -> unit
44 structure Thy_Info: THY_INFO =
47 (** theory loader actions and hooks **)
49 datatype action = Update | Outdate | Remove;
50 val str_of_action = fn Update => "Update" | Outdate => "Outdate" | Remove => "Remove";
53 val hooks = Unsynchronized.ref ([]: (action -> string -> unit) list);
55 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
56 fun perform action name = List.app (fn f => (try (fn () => f action name) (); ())) (! hooks);
65 fun loader_msg txt [] = "Theory loader: " ^ txt
66 | loader_msg txt names = "Theory loader: " ^ txt ^ " " ^ commas_quote names;
68 val show_path = space_implode " via " o map quote;
69 fun cycle_msg names = loader_msg ("cyclic dependency of " ^ show_path names) [];
72 (* derived graph operations *)
74 fun add_deps name parents G = Graph.add_deps_acyclic (name, parents) G
75 handle Graph.CYCLES namess => error (cat_lines (map cycle_msg namess));
77 fun upd_deps name entry G =
78 fold (fn parent => Graph.del_edge (parent, name)) (Graph.imm_preds G name) G
79 |> Graph.map_node name (K entry);
81 fun new_deps name parents entry G =
82 (if can (Graph.get_node G) name then upd_deps name entry G else Graph.new_node (name, entry) G)
83 |> add_deps name parents;
89 {update_time: int, (*symbolic time of update; negative value means outdated*)
90 master: (Path.T * File.ident) option, (*master dependencies for thy file*)
91 text: string list, (*source text for thy*)
92 parents: string list, (*source specification of parents (partially qualified)*)
93 (*auxiliary files: source path, physical path + identifier*)
94 files: (Path.T * (Path.T * File.ident) option) list};
96 fun make_deps update_time master text parents files : deps =
97 {update_time = update_time, master = master, text = text, parents = parents, files = files};
99 fun init_deps master text parents files =
100 SOME (make_deps ~1 master text parents (map (rpair NONE) files));
102 fun master_dir NONE = Path.current
103 | master_dir (SOME (path, _)) = Path.dir path;
105 fun master_dir' (d: deps option) = the_default Path.current (Option.map (master_dir o #master) d);
106 fun master_dir'' d = the_default Path.current (Option.map master_dir' d);
108 fun base_name s = Path.implode (Path.base (Path.explode s));
111 type thy = deps option * theory option;
114 val database = Unsynchronized.ref (Graph.empty: thy Graph.T);
116 fun get_thys () = ! database;
117 fun change_thys f = CRITICAL (fn () => Unsynchronized.change database f);
121 (* access thy graph *)
123 fun thy_graph f x = f (get_thys ()) x;
125 fun get_names () = Graph.topological_order (get_thys ());
130 fun lookup_thy name =
131 SOME (thy_graph Graph.get_node name) handle Graph.UNDEF _ => NONE;
133 val known_thy = is_some o lookup_thy;
134 fun check_known_thy name = known_thy name orelse (warning ("Unknown theory " ^ quote name); false);
135 fun if_known_thy f name = if check_known_thy name then f name else ();
138 (case lookup_thy name of
140 | NONE => error (loader_msg "nothing known about theory" [name]));
142 fun change_thy name f = CRITICAL (fn () =>
143 (get_thy name; change_thys (Graph.map_node name f)));
148 val lookup_deps = Option.map #1 o lookup_thy;
149 val get_deps = #1 o get_thy;
150 fun change_deps name f = change_thy name (fn (deps, x) => (f deps, x));
152 val is_finished = is_none o get_deps;
153 val master_directory = master_dir' o get_deps;
155 fun loaded_files name =
156 (case get_deps name of
158 | SOME {master, files, ...} =>
159 (case master of SOME (thy_path, _) => [thy_path] | NONE => []) @
160 (map_filter (Option.map #1 o #2) files));
162 fun get_parents name =
163 thy_graph Graph.imm_preds name handle Graph.UNDEF _ =>
164 error (loader_msg "nothing known about theory" [name]);
169 fun lookup_theory name =
170 (case lookup_thy name of
171 SOME (_, SOME thy) => SOME thy
174 fun get_theory name =
175 (case lookup_theory name of
176 SOME theory => theory
177 | _ => error (loader_msg "undefined theory entry for" [name]));
179 fun the_theory name thy =
180 if Context.theory_name thy = name then thy
181 else get_theory name;
185 (** thy operations **)
189 fun check_unfinished fail name =
190 if known_thy name andalso is_finished name then
191 fail (loader_msg "cannot update finished theory" [name])
194 fun check_files name =
196 val files = (case get_deps name of SOME {files, ...} => files | NONE => []);
197 val missing_files = map_filter (fn (path, NONE) => SOME (Path.implode path) | _ => NONE) files;
198 val _ = null missing_files orelse
199 error (loader_msg "unresolved dependencies of theory" [name] ^
200 " on file(s): " ^ commas_quote missing_files);
204 (* maintain update_time *)
208 fun is_outdated name =
209 (case lookup_deps name of
210 SOME (SOME {update_time, ...}) => update_time < 0
213 fun unfinished name =
214 if is_finished name then (warning (loader_msg "tried to touch finished theory" [name]); NONE)
219 fun outdate_thy name =
220 if is_finished name orelse is_outdated name then ()
221 else CRITICAL (fn () =>
222 (change_deps name (Option.map (fn {master, text, parents, files, ...} =>
223 make_deps ~1 master text parents files)); perform Outdate name));
225 fun touch_thys names =
226 List.app outdate_thy (thy_graph Graph.all_succs (map_filter unfinished names));
228 fun touch_thy name = touch_thys [name];
229 fun touch_child_thys name = touch_thys (thy_graph Graph.imm_succs name);
234 (* management data *)
236 structure Management_Data = Theory_Data
239 Task_Queue.group option * (*worker thread group*)
240 int; (*abstract update time*)
241 val empty = (NONE, 0);
242 fun extend _ = empty;
246 val thy_ord = int_ord o pairself (#2 o Management_Data.get);
252 (case lookup_theory name of
254 | SOME thy => PureThy.join_proofs thy);
256 fun cancel_thy name =
257 (case lookup_theory name of
260 (case #1 (Management_Data.get thy) of
262 | SOME group => Future.cancel_group group));
267 fun remove_thy name =
268 if is_finished name then error (loader_msg "cannot remove finished theory" [name])
271 val succs = thy_graph Graph.all_succs [name];
272 val _ = List.app cancel_thy succs;
273 val _ = priority (loader_msg "removing" succs);
274 val _ = CRITICAL (fn () =>
275 (List.app (perform Remove) succs; change_thys (Graph.del_nodes succs)));
278 val kill_thy = if_known_thy remove_thy;
285 fun provide path name info (SOME {update_time, master, text, parents, files}) =
286 (if AList.defined (op =) files path then ()
287 else warning (loader_msg "undeclared dependency of theory" [name] ^
288 " on file: " ^ quote (Path.implode path));
289 SOME (make_deps update_time master text parents
290 (AList.update (op =) (path, SOME info) files)))
291 | provide _ _ _ NONE = NONE;
294 (case Option.map (Context.theory_name o Context.the_theory) (Context.thread_data ()) of
295 NONE => (Thy_Load.load_ml Path.current path; ())
297 (case lookup_deps name of
299 change_deps name (provide path name (Thy_Load.load_ml (master_dir' deps) path))
300 | NONE => (Thy_Load.load_ml Path.current path; ())));
304 fun provide_file path name =
306 val dir = master_directory name;
307 val _ = check_unfinished error name;
309 (case Thy_Load.check_file dir path of
310 SOME path_info => change_deps name (provide path name path_info)
311 | NONE => error ("Could not find file " ^ quote (Path.implode path)))
314 fun load_file time path =
316 let val name = Path.implode path in
318 (priority ("\n**** Starting file " ^ quote name ^ " ****");
320 priority ("**** Finished file " ^ quote name ^ " ****\n")))
324 fun exec_file time path = ML_Context.exec (fn () => load_file time path);
326 val use = load_file false o Path.explode;
327 val time_use = load_file true o Path.explode;
334 fun required_by _ [] = ""
335 | required_by s initiators = s ^ "(required by " ^ show_path (rev initiators) ^ ")";
337 fun load_thy time upd_time initiators name =
339 val _ = priority ("Loading theory " ^ quote name ^ required_by " " initiators);
341 (case get_deps name of
342 SOME {master = SOME (master_path, _), text as _ :: _, files, ...} =>
343 (Path.position master_path, text, files)
344 | _ => error (loader_msg "corrupted dependency information" [name]));
345 val _ = touch_thy name;
346 val _ = CRITICAL (fn () =>
347 change_deps name (Option.map (fn {master, text, parents, files, ...} =>
348 make_deps upd_time master text parents files)));
349 val after_load = Outer_Syntax.load_thy name pos text (time orelse ! Output.timing);
353 (Option.map (fn {update_time, master, parents, files, ...} =>
354 make_deps update_time master [] parents files));
355 perform Update name));
359 (* scheduling loader tasks *)
361 datatype task = Task of (unit -> unit -> unit) | Finished | Running;
362 fun task_finished Finished = true | task_finished _ = false;
366 fun schedule_futures task_graph = uninterruptible (fn _ => fn () =>
368 val tasks = Graph.topological_order task_graph |> map_filter (fn name =>
369 (case Graph.get_node task_graph name of Task body => SOME (name, body) | _ => NONE));
371 val par_proofs = ! parallel_proofs >= 1;
373 fun fork (name, body) tab =
375 val deps = Graph.imm_preds task_graph name
376 |> map_filter (fn parent =>
377 (case Symtab.lookup tab parent of SOME future => SOME (parent, future) | NONE => NONE));
378 fun failed (parent, future) = if can Future.join future then NONE else SOME parent;
380 val future = Future.fork_deps (map #2 deps) (fn () =>
381 (case map_filter failed deps of
383 | bad => error (loader_msg
384 ("failed to load " ^ quote name ^ " (unresolved " ^ commas_quote bad ^ ")") [])));
386 if par_proofs then future
387 else Future.map (fn after_load => (after_load (); fn () => ())) future;
388 in Symtab.update (name, future') tab end;
390 val futures = fold fork tasks Symtab.empty;
392 val failed = tasks |> maps (fn (name, _) =>
394 val after_load = Future.join (the (Symtab.lookup futures name));
395 val _ = join_thy name;
396 val _ = after_load ();
397 in [] end handle exn => [(name, exn)]) |> rev;
399 val _ = List.app (kill_thy o #1) failed;
400 val _ = Exn.release_all (map (Exn.Exn o #2) failed);
403 fun schedule_seq tasks =
404 Graph.topological_order tasks
405 |> List.app (fn name =>
406 (case Graph.get_node tasks name of
408 let val after_load = body ()
409 in after_load () handle exn => (kill_thy name; reraise exn) end
414 fun schedule_tasks tasks =
415 if not (Multithreading.enabled ()) then schedule_seq tasks
416 else if Multithreading.self_critical () then
417 (warning (loader_msg "no multithreading within critical section" []);
419 else schedule_futures tasks;
424 (* require_thy -- checking database entries wrt. the file-system *)
428 fun check_ml master (src_path, info) =
430 (case info of NONE => NONE
432 (case Thy_Load.check_ml (master_dir master) src_path of NONE => NONE
433 | SOME (path', id') => if id <> id' then NONE else SOME (path', id')))
434 in (src_path, info') end;
436 fun check_deps dir name =
437 (case lookup_deps name of
438 SOME NONE => (true, NONE, get_parents name)
440 let val {master, text, imports = parents, uses = files} = Thy_Load.deps_thy dir name
441 in (false, init_deps (SOME master) text parents files, parents) end
442 | SOME (SOME {update_time, master, text, parents, files}) =>
444 val (thy_path, thy_id) = Thy_Load.check_thy dir name;
445 val master' = SOME (thy_path, thy_id);
447 if Option.map #2 master <> SOME thy_id then
448 let val {text = text', imports = parents', uses = files', ...} =
449 Thy_Load.deps_thy dir name;
450 in (false, init_deps master' text' parents' files', parents') end
453 val files' = map (check_ml master') files;
454 val current = update_time >= 0 andalso can get_theory name
455 andalso forall (is_some o snd) files';
456 val update_time' = if current then update_time else ~1;
457 val deps' = SOME (make_deps update_time' master' text parents files');
458 in (current, deps', parents) end
461 fun read_text (SOME {update_time, master = master as SOME (path, _), text = _, parents, files}) =
462 SOME (make_deps update_time master (explode (File.read path)) parents files);
466 fun require_thys time initiators dir strs tasks =
467 fold_map (require_thy time initiators dir) strs tasks |>> forall I
468 and require_thy time initiators dir str tasks =
470 val path = Path.expand (Path.explode str);
471 val name = Path.implode (Path.base path);
472 val dir' = Path.append dir (Path.dir path);
473 val _ = member (op =) initiators name andalso error (cycle_msg initiators);
475 (case try (Graph.get_node tasks) name of
476 SOME task => (task_finished task, tasks)
479 val (current, deps, parents) = check_deps dir' name
480 handle ERROR msg => cat_error msg
481 (loader_msg "the error(s) above occurred while examining theory" [name] ^
482 required_by "\n" initiators);
483 val parent_names = map base_name parents;
485 val (parents_current, tasks_graph') =
486 require_thys time (name :: initiators)
487 (Path.append dir (master_dir' deps)) parents tasks;
489 val all_current = current andalso parents_current;
490 val _ = if not all_current andalso known_thy name then outdate_thy name else ();
492 if all_current then (deps, SOME (get_theory name))
493 else (read_text deps, NONE);
494 val _ = change_thys (new_deps name parent_names entry);
496 val upd_time = serial ();
497 val tasks_graph'' = tasks_graph' |> new_deps name parent_names
498 (if all_current then Finished
499 else Task (fn () => load_thy time upd_time initiators name));
500 in (all_current, tasks_graph'') end)
510 fun gen_use_thy' req dir arg =
511 schedule_tasks (snd (req [] dir arg Graph.empty));
513 fun gen_use_thy req str =
514 let val name = base_name str in
515 check_unfinished warning name;
516 gen_use_thy' req Path.current str
521 val use_thys_dir = gen_use_thy' (require_thys false);
522 val use_thys = use_thys_dir Path.current;
523 val use_thy = gen_use_thy (require_thy false);
524 val time_use_thy = gen_use_thy (require_thy true);
529 (* begin / end theory *)
531 fun begin_theory name parents uses int =
533 val parent_names = map base_name parents;
534 val dir = master_dir'' (lookup_deps name);
535 val _ = check_unfinished error name;
536 val _ = if int then use_thys_dir dir parents else ();
538 val theory = Theory.begin_theory name (map get_theory parent_names);
541 if known_thy name then get_deps name
542 else init_deps NONE [] parents (map #1 uses);
543 val _ = change_thys (new_deps name parent_names (deps, NONE));
545 val update_time = (case deps of NONE => 0 | SOME {update_time, ...} => update_time);
546 val update_time = if update_time > 0 then update_time else serial ();
548 |> Management_Data.put (Future.worker_group (), update_time)
549 |> Present.begin_theory update_time dir uses;
551 val uses_now = map_filter (fn (x, true) => SOME x | _ => NONE) uses;
553 fold (fn x => Context.theory_map (exec_file false x) o Theory.checkpoint) uses_now theory';
556 fun end_theory theory =
558 val name = Context.theory_name theory;
559 val _ = check_files name;
560 val theory' = Theory.end_theory theory;
561 val _ = change_thy name (fn (deps, _) => (deps, SOME theory'));
565 (* register existing theories *)
567 fun register_thy name =
569 val _ = priority ("Registering theory " ^ quote name);
570 val thy = get_theory name;
571 val _ = map get_theory (get_parents name);
572 val _ = check_unfinished error name;
573 val _ = touch_thy name;
574 val master = #master (Thy_Load.deps_thy Path.current name);
575 val upd_time = #2 (Management_Data.get thy);
578 (change_deps name (Option.map
579 (fn {parents, files, ...} => make_deps upd_time (SOME master) [] parents files));
580 perform Update name))
583 fun register_theory theory =
585 val name = Context.theory_name theory;
586 val parents = Theory.parents_of theory;
587 val parent_names = map Context.theory_name parents;
590 error (loader_msg txt bads ^ "\ncannot register theory " ^ quote name);
592 val nonfinished = filter_out is_finished parent_names;
593 fun get_variant (x, y_name) =
594 if Theory.eq_thy (x, get_theory y_name) then NONE
596 val variants = map_filter get_variant (parents ~~ parent_names);
599 (Graph.new_node (name, (NONE, SOME theory)) G
600 handle Graph.DUP _ => err "duplicate theory entry" [])
601 |> add_deps name parent_names;
603 if not (null nonfinished) then err "non-finished parent theories" nonfinished
604 else if not (null variants) then err "different versions of parent theories" variants
605 else CRITICAL (fn () => (change_thys register; perform Update name))
609 (* finish all theories *)
611 fun finish () = change_thys (Graph.map_nodes (fn (_, entry) => (NONE, entry)));