src/Pure/context.ML
author wenzelm
Wed May 17 22:34:47 2006 +0200 (2006-05-17)
changeset 19678 d1a15431de34
parent 19482 9f11af8f7ef9
child 19815 4820c3d52548
permissions -rw-r--r--
added mapping;
     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 (Theory ({id, ids, iids, ...}, _, _, _)) =
   232   name = #2 id orelse
   233   Inttab.exists (equal name o #2) ids orelse
   234   Inttab.exists (equal name o #2) iids;
   235 
   236 fun names_of (Theory ({id, ids, iids, ...}, _, _, _)) =
   237   rev (#2 id :: Inttab.fold (cons o #2) iids (Inttab.fold (cons o #2) ids []));
   238 
   239 fun pretty_thy thy =
   240   Pretty.str_list "{" "}" (names_of thy @ (if is_stale thy then ["!"] else []));
   241 
   242 val string_of_thy = Pretty.string_of o pretty_thy;
   243 val pprint_thy = Pretty.pprint o pretty_thy;
   244 
   245 fun pretty_abbrev_thy thy =
   246   let
   247     val names = names_of thy;
   248     val n = length names;
   249     val abbrev = if n > 5 then "..." :: List.drop (names, n - 5) else names;
   250   in Pretty.str_list "{" "}" abbrev end;
   251 
   252 val str_of_thy = Pretty.str_of o pretty_abbrev_thy;
   253 
   254 
   255 (* consistency *)    (*exception TERM*)
   256 
   257 fun check_thy thy =
   258   if is_stale thy then
   259     raise TERM ("Stale theory encountered:\n" ^ string_of_thy thy, [])
   260   else thy;
   261 
   262 fun check_ins id ids =
   263   if draft_id id orelse Inttab.defined ids (#1 id) then ids
   264   else if Inttab.exists (equal (#2 id) o #2) ids then
   265     raise TERM ("Different versions of theory component " ^ quote (#2 id), [])
   266   else Inttab.update id ids;
   267 
   268 fun check_insert intermediate id (ids, iids) =
   269   let val ids' = check_ins id ids and iids' = check_ins id iids
   270   in if intermediate then (ids, iids') else (ids', iids) end;
   271 
   272 fun check_merge
   273     (Theory ({id = id1, ids = ids1, iids = iids1, ...}, _, _, history1))
   274     (Theory ({id = id2, ids = ids2, iids = iids2, ...}, _, _, history2)) =
   275   (Inttab.fold check_ins ids2 ids1, Inttab.fold check_ins iids2 iids1)
   276   |> check_insert (#version history1 > 0) id1
   277   |> check_insert (#version history2 > 0) id2;
   278 
   279 
   280 (* equality and inclusion *)
   281 
   282 val eq_thy = eq_id o pairself (#id o identity_of o check_thy);
   283 
   284 fun proper_subthy
   285     (Theory ({id = (i, _), ...}, _, _, _), Theory ({ids, iids, ...}, _, _, _)) =
   286   Inttab.defined ids i orelse Inttab.defined iids i;
   287 
   288 fun subthy thys = eq_thy thys orelse proper_subthy thys;
   289 
   290 fun joinable (thy1, thy2) = subthy (thy1, thy2) orelse subthy (thy2, thy1);
   291 
   292 
   293 (* theory references *)
   294 
   295 (*theory_ref provides a safe way to store dynamic references to a
   296   theory in external data structures -- a plain theory value would
   297   become stale as the self reference moves on*)
   298 
   299 datatype theory_ref = TheoryRef of theory ref;
   300 
   301 val self_ref = TheoryRef o the_self o check_thy;
   302 fun deref (TheoryRef (ref thy)) = thy;
   303 
   304 
   305 (* trivial merge *)    (*exception TERM*)
   306 
   307 fun merge (thy1, thy2) =
   308   if eq_thy (thy1, thy2) then thy1
   309   else if proper_subthy (thy2, thy1) then thy1
   310   else if proper_subthy (thy1, thy2) then thy2
   311   else (check_merge thy1 thy2;
   312     raise TERM (cat_lines ["Attempt to perform non-trivial merge of theories:",
   313       str_of_thy thy1, str_of_thy thy2], []));
   314 
   315 fun merge_refs (ref1, ref2) =
   316   if ref1 = ref2 then ref1
   317   else self_ref (merge (deref ref1, deref ref2));
   318 
   319 
   320 
   321 (** build theories **)
   322 
   323 (* primitives *)
   324 
   325 fun create_thy name self id ids iids data ancestry history =
   326   let
   327     val {version, name = _, intermediates = _} = history;
   328     val intermediate = version > 0;
   329     val (ids', iids') = check_insert intermediate id (ids, iids);
   330     val id' = (serial (), name);
   331     val _ = check_insert intermediate id' (ids', iids');
   332     val identity' = make_identity self id' ids' iids';
   333   in vitalize (Theory (identity', data, ancestry, history)) end;
   334 
   335 fun change_thy name f (thy as Theory ({self, id, ids, iids}, data, ancestry, history)) =
   336   let
   337     val _ = check_thy thy;
   338     val (self', data', ancestry') =
   339       if is_draft thy then (self, data, ancestry)    (*destructive change!*)
   340       else if #version history > 0
   341       then (NONE, map_theory_data copy_data data, ancestry)
   342       else (NONE, map_theory_data extend_data data,
   343         make_ancestry [thy] (thy :: #ancestors ancestry));
   344     val data'' = f data';
   345   in create_thy name self' id ids iids data'' ancestry' history end;
   346 
   347 fun name_thy name = change_thy name I;
   348 val modify_thy = change_thy draftN;
   349 val extend_thy = modify_thy I;
   350 
   351 fun copy_thy (thy as Theory ({id, ids, iids, ...}, data, ancestry, history)) =
   352   (check_thy thy;
   353     create_thy draftN NONE id ids iids (map_theory_data copy_data data) ancestry history);
   354 
   355 val pre_pure_thy = create_thy draftN NONE (serial (), draftN) Inttab.empty Inttab.empty
   356   (make_data Datatab.empty Datatab.empty) (make_ancestry [] []) (make_history ProtoPureN 0 []);
   357 
   358 
   359 (* named theory nodes *)
   360 
   361 fun merge_thys pp (thy1, thy2) =
   362   if exists_name CPureN thy1 <> exists_name CPureN thy2 then
   363     error "Cannot merge Pure and CPure developments"
   364   else
   365     let
   366       val (ids, iids) = check_merge thy1 thy2;
   367       val data1 = data_of thy1 and data2 = data_of thy2;
   368       val data = make_data
   369         (merge_data (pp thy1) (#theory data1, #theory data2))
   370         (Datatab.merge (K true) (#proof data1, #proof data2));
   371       val ancestry = make_ancestry [] [];
   372       val history = make_history "" 0 [];
   373     in create_thy draftN NONE (serial (), draftN) ids iids data ancestry history end;
   374 
   375 fun maximal_thys thys =
   376   thys |> filter (fn thy => not (exists (fn thy' => proper_subthy (thy, thy')) thys));
   377 
   378 fun begin_thy pp name imports =
   379   if name = draftN then error ("Illegal theory name: " ^ quote draftN)
   380   else
   381     let
   382       val parents =
   383         maximal_thys (distinct eq_thy (map check_thy imports));
   384       val ancestors = distinct eq_thy (parents @ maps ancestors_of parents);
   385       val Theory ({id, ids, iids, ...}, data, _, _) =
   386         (case parents of
   387           [] => error "No parent theories"
   388         | [thy] => extend_thy thy
   389         | thy :: thys => Library.foldl (merge_thys pp) (thy, thys));
   390       val ancestry = make_ancestry parents ancestors;
   391       val history = make_history name 0 [];
   392     in create_thy draftN NONE id ids iids data ancestry history end;
   393 
   394 
   395 (* undoable checkpoints *)
   396 
   397 fun checkpoint_thy thy =
   398   if not (is_draft thy) then thy
   399   else
   400     let
   401       val {name, version, intermediates} = history_of thy;
   402       val thy' as Theory (identity', data', ancestry', _) =
   403         name_thy (name ^ ":" ^ string_of_int version) thy;
   404       val history' = make_history name (version + 1) (thy' :: intermediates);
   405     in vitalize (Theory (identity', data', ancestry', history')) end;
   406 
   407 fun finish_thy thy =
   408   let
   409     val {name, version, intermediates} = history_of thy;
   410     val rs = map (the_self o check_thy) intermediates;
   411     val thy' as Theory ({self, id, ids, ...}, data', ancestry', _) = name_thy name thy;
   412     val identity' = make_identity self id ids Inttab.empty;
   413     val history' = make_history name 0 [];
   414     val thy'' = vitalize (Theory (identity', data', ancestry', history'));
   415     val _ = List.app (fn r => r := thy'') rs;
   416   in thy'' end;
   417 
   418 
   419 (* theory data *)
   420 
   421 fun dest_data name_of tab =
   422   map name_of (Datatab.keys tab)
   423   |> map (rpair ()) |> Symtab.make_list |> Symtab.dest
   424   |> map (apsnd length)
   425   |> map (fn (name, 1) => name | (name, n) => name ^ enclose "[" "]" (string_of_int n));
   426 
   427 val theory_data_of = dest_data invoke_name o #theory o data_of;
   428 
   429 structure TheoryData =
   430 struct
   431 
   432 val declare = declare_theory_data;
   433 
   434 fun get k dest thy =
   435   (case Datatab.lookup (#theory (data_of thy)) k of
   436     SOME x => (dest x handle Match =>
   437       error ("Failed to access theory data " ^ quote (invoke_name k)))
   438   | NONE => error ("Uninitialized theory data " ^ quote (invoke_name k)));
   439 
   440 fun put k mk x = modify_thy (map_theory_data (Datatab.update (k, mk x)));
   441 fun init k = put k I (invoke_empty k);
   442 
   443 end;
   444 
   445 
   446 
   447 (*** ML theory context ***)
   448 
   449 local
   450   val current_theory = ref (NONE: theory option);
   451 in
   452   fun get_context () = ! current_theory;
   453   fun set_context opt_thy = current_theory := opt_thy;
   454   fun setmp opt_thy f x = Library.setmp current_theory opt_thy f x;
   455 end;
   456 
   457 fun the_context () =
   458   (case get_context () of
   459     SOME thy => thy
   460   | _ => error "Unknown theory context");
   461 
   462 fun context thy = set_context (SOME thy);
   463 fun reset_context () = set_context NONE;
   464 
   465 fun pass opt_thy f x =
   466   setmp opt_thy (fn x => let val y = f x in (y, get_context ()) end) x;
   467 
   468 fun pass_theory thy f x =
   469   (case pass (SOME thy) f x of
   470     (y, SOME thy') => (y, thy')
   471   | (_, NONE) => error "Lost theory context in ML");
   472 
   473 fun save f x = setmp (get_context ()) f x;
   474 
   475 
   476 (* map context *)
   477 
   478 nonfix >>;
   479 fun >> f = set_context (SOME (f (the_context ())));
   480 
   481 
   482 (* use ML text *)
   483 
   484 val ml_output = (writeln, Output.error_msg);
   485 
   486 fun use_output verbose txt =
   487   Output.ML_errors (use_text ml_output verbose) (Symbol.escape txt);
   488 
   489 fun use_mltext txt verbose opt_thy = setmp opt_thy (fn () => use_output verbose txt) ();
   490 fun use_mltext_theory txt verbose thy = #2 (pass_theory thy (use_output verbose) txt);
   491 
   492 fun use_context txt = use_mltext_theory ("Context.>> (" ^ txt ^ ");") false;
   493 
   494 fun use_let bind body txt =
   495   use_context ("let " ^ bind ^ " = " ^ txt ^ " in\n" ^ body ^ " end");
   496 
   497 
   498 (* delayed theory setup *)
   499 
   500 local
   501   val setup_fn = ref (I: theory -> theory);
   502 in
   503   fun add_setup f = setup_fn := (! setup_fn #> f);
   504   fun setup () = let val f = ! setup_fn in setup_fn := I; f end;
   505 end;
   506 
   507 
   508 
   509 (*** proof context ***)
   510 
   511 (* datatype proof *)
   512 
   513 datatype proof = Proof of theory_ref * Object.T Datatab.table;
   514 
   515 fun theory_of_proof (Proof (thy_ref, _)) = deref thy_ref;
   516 fun data_of_proof (Proof (_, data)) = data;
   517 fun map_prf f (Proof (thy_ref, data)) = Proof (thy_ref, f data);
   518 
   519 fun transfer_proof thy' (prf as Proof (thy_ref, data)) =
   520   if not (subthy (deref thy_ref, thy')) then
   521     error "transfer proof context: no a super theory"
   522   else Proof (self_ref thy', data);
   523 
   524 
   525 (* proof data kinds *)
   526 
   527 local
   528 
   529 type kind =
   530  {name: string,
   531   init: theory -> Object.T};
   532 
   533 val kinds = ref (Datatab.empty: kind Datatab.table);
   534 
   535 fun invoke meth_name meth_fn k =
   536   (case Datatab.lookup (! kinds) k of
   537     SOME kind => meth_fn kind |> transform_failure (fn exn =>
   538       EXCEPTION (exn, "Proof data method " ^ #name kind ^ "." ^ meth_name ^ " failed"))
   539   | NONE => sys_error ("Invalid proof data identifier " ^ string_of_int k));
   540 
   541 fun invoke_name k = invoke "name" (K o #name) k ();
   542 val invoke_init   = invoke "init" #init;
   543 
   544 in
   545 
   546 val proof_data_of = dest_data invoke_name o #proof o data_of;
   547 
   548 fun init_proof thy =
   549   Proof (self_ref thy, Datatab.map' (fn k => fn _ => invoke_init k thy) (#proof (data_of thy)));
   550 
   551 structure ProofData =
   552 struct
   553 
   554 fun declare name init =
   555   let
   556     val k = serial ();
   557     val kind = {name = name, init = init};
   558     val _ = conditional (Datatab.exists (equal name o #name o #2) (! kinds)) (fn () =>
   559       warning ("Duplicate declaration of proof data " ^ quote name));
   560     val _ = change kinds (Datatab.update (k, kind));
   561   in k end;
   562 
   563 fun init k = modify_thy (map_proof_data (Datatab.update (k, ())));
   564 
   565 fun get k dest prf =
   566   (case Datatab.lookup (data_of_proof prf) k of
   567     SOME x => (dest x handle Match =>
   568       error ("Failed to access proof data " ^ quote (invoke_name k)))
   569   | NONE => error ("Uninitialized proof data " ^ quote (invoke_name k)));
   570 
   571 fun put k mk x = map_prf (Datatab.update (k, mk x));
   572 
   573 end;
   574 
   575 end;
   576 
   577 
   578 
   579 (*** generic context ***)
   580 
   581 datatype generic = Theory of theory | Proof of proof;
   582 
   583 fun cases f _ (Theory thy) = f thy
   584   | cases _ g (Proof prf) = g prf;
   585 
   586 fun mapping f g = cases (Theory o f) (Proof o g);
   587 
   588 val the_theory = cases I (fn _ => raise Fail "Ill-typed context: theory expected");
   589 val the_proof = cases (fn _ => raise Fail "Ill-typed context: proof expected") I;
   590 
   591 fun map_theory f = Theory o f o the_theory;
   592 fun map_proof f = Proof o f o the_proof;
   593 
   594 fun theory_map f = the_theory o f o Theory;
   595 fun proof_map f = the_proof o f o Proof;
   596 
   597 val theory_of = cases I theory_of_proof;
   598 val proof_of = cases init_proof I;
   599 
   600 end;
   601 
   602 structure BasicContext: BASIC_CONTEXT = Context;
   603 open BasicContext;
   604 
   605 
   606 
   607 (*** type-safe interfaces for data declarations ***)
   608 
   609 (** theory data **)
   610 
   611 signature THEORY_DATA_ARGS =
   612 sig
   613   val name: string
   614   type T
   615   val empty: T
   616   val copy: T -> T
   617   val extend: T -> T
   618   val merge: Pretty.pp -> T * T -> T
   619   val print: theory -> T -> unit
   620 end;
   621 
   622 signature THEORY_DATA =
   623 sig
   624   type T
   625   val init: theory -> theory
   626   val print: theory -> unit
   627   val get: theory -> T
   628   val get_sg: theory -> T    (*obsolete*)
   629   val put: T -> theory -> theory
   630   val map: (T -> T) -> theory -> theory
   631 end;
   632 
   633 functor TheoryDataFun(Data: THEORY_DATA_ARGS): THEORY_DATA =
   634 struct
   635 
   636 structure TheoryData = Context.TheoryData;
   637 
   638 type T = Data.T;
   639 exception Data of T;
   640 
   641 val kind = TheoryData.declare Data.name
   642   (Data Data.empty)
   643   (fn Data x => Data (Data.copy x))
   644   (fn Data x => Data (Data.extend x))
   645   (fn pp => fn (Data x1, Data x2) => Data (Data.merge pp (x1, x2)));
   646 
   647 val init = TheoryData.init kind;
   648 val get = TheoryData.get kind (fn Data x => x);
   649 val get_sg = get;
   650 fun print thy = Data.print thy (get thy);
   651 val put = TheoryData.put kind Data;
   652 fun map f thy = put (f (get thy)) thy;
   653 
   654 end;
   655 
   656 
   657 
   658 (** proof data **)
   659 
   660 signature PROOF_DATA_ARGS =
   661 sig
   662   val name: string
   663   type T
   664   val init: theory -> T
   665   val print: Context.proof -> T -> unit
   666 end;
   667 
   668 signature PROOF_DATA =
   669 sig
   670   type T
   671   val init: theory -> theory
   672   val print: Context.proof -> unit
   673   val get: Context.proof -> T
   674   val put: T -> Context.proof -> Context.proof
   675   val map: (T -> T) -> Context.proof -> Context.proof
   676 end;
   677 
   678 functor ProofDataFun(Data: PROOF_DATA_ARGS): PROOF_DATA =
   679 struct
   680 
   681 structure ProofData = Context.ProofData;
   682 
   683 type T = Data.T;
   684 exception Data of T;
   685 
   686 val kind = ProofData.declare Data.name (Data o Data.init);
   687 
   688 val init = ProofData.init kind;
   689 val get = ProofData.get kind (fn Data x => x);
   690 fun print prf = Data.print prf (get prf);
   691 val put = ProofData.put kind Data;
   692 fun map f prf = put (f (get prf)) prf;
   693 
   694 end;
   695 
   696 
   697 
   698 (** generic data **)
   699 
   700 signature GENERIC_DATA_ARGS =
   701 sig
   702   val name: string
   703   type T
   704   val empty: T
   705   val extend: T -> T
   706   val merge: Pretty.pp -> T * T -> T
   707   val print: Context.generic -> T -> unit
   708 end;
   709 
   710 signature GENERIC_DATA =
   711 sig
   712   type T
   713   val init: theory -> theory
   714   val get: Context.generic -> T
   715   val put: T -> Context.generic -> Context.generic
   716   val map: (T -> T) -> Context.generic -> Context.generic
   717   val print: Context.generic -> unit
   718 end;
   719 
   720 functor GenericDataFun(Data: GENERIC_DATA_ARGS): GENERIC_DATA =
   721 struct
   722 
   723 structure ThyData = TheoryDataFun(open Data val copy = I fun print _ _ = ());
   724 structure PrfData =
   725   ProofDataFun(val name = Data.name type T = Data.T val init = ThyData.get fun print _ _ = ());
   726 
   727 type T = Data.T;
   728 val init = ThyData.init #> PrfData.init;
   729 
   730 fun get (Context.Theory thy) = ThyData.get thy
   731   | get (Context.Proof prf) = PrfData.get prf;
   732 
   733 fun put x (Context.Theory thy) = Context.Theory (ThyData.put x thy)
   734   | put x (Context.Proof prf) = Context.Proof (PrfData.put x prf);
   735 
   736 fun map f ctxt = put (f (get ctxt)) ctxt;
   737 
   738 fun print ctxt = Data.print ctxt (get ctxt);
   739 
   740 end;
   741 
   742 
   743 (*hide private interface*)
   744 structure Context: CONTEXT = Context;