src/Pure/Thy/thy_info.ML
author wenzelm
Mon, 31 May 2010 21:06:57 +0200
changeset 37216 3165bc303f66
parent 36953 2af1ad9aa1a3
child 38139 c7ce7685e087
permissions -rw-r--r--
modernized some structure names, keeping a few legacy aliases;
     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 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
    42 end;
    43 
    44 structure Thy_Info: THY_INFO =
    45 struct
    46 
    47 (** theory loader actions and hooks **)
    48 
    49 datatype action = Update | Outdate | Remove;
    50 val str_of_action = fn Update => "Update" | Outdate => "Outdate" | Remove => "Remove";
    51 
    52 local
    53   val hooks = Unsynchronized.ref ([]: (action -> string -> unit) list);
    54 in
    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);
    57 end;
    58 
    59 
    60 
    61 (** thy database **)
    62 
    63 (* messages *)
    64 
    65 fun loader_msg txt [] = "Theory loader: " ^ txt
    66   | loader_msg txt names = "Theory loader: " ^ txt ^ " " ^ commas_quote names;
    67 
    68 val show_path = space_implode " via " o map quote;
    69 fun cycle_msg names = loader_msg ("cyclic dependency of " ^ show_path names) [];
    70 
    71 
    72 (* derived graph operations *)
    73 
    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));
    76 
    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);
    80 
    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;
    84 
    85 
    86 (* thy database *)
    87 
    88 type deps =
    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};
    95 
    96 fun make_deps update_time master text parents files : deps =
    97   {update_time = update_time, master = master, text = text, parents = parents, files = files};
    98 
    99 fun init_deps master text parents files =
   100   SOME (make_deps ~1 master text parents (map (rpair NONE) files));
   101 
   102 fun master_dir NONE = Path.current
   103   | master_dir (SOME (path, _)) = Path.dir path;
   104 
   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);
   107 
   108 fun base_name s = Path.implode (Path.base (Path.explode s));
   109 
   110 
   111 type thy = deps option * theory option;
   112 
   113 local
   114   val database = Unsynchronized.ref (Graph.empty: thy Graph.T);
   115 in
   116   fun get_thys () = ! database;
   117   fun change_thys f = CRITICAL (fn () => Unsynchronized.change database f);
   118 end;
   119 
   120 
   121 (* access thy graph *)
   122 
   123 fun thy_graph f x = f (get_thys ()) x;
   124 
   125 fun get_names () = Graph.topological_order (get_thys ());
   126 
   127 
   128 (* access thy *)
   129 
   130 fun lookup_thy name =
   131   SOME (thy_graph Graph.get_node name) handle Graph.UNDEF _ => NONE;
   132 
   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 ();
   136 
   137 fun get_thy name =
   138   (case lookup_thy name of
   139     SOME thy => thy
   140   | NONE => error (loader_msg "nothing known about theory" [name]));
   141 
   142 fun change_thy name f = CRITICAL (fn () =>
   143   (get_thy name; change_thys (Graph.map_node name f)));
   144 
   145 
   146 (* access deps *)
   147 
   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));
   151 
   152 val is_finished = is_none o get_deps;
   153 val master_directory = master_dir' o get_deps;
   154 
   155 fun loaded_files name =
   156   (case get_deps name of
   157     NONE => []
   158   | SOME {master, files, ...} =>
   159       (case master of SOME (thy_path, _) => [thy_path] | NONE => []) @
   160       (map_filter (Option.map #1 o #2) files));
   161 
   162 fun get_parents name =
   163   thy_graph Graph.imm_preds name handle Graph.UNDEF _ =>
   164     error (loader_msg "nothing known about theory" [name]);
   165 
   166 
   167 (* access theory *)
   168 
   169 fun lookup_theory name =
   170   (case lookup_thy name of
   171     SOME (_, SOME thy) => SOME thy
   172   | _ => NONE);
   173 
   174 fun get_theory name =
   175   (case lookup_theory name of
   176     SOME theory => theory
   177   | _ => error (loader_msg "undefined theory entry for" [name]));
   178 
   179 fun the_theory name thy =
   180   if Context.theory_name thy = name then thy
   181   else get_theory name;
   182 
   183 
   184 
   185 (** thy operations **)
   186 
   187 (* check state *)
   188 
   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])
   192   else ();
   193 
   194 fun check_files name =
   195   let
   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);
   201   in () end;
   202 
   203 
   204 (* maintain update_time *)
   205 
   206 local
   207 
   208 fun is_outdated name =
   209   (case lookup_deps name of
   210     SOME (SOME {update_time, ...}) => update_time < 0
   211   | _ => false);
   212 
   213 fun unfinished name =
   214   if is_finished name then (warning (loader_msg "tried to touch finished theory" [name]); NONE)
   215   else SOME name;
   216 
   217 in
   218 
   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));
   224 
   225 fun touch_thys names =
   226   List.app outdate_thy (thy_graph Graph.all_succs (map_filter unfinished names));
   227 
   228 fun touch_thy name = touch_thys [name];
   229 fun touch_child_thys name = touch_thys (thy_graph Graph.imm_succs name);
   230 
   231 end;
   232 
   233 
   234 (* management data *)
   235 
   236 structure Management_Data = Theory_Data
   237 (
   238   type T =
   239     Task_Queue.group option *   (*worker thread group*)
   240     int;                        (*abstract update time*)
   241   val empty = (NONE, 0);
   242   fun extend _ = empty;
   243   fun merge _ = empty;
   244 );
   245 
   246 val thy_ord = int_ord o pairself (#2 o Management_Data.get);
   247 
   248 
   249 (* pending proofs *)
   250 
   251 fun join_thy name =
   252   (case lookup_theory name of
   253     NONE => ()
   254   | SOME thy => PureThy.join_proofs thy);
   255 
   256 fun cancel_thy name =
   257   (case lookup_theory name of
   258     NONE => ()
   259   | SOME thy =>
   260       (case #1 (Management_Data.get thy) of
   261         NONE => ()
   262       | SOME group => Future.cancel_group group));
   263 
   264 
   265 (* remove theory *)
   266 
   267 fun remove_thy name =
   268   if is_finished name then error (loader_msg "cannot remove finished theory" [name])
   269   else
   270     let
   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)));
   276     in () end;
   277 
   278 val kill_thy = if_known_thy remove_thy;
   279 
   280 
   281 (* load_file *)
   282 
   283 local
   284 
   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;
   292 
   293 fun run_file path =
   294   (case Option.map (Context.theory_name o Context.the_theory) (Context.thread_data ()) of
   295     NONE => (Thy_Load.load_ml Path.current path; ())
   296   | SOME name =>
   297       (case lookup_deps name of
   298         SOME deps =>
   299           change_deps name (provide path name (Thy_Load.load_ml (master_dir' deps) path))
   300       | NONE => (Thy_Load.load_ml Path.current path; ())));
   301 
   302 in
   303 
   304 fun provide_file path name =
   305   let
   306     val dir = master_directory name;
   307     val _ = check_unfinished error name;
   308   in
   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)))
   312   end;
   313 
   314 fun load_file time path =
   315   if time then
   316     let val name = Path.implode path in
   317       timeit (fn () =>
   318        (priority ("\n**** Starting file " ^ quote name ^ " ****");
   319         run_file path;
   320         priority ("**** Finished file " ^ quote name ^ " ****\n")))
   321     end
   322   else run_file path;
   323 
   324 fun exec_file time path = ML_Context.exec (fn () => load_file time path);
   325 
   326 val use = load_file false o Path.explode;
   327 val time_use = load_file true o Path.explode;
   328 
   329 end;
   330 
   331 
   332 (* load_thy *)
   333 
   334 fun required_by _ [] = ""
   335   | required_by s initiators = s ^ "(required by " ^ show_path (rev initiators) ^ ")";
   336 
   337 fun load_thy time upd_time initiators name =
   338   let
   339     val _ = priority ("Loading theory " ^ quote name ^ required_by " " initiators);
   340     val (pos, text, _) =
   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);
   350     val _ =
   351       CRITICAL (fn () =>
   352        (change_deps name
   353           (Option.map (fn {update_time, master, parents, files, ...} =>
   354             make_deps update_time master [] parents files));
   355         perform Update name));
   356   in after_load end;
   357 
   358 
   359 (* scheduling loader tasks *)
   360 
   361 datatype task = Task of (unit -> unit -> unit) | Finished | Running;
   362 fun task_finished Finished = true | task_finished _ = false;
   363 
   364 local
   365 
   366 fun schedule_futures task_graph = uninterruptible (fn _ => fn () =>
   367   let
   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));
   370 
   371     val par_proofs = ! parallel_proofs >= 1;
   372 
   373     fun fork (name, body) tab =
   374       let
   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;
   379 
   380         val future = Future.fork_deps (map #2 deps) (fn () =>
   381           (case map_filter failed deps of
   382             [] => body ()
   383           | bad => error (loader_msg
   384               ("failed to load " ^ quote name ^ " (unresolved " ^ commas_quote bad ^ ")") [])));
   385         val future' =
   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;
   389 
   390     val futures = fold fork tasks Symtab.empty;
   391 
   392     val failed = tasks |> maps (fn (name, _) =>
   393       let
   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;
   398 
   399     val _ = List.app (kill_thy o #1) failed;
   400     val _ = Exn.release_all (map (Exn.Exn o #2) failed);
   401   in () end) ();
   402 
   403 fun schedule_seq tasks =
   404   Graph.topological_order tasks
   405   |> List.app (fn name =>
   406     (case Graph.get_node tasks name of
   407       Task body =>
   408         let val after_load = body ()
   409         in after_load () handle exn => (kill_thy name; reraise exn) end
   410     | _ => ()));
   411 
   412 in
   413 
   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" []);
   418       schedule_seq tasks)
   419   else schedule_futures tasks;
   420 
   421 end;
   422 
   423 
   424 (* require_thy -- checking database entries wrt. the file-system *)
   425 
   426 local
   427 
   428 fun check_ml master (src_path, info) =
   429   let val info' =
   430     (case info of NONE => NONE
   431     | SOME (_, id) =>
   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;
   435 
   436 fun check_deps dir name =
   437   (case lookup_deps name of
   438     SOME NONE => (true, NONE, get_parents name)
   439   | NONE =>
   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}) =>
   443       let
   444         val (thy_path, thy_id) = Thy_Load.check_thy dir name;
   445         val master' = SOME (thy_path, thy_id);
   446       in
   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
   451         else
   452           let
   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
   459       end);
   460 
   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);
   463 
   464 in
   465 
   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 =
   469   let
   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);
   474   in
   475     (case try (Graph.get_node tasks) name of
   476       SOME task => (task_finished task, tasks)
   477     | NONE =>
   478         let
   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;
   484 
   485           val (parents_current, tasks_graph') =
   486             require_thys time (name :: initiators)
   487               (Path.append dir (master_dir' deps)) parents tasks;
   488 
   489           val all_current = current andalso parents_current;
   490           val _ = if not all_current andalso known_thy name then outdate_thy name else ();
   491           val entry =
   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);
   495 
   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)
   501   end;
   502 
   503 end;
   504 
   505 
   506 (* use_thy etc. *)
   507 
   508 local
   509 
   510 fun gen_use_thy' req dir arg =
   511   schedule_tasks (snd (req [] dir arg Graph.empty));
   512 
   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
   517   end;
   518 
   519 in
   520 
   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);
   525 
   526 end;
   527 
   528 
   529 (* begin / end theory *)
   530 
   531 fun begin_theory name parents uses int =
   532   let
   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 ();
   537 
   538     val theory = Theory.begin_theory name (map get_theory parent_names);
   539 
   540     val deps =
   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));
   544 
   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 ();
   547     val theory' = theory
   548       |> Management_Data.put (Future.worker_group (), update_time)
   549       |> Present.begin_theory update_time dir uses;
   550 
   551     val uses_now = map_filter (fn (x, true) => SOME x | _ => NONE) uses;
   552     val theory'' =
   553       fold (fn x => Context.theory_map (exec_file false x) o Theory.checkpoint) uses_now theory';
   554   in theory'' end;
   555 
   556 fun end_theory theory =
   557   let
   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'));
   562   in () end;
   563 
   564 
   565 (* register existing theories *)
   566 
   567 fun register_thy name =
   568   let
   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);
   576   in
   577     CRITICAL (fn () =>
   578      (change_deps name (Option.map
   579        (fn {parents, files, ...} => make_deps upd_time (SOME master) [] parents files));
   580       perform Update name))
   581   end;
   582 
   583 fun register_theory theory =
   584   let
   585     val name = Context.theory_name theory;
   586     val parents = Theory.parents_of theory;
   587     val parent_names = map Context.theory_name parents;
   588 
   589     fun err txt bads =
   590       error (loader_msg txt bads ^ "\ncannot register theory " ^ quote name);
   591 
   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
   595       else SOME y_name;
   596     val variants = map_filter get_variant (parents ~~ parent_names);
   597 
   598     fun register G =
   599       (Graph.new_node (name, (NONE, SOME theory)) G
   600         handle Graph.DUP _ => err "duplicate theory entry" [])
   601       |> add_deps name parent_names;
   602   in
   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))
   606   end;
   607 
   608 
   609 (* finish all theories *)
   610 
   611 fun finish () = change_thys (Graph.map_nodes (fn (_, entry) => (NONE, entry)));
   612 
   613 end;