src/HOL/Tools/record_package.ML
author berghofe
Mon Jan 29 13:26:04 2001 +0100 (2001-01-29 ago)
changeset 10988 e0016a009c17
parent 10008 61eb9f3aa92a
child 11473 4546d8d39221
permissions -rw-r--r--
Splitting of arguments of product types in induction rules is now less
aggressive.
     1 (*  Title:      HOL/Tools/record_package.ML
     2     ID:         $Id$
     3     Author:     Wolfgang Naraschewski and Markus Wenzel, TU Muenchen
     4     License:    GPL (GNU GENERAL PUBLIC LICENSE)
     5 
     6 Extensible records with structural subtyping in HOL.
     7 *)
     8 
     9 signature BASIC_RECORD_PACKAGE =
    10 sig
    11   val record_simproc: simproc
    12   val record_split_tac: int -> tactic
    13   val record_split_name: string
    14   val record_split_wrapper: string * wrapper
    15 end;
    16 
    17 signature RECORD_PACKAGE =
    18 sig
    19   include BASIC_RECORD_PACKAGE
    20   val quiet_mode: bool ref
    21   val updateN: string
    22   val moreS: sort
    23   val mk_fieldT: (string * typ) * typ -> typ
    24   val dest_fieldT: typ -> (string * typ) * typ
    25   val mk_field: (string * term) * term -> term
    26   val mk_fst: term -> term
    27   val mk_snd: term -> term
    28   val mk_recordT: (string * typ) list * typ -> typ
    29   val dest_recordT: typ -> (string * typ) list * typ
    30   val mk_record: (string * term) list * term -> term
    31   val mk_sel: term -> string -> term
    32   val mk_update: term -> string * term -> term
    33   val print_records: theory -> unit
    34   val add_record: (string list * bstring) -> string option
    35     -> (bstring * string) list -> theory -> theory * {simps: thm list, iffs: thm list}
    36   val add_record_i: (string list * bstring) -> (typ list * string) option
    37     -> (bstring * typ) list -> theory -> theory * {simps: thm list, iffs: thm list}
    38   val setup: (theory -> theory) list
    39 end;
    40 
    41 
    42 structure RecordPackage: RECORD_PACKAGE =
    43 struct
    44 
    45 
    46 (*** utilities ***)
    47 
    48 (* messages *)
    49 
    50 val quiet_mode = ref false;
    51 fun message s = if ! quiet_mode then () else writeln s;
    52 
    53 
    54 (* definitions and equations *)
    55 
    56 infix 0 :== ===;
    57 
    58 val (op :==) = Logic.mk_defpair;
    59 val (op ===) = HOLogic.mk_Trueprop o HOLogic.mk_eq;
    60 
    61 
    62 (* proof by simplification *)
    63 
    64 fun prove_simp sign ss tacs simps =
    65   let
    66     val ss' = Simplifier.addsimps (ss, simps);
    67 
    68     fun prove goal =
    69       Goals.prove_goalw_cterm [] (Thm.cterm_of sign goal)
    70         (K (tacs @ [ALLGOALS (Simplifier.asm_full_simp_tac ss')]))
    71       handle ERROR => error ("The error(s) above occurred while trying to prove "
    72         ^ quote (Sign.string_of_term sign goal));
    73   in prove end;
    74 
    75 
    76 
    77 (*** syntax operations ***)
    78 
    79 (** name components **)
    80 
    81 val recordN = "record";
    82 val moreN = "more";
    83 val schemeN = "_scheme";
    84 val fieldN = "_field";
    85 val raw_fieldN = "_raw_field";
    86 val field_typeN = "_field_type";
    87 val fstN = "_val";
    88 val sndN = "_more";
    89 val updateN = "_update";
    90 val makeN = "make";
    91 val make_schemeN = "make_scheme";
    92 
    93 (*see datatype package*)
    94 val caseN = "_case";
    95 
    96 
    97 
    98 (** generic operations **)
    99 
   100 (* adhoc priming of vars *)
   101 
   102 fun prime (Free (x, T)) = Free (x ^ "'", T)
   103   | prime t = raise TERM ("prime: no free variable", [t]);
   104 
   105 
   106 (* product case *)
   107 
   108 fun fst_fn T U = Abs ("x", T, Abs ("y", U, Bound 1));
   109 fun snd_fn T U = Abs ("x", T, Abs ("y", U, Bound 0));
   110 
   111 fun mk_prod_case name f p =
   112   let
   113     val fT as Type ("fun", [A, Type ("fun", [B, C])]) = fastype_of f;
   114     val pT = fastype_of p;
   115   in Const (suffix caseN name, fT --> pT --> C) $ f $ p end;
   116 
   117 
   118 
   119 (** tuple operations **)
   120 
   121 (* more type class *)
   122 
   123 val moreS = ["Record.more"];
   124 
   125 
   126 (* types *)
   127 
   128 fun mk_fieldT ((c, T), U) = Type (suffix field_typeN c, [T, U]);
   129 
   130 fun dest_fieldT (typ as Type (c_field_type, [T, U])) =
   131       (case try (unsuffix field_typeN) c_field_type of
   132         None => raise TYPE ("dest_fieldT", [typ], [])
   133       | Some c => ((c, T), U))
   134   | dest_fieldT typ = raise TYPE ("dest_fieldT", [typ], []);
   135 
   136 
   137 (* constructors *)
   138 
   139 fun mk_fieldC U (c, T) = (suffix fieldN c, T --> U --> mk_fieldT ((c, T), U));
   140 
   141 fun gen_mk_field sfx ((c, t), u) =
   142   let val T = fastype_of t and U = fastype_of u
   143   in Const (suffix sfx c, [T, U] ---> mk_fieldT ((c, T), U)) $ t $ u end;
   144 
   145 val mk_field = gen_mk_field fieldN;
   146 val mk_raw_field = gen_mk_field raw_fieldN;
   147 
   148 
   149 (* destructors *)
   150 
   151 fun mk_fstC U (c, T) = (suffix fstN c, mk_fieldT ((c, T), U) --> T);
   152 fun mk_sndC U (c, T) = (suffix sndN c, mk_fieldT ((c, T), U) --> U);
   153 
   154 fun dest_field fst_or_snd p =
   155   let
   156     val pT = fastype_of p;
   157     val ((c, T), U) = dest_fieldT pT;
   158     val (destN, destT) = if fst_or_snd then (fstN, T) else (sndN, U);
   159   in Const (suffix destN c, pT --> destT) $ p end;
   160 
   161 val mk_fst = dest_field true;
   162 val mk_snd = dest_field false;
   163 
   164 
   165 
   166 (** record operations **)
   167 
   168 (* types *)
   169 
   170 val mk_recordT = foldr mk_fieldT;
   171 
   172 fun dest_recordT T =
   173   (case try dest_fieldT T of
   174     None => ([], T)
   175   | Some (c_T, U) => apfst (cons c_T) (dest_recordT U));
   176 
   177 fun find_fieldT c rT =
   178   (case assoc (fst (dest_recordT rT), c) of
   179     None => raise TYPE ("find_field: " ^ c, [rT], [])
   180   | Some T => T);
   181 
   182 
   183 (* constructors *)
   184 
   185 val mk_record = foldr mk_field;
   186 
   187 
   188 (* selectors *)
   189 
   190 fun mk_selC rT (c, T) = (c, rT --> T);
   191 
   192 fun mk_sel r c =
   193   let val rT = fastype_of r
   194   in Const (mk_selC rT (c, find_fieldT c rT)) $ r end;
   195 
   196 val mk_moreC = mk_selC;
   197 
   198 fun mk_more r c =
   199   let val rT = fastype_of r
   200   in Const (mk_moreC rT (c, snd (dest_recordT rT))) $ r end;
   201 
   202 
   203 (* updates *)
   204 
   205 fun mk_updateC rT (c, T) = (suffix updateN c, T --> rT --> rT);
   206 
   207 fun mk_update r (c, x) =
   208   let val rT = fastype_of r
   209   in Const (mk_updateC rT (c, find_fieldT c rT)) $ x $ r end;
   210 
   211 val mk_more_updateC = mk_updateC;
   212 
   213 fun mk_more_update r (c, x) =
   214   let val rT = fastype_of r
   215   in Const (mk_more_updateC rT (c, snd (dest_recordT rT))) $ x $ r end;
   216 
   217 
   218 (* make *)
   219 
   220 fun mk_makeC rT (c, Ts) = (c, Ts ---> rT);
   221 
   222 
   223 
   224 (** concrete syntax for records **)
   225 
   226 (* parse translations *)
   227 
   228 fun gen_field_tr mark sfx (t as Const (c, _) $ Free (name, _) $ arg) =
   229       if c = mark then Syntax.const (suffix sfx name) $ arg
   230       else raise TERM ("gen_field_tr: " ^ mark, [t])
   231   | gen_field_tr mark _ t = raise TERM ("gen_field_tr: " ^ mark, [t]);
   232 
   233 fun gen_fields_tr sep mark sfx (tm as Const (c, _) $ t $ u) =
   234       if c = sep then gen_field_tr mark sfx t :: gen_fields_tr sep mark sfx u
   235       else [gen_field_tr mark sfx tm]
   236   | gen_fields_tr _ mark sfx tm = [gen_field_tr mark sfx tm];
   237 
   238 fun gen_record_tr sep mark sfx unit [t] = foldr (op $) (gen_fields_tr sep mark sfx t, unit)
   239   | gen_record_tr _ _ _ _ ts = raise TERM ("gen_record_tr", ts);
   240 
   241 fun gen_record_scheme_tr sep mark sfx [t, more] = foldr (op $) (gen_fields_tr sep mark sfx t, more)
   242   | gen_record_scheme_tr _ _ _ ts = raise TERM ("gen_record_scheme_tr", ts);
   243 
   244 
   245 val record_type_tr = gen_record_tr "_field_types" "_field_type" field_typeN (Syntax.const "unit");
   246 val record_type_scheme_tr = gen_record_scheme_tr "_field_types" "_field_type" field_typeN;
   247 
   248 val record_tr = gen_record_tr "_fields" "_field" fieldN HOLogic.unit;
   249 val record_scheme_tr = gen_record_scheme_tr "_fields" "_field" fieldN;
   250 
   251 fun record_update_tr [t, u] =
   252       foldr (op $) (rev (gen_fields_tr "_updates" "_update" updateN u), t)
   253   | record_update_tr ts = raise TERM ("record_update_tr", ts);
   254 
   255 
   256 val parse_translation =
   257  [("_record_type", record_type_tr),
   258   ("_record_type_scheme", record_type_scheme_tr),
   259   ("_record", record_tr),
   260   ("_record_scheme", record_scheme_tr),
   261   ("_record_update", record_update_tr)];
   262 
   263 
   264 (* print translations *)
   265 
   266 fun gen_fields_tr' mark sfx (tm as Const (name_field, _) $ t $ u) =
   267       (case try (unsuffix sfx) name_field of
   268         Some name =>
   269           apfst (cons (Syntax.const mark $ Syntax.free name $ t)) (gen_fields_tr' mark sfx u)
   270       | None => ([], tm))
   271   | gen_fields_tr' _ _ tm = ([], tm);
   272 
   273 fun gen_record_tr' sep mark sfx is_unit record record_scheme tm =
   274   let
   275     val (ts, u) = gen_fields_tr' mark sfx tm;
   276     val t' = foldr1 (fn (v, w) => Syntax.const sep $ v $ w) ts;
   277   in
   278     if is_unit u then Syntax.const record $ t'
   279     else Syntax.const record_scheme $ t' $ u
   280   end;
   281 
   282 
   283 val record_type_tr' =
   284   gen_record_tr' "_field_types" "_field_type" field_typeN
   285     (fn Const ("unit", _) => true | _ => false) "_record_type" "_record_type_scheme";
   286 
   287 val record_tr' =
   288   gen_record_tr' "_fields" "_field" fieldN HOLogic.is_unit "_record" "_record_scheme";
   289 
   290 fun record_update_tr' tm =
   291   let val (ts, u) = gen_fields_tr' "_update" updateN tm in
   292     Syntax.const "_record_update" $ u $
   293       foldr1 (fn (v, w) => Syntax.const "_updates" $ v $ w) (rev ts)
   294   end;
   295 
   296 
   297 fun gen_field_tr' sfx tr' name =
   298   let val name_sfx = suffix sfx name
   299   in (name_sfx, fn [t, u] => tr' (Syntax.const name_sfx $ t $ u) | _ => raise Match) end;
   300 
   301 fun print_translation names =
   302   map (gen_field_tr' field_typeN record_type_tr') names @
   303   map (gen_field_tr' fieldN record_tr') names @
   304   map (gen_field_tr' updateN record_update_tr') names;
   305 
   306 
   307 
   308 (*** extend theory by record definition ***)
   309 
   310 (** record info **)
   311 
   312 (* type record_info and parent_info *)
   313 
   314 type record_info =
   315  {args: (string * sort) list,
   316   parent: (typ list * string) option,
   317   fields: (string * typ) list,
   318   simps: thm list};
   319 
   320 type parent_info =
   321  {name: string,
   322   fields: (string * typ) list,
   323   simps: thm list};
   324 
   325 
   326 (* data kind 'HOL/records' *)
   327 
   328 type record_data =
   329  {records: record_info Symtab.table,
   330   sel_upd:
   331    {selectors: unit Symtab.table,
   332     updates: string Symtab.table,
   333     simpset: Simplifier.simpset},
   334   field_splits:
   335    {fields: unit Symtab.table,
   336     simpset: Simplifier.simpset}};
   337 
   338 fun make_record_data records sel_upd field_splits =
   339  {records = records, sel_upd = sel_upd, field_splits = field_splits}: record_data;
   340 
   341 structure RecordsArgs =
   342 struct
   343   val name = "HOL/records";
   344   type T = record_data;
   345 
   346   val empty =
   347     make_record_data Symtab.empty
   348       {selectors = Symtab.empty, updates = Symtab.empty, simpset = HOL_basic_ss}
   349       {fields = Symtab.empty, simpset = HOL_basic_ss};
   350 
   351   val copy = I;
   352   val prep_ext = I;
   353   fun merge
   354    ({records = recs1,
   355      sel_upd = {selectors = sels1, updates = upds1, simpset = ss1},
   356      field_splits = {fields = flds1, simpset = fld_ss1}},
   357     {records = recs2,
   358      sel_upd = {selectors = sels2, updates = upds2, simpset = ss2},
   359      field_splits = {fields = flds2, simpset = fld_ss2}}) =
   360     make_record_data
   361       (Symtab.merge (K true) (recs1, recs2))
   362       {selectors = Symtab.merge (K true) (sels1, sels2),
   363         updates = Symtab.merge (K true) (upds1, upds2),
   364         simpset = Simplifier.merge_ss (ss1, ss2)}
   365       {fields = Symtab.merge (K true) (flds1, flds2),
   366         simpset = Simplifier.merge_ss (fld_ss1, fld_ss2)};
   367 
   368   fun print sg ({records = recs, ...}: record_data) =
   369     let
   370       val prt_typ = Sign.pretty_typ sg;
   371       val ext_const = Sign.cond_extern sg Sign.constK;
   372 
   373       fun pretty_parent None = []
   374         | pretty_parent (Some (Ts, name)) =
   375             [Pretty.block [prt_typ (Type (name, Ts)), Pretty.str " +"]];
   376 
   377       fun pretty_field (c, T) = Pretty.block
   378         [Pretty.str (ext_const c), Pretty.str " ::", Pretty.brk 1, Pretty.quote (prt_typ T)];
   379 
   380       fun pretty_record (name, {args, parent, fields, simps = _}) = Pretty.block (Pretty.fbreaks
   381         (Pretty.block [prt_typ (Type (name, map TFree args)), Pretty.str " = "] ::
   382           pretty_parent parent @ map pretty_field fields));
   383     in
   384       map pretty_record (Sign.cond_extern_table sg Sign.typeK recs)
   385       |> Pretty.chunks |> Pretty.writeln
   386     end;
   387 end;
   388 
   389 structure RecordsData = TheoryDataFun(RecordsArgs);
   390 val print_records = RecordsData.print;
   391 
   392 
   393 (* access 'records' *)
   394 
   395 fun get_record thy name = Symtab.lookup (#records (RecordsData.get thy), name);
   396 
   397 fun put_record name info thy =
   398   let
   399     val {records, sel_upd, field_splits} = RecordsData.get thy;
   400     val data = make_record_data (Symtab.update ((name, info), records)) sel_upd field_splits;
   401   in RecordsData.put data thy end;
   402 
   403 
   404 (* access 'sel_upd' *)
   405 
   406 fun get_sel_upd sg = #sel_upd (RecordsData.get_sg sg);
   407 
   408 fun get_selectors sg name = Symtab.lookup (#selectors (get_sel_upd sg), name);
   409 fun get_updates sg name = Symtab.lookup (#updates (get_sel_upd sg), name);
   410 fun get_simpset sg = #simpset (get_sel_upd sg);
   411 
   412 
   413 fun put_sel_upd names simps thy =
   414   let
   415     val sels = map (rpair ()) names;
   416     val upds = map (suffix updateN) names ~~ names;
   417 
   418     val {records, sel_upd = {selectors, updates, simpset}, field_splits} = RecordsData.get thy;
   419     val data = make_record_data records
   420       {selectors = Symtab.extend (selectors, sels),
   421         updates = Symtab.extend (updates, upds),
   422         simpset = Simplifier.addsimps (simpset, simps)}
   423       field_splits;
   424   in RecordsData.put data thy end;
   425 
   426 
   427 (* access 'field_splits' *)
   428 
   429 fun add_record_splits splits thy =
   430   let
   431     val {records, sel_upd, field_splits = {fields, simpset}} = RecordsData.get thy;
   432     val flds = map (rpair () o fst) splits;
   433     val simps = map snd splits;
   434     val data = make_record_data records sel_upd
   435       {fields = Symtab.extend (fields, flds), simpset = Simplifier.addsimps (simpset, simps)};
   436   in RecordsData.put data thy end;
   437 
   438 
   439 (* parent records *)
   440 
   441 fun inst_record thy (types, name) =
   442   let
   443     val sign = Theory.sign_of thy;
   444     fun err msg = error (msg ^ " parent record " ^ quote name);
   445 
   446     val {args, parent, fields, simps} =
   447       (case get_record thy name of Some info => info | None => err "Unknown");
   448     val _ = if length types <> length args then err "Bad number of arguments for" else ();
   449 
   450     fun bad_inst ((x, S), T) =
   451       if Sign.of_sort sign (T, S) then None else Some x
   452     val bads = mapfilter bad_inst (args ~~ types);
   453 
   454     val inst = map fst args ~~ types;
   455     val subst = Term.map_type_tfree (fn (x, _) => the (assoc (inst, x)));
   456   in
   457     if not (null bads) then
   458       err ("Ill-sorted instantiation of " ^ commas bads ^ " in")
   459     else (apsome (apfst (map subst)) parent, map (apsnd subst) fields, simps)
   460   end;
   461 
   462 fun add_parents thy (None, parents) = parents
   463   | add_parents thy (Some (types, name), parents) =
   464       let val (pparent, pfields, psimps) = inst_record thy (types, name)
   465       in add_parents thy (pparent, {name = name, fields = pfields, simps = psimps} :: parents) end;
   466 
   467 
   468 
   469 (** record simproc **)
   470 
   471 local
   472 
   473 val sel_upd_pat = [Thm.read_cterm (Theory.sign_of HOL.thy) ("s (u k r)", HOLogic.termT)];
   474 
   475 fun proc sg _ t =
   476   (case t of (sel as Const (s, _)) $ ((upd as Const (u, _)) $ k $ r) =>
   477     (case get_selectors sg s of Some () =>
   478       (case get_updates sg u of Some u_name =>
   479         let
   480           fun atomize x t = Free (x, fastype_of t);
   481           val k' = atomize "k" k;
   482           val r' = atomize "r" r;
   483           val t' = sel $ (upd $ k' $ r');
   484           val prove = mk_meta_eq o prove_simp sg (get_simpset sg) [] [];
   485         in
   486           if u_name = s then Some (prove (t' === k'))
   487           else Some (prove (t' === sel $ r'))
   488         end
   489       | None => None)
   490     | None => None)
   491   | _ => None);
   492 
   493 in
   494 
   495 val record_simproc = Simplifier.mk_simproc "record_simp" sel_upd_pat proc;
   496 
   497 end;
   498 
   499 
   500 
   501 (** record field splitting **)
   502 
   503 (* tactic *)
   504 
   505 fun record_split_tac i st =
   506   let
   507     val {field_splits = {fields, simpset}, ...} = RecordsData.get_sg (Thm.sign_of_thm st);
   508 
   509     fun is_fieldT (_, Type (a, [_, _])) = is_some (Symtab.lookup (fields, a))
   510       | is_fieldT _ = false;
   511     val params = Logic.strip_params (Library.nth_elem (i - 1, Thm.prems_of st));
   512   in
   513     if exists is_fieldT params then Simplifier.full_simp_tac simpset i st
   514     else Seq.empty
   515   end handle Library.LIST _ => Seq.empty;
   516 
   517 
   518 (* wrapper *)
   519 
   520 val record_split_name = "record_split_tac";
   521 val record_split_wrapper = (record_split_name, fn tac => record_split_tac ORELSE' tac);
   522 
   523 
   524 (* method *)
   525 
   526 val record_split_method =
   527   ("record_split", Method.no_args (Method.SIMPLE_METHOD' HEADGOAL record_split_tac),
   528     "split record fields");
   529 
   530 
   531 
   532 (** internal theory extenders **)
   533 
   534 (* field_type_defs *)
   535 
   536 fun field_type_def ((thy, simps), (name, tname, vs, T, U)) =
   537   let
   538     val full = Sign.full_name (Theory.sign_of thy);
   539     val (thy', {simps = simps', ...}) =
   540       thy
   541       |> setmp DatatypePackage.quiet_mode true
   542         (DatatypePackage.add_datatype_i true [tname]
   543           [(vs, tname, Syntax.NoSyn, [(name, [T, U], Syntax.NoSyn)])]);
   544     val thy'' =
   545       thy'
   546       |> setmp AxClass.quiet_mode true
   547         (AxClass.add_inst_arity_i (full tname, [HOLogic.termS, moreS], moreS) [] [] None);
   548   in (thy'', simps' @ simps) end;
   549 
   550 fun field_type_defs args thy = foldl field_type_def ((thy, []), args);
   551 
   552 
   553 (* field_definitions *)
   554 
   555 fun field_definitions fields names xs zeta moreT more vars named_vars thy =
   556   let
   557     val sign = Theory.sign_of thy;
   558     val base = Sign.base_name;
   559     val full_path = Sign.full_name_path sign;
   560 
   561 
   562     (* prepare declarations and definitions *)
   563 
   564     (*field types*)
   565     fun mk_fieldT_spec c =
   566       (suffix raw_fieldN c, suffix field_typeN c,
   567         ["'a", zeta], TFree ("'a", HOLogic.termS), moreT);
   568     val fieldT_specs = map (mk_fieldT_spec o base) names;
   569 
   570     (*field constructors*)
   571     val field_decls = map (mk_fieldC moreT) fields;
   572 
   573     fun mk_field_spec (c, v) =
   574       mk_field ((c, v), more) :== mk_raw_field ((c, v), more);
   575     val field_specs = map mk_field_spec named_vars;
   576 
   577     (*field destructors*)
   578     val dest_decls = map (mk_fstC moreT) fields @ map (mk_sndC moreT) fields;
   579 
   580     fun mk_dest_spec dest f (c, T) =
   581       let val p = Free ("p", mk_fieldT ((c, T), moreT));
   582       in dest p :== mk_prod_case (suffix field_typeN c) (f T moreT) p end;
   583     val dest_specs =
   584       map (mk_dest_spec mk_fst fst_fn) fields @
   585       map (mk_dest_spec mk_snd snd_fn) fields;
   586 
   587 
   588     (* prepare theorems *)
   589 
   590     (*constructor injects*)
   591     fun mk_inject_prop (c, v) =
   592       HOLogic.mk_eq (mk_field ((c, v), more), mk_field ((c, prime v), prime more)) ===
   593         (HOLogic.conj $ HOLogic.mk_eq (v, prime v) $ HOLogic.mk_eq (more, prime more));
   594     val inject_props = map mk_inject_prop named_vars;
   595 
   596     (*destructor conversions*)
   597     fun mk_dest_prop dest dest' (c, v) =
   598       dest (mk_field ((c, v), more)) === dest' (v, more);
   599     val dest_props =
   600       map (mk_dest_prop mk_fst fst) named_vars @
   601       map (mk_dest_prop mk_snd snd) named_vars;
   602 
   603     (*surjective pairing*)
   604     fun mk_surj_prop (c, T) =
   605       let val p = Free ("p", mk_fieldT ((c, T), moreT));
   606       in p === mk_field ((c, mk_fst p), mk_snd p) end;
   607     val surj_props = map mk_surj_prop fields;
   608 
   609 
   610     (* 1st stage: types_thy *)
   611 
   612     val (types_thy, datatype_simps) =
   613       thy
   614       |> field_type_defs fieldT_specs;
   615 
   616 
   617     (* 2nd stage: defs_thy *)
   618 
   619     val (defs_thy, (field_defs, dest_defs)) =
   620       types_thy
   621        |> (Theory.add_consts_i o map (Syntax.no_syn o apfst base)) (field_decls @ dest_decls)
   622        |> (PureThy.add_defs_i false o map (fn x => (x, [Drule.tag_internal]))) field_specs
   623        |>>> (PureThy.add_defs_i false o map (fn x => (x, [Drule.tag_internal]))) dest_specs;
   624 
   625 
   626     (* 3rd stage: thms_thy *)
   627 
   628     val prove = prove_simp (Theory.sign_of defs_thy) HOL_basic_ss;
   629     val prove_std = prove [] (field_defs @ dest_defs @ datatype_simps);
   630 
   631     val field_injects = map prove_std inject_props;
   632     val dest_convs = map prove_std dest_props;
   633     val surj_pairs = map (prove [DatatypePackage.induct_tac "p" 1]
   634       (map Thm.symmetric field_defs @ dest_convs)) surj_props;
   635 
   636     fun mk_split (x, th) = SplitPairedAll.rule_params x moreN (th RS eq_reflection);
   637     val field_splits = map2 mk_split (xs, surj_pairs);
   638 
   639     val thms_thy =
   640       defs_thy
   641       |> (#1 oo (PureThy.add_thmss o map Thm.no_attributes))
   642         [("field_defs", field_defs),
   643           ("dest_defs", dest_defs),
   644           ("dest_convs", dest_convs),
   645           ("surj_pairs", surj_pairs),
   646           ("field_splits", field_splits)];
   647 
   648   in (thms_thy, dest_convs, field_injects, field_splits) end;
   649 
   650 
   651 (* record_definition *)
   652 
   653 fun record_definition (args, bname) parent (parents: parent_info list) bfields thy =
   654   let
   655     val sign = Theory.sign_of thy;
   656     val full = Sign.full_name_path sign bname;
   657     val base = Sign.base_name;
   658 
   659 
   660     (* basic components *)
   661 
   662     val alphas = map fst args;
   663     val name = Sign.full_name sign bname;       (*not made part of record name space!*)
   664 
   665     val parent_fields = flat (map #fields parents);
   666     val parent_names = map fst parent_fields;
   667     val parent_types = map snd parent_fields;
   668     val parent_len = length parent_fields;
   669     val parent_xs = variantlist (map (base o fst) parent_fields, [moreN, recordN]);
   670     val parent_vars = ListPair.map Free (parent_xs, parent_types);
   671     val parent_named_vars = parent_names ~~ parent_vars;
   672 
   673     val fields = map (apfst full) bfields;
   674     val names = map fst fields;
   675     val types = map snd fields;
   676     val len = length fields;
   677     val xs = variantlist (map fst bfields, moreN :: recordN :: parent_xs);
   678     val vars = ListPair.map Free (xs, types);
   679     val named_vars = names ~~ vars;
   680 
   681     val all_fields = parent_fields @ fields;
   682     val all_names = parent_names @ names;
   683     val all_types = parent_types @ types;
   684     val all_len = parent_len + len;
   685     val all_xs = parent_xs @ xs;
   686     val all_vars = parent_vars @ vars;
   687     val all_named_vars = parent_named_vars @ named_vars;
   688 
   689     val zeta = variant alphas "'z";
   690     val moreT = TFree (zeta, moreS);
   691     val more = Free (moreN, moreT);
   692     val full_moreN = full moreN;
   693     fun more_part t = mk_more t full_moreN;
   694     fun more_part_update t x = mk_more_update t (full_moreN, x);
   695 
   696     val parent_more = funpow parent_len mk_snd;
   697     val idxs = 0 upto (len - 1);
   698 
   699     val rec_schemeT = mk_recordT (all_fields, moreT);
   700     val rec_scheme = mk_record (all_named_vars, more);
   701     val r = Free (recordN, rec_schemeT);
   702     val recT = mk_recordT (all_fields, HOLogic.unitT);
   703 
   704 
   705     (* prepare print translation functions *)
   706 
   707     val field_tr's =
   708       print_translation (distinct (flat (map NameSpace.accesses (full_moreN :: names))));
   709 
   710 
   711     (* prepare declarations *)
   712 
   713     val sel_decls = map (mk_selC rec_schemeT) bfields @
   714       [mk_moreC rec_schemeT (moreN, moreT)];
   715     val update_decls = map (mk_updateC rec_schemeT) bfields @
   716       [mk_more_updateC rec_schemeT (moreN, moreT)];
   717     val make_decls =
   718       [(mk_makeC rec_schemeT (make_schemeN, all_types @ [moreT])),
   719        (mk_makeC recT (makeN, all_types))];
   720 
   721 
   722     (* prepare definitions *)
   723 
   724     (*record (scheme) type abbreviation*)
   725     val recordT_specs =
   726       [(suffix schemeN bname, alphas @ [zeta], rec_schemeT, Syntax.NoSyn),
   727         (bname, alphas, recT, Syntax.NoSyn)];
   728 
   729     (*selectors*)
   730     fun mk_sel_spec (i, c) =
   731       mk_sel r c :== mk_fst (funpow i mk_snd (parent_more r));
   732     val sel_specs =
   733       ListPair.map mk_sel_spec (idxs, names) @
   734         [more_part r :== funpow len mk_snd (parent_more r)];
   735 
   736     (*updates*)
   737     val all_sels = all_names ~~ map (mk_sel r) all_names;
   738     fun mk_upd_spec (i, (c, x)) =
   739       mk_update r (c, x) :==
   740         mk_record (nth_update (c, x) (parent_len + i, all_sels), more_part r)
   741     val update_specs =
   742       ListPair.map mk_upd_spec (idxs, named_vars) @
   743         [more_part_update r more :== mk_record (all_sels, more)];
   744 
   745     (*makes*)
   746     val make_scheme = Const (mk_makeC rec_schemeT (full make_schemeN, all_types @ [moreT]));
   747     val make = Const (mk_makeC recT (full makeN, all_types));
   748     val make_specs =
   749       [list_comb (make_scheme, all_vars) $ more :== rec_scheme,
   750         list_comb (make, all_vars) :== mk_record (all_named_vars, HOLogic.unit)];
   751 
   752 
   753     (* prepare propositions *)
   754 
   755     (*selectors*)
   756     val sel_props =
   757       map (fn (c, x) => mk_sel rec_scheme c === x) named_vars @
   758         [more_part rec_scheme === more];
   759 
   760     (*updates*)
   761     fun mk_upd_prop (i, (c, T)) =
   762       let val x' = Free (variant all_xs (base c ^ "'"), T) in
   763         mk_update rec_scheme (c, x') ===
   764           mk_record (nth_update (c, x') (parent_len + i, all_named_vars), more)
   765       end;
   766     val update_props =
   767       ListPair.map mk_upd_prop (idxs, fields) @
   768         let val more' = Free (variant all_xs (moreN ^ "'"), moreT)
   769         in [more_part_update rec_scheme more' === mk_record (all_named_vars, more')] end;
   770 
   771     (*equality*)
   772     fun mk_sel_eq (t, T) =
   773       let val t' = Term.abstract_over (r, t)
   774       in HOLogic.mk_Trueprop (HOLogic.eq_const T $ Term.incr_boundvars 1 t' $ t') end;
   775     val sel_eqs = map2 mk_sel_eq (map (mk_sel r) all_names @ [more_part r], all_types @ [moreT]);
   776     val equality_prop =
   777       Term.all rec_schemeT $ (Abs ("r", rec_schemeT,
   778         Term.all rec_schemeT $ (Abs ("r'", rec_schemeT,
   779           Logic.list_implies (sel_eqs,
   780             HOLogic.mk_Trueprop (HOLogic.eq_const rec_schemeT $ Bound 1 $ Bound 0))))));
   781 
   782 
   783     (* 1st stage: fields_thy *)
   784 
   785     val (fields_thy, field_simps, field_injects, field_splits) =
   786       thy
   787       |> Theory.add_path bname
   788       |> field_definitions fields names xs zeta moreT more vars named_vars;
   789 
   790     val named_splits = map2 (fn (c, th) => (suffix field_typeN c, th)) (names, field_splits);
   791 
   792 
   793     (* 2nd stage: defs_thy *)
   794 
   795     val (defs_thy, ((sel_defs, update_defs), make_defs)) =
   796       fields_thy
   797       |> add_record_splits named_splits
   798       |> Theory.parent_path
   799       |> Theory.add_tyabbrs_i recordT_specs     (*not made part of record name space!*)
   800       |> Theory.add_path bname
   801       |> Theory.add_trfuns ([], [], field_tr's, [])
   802       |> (Theory.add_consts_i o map Syntax.no_syn)
   803         (sel_decls @ update_decls @ make_decls)
   804       |> (PureThy.add_defs_i false o map (fn x => (x, [Drule.tag_internal]))) sel_specs
   805       |>>> (PureThy.add_defs_i false o map (fn x => (x, [Drule.tag_internal]))) update_specs
   806       |>>> (PureThy.add_defs_i false o map Thm.no_attributes) make_specs;
   807 
   808 
   809     (* 3rd stage: thms_thy *)
   810 
   811     val parent_simps = flat (map #simps parents);
   812     val prove = prove_simp (Theory.sign_of defs_thy) HOL_basic_ss [];
   813     val prove' = prove_simp (Theory.sign_of defs_thy) HOL_ss;
   814 
   815     val sel_convs = map (prove (parent_simps @ sel_defs @ field_simps)) sel_props;
   816     val update_convs = map (prove (parent_simps @ update_defs @ sel_convs)) update_props;
   817     val equality =
   818       prove' [ALLGOALS record_split_tac] (parent_simps @ sel_convs @ field_injects) equality_prop;
   819 
   820     val simps = field_simps @ sel_convs @ update_convs @ make_defs @ [equality];
   821     val iffs = field_injects;
   822 
   823     val thms_thy =
   824       defs_thy
   825       |> (#1 oo (PureThy.add_thmss o map Thm.no_attributes))
   826         [("select_defs", sel_defs),
   827           ("update_defs", update_defs),
   828           ("make_defs", make_defs),
   829           ("select_convs", sel_convs),
   830           ("update_convs", update_convs)]
   831       |> (#1 oo PureThy.add_thms)
   832           [(("equality", equality), [Classical.xtra_intro_global])]
   833       |> (#1 oo PureThy.add_thmss)
   834         [(("simps", simps), [Simplifier.simp_add_global]),
   835          (("iffs", iffs), [iff_add_global])];
   836 
   837 
   838     (* 4th stage: final_thy *)
   839 
   840     val final_thy =
   841       thms_thy
   842       |> put_record name {args = args, parent = parent, fields = fields, simps = simps}
   843       |> put_sel_upd (names @ [full_moreN]) (field_simps @ sel_defs @ update_defs)
   844       |> Theory.parent_path;
   845 
   846   in (final_thy, {simps = simps, iffs = iffs}) end;
   847 
   848 
   849 
   850 (** theory extender interface **)
   851 
   852 (* prepare arguments *)
   853 
   854 (*note: read_raw_typ avoids expanding type abbreviations*)
   855 fun read_raw_parent sign s =
   856   (case Sign.read_raw_typ (sign, K None) s handle TYPE (msg, _, _) => error msg of
   857     Type (name, Ts) => (Ts, name)
   858   | _ => error ("Bad parent record specification: " ^ quote s));
   859 
   860 fun read_typ sign (env, s) =
   861   let
   862     fun def_sort (x, ~1) = assoc (env, x)
   863       | def_sort _ = None;
   864     val T = Type.no_tvars (Sign.read_typ (sign, def_sort) s) handle TYPE (msg, _, _) => error msg;
   865   in (Term.add_typ_tfrees (T, env), T) end;
   866 
   867 fun cert_typ sign (env, raw_T) =
   868   let val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle TYPE (msg, _, _) => error msg
   869   in (Term.add_typ_tfrees (T, env), T) end;
   870 
   871 
   872 (* add_record *)
   873 
   874 (*we do all preparations and error checks here, deferring the real
   875   work to record_definition*)
   876 
   877 fun gen_add_record prep_typ prep_raw_parent (params, bname) raw_parent raw_fields thy =
   878   let
   879     val _ = Theory.requires thy "Record" "record definitions";
   880     val sign = Theory.sign_of thy;
   881     val _ = message ("Defining record " ^ quote bname ^ " ...");
   882 
   883 
   884     (* parents *)
   885 
   886     fun prep_inst T = snd (cert_typ sign ([], T));
   887 
   888     val parent = apsome (apfst (map prep_inst) o prep_raw_parent sign) raw_parent
   889       handle ERROR => error ("The error(s) above in parent record specification");
   890     val parents = add_parents thy (parent, []);
   891 
   892     val init_env =
   893       (case parent of
   894         None => []
   895       | Some (types, _) => foldr Term.add_typ_tfrees (types, []));
   896 
   897 
   898     (* fields *)
   899 
   900     fun prep_field (env, (c, raw_T)) =
   901       let val (env', T) = prep_typ sign (env, raw_T) handle ERROR =>
   902         error ("The error(s) above occured in field " ^ quote c)
   903       in (env', (c, T)) end;
   904 
   905     val (envir, bfields) = foldl_map prep_field (init_env, raw_fields);
   906     val envir_names = map fst envir;
   907 
   908 
   909     (* args *)
   910 
   911     val defaultS = Sign.defaultS sign;
   912     val args = map (fn x => (x, if_none (assoc (envir, x)) defaultS)) params;
   913 
   914 
   915     (* errors *)
   916 
   917     val name = Sign.full_name sign bname;
   918     val err_dup_record =
   919       if is_none (get_record thy name) then []
   920       else ["Duplicate definition of record " ^ quote name];
   921 
   922     val err_dup_parms =
   923       (case duplicates params of
   924         [] => []
   925       | dups => ["Duplicate parameter(s) " ^ commas dups]);
   926 
   927     val err_extra_frees =
   928       (case gen_rems (op =) (envir_names, params) of
   929         [] => []
   930       | extras => ["Extra free type variable(s) " ^ commas extras]);
   931 
   932     val err_no_fields = if null bfields then ["No fields present"] else [];
   933 
   934     val err_dup_fields =
   935       (case duplicates (map fst bfields) of
   936         [] => []
   937       | dups => ["Duplicate field(s) " ^ commas_quote dups]);
   938 
   939     val err_bad_fields =
   940       if forall (not_equal moreN o fst) bfields then []
   941       else ["Illegal field name " ^ quote moreN];
   942 
   943     val err_dup_sorts =
   944       (case duplicates envir_names of
   945         [] => []
   946       | dups => ["Inconsistent sort constraints for " ^ commas dups]);
   947 
   948     val errs =
   949       err_dup_record @ err_dup_parms @ err_extra_frees @ err_no_fields @
   950       err_dup_fields @ err_bad_fields @ err_dup_sorts;
   951   in
   952     if null errs then () else error (cat_lines errs);
   953     thy |> record_definition (args, bname) parent parents bfields
   954   end
   955   handle ERROR => error ("Failed to define record " ^ quote bname);
   956 
   957 val add_record = gen_add_record read_typ read_raw_parent;
   958 val add_record_i = gen_add_record cert_typ (K I);
   959 
   960 
   961 
   962 (** package setup **)
   963 
   964 (* setup theory *)
   965 
   966 val setup =
   967  [RecordsData.init,
   968   Theory.add_trfuns ([], parse_translation, [], []),
   969   Method.add_methods [record_split_method],
   970   Simplifier.change_simpset_of Simplifier.addsimprocs [record_simproc]];
   971 
   972 
   973 (* outer syntax *)
   974 
   975 local structure P = OuterParse and K = OuterSyntax.Keyword in
   976 
   977 val record_decl =
   978   P.type_args -- P.name -- (P.$$$ "=" |-- Scan.option (P.typ --| P.$$$ "+")
   979     -- Scan.repeat1 (P.name -- (P.$$$ "::" |-- P.typ) --| P.marg_comment));
   980 
   981 val recordP =
   982   OuterSyntax.command "record" "define extensible record" K.thy_decl
   983     (record_decl >> (fn (x, (y, z)) => Toplevel.theory (#1 o add_record x y z)));
   984 
   985 val _ = OuterSyntax.add_parsers [recordP];
   986 
   987 end;
   988 
   989 
   990 end;
   991 
   992 structure BasicRecordPackage: BASIC_RECORD_PACKAGE = RecordPackage;
   993 open BasicRecordPackage;