src/Pure/Thy/thy_info.ML
author wenzelm
Tue Sep 29 11:49:22 2009 +0200 (2009-09-29)
changeset 32738 15bb09ca0378
parent 32106 d7697e311d81
child 32794 7b100d30eb32
permissions -rw-r--r--
explicit indication of Unsynchronized.ref;
     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 ThyInfo: 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 = TheoryDataFun
   237 (
   238   type T =
   239     Task_Queue.group option *   (*worker thread group*)
   240     int;                        (*abstract update time*)
   241   val empty = (NONE, 0);
   242   val copy = I;
   243   fun extend _ = empty;
   244   fun merge _ _ = empty;
   245 );
   246 
   247 val thy_ord = int_ord o pairself (#2 o Management_Data.get);
   248 
   249 
   250 (* pending proofs *)
   251 
   252 fun join_thy name =
   253   (case lookup_theory name of
   254     NONE => ()
   255   | SOME thy => PureThy.join_proofs thy);
   256 
   257 fun cancel_thy name =
   258   (case lookup_theory name of
   259     NONE => ()
   260   | SOME thy =>
   261       (case #1 (Management_Data.get thy) of
   262         NONE => ()
   263       | SOME group => Future.cancel_group group));
   264 
   265 
   266 (* remove theory *)
   267 
   268 fun remove_thy name =
   269   if is_finished name then error (loader_msg "cannot remove finished theory" [name])
   270   else
   271     let
   272       val succs = thy_graph Graph.all_succs [name];
   273       val _ = List.app cancel_thy succs;
   274       val _ = priority (loader_msg "removing" succs);
   275       val _ = CRITICAL (fn () =>
   276         (List.app (perform Remove) succs; change_thys (Graph.del_nodes succs)));
   277     in () end;
   278 
   279 val kill_thy = if_known_thy remove_thy;
   280 
   281 
   282 (* load_file *)
   283 
   284 local
   285 
   286 fun provide path name info (deps as SOME {update_time, master, text, parents, files}) =
   287      (if AList.defined (op =) files path then ()
   288       else warning (loader_msg "undeclared dependency of theory" [name] ^
   289         " on file: " ^ quote (Path.implode path));
   290       SOME (make_deps update_time master text parents
   291         (AList.update (op =) (path, SOME info) files)))
   292   | provide _ _ _ NONE = NONE;
   293 
   294 fun run_file path =
   295   (case Option.map (Context.theory_name o Context.the_theory) (Context.thread_data ()) of
   296     NONE => (ThyLoad.load_ml Path.current path; ())
   297   | SOME name =>
   298       (case lookup_deps name of
   299         SOME deps =>
   300           change_deps name (provide path name (ThyLoad.load_ml (master_dir' deps) path))
   301       | NONE => (ThyLoad.load_ml Path.current path; ())));
   302 
   303 in
   304 
   305 fun provide_file path name =
   306   let
   307     val dir = master_directory name;
   308     val _ = check_unfinished error name;
   309   in
   310     (case ThyLoad.check_file dir path of
   311       SOME path_info => change_deps name (provide path name path_info)
   312     | NONE => error ("Could not find file " ^ quote (Path.implode path)))
   313   end;
   314 
   315 fun load_file time path =
   316   if time then
   317     let val name = Path.implode path in
   318       timeit (fn () =>
   319        (priority ("\n**** Starting file " ^ quote name ^ " ****");
   320         run_file path;
   321         priority ("**** Finished file " ^ quote name ^ " ****\n")))
   322     end
   323   else run_file path;
   324 
   325 fun exec_file time path = ML_Context.exec (fn () => load_file time path);
   326 
   327 val use = load_file false o Path.explode;
   328 val time_use = load_file true o Path.explode;
   329 
   330 end;
   331 
   332 
   333 (* load_thy *)
   334 
   335 fun required_by _ [] = ""
   336   | required_by s initiators = s ^ "(required by " ^ show_path (rev initiators) ^ ")";
   337 
   338 fun load_thy time upd_time initiators name =
   339   let
   340     val _ = priority ("Loading theory " ^ quote name ^ required_by " " initiators);
   341     val (pos, text, files) =
   342       (case get_deps name of
   343         SOME {master = SOME (master_path, _), text as _ :: _, files, ...} =>
   344           (Path.position master_path, text, files)
   345       | _ => error (loader_msg "corrupted dependency information" [name]));
   346     val _ = touch_thy name;
   347     val _ = CRITICAL (fn () =>
   348       change_deps name (Option.map (fn {master, text, parents, files, ...} =>
   349         make_deps upd_time master text parents files)));
   350     val after_load = OuterSyntax.load_thy name pos text (time orelse ! Output.timing);
   351     val _ =
   352       CRITICAL (fn () =>
   353        (change_deps name
   354           (Option.map (fn {update_time, master, parents, files, ...} =>
   355             make_deps update_time master [] parents files));
   356         perform Update name));
   357   in after_load end;
   358 
   359 
   360 (* scheduling loader tasks *)
   361 
   362 datatype task = Task of (unit -> unit -> unit) | Finished | Running;
   363 fun task_finished Finished = true | task_finished _ = false;
   364 
   365 local
   366 
   367 fun schedule_futures task_graph =
   368   let
   369     val tasks = Graph.topological_order task_graph |> map_filter (fn name =>
   370       (case Graph.get_node task_graph name of Task body => SOME (name, body) | _ => NONE));
   371 
   372     val par_proofs = ! parallel_proofs >= 1;
   373 
   374     fun fork (name, body) tab =
   375       let
   376         val deps = Graph.imm_preds task_graph name
   377           |> map_filter (fn parent =>
   378             (case Symtab.lookup tab parent of SOME future => SOME (parent, future) | NONE => NONE));
   379         fun failed (parent, future) = if can Future.join future then NONE else SOME parent;
   380 
   381         val future = Future.fork_deps (map #2 deps) (fn () =>
   382           (case map_filter failed deps of
   383             [] => body ()
   384           | bad => error (loader_msg
   385               ("failed to load " ^ quote name ^ " (unresolved " ^ commas_quote bad ^ ")") [])));
   386         val future' =
   387           if par_proofs then future
   388           else Future.map (fn after_load => (after_load (); fn () => ())) future;
   389       in Symtab.update (name, future') tab end;
   390 
   391     val futures = fold fork tasks Symtab.empty;
   392 
   393     val exns = tasks |> maps (fn (name, _) =>
   394       let
   395         val after_load = Future.join (the (Symtab.lookup futures name));
   396         val _ = join_thy name;
   397         val _ = after_load ();
   398       in [] end handle exn => (kill_thy name; [exn]));
   399 
   400   in ignore (Exn.release_all (map Exn.Exn (rev exns))) end;
   401 
   402 fun schedule_seq tasks =
   403   Graph.topological_order tasks
   404   |> List.app (fn name =>
   405     (case Graph.get_node tasks name of
   406       Task body =>
   407         let val after_load = body ()
   408         in after_load () handle exn => (kill_thy name; reraise exn) end
   409     | _ => ()));
   410 
   411 in
   412 
   413 fun schedule_tasks tasks n =
   414   if not (Multithreading.enabled ()) then schedule_seq tasks
   415   else if Multithreading.self_critical () then
   416      (warning (loader_msg "no multithreading within critical section" []);
   417       schedule_seq tasks)
   418   else schedule_futures tasks;
   419 
   420 end;
   421 
   422 
   423 (* require_thy -- checking database entries wrt. the file-system *)
   424 
   425 local
   426 
   427 fun check_ml master (src_path, info) =
   428   let val info' =
   429     (case info of NONE => NONE
   430     | SOME (_, id) =>
   431         (case ThyLoad.check_ml (master_dir master) src_path of NONE => NONE
   432         | SOME (path', id') => if id <> id' then NONE else SOME (path', id')))
   433   in (src_path, info') end;
   434 
   435 fun check_deps dir name =
   436   (case lookup_deps name of
   437     SOME NONE => (true, NONE, get_parents name)
   438   | NONE =>
   439       let val {master, text, imports = parents, uses = files} = ThyLoad.deps_thy dir name
   440       in (false, init_deps (SOME master) text parents files, parents) end
   441   | SOME (deps as SOME {update_time, master, text, parents, files}) =>
   442       let
   443         val (thy_path, thy_id) = ThyLoad.check_thy dir name;
   444         val master' = SOME (thy_path, thy_id);
   445       in
   446         if Option.map #2 master <> SOME thy_id then
   447           let val {text = text', imports = parents', uses = files', ...} =
   448             ThyLoad.deps_thy dir name;
   449           in (false, init_deps master' text' parents' files', parents') end
   450         else
   451           let
   452             val files' = map (check_ml master') files;
   453             val current = update_time >= 0 andalso can get_theory name
   454               andalso forall (is_some o snd) files';
   455             val update_time' = if current then update_time else ~1;
   456             val deps' = SOME (make_deps update_time' master' text parents files');
   457           in (current, deps', parents) end
   458       end);
   459 
   460 fun read_text (SOME {update_time, master = master as SOME (path, _), text = _, parents, files}) =
   461   SOME (make_deps update_time master (explode (File.read path)) parents files);
   462 
   463 in
   464 
   465 fun require_thys time initiators dir strs tasks =
   466       fold_map (require_thy time initiators dir) strs tasks |>> forall I
   467 and require_thy time initiators dir str tasks =
   468   let
   469     val path = Path.expand (Path.explode str);
   470     val name = Path.implode (Path.base path);
   471     val dir' = Path.append dir (Path.dir path);
   472     val _ = member (op =) initiators name andalso error (cycle_msg initiators);
   473   in
   474     (case try (Graph.get_node (fst tasks)) name of
   475       SOME task => (task_finished task, tasks)
   476     | NONE =>
   477         let
   478           val (current, deps, parents) = check_deps dir' name
   479             handle ERROR msg => cat_error msg
   480               (loader_msg "the error(s) above occurred while examining theory" [name] ^
   481                 required_by "\n" initiators);
   482           val parent_names = map base_name parents;
   483 
   484           val (parents_current, (tasks_graph', tasks_len')) =
   485             require_thys time (name :: initiators)
   486               (Path.append dir (master_dir' deps)) parents tasks;
   487 
   488           val all_current = current andalso parents_current;
   489           val _ = if not all_current andalso known_thy name then outdate_thy name else ();
   490           val entry =
   491             if all_current then (deps, SOME (get_theory name))
   492             else (read_text deps, NONE);
   493           val _ = change_thys (new_deps name parent_names entry);
   494 
   495           val upd_time = serial ();
   496           val tasks_graph'' = tasks_graph' |> new_deps name parent_names
   497            (if all_current then Finished
   498             else Task (fn () => load_thy time upd_time initiators name));
   499           val tasks_len'' = if all_current then tasks_len' else tasks_len' + 1;
   500         in (all_current, (tasks_graph'', tasks_len'')) 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   let val (_, (tasks, n)) = req [] dir arg (Graph.empty, 0)
   512   in schedule_tasks tasks n end;
   513 
   514 fun gen_use_thy req str =
   515   let val name = base_name str in
   516     check_unfinished warning name;
   517     gen_use_thy' req Path.current str
   518   end;
   519 
   520 in
   521 
   522 val use_thys_dir = gen_use_thy' (require_thys false);
   523 val use_thys = use_thys_dir Path.current;
   524 val use_thy = gen_use_thy (require_thy false);
   525 val time_use_thy = gen_use_thy (require_thy true);
   526 
   527 end;
   528 
   529 
   530 (* begin / end theory *)
   531 
   532 fun begin_theory name parents uses int =
   533   let
   534     val parent_names = map base_name parents;
   535     val dir = master_dir'' (lookup_deps name);
   536     val _ = check_unfinished error name;
   537     val _ = if int then use_thys_dir dir parents else ();
   538 
   539     val theory = Theory.begin_theory name (map get_theory parent_names);
   540 
   541     val deps =
   542       if known_thy name then get_deps name
   543       else init_deps NONE [] parents (map #1 uses);
   544     val _ = change_thys (new_deps name parent_names (deps, NONE));
   545 
   546     val update_time = (case deps of NONE => 0 | SOME {update_time, ...} => update_time);
   547     val update_time = if update_time > 0 then update_time else serial ();
   548     val theory' = theory
   549       |> Management_Data.put (Future.worker_group (), update_time)
   550       |> Present.begin_theory update_time dir uses;
   551 
   552     val uses_now = map_filter (fn (x, true) => SOME x | _ => NONE) uses;
   553     val theory'' =
   554       fold (fn x => Context.theory_map (exec_file false x) o Theory.checkpoint) uses_now theory';
   555   in theory'' end;
   556 
   557 fun end_theory theory =
   558   let
   559     val name = Context.theory_name theory;
   560     val _ = check_files name;
   561     val theory' = Theory.end_theory theory;
   562     val _ = change_thy name (fn (deps, _) => (deps, SOME theory'));
   563   in () end;
   564 
   565 
   566 (* register existing theories *)
   567 
   568 fun register_thy name =
   569   let
   570     val _ = priority ("Registering theory " ^ quote name);
   571     val thy = get_theory name;
   572     val _ = map get_theory (get_parents name);
   573     val _ = check_unfinished error name;
   574     val _ = touch_thy name;
   575     val master = #master (ThyLoad.deps_thy Path.current name);
   576     val upd_time = #2 (Management_Data.get thy);
   577   in
   578     CRITICAL (fn () =>
   579      (change_deps name (Option.map
   580        (fn {parents, files, ...} => make_deps upd_time (SOME master) [] parents files));
   581       perform Update name))
   582   end;
   583 
   584 fun register_theory theory =
   585   let
   586     val name = Context.theory_name theory;
   587     val parents = Theory.parents_of theory;
   588     val parent_names = map Context.theory_name parents;
   589 
   590     fun err txt bads =
   591       error (loader_msg txt bads ^ "\ncannot register theory " ^ quote name);
   592 
   593     val nonfinished = filter_out is_finished parent_names;
   594     fun get_variant (x, y_name) =
   595       if Theory.eq_thy (x, get_theory y_name) then NONE
   596       else SOME y_name;
   597     val variants = map_filter get_variant (parents ~~ parent_names);
   598 
   599     fun register G =
   600       (Graph.new_node (name, (NONE, SOME theory)) G
   601         handle Graph.DUP _ => err "duplicate theory entry" [])
   602       |> add_deps name parent_names;
   603   in
   604     if not (null nonfinished) then err "non-finished parent theories" nonfinished
   605     else if not (null variants) then err "different versions of parent theories" variants
   606     else CRITICAL (fn () => (change_thys register; perform Update name))
   607   end;
   608 
   609 
   610 (* finish all theories *)
   611 
   612 fun finish () = change_thys (Graph.map_nodes (fn (_, entry) => (NONE, entry)));
   613 
   614 end;