src/Pure/Thy/thy_info.ML
author wenzelm
Tue, 06 Jul 1999 21:03:34 +0200
changeset 6900 29060d9b60d4
parent 6666 be06ed5d0b4c
child 7066 febce8eee487
permissions -rw-r--r--
begin_theory: disallow finished;

(*  Title:      Pure/Thy/thy_info.ML
    ID:         $Id$
    Author:     Markus Wenzel, TU Muenchen

Theory loader database, including theory and file dependencies.
*)

signature BASIC_THY_INFO =
sig
  val theory: string -> theory
  val theory_of_sign: Sign.sg -> theory
  val theory_of_thm: thm -> theory
(*val use: string -> unit*)             (*exported later*)
  val time_use: string -> unit
  val touch_thy: string -> unit
  val use_thy: string -> unit
  val update_thy: string -> unit
  val remove_thy: string -> unit
  val time_use_thy: string -> unit
  val use_thy_only: string -> unit
end;

signature THY_INFO =
sig
  include BASIC_THY_INFO
  val names: unit -> string list
  val get_theory: string -> theory
  val put_theory: theory -> unit
  val get_preds: string -> string list
  val loaded_files: string -> (Path.T * File.info) list
  val load_file: bool -> Path.T -> unit
  val use_path: Path.T -> unit
  val use: string -> unit
  val begin_theory: string -> string list -> (Path.T * bool) list -> theory
  val end_theory: theory -> theory
  val finish: unit -> unit
  val register_theory: theory -> unit
end;

structure ThyInfo: THY_INFO =
struct


(** thy database **)

(* messages *)

fun gen_msg txt [] = txt
  | gen_msg txt names = txt ^ " " ^ commas_quote names;

fun loader_msg txt names = gen_msg ("Theory loader: " ^ txt) names;

val show_path = space_implode " via " o map quote;
fun cycle_msg name names = loader_msg ("cyclic dependency of " ^ show_path (name :: names)) [];


(* derived graph operations *)

fun add_deps name parents G =
  foldl (fn (H, parent) => Graph.add_edge_acyclic (parent, name) H) (G, parents)
    handle Graph.CYCLES namess => error (cat_lines (map (cycle_msg name) namess));

fun del_deps name G =
  foldl (fn (H, parent) => Graph.del_edge (parent, name) H) (G, Graph.imm_preds G name);

fun update_node name parents entry G =
  add_deps name parents
    (if can (Graph.get_node G) name then del_deps name G else Graph.new_node (name, entry) G);


(* thy database *)

type deps =
  {present: bool, outdated: bool,
    master: (Path.T * File.info) list, files: (Path.T * (Path.T * File.info) option) list};

fun make_deps present outdated master files =
  {present = present, outdated = outdated, master = master, files = files}: deps;

type thy = deps option * theory option;

local
  val database = ref (Graph.empty: thy Graph.T);
in
  fun get_thys () = ! database;
  fun change_thys f = database := (f (! database));
end;


(* access thy graph *)

fun thy_graph f x = f (get_thys ()) x;
fun get_names () = Graph.keys (get_thys ());


(* access thy *)

fun lookup_thy name = Some (thy_graph Graph.get_node name) handle Graph.UNDEFINED _ => None;

fun get_thy name =
  (case lookup_thy name of
    Some thy => thy
  | None => error (loader_msg "nothing known about theory" [name]));

fun change_thy name f = (get_thy name; change_thys (Graph.map_node name f));


(* access deps *)

val lookup_deps = apsome #1 o lookup_thy;
val get_deps = #1 o get_thy;
fun change_deps name f = change_thy name (fn (deps, x) => (f deps, x));

fun is_finished name = is_none (get_deps name);
fun get_files name = (case get_deps name of Some {files, ...} => files | _ => []);
val loaded_files = mapfilter #2 o get_files;

fun get_preds name =
  (thy_graph Graph.imm_preds name) handle Graph.UNDEFINED _ =>
    error (loader_msg "nothing known about theory" [name]);


(* access theory *)

fun get_theory name =
  (case get_thy name of
    (_, Some theory) => theory
  | _ => error (loader_msg "undefined theory entry for" [name]));

val theory_of_sign = get_theory o Sign.name_of;
val theory_of_thm = theory_of_sign o Thm.sign_of_thm;

fun put_theory theory =
  change_thy (PureThy.get_name theory) (fn (deps, _) => (deps, Some theory));



(** thy operations **)

(* maintain 'outdated' flag *)

fun is_outdated name =
  (case lookup_deps name of
    Some (Some {outdated, ...}) => outdated
  | _ => false);

fun outdate_thy name =
  if is_finished name then ()
  else change_deps name (apsome (fn {present, outdated = _, master, files} =>
    make_deps present true master files));

fun touch_thy name =
  if is_outdated name then ()
  else if is_finished name then warning (loader_msg "tried to touch finished theory" [name])
  else
    (case filter_out is_outdated (thy_graph Graph.all_succs [name]) \ name of
      [] => outdate_thy name
    | names =>
       (warning (loader_msg "the following theories become out-of-date:" names);
        seq outdate_thy names; outdate_thy name));

val untouch_deps = apsome (fn {present, outdated = _, master, files}: deps =>
  make_deps present false master files);


(* load_thy *)

fun required_by [] = ""
  | required_by initiators = " (required by " ^ show_path (rev initiators) ^ ")";

fun load_thy ml time initiators dir name parents =
  let
    val _ = if name mem_string initiators then error (cycle_msg name (rev initiators)) else ();
    val _ = writeln ("Loading theory " ^ quote name ^ required_by initiators);

    val _ = seq touch_thy (thy_graph Graph.all_succs [name]);
    val master = ThyLoad.load_thy dir name ml time;

    val files = get_files name;
    val missing_files = mapfilter (fn (path, None) => Some (Path.pack path) | _ => None) files;
  in
    if null missing_files then ()
    else warning (loader_msg "unresolved dependencies of theory" [name] ^
      "\nfile(s): " ^ commas_quote missing_files);
    change_deps name (fn _ => Some (make_deps true false master files))
  end;


(* load_file *)

fun run_file path =
  let
    fun provide name info (deps as Some {present, outdated, master, files}) =
          if exists (equal path o #1) files then
            Some (make_deps present outdated master (overwrite (files, (path, Some info))))
          else (warning (loader_msg "undeclared dependency of theory" [name] ^
            " on file: " ^ quote (Path.pack path)); deps)
      | provide _ _ None = None;
  in
    (case apsome PureThy.get_name (Context.get_context ()) of
      None => (ThyLoad.load_file path; ())
    | Some name =>
        if is_some (lookup_thy name) then change_deps name (provide name (ThyLoad.load_file path))
        else (ThyLoad.load_file path; ()))
  end;

fun load_file false path = run_file path
  | load_file true path =
      let val name = Path.pack path in
        timeit (fn () =>
         (writeln ("\n**** Starting file " ^ quote name ^ " ****");
          run_file path;
          writeln ("**** Finished file " ^ quote name ^ " ****\n")))
      end;

val use_path = load_file false;
val use = use_path o Path.unpack;
val time_use = load_file true o Path.unpack;


(* require_thy *)

fun init_deps master files = Some (make_deps false false master (map (rpair None) files));

fun load_deps dir name ml =
  let val (master, (parents, files)) = ThyLoad.deps_thy dir name ml
  in (Some (init_deps master files), parents) end;

fun file_current (_, None) = false
  | file_current (path, info) = info = ThyLoad.check_file path;

fun current_deps ml strict dir name =
  (case lookup_deps name of
    None => (false, load_deps dir name ml)
  | Some deps =>
      let val same_deps = (None, thy_graph Graph.imm_preds name) in
        (case deps of
          None => (true, same_deps)
        | Some {present, outdated, master, files} =>
            if present andalso not strict then (true, same_deps)
            else
              let val master' = ThyLoad.check_thy dir name ml in
                if master <> master' then (false, load_deps dir name ml)
                else (not outdated andalso forall file_current files, same_deps)
              end)
      end);

fun require_thy ml time strict keep_strict initiators prfx s =
  let
    val path = Path.expand (Path.unpack s);
    val name = Path.pack (Path.base path);
    val dir = Path.append prfx (Path.dir path);

    val require_parent =
      #1 o require_thy ml time (strict andalso keep_strict) keep_strict (name :: initiators) dir;
    val (current, (new_deps, parents)) = current_deps ml strict dir name handle ERROR =>
      error (loader_msg "The error(s) above occurred while examining theory" [name] ^
        (if null initiators then "" else "\n" ^ required_by initiators));
    val parents_current = map require_parent parents;

    val result =
      if current andalso forall I parents_current then true
      else
        ((case new_deps of
          Some deps => change_thys (update_node name parents (untouch_deps deps, None))
        | None => ());
          load_thy ml time initiators dir name parents;
          false);
  in (result, name) end;

fun gen_use_thy f s =
  let val (_, name) = f Path.current s in Context.context (get_theory name) end;

val weak_use_thy = gen_use_thy (require_thy true false false false []);
val use_thy      = gen_use_thy (require_thy true false true false []);
val update_thy   = gen_use_thy (require_thy true false true true []);
val time_use_thy = gen_use_thy (require_thy true true true false []);
val use_thy_only = gen_use_thy (require_thy false false true false []);


(* remove_thy *)

fun remove_thy name =
  if is_finished name then error (loader_msg "cannot remove finished theory" [name])
  else
    let val succs = thy_graph Graph.all_succs [name] in
      writeln (loader_msg "removing" succs);
      change_thys (Graph.del_nodes succs)
    end;


(* begin / end theory *)                (* FIXME tune *) (* FIXME files vs. paths (!?!?) *)

fun begin_theory name parents paths =
  let
    val _ =
      if is_some (lookup_thy name) andalso is_finished name then
        error (loader_msg "cannot change finished theory" [name])
      else ();
    val _ = (map Path.basic parents; seq weak_use_thy parents);
    val theory = PureThy.begin_theory name (map get_theory parents);
    val _ = change_thys (update_node name parents (init_deps [] [], Some theory));
    val use_paths = mapfilter (fn (x, true) => Some x | _ => None) paths;
  in Context.setmp (Some theory) (seq use_path) use_paths; theory end;

fun end_theory theory =
  let val theory' = PureThy.end_theory theory
  in put_theory theory'; theory' end;


(* finish all theories *)

fun finish () = change_thys (Graph.map_nodes (fn (_, entry) => (None, entry)));


(* register existing theories *)

fun register_theory theory =
  let
    val name = PureThy.get_name theory;
    val parents = Theory.parents_of theory;
    val parent_names = map PureThy.get_name parents;

    fun err txt bads =
      error (loader_msg txt bads ^ "\n" ^ gen_msg "cannot register theory" [name]);

    val nonfinished = filter_out is_finished parent_names;
    fun get_variant (x, y_name) =
      if Theory.eq_thy (x, get_theory y_name) then None
      else Some y_name;
    val variants = mapfilter get_variant (parents ~~ parent_names);

    fun register G =
      (Graph.new_node (name, (None, Some theory)) G
        handle Graph.DUPLICATE _ => err "duplicate theory entry" [])
      |> add_deps name parent_names;
  in
    if not (null nonfinished) then err "non-finished parent theories" nonfinished
    else if not (null variants) then err "different versions of parent theories" variants
    else change_thys register
  end;


(*final declarations of this structure*)
val theory = get_theory;
val names = get_names;

end;

structure BasicThyInfo: BASIC_THY_INFO = ThyInfo;
open BasicThyInfo;