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