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