src/Pure/Thy/thy_info.ML
author wenzelm
Mon, 30 Jul 2007 11:12:28 +0200
changeset 24071 82873bc360c2
parent 24068 245b7e68a3bc
child 24080 8c67d869531b
permissions -rw-r--r--
marked some CRITICAL sections;
     1 (*  Title:      Pure/Thy/thy_info.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Main part of theory loader database, including handling of theory and
     6 file dependencies.
     7 *)
     8 
     9 signature BASIC_THY_INFO =
    10 sig
    11   val theory: string -> theory
    12   val touch_thy: string -> unit
    13   val remove_thy: string -> unit
    14 end;
    15 
    16 signature THY_INFO =
    17 sig
    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
    46 end;
    47 
    48 structure ThyInfo: THY_INFO =
    49 struct
    50 
    51 (** theory loader actions and hooks **)
    52 
    53 datatype action = Update | Outdate | Remove;
    54 val str_of_action = fn Update => "Update" | Outdate => "Outdate" | Remove => "Remove";
    55 
    56 local
    57   val hooks = ref ([]: (action -> string -> unit) list);
    58 in
    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);
    61 end;
    62 
    63 
    64 
    65 (** thy database **)
    66 
    67 (* messages *)
    68 
    69 fun loader_msg txt [] = "Theory loader: " ^ txt
    70   | loader_msg txt names = "Theory loader: " ^ txt ^ " " ^ commas_quote names;
    71 
    72 val show_path = space_implode " via " o map quote;
    73 fun cycle_msg names = loader_msg ("cyclic dependency of " ^ show_path names) [];
    74 
    75 
    76 (* derived graph operations *)
    77 
    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));
    80 
    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);
    84 
    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;
    88 
    89 
    90 (* thy database *)
    91 
    92 type master = (Path.T * File.ident) * (Path.T * File.ident) option;
    93 
    94 type deps =
    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};
   101 
   102 fun make_deps outdated master text parents files : deps =
   103   {outdated = outdated, master = master, text = text, parents = parents, files = files};
   104 
   105 fun init_deps master text parents files =
   106   SOME (make_deps true master text parents (map (rpair NONE) files));
   107 
   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];
   111 
   112 fun master_dir (NONE: master option) = Path.current
   113   | master_dir (SOME ((path, _), _)) = Path.dir path;
   114 
   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);
   117 
   118 fun base_name s = Path.implode (Path.base (Path.explode s));
   119 
   120 
   121 type thy = deps option * theory option;
   122 
   123 local
   124   val database = ref (Graph.empty: thy Graph.T);
   125 in
   126   fun get_thys () = ! database;
   127   fun change_thys f = CRITICAL (fn () => Library.change database f);
   128 end;
   129 
   130 
   131 (* access thy graph *)
   132 
   133 fun thy_graph f x = f (get_thys ()) x;
   134 
   135 fun get_names () = Graph.topological_order (get_thys ());
   136 
   137 
   138 (* access thy *)
   139 
   140 fun lookup_thy name =
   141   SOME (thy_graph Graph.get_node name) handle Graph.UNDEF _ => NONE;
   142 
   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 ();
   146 
   147 fun get_thy name =
   148   (case lookup_thy name of
   149     SOME thy => thy
   150   | NONE => error (loader_msg "nothing known about theory" [name]));
   151 
   152 fun change_thy name f = CRITICAL (fn () =>
   153   (get_thy name; change_thys (Graph.map_node name f)));
   154 
   155 
   156 (* access deps *)
   157 
   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));
   161 
   162 fun is_finished name = is_none (get_deps name);
   163 
   164 fun loaded_files name =
   165   (case get_deps name of
   166     NONE => []
   167   | SOME {master, files, ...} =>
   168       (case master of SOME ((thy_path, _), _) => [thy_path] | NONE => []) @
   169       (map_filter (Option.map #1 o #2) files));
   170 
   171 fun get_parents name =
   172   thy_graph Graph.imm_preds name handle Graph.UNDEF _ =>
   173     error (loader_msg "nothing known about theory" [name]);
   174 
   175 
   176 (* pretty printing a theory *)
   177 
   178 local
   179 
   180 fun relevant_names names =
   181   let
   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;
   186 
   187 in
   188 
   189 fun pretty_theory thy =
   190   Pretty.str_list "{" "}" (relevant_names (Context.names_of thy));
   191 
   192 end;
   193 
   194 
   195 (* access theory *)
   196 
   197 fun lookup_theory name =
   198   (case lookup_thy name of
   199     SOME (_, SOME thy) => SOME thy
   200   | _ => NONE);
   201 
   202 fun get_theory name =
   203   (case lookup_theory name of
   204     SOME theory => theory
   205   | _ => error (loader_msg "undefined theory entry for" [name]));
   206 
   207 fun the_theory name thy =
   208   if Context.theory_name thy = name then thy
   209   else get_theory name;
   210 
   211 val _ = ML_Context.value_antiq "theory"
   212   (Scan.lift Args.name
   213     >> (fn name => (name ^ "_thy", "ThyInfo.theory " ^ ML_Syntax.print_string name))
   214   || Scan.succeed ("thy", "ML_Context.the_context ()"));
   215 
   216 
   217 
   218 (** thy operations **)
   219 
   220 (* maintain 'outdated' flag *)
   221 
   222 local
   223 
   224 fun is_outdated name =
   225   (case lookup_deps name of
   226     SOME (SOME {outdated, ...}) => outdated
   227   | _ => false);
   228 
   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));
   234 
   235 fun check_unfinished name =
   236   if is_finished name then (warning (loader_msg "tried to touch finished theory" [name]); NONE)
   237   else SOME name;
   238 
   239 in
   240 
   241 fun touch_thys names =
   242   List.app outdate_thy (thy_graph Graph.all_succs (map_filter check_unfinished names));
   243 
   244 fun touch_thy name = touch_thys [name];
   245 fun touch_child_thys name = touch_thys (thy_graph Graph.imm_succs name);
   246 
   247 fun touch_all_thys () = List.app outdate_thy (get_names ());
   248 
   249 end;
   250 
   251 
   252 (* check 'finished' state *)
   253 
   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])
   257   else ();
   258 
   259 
   260 (* load_file *)
   261 
   262 local
   263 
   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;
   270 
   271 fun run_file path =
   272   (case Option.map (Context.theory_name o Context.the_theory) (ML_Context.get_context ()) of
   273     NONE => (ThyLoad.load_ml Path.current path; ())
   274   | SOME name =>
   275       (case lookup_deps name of
   276         SOME deps =>
   277           change_deps name (provide path name (ThyLoad.load_ml (master_dir' deps) path))
   278       | NONE => (ThyLoad.load_ml Path.current path; ())));
   279 
   280 in
   281 
   282 fun load_file time path =
   283   if time then
   284     let val name = Path.implode path in
   285       timeit (fn () =>
   286        (priority ("\n**** Starting file " ^ quote name ^ " ****");
   287         run_file path;
   288         priority ("**** Finished file " ^ quote name ^ " ****\n")))
   289     end
   290   else run_file path;
   291 
   292 val use = load_file false o Path.explode;
   293 val time_use = load_file true o Path.explode;
   294 
   295 end;
   296 
   297 
   298 (* load_thy *)
   299 
   300 fun required_by _ [] = ""
   301   | required_by s initiators = s ^ "(required by " ^ show_path (rev initiators) ^ ")";
   302 
   303 fun load_thy really ml time initiators dir name =
   304   let
   305     val _ =
   306       if really then priority ("Loading theory " ^ quote name ^ required_by " " initiators)
   307       else priority ("Registering theory " ^ quote name);
   308 
   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]));
   314 
   315     val _ = touch_thy name;
   316     val _ =
   317       if really then
   318         ThyLoad.load_thy dir name (Position.path master_path) text ml (time orelse ! Output.timing)
   319       else ();
   320 
   321     val missing_files = map_filter (fn (path, NONE) => SOME (Path.implode path) | _ => NONE) files;
   322     val _ =
   323       if null missing_files then ()
   324       else warning (loader_msg "unresolved dependencies of theory" [name] ^
   325         " on file(s): " ^ commas_quote missing_files);
   326   in
   327     CRITICAL (fn () =>
   328      (change_deps name
   329         (Option.map (fn {master, parents, files, ...} => make_deps false master [] parents files));
   330       perform Update name))
   331   end;
   332 
   333 
   334 (* require_thy -- checking database entries wrt. the file-system *)
   335 
   336 local
   337 
   338 fun check_ml master (src_path, info) =
   339   let val info' =
   340     (case info of NONE => NONE
   341     | SOME (_, id) =>
   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;
   345 
   346 fun check_deps ml strict dir name =
   347   (case lookup_deps name of
   348     SOME NONE => (true, NONE, get_parents name)
   349   | NONE =>
   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)
   354       else
   355         let val master' = SOME (ThyLoad.check_thy dir name ml) in
   356           if master_idents master <> master_idents master'
   357           then
   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
   361           else
   362             let
   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
   367         end);
   368 
   369 in
   370 
   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
   373   |>> forall I
   374 and require_thy really ml time strict keep_strict initiators dir str tasks =
   375   let
   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);
   380   in
   381     (case try (Graph.get_node (fst tasks)) name of
   382       SOME task => (Task.is_finished task, tasks)
   383     | NONE =>
   384         let
   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;
   390 
   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;
   394 
   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));
   398 
   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)
   404   end;
   405 
   406 end;
   407 
   408 
   409 (* variations on use_thy -- scheduling required theories *)
   410 
   411 local
   412 
   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 () | _ => ()));
   416 
   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';
   421 
   422 fun next_task G =
   423   let
   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;
   427   in
   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)
   430     else
   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))
   435   end;
   436 
   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" []);
   442       schedule_seq tasks)
   443     else
   444       (case Multithreading.schedule (Int.min (m, n)) next_task tasks of
   445         [] => ()
   446       | exns => raise Exn.EXCEPTIONS (exns, ""))
   447   end;
   448 
   449 fun gen_use_thy' req dir arg =
   450   let val (_, tasks) = req [] dir arg (Graph.empty, 0)
   451   in schedule_tasks tasks end;
   452 
   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))))
   458   end;
   459 
   460 in
   461 
   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;
   465 
   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);
   469 
   470 end;
   471 
   472 
   473 (* remove_thy *)
   474 
   475 fun remove_thy name =
   476   if is_finished name then error (loader_msg "cannot remove finished theory" [name])
   477   else
   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)))
   481     end;
   482 
   483 
   484 (* begin / end theory *)
   485 
   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
   489       NONE => ()
   490     | SOME (path, _) => error ("Illegal use of theory ML file: " ^ quote (Path.implode path)))
   491   end;
   492 
   493 fun begin_theory name parents uses int =
   494   let
   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 ();
   499     (* FIXME tmp *)
   500     val _ = CRITICAL (fn () =>
   501       ML_Context.set_context (SOME (Context.Theory (get_theory (List.last parent_names)))));
   502     val _ = check_uses name uses;
   503 
   504     val theory =
   505       Theory.begin_theory name (map get_theory parent_names)
   506       |> Present.begin_theory dir uses;
   507 
   508     val deps =
   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));
   512 
   513     val uses_now = map_filter (fn (x, true) => SOME x | _ => NONE) uses;
   514     val ((), theory') =
   515       ML_Context.pass_context (Context.Theory theory) (List.app (load_file false)) uses_now
   516       ||> Context.the_theory;
   517   in theory' end;
   518 
   519 fun end_theory theory =
   520   let
   521     val name = Context.theory_name theory;
   522     val theory' = Theory.end_theory theory;
   523     val _ = change_thy name (fn (deps, _) => (deps, SOME theory'));
   524   in theory' end;
   525 
   526 
   527 (* finish all theories *)
   528 
   529 fun finish () = change_thys (Graph.map_nodes (fn (_, entry) => (NONE, entry)));
   530 
   531 
   532 (* register existing theories *)
   533 
   534 fun register_theory theory =
   535   let
   536     val name = Context.theory_name theory;
   537     val parents = Theory.parents_of theory;
   538     val parent_names = map Context.theory_name parents;
   539 
   540     fun err txt bads =
   541       error (loader_msg txt bads ^ "\ncannot register theory " ^ quote name);
   542 
   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
   546       else SOME y_name;
   547     val variants = map_filter get_variant (parents ~~ parent_names);
   548 
   549     fun register G =
   550       (Graph.new_node (name, (NONE, SOME theory)) G
   551         handle Graph.DUP _ => err "duplicate theory entry" [])
   552       |> add_deps name parent_names;
   553   in
   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))
   557   end;
   558 
   559 val _ = register_theory ProtoPure.thy;
   560 
   561 (*final declarations of this structure*)
   562 val theory = get_theory;
   563 val names = get_names;
   564 
   565 end;
   566 
   567 structure BasicThyInfo: BASIC_THY_INFO = ThyInfo;
   568 open BasicThyInfo;