src/Pure/theory.ML
author haftmann
Tue, 18 Sep 2007 07:46:00 +0200
changeset 24626 85eceef2edc7
parent 24199 8be734b5f59f
child 24666 9885a86f14a8
permissions -rw-r--r--
introduced generic concepts for theory interpretators

(*  Title:      Pure/theory.ML
    ID:         $Id$
    Author:     Lawrence C Paulson and Markus Wenzel

Logical theory content: axioms, definitions, oracles.
*)

signature BASIC_THEORY =
sig
  val eq_thy: theory * theory -> bool
  val subthy: theory * theory -> bool
end

signature THEORY =
sig
  include BASIC_THEORY
  include SIGN_THEORY
  val parents_of: theory -> theory list
  val ancestors_of: theory -> theory list
  val begin_theory: string -> theory list -> theory
  val end_theory: theory -> theory
  val checkpoint: theory -> theory
  val copy: theory -> theory
  val rep_theory: theory ->
   {axioms: term NameSpace.table,
    defs: Defs.T,
    oracles: ((theory * Object.T -> term) * stamp) NameSpace.table}
  val axiom_space: theory -> NameSpace.T
  val axiom_table: theory -> term Symtab.table
  val oracle_space: theory -> NameSpace.T
  val oracle_table: theory -> ((theory * Object.T -> term) * stamp) Symtab.table
  val axioms_of: theory -> (string * term) list
  val all_axioms_of: theory -> (string * term) list
  val defs_of : theory -> Defs.T
  val check_thy: theory -> theory_ref
  val deref: theory_ref -> theory
  val merge: theory * theory -> theory
  val merge_refs: theory_ref * theory_ref -> theory_ref
  val merge_list: theory list -> theory
  val requires: theory -> string -> string -> unit
  val assert_super: theory -> theory -> theory
  val cert_axm: theory -> string * term -> string * term
  val read_axm: theory -> string * string -> string * term
  val add_axioms: (bstring * string) list -> theory -> theory
  val add_axioms_i: (bstring * term) list -> theory -> theory
  val add_deps: string -> string * typ -> (string * typ) list -> theory -> theory
  val add_defs: bool -> bool -> (bstring * string) list -> theory -> theory
  val add_defs_i: bool -> bool -> (bstring * term) list -> theory -> theory
  val add_finals: bool -> string list -> theory -> theory
  val add_finals_i: bool -> term list -> theory -> theory
  val add_oracle: bstring * (theory * Object.T -> term) -> theory -> theory
end

signature THEORY_INTERPRETATOR =
sig
  type T
  type interpretator = T list -> theory -> theory
  val add_those: T list -> theory -> theory
  val all_those: theory -> T list
  val add_interpretator: interpretator -> theory -> theory
  val init: theory -> theory
end;

signature THEORY_INTERPRETATOR_KEY =
sig
  type T
  val eq: T * T -> bool
end;

structure Theory =
struct


(** datatype thy **)

datatype thy = Thy of
 {axioms: term NameSpace.table,
  defs: Defs.T,
  oracles: ((theory * Object.T -> term) * stamp) NameSpace.table,
  consolidate: theory -> theory};

fun make_thy (axioms, defs, oracles, consolidate) =
  Thy {axioms = axioms, defs = defs, oracles = oracles, consolidate = consolidate};

fun err_dup_axm dup = error ("Duplicate axiom: " ^ quote dup);
fun err_dup_ora dup = error ("Duplicate oracle: " ^ quote dup);

structure ThyData = TheoryDataFun
(
  type T = thy;
  val empty = make_thy (NameSpace.empty_table, Defs.empty, NameSpace.empty_table, I);
  val copy = I;

  fun extend (Thy {axioms, defs, oracles, consolidate}) =
    make_thy (NameSpace.empty_table, defs, oracles, consolidate);

  fun merge pp (thy1, thy2) =
    let
      val Thy {axioms = _, defs = defs1, oracles = oracles1,
        consolidate = consolidate1} = thy1;
      val Thy {axioms = _, defs = defs2, oracles = oracles2,
        consolidate = consolidate2} = thy2;

      val axioms = NameSpace.empty_table;
      val defs = Defs.merge pp (defs1, defs2);
      val oracles = NameSpace.merge_tables (eq_snd (op =)) (oracles1, oracles2)
        handle Symtab.DUP dup => err_dup_ora dup;
      val consolidate = consolidate1 #> consolidate2;
    in make_thy (axioms, defs, oracles, consolidate) end;
);

fun rep_theory thy = ThyData.get thy |> (fn Thy {axioms, defs, oracles, ...} =>
  {axioms = axioms, defs = defs, oracles = oracles});

fun map_thy f = ThyData.map (fn (Thy {axioms, defs, oracles, consolidate}) =>
  make_thy (f (axioms, defs, oracles, consolidate)));

fun map_axioms f = map_thy
  (fn (axioms, defs, oracles, consolidate) => (f axioms, defs, oracles, consolidate));
fun map_defs f = map_thy
  (fn (axioms, defs, oracles, consolidate) => (axioms, f defs, oracles, consolidate));
fun map_oracles f = map_thy
  (fn (axioms, defs, oracles, consolidate) => (axioms, defs, f oracles, consolidate));


(* basic operations *)

val axiom_space = #1 o #axioms o rep_theory;
val axiom_table = #2 o #axioms o rep_theory;

val oracle_space = #1 o #oracles o rep_theory;
val oracle_table = #2 o #oracles o rep_theory;

val axioms_of = Symtab.dest o #2 o #axioms o rep_theory;

val defs_of = #defs o rep_theory;

fun requires thy name what =
  if Context.exists_name name thy then ()
  else error ("Require theory " ^ quote name ^ " as an ancestor for " ^ what);


(* interpretators *)

fun add_consolidate f = map_thy
  (fn (axioms, defs, oracles, consolidate) => (axioms, defs, oracles, consolidate #> f));

fun consolidate thy =
  let
    val Thy {consolidate, ...} = ThyData.get thy;
  in
    thy |> consolidate
  end;


(** type theory **)

(* context operations *)

val eq_thy = Context.eq_thy;
val subthy = Context.subthy;

fun assert_super thy1 thy2 =
  if subthy (thy1, thy2) then thy2
  else raise THEORY ("Not a super theory", [thy1, thy2]);

val parents_of = Context.parents_of;
val ancestors_of = Context.ancestors_of;

val check_thy = Context.check_thy;
val deref = Context.deref;
val merge = Context.merge;
val merge_refs = Context.merge_refs;

fun merge_list [] = raise THEORY ("Empty merge of theories", [])
  | merge_list (thy :: thys) = Library.foldl merge (thy, thys);

val begin_theory = Sign.local_path o consolidate oo Context.begin_thy Sign.pp;
val end_theory = Context.finish_thy;
val checkpoint = Context.checkpoint_thy;
val copy = Context.copy_thy;


(* signature operations *)

structure SignTheory: SIGN_THEORY = Sign;
open SignTheory;



(** axioms **)

fun all_axioms_of thy = maps axioms_of (thy :: ancestors_of thy);


(* prepare axioms *)

fun err_in_axm msg name =
  cat_error msg ("The error(s) above occurred in axiom " ^ quote name);

fun cert_axm thy (name, raw_tm) =
  let
    val (t, T, _) = Sign.certify_prop thy raw_tm
      handle TYPE (msg, _, _) => error msg
        | TERM (msg, _) => error msg;
  in
    Term.no_dummy_patterns t handle TERM (msg, _) => error msg;
    (name, Sign.no_vars (Sign.pp thy) t)
  end;

fun read_axm thy (name, str) =
  cert_axm thy (name, Sign.read_prop thy str)
    handle ERROR msg => err_in_axm msg name;


(* add_axioms(_i) *)

local

fun gen_add_axioms prep_axm raw_axms thy = thy |> map_axioms (fn axioms =>
  let
    val axms = map (apsnd (Compress.term thy o Logic.varify) o prep_axm thy) raw_axms;
    val axioms' = NameSpace.extend_table (Sign.naming_of thy) axms axioms
      handle Symtab.DUP dup => err_dup_axm dup;
  in axioms' end);

in

val add_axioms = gen_add_axioms read_axm;
val add_axioms_i = gen_add_axioms cert_axm;

end;



(** add constant definitions **)

(* dependencies *)

fun dependencies thy unchecked is_def name lhs rhs =
  let
    val pp = Sign.pp thy;
    val consts = Sign.consts_of thy;
    fun prep const =
      let val Const (c, T) = Sign.no_vars pp (Const const)
      in (c, Consts.typargs consts (c, Compress.typ thy (Logic.varifyT T))) end;

    val lhs_vars = Term.add_tfreesT (#2 lhs) [];
    val rhs_extras = fold (#2 #> Term.fold_atyps (fn TFree v =>
      if member (op =) lhs_vars v then I else insert (op =) v | _ => I)) rhs [];
    val _ =
      if null rhs_extras then ()
      else error ("Specification depends on extra type variables: " ^
        commas_quote (map (Pretty.string_of_typ pp o TFree) rhs_extras) ^
        "\nThe error(s) above occurred in " ^ quote name);
  in Defs.define pp unchecked is_def name (prep lhs) (map prep rhs) end;

fun add_deps a raw_lhs raw_rhs thy =
  let
    val lhs :: rhs = map (dest_Const o Sign.cert_term thy o Const) (raw_lhs :: raw_rhs);
    val name = if a = "" then (#1 lhs ^ " axiom") else a;
  in thy |> map_defs (dependencies thy false false name lhs rhs) end;


(* check_overloading *)

fun check_overloading thy overloaded (c, T) =
  let
    val declT =
      (case Sign.const_constraint thy c of
        NONE => error ("Undeclared constant " ^ quote c)
      | SOME declT => declT);
    val T' = Logic.varifyT T;

    fun message txt =
      [Pretty.block [Pretty.str "Specification of constant ",
        Pretty.str c, Pretty.str " ::", Pretty.brk 1, Pretty.quote (Sign.pretty_typ thy T)],
        Pretty.str txt] |> Pretty.chunks |> Pretty.string_of;
  in
    if Sign.typ_instance thy (declT, T') then ()
    else if Type.raw_instance (declT, T') then
      error (Library.setmp show_sorts true
        message "imposes additional sort constraints on the constant declaration")
    else if overloaded then ()
    else warning (message "is strictly less general than the declared type");
    (c, T)
  end;


(* check_def *)

fun check_def thy unchecked overloaded (bname, tm) defs =
  let
    val name = Sign.full_name thy bname;
    val (lhs_const, rhs) = Sign.cert_def (Sign.pp thy) tm;
    val rhs_consts = fold_aterms (fn Const const => insert (op =) const | _ => I) rhs [];
    val _ = check_overloading thy overloaded lhs_const;
  in defs |> dependencies thy unchecked true name lhs_const rhs_consts end
  handle ERROR msg => cat_error msg (Pretty.string_of (Pretty.block
   [Pretty.str ("The error(s) above occurred in definition " ^ quote bname ^ ":"),
    Pretty.fbrk, Pretty.quote (Sign.pretty_term thy tm)]));


(* add_defs(_i) *)

local

fun gen_add_defs prep_axm unchecked overloaded raw_axms thy =
  let val axms = map (prep_axm thy) raw_axms in
    thy
    |> map_defs (fold (check_def thy unchecked overloaded) axms)
    |> add_axioms_i axms
  end;

in

val add_defs_i = gen_add_defs cert_axm;
val add_defs = gen_add_defs read_axm;

end;


(* add_finals(_i) *)

local

fun gen_add_finals prep_term overloaded args thy =
  let
    fun const_of (Const const) = const
      | const_of (Free _) = error "Attempt to finalize variable (or undeclared constant)"
      | const_of _ = error "Attempt to finalize non-constant term";
    fun specify (c, T) = dependencies thy false false (c ^ " axiom") (c, T) [];
    val finalize = specify o check_overloading thy overloaded o const_of o prep_term thy;
  in thy |> map_defs (fold finalize args) end;

in

val add_finals = gen_add_finals Sign.read_term;
val add_finals_i = gen_add_finals Sign.cert_term;

end;



(** add oracle **)

fun add_oracle (bname, oracle) thy = thy |> map_oracles (fn oracles =>
  NameSpace.extend_table (Sign.naming_of thy) [(bname, (oracle, stamp ()))] oracles
    handle Symtab.DUP dup => err_dup_ora dup);

end;

functor TheoryInterpretatorFun(Key: THEORY_INTERPRETATOR_KEY) : THEORY_INTERPRETATOR =
struct

open Key;

type interpretator = T list -> theory -> theory;

fun apply ips x = fold_rev (fn (_, f) => f x) ips;

structure InterpretatorData = TheoryDataFun (
  type T = ((serial * interpretator) list * T list) * (theory -> theory);
  val empty = (([], []), I);
  val extend = I;
  val copy = I;
  fun merge pp (((interpretators1, done1), upd1), ((interpretators2, done2), upd2)) =
    let
      fun diff (interpretators1 : (serial * interpretator) list, done1)
        (interpretators2, done2) = let
          val interpretators = subtract (eq_fst (op =)) interpretators1 interpretators2;
          val undone = subtract eq done2 done1;
        in apply interpretators undone end;
      val interpretators = AList.merge (op =) (K true) (interpretators1, interpretators2);
      val done = Library.merge eq (done1, done2);
      val upd_new = diff (interpretators2, done2) (interpretators1, done1)
        #> diff (interpretators1, done1) (interpretators2, done2);
      val upd = upd1 #> upd2 #> upd_new;
    in ((interpretators, done), upd) end;
);

fun consolidate thy =
  let
    val (_, upd) = InterpretatorData.get thy;
  in
    thy |> upd |> (InterpretatorData.map o apsnd) (K I)
  end;

val init = Theory.add_consolidate consolidate;

fun add_those xs thy =
  let
    val ((interpretators, _), _) = InterpretatorData.get thy;
  in
    thy
    |> apply interpretators xs
    |> (InterpretatorData.map o apfst o apsnd) (append xs)
  end;

val all_those = snd o fst o InterpretatorData.get;

fun add_interpretator interpretator thy =
  let
    val ((interpretators, xs), _) = InterpretatorData.get thy;
  in
    thy
    |> interpretator (rev xs)
    |> (InterpretatorData.map o apfst o apfst) (cons (serial (), interpretator))
  end;

end;

structure Theory: THEORY = Theory;
structure BasicTheory: BASIC_THEORY = Theory;
open BasicTheory;