src/Pure/context.ML
author wenzelm
Wed Jun 13 00:01:58 2007 +0200 (2007-06-13)
changeset 23355 d2c033fd4514
parent 22847 22da6c4bc422
child 23595 7ca68a2c8575
permissions -rw-r--r--
merge/merge_refs: plain error instead of exception TERM;
     1 (*  Title:      Pure/context.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Generic theory contexts with unique identity, arbitrarily typed data,
     6 development graph and history support.  Generic proof contexts with
     7 arbitrarily typed data.
     8 *)
     9 
    10 signature BASIC_CONTEXT =
    11 sig
    12   type theory
    13   type theory_ref
    14   exception THEORY of string * theory list
    15 end;
    16 
    17 signature CONTEXT =
    18 sig
    19   include BASIC_CONTEXT
    20   (*theory context*)
    21   val theory_name: theory -> string
    22   val parents_of: theory -> theory list
    23   val ancestors_of: theory -> theory list
    24   val is_stale: theory -> bool
    25   val ProtoPureN: string
    26   val PureN: string
    27   val CPureN: string
    28   val draftN: string
    29   val exists_name: string -> theory -> bool
    30   val names_of: theory -> string list
    31   val pretty_thy: theory -> Pretty.T
    32   val string_of_thy: theory -> string
    33   val pprint_thy: theory -> pprint_args -> unit
    34   val pretty_abbrev_thy: theory -> Pretty.T
    35   val str_of_thy: theory -> string
    36   val check_thy: theory -> theory
    37   val eq_thy: theory * theory -> bool
    38   val thy_ord: theory * theory -> order
    39   val subthy: theory * theory -> bool
    40   val joinable: theory * theory -> bool
    41   val merge: theory * theory -> theory
    42   val merge_refs: theory_ref * theory_ref -> theory_ref
    43   val self_ref: theory -> theory_ref
    44   val deref: theory_ref -> theory
    45   val copy_thy: theory -> theory
    46   val checkpoint_thy: theory -> theory
    47   val finish_thy: theory -> theory
    48   val pre_pure_thy: theory
    49   val begin_thy: (theory -> Pretty.pp) -> string -> theory list -> theory
    50   (*proof context*)
    51   type proof
    52   val theory_of_proof: proof -> theory
    53   val transfer_proof: theory -> proof -> proof
    54   val init_proof: theory -> proof
    55   (*generic context*)
    56   datatype generic = Theory of theory | Proof of proof
    57   val cases: (theory -> 'a) -> (proof -> 'a) -> generic -> 'a
    58   val mapping: (theory -> theory) -> (proof -> proof) -> generic -> generic
    59   val mapping_result: (theory -> 'a * theory) -> (proof -> 'a * proof) -> generic -> 'a * generic
    60   val the_theory: generic -> theory
    61   val the_proof: generic -> proof
    62   val map_theory: (theory -> theory) -> generic -> generic
    63   val map_proof: (proof -> proof) -> generic -> generic
    64   val theory_map: (generic -> generic) -> theory -> theory
    65   val proof_map: (generic -> generic) -> proof -> proof
    66   val theory_of: generic -> theory   (*total*)
    67   val proof_of: generic -> proof     (*total*)
    68   (*delayed setup*)
    69   val add_setup: (theory -> theory) -> unit
    70   val setup: unit -> theory -> theory
    71 end;
    72 
    73 signature PRIVATE_CONTEXT =
    74 sig
    75   include CONTEXT
    76   structure TheoryData:
    77   sig
    78     val declare: Object.T -> (Object.T -> Object.T) -> (Object.T -> Object.T) ->
    79       (Pretty.pp -> Object.T * Object.T -> Object.T) -> serial
    80     val get: serial -> (Object.T -> 'a) -> theory -> 'a
    81     val put: serial -> ('a -> Object.T) -> 'a -> theory -> theory
    82   end
    83   structure ProofData:
    84   sig
    85     val declare: (theory -> Object.T) -> serial
    86     val get: serial -> (Object.T -> 'a) -> proof -> 'a
    87     val put: serial -> ('a -> Object.T) -> 'a -> proof -> proof
    88   end
    89 end;
    90 
    91 structure Context: PRIVATE_CONTEXT =
    92 struct
    93 
    94 (*** theory context ***)
    95 
    96 (** theory data **)
    97 
    98 (* data kinds and access methods *)
    99 
   100 (*private copy avoids potential conflict of table exceptions*)
   101 structure Datatab = TableFun(type key = int val ord = int_ord);
   102 
   103 local
   104 
   105 type kind =
   106  {empty: Object.T,
   107   copy: Object.T -> Object.T,
   108   extend: Object.T -> Object.T,
   109   merge: Pretty.pp -> Object.T * Object.T -> Object.T};
   110 
   111 val kinds = ref (Datatab.empty: kind Datatab.table);
   112 
   113 fun invoke f k =
   114   (case Datatab.lookup (! kinds) k of
   115     SOME kind => f kind
   116   | NONE => sys_error "Invalid theory data identifier");
   117 
   118 in
   119 
   120 fun invoke_empty k   = invoke (K o #empty) k ();
   121 val invoke_copy      = invoke #copy;
   122 val invoke_extend    = invoke #extend;
   123 fun invoke_merge pp  = invoke (fn kind => #merge kind pp);
   124 
   125 fun declare_theory_data empty copy extend merge =
   126   let
   127     val k = serial ();
   128     val kind = {empty = empty, copy = copy, extend = extend, merge = merge};
   129     val _ = change kinds (Datatab.update (k, kind));
   130   in k end;
   131 
   132 val copy_data = Datatab.map' invoke_copy;
   133 val extend_data = Datatab.map' invoke_extend;
   134 fun merge_data pp = Datatab.join (invoke_merge pp) o pairself extend_data;
   135 
   136 end;
   137 
   138 
   139 
   140 (** datatype theory **)
   141 
   142 datatype theory =
   143   Theory of
   144    (*identity*)
   145    {self: theory ref option,            (*dynamic self reference -- follows theory changes*)
   146     id: serial * string,                (*identifier of this theory*)
   147     ids: string Inttab.table,           (*identifiers of ancestors*)
   148     iids: string Inttab.table} *        (*identifiers of intermediate checkpoints*)
   149    (*data*)
   150    Object.T Datatab.table *
   151    (*ancestry*)
   152    {parents: theory list,               (*immediate predecessors*)
   153     ancestors: theory list} *           (*all predecessors*)
   154    (*history*)
   155    {name: string,                       (*prospective name of finished theory*)
   156     version: int,                       (*checkpoint counter*)
   157     intermediates: theory list};        (*intermediate checkpoints*)
   158 
   159 exception THEORY of string * theory list;
   160 
   161 fun rep_theory (Theory args) = args;
   162 
   163 val identity_of = #1 o rep_theory;
   164 val data_of     = #2 o rep_theory;
   165 val ancestry_of = #3 o rep_theory;
   166 val history_of  = #4 o rep_theory;
   167 
   168 fun make_identity self id ids iids = {self = self, id = id, ids = ids, iids = iids};
   169 fun make_ancestry parents ancestors = {parents = parents, ancestors = ancestors};
   170 fun make_history name vers ints = {name = name, version = vers, intermediates = ints};
   171 
   172 val the_self = the o #self o identity_of;
   173 val parents_of = #parents o ancestry_of;
   174 val ancestors_of = #ancestors o ancestry_of;
   175 val theory_name = #name o history_of;
   176 
   177 
   178 (* staleness *)
   179 
   180 fun eq_id ((i: int, _), (j, _)) = (i = j);
   181 
   182 fun is_stale
   183     (Theory ({self = SOME (ref (Theory ({id = id', ...}, _, _, _))), id, ...}, _, _, _)) =
   184       not (eq_id (id, id'))
   185   | is_stale (Theory ({self = NONE, ...}, _, _, _)) = true;
   186 
   187 fun vitalize (thy as Theory ({self = SOME r, ...}, _, _, _)) = (r := thy; thy)
   188   | vitalize (thy as Theory ({self = NONE, id, ids, iids}, data, ancestry, history)) =
   189       let
   190         val r = ref thy;
   191         val thy' = Theory (make_identity (SOME r) id ids iids, data, ancestry, history);
   192       in r := thy'; thy' end;
   193 
   194 
   195 (* names *)
   196 
   197 val ProtoPureN = "ProtoPure";
   198 val PureN = "Pure";
   199 val CPureN = "CPure";
   200 
   201 val draftN = "#";
   202 fun draft_id (_, name) = (name = draftN);
   203 val is_draft = draft_id o #id o identity_of;
   204 
   205 fun exists_name name (thy as Theory ({id, ids, iids, ...}, _, _, _)) =
   206   name = theory_name thy orelse
   207   name = #2 id orelse
   208   Inttab.exists (equal name o #2) ids orelse
   209   Inttab.exists (equal name o #2) iids;
   210 
   211 fun names_of (Theory ({id, ids, iids, ...}, _, _, _)) =
   212   rev (#2 id :: Inttab.fold (cons o #2) iids (Inttab.fold (cons o #2) ids []));
   213 
   214 fun pretty_thy thy =
   215   Pretty.str_list "{" "}" (names_of thy @ (if is_stale thy then ["!"] else []));
   216 
   217 val string_of_thy = Pretty.string_of o pretty_thy;
   218 val pprint_thy = Pretty.pprint o pretty_thy;
   219 
   220 fun pretty_abbrev_thy thy =
   221   let
   222     val names = names_of thy;
   223     val n = length names;
   224     val abbrev = if n > 5 then "..." :: List.drop (names, n - 5) else names;
   225   in Pretty.str_list "{" "}" abbrev end;
   226 
   227 val str_of_thy = Pretty.str_of o pretty_abbrev_thy;
   228 
   229 
   230 (* consistency *)
   231 
   232 fun check_thy thy =
   233   if is_stale thy then error ("Stale theory encountered:\n" ^ string_of_thy thy)
   234   else thy;
   235 
   236 fun check_ins id ids =
   237   if draft_id id orelse Inttab.defined ids (#1 id) then ids
   238   else if Inttab.exists (equal (#2 id) o #2) ids then
   239     error ("Different versions of theory component " ^ quote (#2 id))
   240   else Inttab.update id ids;
   241 
   242 fun check_insert intermediate id (ids, iids) =
   243   let val ids' = check_ins id ids and iids' = check_ins id iids
   244   in if intermediate then (ids, iids') else (ids', iids) end;
   245 
   246 fun check_merge
   247     (Theory ({id = id1, ids = ids1, iids = iids1, ...}, _, _, history1))
   248     (Theory ({id = id2, ids = ids2, iids = iids2, ...}, _, _, history2)) =
   249   (Inttab.fold check_ins ids2 ids1, Inttab.fold check_ins iids2 iids1)
   250   |> check_insert (#version history1 > 0) id1
   251   |> check_insert (#version history2 > 0) id2;
   252 
   253 
   254 (* equality and inclusion *)
   255 
   256 val eq_thy = eq_id o pairself (#id o identity_of o check_thy);
   257 val thy_ord = int_ord o pairself (#1 o #id o identity_of);
   258 
   259 fun proper_subthy
   260     (Theory ({id = (i, _), ...}, _, _, _), Theory ({ids, iids, ...}, _, _, _)) =
   261   Inttab.defined ids i orelse Inttab.defined iids i;
   262 
   263 fun subthy thys = eq_thy thys orelse proper_subthy thys;
   264 
   265 fun joinable (thy1, thy2) = subthy (thy1, thy2) orelse subthy (thy2, thy1);
   266 
   267 
   268 (* theory references *)
   269 
   270 (*theory_ref provides a safe way to store dynamic references to a
   271   theory in external data structures -- a plain theory value would
   272   become stale as the self reference moves on*)
   273 
   274 datatype theory_ref = TheoryRef of theory ref;
   275 
   276 val self_ref = TheoryRef o the_self o check_thy;
   277 fun deref (TheoryRef (ref thy)) = thy;
   278 
   279 
   280 (* trivial merge *)
   281 
   282 fun merge (thy1, thy2) =
   283   if eq_thy (thy1, thy2) then thy1
   284   else if proper_subthy (thy2, thy1) then thy1
   285   else if proper_subthy (thy1, thy2) then thy2
   286   else (check_merge thy1 thy2;
   287     error (cat_lines ["Attempt to perform non-trivial merge of theories:",
   288       str_of_thy thy1, str_of_thy thy2]));
   289 
   290 fun merge_refs (ref1, ref2) =
   291   if ref1 = ref2 then ref1
   292   else self_ref (merge (deref ref1, deref ref2));
   293 
   294 
   295 
   296 (** build theories **)
   297 
   298 (* primitives *)
   299 
   300 fun create_thy name self id ids iids data ancestry history =
   301   let
   302     val {version, name = _, intermediates = _} = history;
   303     val intermediate = version > 0;
   304     val (ids', iids') = check_insert intermediate id (ids, iids);
   305     val id' = (serial (), name);
   306     val _ = check_insert intermediate id' (ids', iids');
   307     val identity' = make_identity self id' ids' iids';
   308   in vitalize (Theory (identity', data, ancestry, history)) end;
   309 
   310 fun change_thy name f (thy as Theory ({self, id, ids, iids}, data, ancestry, history)) =
   311   let
   312     val _ = check_thy thy;
   313     val (self', data', ancestry') =
   314       if is_draft thy then (self, data, ancestry)    (*destructive change!*)
   315       else if #version history > 0
   316       then (NONE, copy_data data, ancestry)
   317       else (NONE, extend_data data,
   318         make_ancestry [thy] (thy :: #ancestors ancestry));
   319     val data'' = f data';
   320   in create_thy name self' id ids iids data'' ancestry' history end;
   321 
   322 fun name_thy name = change_thy name I;
   323 val modify_thy = change_thy draftN;
   324 val extend_thy = modify_thy I;
   325 
   326 fun copy_thy (thy as Theory ({id, ids, iids, ...}, data, ancestry, history)) =
   327   (check_thy thy; create_thy draftN NONE id ids iids (copy_data data) ancestry history);
   328 
   329 val pre_pure_thy = create_thy draftN NONE (serial (), draftN) Inttab.empty Inttab.empty
   330   Datatab.empty (make_ancestry [] []) (make_history ProtoPureN 0 []);
   331 
   332 
   333 (* named theory nodes *)
   334 
   335 fun merge_thys pp (thy1, thy2) =
   336   if exists_name CPureN thy1 <> exists_name CPureN thy2 then
   337     error "Cannot merge Pure and CPure developments"
   338   else
   339     let
   340       val (ids, iids) = check_merge thy1 thy2;
   341       val data = merge_data (pp thy1) (data_of thy1, data_of thy2);
   342       val ancestry = make_ancestry [] [];
   343       val history = make_history "" 0 [];
   344     in create_thy draftN NONE (serial (), draftN) ids iids data ancestry history end;
   345 
   346 fun maximal_thys thys =
   347   thys |> filter (fn thy => not (exists (fn thy' => proper_subthy (thy, thy')) thys));
   348 
   349 fun begin_thy pp name imports =
   350   if name = draftN then error ("Illegal theory name: " ^ quote draftN)
   351   else
   352     let
   353       val parents =
   354         maximal_thys (distinct eq_thy (map check_thy imports));
   355       val ancestors = distinct eq_thy (parents @ maps ancestors_of parents);
   356       val Theory ({id, ids, iids, ...}, data, _, _) =
   357         (case parents of
   358           [] => error "No parent theories"
   359         | [thy] => extend_thy thy
   360         | thy :: thys => Library.foldl (merge_thys pp) (thy, thys));
   361       val ancestry = make_ancestry parents ancestors;
   362       val history = make_history name 0 [];
   363     in create_thy draftN NONE id ids iids data ancestry history end;
   364 
   365 
   366 (* undoable checkpoints *)
   367 
   368 fun checkpoint_thy thy =
   369   if not (is_draft thy) then thy
   370   else
   371     let
   372       val {name, version, intermediates} = history_of thy;
   373       val thy' as Theory (identity', data', ancestry', _) =
   374         name_thy (name ^ ":" ^ string_of_int version) thy;
   375       val history' = make_history name (version + 1) (thy' :: intermediates);
   376     in vitalize (Theory (identity', data', ancestry', history')) end;
   377 
   378 fun finish_thy thy =
   379   let
   380     val {name, version, intermediates} = history_of thy;
   381     val rs = map (the_self o check_thy) intermediates;
   382     val thy' as Theory ({self, id, ids, ...}, data', ancestry', _) = name_thy name thy;
   383     val identity' = make_identity self id ids Inttab.empty;
   384     val history' = make_history name 0 [];
   385     val thy'' = vitalize (Theory (identity', data', ancestry', history'));
   386     val _ = List.app (fn r => r := thy'') rs;
   387   in thy'' end;
   388 
   389 
   390 (* theory data *)
   391 
   392 structure TheoryData =
   393 struct
   394 
   395 val declare = declare_theory_data;
   396 
   397 fun get k dest thy =
   398   dest ((case Datatab.lookup (data_of thy) k of
   399     SOME x => x
   400   | NONE => invoke_copy k (invoke_empty k)));   (*adhoc value*)
   401 
   402 fun put k mk x = modify_thy (Datatab.update (k, mk x));
   403 
   404 end;
   405 
   406 
   407 
   408 (*** proof context ***)
   409 
   410 (* datatype proof *)
   411 
   412 datatype proof = Proof of theory_ref * Object.T Datatab.table;
   413 
   414 fun theory_of_proof (Proof (thy_ref, _)) = deref thy_ref;
   415 fun data_of_proof (Proof (_, data)) = data;
   416 fun map_prf f (Proof (thy_ref, data)) = Proof (thy_ref, f data);
   417 
   418 
   419 (* proof data kinds *)
   420 
   421 local
   422 
   423 val kinds = ref (Datatab.empty: (theory -> Object.T) Datatab.table);
   424 
   425 fun invoke_init k =
   426   (case Datatab.lookup (! kinds) k of
   427     SOME init => init
   428   | NONE => sys_error "Invalid proof data identifier");
   429 
   430 fun init_data thy =
   431   Datatab.map' (fn k => fn _ => invoke_init k thy) (! kinds);
   432 
   433 fun init_new_data data thy =
   434   Datatab.merge (K true) (data, init_data thy);
   435 
   436 in
   437 
   438 fun init_proof thy = Proof (self_ref thy, init_data thy);
   439 
   440 fun transfer_proof thy' (prf as Proof (thy_ref, data)) =
   441   if not (subthy (deref thy_ref, thy')) then
   442     error "transfer proof context: not a super theory"
   443   else Proof (self_ref thy', init_new_data data thy');
   444 
   445 
   446 structure ProofData =
   447 struct
   448 
   449 fun declare init =
   450   let
   451     val k = serial ();
   452     val _ = change kinds (Datatab.update (k, init));
   453   in k end;
   454 
   455 fun get k dest prf =
   456   dest (case Datatab.lookup (data_of_proof prf) k of
   457     SOME x => x
   458   | NONE => invoke_init k (theory_of_proof prf));   (*adhoc value*)
   459 
   460 fun put k mk x = map_prf (Datatab.update (k, mk x));
   461 
   462 end;
   463 
   464 end;
   465 
   466 
   467 
   468 (*** generic context ***)
   469 
   470 datatype generic = Theory of theory | Proof of proof;
   471 
   472 fun cases f _ (Theory thy) = f thy
   473   | cases _ g (Proof prf) = g prf;
   474 
   475 fun mapping f g = cases (Theory o f) (Proof o g);
   476 fun mapping_result f g = cases (apsnd Theory o f) (apsnd Proof o g);
   477 
   478 val the_theory = cases I (fn _ => raise Fail "Ill-typed context: theory expected");
   479 val the_proof = cases (fn _ => raise Fail "Ill-typed context: proof expected") I;
   480 
   481 fun map_theory f = Theory o f o the_theory;
   482 fun map_proof f = Proof o f o the_proof;
   483 
   484 fun theory_map f = the_theory o f o Theory;
   485 fun proof_map f = the_proof o f o Proof;
   486 
   487 val theory_of = cases I theory_of_proof;
   488 val proof_of = cases init_proof I;
   489 
   490 
   491 
   492 (** delayed theory setup **)
   493 
   494 local
   495   val setup_fn = ref (I: theory -> theory);
   496 in
   497   fun add_setup f = setup_fn := (! setup_fn #> f);
   498   fun setup () = let val f = ! setup_fn in setup_fn := I; f end;
   499 end;
   500 
   501 end;
   502 
   503 structure BasicContext: BASIC_CONTEXT = Context;
   504 open BasicContext;
   505 
   506 
   507 
   508 (*** type-safe interfaces for data declarations ***)
   509 
   510 (** theory data **)
   511 
   512 signature THEORY_DATA_ARGS =
   513 sig
   514   type T
   515   val empty: T
   516   val copy: T -> T
   517   val extend: T -> T
   518   val merge: Pretty.pp -> T * T -> T
   519 end;
   520 
   521 signature THEORY_DATA =
   522 sig
   523   type T
   524   val get: theory -> T
   525   val put: T -> theory -> theory
   526   val map: (T -> T) -> theory -> theory
   527   val init: theory -> theory
   528 end;
   529 
   530 functor TheoryDataFun(Data: THEORY_DATA_ARGS): THEORY_DATA =
   531 struct
   532 
   533 structure TheoryData = Context.TheoryData;
   534 
   535 type T = Data.T;
   536 exception Data of T;
   537 
   538 val kind = TheoryData.declare
   539   (Data Data.empty)
   540   (fn Data x => Data (Data.copy x))
   541   (fn Data x => Data (Data.extend x))
   542   (fn pp => fn (Data x1, Data x2) => Data (Data.merge pp (x1, x2)));
   543 
   544 val get = TheoryData.get kind (fn Data x => x);
   545 val put = TheoryData.put kind Data;
   546 fun map f thy = put (f (get thy)) thy;
   547 
   548 fun init thy = map I thy;
   549 
   550 end;
   551 
   552 
   553 
   554 (** proof data **)
   555 
   556 signature PROOF_DATA_ARGS =
   557 sig
   558   type T
   559   val init: theory -> T
   560 end;
   561 
   562 signature PROOF_DATA =
   563 sig
   564   type T
   565   val get: Context.proof -> T
   566   val put: T -> Context.proof -> Context.proof
   567   val map: (T -> T) -> Context.proof -> Context.proof
   568 end;
   569 
   570 functor ProofDataFun(Data: PROOF_DATA_ARGS): PROOF_DATA =
   571 struct
   572 
   573 structure ProofData = Context.ProofData;
   574 
   575 type T = Data.T;
   576 exception Data of T;
   577 
   578 val kind = ProofData.declare (Data o Data.init);
   579 
   580 val get = ProofData.get kind (fn Data x => x);
   581 val put = ProofData.put kind Data;
   582 fun map f prf = put (f (get prf)) prf;
   583 
   584 end;
   585 
   586 
   587 
   588 (** generic data **)
   589 
   590 signature GENERIC_DATA_ARGS =
   591 sig
   592   type T
   593   val empty: T
   594   val extend: T -> T
   595   val merge: Pretty.pp -> T * T -> T
   596 end;
   597 
   598 signature GENERIC_DATA =
   599 sig
   600   type T
   601   val get: Context.generic -> T
   602   val put: T -> Context.generic -> Context.generic
   603   val map: (T -> T) -> Context.generic -> Context.generic
   604 end;
   605 
   606 functor GenericDataFun(Data: GENERIC_DATA_ARGS): GENERIC_DATA =
   607 struct
   608 
   609 structure ThyData = TheoryDataFun(open Data val copy = I);
   610 structure PrfData = ProofDataFun(type T = Data.T val init = ThyData.get);
   611 
   612 type T = Data.T;
   613 
   614 fun get (Context.Theory thy) = ThyData.get thy
   615   | get (Context.Proof prf) = PrfData.get prf;
   616 
   617 fun put x (Context.Theory thy) = Context.Theory (ThyData.put x thy)
   618   | put x (Context.Proof prf) = Context.Proof (PrfData.put x prf);
   619 
   620 fun map f ctxt = put (f (get ctxt)) ctxt;
   621 
   622 end;
   623 
   624 (*hide private interface*)
   625 structure Context: CONTEXT = Context;
   626 
   627 (*fake predeclarations*)
   628 structure Proof = struct type context = Context.proof end;
   629 structure ProofContext =
   630 struct val theory_of = Context.theory_of_proof val init = Context.init_proof end;