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