src/HOL/Tools/record.ML
changeset 31723 f5cafe803b55
parent 31136 85d04515abb3
child 31902 862ae16a799d
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/Tools/record.ML	Fri Jun 19 17:23:21 2009 +0200
     1.3 @@ -0,0 +1,2325 @@
     1.4 +(*  Title:      HOL/Tools/record.ML
     1.5 +    Author:     Wolfgang Naraschewski, Norbert Schirmer and Markus Wenzel, TU Muenchen
     1.6 +
     1.7 +Extensible records with structural subtyping in HOL.
     1.8 +*)
     1.9 +
    1.10 +
    1.11 +signature BASIC_RECORD =
    1.12 +sig
    1.13 +  val record_simproc: simproc
    1.14 +  val record_eq_simproc: simproc
    1.15 +  val record_upd_simproc: simproc
    1.16 +  val record_split_simproc: (term -> int) -> simproc
    1.17 +  val record_ex_sel_eq_simproc: simproc
    1.18 +  val record_split_tac: int -> tactic
    1.19 +  val record_split_simp_tac: thm list -> (term -> int) -> int -> tactic
    1.20 +  val record_split_name: string
    1.21 +  val record_split_wrapper: string * wrapper
    1.22 +  val print_record_type_abbr: bool ref
    1.23 +  val print_record_type_as_fields: bool ref
    1.24 +end;
    1.25 +
    1.26 +signature RECORD =
    1.27 +sig
    1.28 +  include BASIC_RECORD
    1.29 +  val timing: bool ref
    1.30 +  val record_quick_and_dirty_sensitive: bool ref
    1.31 +  val updateN: string
    1.32 +  val updN: string
    1.33 +  val ext_typeN: string
    1.34 +  val extN: string
    1.35 +  val makeN: string
    1.36 +  val moreN: string
    1.37 +  val ext_dest: string
    1.38 +
    1.39 +  val last_extT: typ -> (string * typ list) option
    1.40 +  val dest_recTs : typ -> (string * typ list) list
    1.41 +  val get_extT_fields:  theory -> typ -> (string * typ) list * (string * typ)
    1.42 +  val get_recT_fields:  theory -> typ -> (string * typ) list * (string * typ)
    1.43 +  val get_parent: theory -> string -> (typ list * string) option
    1.44 +  val get_extension: theory -> string -> (string * typ list) option
    1.45 +  val get_extinjects: theory -> thm list
    1.46 +  val get_simpset: theory -> simpset
    1.47 +  val print_records: theory -> unit
    1.48 +  val read_typ: Proof.context -> string -> (string * sort) list -> typ * (string * sort) list
    1.49 +  val cert_typ: Proof.context -> typ -> (string * sort) list -> typ * (string * sort) list
    1.50 +  val add_record: bool -> string list * string -> string option -> (string * string * mixfix) list
    1.51 +    -> theory -> theory
    1.52 +  val add_record_i: bool -> string list * string -> (typ list * string) option
    1.53 +    -> (string * typ * mixfix) list -> theory -> theory
    1.54 +  val setup: theory -> theory
    1.55 +end;
    1.56 +
    1.57 +
    1.58 +structure Record: RECORD =
    1.59 +struct
    1.60 +
    1.61 +val eq_reflection = thm "eq_reflection";
    1.62 +val rec_UNIV_I = thm "rec_UNIV_I";
    1.63 +val rec_True_simp = thm "rec_True_simp";
    1.64 +val Pair_eq = thm "Product_Type.prod.inject";
    1.65 +val atomize_all = thm "HOL.atomize_all";
    1.66 +val atomize_imp = thm "HOL.atomize_imp";
    1.67 +val meta_allE = thm "Pure.meta_allE";
    1.68 +val prop_subst = thm "prop_subst";
    1.69 +val Pair_sel_convs = [fst_conv,snd_conv];
    1.70 +val K_record_comp = @{thm "K_record_comp"};
    1.71 +val K_comp_convs = [@{thm o_apply}, K_record_comp]
    1.72 +
    1.73 +(** name components **)
    1.74 +
    1.75 +val rN = "r";
    1.76 +val wN = "w";
    1.77 +val moreN = "more";
    1.78 +val schemeN = "_scheme";
    1.79 +val ext_typeN = "_ext_type";
    1.80 +val extN ="_ext";
    1.81 +val casesN = "_cases";
    1.82 +val ext_dest = "_sel";
    1.83 +val updateN = "_update";
    1.84 +val updN = "_upd";
    1.85 +val makeN = "make";
    1.86 +val fields_selN = "fields";
    1.87 +val extendN = "extend";
    1.88 +val truncateN = "truncate";
    1.89 +
    1.90 +(*see typedef.ML*)
    1.91 +val RepN = "Rep_";
    1.92 +val AbsN = "Abs_";
    1.93 +
    1.94 +(*** utilities ***)
    1.95 +
    1.96 +fun but_last xs = fst (split_last xs);
    1.97 +
    1.98 +fun varifyT midx =
    1.99 +  let fun varify (a, S) = TVar ((a, midx + 1), S);
   1.100 +  in map_type_tfree varify end;
   1.101 +
   1.102 +fun domain_type' T =
   1.103 +    domain_type T handle Match => T;
   1.104 +
   1.105 +fun range_type' T =
   1.106 +    range_type T handle Match => T;
   1.107 +
   1.108 +(* messages *)
   1.109 +
   1.110 +fun trace_thm str thm =
   1.111 +    tracing (str ^ (Pretty.string_of (Display.pretty_thm thm)));
   1.112 +
   1.113 +fun trace_thms str thms =
   1.114 +    (tracing str; map (trace_thm "") thms);
   1.115 +
   1.116 +fun trace_term str t =
   1.117 +    tracing (str ^ Syntax.string_of_term_global Pure.thy t);
   1.118 +
   1.119 +(* timing *)
   1.120 +
   1.121 +val timing = ref false;
   1.122 +fun timeit_msg s x = if !timing then (warning s; timeit x) else x ();
   1.123 +fun timing_msg s = if !timing then warning s else ();
   1.124 +
   1.125 +(* syntax *)
   1.126 +
   1.127 +fun prune n xs = Library.drop (n, xs);
   1.128 +fun prefix_base s = Long_Name.map_base_name (fn bname => s ^ bname);
   1.129 +
   1.130 +val Trueprop = HOLogic.mk_Trueprop;
   1.131 +fun All xs t = Term.list_all_free (xs, t);
   1.132 +
   1.133 +infix 9 $$;
   1.134 +infix 0 :== ===;
   1.135 +infixr 0 ==>;
   1.136 +
   1.137 +val (op $$) = Term.list_comb;
   1.138 +val (op :==) = PrimitiveDefs.mk_defpair;
   1.139 +val (op ===) = Trueprop o HOLogic.mk_eq;
   1.140 +val (op ==>) = Logic.mk_implies;
   1.141 +
   1.142 +(* morphisms *)
   1.143 +
   1.144 +fun mk_RepN name = suffix ext_typeN (prefix_base RepN name);
   1.145 +fun mk_AbsN name = suffix ext_typeN (prefix_base AbsN name);
   1.146 +
   1.147 +fun mk_Rep name repT absT  =
   1.148 +  Const (suffix ext_typeN (prefix_base RepN name),absT --> repT);
   1.149 +
   1.150 +fun mk_Abs name repT absT =
   1.151 +  Const (mk_AbsN name,repT --> absT);
   1.152 +
   1.153 +(* constructor *)
   1.154 +
   1.155 +fun mk_extC (name,T) Ts  = (suffix extN name, Ts ---> T);
   1.156 +
   1.157 +fun mk_ext (name,T) ts =
   1.158 +  let val Ts = map fastype_of ts
   1.159 +  in list_comb (Const (mk_extC (name,T) Ts),ts) end;
   1.160 +
   1.161 +(* cases *)
   1.162 +
   1.163 +fun mk_casesC (name,T,vT) Ts = (suffix casesN name, (Ts ---> vT) --> T --> vT)
   1.164 +
   1.165 +fun mk_cases (name,T,vT) f =
   1.166 +  let val Ts = binder_types (fastype_of f)
   1.167 +  in Const (mk_casesC (name,T,vT) Ts) $ f end;
   1.168 +
   1.169 +(* selector *)
   1.170 +
   1.171 +fun mk_selC sT (c,T) = (c,sT --> T);
   1.172 +
   1.173 +fun mk_sel s (c,T) =
   1.174 +  let val sT = fastype_of s
   1.175 +  in Const (mk_selC sT (c,T)) $ s end;
   1.176 +
   1.177 +(* updates *)
   1.178 +
   1.179 +fun mk_updC sfx sT (c,T) = (suffix sfx c, (T --> T) --> sT --> sT);
   1.180 +
   1.181 +fun mk_upd' sfx c v sT =
   1.182 +  let val vT = domain_type (fastype_of v);
   1.183 +  in Const (mk_updC sfx sT (c, vT)) $ v  end;
   1.184 +
   1.185 +fun mk_upd sfx c v s = mk_upd' sfx c v (fastype_of s) $ s
   1.186 +
   1.187 +(* types *)
   1.188 +
   1.189 +fun dest_recT (typ as Type (c_ext_type, Ts as (T::_))) =
   1.190 +      (case try (unsuffix ext_typeN) c_ext_type of
   1.191 +        NONE => raise TYPE ("Record.dest_recT", [typ], [])
   1.192 +      | SOME c => ((c, Ts), List.last Ts))
   1.193 +  | dest_recT typ = raise TYPE ("Record.dest_recT", [typ], []);
   1.194 +
   1.195 +fun is_recT T =
   1.196 +  (case try dest_recT T of NONE => false | SOME _ => true);
   1.197 +
   1.198 +fun dest_recTs T =
   1.199 +  let val ((c, Ts), U) = dest_recT T
   1.200 +  in (c, Ts) :: dest_recTs U
   1.201 +  end handle TYPE _ => [];
   1.202 +
   1.203 +fun last_extT T =
   1.204 +  let val ((c, Ts), U) = dest_recT T
   1.205 +  in (case last_extT U of
   1.206 +        NONE => SOME (c,Ts)
   1.207 +      | SOME l => SOME l)
   1.208 +  end handle TYPE _ => NONE
   1.209 +
   1.210 +fun rec_id i T =
   1.211 +  let val rTs = dest_recTs T
   1.212 +      val rTs' = if i < 0 then rTs else Library.take (i,rTs)
   1.213 +  in Library.foldl (fn (s,(c,T)) => s ^ c) ("",rTs') end;
   1.214 +
   1.215 +(*** extend theory by record definition ***)
   1.216 +
   1.217 +(** record info **)
   1.218 +
   1.219 +(* type record_info and parent_info  *)
   1.220 +
   1.221 +type record_info =
   1.222 + {args: (string * sort) list,
   1.223 +  parent: (typ list * string) option,
   1.224 +  fields: (string * typ) list,
   1.225 +  extension: (string * typ list),
   1.226 +  induct: thm
   1.227 + };
   1.228 +
   1.229 +fun make_record_info args parent fields extension induct =
   1.230 + {args = args, parent = parent, fields = fields, extension = extension,
   1.231 +  induct = induct}: record_info;
   1.232 +
   1.233 +
   1.234 +type parent_info =
   1.235 + {name: string,
   1.236 +  fields: (string * typ) list,
   1.237 +  extension: (string * typ list),
   1.238 +  induct: thm
   1.239 +};
   1.240 +
   1.241 +fun make_parent_info name fields extension induct =
   1.242 + {name = name, fields = fields, extension = extension, induct = induct}: parent_info;
   1.243 +
   1.244 +
   1.245 +(* theory data *)
   1.246 +
   1.247 +type record_data =
   1.248 + {records: record_info Symtab.table,
   1.249 +  sel_upd:
   1.250 +   {selectors: unit Symtab.table,
   1.251 +    updates: string Symtab.table,
   1.252 +    simpset: Simplifier.simpset},
   1.253 +  equalities: thm Symtab.table,
   1.254 +  extinjects: thm list,
   1.255 +  extsplit: thm Symtab.table, (* maps extension name to split rule *)
   1.256 +  splits: (thm*thm*thm*thm) Symtab.table,    (* !!,!,EX - split-equalities,induct rule *)
   1.257 +  extfields: (string*typ) list Symtab.table, (* maps extension to its fields *)
   1.258 +  fieldext: (string*typ list) Symtab.table   (* maps field to its extension *)
   1.259 +};
   1.260 +
   1.261 +fun make_record_data
   1.262 +      records sel_upd equalities extinjects extsplit splits extfields fieldext =
   1.263 + {records = records, sel_upd = sel_upd,
   1.264 +  equalities = equalities, extinjects=extinjects, extsplit = extsplit, splits = splits,
   1.265 +  extfields = extfields, fieldext = fieldext }: record_data;
   1.266 +
   1.267 +structure RecordsData = TheoryDataFun
   1.268 +(
   1.269 +  type T = record_data;
   1.270 +  val empty =
   1.271 +    make_record_data Symtab.empty
   1.272 +      {selectors = Symtab.empty, updates = Symtab.empty, simpset = HOL_basic_ss}
   1.273 +       Symtab.empty [] Symtab.empty Symtab.empty Symtab.empty Symtab.empty;
   1.274 +
   1.275 +  val copy = I;
   1.276 +  val extend = I;
   1.277 +  fun merge _
   1.278 +   ({records = recs1,
   1.279 +     sel_upd = {selectors = sels1, updates = upds1, simpset = ss1},
   1.280 +     equalities = equalities1,
   1.281 +     extinjects = extinjects1,
   1.282 +     extsplit = extsplit1,
   1.283 +     splits = splits1,
   1.284 +     extfields = extfields1,
   1.285 +     fieldext = fieldext1},
   1.286 +    {records = recs2,
   1.287 +     sel_upd = {selectors = sels2, updates = upds2, simpset = ss2},
   1.288 +     equalities = equalities2,
   1.289 +     extinjects = extinjects2,
   1.290 +     extsplit = extsplit2,
   1.291 +     splits = splits2,
   1.292 +     extfields = extfields2,
   1.293 +     fieldext = fieldext2}) =
   1.294 +    make_record_data
   1.295 +      (Symtab.merge (K true) (recs1, recs2))
   1.296 +      {selectors = Symtab.merge (K true) (sels1, sels2),
   1.297 +        updates = Symtab.merge (K true) (upds1, upds2),
   1.298 +        simpset = Simplifier.merge_ss (ss1, ss2)}
   1.299 +      (Symtab.merge Thm.eq_thm_prop (equalities1, equalities2))
   1.300 +      (Library.merge Thm.eq_thm_prop (extinjects1, extinjects2))
   1.301 +      (Symtab.merge Thm.eq_thm_prop (extsplit1,extsplit2))
   1.302 +      (Symtab.merge (fn ((a,b,c,d),(w,x,y,z))
   1.303 +                     => Thm.eq_thm (a,w) andalso Thm.eq_thm (b,x) andalso
   1.304 +                        Thm.eq_thm (c,y) andalso Thm.eq_thm (d,z))
   1.305 +                    (splits1, splits2))
   1.306 +      (Symtab.merge (K true) (extfields1,extfields2))
   1.307 +      (Symtab.merge (K true) (fieldext1,fieldext2));
   1.308 +);
   1.309 +
   1.310 +fun print_records thy =
   1.311 +  let
   1.312 +    val {records = recs, ...} = RecordsData.get thy;
   1.313 +    val prt_typ = Syntax.pretty_typ_global thy;
   1.314 +
   1.315 +    fun pretty_parent NONE = []
   1.316 +      | pretty_parent (SOME (Ts, name)) =
   1.317 +          [Pretty.block [prt_typ (Type (name, Ts)), Pretty.str " +"]];
   1.318 +
   1.319 +    fun pretty_field (c, T) = Pretty.block
   1.320 +      [Pretty.str (Sign.extern_const thy c), Pretty.str " ::",
   1.321 +        Pretty.brk 1, Pretty.quote (prt_typ T)];
   1.322 +
   1.323 +    fun pretty_record (name, {args, parent, fields, ...}: record_info) =
   1.324 +      Pretty.block (Pretty.fbreaks (Pretty.block
   1.325 +        [prt_typ (Type (name, map TFree args)), Pretty.str " = "] ::
   1.326 +        pretty_parent parent @ map pretty_field fields));
   1.327 +  in map pretty_record (Symtab.dest recs) |> Pretty.chunks |> Pretty.writeln end;
   1.328 +
   1.329 +
   1.330 +(* access 'records' *)
   1.331 +
   1.332 +val get_record = Symtab.lookup o #records o RecordsData.get;
   1.333 +
   1.334 +fun put_record name info thy =
   1.335 +  let
   1.336 +    val {records, sel_upd, equalities, extinjects,extsplit,splits,extfields,fieldext} =
   1.337 +          RecordsData.get thy;
   1.338 +    val data = make_record_data (Symtab.update (name, info) records)
   1.339 +      sel_upd equalities extinjects extsplit splits extfields fieldext;
   1.340 +  in RecordsData.put data thy end;
   1.341 +
   1.342 +
   1.343 +(* access 'sel_upd' *)
   1.344 +
   1.345 +val get_sel_upd = #sel_upd o RecordsData.get;
   1.346 +
   1.347 +val is_selector = Symtab.defined o #selectors o get_sel_upd;
   1.348 +val get_updates = Symtab.lookup o #updates o get_sel_upd;
   1.349 +fun get_simpset thy = Simplifier.theory_context thy (#simpset (get_sel_upd thy));
   1.350 +
   1.351 +fun put_sel_upd names simps = RecordsData.map (fn {records,
   1.352 +  sel_upd = {selectors, updates, simpset},
   1.353 +    equalities, extinjects, extsplit, splits, extfields, fieldext} =>
   1.354 +  make_record_data records
   1.355 +    {selectors = fold (fn name => Symtab.update (name, ())) names selectors,
   1.356 +      updates = fold (fn name => Symtab.update ((suffix updateN) name, name)) names updates,
   1.357 +      simpset = Simplifier.addsimps (simpset, simps)}
   1.358 +      equalities extinjects extsplit splits extfields fieldext);
   1.359 +
   1.360 +
   1.361 +(* access 'equalities' *)
   1.362 +
   1.363 +fun add_record_equalities name thm thy =
   1.364 +  let
   1.365 +    val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields,fieldext} =
   1.366 +          RecordsData.get thy;
   1.367 +    val data = make_record_data records sel_upd
   1.368 +           (Symtab.update_new (name, thm) equalities) extinjects extsplit
   1.369 +           splits extfields fieldext;
   1.370 +  in RecordsData.put data thy end;
   1.371 +
   1.372 +val get_equalities =Symtab.lookup o #equalities o RecordsData.get;
   1.373 +
   1.374 +
   1.375 +(* access 'extinjects' *)
   1.376 +
   1.377 +fun add_extinjects thm thy =
   1.378 +  let
   1.379 +    val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields,fieldext} =
   1.380 +          RecordsData.get thy;
   1.381 +    val data =
   1.382 +      make_record_data records sel_upd equalities (insert Thm.eq_thm_prop thm extinjects) extsplit
   1.383 +        splits extfields fieldext;
   1.384 +  in RecordsData.put data thy end;
   1.385 +
   1.386 +val get_extinjects = rev o #extinjects o RecordsData.get;
   1.387 +
   1.388 +
   1.389 +(* access 'extsplit' *)
   1.390 +
   1.391 +fun add_extsplit name thm thy =
   1.392 +  let
   1.393 +    val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields,fieldext} =
   1.394 +          RecordsData.get thy;
   1.395 +    val data = make_record_data records sel_upd
   1.396 +      equalities extinjects (Symtab.update_new (name, thm) extsplit) splits
   1.397 +      extfields fieldext;
   1.398 +  in RecordsData.put data thy end;
   1.399 +
   1.400 +val get_extsplit = Symtab.lookup o #extsplit o RecordsData.get;
   1.401 +
   1.402 +
   1.403 +(* access 'splits' *)
   1.404 +
   1.405 +fun add_record_splits name thmP thy =
   1.406 +  let
   1.407 +    val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields,fieldext} =
   1.408 +          RecordsData.get thy;
   1.409 +    val data = make_record_data records sel_upd
   1.410 +      equalities extinjects extsplit (Symtab.update_new (name, thmP) splits)
   1.411 +      extfields fieldext;
   1.412 +  in RecordsData.put data thy end;
   1.413 +
   1.414 +val get_splits = Symtab.lookup o #splits o RecordsData.get;
   1.415 +
   1.416 +
   1.417 +(* parent/extension of named record *)
   1.418 +
   1.419 +val get_parent = (Option.join o Option.map #parent) oo (Symtab.lookup o #records o RecordsData.get);
   1.420 +val get_extension = Option.map #extension oo (Symtab.lookup o #records o RecordsData.get);
   1.421 +
   1.422 +
   1.423 +(* access 'extfields' *)
   1.424 +
   1.425 +fun add_extfields name fields thy =
   1.426 +  let
   1.427 +    val {records, sel_upd, equalities, extinjects, extsplit,splits, extfields, fieldext} =
   1.428 +          RecordsData.get thy;
   1.429 +    val data = make_record_data records sel_upd
   1.430 +         equalities extinjects extsplit splits
   1.431 +         (Symtab.update_new (name, fields) extfields) fieldext;
   1.432 +  in RecordsData.put data thy end;
   1.433 +
   1.434 +val get_extfields = Symtab.lookup o #extfields o RecordsData.get;
   1.435 +
   1.436 +fun get_extT_fields thy T =
   1.437 +  let
   1.438 +    val ((name,Ts),moreT) = dest_recT T;
   1.439 +    val recname = let val (nm::recn::rst) = rev (Long_Name.explode name)
   1.440 +                  in Long_Name.implode (rev (nm::rst)) end;
   1.441 +    val midx = maxidx_of_typs (moreT::Ts);
   1.442 +    val varifyT = varifyT midx;
   1.443 +    val {records,extfields,...} = RecordsData.get thy;
   1.444 +    val (flds,(more,_)) = split_last (Symtab.lookup_list extfields name);
   1.445 +    val args = map varifyT (snd (#extension (the (Symtab.lookup records recname))));
   1.446 +
   1.447 +    val subst = fold (Sign.typ_match thy) (but_last args ~~ but_last Ts) (Vartab.empty);
   1.448 +    val flds' = map (apsnd ((Envir.norm_type subst) o varifyT)) flds;
   1.449 +  in (flds',(more,moreT)) end;
   1.450 +
   1.451 +fun get_recT_fields thy T =
   1.452 +  let
   1.453 +    val (root_flds,(root_more,root_moreT)) = get_extT_fields thy T;
   1.454 +    val (rest_flds,rest_more) =
   1.455 +           if is_recT root_moreT then get_recT_fields thy root_moreT
   1.456 +           else ([],(root_more,root_moreT));
   1.457 +  in (root_flds@rest_flds,rest_more) end;
   1.458 +
   1.459 +
   1.460 +(* access 'fieldext' *)
   1.461 +
   1.462 +fun add_fieldext extname_types fields thy =
   1.463 +  let
   1.464 +    val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =
   1.465 +           RecordsData.get thy;
   1.466 +    val fieldext' =
   1.467 +      fold (fn field => Symtab.update_new (field, extname_types)) fields fieldext;
   1.468 +    val data=make_record_data records sel_upd equalities extinjects extsplit
   1.469 +              splits extfields fieldext';
   1.470 +  in RecordsData.put data thy end;
   1.471 +
   1.472 +
   1.473 +val get_fieldext = Symtab.lookup o #fieldext o RecordsData.get;
   1.474 +
   1.475 +
   1.476 +(* parent records *)
   1.477 +
   1.478 +fun add_parents thy NONE parents = parents
   1.479 +  | add_parents thy (SOME (types, name)) parents =
   1.480 +      let
   1.481 +        fun err msg = error (msg ^ " parent record " ^ quote name);
   1.482 +
   1.483 +        val {args, parent, fields, extension, induct} =
   1.484 +          (case get_record thy name of SOME info => info | NONE => err "Unknown");
   1.485 +        val _ = if length types <> length args then err "Bad number of arguments for" else ();
   1.486 +
   1.487 +        fun bad_inst ((x, S), T) =
   1.488 +          if Sign.of_sort thy (T, S) then NONE else SOME x
   1.489 +        val bads = List.mapPartial bad_inst (args ~~ types);
   1.490 +        val _ = null bads orelse err ("Ill-sorted instantiation of " ^ commas bads ^ " in");
   1.491 +
   1.492 +        val inst = map fst args ~~ types;
   1.493 +        val subst = Term.map_type_tfree (the o AList.lookup (op =) inst o fst);
   1.494 +        val parent' = Option.map (apfst (map subst)) parent;
   1.495 +        val fields' = map (apsnd subst) fields;
   1.496 +        val extension' = apsnd (map subst) extension;
   1.497 +      in
   1.498 +        add_parents thy parent'
   1.499 +          (make_parent_info name fields' extension' induct :: parents)
   1.500 +      end;
   1.501 +
   1.502 +
   1.503 +
   1.504 +(** concrete syntax for records **)
   1.505 +
   1.506 +(* decode type *)
   1.507 +
   1.508 +fun decode_type thy t =
   1.509 +  let
   1.510 +    fun get_sort xs n = AList.lookup (op =) xs (n: indexname) |> the_default (Sign.defaultS thy);
   1.511 +    val map_sort = Sign.intern_sort thy;
   1.512 +  in
   1.513 +    Syntax.typ_of_term (get_sort (Syntax.term_sorts map_sort t)) map_sort t
   1.514 +    |> Sign.intern_tycons thy
   1.515 +  end;
   1.516 +
   1.517 +
   1.518 +(* parse translations *)
   1.519 +
   1.520 +fun gen_field_tr mark sfx (t as Const (c, _) $ Const (name, _) $ arg) =
   1.521 +      if c = mark then Syntax.const (suffix sfx name) $ (Abs ("_",dummyT, arg))
   1.522 +      else raise TERM ("gen_field_tr: " ^ mark, [t])
   1.523 +  | gen_field_tr mark _ t = raise TERM ("gen_field_tr: " ^ mark, [t]);
   1.524 +
   1.525 +fun gen_fields_tr sep mark sfx (tm as Const (c, _) $ t $ u) =
   1.526 +      if c = sep then gen_field_tr mark sfx t :: gen_fields_tr sep mark sfx u
   1.527 +      else [gen_field_tr mark sfx tm]
   1.528 +  | gen_fields_tr _ mark sfx tm = [gen_field_tr mark sfx tm];
   1.529 +
   1.530 +
   1.531 +fun record_update_tr [t, u] =
   1.532 +      Library.foldr (op $) (rev (gen_fields_tr "_updates" "_update" updateN u), t)
   1.533 +  | record_update_tr ts = raise TERM ("record_update_tr", ts);
   1.534 +
   1.535 +fun update_name_tr (Free (x, T) :: ts) = Free (suffix updateN x, T) $$ ts
   1.536 +  | update_name_tr (Const (x, T) :: ts) = Const (suffix updateN x, T) $$ ts
   1.537 +  | update_name_tr (((c as Const ("_constrain", _)) $ t $ ty) :: ts) =
   1.538 +      (c $ update_name_tr [t] $ (Syntax.const "fun" $ ty $ Syntax.const "dummy")) $$ ts
   1.539 +  | update_name_tr ts = raise TERM ("update_name_tr", ts);
   1.540 +
   1.541 +fun dest_ext_field mark (t as (Const (c,_) $ Const (name,_) $ arg)) =
   1.542 +     if c = mark then (name,arg) else raise TERM ("dest_ext_field: " ^ mark, [t])
   1.543 +  | dest_ext_field _ t = raise TERM ("dest_ext_field", [t])
   1.544 +
   1.545 +fun dest_ext_fields sep mark (trm as (Const (c,_) $ t $ u)) =
   1.546 +     if c = sep then dest_ext_field mark t::dest_ext_fields sep mark u
   1.547 +     else [dest_ext_field mark trm]
   1.548 +  | dest_ext_fields _ mark t = [dest_ext_field mark t]
   1.549 +
   1.550 +fun gen_ext_fields_tr sep mark sfx more ctxt t =
   1.551 +  let
   1.552 +    val thy = ProofContext.theory_of ctxt;
   1.553 +    val msg = "error in record input: ";
   1.554 +    val fieldargs = dest_ext_fields sep mark t;
   1.555 +    fun splitargs (field::fields) ((name,arg)::fargs) =
   1.556 +          if can (unsuffix name) field
   1.557 +          then let val (args,rest) = splitargs fields fargs
   1.558 +               in (arg::args,rest) end
   1.559 +          else raise TERM (msg ^ "expecting field " ^ field ^ " but got " ^ name, [t])
   1.560 +      | splitargs [] (fargs as (_::_)) = ([],fargs)
   1.561 +      | splitargs (_::_) [] = raise TERM (msg ^ "expecting more fields", [t])
   1.562 +      | splitargs _ _ = ([],[]);
   1.563 +
   1.564 +    fun mk_ext (fargs as (name,arg)::_) =
   1.565 +         (case get_fieldext thy (Sign.intern_const thy name) of
   1.566 +            SOME (ext,_) => (case get_extfields thy ext of
   1.567 +                               SOME flds
   1.568 +                                 => let val (args,rest) =
   1.569 +                                               splitargs (map fst (but_last flds)) fargs;
   1.570 +                                        val more' = mk_ext rest;
   1.571 +                                    in list_comb (Syntax.const (suffix sfx ext),args@[more'])
   1.572 +                                    end
   1.573 +                             | NONE => raise TERM(msg ^ "no fields defined for "
   1.574 +                                                   ^ ext,[t]))
   1.575 +          | NONE => raise TERM (msg ^ name ^" is no proper field",[t]))
   1.576 +      | mk_ext [] = more
   1.577 +
   1.578 +  in mk_ext fieldargs end;
   1.579 +
   1.580 +fun gen_ext_type_tr sep mark sfx more ctxt t =
   1.581 +  let
   1.582 +    val thy = ProofContext.theory_of ctxt;
   1.583 +    val msg = "error in record-type input: ";
   1.584 +    val fieldargs = dest_ext_fields sep mark t;
   1.585 +    fun splitargs (field::fields) ((name,arg)::fargs) =
   1.586 +          if can (unsuffix name) field
   1.587 +          then let val (args,rest) = splitargs fields fargs
   1.588 +               in (arg::args,rest) end
   1.589 +          else raise TERM (msg ^ "expecting field " ^ field ^ " but got " ^ name, [t])
   1.590 +      | splitargs [] (fargs as (_::_)) = ([],fargs)
   1.591 +      | splitargs (_::_) [] = raise TERM (msg ^ "expecting more fields", [t])
   1.592 +      | splitargs _ _ = ([],[]);
   1.593 +
   1.594 +    fun mk_ext (fargs as (name,arg)::_) =
   1.595 +         (case get_fieldext thy (Sign.intern_const thy name) of
   1.596 +            SOME (ext,alphas) =>
   1.597 +              (case get_extfields thy ext of
   1.598 +                 SOME flds
   1.599 +                  => (let
   1.600 +                       val flds' = but_last flds;
   1.601 +                       val types = map snd flds';
   1.602 +                       val (args,rest) = splitargs (map fst flds') fargs;
   1.603 +                       val argtypes = map (Sign.certify_typ thy o decode_type thy) args;
   1.604 +                       val midx =  fold (fn T => fn i => Int.max (maxidx_of_typ T, i))
   1.605 +                                    argtypes 0;
   1.606 +                       val varifyT = varifyT midx;
   1.607 +                       val vartypes = map varifyT types;
   1.608 +
   1.609 +                       val subst = fold (Sign.typ_match thy) (vartypes ~~ argtypes)
   1.610 +                                            Vartab.empty;
   1.611 +                       val alphas' = map ((Syntax.term_of_typ (! Syntax.show_sorts)) o
   1.612 +                                          Envir.norm_type subst o varifyT)
   1.613 +                                         (but_last alphas);
   1.614 +
   1.615 +                       val more' = mk_ext rest;
   1.616 +                     in list_comb (Syntax.const (suffix sfx ext),alphas'@[more'])
   1.617 +                     end handle TYPE_MATCH => raise
   1.618 +                           TERM (msg ^ "type is no proper record (extension)", [t]))
   1.619 +               | NONE => raise TERM (msg ^ "no fields defined for " ^ ext,[t]))
   1.620 +          | NONE => raise TERM (msg ^ name ^" is no proper field",[t]))
   1.621 +      | mk_ext [] = more
   1.622 +
   1.623 +  in mk_ext fieldargs end;
   1.624 +
   1.625 +fun gen_adv_record_tr sep mark sfx unit ctxt [t] =
   1.626 +      gen_ext_fields_tr sep mark sfx unit ctxt t
   1.627 +  | gen_adv_record_tr _ _ _ _ _ ts = raise TERM ("gen_record_tr", ts);
   1.628 +
   1.629 +fun gen_adv_record_scheme_tr sep mark sfx ctxt [t, more] =
   1.630 +      gen_ext_fields_tr sep mark sfx more ctxt t
   1.631 +  | gen_adv_record_scheme_tr _ _ _ _ ts = raise TERM ("gen_record_scheme_tr", ts);
   1.632 +
   1.633 +fun gen_adv_record_type_tr sep mark sfx unit ctxt [t] =
   1.634 +      gen_ext_type_tr sep mark sfx unit ctxt t
   1.635 +  | gen_adv_record_type_tr _ _ _ _ _ ts = raise TERM ("gen_record_tr", ts);
   1.636 +
   1.637 +fun gen_adv_record_type_scheme_tr sep mark sfx ctxt [t, more] =
   1.638 +      gen_ext_type_tr sep mark sfx more ctxt t
   1.639 +  | gen_adv_record_type_scheme_tr _ _ _ _ ts = raise TERM ("gen_record_scheme_tr", ts);
   1.640 +
   1.641 +val adv_record_tr = gen_adv_record_tr "_fields" "_field" extN HOLogic.unit;
   1.642 +val adv_record_scheme_tr = gen_adv_record_scheme_tr "_fields" "_field" extN;
   1.643 +
   1.644 +val adv_record_type_tr =
   1.645 +      gen_adv_record_type_tr "_field_types" "_field_type" ext_typeN
   1.646 +        (Syntax.term_of_typ false (HOLogic.unitT));
   1.647 +val adv_record_type_scheme_tr =
   1.648 +      gen_adv_record_type_scheme_tr "_field_types" "_field_type" ext_typeN;
   1.649 +
   1.650 +
   1.651 +val parse_translation =
   1.652 + [("_record_update", record_update_tr),
   1.653 +  ("_update_name", update_name_tr)];
   1.654 +
   1.655 +
   1.656 +val adv_parse_translation =
   1.657 + [("_record",adv_record_tr),
   1.658 +  ("_record_scheme",adv_record_scheme_tr),
   1.659 +  ("_record_type",adv_record_type_tr),
   1.660 +  ("_record_type_scheme",adv_record_type_scheme_tr)];
   1.661 +
   1.662 +
   1.663 +(* print translations *)
   1.664 +
   1.665 +val print_record_type_abbr = ref true;
   1.666 +val print_record_type_as_fields = ref true;
   1.667 +
   1.668 +fun gen_field_upds_tr' mark sfx (tm as Const (name_field, _) $ k $ u) =
   1.669 +  let val t = (case k of (Abs (_,_,(Abs (_,_,t)$Bound 0))) 
   1.670 +                  => if null (loose_bnos t) then t else raise Match
   1.671 +               | Abs (x,_,t) => if null (loose_bnos t) then t else raise Match
   1.672 +               | _ => raise Match)
   1.673 +
   1.674 +      (* (case k of (Const ("K_record",_)$t) => t
   1.675 +               | Abs (x,_,Const ("K_record",_)$t$Bound 0) => t
   1.676 +               | _ => raise Match)*)
   1.677 +  in
   1.678 +    (case try (unsuffix sfx) name_field of
   1.679 +      SOME name =>
   1.680 +        apfst (cons (Syntax.const mark $ Syntax.free name $ t)) (gen_field_upds_tr' mark sfx u)
   1.681 +     | NONE => ([], tm))
   1.682 +  end
   1.683 +  | gen_field_upds_tr' _ _ tm = ([], tm);
   1.684 +
   1.685 +fun record_update_tr' tm =
   1.686 +  let val (ts, u) = gen_field_upds_tr' "_update" updateN tm in
   1.687 +    if null ts then raise Match
   1.688 +    else Syntax.const "_record_update" $ u $
   1.689 +          foldr1 (fn (v, w) => Syntax.const "_updates" $ v $ w) (rev ts)
   1.690 +  end;
   1.691 +
   1.692 +fun gen_field_tr' sfx tr' name =
   1.693 +  let val name_sfx = suffix sfx name
   1.694 +  in (name_sfx, fn [t, u] => tr' (Syntax.const name_sfx $ t $ u) | _ => raise Match) end;
   1.695 +
   1.696 +fun record_tr' sep mark record record_scheme unit ctxt t =
   1.697 +  let
   1.698 +    val thy = ProofContext.theory_of ctxt;
   1.699 +    fun field_lst t =
   1.700 +      (case strip_comb t of
   1.701 +        (Const (ext,_),args as (_::_))
   1.702 +         => (case try (unsuffix extN) (Sign.intern_const thy ext) of
   1.703 +               SOME ext'
   1.704 +               => (case get_extfields thy ext' of
   1.705 +                     SOME flds
   1.706 +                     => (let
   1.707 +                          val (f::fs) = but_last (map fst flds);
   1.708 +                          val flds' = Sign.extern_const thy f :: map Long_Name.base_name fs;
   1.709 +                          val (args',more) = split_last args;
   1.710 +                         in (flds'~~args')@field_lst more end
   1.711 +                         handle Library.UnequalLengths => [("",t)])
   1.712 +                   | NONE => [("",t)])
   1.713 +             | NONE => [("",t)])
   1.714 +       | _ => [("",t)])
   1.715 +
   1.716 +    val (flds,(_,more)) = split_last (field_lst t);
   1.717 +    val _ = if null flds then raise Match else ();
   1.718 +    val flds' = map (fn (n,t)=>Syntax.const mark$Syntax.const n$t) flds;
   1.719 +    val flds'' = foldr1 (fn (x,y) => Syntax.const sep$x$y) flds';
   1.720 +
   1.721 +  in if unit more
   1.722 +     then Syntax.const record$flds''
   1.723 +     else Syntax.const record_scheme$flds''$more
   1.724 +  end
   1.725 +
   1.726 +fun gen_record_tr' name =
   1.727 +  let val name_sfx = suffix extN name;
   1.728 +      val unit = (fn Const (@{const_syntax "Product_Type.Unity"},_) => true | _ => false);
   1.729 +      fun tr' ctxt ts = record_tr' "_fields" "_field" "_record" "_record_scheme" unit ctxt
   1.730 +                       (list_comb (Syntax.const name_sfx,ts))
   1.731 +  in (name_sfx,tr')
   1.732 +  end
   1.733 +
   1.734 +fun print_translation names =
   1.735 +  map (gen_field_tr' updateN record_update_tr') names;
   1.736 +
   1.737 +
   1.738 +(* record_type_abbr_tr' tries to reconstruct the record name type abbreviation from *)
   1.739 +(* the (nested) extension types.                                                    *)
   1.740 +fun record_type_abbr_tr' default_tr' abbr alphas zeta lastExt schemeT ctxt tm =
   1.741 +  let
   1.742 +      val thy = ProofContext.theory_of ctxt;
   1.743 +      (* tm is term representation of a (nested) field type. We first reconstruct the      *)
   1.744 +      (* type from tm so that we can continue on the type level rather then the term level.*)
   1.745 +
   1.746 +      (* WORKAROUND:
   1.747 +       * If a record type occurs in an error message of type inference there
   1.748 +       * may be some internal frees donoted by ??:
   1.749 +       * (Const "_tfree",_)$Free ("??'a",_).
   1.750 +
   1.751 +       * This will unfortunately be translated to Type ("??'a",[]) instead of
   1.752 +       * TFree ("??'a",_) by typ_of_term, which will confuse unify below.
   1.753 +       * fixT works around.
   1.754 +       *)
   1.755 +      fun fixT (T as Type (x,[])) =
   1.756 +            if String.isPrefix "??'" x then TFree (x,Sign.defaultS thy) else T
   1.757 +        | fixT (Type (x,xs)) = Type (x,map fixT xs)
   1.758 +        | fixT T = T;
   1.759 +
   1.760 +      val T = fixT (decode_type thy tm);
   1.761 +      val midx = maxidx_of_typ T;
   1.762 +      val varifyT = varifyT midx;
   1.763 +
   1.764 +      fun mk_type_abbr subst name alphas =
   1.765 +          let val abbrT = Type (name, map (fn a => varifyT (TFree (a, Sign.defaultS thy))) alphas);
   1.766 +          in Syntax.term_of_typ (! Syntax.show_sorts)
   1.767 +               (Sign.extern_typ thy (Envir.norm_type subst abbrT)) end;
   1.768 +
   1.769 +      fun match rT T = (Sign.typ_match thy (varifyT rT,T)
   1.770 +                                                Vartab.empty);
   1.771 +
   1.772 +   in if !print_record_type_abbr
   1.773 +      then (case last_extT T of
   1.774 +             SOME (name,_)
   1.775 +              => if name = lastExt
   1.776 +                 then
   1.777 +                  (let
   1.778 +                     val subst = match schemeT T
   1.779 +                   in
   1.780 +                    if HOLogic.is_unitT (Envir.norm_type subst (varifyT (TFree(zeta,Sign.defaultS thy))))
   1.781 +                    then mk_type_abbr subst abbr alphas
   1.782 +                    else mk_type_abbr subst (suffix schemeN abbr) (alphas@[zeta])
   1.783 +                   end handle TYPE_MATCH => default_tr' ctxt tm)
   1.784 +                 else raise Match (* give print translation of specialised record a chance *)
   1.785 +            | _ => raise Match)
   1.786 +       else default_tr' ctxt tm
   1.787 +  end
   1.788 +
   1.789 +fun record_type_tr' sep mark record record_scheme ctxt t =
   1.790 +  let
   1.791 +    val thy = ProofContext.theory_of ctxt;
   1.792 +
   1.793 +    val T = decode_type thy t;
   1.794 +    val varifyT = varifyT (Term.maxidx_of_typ T);
   1.795 +
   1.796 +    fun term_of_type T = Syntax.term_of_typ (!Syntax.show_sorts) (Sign.extern_typ thy T);
   1.797 +
   1.798 +    fun field_lst T =
   1.799 +      (case T of
   1.800 +        Type (ext, args)
   1.801 +         => (case try (unsuffix ext_typeN) ext of
   1.802 +               SOME ext'
   1.803 +               => (case get_extfields thy ext' of
   1.804 +                     SOME flds
   1.805 +                     => (case get_fieldext thy (fst (hd flds)) of
   1.806 +                           SOME (_, alphas)
   1.807 +                           => (let
   1.808 +                                val (f :: fs) = but_last flds;
   1.809 +                                val flds' = apfst (Sign.extern_const thy) f
   1.810 +                                  :: map (apfst Long_Name.base_name) fs;
   1.811 +                                val (args', more) = split_last args;
   1.812 +                                val alphavars = map varifyT (but_last alphas);
   1.813 +                                val subst = fold2 (curry (Sign.typ_match thy))
   1.814 +                                  alphavars args' Vartab.empty;
   1.815 +                                val flds'' = (map o apsnd)
   1.816 +                                  (Envir.norm_type subst o varifyT) flds';
   1.817 +                              in flds'' @ field_lst more end
   1.818 +                              handle TYPE_MATCH => [("", T)]
   1.819 +                                  | Library.UnequalLengths => [("", T)])
   1.820 +                         | NONE => [("", T)])
   1.821 +                   | NONE => [("", T)])
   1.822 +             | NONE => [("", T)])
   1.823 +        | _ => [("", T)])
   1.824 +
   1.825 +    val (flds, (_, moreT)) = split_last (field_lst T);
   1.826 +    val flds' = map (fn (n, T) => Syntax.const mark $ Syntax.const n $ term_of_type T) flds;
   1.827 +    val flds'' = foldr1 (fn (x, y) => Syntax.const sep $ x $ y) flds' handle Empty => raise Match;
   1.828 +
   1.829 +  in if not (!print_record_type_as_fields) orelse null flds then raise Match
   1.830 +     else if moreT = HOLogic.unitT
   1.831 +          then Syntax.const record$flds''
   1.832 +          else Syntax.const record_scheme$flds''$term_of_type moreT
   1.833 +  end
   1.834 +
   1.835 +
   1.836 +fun gen_record_type_tr' name =
   1.837 +  let val name_sfx = suffix ext_typeN name;
   1.838 +      fun tr' ctxt ts = record_type_tr' "_field_types" "_field_type"
   1.839 +                       "_record_type" "_record_type_scheme" ctxt
   1.840 +                       (list_comb (Syntax.const name_sfx,ts))
   1.841 +  in (name_sfx,tr')
   1.842 +  end
   1.843 +
   1.844 +
   1.845 +fun gen_record_type_abbr_tr' abbr alphas zeta lastExt schemeT name =
   1.846 +  let val name_sfx = suffix ext_typeN name;
   1.847 +      val default_tr' = record_type_tr' "_field_types" "_field_type"
   1.848 +                               "_record_type" "_record_type_scheme"
   1.849 +      fun tr' ctxt ts =
   1.850 +          record_type_abbr_tr' default_tr' abbr alphas zeta lastExt schemeT ctxt
   1.851 +                               (list_comb (Syntax.const name_sfx,ts))
   1.852 +  in (name_sfx, tr') end;
   1.853 +
   1.854 +(** record simprocs **)
   1.855 +
   1.856 +val record_quick_and_dirty_sensitive = ref false;
   1.857 +
   1.858 +
   1.859 +fun quick_and_dirty_prove stndrd thy asms prop tac =
   1.860 +  if !record_quick_and_dirty_sensitive andalso !quick_and_dirty
   1.861 +  then Goal.prove (ProofContext.init thy) [] []
   1.862 +        (Logic.list_implies (map Logic.varify asms,Logic.varify prop))
   1.863 +        (K (SkipProof.cheat_tac @{theory HOL}))
   1.864 +        (* standard can take quite a while for large records, thats why
   1.865 +         * we varify the proposition manually here.*)
   1.866 +  else let val prf = Goal.prove (ProofContext.init thy) [] asms prop tac;
   1.867 +       in if stndrd then standard prf else prf end;
   1.868 +
   1.869 +fun quick_and_dirty_prf noopt opt () =
   1.870 +      if !record_quick_and_dirty_sensitive andalso !quick_and_dirty
   1.871 +      then noopt ()
   1.872 +      else opt ();
   1.873 +
   1.874 +local
   1.875 +fun abstract_over_fun_app (Abs (f,fT,t)) =
   1.876 +  let
   1.877 +     val (f',t') = Term.dest_abs (f,fT,t);
   1.878 +     val T = domain_type fT;
   1.879 +     val (x,T') = hd (Term.variant_frees t' [("x",T)]);
   1.880 +     val f_x = Free (f',fT)$(Free (x,T'));
   1.881 +     fun is_constr (Const (c,_)$_) = can (unsuffix extN) c
   1.882 +       | is_constr _ = false;
   1.883 +     fun subst (t as u$w) = if Free (f',fT)=u
   1.884 +                            then if is_constr w then f_x
   1.885 +                                 else raise TERM ("abstract_over_fun_app",[t])
   1.886 +                            else subst u$subst w
   1.887 +       | subst (Abs (x,T,t)) = (Abs (x,T,subst t))
   1.888 +       | subst t = t
   1.889 +     val t'' = abstract_over (f_x,subst t');
   1.890 +     val vars = strip_qnt_vars "all" t'';
   1.891 +     val bdy = strip_qnt_body "all" t'';
   1.892 +
   1.893 +  in list_abs ((x,T')::vars,bdy) end
   1.894 +  | abstract_over_fun_app t = raise TERM ("abstract_over_fun_app",[t]);
   1.895 +(* Generates a theorem of the kind:
   1.896 + * !!f x*. PROP P (f ( r x* ) x* == !!r x*. PROP P r x*
   1.897 + *)
   1.898 +fun mk_fun_apply_eq (Abs (f, fT, t)) thy =
   1.899 +  let
   1.900 +    val rT = domain_type fT;
   1.901 +    val vars = Term.strip_qnt_vars "all" t;
   1.902 +    val Ts = map snd vars;
   1.903 +    val n = length vars;
   1.904 +    fun app_bounds 0 t = t$Bound 0
   1.905 +      | app_bounds n t = if n > 0 then app_bounds (n-1) (t$Bound n) else t
   1.906 +
   1.907 +
   1.908 +    val [P,r] = Term.variant_frees t [("P",rT::Ts--->Term.propT),("r",Ts--->rT)];
   1.909 +    val prop = Logic.mk_equals
   1.910 +                (list_all ((f,fT)::vars,
   1.911 +                           app_bounds (n - 1) ((Free P)$(Bound n$app_bounds (n-1) (Free r)))),
   1.912 +                 list_all ((fst r,rT)::vars,
   1.913 +                           app_bounds (n - 1) ((Free P)$Bound n)));
   1.914 +    val prove_standard = quick_and_dirty_prove true thy;
   1.915 +    val thm = prove_standard [] prop (fn _ =>
   1.916 +	 EVERY [rtac equal_intr_rule 1,
   1.917 +                Goal.norm_hhf_tac 1,REPEAT (etac meta_allE 1), atac 1,
   1.918 +                Goal.norm_hhf_tac 1,REPEAT (etac meta_allE 1), atac 1]);
   1.919 +  in thm end
   1.920 +  | mk_fun_apply_eq t thy = raise TERM ("mk_fun_apply_eq",[t]);
   1.921 +
   1.922 +in
   1.923 +(* During proof of theorems produced by record_simproc you can end up in
   1.924 + * situations like "!!f ... . ... f r ..." where f is an extension update function.
   1.925 + * In order to split "f r" we transform this to "!!r ... . ... r ..." so that the
   1.926 + * usual split rules for extensions can apply.
   1.927 + *)
   1.928 +val record_split_f_more_simproc =
   1.929 +  Simplifier.simproc @{theory HOL} "record_split_f_more_simp" ["x"]
   1.930 +    (fn thy => fn _ => fn t =>
   1.931 +      (case t of (Const ("all", Type (_, [Type (_, [Type("fun",[T,T']), _]), _])))$
   1.932 +                  (trm as Abs _) =>
   1.933 +         (case rec_id (~1) T of
   1.934 +            "" => NONE
   1.935 +          | n => if T=T'
   1.936 +                 then (let
   1.937 +                        val P=cterm_of thy (abstract_over_fun_app trm);
   1.938 +                        val thm = mk_fun_apply_eq trm thy;
   1.939 +                        val PV = cterm_of thy (hd (OldTerm.term_vars (prop_of thm)));
   1.940 +                        val thm' = cterm_instantiate [(PV,P)] thm;
   1.941 +                       in SOME  thm' end handle TERM _ => NONE)
   1.942 +                else NONE)
   1.943 +       | _ => NONE))
   1.944 +end
   1.945 +
   1.946 +fun prove_split_simp thy ss T prop =
   1.947 +  let
   1.948 +    val {sel_upd={simpset,...},extsplit,...} = RecordsData.get thy;
   1.949 +    val extsplits =
   1.950 +            Library.foldl (fn (thms,(n,_)) => the_list (Symtab.lookup extsplit n) @ thms)
   1.951 +                    ([],dest_recTs T);
   1.952 +    val thms = (case get_splits thy (rec_id (~1) T) of
   1.953 +                   SOME (all_thm,_,_,_) =>
   1.954 +                     all_thm::(case extsplits of [thm] => [] | _ => extsplits)
   1.955 +                              (* [thm] is the same as all_thm *)
   1.956 +                 | NONE => extsplits)
   1.957 +    val thms'=K_comp_convs@thms;
   1.958 +    val ss' = (Simplifier.inherit_context ss simpset
   1.959 +                addsimps thms'
   1.960 +                addsimprocs [record_split_f_more_simproc]);
   1.961 +  in
   1.962 +    quick_and_dirty_prove true thy [] prop (fn _ => simp_tac ss' 1)
   1.963 +  end;
   1.964 +
   1.965 +
   1.966 +local
   1.967 +fun eq (s1:string) (s2:string) = (s1 = s2);
   1.968 +fun has_field extfields f T =
   1.969 +     exists (fn (eN,_) => exists (eq f o fst) (Symtab.lookup_list extfields eN))
   1.970 +       (dest_recTs T);
   1.971 +
   1.972 +fun K_skeleton n (T as Type (_,[_,kT])) (b as Bound i) (Abs (x,xT,t)) =
   1.973 +     if null (loose_bnos t) then ((n,kT),(Abs (x,xT,Bound (i+1)))) else ((n,T),b)
   1.974 +  | K_skeleton n T b _ = ((n,T),b);
   1.975 +
   1.976 +(*
   1.977 +fun K_skeleton n _ b ((K_rec as Const ("Record.K_record",Type (_,[kT,_])))$_) = 
   1.978 +      ((n,kT),K_rec$b)
   1.979 +  | K_skeleton n _ (Bound i) 
   1.980 +      (Abs (x,T,(K_rec as Const ("Record.K_record",Type (_,[kT,_])))$_$Bound 0)) =
   1.981 +        ((n,kT),Abs (x,T,(K_rec$Bound (i+1)$Bound 0)))
   1.982 +  | K_skeleton n T b  _ = ((n,T),b);
   1.983 + *)
   1.984 +
   1.985 +fun normalize_rhs thm =
   1.986 +  let
   1.987 +     val ss = HOL_basic_ss addsimps K_comp_convs; 
   1.988 +     val rhs = thm |> Thm.cprop_of |> Thm.dest_comb |> snd;
   1.989 +     val rhs' = (Simplifier.rewrite ss rhs);
   1.990 +  in Thm.transitive thm rhs' end;
   1.991 +in
   1.992 +(* record_simproc *)
   1.993 +(* Simplifies selections of an record update:
   1.994 + *  (1)  S (S_update k r) = k (S r)
   1.995 + *  (2)  S (X_update k r) = S r
   1.996 + * The simproc skips multiple updates at once, eg:
   1.997 + *  S (X_update x (Y_update y (S_update k r))) = k (S r)
   1.998 + * But be careful in (2) because of the extendibility of records.
   1.999 + * - If S is a more-selector we have to make sure that the update on component
  1.1000 + *   X does not affect the selected subrecord.
  1.1001 + * - If X is a more-selector we have to make sure that S is not in the updated
  1.1002 + *   subrecord.
  1.1003 + *)
  1.1004 +val record_simproc =
  1.1005 +  Simplifier.simproc @{theory HOL} "record_simp" ["x"]
  1.1006 +    (fn thy => fn ss => fn t =>
  1.1007 +      (case t of (sel as Const (s, Type (_,[domS,rangeS])))$
  1.1008 +                   ((upd as Const (u,Type(_,[_,Type (_,[rT,_])]))) $ k $ r)=>
  1.1009 +        if is_selector thy s then
  1.1010 +          (case get_updates thy u of SOME u_name =>
  1.1011 +            let
  1.1012 +              val {sel_upd={updates,...},extfields,...} = RecordsData.get thy;
  1.1013 +
  1.1014 +              fun mk_eq_terms ((upd as Const (u,Type(_,[kT,_]))) $ k $ r) =
  1.1015 +                  (case Symtab.lookup updates u of
  1.1016 +                     NONE => NONE
  1.1017 +                   | SOME u_name
  1.1018 +                     => if u_name = s
  1.1019 +                        then (case mk_eq_terms r of
  1.1020 +                               NONE =>
  1.1021 +                                 let
  1.1022 +                                   val rv = ("r",rT)
  1.1023 +                                   val rb = Bound 0
  1.1024 +                                   val (kv,kb) = K_skeleton "k" kT (Bound 1) k;
  1.1025 +                                  in SOME (upd$kb$rb,kb$(sel$rb),[kv,rv]) end
  1.1026 +                              | SOME (trm,trm',vars) =>
  1.1027 +                                 let
  1.1028 +                                   val (kv,kb) = K_skeleton "k" kT (Bound (length vars)) k;
  1.1029 +                                 in SOME (upd$kb$trm,kb$trm',kv::vars) end)
  1.1030 +                        else if has_field extfields u_name rangeS
  1.1031 +                             orelse has_field extfields s (domain_type kT)
  1.1032 +                             then NONE
  1.1033 +                             else (case mk_eq_terms r of
  1.1034 +                                     SOME (trm,trm',vars)
  1.1035 +                                     => let
  1.1036 +                                          val (kv,kb) = 
  1.1037 +                                                 K_skeleton "k" kT (Bound (length vars)) k;
  1.1038 +                                        in SOME (upd$kb$trm,trm',kv::vars) end
  1.1039 +                                   | NONE
  1.1040 +                                     => let
  1.1041 +                                          val rv = ("r",rT)
  1.1042 +                                          val rb = Bound 0
  1.1043 +                                          val (kv,kb) = K_skeleton "k" kT (Bound 1) k;
  1.1044 +                                        in SOME (upd$kb$rb,sel$rb,[kv,rv]) end))
  1.1045 +                | mk_eq_terms r = NONE
  1.1046 +            in
  1.1047 +              (case mk_eq_terms (upd$k$r) of
  1.1048 +                 SOME (trm,trm',vars)
  1.1049 +                 => SOME (prove_split_simp thy ss domS
  1.1050 +                                 (list_all(vars, Logic.mk_equals (sel $ trm, trm'))))
  1.1051 +               | NONE => NONE)
  1.1052 +            end
  1.1053 +          | NONE => NONE)
  1.1054 +        else NONE
  1.1055 +      | _ => NONE));
  1.1056 +
  1.1057 +(* record_upd_simproc *)
  1.1058 +(* simplify multiple updates:
  1.1059 + *  (1)  "N_update y (M_update g (N_update x (M_update f r))) =
  1.1060 +          (N_update (y o x) (M_update (g o f) r))"
  1.1061 + *  (2)  "r(|M:= M r|) = r"
  1.1062 + * For (2) special care of "more" updates has to be taken:
  1.1063 + *    r(|more := m; A := A r|)
  1.1064 + * If A is contained in the fields of m we cannot remove the update A := A r!
  1.1065 + * (But r(|more := r; A := A (r(|more := r|))|) = r(|more := r|)
  1.1066 +*)
  1.1067 +val record_upd_simproc =
  1.1068 +  Simplifier.simproc @{theory HOL} "record_upd_simp" ["x"]
  1.1069 +    (fn thy => fn ss => fn t =>
  1.1070 +      (case t of ((upd as Const (u, Type(_,[_,Type(_,[rT,_])]))) $ k $ r) =>
  1.1071 +         let datatype ('a,'b) calc = Init of 'b | Inter of 'a
  1.1072 +             val {sel_upd={selectors,updates,...},extfields,...} = RecordsData.get thy;
  1.1073 +
  1.1074 +             (*fun mk_abs_var x t = (x, fastype_of t);*)
  1.1075 +             fun sel_name u = Long_Name.base_name (unsuffix updateN u);
  1.1076 +
  1.1077 +             fun seed s (upd as Const (more,Type(_,[mT,_]))$ k $ r) =
  1.1078 +                  if has_field extfields s (domain_type' mT) then upd else seed s r
  1.1079 +               | seed _ r = r;
  1.1080 +
  1.1081 +             fun grow u uT k kT vars (sprout,skeleton) =
  1.1082 +                   if sel_name u = moreN
  1.1083 +                   then let val (kv,kb) = K_skeleton "k" kT (Bound (length vars)) k;
  1.1084 +                        in ((Const (u,uT)$k$sprout,Const (u,uT)$kb$skeleton),kv::vars) end
  1.1085 +                   else ((sprout,skeleton),vars);
  1.1086 +
  1.1087 +
  1.1088 +             fun dest_k (Abs (x,T,((sel as Const (s,_))$r))) =
  1.1089 +                  if null (loose_bnos r) then SOME (x,T,sel,s,r) else NONE
  1.1090 +               | dest_k (Abs (_,_,(Abs (x,T,((sel as Const (s,_))$r)))$Bound 0)) =
  1.1091 +                  (* eta expanded variant *)
  1.1092 +                  if null (loose_bnos r) then SOME (x,T,sel,s,r) else NONE
  1.1093 +               | dest_k _ = NONE;
  1.1094 +
  1.1095 +             fun is_upd_same (sprout,skeleton) u k =
  1.1096 +               (case dest_k k of SOME (x,T,sel,s,r) =>
  1.1097 +                   if (unsuffix updateN u) = s andalso (seed s sprout) = r
  1.1098 +                   then SOME (fn t => Abs (x,T,incr_boundvars 1 t),sel,seed s skeleton)
  1.1099 +                   else NONE
  1.1100 +                | NONE => NONE);
  1.1101 +
  1.1102 +             fun init_seed r = ((r,Bound 0), [("r", rT)]);
  1.1103 +
  1.1104 +             fun add (n:string) f fmaps =
  1.1105 +               (case AList.lookup (op =) fmaps n of
  1.1106 +                  NONE => AList.update (op =) (n,[f]) fmaps
  1.1107 +                | SOME fs => AList.update (op =) (n,f::fs) fmaps)
  1.1108 +
  1.1109 +             fun comps (n:string) T fmaps =
  1.1110 +               (case AList.lookup (op =) fmaps n of
  1.1111 +                 SOME fs =>
  1.1112 +                   foldr1 (fn (f,g) => Const ("Fun.comp",(T-->T)-->(T-->T)-->(T-->T))$f$g) fs
  1.1113 +                | NONE => error ("record_upd_simproc.comps"))
  1.1114 +
  1.1115 +             (* mk_updterm returns either
  1.1116 +              *  - Init (orig-term, orig-term-skeleton, vars) if no optimisation can be made,
  1.1117 +              *     where vars are the bound variables in the skeleton
  1.1118 +              *  - Inter (orig-term-skeleton,simplified-term-skeleton,
  1.1119 +              *           vars, (term-sprout, skeleton-sprout))
  1.1120 +              *     where "All vars. orig-term-skeleton = simplified-term-skeleton" is
  1.1121 +              *     the desired simplification rule,
  1.1122 +              *     the sprouts accumulate the "more-updates" on the way from the seed
  1.1123 +              *     to the outermost update. It is only relevant to calculate the
  1.1124 +              *     possible simplification for (2)
  1.1125 +              * The algorithm first walks down the updates to the seed-record while
  1.1126 +              * memorising the updates in the already-table. While walking up the
  1.1127 +              * updates again, the optimised term is constructed.
  1.1128 +              *)
  1.1129 +             fun mk_updterm upds already
  1.1130 +                 (t as ((upd as Const (u,uT as (Type (_,[kT,_])))) $ k $ r)) =
  1.1131 +                 if Symtab.defined upds u
  1.1132 +                 then let
  1.1133 +                         fun rest already = mk_updterm upds already
  1.1134 +                      in if u mem_string already
  1.1135 +                         then (case (rest already r) of
  1.1136 +                                 Init ((sprout,skel),vars) =>
  1.1137 +                                 let
  1.1138 +                                   val n = sel_name u;
  1.1139 +                                   val (kv,kb) = K_skeleton n kT (Bound (length vars)) k;
  1.1140 +                                   val (sprout',vars')= grow u uT k kT (kv::vars) (sprout,skel);
  1.1141 +                                 in Inter (upd$kb$skel,skel,vars',add n kb [],sprout') end
  1.1142 +                               | Inter (trm,trm',vars,fmaps,sprout) =>
  1.1143 +                                 let
  1.1144 +                                   val n = sel_name u;
  1.1145 +                                   val (kv,kb) = K_skeleton n kT (Bound (length vars)) k;
  1.1146 +                                   val (sprout',vars') = grow u uT k kT (kv::vars) sprout;
  1.1147 +                                 in Inter(upd$kb$trm,trm',kv::vars',add n kb fmaps,sprout')
  1.1148 +                                 end)
  1.1149 +                         else
  1.1150 +                          (case rest (u::already) r of
  1.1151 +                             Init ((sprout,skel),vars) =>
  1.1152 +                              (case is_upd_same (sprout,skel) u k of
  1.1153 +                                 SOME (K_rec,sel,skel') =>
  1.1154 +                                 let
  1.1155 +                                   val (sprout',vars') = grow u uT k kT vars (sprout,skel);
  1.1156 +                                  in Inter(upd$(K_rec (sel$skel'))$skel,skel,vars',[],sprout')
  1.1157 +                                  end
  1.1158 +                               | NONE =>
  1.1159 +                                 let
  1.1160 +                                   val n = sel_name u;
  1.1161 +                                   val (kv,kb) = K_skeleton n kT (Bound (length vars)) k;
  1.1162 +                                 in Init ((upd$k$sprout,upd$kb$skel),kv::vars) end)
  1.1163 +                           | Inter (trm,trm',vars,fmaps,sprout) =>
  1.1164 +                               (case is_upd_same sprout u k of
  1.1165 +                                  SOME (K_rec,sel,skel) =>
  1.1166 +                                  let
  1.1167 +                                    val (sprout',vars') = grow u uT k kT vars sprout
  1.1168 +                                  in Inter(upd$(K_rec (sel$skel))$trm,trm',vars',fmaps,sprout')
  1.1169 +                                  end
  1.1170 +                                | NONE =>
  1.1171 +                                  let
  1.1172 +                                    val n = sel_name u
  1.1173 +                                    val T = domain_type kT
  1.1174 +                                    val (kv,kb) = K_skeleton n kT (Bound (length vars)) k;
  1.1175 +                                    val (sprout',vars') = grow u uT k kT (kv::vars) sprout
  1.1176 +                                    val fmaps' = add n kb fmaps
  1.1177 +                                  in Inter (upd$kb$trm,upd$comps n T fmaps'$trm'
  1.1178 +                                           ,vars',fmaps',sprout') end))
  1.1179 +                     end
  1.1180 +                 else Init (init_seed t)
  1.1181 +               | mk_updterm _ _ t = Init (init_seed t);
  1.1182 +
  1.1183 +         in (case mk_updterm updates [] t of
  1.1184 +               Inter (trm,trm',vars,_,_)
  1.1185 +                => SOME (normalize_rhs 
  1.1186 +                          (prove_split_simp thy ss rT
  1.1187 +                            (list_all(vars, Logic.mk_equals (trm, trm')))))
  1.1188 +             | _ => NONE)
  1.1189 +         end
  1.1190 +       | _ => NONE))
  1.1191 +end
  1.1192 +
  1.1193 +(* record_eq_simproc *)
  1.1194 +(* looks up the most specific record-equality.
  1.1195 + * Note on efficiency:
  1.1196 + * Testing equality of records boils down to the test of equality of all components.
  1.1197 + * Therefore the complexity is: #components * complexity for single component.
  1.1198 + * Especially if a record has a lot of components it may be better to split up
  1.1199 + * the record first and do simplification on that (record_split_simp_tac).
  1.1200 + * e.g. r(|lots of updates|) = x
  1.1201 + *
  1.1202 + *               record_eq_simproc       record_split_simp_tac
  1.1203 + * Complexity: #components * #updates     #updates
  1.1204 + *
  1.1205 + *)
  1.1206 +val record_eq_simproc =
  1.1207 +  Simplifier.simproc @{theory HOL} "record_eq_simp" ["r = s"]
  1.1208 +    (fn thy => fn _ => fn t =>
  1.1209 +      (case t of Const ("op =", Type (_, [T, _])) $ _ $ _ =>
  1.1210 +        (case rec_id (~1) T of
  1.1211 +           "" => NONE
  1.1212 +         | name => (case get_equalities thy name of
  1.1213 +                                NONE => NONE
  1.1214 +                              | SOME thm => SOME (thm RS Eq_TrueI)))
  1.1215 +       | _ => NONE));
  1.1216 +
  1.1217 +(* record_split_simproc *)
  1.1218 +(* splits quantified occurrences of records, for which P holds. P can peek on the
  1.1219 + * subterm starting at the quantified occurrence of the record (including the quantifier)
  1.1220 + * P t = 0: do not split
  1.1221 + * P t = ~1: completely split
  1.1222 + * P t > 0: split up to given bound of record extensions
  1.1223 + *)
  1.1224 +fun record_split_simproc P =
  1.1225 +  Simplifier.simproc @{theory HOL} "record_split_simp" ["x"]
  1.1226 +    (fn thy => fn _ => fn t =>
  1.1227 +      (case t of (Const (quantifier, Type (_, [Type (_, [T, _]), _])))$trm =>
  1.1228 +         if quantifier = "All" orelse quantifier = "all" orelse quantifier = "Ex"
  1.1229 +         then (case rec_id (~1) T of
  1.1230 +                 "" => NONE
  1.1231 +               | name
  1.1232 +                  => let val split = P t
  1.1233 +                     in if split <> 0 then
  1.1234 +                        (case get_splits thy (rec_id split T) of
  1.1235 +                              NONE => NONE
  1.1236 +                            | SOME (all_thm, All_thm, Ex_thm,_)
  1.1237 +                               => SOME (case quantifier of
  1.1238 +                                          "all" => all_thm
  1.1239 +                                        | "All" => All_thm RS eq_reflection
  1.1240 +                                        | "Ex"  => Ex_thm RS eq_reflection
  1.1241 +                                        | _     => error "record_split_simproc"))
  1.1242 +                        else NONE
  1.1243 +                      end)
  1.1244 +         else NONE
  1.1245 +       | _ => NONE))
  1.1246 +
  1.1247 +val record_ex_sel_eq_simproc =
  1.1248 +  Simplifier.simproc @{theory HOL} "record_ex_sel_eq_simproc" ["Ex t"]
  1.1249 +    (fn thy => fn ss => fn t =>
  1.1250 +       let
  1.1251 +         fun prove prop =
  1.1252 +           quick_and_dirty_prove true thy [] prop
  1.1253 +             (fn _ => simp_tac (Simplifier.inherit_context ss (get_simpset thy)
  1.1254 +               addsimps simp_thms addsimprocs [record_split_simproc (K ~1)]) 1);
  1.1255 +
  1.1256 +         fun mkeq (lr,Teq,(sel,Tsel),x) i =
  1.1257 +              if is_selector thy sel then
  1.1258 +                 let val x' = if not (loose_bvar1 (x,0))
  1.1259 +                              then Free ("x" ^ string_of_int i, range_type Tsel)
  1.1260 +                              else raise TERM ("",[x]);
  1.1261 +                     val sel' = Const (sel,Tsel)$Bound 0;
  1.1262 +                     val (l,r) = if lr then (sel',x') else (x',sel');
  1.1263 +                  in Const ("op =",Teq)$l$r end
  1.1264 +              else raise TERM ("",[Const (sel,Tsel)]);
  1.1265 +
  1.1266 +         fun dest_sel_eq (Const ("op =",Teq)$(Const (sel,Tsel)$Bound 0)$X) =
  1.1267 +                           (true,Teq,(sel,Tsel),X)
  1.1268 +           | dest_sel_eq (Const ("op =",Teq)$X$(Const (sel,Tsel)$Bound 0)) =
  1.1269 +                           (false,Teq,(sel,Tsel),X)
  1.1270 +           | dest_sel_eq _ = raise TERM ("",[]);
  1.1271 +
  1.1272 +       in
  1.1273 +         (case t of
  1.1274 +           (Const ("Ex",Tex)$Abs(s,T,t)) =>
  1.1275 +             (let val eq = mkeq (dest_sel_eq t) 0;
  1.1276 +                 val prop = list_all ([("r",T)],
  1.1277 +                              Logic.mk_equals (Const ("Ex",Tex)$Abs(s,T,eq),
  1.1278 +                                               HOLogic.true_const));
  1.1279 +             in SOME (prove prop) end
  1.1280 +             handle TERM _ => NONE)
  1.1281 +          | _ => NONE)
  1.1282 +         end)
  1.1283 +
  1.1284 +
  1.1285 +
  1.1286 +
  1.1287 +local
  1.1288 +val inductive_atomize = thms "induct_atomize";
  1.1289 +val inductive_rulify = thms "induct_rulify";
  1.1290 +in
  1.1291 +(* record_split_simp_tac *)
  1.1292 +(* splits (and simplifies) all records in the goal for which P holds.
  1.1293 + * For quantified occurrences of a record
  1.1294 + * P can peek on the whole subterm (including the quantifier); for free variables P
  1.1295 + * can only peek on the variable itself.
  1.1296 + * P t = 0: do not split
  1.1297 + * P t = ~1: completely split
  1.1298 + * P t > 0: split up to given bound of record extensions
  1.1299 + *)
  1.1300 +fun record_split_simp_tac thms P i st =
  1.1301 +  let
  1.1302 +    val thy = Thm.theory_of_thm st;
  1.1303 +
  1.1304 +    val has_rec = exists_Const
  1.1305 +      (fn (s, Type (_, [Type (_, [T, _]), _])) =>
  1.1306 +          (s = "all" orelse s = "All" orelse s = "Ex") andalso is_recT T
  1.1307 +        | _ => false);
  1.1308 +
  1.1309 +    val goal = nth (Thm.prems_of st) (i - 1);
  1.1310 +    val frees = List.filter (is_recT o type_of) (OldTerm.term_frees goal);
  1.1311 +
  1.1312 +    fun mk_split_free_tac free induct_thm i =
  1.1313 +        let val cfree = cterm_of thy free;
  1.1314 +            val (_$(_$r)) = concl_of induct_thm;
  1.1315 +            val crec = cterm_of thy r;
  1.1316 +            val thm  = cterm_instantiate [(crec,cfree)] induct_thm;
  1.1317 +        in EVERY [simp_tac (HOL_basic_ss addsimps inductive_atomize) i,
  1.1318 +                  rtac thm i,
  1.1319 +                  simp_tac (HOL_basic_ss addsimps inductive_rulify) i]
  1.1320 +        end;
  1.1321 +
  1.1322 +    fun split_free_tac P i (free as Free (n,T)) =
  1.1323 +        (case rec_id (~1) T of
  1.1324 +           "" => NONE
  1.1325 +         | name => let val split = P free
  1.1326 +                   in if split <> 0 then
  1.1327 +                      (case get_splits thy (rec_id split T) of
  1.1328 +                             NONE => NONE
  1.1329 +                           | SOME (_,_,_,induct_thm)
  1.1330 +                               => SOME (mk_split_free_tac free induct_thm i))
  1.1331 +                      else NONE
  1.1332 +                   end)
  1.1333 +     | split_free_tac _ _ _ = NONE;
  1.1334 +
  1.1335 +    val split_frees_tacs = List.mapPartial (split_free_tac P i) frees;
  1.1336 +
  1.1337 +    val simprocs = if has_rec goal then [record_split_simproc P] else [];
  1.1338 +    val thms' = K_comp_convs@thms
  1.1339 +  in st |> ((EVERY split_frees_tacs)
  1.1340 +           THEN (Simplifier.full_simp_tac (get_simpset thy addsimps thms' addsimprocs simprocs) i))
  1.1341 +  end handle Empty => Seq.empty;
  1.1342 +end;
  1.1343 +
  1.1344 +
  1.1345 +(* record_split_tac *)
  1.1346 +(* splits all records in the goal, which are quantified by ! or !!. *)
  1.1347 +fun record_split_tac i st =
  1.1348 +  let
  1.1349 +    val thy = Thm.theory_of_thm st;
  1.1350 +
  1.1351 +    val has_rec = exists_Const
  1.1352 +      (fn (s, Type (_, [Type (_, [T, _]), _])) =>
  1.1353 +          (s = "all" orelse s = "All") andalso is_recT T
  1.1354 +        | _ => false);
  1.1355 +
  1.1356 +    val goal = nth (Thm.prems_of st) (i - 1);
  1.1357 +
  1.1358 +    fun is_all t =
  1.1359 +      (case t of (Const (quantifier, _)$_) =>
  1.1360 +         if quantifier = "All" orelse quantifier = "all" then ~1 else 0
  1.1361 +       | _ => 0);
  1.1362 +
  1.1363 +  in if has_rec goal
  1.1364 +     then Simplifier.full_simp_tac
  1.1365 +           (HOL_basic_ss addsimprocs [record_split_simproc is_all]) i st
  1.1366 +     else Seq.empty
  1.1367 +  end handle Subscript => Seq.empty;
  1.1368 +
  1.1369 +(* wrapper *)
  1.1370 +
  1.1371 +val record_split_name = "record_split_tac";
  1.1372 +val record_split_wrapper = (record_split_name, fn tac => record_split_tac ORELSE' tac);
  1.1373 +
  1.1374 +
  1.1375 +
  1.1376 +(** theory extender interface **)
  1.1377 +
  1.1378 +(* prepare arguments *)
  1.1379 +
  1.1380 +fun read_raw_parent ctxt raw_T =
  1.1381 +  (case ProofContext.read_typ_abbrev ctxt raw_T of
  1.1382 +    Type (name, Ts) => (Ts, name)
  1.1383 +  | T => error ("Bad parent record specification: " ^ Syntax.string_of_typ ctxt T));
  1.1384 +
  1.1385 +fun read_typ ctxt raw_T env =
  1.1386 +  let
  1.1387 +    val ctxt' = fold (Variable.declare_typ o TFree) env ctxt;
  1.1388 +    val T = Syntax.read_typ ctxt' raw_T;
  1.1389 +    val env' = OldTerm.add_typ_tfrees (T, env);
  1.1390 +  in (T, env') end;
  1.1391 +
  1.1392 +fun cert_typ ctxt raw_T env =
  1.1393 +  let
  1.1394 +    val thy = ProofContext.theory_of ctxt;
  1.1395 +    val T = Type.no_tvars (Sign.certify_typ thy raw_T) handle TYPE (msg, _, _) => error msg;
  1.1396 +    val env' = OldTerm.add_typ_tfrees (T, env);
  1.1397 +  in (T, env') end;
  1.1398 +
  1.1399 +
  1.1400 +(* attributes *)
  1.1401 +
  1.1402 +fun case_names_fields x = RuleCases.case_names ["fields"] x;
  1.1403 +fun induct_type_global name = [case_names_fields, Induct.induct_type name];
  1.1404 +fun cases_type_global name = [case_names_fields, Induct.cases_type name];
  1.1405 +
  1.1406 +(* tactics *)
  1.1407 +
  1.1408 +fun simp_all_tac ss simps = ALLGOALS (Simplifier.asm_full_simp_tac (ss addsimps simps));
  1.1409 +
  1.1410 +(* do case analysis / induction according to rule on last parameter of ith subgoal
  1.1411 + * (or on s if there are no parameters);
  1.1412 + * Instatiation of record variable (and predicate) in rule is calculated to
  1.1413 + * avoid problems with higher order unification.
  1.1414 + *)
  1.1415 +
  1.1416 +fun try_param_tac s rule i st =
  1.1417 +  let
  1.1418 +    val cert = cterm_of (Thm.theory_of_thm st);
  1.1419 +    val g = nth (prems_of st) (i - 1);
  1.1420 +    val params = Logic.strip_params g;
  1.1421 +    val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl g);
  1.1422 +    val rule' = Thm.lift_rule (Thm.cprem_of st i) rule;
  1.1423 +    val (P, ys) = strip_comb (HOLogic.dest_Trueprop
  1.1424 +      (Logic.strip_assums_concl (prop_of rule')));
  1.1425 +    (* ca indicates if rule is a case analysis or induction rule *)
  1.1426 +    val (x, ca) = (case rev (Library.drop (length params, ys)) of
  1.1427 +        [] => (head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
  1.1428 +          (hd (rev (Logic.strip_assums_hyp (hd (prems_of rule')))))))), true)
  1.1429 +      | [x] => (head_of x, false));
  1.1430 +    val rule'' = cterm_instantiate (map (pairself cert) (case (rev params) of
  1.1431 +        [] => (case AList.lookup (op =) (map dest_Free (OldTerm.term_frees (prop_of st))) s of
  1.1432 +          NONE => sys_error "try_param_tac: no such variable"
  1.1433 +        | SOME T => [(P, if ca then concl else lambda (Free (s, T)) concl),
  1.1434 +            (x, Free (s, T))])
  1.1435 +      | (_, T) :: _ => [(P, list_abs (params, if ca then concl
  1.1436 +          else incr_boundvars 1 (Abs (s, T, concl)))),
  1.1437 +        (x, list_abs (params, Bound 0))])) rule'
  1.1438 +  in compose_tac (false, rule'', nprems_of rule) i st end;
  1.1439 +
  1.1440 +
  1.1441 +(* !!x1 ... xn. ... ==> EX x1 ... xn. P x1 ... xn;
  1.1442 +   instantiates x1 ... xn with parameters x1 ... xn *)
  1.1443 +fun ex_inst_tac i st =
  1.1444 +  let
  1.1445 +    val thy = Thm.theory_of_thm st;
  1.1446 +    val g = nth (prems_of st) (i - 1);
  1.1447 +    val params = Logic.strip_params g;
  1.1448 +    val exI' = Thm.lift_rule (Thm.cprem_of st i) exI;
  1.1449 +    val (_$(_$x)) = Logic.strip_assums_concl (hd (prems_of exI'));
  1.1450 +    val cx = cterm_of thy (fst (strip_comb x));
  1.1451 +
  1.1452 +  in Seq.single (Library.foldl (fn (st,v) =>
  1.1453 +        Seq.hd
  1.1454 +        (compose_tac (false, cterm_instantiate
  1.1455 +                                [(cx,cterm_of thy (list_abs (params,Bound v)))] exI',1)
  1.1456 +                i st)) (st,((length params) - 1) downto 0))
  1.1457 +  end;
  1.1458 +
  1.1459 +fun extension_typedef name repT alphas thy =
  1.1460 +  let
  1.1461 +    fun get_thms thy name =
  1.1462 +      let
  1.1463 +        val SOME { Abs_induct = abs_induct,
  1.1464 +          Abs_inject=abs_inject, Abs_inverse = abs_inverse, ...} = Typedef.get_info thy name;
  1.1465 +        val rewrite_rule = MetaSimplifier.rewrite_rule [rec_UNIV_I, rec_True_simp];
  1.1466 +      in map rewrite_rule [abs_inject, abs_inverse, abs_induct] end;
  1.1467 +    val tname = Binding.name (Long_Name.base_name name);
  1.1468 +  in
  1.1469 +    thy
  1.1470 +    |> Typecopy.typecopy (Binding.suffix_name ext_typeN tname, alphas) repT NONE
  1.1471 +    |-> (fn (name, _) => `(fn thy => get_thms thy name))
  1.1472 +  end;
  1.1473 +
  1.1474 +fun mixit convs refls =
  1.1475 +  let fun f ((res,lhs,rhs),refl) = ((refl,List.revAppend (lhs,refl::tl rhs))::res,hd rhs::lhs,tl rhs);
  1.1476 +  in #1 (Library.foldl f (([],[],convs),refls)) end;
  1.1477 +
  1.1478 +
  1.1479 +fun extension_definition full name fields names alphas zeta moreT more vars thy =
  1.1480 +  let
  1.1481 +    val base = Long_Name.base_name;
  1.1482 +    val fieldTs = (map snd fields);
  1.1483 +    val alphas_zeta = alphas@[zeta];
  1.1484 +    val alphas_zetaTs = map (fn n => TFree (n, HOLogic.typeS)) alphas_zeta;
  1.1485 +    val vT = TFree (Name.variant alphas_zeta "'v", HOLogic.typeS);
  1.1486 +    val extT_name = suffix ext_typeN name
  1.1487 +    val extT = Type (extT_name, alphas_zetaTs);
  1.1488 +    val repT = foldr1 HOLogic.mk_prodT (fieldTs@[moreT]);
  1.1489 +    val fields_more = fields@[(full moreN,moreT)];
  1.1490 +    val fields_moreTs = fieldTs@[moreT];
  1.1491 +    val bfields_more = map (apfst base) fields_more;
  1.1492 +    val r = Free (rN,extT)
  1.1493 +    val len = length fields;
  1.1494 +    val idxms = 0 upto len;
  1.1495 +
  1.1496 +    (* prepare declarations and definitions *)
  1.1497 +
  1.1498 +    (*fields constructor*)
  1.1499 +    val ext_decl = (mk_extC (name,extT) fields_moreTs);
  1.1500 +    (*
  1.1501 +    val ext_spec = Const ext_decl :==
  1.1502 +         (foldr (uncurry lambda)
  1.1503 +            (mk_Abs name repT extT $ (foldr1 HOLogic.mk_prod (vars@[more]))) (vars@[more]))
  1.1504 +    *)
  1.1505 +    val ext_spec = list_comb (Const ext_decl,vars@[more]) :==
  1.1506 +         (mk_Abs name repT extT $ (foldr1 HOLogic.mk_prod (vars@[more])));
  1.1507 +
  1.1508 +    fun mk_ext args = list_comb (Const ext_decl, args);
  1.1509 +
  1.1510 +    (*destructors*)
  1.1511 +    val _ = timing_msg "record extension preparing definitions";
  1.1512 +    val dest_decls = map (mk_selC extT o (apfst (suffix ext_dest))) bfields_more;
  1.1513 +
  1.1514 +    fun mk_dest_spec (i, (c,T)) =
  1.1515 +      let val snds = (funpow i HOLogic.mk_snd (mk_Rep name repT extT $ r))
  1.1516 +      in Const (mk_selC extT (suffix ext_dest c,T))
  1.1517 +         :== (lambda r (if i=len then snds else HOLogic.mk_fst snds))
  1.1518 +      end;
  1.1519 +    val dest_specs =
  1.1520 +      ListPair.map mk_dest_spec (idxms, fields_more);
  1.1521 +
  1.1522 +    (*updates*)
  1.1523 +    val upd_decls = map (mk_updC updN extT) bfields_more;
  1.1524 +    fun mk_upd_spec (c,T) =
  1.1525 +      let
  1.1526 +        val args = map (fn (n,nT) => if n=c then Free (base c,T --> T)$
  1.1527 +                                                  (mk_sel r (suffix ext_dest n,nT))
  1.1528 +                                     else (mk_sel r (suffix ext_dest n,nT)))
  1.1529 +                       fields_more;
  1.1530 +      in Const (mk_updC updN extT (c,T))$(Free (base c,T --> T))$r
  1.1531 +          :== mk_ext args
  1.1532 +      end;
  1.1533 +    val upd_specs = map mk_upd_spec fields_more;
  1.1534 +
  1.1535 +    (* 1st stage: defs_thy *)
  1.1536 +    fun mk_defs () =
  1.1537 +      thy
  1.1538 +      |> extension_typedef name repT (alphas @ [zeta])
  1.1539 +      ||> Sign.add_consts_i
  1.1540 +            (map (Syntax.no_syn o apfst Binding.name) (apfst base ext_decl :: dest_decls @ upd_decls))
  1.1541 +      ||>> PureThy.add_defs false
  1.1542 +            (map (Thm.no_attributes o apfst Binding.name) (ext_spec :: dest_specs))
  1.1543 +      ||>> PureThy.add_defs false
  1.1544 +            (map (Thm.no_attributes o apfst Binding.name) upd_specs)
  1.1545 +      |-> (fn args as ((_, dest_defs), upd_defs) =>
  1.1546 +          fold Code.add_default_eqn dest_defs
  1.1547 +          #> fold Code.add_default_eqn upd_defs
  1.1548 +          #> pair args);
  1.1549 +    val ((([abs_inject, abs_inverse, abs_induct], ext_def :: dest_defs), upd_defs), defs_thy) =
  1.1550 +      timeit_msg "record extension type/selector/update defs:" mk_defs;
  1.1551 +
  1.1552 +    (* prepare propositions *)
  1.1553 +    val _ = timing_msg "record extension preparing propositions";
  1.1554 +    val vars_more = vars@[more];
  1.1555 +    val named_vars_more = (names@[full moreN])~~vars_more;
  1.1556 +    val variants = map (fn (Free (x,_))=>x) vars_more;
  1.1557 +    val ext = mk_ext vars_more;
  1.1558 +    val s     = Free (rN, extT);
  1.1559 +    val w     = Free (wN, extT);
  1.1560 +    val P = Free (Name.variant variants "P", extT-->HOLogic.boolT);
  1.1561 +    val C = Free (Name.variant variants "C", HOLogic.boolT);
  1.1562 +
  1.1563 +    val inject_prop =
  1.1564 +      let val vars_more' = map (fn (Free (x,T)) => Free (x ^ "'",T)) vars_more;
  1.1565 +      in All (map dest_Free (vars_more@vars_more'))
  1.1566 +          ((HOLogic.eq_const extT $
  1.1567 +            mk_ext vars_more$mk_ext vars_more')
  1.1568 +           ===
  1.1569 +           foldr1 HOLogic.mk_conj (map HOLogic.mk_eq (vars_more ~~ vars_more')))
  1.1570 +      end;
  1.1571 +
  1.1572 +    val induct_prop =
  1.1573 +      (All (map dest_Free vars_more) (Trueprop (P $ ext)), Trueprop (P $ s));
  1.1574 +
  1.1575 +    val cases_prop =
  1.1576 +      (All (map dest_Free vars_more)
  1.1577 +        (Trueprop (HOLogic.mk_eq (s,ext)) ==> Trueprop C))
  1.1578 +      ==> Trueprop C;
  1.1579 +
  1.1580 +    (*destructors*)
  1.1581 +    val dest_conv_props =
  1.1582 +       map (fn (c, x as Free (_,T)) => mk_sel ext (suffix ext_dest c,T) === x) named_vars_more;
  1.1583 +
  1.1584 +    (*updates*)
  1.1585 +    fun mk_upd_prop (i,(c,T)) =
  1.1586 +      let val x' = Free (Name.variant variants (base c ^ "'"),T --> T)
  1.1587 +          val args' = nth_map i  (K (x'$nth vars_more i)) vars_more
  1.1588 +      in mk_upd updN c x' ext === mk_ext args'  end;
  1.1589 +    val upd_conv_props = ListPair.map mk_upd_prop (idxms, fields_more);
  1.1590 +
  1.1591 +    val surjective_prop =
  1.1592 +      let val args =
  1.1593 +           map (fn (c, Free (_,T)) => mk_sel s (suffix ext_dest c,T)) named_vars_more;
  1.1594 +      in s === mk_ext args end;
  1.1595 +
  1.1596 +    val split_meta_prop =
  1.1597 +      let val P = Free (Name.variant variants "P", extT-->Term.propT) in
  1.1598 +        Logic.mk_equals
  1.1599 +         (All [dest_Free s] (P $ s), All (map dest_Free vars_more) (P $ ext))
  1.1600 +      end;
  1.1601 +
  1.1602 +    fun prove stndrd = quick_and_dirty_prove stndrd defs_thy;
  1.1603 +    val prove_standard = quick_and_dirty_prove true defs_thy;
  1.1604 +    fun prove_simp stndrd simps =
  1.1605 +      let val tac = simp_all_tac HOL_ss simps
  1.1606 +      in fn prop => prove stndrd [] prop (K tac) end;
  1.1607 +
  1.1608 +    fun inject_prf () = (prove_simp true [ext_def,abs_inject,Pair_eq] inject_prop);
  1.1609 +    val inject = timeit_msg "record extension inject proof:" inject_prf;
  1.1610 +
  1.1611 +    fun induct_prf () =
  1.1612 +      let val (assm, concl) = induct_prop
  1.1613 +      in prove_standard [assm] concl (fn {prems, ...} =>
  1.1614 +           EVERY [try_param_tac rN abs_induct 1,
  1.1615 +                  simp_tac (HOL_ss addsimps [split_paired_all]) 1,
  1.1616 +                  resolve_tac (map (rewrite_rule [ext_def]) prems) 1])
  1.1617 +      end;
  1.1618 +    val induct = timeit_msg "record extension induct proof:" induct_prf;
  1.1619 +
  1.1620 +    fun cases_prf_opt () =
  1.1621 +      let
  1.1622 +        val (_$(Pvar$_)) = concl_of induct;
  1.1623 +        val ind = cterm_instantiate
  1.1624 +                    [(cterm_of defs_thy Pvar, cterm_of defs_thy
  1.1625 +                            (lambda w (HOLogic.imp$HOLogic.mk_eq(r,w)$C)))]
  1.1626 +                    induct;
  1.1627 +        in standard (ObjectLogic.rulify (mp OF [ind, refl])) end;
  1.1628 +
  1.1629 +    fun cases_prf_noopt () =
  1.1630 +        prove_standard [] cases_prop (fn _ =>
  1.1631 +         EVERY [asm_full_simp_tac (HOL_basic_ss addsimps [atomize_all, atomize_imp]) 1,
  1.1632 +                try_param_tac rN induct 1,
  1.1633 +                rtac impI 1,
  1.1634 +                REPEAT (etac allE 1),
  1.1635 +                etac mp 1,
  1.1636 +                rtac refl 1])
  1.1637 +
  1.1638 +    val cases_prf = quick_and_dirty_prf cases_prf_noopt cases_prf_opt;
  1.1639 +    val cases = timeit_msg "record extension cases proof:" cases_prf;
  1.1640 +
  1.1641 +    fun dest_convs_prf () = map (prove_simp false
  1.1642 +                      ([ext_def,abs_inverse]@Pair_sel_convs@dest_defs)) dest_conv_props;
  1.1643 +    val dest_convs = timeit_msg "record extension dest_convs proof:" dest_convs_prf;
  1.1644 +    fun dest_convs_standard_prf () = map standard dest_convs;
  1.1645 +
  1.1646 +    val dest_convs_standard =
  1.1647 +        timeit_msg "record extension dest_convs_standard proof:" dest_convs_standard_prf;
  1.1648 +
  1.1649 +    fun upd_convs_prf_noopt () = map (prove_simp true (dest_convs_standard@upd_defs))
  1.1650 +                                       upd_conv_props;
  1.1651 +    fun upd_convs_prf_opt () =
  1.1652 +      let
  1.1653 +
  1.1654 +        fun mkrefl (c,T) = Thm.reflexive
  1.1655 +                    (cterm_of defs_thy (Free (Name.variant variants (base c ^ "'"),T-->T)));
  1.1656 +        val refls = map mkrefl fields_more;
  1.1657 +        val dest_convs' = map mk_meta_eq dest_convs;
  1.1658 +        val map_eqs = map (uncurry Thm.combination) (refls ~~ dest_convs');
  1.1659 +
  1.1660 +        val constr_refl = Thm.reflexive (cterm_of defs_thy (head_of ext));
  1.1661 +
  1.1662 +        fun mkthm (udef,(fld_refl,thms)) =
  1.1663 +          let val bdyeq = Library.foldl (uncurry Thm.combination) (constr_refl,thms);
  1.1664 +               (* (|N=N (|N=N,M=M,K=K,more=more|)
  1.1665 +                    M=M (|N=N,M=M,K=K,more=more|)
  1.1666 +                    K=K'
  1.1667 +                    more = more (|N=N,M=M,K=K,more=more|) =
  1.1668 +                  (|N=N,M=M,K=K',more=more|)
  1.1669 +                *)
  1.1670 +              val (_$(_$v$r)$_) = prop_of udef;
  1.1671 +              val (_$(v'$_)$_) = prop_of fld_refl;
  1.1672 +              val udef' = cterm_instantiate
  1.1673 +                            [(cterm_of defs_thy v,cterm_of defs_thy v'),
  1.1674 +                             (cterm_of defs_thy r,cterm_of defs_thy ext)] udef;
  1.1675 +          in  standard (Thm.transitive udef' bdyeq) end;
  1.1676 +      in map mkthm (rev upd_defs  ~~ (mixit dest_convs' map_eqs)) end;
  1.1677 +
  1.1678 +    val upd_convs_prf = quick_and_dirty_prf upd_convs_prf_noopt upd_convs_prf_opt;
  1.1679 +
  1.1680 +    val upd_convs =
  1.1681 +         timeit_msg "record extension upd_convs proof:" upd_convs_prf;
  1.1682 +
  1.1683 +    fun surjective_prf () =
  1.1684 +      prove_standard [] surjective_prop (fn _ =>
  1.1685 +          (EVERY [try_param_tac rN induct 1,
  1.1686 +                  simp_tac (HOL_basic_ss addsimps dest_convs_standard) 1]));
  1.1687 +    val surjective = timeit_msg "record extension surjective proof:" surjective_prf;
  1.1688 +
  1.1689 +    fun split_meta_prf () =
  1.1690 +        prove_standard [] split_meta_prop (fn _ =>
  1.1691 +         EVERY [rtac equal_intr_rule 1, Goal.norm_hhf_tac 1,
  1.1692 +                etac meta_allE 1, atac 1,
  1.1693 +                rtac (prop_subst OF [surjective]) 1,
  1.1694 +                REPEAT (etac meta_allE 1), atac 1]);
  1.1695 +    val split_meta = timeit_msg "record extension split_meta proof:" split_meta_prf;
  1.1696 +
  1.1697 +
  1.1698 +    val (([inject',induct',cases',surjective',split_meta'],
  1.1699 +          [dest_convs',upd_convs']),
  1.1700 +      thm_thy) =
  1.1701 +      defs_thy
  1.1702 +      |> (PureThy.add_thms o map (Thm.no_attributes o apfst Binding.name))
  1.1703 +           [("ext_inject", inject),
  1.1704 +            ("ext_induct", induct),
  1.1705 +            ("ext_cases", cases),
  1.1706 +            ("ext_surjective", surjective),
  1.1707 +            ("ext_split", split_meta)]
  1.1708 +      ||>> (PureThy.add_thmss o map (Thm.no_attributes o apfst Binding.name))
  1.1709 +            [("dest_convs", dest_convs_standard), ("upd_convs", upd_convs)]
  1.1710 +
  1.1711 +  in (thm_thy,extT,induct',inject',dest_convs',split_meta',upd_convs')
  1.1712 +  end;
  1.1713 +
  1.1714 +fun chunks []      []   = []
  1.1715 +  | chunks []      xs   = [xs]
  1.1716 +  | chunks (l::ls) xs  = Library.take (l,xs)::chunks ls (Library.drop (l,xs));
  1.1717 +
  1.1718 +fun chop_last [] = error "last: list should not be empty"
  1.1719 +  | chop_last [x] = ([],x)
  1.1720 +  | chop_last (x::xs) = let val (tl,l) = chop_last xs in (x::tl,l) end;
  1.1721 +
  1.1722 +fun subst_last s []      = error "subst_last: list should not be empty"
  1.1723 +  | subst_last s ([x])   = [s]
  1.1724 +  | subst_last s (x::xs) = (x::subst_last s xs);
  1.1725 +
  1.1726 +(* mk_recordT builds up the record type from the current extension tpye extT and a list
  1.1727 + * of parent extensions, starting with the root of the record hierarchy
  1.1728 +*)
  1.1729 +fun mk_recordT extT =
  1.1730 +    fold_rev (fn (parent, Ts) => fn T => Type (parent, subst_last T Ts)) extT;
  1.1731 +
  1.1732 +
  1.1733 +
  1.1734 +fun obj_to_meta_all thm =
  1.1735 +  let
  1.1736 +    fun E thm = case (SOME (spec OF [thm]) handle THM _ => NONE) of
  1.1737 +                  SOME thm' => E thm'
  1.1738 +                | NONE => thm;
  1.1739 +    val th1 = E thm;
  1.1740 +    val th2 = Drule.forall_intr_vars th1;
  1.1741 +  in th2 end;
  1.1742 +
  1.1743 +fun meta_to_obj_all thm =
  1.1744 +  let
  1.1745 +    val thy = Thm.theory_of_thm thm;
  1.1746 +    val prop = Thm.prop_of thm;
  1.1747 +    val params = Logic.strip_params prop;
  1.1748 +    val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl prop);
  1.1749 +    val ct = cterm_of thy
  1.1750 +      (HOLogic.mk_Trueprop (HOLogic.list_all (params, concl)));
  1.1751 +    val thm' = Seq.hd (REPEAT (rtac allI 1) (Thm.trivial ct));
  1.1752 +  in
  1.1753 +    Thm.implies_elim thm' thm
  1.1754 +  end;
  1.1755 +
  1.1756 +
  1.1757 +
  1.1758 +(* record_definition *)
  1.1759 +
  1.1760 +fun record_definition (args, bname) parent (parents: parent_info list) raw_fields thy =
  1.1761 +  let
  1.1762 +    val external_names = NameSpace.external_names (Sign.naming_of thy);
  1.1763 +
  1.1764 +    val alphas = map fst args;
  1.1765 +    val name = Sign.full_bname thy bname;
  1.1766 +    val full = Sign.full_bname_path thy bname;
  1.1767 +    val base = Long_Name.base_name;
  1.1768 +
  1.1769 +    val (bfields, field_syntax) = split_list (map (fn (x, T, mx) => ((x, T), mx)) raw_fields);
  1.1770 +
  1.1771 +    val parent_fields = List.concat (map #fields parents);
  1.1772 +    val parent_chunks = map (length o #fields) parents;
  1.1773 +    val parent_names = map fst parent_fields;
  1.1774 +    val parent_types = map snd parent_fields;
  1.1775 +    val parent_fields_len = length parent_fields;
  1.1776 +    val parent_variants = Name.variant_list [moreN, rN, rN ^ "'", wN] (map base parent_names);
  1.1777 +    val parent_vars = ListPair.map Free (parent_variants, parent_types);
  1.1778 +    val parent_len = length parents;
  1.1779 +    val parents_idx = (map #name parents) ~~ (0 upto (parent_len - 1));
  1.1780 +
  1.1781 +    val fields = map (apfst full) bfields;
  1.1782 +    val names = map fst fields;
  1.1783 +    val extN = full bname;
  1.1784 +    val types = map snd fields;
  1.1785 +    val alphas_fields = List.foldr OldTerm.add_typ_tfree_names [] types;
  1.1786 +    val alphas_ext = alphas inter alphas_fields;
  1.1787 +    val len = length fields;
  1.1788 +    val variants =
  1.1789 +      Name.variant_list (moreN :: rN :: (rN ^ "'") :: wN :: parent_variants) (map fst bfields);
  1.1790 +    val vars = ListPair.map Free (variants, types);
  1.1791 +    val named_vars = names ~~ vars;
  1.1792 +    val idxs = 0 upto (len - 1);
  1.1793 +    val idxms = 0 upto len;
  1.1794 +
  1.1795 +    val all_fields = parent_fields @ fields;
  1.1796 +    val all_names = parent_names @ names;
  1.1797 +    val all_types = parent_types @ types;
  1.1798 +    val all_len = parent_fields_len + len;
  1.1799 +    val all_variants = parent_variants @ variants;
  1.1800 +    val all_vars = parent_vars @ vars;
  1.1801 +    val all_named_vars = (parent_names ~~ parent_vars) @ named_vars;
  1.1802 +
  1.1803 +
  1.1804 +    val zeta = Name.variant alphas "'z";
  1.1805 +    val moreT = TFree (zeta, HOLogic.typeS);
  1.1806 +    val more = Free (moreN, moreT);
  1.1807 +    val full_moreN = full moreN;
  1.1808 +    val bfields_more = bfields @ [(moreN,moreT)];
  1.1809 +    val fields_more = fields @ [(full_moreN,moreT)];
  1.1810 +    val vars_more = vars @ [more];
  1.1811 +    val named_vars_more = named_vars @[(full_moreN,more)];
  1.1812 +    val all_vars_more = all_vars @ [more];
  1.1813 +    val all_named_vars_more = all_named_vars @ [(full_moreN,more)];
  1.1814 +
  1.1815 +    (* 1st stage: extension_thy *)
  1.1816 +    val (extension_thy,extT,ext_induct,ext_inject,ext_dest_convs,ext_split,u_convs) =
  1.1817 +      thy
  1.1818 +      |> Sign.add_path bname
  1.1819 +      |> extension_definition full extN fields names alphas_ext zeta moreT more vars;
  1.1820 +
  1.1821 +    val _ = timing_msg "record preparing definitions";
  1.1822 +    val Type extension_scheme = extT;
  1.1823 +    val extension_name = unsuffix ext_typeN (fst extension_scheme);
  1.1824 +    val extension = let val (n,Ts) = extension_scheme in (n,subst_last HOLogic.unitT Ts) end;
  1.1825 +    val extension_names =
  1.1826 +         (map ((unsuffix ext_typeN) o fst o #extension) parents) @ [extN];
  1.1827 +    val extension_id = Library.foldl (op ^) ("",extension_names);
  1.1828 +
  1.1829 +
  1.1830 +    fun rec_schemeT n = mk_recordT (map #extension (prune n parents)) extT;
  1.1831 +    val rec_schemeT0 = rec_schemeT 0;
  1.1832 +
  1.1833 +    fun recT n =
  1.1834 +      let val (c,Ts) = extension
  1.1835 +      in mk_recordT (map #extension (prune n parents)) (Type (c,subst_last HOLogic.unitT Ts))
  1.1836 +      end;
  1.1837 +    val recT0 = recT 0;
  1.1838 +
  1.1839 +    fun mk_rec args n =
  1.1840 +      let val (args',more) = chop_last args;
  1.1841 +          fun mk_ext' (((name,T),args),more) = mk_ext (name,T) (args@[more]);
  1.1842 +          fun build Ts =
  1.1843 +           List.foldr mk_ext' more (prune n (extension_names ~~ Ts ~~ (chunks parent_chunks args')))
  1.1844 +      in
  1.1845 +        if more = HOLogic.unit
  1.1846 +        then build (map recT (0 upto parent_len))
  1.1847 +        else build (map rec_schemeT (0 upto parent_len))
  1.1848 +      end;
  1.1849 +
  1.1850 +    val r_rec0 = mk_rec all_vars_more 0;
  1.1851 +    val r_rec_unit0 = mk_rec (all_vars@[HOLogic.unit]) 0;
  1.1852 +
  1.1853 +    fun r n = Free (rN, rec_schemeT n)
  1.1854 +    val r0 = r 0;
  1.1855 +    fun r_unit n = Free (rN, recT n)
  1.1856 +    val r_unit0 = r_unit 0;
  1.1857 +    val w = Free (wN, rec_schemeT 0)
  1.1858 +
  1.1859 +    (* prepare print translation functions *)
  1.1860 +    val field_tr's =
  1.1861 +      print_translation (distinct (op =) (maps external_names (full_moreN :: names)));
  1.1862 +
  1.1863 +    val adv_ext_tr's =
  1.1864 +    let
  1.1865 +      val trnames = external_names extN;
  1.1866 +    in map (gen_record_tr') trnames end;
  1.1867 +
  1.1868 +    val adv_record_type_abbr_tr's =
  1.1869 +      let val trnames = external_names (hd extension_names);
  1.1870 +          val lastExt = unsuffix ext_typeN (fst extension);
  1.1871 +      in map (gen_record_type_abbr_tr' name alphas zeta lastExt rec_schemeT0) trnames
  1.1872 +      end;
  1.1873 +
  1.1874 +    val adv_record_type_tr's =
  1.1875 +      let val trnames = if parent_len > 0 then external_names extN else [];
  1.1876 +                        (* avoid conflict with adv_record_type_abbr_tr's *)
  1.1877 +      in map (gen_record_type_tr') trnames
  1.1878 +      end;
  1.1879 +
  1.1880 +
  1.1881 +    (* prepare declarations *)
  1.1882 +
  1.1883 +    val sel_decls = map (mk_selC rec_schemeT0) bfields_more;
  1.1884 +    val upd_decls = map (mk_updC updateN rec_schemeT0) bfields_more;
  1.1885 +    val make_decl = (makeN, all_types ---> recT0);
  1.1886 +    val fields_decl = (fields_selN, types ---> Type extension);
  1.1887 +    val extend_decl = (extendN, recT0 --> moreT --> rec_schemeT0);
  1.1888 +    val truncate_decl = (truncateN, rec_schemeT0 --> recT0);
  1.1889 +
  1.1890 +    (* prepare definitions *)
  1.1891 +
  1.1892 +    fun parent_more s =
  1.1893 +         if null parents then s
  1.1894 +         else mk_sel s (Long_Name.qualify (#name (List.last parents)) moreN, extT);
  1.1895 +
  1.1896 +    fun parent_more_upd v s =
  1.1897 +      if null parents then v$s
  1.1898 +      else let val mp = Long_Name.qualify (#name (List.last parents)) moreN;
  1.1899 +           in mk_upd updateN mp v s end;
  1.1900 +
  1.1901 +    (*record (scheme) type abbreviation*)
  1.1902 +    val recordT_specs =
  1.1903 +      [(Binding.name (suffix schemeN bname), alphas @ [zeta], rec_schemeT0, Syntax.NoSyn),
  1.1904 +        (Binding.name bname, alphas, recT0, Syntax.NoSyn)];
  1.1905 +
  1.1906 +    (*selectors*)
  1.1907 +    fun mk_sel_spec (c,T) =
  1.1908 +         Const (mk_selC rec_schemeT0 (c,T))
  1.1909 +          :== (lambda r0 (Const (mk_selC extT (suffix ext_dest c,T))$parent_more r0));
  1.1910 +    val sel_specs = map mk_sel_spec fields_more;
  1.1911 +
  1.1912 +    (*updates*)
  1.1913 +
  1.1914 +    fun mk_upd_spec (c,T) =
  1.1915 +      let
  1.1916 +        val new = mk_upd' updN c (Free (base c,T-->T)) extT(*(parent_more r0)*);
  1.1917 +      in Const (mk_updC updateN rec_schemeT0 (c,T))$(Free (base c,T-->T))$r0
  1.1918 +          :== (parent_more_upd new r0)
  1.1919 +      end;
  1.1920 +    val upd_specs = map mk_upd_spec fields_more;
  1.1921 +
  1.1922 +    (*derived operations*)
  1.1923 +    val make_spec = Const (full makeN, all_types ---> recT0) $$ all_vars :==
  1.1924 +      mk_rec (all_vars @ [HOLogic.unit]) 0;
  1.1925 +    val fields_spec = Const (full fields_selN, types ---> Type extension) $$ vars :==
  1.1926 +      mk_rec (all_vars @ [HOLogic.unit]) parent_len;
  1.1927 +    val extend_spec =
  1.1928 +      Const (full extendN, recT0-->moreT-->rec_schemeT0) $ r_unit0 $ more :==
  1.1929 +      mk_rec ((map (mk_sel r_unit0) all_fields) @ [more]) 0;
  1.1930 +    val truncate_spec = Const (full truncateN, rec_schemeT0 --> recT0) $ r0 :==
  1.1931 +      mk_rec ((map (mk_sel r0) all_fields) @ [HOLogic.unit]) 0;
  1.1932 +
  1.1933 +    (* 2st stage: defs_thy *)
  1.1934 +
  1.1935 +    fun mk_defs () =
  1.1936 +      extension_thy
  1.1937 +      |> Sign.add_trfuns
  1.1938 +          ([],[],field_tr's, [])
  1.1939 +      |> Sign.add_advanced_trfuns
  1.1940 +          ([],[],adv_ext_tr's @ adv_record_type_tr's @ adv_record_type_abbr_tr's,[])
  1.1941 +      |> Sign.parent_path
  1.1942 +      |> Sign.add_tyabbrs_i recordT_specs
  1.1943 +      |> Sign.add_path bname
  1.1944 +      |> Sign.add_consts_i
  1.1945 +          (map2 (fn (x, T) => fn mx => (Binding.name x, T, mx))
  1.1946 +            sel_decls (field_syntax @ [Syntax.NoSyn]))
  1.1947 +      |> (Sign.add_consts_i o map (fn (x, T) => (Binding.name x, T, Syntax.NoSyn)))
  1.1948 +          (upd_decls @ [make_decl, fields_decl, extend_decl, truncate_decl])
  1.1949 +      |> ((PureThy.add_defs false o map (Thm.no_attributes o apfst Binding.name)) sel_specs)
  1.1950 +      ||>> ((PureThy.add_defs false o map (Thm.no_attributes o apfst Binding.name)) upd_specs)
  1.1951 +      ||>> ((PureThy.add_defs false o map (Thm.no_attributes o apfst Binding.name))
  1.1952 +             [make_spec, fields_spec, extend_spec, truncate_spec])
  1.1953 +      |-> (fn defs as ((sel_defs, upd_defs), derived_defs) =>
  1.1954 +          fold Code.add_default_eqn sel_defs
  1.1955 +          #> fold Code.add_default_eqn upd_defs
  1.1956 +          #> fold Code.add_default_eqn derived_defs
  1.1957 +          #> pair defs)
  1.1958 +    val (((sel_defs, upd_defs), derived_defs), defs_thy) =
  1.1959 +      timeit_msg "record trfuns/tyabbrs/selectors/updates/make/fields/extend/truncate defs:"
  1.1960 +        mk_defs;
  1.1961 +
  1.1962 +
  1.1963 +    (* prepare propositions *)
  1.1964 +    val _ = timing_msg "record preparing propositions";
  1.1965 +    val P = Free (Name.variant all_variants "P", rec_schemeT0-->HOLogic.boolT);
  1.1966 +    val C = Free (Name.variant all_variants "C", HOLogic.boolT);
  1.1967 +    val P_unit = Free (Name.variant all_variants "P", recT0-->HOLogic.boolT);
  1.1968 +
  1.1969 +    (*selectors*)
  1.1970 +    val sel_conv_props =
  1.1971 +       map (fn (c, x as Free (_,T)) => mk_sel r_rec0 (c,T) === x) named_vars_more;
  1.1972 +
  1.1973 +    (*updates*)
  1.1974 +    fun mk_upd_prop (i,(c,T)) =
  1.1975 +      let val x' = Free (Name.variant all_variants (base c ^ "'"),T-->T);
  1.1976 +          val n = parent_fields_len + i;
  1.1977 +          val args' = nth_map n (K (x'$nth all_vars_more n)) all_vars_more
  1.1978 +      in mk_upd updateN c x' r_rec0 === mk_rec args' 0  end;
  1.1979 +    val upd_conv_props = ListPair.map mk_upd_prop (idxms, fields_more);
  1.1980 +
  1.1981 +    (*induct*)
  1.1982 +    val induct_scheme_prop =
  1.1983 +      All (map dest_Free all_vars_more) (Trueprop (P $ r_rec0)) ==> Trueprop (P $ r0);
  1.1984 +    val induct_prop =
  1.1985 +      (All (map dest_Free all_vars) (Trueprop (P_unit $ r_rec_unit0)),
  1.1986 +       Trueprop (P_unit $ r_unit0));
  1.1987 +
  1.1988 +    (*surjective*)
  1.1989 +    val surjective_prop =
  1.1990 +      let val args = map (fn (c,Free (_,T)) => mk_sel r0 (c,T)) all_named_vars_more
  1.1991 +      in r0 === mk_rec args 0 end;
  1.1992 +
  1.1993 +    (*cases*)
  1.1994 +    val cases_scheme_prop =
  1.1995 +      (All (map dest_Free all_vars_more)
  1.1996 +        (Trueprop (HOLogic.mk_eq (r0,r_rec0)) ==> Trueprop C))
  1.1997 +      ==> Trueprop C;
  1.1998 +
  1.1999 +    val cases_prop =
  1.2000 +      (All (map dest_Free all_vars)
  1.2001 +        (Trueprop (HOLogic.mk_eq (r_unit0,r_rec_unit0)) ==> Trueprop C))
  1.2002 +       ==> Trueprop C;
  1.2003 +
  1.2004 +    (*split*)
  1.2005 +    val split_meta_prop =
  1.2006 +      let val P = Free (Name.variant all_variants "P", rec_schemeT0-->Term.propT) in
  1.2007 +        Logic.mk_equals
  1.2008 +         (All [dest_Free r0] (P $ r0), All (map dest_Free all_vars_more) (P $ r_rec0))
  1.2009 +      end;
  1.2010 +
  1.2011 +    val split_object_prop =
  1.2012 +      let fun ALL vs t = List.foldr (fn ((v,T),t) => HOLogic.mk_all (v,T,t)) t vs
  1.2013 +      in (ALL [dest_Free r0] (P $ r0)) === (ALL (map dest_Free all_vars_more) (P $ r_rec0))
  1.2014 +      end;
  1.2015 +
  1.2016 +
  1.2017 +    val split_ex_prop =
  1.2018 +      let fun EX vs t = List.foldr (fn ((v,T),t) => HOLogic.mk_exists (v,T,t)) t vs
  1.2019 +      in (EX [dest_Free r0] (P $ r0)) === (EX (map dest_Free all_vars_more) (P $ r_rec0))
  1.2020 +      end;
  1.2021 +
  1.2022 +    (*equality*)
  1.2023 +    val equality_prop =
  1.2024 +      let
  1.2025 +        val s' = Free (rN ^ "'", rec_schemeT0)
  1.2026 +        fun mk_sel_eq (c,Free (_,T)) =  mk_sel r0 (c,T) === mk_sel s' (c,T)
  1.2027 +        val seleqs = map mk_sel_eq all_named_vars_more
  1.2028 +      in All (map dest_Free [r0,s']) (Logic.list_implies (seleqs,r0 === s')) end;
  1.2029 +
  1.2030 +    (* 3rd stage: thms_thy *)
  1.2031 +
  1.2032 +    fun prove stndrd = quick_and_dirty_prove stndrd defs_thy;
  1.2033 +    val prove_standard = quick_and_dirty_prove true defs_thy;
  1.2034 +
  1.2035 +    fun prove_simp stndrd ss simps =
  1.2036 +      let val tac = simp_all_tac ss simps
  1.2037 +      in fn prop => prove stndrd [] prop (K tac) end;
  1.2038 +
  1.2039 +    val ss = get_simpset defs_thy;
  1.2040 +
  1.2041 +    fun sel_convs_prf () = map (prove_simp false ss
  1.2042 +                           (sel_defs@ext_dest_convs)) sel_conv_props;
  1.2043 +    val sel_convs = timeit_msg "record sel_convs proof:" sel_convs_prf;
  1.2044 +    fun sel_convs_standard_prf () = map standard sel_convs
  1.2045 +    val sel_convs_standard =
  1.2046 +          timeit_msg "record sel_convs_standard proof:" sel_convs_standard_prf;
  1.2047 +
  1.2048 +    fun upd_convs_prf () =
  1.2049 +          map (prove_simp true ss (upd_defs@u_convs)) upd_conv_props;
  1.2050 +
  1.2051 +    val upd_convs = timeit_msg "record upd_convs proof:" upd_convs_prf;
  1.2052 +
  1.2053 +    val parent_induct = if null parents then [] else [#induct (hd (rev parents))];
  1.2054 +
  1.2055 +    fun induct_scheme_prf () = prove_standard [] induct_scheme_prop (fn _ =>
  1.2056 +          (EVERY [if null parent_induct
  1.2057 +                  then all_tac else try_param_tac rN (hd parent_induct) 1,
  1.2058 +                  try_param_tac rN ext_induct 1,
  1.2059 +                  asm_simp_tac HOL_basic_ss 1]));
  1.2060 +    val induct_scheme = timeit_msg "record induct_scheme proof:" induct_scheme_prf;
  1.2061 +
  1.2062 +    fun induct_prf () =
  1.2063 +      let val (assm, concl) = induct_prop;
  1.2064 +      in
  1.2065 +        prove_standard [assm] concl (fn {prems, ...} =>
  1.2066 +          try_param_tac rN induct_scheme 1
  1.2067 +          THEN try_param_tac "more" @{thm unit.induct} 1
  1.2068 +          THEN resolve_tac prems 1)
  1.2069 +      end;
  1.2070 +    val induct = timeit_msg "record induct proof:" induct_prf;
  1.2071 +
  1.2072 +    fun surjective_prf () =
  1.2073 +      prove_standard [] surjective_prop (fn prems =>
  1.2074 +          (EVERY [try_param_tac rN induct_scheme 1,
  1.2075 +                  simp_tac (ss addsimps sel_convs_standard) 1]))
  1.2076 +    val surjective = timeit_msg "record surjective proof:" surjective_prf;
  1.2077 +
  1.2078 +    fun cases_scheme_prf_opt () =
  1.2079 +      let
  1.2080 +        val (_$(Pvar$_)) = concl_of induct_scheme;
  1.2081 +        val ind = cterm_instantiate
  1.2082 +                    [(cterm_of defs_thy Pvar, cterm_of defs_thy
  1.2083 +                            (lambda w (HOLogic.imp$HOLogic.mk_eq(r0,w)$C)))]
  1.2084 +                    induct_scheme;
  1.2085 +        in standard (ObjectLogic.rulify (mp OF [ind, refl])) end;
  1.2086 +
  1.2087 +    fun cases_scheme_prf_noopt () =
  1.2088 +        prove_standard [] cases_scheme_prop (fn _ =>
  1.2089 +         EVERY [asm_full_simp_tac (HOL_basic_ss addsimps [atomize_all, atomize_imp]) 1,
  1.2090 +               try_param_tac rN induct_scheme 1,
  1.2091 +               rtac impI 1,
  1.2092 +               REPEAT (etac allE 1),
  1.2093 +               etac mp 1,
  1.2094 +               rtac refl 1])
  1.2095 +    val cases_scheme_prf = quick_and_dirty_prf cases_scheme_prf_noopt cases_scheme_prf_opt;
  1.2096 +    val cases_scheme = timeit_msg "record cases_scheme proof:" cases_scheme_prf;
  1.2097 +
  1.2098 +    fun cases_prf () =
  1.2099 +      prove_standard [] cases_prop  (fn _ =>
  1.2100 +        try_param_tac rN cases_scheme 1
  1.2101 +        THEN simp_all_tac HOL_basic_ss [unit_all_eq1]);
  1.2102 +    val cases = timeit_msg "record cases proof:" cases_prf;
  1.2103 +
  1.2104 +    fun split_meta_prf () =
  1.2105 +        prove false [] split_meta_prop (fn _ =>
  1.2106 +         EVERY [rtac equal_intr_rule 1, Goal.norm_hhf_tac 1,
  1.2107 +                etac meta_allE 1, atac 1,
  1.2108 +                rtac (prop_subst OF [surjective]) 1,
  1.2109 +                REPEAT (etac meta_allE 1), atac 1]);
  1.2110 +    val split_meta = timeit_msg "record split_meta proof:" split_meta_prf;
  1.2111 +    val split_meta_standard = standard split_meta;
  1.2112 +
  1.2113 +    fun split_object_prf_opt () =
  1.2114 +      let
  1.2115 +        val cPI= cterm_of defs_thy (lambda r0 (Trueprop (P$r0)));
  1.2116 +        val (_$Abs(_,_,P$_)) = fst (Logic.dest_equals (concl_of split_meta_standard));
  1.2117 +        val cP = cterm_of defs_thy P;
  1.2118 +        val split_meta' = cterm_instantiate [(cP,cPI)] split_meta_standard;
  1.2119 +        val (l,r) = HOLogic.dest_eq (HOLogic.dest_Trueprop split_object_prop);
  1.2120 +        val cl = cterm_of defs_thy (HOLogic.mk_Trueprop l);
  1.2121 +        val cr = cterm_of defs_thy (HOLogic.mk_Trueprop r);
  1.2122 +        val thl = assume cl                 (*All r. P r*) (* 1 *)
  1.2123 +                |> obj_to_meta_all          (*!!r. P r*)
  1.2124 +                |> equal_elim split_meta'   (*!!n m more. P (ext n m more)*)
  1.2125 +                |> meta_to_obj_all          (*All n m more. P (ext n m more)*) (* 2*)
  1.2126 +                |> implies_intr cl          (* 1 ==> 2 *)
  1.2127 +        val thr = assume cr                           (*All n m more. P (ext n m more)*)
  1.2128 +                |> obj_to_meta_all                    (*!!n m more. P (ext n m more)*)
  1.2129 +                |> equal_elim (symmetric split_meta') (*!!r. P r*)
  1.2130 +                |> meta_to_obj_all                    (*All r. P r*)
  1.2131 +                |> implies_intr cr                    (* 2 ==> 1 *)
  1.2132 +     in standard (thr COMP (thl COMP iffI)) end;
  1.2133 +
  1.2134 +    fun split_object_prf_noopt () =
  1.2135 +        prove_standard [] split_object_prop (fn _ =>
  1.2136 +         EVERY [rtac iffI 1,
  1.2137 +                REPEAT (rtac allI 1), etac allE 1, atac 1,
  1.2138 +                rtac allI 1, rtac induct_scheme 1,REPEAT (etac allE 1),atac 1]);
  1.2139 +
  1.2140 +    val split_object_prf = quick_and_dirty_prf split_object_prf_noopt split_object_prf_opt;
  1.2141 +    val split_object = timeit_msg "record split_object proof:" split_object_prf;
  1.2142 +
  1.2143 +
  1.2144 +    fun split_ex_prf () =
  1.2145 +        prove_standard [] split_ex_prop (fn _ =>
  1.2146 +          EVERY [rtac iffI 1,
  1.2147 +                   etac exE 1,
  1.2148 +                   simp_tac (HOL_basic_ss addsimps [split_meta_standard]) 1,
  1.2149 +                   ex_inst_tac 1,
  1.2150 +                   (*REPEAT (rtac exI 1),*)
  1.2151 +                   atac 1,
  1.2152 +                 REPEAT (etac exE 1),
  1.2153 +                 rtac exI 1,
  1.2154 +                 atac 1]);
  1.2155 +    val split_ex = timeit_msg "record split_ex proof:" split_ex_prf;
  1.2156 +
  1.2157 +    fun equality_tac thms =
  1.2158 +      let val (s'::s::eqs) = rev thms;
  1.2159 +          val ss' = ss addsimps (s'::s::sel_convs_standard);
  1.2160 +          val eqs' = map (simplify ss') eqs;
  1.2161 +      in simp_tac (HOL_basic_ss addsimps (s'::s::eqs')) 1 end;
  1.2162 +
  1.2163 +   fun equality_prf () = prove_standard [] equality_prop (fn {context, ...} =>
  1.2164 +      fn st => let val [s, s'] = map #1 (rev (Tactic.innermost_params 1 st)) in
  1.2165 +        st |> (res_inst_tac context [((rN, 0), s)] cases_scheme 1
  1.2166 +        THEN res_inst_tac context [((rN, 0), s')] cases_scheme 1
  1.2167 +        THEN (METAHYPS equality_tac 1))
  1.2168 +             (* simp_all_tac ss (sel_convs) would also work but is less efficient *)
  1.2169 +      end);
  1.2170 +     val equality = timeit_msg "record equality proof:" equality_prf;
  1.2171 +
  1.2172 +    val ((([sel_convs',upd_convs',sel_defs',upd_defs',[split_meta',split_object',split_ex'],derived_defs'],
  1.2173 +            [surjective',equality']),[induct_scheme',induct',cases_scheme',cases']), thms_thy) =
  1.2174 +      defs_thy
  1.2175 +      |> (PureThy.add_thmss o map (Thm.no_attributes o apfst Binding.name))
  1.2176 +         [("select_convs", sel_convs_standard),
  1.2177 +          ("update_convs", upd_convs),
  1.2178 +          ("select_defs", sel_defs),
  1.2179 +          ("update_defs", upd_defs),
  1.2180 +          ("splits", [split_meta_standard,split_object,split_ex]),
  1.2181 +          ("defs", derived_defs)]
  1.2182 +      ||>> (PureThy.add_thms o map (Thm.no_attributes o apfst Binding.name))
  1.2183 +          [("surjective", surjective),
  1.2184 +           ("equality", equality)]
  1.2185 +      ||>> (PureThy.add_thms o (map o apfst o apfst) Binding.name)
  1.2186 +        [(("induct_scheme", induct_scheme), induct_type_global (suffix schemeN name)),
  1.2187 +         (("induct", induct), induct_type_global name),
  1.2188 +         (("cases_scheme", cases_scheme), cases_type_global (suffix schemeN name)),
  1.2189 +         (("cases", cases), cases_type_global name)];
  1.2190 +
  1.2191 +
  1.2192 +    val sel_upd_simps = sel_convs' @ upd_convs';
  1.2193 +    val iffs = [ext_inject]
  1.2194 +    val final_thy =
  1.2195 +      thms_thy
  1.2196 +      |> (snd oo PureThy.add_thmss)
  1.2197 +          [((Binding.name "simps", sel_upd_simps),
  1.2198 +            [Simplifier.simp_add, Nitpick_Const_Simp_Thms.add]),
  1.2199 +           ((Binding.name "iffs", iffs), [iff_add])]
  1.2200 +      |> put_record name (make_record_info args parent fields extension induct_scheme')
  1.2201 +      |> put_sel_upd (names @ [full_moreN]) sel_upd_simps
  1.2202 +      |> add_record_equalities extension_id equality'
  1.2203 +      |> add_extinjects ext_inject
  1.2204 +      |> add_extsplit extension_name ext_split
  1.2205 +      |> add_record_splits extension_id (split_meta',split_object',split_ex',induct_scheme')
  1.2206 +      |> add_extfields extension_name (fields @ [(full_moreN,moreT)])
  1.2207 +      |> add_fieldext (extension_name,snd extension) (names @ [full_moreN])
  1.2208 +      |> Sign.parent_path;
  1.2209 +
  1.2210 +  in final_thy
  1.2211 +  end;
  1.2212 +
  1.2213 +
  1.2214 +(* add_record *)
  1.2215 +
  1.2216 +(*we do all preparations and error checks here, deferring the real
  1.2217 +  work to record_definition*)
  1.2218 +fun gen_add_record prep_typ prep_raw_parent quiet_mode (params, bname) raw_parent raw_fields thy =
  1.2219 +  let
  1.2220 +    val _ = Theory.requires thy "Record" "record definitions";
  1.2221 +    val _ = if quiet_mode then () else writeln ("Defining record " ^ quote bname ^ " ...");
  1.2222 +
  1.2223 +    val ctxt = ProofContext.init thy;
  1.2224 +
  1.2225 +
  1.2226 +    (* parents *)
  1.2227 +
  1.2228 +    fun prep_inst T = fst (cert_typ ctxt T []);
  1.2229 +
  1.2230 +    val parent = Option.map (apfst (map prep_inst) o prep_raw_parent ctxt) raw_parent
  1.2231 +      handle ERROR msg => cat_error msg ("The error(s) above in parent record specification");
  1.2232 +    val parents = add_parents thy parent [];
  1.2233 +
  1.2234 +    val init_env =
  1.2235 +      (case parent of
  1.2236 +        NONE => []
  1.2237 +      | SOME (types, _) => List.foldr OldTerm.add_typ_tfrees [] types);
  1.2238 +
  1.2239 +
  1.2240 +    (* fields *)
  1.2241 +
  1.2242 +    fun prep_field (c, raw_T, mx) env =
  1.2243 +      let val (T, env') = prep_typ ctxt raw_T env handle ERROR msg =>
  1.2244 +        cat_error msg ("The error(s) above occured in record field " ^ quote c)
  1.2245 +      in ((c, T, mx), env') end;
  1.2246 +
  1.2247 +    val (bfields, envir) = fold_map prep_field raw_fields init_env;
  1.2248 +    val envir_names = map fst envir;
  1.2249 +
  1.2250 +
  1.2251 +    (* args *)
  1.2252 +
  1.2253 +    val defaultS = Sign.defaultS thy;
  1.2254 +    val args = map (fn x => (x, AList.lookup (op =) envir x |> the_default defaultS)) params;
  1.2255 +
  1.2256 +
  1.2257 +    (* errors *)
  1.2258 +
  1.2259 +    val name = Sign.full_bname thy bname;
  1.2260 +    val err_dup_record =
  1.2261 +      if is_none (get_record thy name) then []
  1.2262 +      else ["Duplicate definition of record " ^ quote name];
  1.2263 +
  1.2264 +    val err_dup_parms =
  1.2265 +      (case duplicates (op =) params of
  1.2266 +        [] => []
  1.2267 +      | dups => ["Duplicate parameter(s) " ^ commas dups]);
  1.2268 +
  1.2269 +    val err_extra_frees =
  1.2270 +      (case subtract (op =) params envir_names of
  1.2271 +        [] => []
  1.2272 +      | extras => ["Extra free type variable(s) " ^ commas extras]);
  1.2273 +
  1.2274 +    val err_no_fields = if null bfields then ["No fields present"] else [];
  1.2275 +
  1.2276 +    val err_dup_fields =
  1.2277 +      (case duplicates (op =) (map #1 bfields) of
  1.2278 +        [] => []
  1.2279 +      | dups => ["Duplicate field(s) " ^ commas_quote dups]);
  1.2280 +
  1.2281 +    val err_bad_fields =
  1.2282 +      if forall (not_equal moreN o #1) bfields then []
  1.2283 +      else ["Illegal field name " ^ quote moreN];
  1.2284 +
  1.2285 +    val err_dup_sorts =
  1.2286 +      (case duplicates (op =) envir_names of
  1.2287 +        [] => []
  1.2288 +      | dups => ["Inconsistent sort constraints for " ^ commas dups]);
  1.2289 +
  1.2290 +    val errs =
  1.2291 +      err_dup_record @ err_dup_parms @ err_extra_frees @ err_no_fields @
  1.2292 +      err_dup_fields @ err_bad_fields @ err_dup_sorts;
  1.2293 +  in
  1.2294 +    if null errs then () else error (cat_lines errs)  ;
  1.2295 +    thy |> record_definition (args, bname) parent parents bfields
  1.2296 +  end
  1.2297 +  handle ERROR msg => cat_error msg ("Failed to define record " ^ quote bname);
  1.2298 +
  1.2299 +val add_record = gen_add_record read_typ read_raw_parent;
  1.2300 +val add_record_i = gen_add_record cert_typ (K I);
  1.2301 +
  1.2302 +(* setup theory *)
  1.2303 +
  1.2304 +val setup =
  1.2305 +  Sign.add_trfuns ([], parse_translation, [], []) #>
  1.2306 +  Sign.add_advanced_trfuns ([], adv_parse_translation, [], []) #>
  1.2307 +  Simplifier.map_simpset (fn ss =>
  1.2308 +    ss addsimprocs [record_simproc, record_upd_simproc, record_eq_simproc]);
  1.2309 +
  1.2310 +(* outer syntax *)
  1.2311 +
  1.2312 +local structure P = OuterParse and K = OuterKeyword in
  1.2313 +
  1.2314 +val record_decl =
  1.2315 +  P.type_args -- P.name --
  1.2316 +    (P.$$$ "=" |-- Scan.option (P.typ --| P.$$$ "+") -- Scan.repeat1 P.const);
  1.2317 +
  1.2318 +val _ =
  1.2319 +  OuterSyntax.command "record" "define extensible record" K.thy_decl
  1.2320 +    (record_decl >> (fn (x, (y, z)) => Toplevel.theory (add_record false x y z)));
  1.2321 +
  1.2322 +end;
  1.2323 +
  1.2324 +end;
  1.2325 +
  1.2326 +
  1.2327 +structure BasicRecord: BASIC_RECORD = Record;
  1.2328 +open BasicRecord;