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