src/Pure/Thy/thy_info.ML
author wenzelm
Wed Jul 21 15:31:38 2010 +0200 (2010-07-21)
changeset 37871 c7ce7685e087
parent 37216 3165bc303f66
child 37873 66d90b2b87bc
permissions -rw-r--r--
replaced Thy_Info.the_theory by Context.this_theory -- avoid referring to accidental theory loader state;
     1 (*  Title:      Pure/Thy/thy_info.ML
     2     Author:     Markus Wenzel, TU Muenchen
     3 
     4 Main part of theory loader database, including handling of theory and
     5 file dependencies.
     6 *)
     7 
     8 signature THY_INFO =
     9 sig
    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 is_finished: string -> bool
    20   val master_directory: string -> Path.T
    21   val loaded_files: string -> Path.T list
    22   val get_parents: string -> string list
    23   val touch_thy: string -> unit
    24   val touch_child_thys: string -> unit
    25   val thy_ord: theory * theory -> order
    26   val remove_thy: string -> unit
    27   val kill_thy: string -> unit
    28   val provide_file: Path.T -> string -> unit
    29   val load_file: bool -> Path.T -> unit
    30   val exec_file: bool -> Path.T -> Context.generic -> Context.generic
    31   val use: string -> unit
    32   val time_use: string -> unit
    33   val use_thys: string list -> unit
    34   val use_thy: string -> unit
    35   val time_use_thy: string -> unit
    36   val begin_theory: string -> string list -> (Path.T * bool) list -> bool -> theory
    37   val end_theory: theory -> unit
    38   val register_thy: string -> unit
    39   val register_theory: theory -> unit
    40   val finish: unit -> unit
    41 end;
    42 
    43 structure Thy_Info: THY_INFO =
    44 struct
    45 
    46 (** theory loader actions and hooks **)
    47 
    48 datatype action = Update | Outdate | Remove;
    49 val str_of_action = fn Update => "Update" | Outdate => "Outdate" | Remove => "Remove";
    50 
    51 local
    52   val hooks = Unsynchronized.ref ([]: (action -> string -> unit) list);
    53 in
    54   fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
    55   fun perform action name = List.app (fn f => (try (fn () => f action name) (); ())) (! hooks);
    56 end;
    57 
    58 
    59 
    60 (** thy database **)
    61 
    62 (* messages *)
    63 
    64 fun loader_msg txt [] = "Theory loader: " ^ txt
    65   | loader_msg txt names = "Theory loader: " ^ txt ^ " " ^ commas_quote names;
    66 
    67 val show_path = space_implode " via " o map quote;
    68 fun cycle_msg names = loader_msg ("cyclic dependency of " ^ show_path names) [];
    69 
    70 
    71 (* derived graph operations *)
    72 
    73 fun add_deps name parents G = Graph.add_deps_acyclic (name, parents) G
    74   handle Graph.CYCLES namess => error (cat_lines (map cycle_msg namess));
    75 
    76 fun upd_deps name entry G =
    77   fold (fn parent => Graph.del_edge (parent, name)) (Graph.imm_preds G name) G
    78   |> Graph.map_node name (K entry);
    79 
    80 fun new_deps name parents entry G =
    81   (if can (Graph.get_node G) name then upd_deps name entry G else Graph.new_node (name, entry) G)
    82   |> add_deps name parents;
    83 
    84 
    85 (* thy database *)
    86 
    87 type deps =
    88   {update_time: int,                      (*symbolic time of update; negative value means outdated*)
    89     master: (Path.T * File.ident) option, (*master dependencies for thy file*)
    90     text: string list,                    (*source text for thy*)
    91     parents: string list,                 (*source specification of parents (partially qualified)*)
    92       (*auxiliary files: source path, physical path + identifier*)
    93     files: (Path.T * (Path.T * File.ident) option) list};
    94 
    95 fun make_deps update_time master text parents files : deps =
    96   {update_time = update_time, master = master, text = text, parents = parents, files = files};
    97 
    98 fun init_deps master text parents files =
    99   SOME (make_deps ~1 master text parents (map (rpair NONE) files));
   100 
   101 fun master_dir NONE = Path.current
   102   | master_dir (SOME (path, _)) = Path.dir path;
   103 
   104 fun master_dir' (d: deps option) = the_default Path.current (Option.map (master_dir o #master) d);
   105 fun master_dir'' d = the_default Path.current (Option.map master_dir' d);
   106 
   107 fun base_name s = Path.implode (Path.base (Path.explode s));
   108 
   109 
   110 type thy = deps option * theory option;
   111 
   112 local
   113   val database = Unsynchronized.ref (Graph.empty: thy Graph.T);
   114 in
   115   fun get_thys () = ! database;
   116   fun change_thys f = CRITICAL (fn () => Unsynchronized.change database f);
   117 end;
   118 
   119 
   120 (* access thy graph *)
   121 
   122 fun thy_graph f x = f (get_thys ()) x;
   123 
   124 fun get_names () = Graph.topological_order (get_thys ());
   125 
   126 
   127 (* access thy *)
   128 
   129 fun lookup_thy name =
   130   SOME (thy_graph Graph.get_node name) handle Graph.UNDEF _ => NONE;
   131 
   132 val known_thy = is_some o lookup_thy;
   133 fun check_known_thy name = known_thy name orelse (warning ("Unknown theory " ^ quote name); false);
   134 fun if_known_thy f name = if check_known_thy name then f name else ();
   135 
   136 fun get_thy name =
   137   (case lookup_thy name of
   138     SOME thy => thy
   139   | NONE => error (loader_msg "nothing known about theory" [name]));
   140 
   141 fun change_thy name f = CRITICAL (fn () =>
   142   (get_thy name; change_thys (Graph.map_node name f)));
   143 
   144 
   145 (* access deps *)
   146 
   147 val lookup_deps = Option.map #1 o lookup_thy;
   148 val get_deps = #1 o get_thy;
   149 fun change_deps name f = change_thy name (fn (deps, x) => (f deps, x));
   150 
   151 val is_finished = is_none o get_deps;
   152 val master_directory = master_dir' o get_deps;
   153 
   154 fun loaded_files name =
   155   (case get_deps name of
   156     NONE => []
   157   | SOME {master, files, ...} =>
   158       (case master of SOME (thy_path, _) => [thy_path] | NONE => []) @
   159       (map_filter (Option.map #1 o #2) files));
   160 
   161 fun get_parents name =
   162   thy_graph Graph.imm_preds name handle Graph.UNDEF _ =>
   163     error (loader_msg "nothing known about theory" [name]);
   164 
   165 
   166 (* access theory *)
   167 
   168 fun lookup_theory name =
   169   (case lookup_thy name of
   170     SOME (_, SOME thy) => SOME thy
   171   | _ => NONE);
   172 
   173 fun get_theory name =
   174   (case lookup_theory name of
   175     SOME theory => theory
   176   | _ => error (loader_msg "undefined theory entry for" [name]));
   177 
   178 
   179 
   180 (** thy operations **)
   181 
   182 (* check state *)
   183 
   184 fun check_unfinished fail name =
   185   if known_thy name andalso is_finished name then
   186     fail (loader_msg "cannot update finished theory" [name])
   187   else ();
   188 
   189 fun check_files name =
   190   let
   191     val files = (case get_deps name of SOME {files, ...} => files | NONE => []);
   192     val missing_files = map_filter (fn (path, NONE) => SOME (Path.implode path) | _ => NONE) files;
   193     val _ = null missing_files orelse
   194       error (loader_msg "unresolved dependencies of theory" [name] ^
   195         " on file(s): " ^ commas_quote missing_files);
   196   in () end;
   197 
   198 
   199 (* maintain update_time *)
   200 
   201 local
   202 
   203 fun is_outdated name =
   204   (case lookup_deps name of
   205     SOME (SOME {update_time, ...}) => update_time < 0
   206   | _ => false);
   207 
   208 fun unfinished name =
   209   if is_finished name then (warning (loader_msg "tried to touch finished theory" [name]); NONE)
   210   else SOME name;
   211 
   212 in
   213 
   214 fun outdate_thy name =
   215   if is_finished name orelse is_outdated name then ()
   216   else CRITICAL (fn () =>
   217    (change_deps name (Option.map (fn {master, text, parents, files, ...} =>
   218     make_deps ~1 master text parents files)); perform Outdate name));
   219 
   220 fun touch_thys names =
   221   List.app outdate_thy (thy_graph Graph.all_succs (map_filter unfinished names));
   222 
   223 fun touch_thy name = touch_thys [name];
   224 fun touch_child_thys name = touch_thys (thy_graph Graph.imm_succs name);
   225 
   226 end;
   227 
   228 
   229 (* management data *)
   230 
   231 structure Management_Data = Theory_Data
   232 (
   233   type T =
   234     Task_Queue.group option *   (*worker thread group*)
   235     int;                        (*abstract update time*)
   236   val empty = (NONE, 0);
   237   fun extend _ = empty;
   238   fun merge _ = empty;
   239 );
   240 
   241 val thy_ord = int_ord o pairself (#2 o Management_Data.get);
   242 
   243 
   244 (* pending proofs *)
   245 
   246 fun join_thy name =
   247   (case lookup_theory name of
   248     NONE => ()
   249   | SOME thy => PureThy.join_proofs thy);
   250 
   251 fun cancel_thy name =
   252   (case lookup_theory name of
   253     NONE => ()
   254   | SOME thy =>
   255       (case #1 (Management_Data.get thy) of
   256         NONE => ()
   257       | SOME group => Future.cancel_group group));
   258 
   259 
   260 (* remove theory *)
   261 
   262 fun remove_thy name =
   263   if is_finished name then error (loader_msg "cannot remove finished theory" [name])
   264   else
   265     let
   266       val succs = thy_graph Graph.all_succs [name];
   267       val _ = List.app cancel_thy succs;
   268       val _ = priority (loader_msg "removing" succs);
   269       val _ = CRITICAL (fn () =>
   270         (List.app (perform Remove) succs; change_thys (Graph.del_nodes succs)));
   271     in () end;
   272 
   273 val kill_thy = if_known_thy remove_thy;
   274 
   275 
   276 (* load_file *)
   277 
   278 local
   279 
   280 fun provide path name info (SOME {update_time, master, text, parents, files}) =
   281      (if AList.defined (op =) files path then ()
   282       else warning (loader_msg "undeclared dependency of theory" [name] ^
   283         " on file: " ^ quote (Path.implode path));
   284       SOME (make_deps update_time master text parents
   285         (AList.update (op =) (path, SOME info) files)))
   286   | provide _ _ _ NONE = NONE;
   287 
   288 fun run_file path =
   289   (case Option.map (Context.theory_name o Context.the_theory) (Context.thread_data ()) of
   290     NONE => (Thy_Load.load_ml Path.current path; ())
   291   | SOME name =>
   292       (case lookup_deps name of
   293         SOME deps =>
   294           change_deps name (provide path name (Thy_Load.load_ml (master_dir' deps) path))
   295       | NONE => (Thy_Load.load_ml Path.current path; ())));
   296 
   297 in
   298 
   299 fun provide_file path name =
   300   let
   301     val dir = master_directory name;
   302     val _ = check_unfinished error name;
   303   in
   304     (case Thy_Load.check_file dir path of
   305       SOME path_info => change_deps name (provide path name path_info)
   306     | NONE => error ("Could not find file " ^ quote (Path.implode path)))
   307   end;
   308 
   309 fun load_file time path =
   310   if time then
   311     let val name = Path.implode path in
   312       timeit (fn () =>
   313        (priority ("\n**** Starting file " ^ quote name ^ " ****");
   314         run_file path;
   315         priority ("**** Finished file " ^ quote name ^ " ****\n")))
   316     end
   317   else run_file path;
   318 
   319 fun exec_file time path = ML_Context.exec (fn () => load_file time path);
   320 
   321 val use = load_file false o Path.explode;
   322 val time_use = load_file true o Path.explode;
   323 
   324 end;
   325 
   326 
   327 (* load_thy *)
   328 
   329 fun required_by _ [] = ""
   330   | required_by s initiators = s ^ "(required by " ^ show_path (rev initiators) ^ ")";
   331 
   332 fun load_thy time upd_time initiators name =
   333   let
   334     val _ = priority ("Loading theory " ^ quote name ^ required_by " " initiators);
   335     val (pos, text, _) =
   336       (case get_deps name of
   337         SOME {master = SOME (master_path, _), text as _ :: _, files, ...} =>
   338           (Path.position master_path, text, files)
   339       | _ => error (loader_msg "corrupted dependency information" [name]));
   340     val _ = touch_thy name;
   341     val _ = CRITICAL (fn () =>
   342       change_deps name (Option.map (fn {master, text, parents, files, ...} =>
   343         make_deps upd_time master text parents files)));
   344     val after_load = Outer_Syntax.load_thy name pos text (time orelse ! Output.timing);
   345     val _ =
   346       CRITICAL (fn () =>
   347        (change_deps name
   348           (Option.map (fn {update_time, master, parents, files, ...} =>
   349             make_deps update_time master [] parents files));
   350         perform Update name));
   351   in after_load end;
   352 
   353 
   354 (* scheduling loader tasks *)
   355 
   356 datatype task = Task of (unit -> unit -> unit) | Finished | Running;
   357 fun task_finished Finished = true | task_finished _ = false;
   358 
   359 local
   360 
   361 fun schedule_futures task_graph = uninterruptible (fn _ => fn () =>
   362   let
   363     val tasks = Graph.topological_order task_graph |> map_filter (fn name =>
   364       (case Graph.get_node task_graph name of Task body => SOME (name, body) | _ => NONE));
   365 
   366     val par_proofs = ! parallel_proofs >= 1;
   367 
   368     fun fork (name, body) tab =
   369       let
   370         val deps = Graph.imm_preds task_graph name
   371           |> map_filter (fn parent =>
   372             (case Symtab.lookup tab parent of SOME future => SOME (parent, future) | NONE => NONE));
   373         fun failed (parent, future) = if can Future.join future then NONE else SOME parent;
   374 
   375         val future = Future.fork_deps (map #2 deps) (fn () =>
   376           (case map_filter failed deps of
   377             [] => body ()
   378           | bad => error (loader_msg
   379               ("failed to load " ^ quote name ^ " (unresolved " ^ commas_quote bad ^ ")") [])));
   380         val future' =
   381           if par_proofs then future
   382           else Future.map (fn after_load => (after_load (); fn () => ())) future;
   383       in Symtab.update (name, future') tab end;
   384 
   385     val futures = fold fork tasks Symtab.empty;
   386 
   387     val failed = tasks |> maps (fn (name, _) =>
   388       let
   389         val after_load = Future.join (the (Symtab.lookup futures name));
   390         val _ = join_thy name;
   391         val _ = after_load ();
   392       in [] end handle exn => [(name, exn)]) |> rev;
   393 
   394     val _ = List.app (kill_thy o #1) failed;
   395     val _ = Exn.release_all (map (Exn.Exn o #2) failed);
   396   in () end) ();
   397 
   398 fun schedule_seq tasks =
   399   Graph.topological_order tasks
   400   |> List.app (fn name =>
   401     (case Graph.get_node tasks name of
   402       Task body =>
   403         let val after_load = body ()
   404         in after_load () handle exn => (kill_thy name; reraise exn) end
   405     | _ => ()));
   406 
   407 in
   408 
   409 fun schedule_tasks tasks =
   410   if not (Multithreading.enabled ()) then schedule_seq tasks
   411   else if Multithreading.self_critical () then
   412      (warning (loader_msg "no multithreading within critical section" []);
   413       schedule_seq tasks)
   414   else schedule_futures tasks;
   415 
   416 end;
   417 
   418 
   419 (* require_thy -- checking database entries wrt. the file-system *)
   420 
   421 local
   422 
   423 fun check_ml master (src_path, info) =
   424   let val info' =
   425     (case info of NONE => NONE
   426     | SOME (_, id) =>
   427         (case Thy_Load.check_ml (master_dir master) src_path of NONE => NONE
   428         | SOME (path', id') => if id <> id' then NONE else SOME (path', id')))
   429   in (src_path, info') end;
   430 
   431 fun check_deps dir name =
   432   (case lookup_deps name of
   433     SOME NONE => (true, NONE, get_parents name)
   434   | NONE =>
   435       let val {master, text, imports = parents, uses = files} = Thy_Load.deps_thy dir name
   436       in (false, init_deps (SOME master) text parents files, parents) end
   437   | SOME (SOME {update_time, master, text, parents, files}) =>
   438       let
   439         val (thy_path, thy_id) = Thy_Load.check_thy dir name;
   440         val master' = SOME (thy_path, thy_id);
   441       in
   442         if Option.map #2 master <> SOME thy_id then
   443           let val {text = text', imports = parents', uses = files', ...} =
   444             Thy_Load.deps_thy dir name;
   445           in (false, init_deps master' text' parents' files', parents') end
   446         else
   447           let
   448             val files' = map (check_ml master') files;
   449             val current = update_time >= 0 andalso can get_theory name
   450               andalso forall (is_some o snd) files';
   451             val update_time' = if current then update_time else ~1;
   452             val deps' = SOME (make_deps update_time' master' text parents files');
   453           in (current, deps', parents) end
   454       end);
   455 
   456 fun read_text (SOME {update_time, master = master as SOME (path, _), text = _, parents, files}) =
   457   SOME (make_deps update_time master (explode (File.read path)) parents files);
   458 
   459 in
   460 
   461 fun require_thys time initiators dir strs tasks =
   462       fold_map (require_thy time initiators dir) strs tasks |>> forall I
   463 and require_thy time initiators dir str tasks =
   464   let
   465     val path = Path.expand (Path.explode str);
   466     val name = Path.implode (Path.base path);
   467     val dir' = Path.append dir (Path.dir path);
   468     val _ = member (op =) initiators name andalso error (cycle_msg initiators);
   469   in
   470     (case try (Graph.get_node tasks) name of
   471       SOME task => (task_finished task, tasks)
   472     | NONE =>
   473         let
   474           val (current, deps, parents) = check_deps dir' name
   475             handle ERROR msg => cat_error msg
   476               (loader_msg "the error(s) above occurred while examining theory" [name] ^
   477                 required_by "\n" initiators);
   478           val parent_names = map base_name parents;
   479 
   480           val (parents_current, tasks_graph') =
   481             require_thys time (name :: initiators)
   482               (Path.append dir (master_dir' deps)) parents tasks;
   483 
   484           val all_current = current andalso parents_current;
   485           val _ = if not all_current andalso known_thy name then outdate_thy name else ();
   486           val entry =
   487             if all_current then (deps, SOME (get_theory name))
   488             else (read_text deps, NONE);
   489           val _ = change_thys (new_deps name parent_names entry);
   490 
   491           val upd_time = serial ();
   492           val tasks_graph'' = tasks_graph' |> new_deps name parent_names
   493            (if all_current then Finished
   494             else Task (fn () => load_thy time upd_time initiators name));
   495         in (all_current, tasks_graph'') end)
   496   end;
   497 
   498 end;
   499 
   500 
   501 (* use_thy etc. *)
   502 
   503 local
   504 
   505 fun gen_use_thy' req dir arg =
   506   schedule_tasks (snd (req [] dir arg Graph.empty));
   507 
   508 fun gen_use_thy req str =
   509   let val name = base_name str in
   510     check_unfinished warning name;
   511     gen_use_thy' req Path.current str
   512   end;
   513 
   514 in
   515 
   516 val use_thys_dir = gen_use_thy' (require_thys false);
   517 val use_thys = use_thys_dir Path.current;
   518 val use_thy = gen_use_thy (require_thy false);
   519 val time_use_thy = gen_use_thy (require_thy true);
   520 
   521 end;
   522 
   523 
   524 (* begin / end theory *)
   525 
   526 fun begin_theory name parents uses int =
   527   let
   528     val parent_names = map base_name parents;
   529     val dir = master_dir'' (lookup_deps name);
   530     val _ = check_unfinished error name;
   531     val _ = if int then use_thys_dir dir parents else ();
   532 
   533     val theory = Theory.begin_theory name (map get_theory parent_names);
   534 
   535     val deps =
   536       if known_thy name then get_deps name
   537       else init_deps NONE [] parents (map #1 uses);
   538     val _ = change_thys (new_deps name parent_names (deps, NONE));
   539 
   540     val update_time = (case deps of NONE => 0 | SOME {update_time, ...} => update_time);
   541     val update_time = if update_time > 0 then update_time else serial ();
   542     val theory' = theory
   543       |> Management_Data.put (Future.worker_group (), update_time)
   544       |> Present.begin_theory update_time dir uses;
   545 
   546     val uses_now = map_filter (fn (x, true) => SOME x | _ => NONE) uses;
   547     val theory'' =
   548       fold (fn x => Context.theory_map (exec_file false x) o Theory.checkpoint) uses_now theory';
   549   in theory'' end;
   550 
   551 fun end_theory theory =
   552   let
   553     val name = Context.theory_name theory;
   554     val _ = check_files name;
   555     val theory' = Theory.end_theory theory;
   556     val _ = change_thy name (fn (deps, _) => (deps, SOME theory'));
   557   in () end;
   558 
   559 
   560 (* register existing theories *)
   561 
   562 fun register_thy name =
   563   let
   564     val _ = priority ("Registering theory " ^ quote name);
   565     val thy = get_theory name;
   566     val _ = map get_theory (get_parents name);
   567     val _ = check_unfinished error name;
   568     val _ = touch_thy name;
   569     val master = #master (Thy_Load.deps_thy Path.current name);
   570     val upd_time = #2 (Management_Data.get thy);
   571   in
   572     CRITICAL (fn () =>
   573      (change_deps name (Option.map
   574        (fn {parents, files, ...} => make_deps upd_time (SOME master) [] parents files));
   575       perform Update name))
   576   end;
   577 
   578 fun register_theory theory =
   579   let
   580     val name = Context.theory_name theory;
   581     val parents = Theory.parents_of theory;
   582     val parent_names = map Context.theory_name parents;
   583 
   584     fun err txt bads =
   585       error (loader_msg txt bads ^ "\ncannot register theory " ^ quote name);
   586 
   587     val nonfinished = filter_out is_finished parent_names;
   588     fun get_variant (x, y_name) =
   589       if Theory.eq_thy (x, get_theory y_name) then NONE
   590       else SOME y_name;
   591     val variants = map_filter get_variant (parents ~~ parent_names);
   592 
   593     fun register G =
   594       (Graph.new_node (name, (NONE, SOME theory)) G
   595         handle Graph.DUP _ => err "duplicate theory entry" [])
   596       |> add_deps name parent_names;
   597   in
   598     if not (null nonfinished) then err "non-finished parent theories" nonfinished
   599     else if not (null variants) then err "different versions of parent theories" variants
   600     else CRITICAL (fn () => (change_thys register; perform Update name))
   601   end;
   602 
   603 
   604 (* finish all theories *)
   605 
   606 fun finish () = change_thys (Graph.map_nodes (fn (_, entry) => (NONE, entry)));
   607 
   608 end;