1 (* Title: Pure/Thy/thy_info.ML
3 Author: Markus Wenzel, TU Muenchen
5 Main part of theory loader database, including handling of theory and
9 signature BASIC_THY_INFO =
11 val theory: string -> theory
12 val touch_thy: string -> unit
13 val remove_thy: string -> unit
18 include BASIC_THY_INFO
19 datatype action = Update | Outdate | Remove
20 val str_of_action: action -> string
21 val add_hook: (action -> string -> unit) -> unit
22 val names: unit -> string list
23 val known_thy: string -> bool
24 val check_known_thy: string -> bool
25 val if_known_thy: (string -> unit) -> string -> unit
26 val lookup_theory: string -> theory option
27 val get_theory: string -> theory
28 val the_theory: string -> theory -> theory
29 val get_parents: string -> string list
30 val loaded_files: string -> Path.T list
31 val touch_child_thys: string -> unit
32 val touch_all_thys: unit -> unit
33 val load_file: bool -> Path.T -> unit
34 val use: string -> unit
35 val time_use: string -> unit
36 val pretend_use_thy_only: string -> unit
37 val use_thys: string list -> unit
38 val use_thy: string -> unit
39 val time_use_thy: string -> unit
40 val update_thy: string -> unit
41 val begin_theory: string -> string list -> (Path.T * bool) list -> bool -> theory
42 val end_theory: theory -> theory
43 val finish: unit -> unit
44 val register_theory: theory -> unit
45 val pretty_theory: theory -> Pretty.T
48 structure ThyInfo: THY_INFO =
51 (** theory loader actions and hooks **)
53 datatype action = Update | Outdate | Remove;
54 val str_of_action = fn Update => "Update" | Outdate => "Outdate" | Remove => "Remove";
57 val hooks = ref ([]: (action -> string -> unit) list);
59 fun add_hook f = CRITICAL (fn () => change hooks (cons f));
60 fun perform action name = List.app (fn f => (try (fn () => f action name) (); ())) (! hooks);
69 fun loader_msg txt [] = "Theory loader: " ^ txt
70 | loader_msg txt names = "Theory loader: " ^ txt ^ " " ^ commas_quote names;
72 val show_path = space_implode " via " o map quote;
73 fun cycle_msg names = loader_msg ("cyclic dependency of " ^ show_path names) [];
76 (* derived graph operations *)
78 fun add_deps name parents G = Graph.add_deps_acyclic (name, parents) G
79 handle Graph.CYCLES namess => error (cat_lines (map cycle_msg namess));
81 fun upd_deps name entry G =
82 fold (fn parent => Graph.del_edge (parent, name)) (Graph.imm_preds G name) G
83 |> Graph.map_node name (K entry);
85 fun new_deps name parents entry G =
86 (if can (Graph.get_node G) name then upd_deps name entry G else Graph.new_node (name, entry) G)
87 |> add_deps name parents;
92 type master = (Path.T * File.ident) * (Path.T * File.ident) option;
95 {outdated: bool, (*entry considered outdated*)
96 master: master option, (*master dependencies for thy + attached ML file*)
97 text: string list, (*source text for thy*)
98 parents: string list, (*source specification of parents (partially qualified)*)
99 files: (*auxiliary files: source path, physical path + identifier*)
100 (Path.T * (Path.T * File.ident) option) list};
102 fun make_deps outdated master text parents files : deps =
103 {outdated = outdated, master = master, text = text, parents = parents, files = files};
105 fun init_deps master text parents files =
106 SOME (make_deps true master text parents (map (rpair NONE) files));
108 fun master_idents (NONE: master option) = []
109 | master_idents (SOME ((_, thy_id), NONE)) = [thy_id]
110 | master_idents (SOME ((_, thy_id), SOME (_, ml_id))) = [thy_id, ml_id];
112 fun master_dir (NONE: master option) = Path.current
113 | master_dir (SOME ((path, _), _)) = Path.dir path;
115 fun master_dir' (d: deps option) = the_default Path.current (Option.map (master_dir o #master) d);
116 fun master_dir'' d = the_default Path.current (Option.map master_dir' d);
118 fun base_name s = Path.implode (Path.base (Path.explode s));
121 type thy = deps option * theory option;
124 val database = ref (Graph.empty: thy Graph.T);
126 fun get_thys () = ! database;
127 fun change_thys f = CRITICAL (fn () => Library.change database f);
131 (* access thy graph *)
133 fun thy_graph f x = f (get_thys ()) x;
135 fun get_names () = Graph.topological_order (get_thys ());
140 fun lookup_thy name =
141 SOME (thy_graph Graph.get_node name) handle Graph.UNDEF _ => NONE;
143 val known_thy = is_some o lookup_thy;
144 fun check_known_thy name = known_thy name orelse (warning ("Unknown theory " ^ quote name); false);
145 fun if_known_thy f name = if check_known_thy name then f name else ();
148 (case lookup_thy name of
150 | NONE => error (loader_msg "nothing known about theory" [name]));
152 fun change_thy name f = CRITICAL (fn () =>
153 (get_thy name; change_thys (Graph.map_node name f)));
158 val lookup_deps = Option.map #1 o lookup_thy;
159 val get_deps = #1 o get_thy;
160 fun change_deps name f = change_thy name (fn (deps, x) => (f deps, x));
162 fun is_finished name = is_none (get_deps name);
164 fun loaded_files name =
165 (case get_deps name of
167 | SOME {master, files, ...} =>
168 (case master of SOME ((thy_path, _), _) => [thy_path] | NONE => []) @
169 (map_filter (Option.map #1 o #2) files));
171 fun get_parents name =
172 thy_graph Graph.imm_preds name handle Graph.UNDEF _ =>
173 error (loader_msg "nothing known about theory" [name]);
176 (* pretty printing a theory *)
180 fun relevant_names names =
182 val (finished, unfinished) =
183 List.filter (fn name => name = Context.draftN orelse known_thy name) names
184 |> List.partition (fn name => name <> Context.draftN andalso is_finished name);
185 in (if not (null finished) then [List.last finished] else []) @ unfinished end;
189 fun pretty_theory thy =
190 Pretty.str_list "{" "}" (relevant_names (Context.names_of thy));
197 fun lookup_theory name =
198 (case lookup_thy name of
199 SOME (_, SOME thy) => SOME thy
202 fun get_theory name =
203 (case lookup_theory name of
204 SOME theory => theory
205 | _ => error (loader_msg "undefined theory entry for" [name]));
207 fun the_theory name thy =
208 if Context.theory_name thy = name then thy
209 else get_theory name;
211 val _ = ML_Context.value_antiq "theory"
213 >> (fn name => (name ^ "_thy", "ThyInfo.theory " ^ ML_Syntax.print_string name))
214 || Scan.succeed ("thy", "ML_Context.the_context ()"));
218 (** thy operations **)
220 (* maintain 'outdated' flag *)
224 fun is_outdated name =
225 (case lookup_deps name of
226 SOME (SOME {outdated, ...}) => outdated
229 fun outdate_thy name =
230 if is_finished name orelse is_outdated name then ()
231 else CRITICAL (fn () =>
232 (change_deps name (Option.map (fn {outdated = _, master, text, parents, files} =>
233 make_deps true master text parents files)); perform Outdate name));
235 fun check_unfinished name =
236 if is_finished name then (warning (loader_msg "tried to touch finished theory" [name]); NONE)
241 fun touch_thys names =
242 List.app outdate_thy (thy_graph Graph.all_succs (map_filter check_unfinished names));
244 fun touch_thy name = touch_thys [name];
245 fun touch_child_thys name = touch_thys (thy_graph Graph.imm_succs name);
247 fun touch_all_thys () = List.app outdate_thy (get_names ());
252 (* check 'finished' state *)
254 fun check_unfinished fail name =
255 if known_thy name andalso is_finished name then
256 fail (loader_msg "cannot update finished theory" [name])
264 fun provide path name info (deps as SOME {outdated, master, text, parents, files}) =
265 (if AList.defined (op =) files path then ()
266 else warning (loader_msg "undeclared dependency of theory" [name] ^
267 " on file: " ^ quote (Path.implode path));
268 SOME (make_deps outdated master text parents (AList.update (op =) (path, SOME info) files)))
269 | provide _ _ _ NONE = NONE;
272 (case Option.map (Context.theory_name o Context.the_theory) (ML_Context.get_context ()) of
273 NONE => (ThyLoad.load_ml Path.current path; ())
275 (case lookup_deps name of
277 change_deps name (provide path name (ThyLoad.load_ml (master_dir' deps) path))
278 | NONE => (ThyLoad.load_ml Path.current path; ())));
282 fun load_file time path =
284 let val name = Path.implode path in
286 (priority ("\n**** Starting file " ^ quote name ^ " ****");
288 priority ("**** Finished file " ^ quote name ^ " ****\n")))
292 val use = load_file false o Path.explode;
293 val time_use = load_file true o Path.explode;
300 fun required_by _ [] = ""
301 | required_by s initiators = s ^ "(required by " ^ show_path (rev initiators) ^ ")";
303 fun load_thy really ml time initiators dir name =
306 if really then priority ("Loading theory " ^ quote name ^ required_by " " initiators)
307 else priority ("Registering theory " ^ quote name);
309 val (master_path, text, files) =
310 (case get_deps name of
311 SOME {master = SOME ((master_path, _), _), text = text as _ :: _, files, ...} =>
312 (master_path, text, files)
313 | _ => error (loader_msg "corrupted dependency information" [name]));
315 val _ = touch_thy name;
318 ThyLoad.load_thy dir name (Position.path master_path) text ml (time orelse ! Output.timing)
321 val missing_files = map_filter (fn (path, NONE) => SOME (Path.implode path) | _ => NONE) files;
323 if null missing_files then ()
324 else warning (loader_msg "unresolved dependencies of theory" [name] ^
325 " on file(s): " ^ commas_quote missing_files);
329 (Option.map (fn {master, parents, files, ...} => make_deps false master [] parents files));
330 perform Update name))
334 (* require_thy -- checking database entries wrt. the file-system *)
338 fun check_ml master (src_path, info) =
340 (case info of NONE => NONE
342 (case ThyLoad.check_ml (master_dir master) src_path of NONE => NONE
343 | SOME (path', id') => if id <> id' then NONE else SOME (path', id')))
344 in (src_path, info') end;
346 fun check_deps ml strict dir name =
347 (case lookup_deps name of
348 SOME NONE => (true, NONE, get_parents name)
350 let val {master, text, imports = parents, uses = files} = ThyLoad.deps_thy dir name ml
351 in (false, init_deps (SOME master) text parents files, parents) end
352 | SOME (deps as SOME {outdated, master, text, parents, files}) =>
353 if not strict andalso can get_theory name then (true, deps, parents)
355 let val master' = SOME (ThyLoad.check_thy dir name ml) in
356 if master_idents master <> master_idents master'
358 let val {text = text', imports = parents', uses = files', ...} =
359 ThyLoad.deps_thy dir name ml;
360 in (false, init_deps master' text' parents' files', parents') end
363 val checked_files = map (check_ml master') files;
364 val current = not outdated andalso forall (is_some o snd) checked_files;
365 val deps' = SOME (make_deps (not current) master' text parents checked_files);
366 in (current, deps', parents) end
371 fun require_thys really ml time strict keep_strict initiators dir strs tasks =
372 fold_map (require_thy really ml time strict keep_strict initiators dir) strs tasks
374 and require_thy really ml time strict keep_strict initiators dir str tasks =
376 val path = Path.expand (Path.explode str);
377 val name = Path.implode (Path.base path);
378 val dir' = Path.append dir (Path.dir path);
379 val _ = member (op =) initiators name andalso error (cycle_msg initiators);
381 (case try (Graph.get_node (fst tasks)) name of
382 SOME task => (Task.is_finished task, tasks)
385 val (current, deps, parents) = check_deps ml strict dir' name
386 handle ERROR msg => cat_error msg
387 (loader_msg "the error(s) above occurred while examining theory" [name] ^
388 required_by "\n" initiators);
389 val parent_names = map base_name parents;
391 val (parents_current, (tasks_graph', tasks_len')) =
392 require_thys true true time (strict andalso keep_strict) keep_strict
393 (name :: initiators) (Path.append dir (master_dir' deps)) parents tasks;
395 val all_current = current andalso parents_current;
396 val thy = if all_current orelse not really then SOME (get_theory name) else NONE;
397 val _ = change_thys (new_deps name parent_names (deps, thy));
399 val tasks_graph'' = tasks_graph' |> new_deps name parent_names
400 (if all_current then Task.Finished
401 else Task.Task (fn () => load_thy really ml time initiators dir' name));
402 val tasks_len'' = if all_current then tasks_len' else tasks_len' + 1;
403 in (all_current, (tasks_graph'', tasks_len'')) end)
409 (* variations on use_thy -- scheduling required theories *)
413 fun schedule_seq tasks =
414 Graph.topological_order tasks
415 |> List.app (fn name => (case Graph.get_node tasks name of Task.Task f => f () | _ => ()));
417 fun max_task (task as (_, (Task.Task _, _))) NONE = SOME task
418 | max_task (task as (_, (Task.Task _, m))) (task' as SOME (_, (_, m'))) =
419 if m > m' then SOME task else task'
420 | max_task _ task' = task';
424 val tasks = Graph.minimals G |> map (fn name =>
425 (name, (Graph.get_node G name, length (Graph.imm_succs G name))))
426 val finished = filter (Task.is_finished o fst o snd) tasks;
428 if not (null finished) then next_task (Graph.del_nodes (map fst finished) G)
429 else if null tasks then ((Task.Finished, I), G)
431 (case fold max_task tasks NONE of
432 NONE => ((Task.Running, I), G)
433 | SOME (name, (task, _)) =>
434 ((task, Graph.del_nodes [name]), Graph.map_node name (K Task.Running) G))
437 fun schedule_tasks (tasks, n) =
438 let val m = ! Multithreading.max_threads in
439 if m <= 1 orelse n <= 1 then schedule_seq tasks
440 else if Multithreading.self_critical () then
441 (warning (loader_msg "no multithreading within critical section" []);
444 (case Multithreading.schedule (Int.min (m, n)) next_task tasks of
446 | exns => raise Exn.EXCEPTIONS (exns, ""))
449 fun gen_use_thy' req dir arg =
450 let val (_, tasks) = req [] dir arg (Graph.empty, 0)
451 in schedule_tasks tasks end;
453 fun gen_use_thy req str =
454 let val name = base_name str in
455 check_unfinished warning name;
456 gen_use_thy' req Path.current str;
457 CRITICAL (fn () => ML_Context.set_context (SOME (Context.Theory (get_theory name))))
462 val quiet_update_thys = gen_use_thy' (require_thys true true false true true);
463 val pretend_use_thy_only = gen_use_thy' (require_thy false false false true false) Path.current;
464 val use_thys = gen_use_thy' (require_thys true true false true false) Path.current;
466 val use_thy = gen_use_thy (require_thy true true false true false);
467 val time_use_thy = gen_use_thy (require_thy true true true true false);
468 val update_thy = gen_use_thy (require_thy true true false true true);
475 fun remove_thy name =
476 if is_finished name then error (loader_msg "cannot remove finished theory" [name])
478 let val succs = thy_graph Graph.all_succs [name] in
479 priority (loader_msg "removing" succs);
480 CRITICAL (fn () => (List.app (perform Remove) succs; change_thys (Graph.del_nodes succs)))
484 (* begin / end theory *)
486 fun check_uses name uses =
487 let val illegal = map (fn ext => Path.ext ext (Path.basic name)) ("" :: ThyLoad.ml_exts) in
488 (case find_first (member (op =) illegal o Path.base o Path.expand o #1) uses of
490 | SOME (path, _) => error ("Illegal use of theory ML file: " ^ quote (Path.implode path)))
493 fun begin_theory name parents uses int =
495 val parent_names = map base_name parents;
496 val dir = master_dir'' (lookup_deps name);
497 val _ = check_unfinished error name;
498 val _ = if int then quiet_update_thys dir parents else ();
500 val _ = CRITICAL (fn () =>
501 ML_Context.set_context (SOME (Context.Theory (get_theory (List.last parent_names)))));
502 val _ = check_uses name uses;
505 Theory.begin_theory name (map get_theory parent_names)
506 |> Present.begin_theory dir uses;
509 if known_thy name then get_deps name
510 else init_deps NONE [] parents (map #1 uses);
511 val _ = change_thys (new_deps name parent_names (deps, NONE));
513 val uses_now = map_filter (fn (x, true) => SOME x | _ => NONE) uses;
515 ML_Context.pass_context (Context.Theory theory) (List.app (load_file false)) uses_now
516 ||> Context.the_theory;
519 fun end_theory theory =
521 val name = Context.theory_name theory;
522 val theory' = Theory.end_theory theory;
523 val _ = change_thy name (fn (deps, _) => (deps, SOME theory'));
527 (* finish all theories *)
529 fun finish () = change_thys (Graph.map_nodes (fn (_, entry) => (NONE, entry)));
532 (* register existing theories *)
534 fun register_theory theory =
536 val name = Context.theory_name theory;
537 val parents = Theory.parents_of theory;
538 val parent_names = map Context.theory_name parents;
541 error (loader_msg txt bads ^ "\ncannot register theory " ^ quote name);
543 val nonfinished = filter_out is_finished parent_names;
544 fun get_variant (x, y_name) =
545 if Theory.eq_thy (x, get_theory y_name) then NONE
547 val variants = map_filter get_variant (parents ~~ parent_names);
550 (Graph.new_node (name, (NONE, SOME theory)) G
551 handle Graph.DUP _ => err "duplicate theory entry" [])
552 |> add_deps name parent_names;
554 if not (null nonfinished) then err "non-finished parent theories" nonfinished
555 else if not (null variants) then err "different versions of parent theories" variants
556 else CRITICAL (fn () => (change_thys register; perform Update name))
559 val _ = register_theory ProtoPure.thy;
561 (*final declarations of this structure*)
562 val theory = get_theory;
563 val names = get_names;
567 structure BasicThyInfo: BASIC_THY_INFO = ThyInfo;