src/HOL/Tools/record_package.ML
author wenzelm
Thu Aug 03 17:30:36 2006 +0200 (2006-08-03)
changeset 20328 5b240a4216b0
parent 20248 7916ce5bb069
child 20350 54fe257afd4f
permissions -rw-r--r--
RuleInsts.bires_inst_tac;
     1 (*  Title:      HOL/Tools/record_package.ML
     2     ID:         $Id$
     3     Author:     Wolfgang Naraschewski, Norbert Schirmer and Markus Wenzel, TU Muenchen
     4 
     5 Extensible records with structural subtyping in HOL.
     6 *)
     7 
     8 signature BASIC_RECORD_PACKAGE =
     9 sig
    10   val record_simproc: simproc
    11   val record_eq_simproc: simproc
    12   val record_upd_simproc: simproc
    13   val record_split_simproc: (term -> int) -> simproc
    14   val record_ex_sel_eq_simproc: simproc
    15   val record_split_tac: int -> tactic
    16   val record_split_simp_tac: thm list -> (term -> int) -> int -> tactic
    17   val record_split_name: string
    18   val record_split_wrapper: string * wrapper
    19   val print_record_type_abbr: bool ref
    20   val print_record_type_as_fields: bool ref
    21 end;
    22 
    23 signature RECORD_PACKAGE =
    24 sig
    25   include BASIC_RECORD_PACKAGE
    26   val quiet_mode: bool ref
    27   val record_quick_and_dirty_sensitive: bool ref
    28   val updateN: string
    29   val ext_typeN: string
    30   val last_extT: typ -> (string * typ list) option
    31   val dest_recTs : typ -> (string * typ list) list
    32   val get_extT_fields:  theory -> typ -> ((string * typ) list * (string * typ))
    33   val get_recT_fields:  theory -> typ -> ((string * typ) list * (string * typ))
    34   val get_extension: theory -> Symtab.key -> (string * typ list) option
    35   val get_extinjects: theory -> thm list
    36   val get_simpset: theory -> simpset
    37   val print_records: theory -> unit
    38   val add_record: string list * string -> string option -> (string * string * mixfix) list
    39     -> theory -> theory
    40   val add_record_i: string list * string -> (typ list * string) option
    41     -> (string * typ * mixfix) list -> theory -> theory
    42   val setup: theory -> theory
    43 end;
    44 
    45 
    46 structure RecordPackage: RECORD_PACKAGE =
    47 struct
    48 
    49 val rec_UNIV_I = thm "rec_UNIV_I";
    50 val rec_True_simp = thm "rec_True_simp";
    51 val Pair_eq = thm "Product_Type.Pair_eq";
    52 val atomize_all = thm "HOL.atomize_all";
    53 val atomize_imp = thm "HOL.atomize_imp";
    54 val meta_allE = thm "Pure.meta_allE";
    55 val prop_subst = thm "prop_subst";
    56 val Pair_sel_convs = [fst_conv,snd_conv];
    57 
    58 
    59 
    60 (** name components **)
    61 
    62 val rN = "r";
    63 val wN = "w";
    64 val moreN = "more";
    65 val schemeN = "_scheme";
    66 val ext_typeN = "_ext_type";
    67 val extN ="_ext";
    68 val casesN = "_cases";
    69 val ext_dest = "_sel";
    70 val updateN = "_update";
    71 val updN = "_upd";
    72 val schemeN = "_scheme";
    73 val makeN = "make";
    74 val fields_selN = "fields";
    75 val extendN = "extend";
    76 val truncateN = "truncate";
    77 
    78 (*see typedef_package.ML*)
    79 val RepN = "Rep_";
    80 val AbsN = "Abs_";
    81 
    82 (*** utilities ***)
    83 
    84 fun but_last xs = fst (split_last xs);
    85 
    86 fun varifyT midx =
    87   let fun varify (a, S) = TVar ((a, midx + 1), S);
    88   in map_type_tfree varify end;
    89 
    90 (* messages *)
    91 
    92 val quiet_mode = ref false;
    93 fun message s = if ! quiet_mode then () else writeln s;
    94 
    95 (* timing *)
    96 
    97 fun timeit_msg s x = if !timing then (warning s; timeit x) else x ();
    98 fun timing_msg s = if !timing then warning s else ();
    99 
   100 (* syntax *)
   101 
   102 fun prune n xs = Library.drop (n, xs);
   103 fun prefix_base s = NameSpace.map_base (fn bname => s ^ bname);
   104 
   105 val Trueprop = HOLogic.mk_Trueprop;
   106 fun All xs t = Term.list_all_free (xs, t);
   107 
   108 infix 9 $$;
   109 infix 0 :== ===;
   110 infixr 0 ==>;
   111 
   112 val (op $$) = Term.list_comb;
   113 val (op :==) = Logic.mk_defpair;
   114 val (op ===) = Trueprop o HOLogic.mk_eq;
   115 val (op ==>) = Logic.mk_implies;
   116 
   117 (* morphisms *)
   118 
   119 fun mk_RepN name = suffix ext_typeN (prefix_base RepN name);
   120 fun mk_AbsN name = suffix ext_typeN (prefix_base AbsN name);
   121 
   122 fun mk_Rep name repT absT  =
   123   Const (suffix ext_typeN (prefix_base RepN name),absT --> repT);
   124 
   125 fun mk_Abs name repT absT =
   126   Const (mk_AbsN name,repT --> absT);
   127 
   128 (* constructor *)
   129 
   130 fun mk_extC (name,T) Ts  = (suffix extN name, Ts ---> T);
   131 
   132 fun mk_ext (name,T) ts =
   133   let val Ts = map fastype_of ts
   134   in list_comb (Const (mk_extC (name,T) Ts),ts) end;
   135 
   136 (* cases *)
   137 
   138 fun mk_casesC (name,T,vT) Ts = (suffix casesN name, (Ts ---> vT) --> T --> vT)
   139 
   140 fun mk_cases (name,T,vT) f =
   141   let val Ts = binder_types (fastype_of f)
   142   in Const (mk_casesC (name,T,vT) Ts) $ f end;
   143 
   144 (* selector *)
   145 
   146 fun mk_selC sT (c,T) = (c,sT --> T);
   147 
   148 fun mk_sel s (c,T) =
   149   let val sT = fastype_of s
   150   in Const (mk_selC sT (c,T)) $ s end;
   151 
   152 (* updates *)
   153 
   154 fun mk_updC sfx sT (c,T) = (suffix sfx c, T --> sT --> sT);
   155 
   156 fun mk_upd sfx c v s =
   157   let val sT = fastype_of s;
   158       val vT = fastype_of v;
   159   in Const (mk_updC sfx sT (c, vT)) $ v $ s end;
   160 
   161 (* types *)
   162 
   163 fun dest_recT (typ as Type (c_ext_type, Ts as (T::_))) =
   164       (case try (unsuffix ext_typeN) c_ext_type of
   165         NONE => raise TYPE ("RecordPackage.dest_recT", [typ], [])
   166       | SOME c => ((c, Ts), List.last Ts))
   167   | dest_recT typ = raise TYPE ("RecordPackage.dest_recT", [typ], []);
   168 
   169 fun is_recT T =
   170   (case try dest_recT T of NONE => false | SOME _ => true);
   171 
   172 fun dest_recTs T =
   173   let val ((c, Ts), U) = dest_recT T
   174   in (c, Ts) :: dest_recTs U
   175   end handle TYPE _ => [];
   176 
   177 fun last_extT T =
   178   let val ((c, Ts), U) = dest_recT T
   179   in (case last_extT U of
   180         NONE => SOME (c,Ts)
   181       | SOME l => SOME l)
   182   end handle TYPE _ => NONE
   183 
   184 fun rec_id i T =
   185   let val rTs = dest_recTs T
   186       val rTs' = if i < 0 then rTs else Library.take (i,rTs)
   187   in Library.foldl (fn (s,(c,T)) => s ^ c) ("",rTs') end;
   188 
   189 (*** extend theory by record definition ***)
   190 
   191 (** record info **)
   192 
   193 (* type record_info and parent_info  *)
   194 
   195 type record_info =
   196  {args: (string * sort) list,
   197   parent: (typ list * string) option,
   198   fields: (string * typ) list,
   199   extension: (string * typ list),
   200   induct: thm
   201  };
   202 
   203 fun make_record_info args parent fields extension induct =
   204  {args = args, parent = parent, fields = fields, extension = extension,
   205   induct = induct}: record_info;
   206 
   207 
   208 type parent_info =
   209  {name: string,
   210   fields: (string * typ) list,
   211   extension: (string * typ list),
   212   induct: thm
   213 };
   214 
   215 fun make_parent_info name fields extension induct =
   216  {name = name, fields = fields, extension = extension, induct = induct}: parent_info;
   217 
   218 (* data kind 'HOL/record' *)
   219 
   220 type record_data =
   221  {records: record_info Symtab.table,
   222   sel_upd:
   223    {selectors: unit Symtab.table,
   224     updates: string Symtab.table,
   225     simpset: Simplifier.simpset},
   226   equalities: thm Symtab.table,
   227   extinjects: thm list,
   228   extsplit: thm Symtab.table, (* maps extension name to split rule *)
   229   splits: (thm*thm*thm*thm) Symtab.table,    (* !!,!,EX - split-equalities,induct rule *)
   230   extfields: (string*typ) list Symtab.table, (* maps extension to its fields *)
   231   fieldext: (string*typ list) Symtab.table   (* maps field to its extension *)
   232 };
   233 
   234 fun make_record_data
   235       records sel_upd equalities extinjects extsplit splits extfields fieldext =
   236  {records = records, sel_upd = sel_upd,
   237   equalities = equalities, extinjects=extinjects, extsplit = extsplit, splits = splits,
   238   extfields = extfields, fieldext = fieldext }: record_data;
   239 
   240 structure RecordsData = TheoryDataFun
   241 (struct
   242   val name = "HOL/records";
   243   type T = record_data;
   244 
   245   val empty =
   246     make_record_data Symtab.empty
   247       {selectors = Symtab.empty, updates = Symtab.empty, simpset = HOL_basic_ss}
   248        Symtab.empty [] Symtab.empty Symtab.empty Symtab.empty Symtab.empty;
   249 
   250   val copy = I;
   251   val extend = I;
   252   fun merge _
   253    ({records = recs1,
   254      sel_upd = {selectors = sels1, updates = upds1, simpset = ss1},
   255      equalities = equalities1,
   256      extinjects = extinjects1,
   257      extsplit = extsplit1,
   258      splits = splits1,
   259      extfields = extfields1,
   260      fieldext = fieldext1},
   261     {records = recs2,
   262      sel_upd = {selectors = sels2, updates = upds2, simpset = ss2},
   263      equalities = equalities2,
   264      extinjects = extinjects2,
   265      extsplit = extsplit2,
   266      splits = splits2,
   267      extfields = extfields2,
   268      fieldext = fieldext2}) =
   269     make_record_data
   270       (Symtab.merge (K true) (recs1, recs2))
   271       {selectors = Symtab.merge (K true) (sels1, sels2),
   272         updates = Symtab.merge (K true) (upds1, upds2),
   273         simpset = Simplifier.merge_ss (ss1, ss2)}
   274       (Symtab.merge Thm.eq_thm (equalities1, equalities2))
   275       (gen_merge_lists Thm.eq_thm extinjects1 extinjects2)
   276       (Symtab.merge Thm.eq_thm (extsplit1,extsplit2))
   277       (Symtab.merge (fn ((a,b,c,d),(w,x,y,z))
   278                      => Thm.eq_thm (a,w) andalso Thm.eq_thm (b,x) andalso
   279                         Thm.eq_thm (c,y) andalso Thm.eq_thm (d,z))
   280                     (splits1, splits2))
   281       (Symtab.merge (K true) (extfields1,extfields2))
   282       (Symtab.merge (K true) (fieldext1,fieldext2));
   283 
   284   fun print thy ({records = recs, ...}: record_data) =
   285     let
   286       val prt_typ = Sign.pretty_typ thy;
   287 
   288       fun pretty_parent NONE = []
   289         | pretty_parent (SOME (Ts, name)) =
   290             [Pretty.block [prt_typ (Type (name, Ts)), Pretty.str " +"]];
   291 
   292       fun pretty_field (c, T) = Pretty.block
   293         [Pretty.str (Sign.extern_const thy c), Pretty.str " ::",
   294           Pretty.brk 1, Pretty.quote (prt_typ T)];
   295 
   296       fun pretty_record (name, {args, parent, fields, ...}: record_info) =
   297         Pretty.block (Pretty.fbreaks (Pretty.block
   298           [prt_typ (Type (name, map TFree args)), Pretty.str " = "] ::
   299           pretty_parent parent @ map pretty_field fields));
   300     in map pretty_record (Symtab.dest recs) |> Pretty.chunks |> Pretty.writeln end;
   301 end);
   302 
   303 val print_records = RecordsData.print;
   304 
   305 
   306 (* access 'records' *)
   307 
   308 val get_record = Symtab.lookup o #records o RecordsData.get;
   309 
   310 fun put_record name info thy =
   311   let
   312     val {records, sel_upd, equalities, extinjects,extsplit,splits,extfields,fieldext} =
   313           RecordsData.get thy;
   314     val data = make_record_data (Symtab.update (name, info) records)
   315       sel_upd equalities extinjects extsplit splits extfields fieldext;
   316   in RecordsData.put data thy end;
   317 
   318 (* access 'sel_upd' *)
   319 
   320 val get_sel_upd = #sel_upd o RecordsData.get;
   321 
   322 val is_selector = Symtab.defined o #selectors o get_sel_upd;
   323 val get_updates = Symtab.lookup o #updates o get_sel_upd;
   324 fun get_simpset thy = Simplifier.theory_context thy (#simpset (get_sel_upd thy));
   325 
   326 fun put_sel_upd names simps thy =
   327   let
   328     val sels = map (rpair ()) names;
   329     val upds = map (suffix updateN) names ~~ names;
   330 
   331     val {records, sel_upd = {selectors, updates, simpset},
   332       equalities, extinjects, extsplit, splits, extfields,fieldext} = RecordsData.get thy;
   333     val data = make_record_data records
   334       {selectors = Symtab.extend (selectors, sels),
   335         updates = Symtab.extend (updates, upds),
   336         simpset = Simplifier.addsimps (simpset, simps)}
   337        equalities extinjects extsplit splits extfields fieldext;
   338   in RecordsData.put data thy end;
   339 
   340 (* access 'equalities' *)
   341 
   342 fun add_record_equalities name thm thy =
   343   let
   344     val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields,fieldext} =
   345           RecordsData.get thy;
   346     val data = make_record_data records sel_upd
   347            (Symtab.update_new (name, thm) equalities) extinjects extsplit
   348            splits extfields fieldext;
   349   in RecordsData.put data thy end;
   350 
   351 val get_equalities =Symtab.lookup o #equalities o RecordsData.get;
   352 
   353 (* access 'extinjects' *)
   354 
   355 fun add_extinjects thm thy =
   356   let
   357     val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields,fieldext} =
   358           RecordsData.get thy;
   359     val data = make_record_data records sel_upd equalities (extinjects@[thm]) extsplit
   360                  splits extfields fieldext;
   361   in RecordsData.put data thy end;
   362 
   363 fun get_extinjects thy = #extinjects (RecordsData.get thy);
   364 
   365 (* access 'extsplit' *)
   366 
   367 fun add_extsplit name thm thy =
   368   let
   369     val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields,fieldext} =
   370           RecordsData.get thy;
   371     val data = make_record_data records sel_upd
   372       equalities extinjects (Symtab.update_new (name, thm) extsplit) splits
   373       extfields fieldext;
   374   in RecordsData.put data thy end;
   375 
   376 val get_extsplit = Symtab.lookup o #extsplit o RecordsData.get;
   377 
   378 (* access 'splits' *)
   379 
   380 fun add_record_splits name thmP thy =
   381   let
   382     val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields,fieldext} =
   383           RecordsData.get thy;
   384     val data = make_record_data records sel_upd
   385       equalities extinjects extsplit (Symtab.update_new (name, thmP) splits)
   386       extfields fieldext;
   387   in RecordsData.put data thy end;
   388 
   389 val get_splits = Symtab.lookup o #splits o RecordsData.get;
   390 
   391 
   392 
   393 (* extension of a record name *)
   394 val get_extension =
   395   Option.map #extension oo (Symtab.lookup o #records o RecordsData.get);
   396 
   397 
   398 (* access 'extfields' *)
   399 
   400 fun add_extfields name fields thy =
   401   let
   402     val {records, sel_upd, equalities, extinjects, extsplit,splits, extfields, fieldext} =
   403           RecordsData.get thy;
   404     val data = make_record_data records sel_upd
   405          equalities extinjects extsplit splits
   406          (Symtab.update_new (name, fields) extfields) fieldext;
   407   in RecordsData.put data thy end;
   408 
   409 val get_extfields = Symtab.lookup o #extfields o RecordsData.get;
   410 
   411 fun get_extT_fields thy T =
   412   let
   413     val ((name,Ts),moreT) = dest_recT T;
   414     val recname = let val (nm::recn::rst) = rev (NameSpace.unpack name)
   415                   in NameSpace.pack (rev (nm::rst)) end;
   416     val midx = maxidx_of_typs (moreT::Ts);
   417     val varifyT = varifyT midx;
   418     val {records,extfields,...} = RecordsData.get thy;
   419     val (flds,(more,_)) = split_last (Symtab.lookup_list extfields name);
   420     val args = map varifyT (snd (#extension (the (Symtab.lookup records recname))));
   421 
   422     val subst = fold (Sign.typ_match thy) (but_last args ~~ but_last Ts) (Vartab.empty);
   423     val flds' = map (apsnd ((Envir.norm_type subst) o varifyT)) flds;
   424   in (flds',(more,moreT)) end;
   425 
   426 fun get_recT_fields thy T =
   427   let
   428     val (root_flds,(root_more,root_moreT)) = get_extT_fields thy T;
   429     val (rest_flds,rest_more) =
   430            if is_recT root_moreT then get_recT_fields thy root_moreT
   431            else ([],(root_more,root_moreT));
   432   in (root_flds@rest_flds,rest_more) end;
   433 
   434 
   435 (* access 'fieldext' *)
   436 
   437 fun add_fieldext extname_types fields thy =
   438   let
   439     val {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =
   440            RecordsData.get thy;
   441     val fieldext' =
   442       fold (fn field => Symtab.update_new (field, extname_types)) fields fieldext;
   443     val data=make_record_data records sel_upd equalities extinjects extsplit
   444               splits extfields fieldext';
   445   in RecordsData.put data thy end;
   446 
   447 
   448 val get_fieldext = Symtab.lookup o #fieldext o RecordsData.get;
   449 
   450 (* parent records *)
   451 
   452 fun add_parents thy NONE parents = parents
   453   | add_parents thy (SOME (types, name)) parents =
   454       let
   455         val sign = Theory.sign_of thy;
   456         fun err msg = error (msg ^ " parent record " ^ quote name);
   457 
   458         val {args, parent, fields, extension, induct} =
   459           (case get_record thy name of SOME info => info | NONE => err "Unknown");
   460         val _ = if length types <> length args then err "Bad number of arguments for" else ();
   461 
   462         fun bad_inst ((x, S), T) =
   463           if Sign.of_sort sign (T, S) then NONE else SOME x
   464         val bads = List.mapPartial bad_inst (args ~~ types);
   465 
   466         val inst = map fst args ~~ types;
   467         val subst = Term.map_type_tfree (the o AList.lookup (op =) inst o fst);
   468         val parent' = Option.map (apfst (map subst)) parent;
   469         val fields' = map (apsnd subst) fields;
   470         val extension' = apsnd (map subst) extension;
   471       in
   472         conditional (not (null bads)) (fn () =>
   473           err ("Ill-sorted instantiation of " ^ commas bads ^ " in"));
   474         add_parents thy parent'
   475           (make_parent_info name fields' extension' induct::parents)
   476       end;
   477 
   478 
   479 (** concrete syntax for records **)
   480 
   481 (* parse translations *)
   482 
   483 fun gen_field_tr mark sfx (t as Const (c, _) $ Const (name, _) $ arg) =
   484       if c = mark then Syntax.const (suffix sfx name) $ arg
   485       else raise TERM ("gen_field_tr: " ^ mark, [t])
   486   | gen_field_tr mark _ t = raise TERM ("gen_field_tr: " ^ mark, [t]);
   487 
   488 fun gen_fields_tr sep mark sfx (tm as Const (c, _) $ t $ u) =
   489       if c = sep then gen_field_tr mark sfx t :: gen_fields_tr sep mark sfx u
   490       else [gen_field_tr mark sfx tm]
   491   | gen_fields_tr _ mark sfx tm = [gen_field_tr mark sfx tm];
   492 
   493 
   494 fun record_update_tr [t, u] =
   495       foldr (op $) t (rev (gen_fields_tr "_updates" "_update" updateN u))
   496   | record_update_tr ts = raise TERM ("record_update_tr", ts);
   497 
   498 fun update_name_tr (Free (x, T) :: ts) = Free (suffix updateN x, T) $$ ts
   499   | update_name_tr (Const (x, T) :: ts) = Const (suffix updateN x, T) $$ ts
   500   | update_name_tr (((c as Const ("_constrain", _)) $ t $ ty) :: ts) =
   501       (c $ update_name_tr [t] $ (Syntax.const "fun" $ ty $ Syntax.const "dummy")) $$ ts
   502   | update_name_tr ts = raise TERM ("update_name_tr", ts);
   503 
   504 fun dest_ext_field mark (t as (Const (c,_) $ Const (name,_) $ arg)) =
   505      if c = mark then (name,arg) else raise TERM ("dest_ext_field: " ^ mark, [t])
   506   | dest_ext_field _ t = raise TERM ("dest_ext_field", [t])
   507 
   508 fun dest_ext_fields sep mark (trm as (Const (c,_) $ t $ u)) =
   509      if c = sep then dest_ext_field mark t::dest_ext_fields sep mark u
   510      else [dest_ext_field mark trm]
   511   | dest_ext_fields _ mark t = [dest_ext_field mark t]
   512 
   513 fun gen_ext_fields_tr sep mark sfx more context t =
   514   let
   515     val thy = Context.theory_of context;
   516     val msg = "error in record input: ";
   517     val fieldargs = dest_ext_fields sep mark t;
   518     fun splitargs (field::fields) ((name,arg)::fargs) =
   519           if can (unsuffix name) field
   520           then let val (args,rest) = splitargs fields fargs
   521                in (arg::args,rest) end
   522           else raise TERM (msg ^ "expecting field " ^ field ^ " but got " ^ name, [t])
   523       | splitargs [] (fargs as (_::_)) = ([],fargs)
   524       | splitargs (_::_) [] = raise TERM (msg ^ "expecting more fields", [t])
   525       | splitargs _ _ = ([],[]);
   526 
   527     fun mk_ext (fargs as (name,arg)::_) =
   528          (case get_fieldext thy (Sign.intern_const thy name) of
   529             SOME (ext,_) => (case get_extfields thy ext of
   530                                SOME flds
   531                                  => let val (args,rest) =
   532                                                splitargs (map fst (but_last flds)) fargs;
   533                                         val more' = mk_ext rest;
   534                                     in list_comb (Syntax.const (suffix sfx ext),args@[more'])
   535                                     end
   536                              | NONE => raise TERM(msg ^ "no fields defined for "
   537                                                    ^ ext,[t]))
   538           | NONE => raise TERM (msg ^ name ^" is no proper field",[t]))
   539       | mk_ext [] = more
   540 
   541   in mk_ext fieldargs end;
   542 
   543 fun gen_ext_type_tr sep mark sfx more context t =
   544   let
   545     val thy = Context.theory_of context;
   546     val msg = "error in record-type input: ";
   547     val fieldargs = dest_ext_fields sep mark t;
   548     fun splitargs (field::fields) ((name,arg)::fargs) =
   549           if can (unsuffix name) field
   550           then let val (args,rest) = splitargs fields fargs
   551                in (arg::args,rest) end
   552           else raise TERM (msg ^ "expecting field " ^ field ^ " but got " ^ name, [t])
   553       | splitargs [] (fargs as (_::_)) = ([],fargs)
   554       | splitargs (_::_) [] = raise TERM (msg ^ "expecting more fields", [t])
   555       | splitargs _ _ = ([],[]);
   556 
   557     fun get_sort xs n = AList.lookup (op =) xs n |> the_default (Sign.defaultS thy);
   558 
   559     fun to_type t = Sign.certify_typ thy
   560                        (Sign.intern_typ thy
   561                          (Syntax.typ_of_term (get_sort (Syntax.raw_term_sorts t)) I t));
   562 
   563     fun mk_ext (fargs as (name,arg)::_) =
   564          (case get_fieldext thy (Sign.intern_const thy name) of
   565             SOME (ext,alphas) =>
   566               (case get_extfields thy ext of
   567                  SOME flds
   568                   => (let
   569                        val flds' = but_last flds;
   570                        val types = map snd flds';
   571                        val (args,rest) = splitargs (map fst flds') fargs;
   572                        val argtypes = map to_type args;
   573                        val midx =  fold (fn T => fn i => Int.max (maxidx_of_typ T, i)) 
   574                                     argtypes 0;
   575                        val varifyT = varifyT midx;
   576                        val vartypes = map varifyT types;
   577 
   578                        val subst = fold (Sign.typ_match thy) (vartypes ~~ argtypes)
   579                                             Vartab.empty;
   580                        val alphas' = map ((Syntax.term_of_typ (! Syntax.show_sorts)) o
   581                                           Envir.norm_type subst o varifyT)
   582                                          (but_last alphas);
   583 
   584                        val more' = mk_ext rest;
   585                      in list_comb (Syntax.const (suffix sfx ext),alphas'@[more'])
   586                      end handle TYPE_MATCH => raise
   587                            TERM (msg ^ "type is no proper record (extension)", [t]))
   588                | NONE => raise TERM (msg ^ "no fields defined for " ^ ext,[t]))
   589           | NONE => raise TERM (msg ^ name ^" is no proper field",[t]))
   590       | mk_ext [] = more
   591 
   592   in mk_ext fieldargs end;
   593 
   594 fun gen_adv_record_tr sep mark sfx unit context [t] =
   595       gen_ext_fields_tr sep mark sfx unit context t
   596   | gen_adv_record_tr _ _ _ _ _ ts = raise TERM ("gen_record_tr", ts);
   597 
   598 fun gen_adv_record_scheme_tr sep mark sfx context [t, more] =
   599       gen_ext_fields_tr sep mark sfx more context t
   600   | gen_adv_record_scheme_tr _ _ _ _ ts = raise TERM ("gen_record_scheme_tr", ts);
   601 
   602 fun gen_adv_record_type_tr sep mark sfx unit context [t] =
   603       gen_ext_type_tr sep mark sfx unit context t
   604   | gen_adv_record_type_tr _ _ _ _ _ ts = raise TERM ("gen_record_tr", ts);
   605 
   606 fun gen_adv_record_type_scheme_tr sep mark sfx context [t, more] =
   607       gen_ext_type_tr sep mark sfx more context t
   608   | gen_adv_record_type_scheme_tr _ _ _ _ ts = raise TERM ("gen_record_scheme_tr", ts);
   609 
   610 val adv_record_tr = gen_adv_record_tr "_fields" "_field" extN HOLogic.unit;
   611 val adv_record_scheme_tr = gen_adv_record_scheme_tr "_fields" "_field" extN;
   612 
   613 val adv_record_type_tr =
   614       gen_adv_record_type_tr "_field_types" "_field_type" ext_typeN
   615         (Syntax.term_of_typ false (HOLogic.unitT));
   616 val adv_record_type_scheme_tr =
   617       gen_adv_record_type_scheme_tr "_field_types" "_field_type" ext_typeN;
   618 
   619 
   620 val parse_translation =
   621  [("_record_update", record_update_tr),
   622   ("_update_name", update_name_tr)];
   623 
   624 val adv_parse_translation =
   625  [("_record",adv_record_tr),
   626   ("_record_scheme",adv_record_scheme_tr),
   627   ("_record_type",adv_record_type_tr),
   628   ("_record_type_scheme",adv_record_type_scheme_tr)];
   629 
   630 (* print translations *)
   631 
   632 val print_record_type_abbr = ref true;
   633 val print_record_type_as_fields = ref true;
   634 
   635 fun gen_field_upds_tr' mark sfx (tm as Const (name_field, _) $ t $ u) =
   636     (case try (unsuffix sfx) name_field of
   637       SOME name =>
   638         apfst (cons (Syntax.const mark $ Syntax.free name $ t)) (gen_field_upds_tr' mark sfx u)
   639      | NONE => ([], tm))
   640   | gen_field_upds_tr' _ _ tm = ([], tm);
   641 
   642 fun record_update_tr' tm =
   643   let val (ts, u) = gen_field_upds_tr' "_update" updateN tm in
   644     Syntax.const "_record_update" $ u $
   645       foldr1 (fn (v, w) => Syntax.const "_updates" $ v $ w) (rev ts)
   646   end;
   647 
   648 fun gen_field_tr' sfx tr' name =
   649   let val name_sfx = suffix sfx name
   650   in (name_sfx, fn [t, u] => tr' (Syntax.const name_sfx $ t $ u) | _ => raise Match) end;
   651 
   652 fun record_tr' sep mark record record_scheme unit context t =
   653   let
   654     val thy = Context.theory_of context;
   655     fun field_lst t =
   656       (case strip_comb t of
   657         (Const (ext,_),args as (_::_))
   658          => (case try (unsuffix extN) (Sign.intern_const thy ext) of
   659                SOME ext'
   660                => (case get_extfields thy ext' of
   661                      SOME flds
   662                      => (let
   663                           val (f::fs) = but_last (map fst flds);
   664                           val flds' = Sign.extern_const thy f :: map NameSpace.base fs;
   665                           val (args',more) = split_last args;
   666                          in (flds'~~args')@field_lst more end
   667                          handle Library.UnequalLengths => [("",t)])
   668                    | NONE => [("",t)])
   669              | NONE => [("",t)])
   670        | _ => [("",t)])
   671 
   672     val (flds,(_,more)) = split_last (field_lst t);
   673     val flds' = map (fn (n,t)=>Syntax.const mark$Syntax.const n$t) flds;
   674     val flds'' = foldr1 (fn (x,y) => Syntax.const sep$x$y) flds';
   675 
   676   in if null flds then raise Match
   677      else if unit more
   678           then Syntax.const record$flds''
   679           else Syntax.const record_scheme$flds''$more
   680   end
   681 
   682 fun gen_record_tr' name =
   683   let val name_sfx = suffix extN name;
   684       val unit = (fn Const ("Unity",_) => true | _ => false);
   685       fun tr' context ts = record_tr' "_fields" "_field" "_record" "_record_scheme" unit context
   686                        (list_comb (Syntax.const name_sfx,ts))
   687   in (name_sfx,tr')
   688   end
   689 
   690 fun print_translation names =
   691   map (gen_field_tr' updateN record_update_tr') names;
   692 
   693 
   694 (* record_type_abbr_tr' tries to reconstruct the record name type abbreviation from *)
   695 (* the (nested) extension types.                                                    *)
   696 fun record_type_abbr_tr' default_tr' abbr alphas zeta lastExt schemeT context tm =
   697   let
   698       val thy = Context.theory_of context;
   699       (* tm is term representation of a (nested) field type. We first reconstruct the      *)
   700       (* type from tm so that we can continue on the type level rather then the term level.*)
   701 
   702       fun get_sort xs n = AList.lookup (op =) xs n |> the_default (Sign.defaultS thy);
   703 
   704       (* WORKAROUND:
   705        * If a record type occurs in an error message of type inference there
   706        * may be some internal frees donoted by ??:
   707        * (Const "_tfree",_)$Free ("??'a",_).
   708 
   709        * This will unfortunately be translated to Type ("??'a",[]) instead of
   710        * TFree ("??'a",_) by typ_of_term, which will confuse unify below.
   711        * fixT works around.
   712        *)
   713       fun fixT (T as Type (x,[])) =
   714             if String.isPrefix "??'" x then TFree (x,Sign.defaultS thy) else T
   715         | fixT (Type (x,xs)) = Type (x,map fixT xs)
   716         | fixT T = T;
   717 
   718       val T = fixT (Sign.intern_typ thy
   719                       (Syntax.typ_of_term (get_sort (Syntax.raw_term_sorts tm)) I tm));
   720       val midx = maxidx_of_typ T;
   721       val varifyT = varifyT midx;
   722 
   723       fun mk_type_abbr subst name alphas =
   724           let val abbrT = Type (name, map (fn a => varifyT (TFree (a, Sign.defaultS thy))) alphas);
   725           in Syntax.term_of_typ (! Syntax.show_sorts)
   726                (Sign.extern_typ thy (Envir.norm_type subst abbrT)) end;
   727 
   728       fun match rT T = (Sign.typ_match thy (varifyT rT,T) 
   729                                                 Vartab.empty);
   730 
   731    in if !print_record_type_abbr
   732       then (case last_extT T of
   733              SOME (name,_)
   734               => if name = lastExt
   735                  then
   736                   (let
   737                      val subst = match schemeT T
   738                    in
   739                     if HOLogic.is_unitT (Envir.norm_type subst (varifyT (TFree(zeta,Sign.defaultS thy))))
   740                     then mk_type_abbr subst abbr alphas
   741                     else mk_type_abbr subst (suffix schemeN abbr) (alphas@[zeta])
   742                    end handle TYPE_MATCH => default_tr' context tm)
   743                  else raise Match (* give print translation of specialised record a chance *)
   744             | _ => raise Match)
   745        else default_tr' context tm
   746   end
   747 
   748 fun record_type_tr' sep mark record record_scheme context t =
   749   let
   750     val thy = Context.theory_of context;
   751     fun get_sort xs n = AList.lookup (op =) xs n |> the_default (Sign.defaultS thy);
   752 
   753     val T = Sign.intern_typ thy (Syntax.typ_of_term (get_sort (Syntax.raw_term_sorts t)) I t)
   754     val varifyT = varifyT (Term.maxidx_of_typ T)
   755 
   756     fun term_of_type T = Syntax.term_of_typ (!Syntax.show_sorts) (Sign.extern_typ thy T);
   757 
   758     fun field_lst T =
   759       (case T of
   760         Type (ext,args)
   761          => (case try (unsuffix ext_typeN) ext of
   762                SOME ext'
   763                => (case get_extfields thy ext' of
   764                      SOME flds
   765                      => (case get_fieldext thy (fst (hd flds)) of
   766                            SOME (_,alphas)
   767                            => (let
   768                                 val (f::fs) = but_last flds;
   769                                 val flds' = apfst (Sign.extern_const thy) f
   770                                             ::map (apfst NameSpace.base) fs;
   771                                 val (args',more) = split_last args;
   772                                 val alphavars = map varifyT (but_last alphas);
   773                                 val subst= fold (Sign.typ_match thy) (alphavars~~args')
   774                                                     Vartab.empty;
   775                                 val flds'' =map (apsnd (Envir.norm_type subst o varifyT))
   776                                                 flds';
   777                               in flds''@field_lst more end
   778                               handle TYPE_MATCH     => [("",T)]
   779                                    | Library.UnequalLengths => [("",T)])
   780                          | NONE => [("",T)])
   781                    | NONE => [("",T)])
   782              | NONE => [("",T)])
   783         | _ => [("",T)])
   784 
   785     val (flds,(_,moreT)) = split_last (field_lst T);
   786     val flds' = map (fn (n,T)=>Syntax.const mark$Syntax.const n$term_of_type T) flds;
   787     val flds'' = foldr1 (fn (x,y) => Syntax.const sep$x$y) flds';
   788 
   789   in if not (!print_record_type_as_fields) orelse null flds then raise Match
   790      else if moreT = HOLogic.unitT
   791           then Syntax.const record$flds''
   792           else Syntax.const record_scheme$flds''$term_of_type moreT
   793   end
   794 
   795 
   796 fun gen_record_type_tr' name =
   797   let val name_sfx = suffix ext_typeN name;
   798       fun tr' context ts = record_type_tr' "_field_types" "_field_type"
   799                        "_record_type" "_record_type_scheme" context
   800                        (list_comb (Syntax.const name_sfx,ts))
   801   in (name_sfx,tr')
   802   end
   803 
   804 
   805 fun gen_record_type_abbr_tr' abbr alphas zeta lastExt schemeT name =
   806   let val name_sfx = suffix ext_typeN name;
   807       val default_tr' = record_type_tr' "_field_types" "_field_type"
   808                                "_record_type" "_record_type_scheme"
   809       fun tr' context ts =
   810           record_type_abbr_tr' default_tr' abbr alphas zeta lastExt schemeT context
   811                                (list_comb (Syntax.const name_sfx,ts))
   812   in (name_sfx, tr') end;
   813 
   814 (** record simprocs **)
   815 
   816 val record_quick_and_dirty_sensitive = ref false;
   817 
   818 
   819 fun quick_and_dirty_prove stndrd thy asms prop tac =
   820   if !record_quick_and_dirty_sensitive andalso !quick_and_dirty
   821   then Goal.prove (ProofContext.init thy) [] []
   822         (Logic.list_implies (map Logic.varify asms,Logic.varify prop))
   823         (K (SkipProof.cheat_tac HOL.thy))
   824         (* standard can take quite a while for large records, thats why
   825          * we varify the proposition manually here.*)
   826   else let val prf = Goal.prove (ProofContext.init thy) [] asms prop tac;
   827        in if stndrd then standard prf else prf end;
   828 
   829 fun quick_and_dirty_prf noopt opt () =
   830       if !record_quick_and_dirty_sensitive andalso !quick_and_dirty
   831       then noopt ()
   832       else opt ();
   833 
   834 
   835 fun prove_split_simp thy ss T prop =
   836   let
   837     val {sel_upd={simpset,...},extsplit,...} = RecordsData.get thy;
   838     val extsplits =
   839             Library.foldl (fn (thms,(n,_)) => the_list (Symtab.lookup extsplit n) @ thms)
   840                     ([],dest_recTs T);
   841     val thms = (case get_splits thy (rec_id (~1) T) of
   842                    SOME (all_thm,_,_,_) =>
   843                      all_thm::(case extsplits of [thm] => [] | _ => extsplits)
   844                               (* [thm] is the same as all_thm *)
   845                  | NONE => extsplits)
   846   in
   847     quick_and_dirty_prove true thy [] prop
   848       (fn _ => simp_tac (Simplifier.inherit_context ss simpset addsimps thms) 1)
   849   end;
   850 
   851 
   852 local
   853 fun eq (s1:string) (s2:string) = (s1 = s2);
   854 fun has_field extfields f T =
   855      exists (fn (eN,_) => exists (eq f o fst) (Symtab.lookup_list extfields eN))
   856        (dest_recTs T);
   857 in
   858 (* record_simproc *)
   859 (* Simplifies selections of an record update:
   860  *  (1)  S (r(|S:=k|)) = k respectively
   861  *  (2)  S (r(|X:=k|)) = S r
   862  * The simproc skips multiple updates at once, eg:
   863  *  S (r (|S:=k,X:=2,Y:=3|)) = k
   864  * But be careful in (2) because of the extendibility of records.
   865  * - If S is a more-selector we have to make sure that the update on component
   866  *   X does not affect the selected subrecord.
   867  * - If X is a more-selector we have to make sure that S is not in the updated
   868  *   subrecord.
   869  *)
   870 val record_simproc =
   871   Simplifier.simproc HOL.thy "record_simp" ["x"]
   872     (fn thy => fn ss => fn t =>
   873       (case t of (sel as Const (s, Type (_,[domS,rangeS])))$
   874                    ((upd as Const (u,Type(_,[_,Type (_,[rT,_])]))) $ k $ r)=>
   875         if is_selector thy s then
   876           (case get_updates thy u of SOME u_name =>
   877             let
   878               val {sel_upd={updates,...},extfields,...} = RecordsData.get thy;
   879 
   880               fun mk_eq_terms ((upd as Const (u,Type(_,[kT,_]))) $ k $ r) =
   881                   (case Symtab.lookup updates u of
   882                      NONE => NONE
   883                    | SOME u_name
   884                      => if u_name = s
   885                         then let
   886                                val rv = ("r",rT)
   887                                val rb = Bound 0
   888                                val kv = ("k",kT)
   889                                val kb = Bound 1
   890                              in SOME (upd$kb$rb,kb,[kv,rv],true) end
   891                         else if has_field extfields u_name rangeS
   892                              orelse has_field extfields s kT
   893                              then NONE
   894                              else (case mk_eq_terms r of
   895                                      SOME (trm,trm',vars,update_s)
   896                                      => let
   897                                           val kv = ("k",kT)
   898                                           val kb = Bound (length vars)
   899                                         in SOME (upd$kb$trm,trm',kv::vars,update_s) end
   900                                    | NONE
   901                                      => let
   902                                           val rv = ("r",rT)
   903                                           val rb = Bound 0
   904                                           val kv = ("k",kT)
   905                                           val kb = Bound 1
   906                                         in SOME (upd$kb$rb,rb,[kv,rv],false) end))
   907                 | mk_eq_terms r = NONE
   908             in
   909               (case mk_eq_terms (upd$k$r) of
   910                  SOME (trm,trm',vars,update_s)
   911                  => if update_s
   912                     then SOME (prove_split_simp thy ss domS
   913                                  (list_all(vars,(equals rangeS$(sel$trm)$trm'))))
   914                     else SOME (prove_split_simp thy ss domS
   915                                  (list_all(vars,(equals rangeS$(sel$trm)$(sel$trm')))))
   916                | NONE => NONE)
   917             end
   918           | NONE => NONE)
   919         else NONE
   920       | _ => NONE));
   921 
   922 (* record_upd_simproc *)
   923 (* simplify multiple updates:
   924  *  (1)  "r(|M:=3,N:=1,M:=2,N:=4|) == r(|M:=2,N:=4|)"
   925  *  (2)  "r(|M:= M r|) = r"
   926  * For (2) special care of "more" updates has to be taken:
   927  *    r(|more := m; A := A r|)
   928  * If A is contained in the fields of m we cannot remove the update A := A r!
   929  * (But r(|more := r; A := A (r(|more := r|))|) = r(|more := r|)
   930 *)
   931 val record_upd_simproc =
   932   Simplifier.simproc HOL.thy "record_upd_simp" ["x"]
   933     (fn thy => fn ss => fn t =>
   934       (case t of ((upd as Const (u, Type(_,[_,Type(_,[rT,_])]))) $ k $ r) =>
   935          let datatype ('a,'b) calc = Init of 'b | Inter of 'a
   936              val {sel_upd={selectors,updates,...},extfields,...} = RecordsData.get thy;
   937 
   938              (*fun mk_abs_var x t = (x, fastype_of t);*)
   939              fun sel_name u = NameSpace.base (unsuffix updateN u);
   940 
   941              fun seed s (upd as Const (more,Type(_,[mT,_]))$ k $ r) =
   942                   if has_field extfields s mT then upd else seed s r
   943                | seed _ r = r;
   944 
   945              fun grow u uT k kT vars (sprout,skeleton) =
   946                    if sel_name u = moreN
   947                    then let val kv = ("k", kT);
   948                             val kb = Bound (length vars);
   949                         in ((Const (u,uT)$k$sprout,Const (u,uT)$kb$skeleton),kv::vars) end
   950                    else ((sprout,skeleton),vars);
   951 
   952              fun is_upd_same (sprout,skeleton) u ((sel as Const (s,_))$r) =
   953                    if (unsuffix updateN u) = s andalso (seed s sprout) = r
   954                    then SOME (sel,seed s skeleton)
   955                    else NONE
   956                | is_upd_same _ _ _ = NONE
   957 
   958              fun init_seed r = ((r,Bound 0), [("r", rT)]);
   959 
   960              (* mk_updterm returns either
   961               *  - Init (orig-term, orig-term-skeleton, vars) if no optimisation can be made,
   962               *     where vars are the bound variables in the skeleton
   963               *  - Inter (orig-term-skeleton,simplified-term-skeleton,
   964               *           vars, (term-sprout, skeleton-sprout))
   965               *     where "All vars. orig-term-skeleton = simplified-term-skeleton" is
   966               *     the desired simplification rule,
   967               *     the sprouts accumulate the "more-updates" on the way from the seed
   968               *     to the outermost update. It is only relevant to calculate the
   969               *     possible simplification for (2)
   970               * The algorithm first walks down the updates to the seed-record while
   971               * memorising the updates in the already-table. While walking up the
   972               * updates again, the optimised term is constructed.
   973               *)
   974              fun mk_updterm upds already
   975                  (t as ((upd as Const (u,uT as (Type (_,[kT,_])))) $ k $ r)) =
   976                  if Symtab.defined upds u
   977                  then let
   978                          fun rest already = mk_updterm upds already
   979                       in if u mem_string already
   980                          then (case (rest already r) of
   981                                  Init ((sprout,skel),vars) =>
   982                                  let
   983                                    val kv = (sel_name u, kT);
   984                                    val kb = Bound (length vars);
   985                                    val (sprout',vars')= grow u uT k kT (kv::vars) (sprout,skel);
   986                                  in Inter (upd$kb$skel,skel,vars',sprout') end
   987                                | Inter (trm,trm',vars,sprout) =>
   988                                  let
   989                                    val kv = (sel_name u, kT);
   990                                    val kb = Bound (length vars);
   991                                    val (sprout',vars') = grow u uT k kT (kv::vars) sprout;
   992                                  in Inter(upd$kb$trm,trm',kv::vars',sprout') end)
   993                          else
   994                           (case rest (u::already) r of
   995                              Init ((sprout,skel),vars) =>
   996                               (case is_upd_same (sprout,skel) u k of
   997                                  SOME (sel,skel') =>
   998                                  let
   999                                    val (sprout',vars') = grow u uT k kT vars (sprout,skel);
  1000                                   in Inter(upd$(sel$skel')$skel,skel,vars',sprout') end
  1001                                | NONE =>
  1002                                  let
  1003                                    val kv = (sel_name u, kT);
  1004                                    val kb = Bound (length vars);
  1005                                  in Init ((upd$k$sprout,upd$kb$skel),kv::vars) end)
  1006                            | Inter (trm,trm',vars,sprout) =>
  1007                                (case is_upd_same sprout u k of
  1008                                   SOME (sel,skel) =>
  1009                                   let
  1010                                     val (sprout',vars') = grow u uT k kT vars sprout
  1011                                   in Inter(upd$(sel$skel)$trm,trm',vars',sprout') end
  1012                                 | NONE =>
  1013                                   let
  1014                                     val kv = (sel_name u, kT)
  1015                                     val kb = Bound (length vars)
  1016                                     val (sprout',vars') = grow u uT k kT (kv::vars) sprout
  1017                                   in Inter (upd$kb$trm,upd$kb$trm',vars',sprout') end))
  1018                       end
  1019                  else Init (init_seed t)
  1020                | mk_updterm _ _ t = Init (init_seed t);
  1021 
  1022          in (case mk_updterm updates [] t of
  1023                Inter (trm,trm',vars,_)
  1024                 => SOME (prove_split_simp thy ss rT
  1025                           (list_all(vars,(equals rT$trm$trm'))))
  1026              | _ => NONE)
  1027          end
  1028        | _ => NONE));
  1029 end
  1030 
  1031 (* record_eq_simproc *)
  1032 (* looks up the most specific record-equality.
  1033  * Note on efficiency:
  1034  * Testing equality of records boils down to the test of equality of all components.
  1035  * Therefore the complexity is: #components * complexity for single component.
  1036  * Especially if a record has a lot of components it may be better to split up
  1037  * the record first and do simplification on that (record_split_simp_tac).
  1038  * e.g. r(|lots of updates|) = x
  1039  *
  1040  *               record_eq_simproc       record_split_simp_tac
  1041  * Complexity: #components * #updates     #updates
  1042  *
  1043  *)
  1044 val record_eq_simproc =
  1045   Simplifier.simproc HOL.thy "record_eq_simp" ["r = s"]
  1046     (fn thy => fn _ => fn t =>
  1047       (case t of Const ("op =", Type (_, [T, _])) $ _ $ _ =>
  1048         (case rec_id (~1) T of
  1049            "" => NONE
  1050          | name => (case get_equalities thy name of
  1051                                 NONE => NONE
  1052                               | SOME thm => SOME (thm RS Eq_TrueI)))
  1053        | _ => NONE));
  1054 
  1055 (* record_split_simproc *)
  1056 (* splits quantified occurrences of records, for which P holds. P can peek on the
  1057  * subterm starting at the quantified occurrence of the record (including the quantifier)
  1058  * P t = 0: do not split
  1059  * P t = ~1: completely split
  1060  * P t > 0: split up to given bound of record extensions
  1061  *)
  1062 fun record_split_simproc P =
  1063   Simplifier.simproc HOL.thy "record_split_simp" ["x"]
  1064     (fn thy => fn _ => fn t =>
  1065       (case t of (Const (quantifier, Type (_, [Type (_, [T, _]), _])))$trm =>
  1066          if quantifier = "All" orelse quantifier = "all" orelse quantifier = "Ex"
  1067          then (case rec_id (~1) T of
  1068                  "" => NONE
  1069                | name
  1070                   => let val split = P t
  1071                      in if split <> 0 then
  1072                         (case get_splits thy (rec_id split T) of
  1073                               NONE => NONE
  1074                             | SOME (all_thm, All_thm, Ex_thm,_)
  1075                                => SOME (case quantifier of
  1076                                           "all" => all_thm
  1077                                         | "All" => All_thm RS HOL.eq_reflection
  1078                                         | "Ex"  => Ex_thm RS HOL.eq_reflection
  1079                                         | _     => error "record_split_simproc"))
  1080                         else NONE
  1081                       end)
  1082          else NONE
  1083        | _ => NONE))
  1084 
  1085 val record_ex_sel_eq_simproc =
  1086   Simplifier.simproc HOL.thy "record_ex_sel_eq_simproc" ["Ex t"]
  1087     (fn thy => fn ss => fn t =>
  1088        let
  1089          fun prove prop =
  1090            quick_and_dirty_prove true thy [] prop
  1091              (fn _ => simp_tac (Simplifier.inherit_context ss (get_simpset thy)
  1092                addsimps simp_thms addsimprocs [record_split_simproc (K ~1)]) 1);
  1093 
  1094          fun mkeq (lr,Teq,(sel,Tsel),x) i =
  1095               if is_selector thy sel then
  1096                  let val x' = if not (loose_bvar1 (x,0))
  1097                               then Free ("x" ^ string_of_int i, range_type Tsel)
  1098                               else raise TERM ("",[x]);
  1099                      val sel' = Const (sel,Tsel)$Bound 0;
  1100                      val (l,r) = if lr then (sel',x') else (x',sel');
  1101                   in Const ("op =",Teq)$l$r end
  1102               else raise TERM ("",[Const (sel,Tsel)]);
  1103 
  1104          fun dest_sel_eq (Const ("op =",Teq)$(Const (sel,Tsel)$Bound 0)$X) =
  1105                            (true,Teq,(sel,Tsel),X)
  1106            | dest_sel_eq (Const ("op =",Teq)$X$(Const (sel,Tsel)$Bound 0)) =
  1107                            (false,Teq,(sel,Tsel),X)
  1108            | dest_sel_eq _ = raise TERM ("",[]);
  1109 
  1110        in
  1111          (case t of
  1112            (Const ("Ex",Tex)$Abs(s,T,t)) =>
  1113              (let val eq = mkeq (dest_sel_eq t) 0;
  1114                  val prop = list_all ([("r",T)],
  1115                               Logic.mk_equals (Const ("Ex",Tex)$Abs(s,T,eq),
  1116                                                HOLogic.true_const));
  1117              in SOME (prove prop) end
  1118              handle TERM _ => NONE)
  1119           | _ => NONE)
  1120          end)
  1121 
  1122 
  1123 
  1124 
  1125 local
  1126 val inductive_atomize = thms "induct_atomize";
  1127 val inductive_rulify = thms "induct_rulify";
  1128 in
  1129 (* record_split_simp_tac *)
  1130 (* splits (and simplifies) all records in the goal for which P holds.
  1131  * For quantified occurrences of a record
  1132  * P can peek on the whole subterm (including the quantifier); for free variables P
  1133  * can only peek on the variable itself.
  1134  * P t = 0: do not split
  1135  * P t = ~1: completely split
  1136  * P t > 0: split up to given bound of record extensions
  1137  *)
  1138 fun record_split_simp_tac thms P i st =
  1139   let
  1140     val thy = Thm.theory_of_thm st;
  1141 
  1142     val has_rec = exists_Const
  1143       (fn (s, Type (_, [Type (_, [T, _]), _])) =>
  1144           (s = "all" orelse s = "All" orelse s = "Ex") andalso is_recT T
  1145         | _ => false);
  1146 
  1147     val goal = nth (Thm.prems_of st) (i - 1);
  1148     val frees = List.filter (is_recT o type_of) (term_frees goal);
  1149 
  1150     fun mk_split_free_tac free induct_thm i =
  1151         let val cfree = cterm_of thy free;
  1152             val (_$(_$r)) = concl_of induct_thm;
  1153             val crec = cterm_of thy r;
  1154             val thm  = cterm_instantiate [(crec,cfree)] induct_thm;
  1155         in EVERY [simp_tac (HOL_basic_ss addsimps inductive_atomize) i,
  1156                   rtac thm i,
  1157                   simp_tac (HOL_basic_ss addsimps inductive_rulify) i]
  1158         end;
  1159 
  1160     fun split_free_tac P i (free as Free (n,T)) =
  1161         (case rec_id (~1) T of
  1162            "" => NONE
  1163          | name => let val split = P free
  1164                    in if split <> 0 then
  1165                       (case get_splits thy (rec_id split T) of
  1166                              NONE => NONE
  1167                            | SOME (_,_,_,induct_thm)
  1168                                => SOME (mk_split_free_tac free induct_thm i))
  1169                       else NONE
  1170                    end)
  1171      | split_free_tac _ _ _ = NONE;
  1172 
  1173     val split_frees_tacs = List.mapPartial (split_free_tac P i) frees;
  1174 
  1175     val simprocs = if has_rec goal then [record_split_simproc P] else [];
  1176 
  1177   in st |> ((EVERY split_frees_tacs)
  1178            THEN (Simplifier.full_simp_tac (get_simpset thy addsimps thms addsimprocs simprocs) i))
  1179   end handle Empty => Seq.empty;
  1180 end;
  1181 
  1182 
  1183 (* record_split_tac *)
  1184 (* splits all records in the goal, which are quantified by ! or !!. *)
  1185 fun record_split_tac i st =
  1186   let
  1187     val thy = Thm.theory_of_thm st;
  1188 
  1189     val has_rec = exists_Const
  1190       (fn (s, Type (_, [Type (_, [T, _]), _])) =>
  1191           (s = "all" orelse s = "All") andalso is_recT T
  1192         | _ => false);
  1193 
  1194     val goal = nth (Thm.prems_of st) (i - 1);
  1195 
  1196     fun is_all t =
  1197       (case t of (Const (quantifier, _)$_) =>
  1198          if quantifier = "All" orelse quantifier = "all" then ~1 else 0
  1199        | _ => 0);
  1200 
  1201   in if has_rec goal
  1202      then Simplifier.full_simp_tac
  1203            (HOL_basic_ss addsimprocs [record_split_simproc is_all]) i st
  1204      else Seq.empty
  1205   end handle Subscript => Seq.empty;
  1206 
  1207 (* wrapper *)
  1208 
  1209 val record_split_name = "record_split_tac";
  1210 val record_split_wrapper = (record_split_name, fn tac => record_split_tac ORELSE' tac);
  1211 
  1212 
  1213 
  1214 (** theory extender interface **)
  1215 
  1216 (* prepare arguments *)
  1217 
  1218 fun read_raw_parent sign s =
  1219   (case Sign.read_typ_abbrev (sign, K NONE) s handle TYPE (msg, _, _) => error msg of
  1220     Type (name, Ts) => (Ts, name)
  1221   | _ => error ("Bad parent record specification: " ^ quote s));
  1222 
  1223 fun read_typ sign (env, s) =
  1224   let
  1225     fun def_sort (x, ~1) = AList.lookup (op =) env x
  1226       | def_sort _ = NONE;
  1227     val T = Type.no_tvars (Sign.read_typ (sign, def_sort) s) handle TYPE (msg, _, _) => error msg;
  1228   in (Term.add_typ_tfrees (T, env), T) end;
  1229 
  1230 fun cert_typ sign (env, raw_T) =
  1231   let val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle TYPE (msg, _, _) => error msg
  1232   in (Term.add_typ_tfrees (T, env), T) end;
  1233 
  1234 (* attributes *)
  1235 
  1236 fun case_names_fields x = RuleCases.case_names ["fields"] x;
  1237 fun induct_type_global name = [case_names_fields, InductAttrib.induct_type name];
  1238 fun cases_type_global name = [case_names_fields, InductAttrib.cases_type name];
  1239 
  1240 (* tactics *)
  1241 
  1242 fun simp_all_tac ss simps = ALLGOALS (Simplifier.asm_full_simp_tac (ss addsimps simps));
  1243 
  1244 (* do case analysis / induction according to rule on last parameter of ith subgoal
  1245  * (or on s if there are no parameters);
  1246  * Instatiation of record variable (and predicate) in rule is calculated to
  1247  * avoid problems with higher order unification.
  1248  *)
  1249 
  1250 fun try_param_tac s rule i st =
  1251   let
  1252     val cert = cterm_of (Thm.theory_of_thm st);
  1253     val g = nth (prems_of st) (i - 1);
  1254     val params = Logic.strip_params g;
  1255     val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl g);
  1256     val rule' = Thm.lift_rule (Thm.cprem_of st i) rule;
  1257     val (P, ys) = strip_comb (HOLogic.dest_Trueprop
  1258       (Logic.strip_assums_concl (prop_of rule')));
  1259     (* ca indicates if rule is a case analysis or induction rule *)
  1260     val (x, ca) = (case rev (Library.drop (length params, ys)) of
  1261         [] => (head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
  1262           (hd (rev (Logic.strip_assums_hyp (hd (prems_of rule')))))))), true)
  1263       | [x] => (head_of x, false));
  1264     val rule'' = cterm_instantiate (map (pairself cert) (case (rev params) of
  1265         [] => (case AList.lookup (op =) (map dest_Free (term_frees (prop_of st))) s of
  1266           NONE => sys_error "try_param_tac: no such variable"
  1267         | SOME T => [(P, if ca then concl else lambda (Free (s, T)) concl),
  1268             (x, Free (s, T))])
  1269       | (_, T) :: _ => [(P, list_abs (params, if ca then concl
  1270           else incr_boundvars 1 (Abs (s, T, concl)))),
  1271         (x, list_abs (params, Bound 0))])) rule'
  1272   in compose_tac (false, rule'', nprems_of rule) i st end;
  1273 
  1274 
  1275 (* !!x1 ... xn. ... ==> EX x1 ... xn. P x1 ... xn;
  1276    instantiates x1 ... xn with parameters x1 ... xn *)
  1277 fun ex_inst_tac i st =
  1278   let
  1279     val thy = Thm.theory_of_thm st;
  1280     val g = nth (prems_of st) (i - 1);
  1281     val params = Logic.strip_params g;
  1282     val exI' = Thm.lift_rule (Thm.cprem_of st i) exI;
  1283     val (_$(_$x)) = Logic.strip_assums_concl (hd (prems_of exI'));
  1284     val cx = cterm_of thy (fst (strip_comb x));
  1285 
  1286   in Seq.single (Library.foldl (fn (st,v) =>
  1287         Seq.hd
  1288         (compose_tac (false, cterm_instantiate
  1289                                 [(cx,cterm_of thy (list_abs (params,Bound v)))] exI',1)
  1290                 i st)) (st,((length params) - 1) downto 0))
  1291   end;
  1292 
  1293 fun extension_typedef name repT alphas thy =
  1294   let
  1295     val UNIV = HOLogic.mk_UNIV repT;
  1296 
  1297     val ({set_def=SOME def, Abs_induct = abs_induct,
  1298                Abs_inject=abs_inject, Abs_inverse = abs_inverse,...}, thy') =
  1299         thy
  1300         |> setmp TypedefPackage.quiet_mode true
  1301            (TypedefPackage.add_typedef_i true NONE
  1302              (suffix ext_typeN (Sign.base_name name), alphas, Syntax.NoSyn) UNIV NONE
  1303              (Tactic.rtac UNIV_witness 1))
  1304     val rewrite_rule = Tactic.rewrite_rule [def, rec_UNIV_I, rec_True_simp];
  1305   in (map rewrite_rule [abs_inject, abs_inverse, abs_induct], thy')
  1306   end;
  1307 
  1308 fun mixit convs refls =
  1309   let fun f ((res,lhs,rhs),refl) = ((refl,List.revAppend (lhs,refl::tl rhs))::res,hd rhs::lhs,tl rhs);
  1310   in #1 (Library.foldl f (([],[],convs),refls)) end;
  1311 
  1312 fun extension_definition full name fields names alphas zeta moreT more vars thy =
  1313   let
  1314     val base = Sign.base_name;
  1315     val fieldTs = (map snd fields);
  1316     val alphas_zeta = alphas@[zeta];
  1317     val alphas_zetaTs = map (fn n => TFree (n, HOLogic.typeS)) alphas_zeta;
  1318     val vT = TFree (Name.variant alphas_zeta "'v", HOLogic.typeS);
  1319     val extT_name = suffix ext_typeN name
  1320     val extT = Type (extT_name, alphas_zetaTs);
  1321     val repT = foldr1 HOLogic.mk_prodT (fieldTs@[moreT]);
  1322     val fields_more = fields@[(full moreN,moreT)];
  1323     val fields_moreTs = fieldTs@[moreT];
  1324     val bfields_more = map (apfst base) fields_more;
  1325     val r = Free (rN,extT)
  1326     val len = length fields;
  1327     val idxms = 0 upto len;
  1328 
  1329     (* prepare declarations and definitions *)
  1330 
  1331     (*fields constructor*)
  1332     val ext_decl = (mk_extC (name,extT) fields_moreTs);
  1333     (*
  1334     val ext_spec = Const ext_decl :==
  1335          (foldr (uncurry lambda)
  1336             (mk_Abs name repT extT $ (foldr1 HOLogic.mk_prod (vars@[more]))) (vars@[more]))
  1337     *)
  1338     val ext_spec = list_comb (Const ext_decl,vars@[more]) :==
  1339          (mk_Abs name repT extT $ (foldr1 HOLogic.mk_prod (vars@[more])));
  1340 
  1341     fun mk_ext args = list_comb (Const ext_decl, args);
  1342 
  1343     (*destructors*)
  1344     val _ = timing_msg "record extension preparing definitions";
  1345     val dest_decls = map (mk_selC extT o (apfst (suffix ext_dest))) bfields_more;
  1346 
  1347     fun mk_dest_spec (i, (c,T)) =
  1348       let val snds = (funpow i HOLogic.mk_snd (mk_Rep name repT extT $ r))
  1349       in Const (mk_selC extT (suffix ext_dest c,T))
  1350          :== (lambda r (if i=len then snds else HOLogic.mk_fst snds))
  1351       end;
  1352     val dest_specs =
  1353       ListPair.map mk_dest_spec (idxms, fields_more);
  1354 
  1355     (*updates*)
  1356     val upd_decls = map (mk_updC updN extT) bfields_more;
  1357     fun mk_upd_spec (c,T) =
  1358       let
  1359         val args = map (fn (n,nT) => if n=c then Free (base c,T)
  1360                                      else (mk_sel r (suffix ext_dest n,nT)))
  1361                        fields_more;
  1362       in Const (mk_updC updN extT (c,T))$(Free (base c,T))$r
  1363           :== mk_ext args
  1364       end;
  1365     val upd_specs = map mk_upd_spec fields_more;
  1366 
  1367     (* 1st stage: defs_thy *)
  1368     fun mk_defs () =
  1369       thy
  1370         |> extension_typedef name repT (alphas@[zeta])
  1371         ||> Theory.add_consts_i
  1372               (map Syntax.no_syn ((apfst base ext_decl)::dest_decls@upd_decls))
  1373         ||>> PureThy.add_defs_i false (map Thm.no_attributes (ext_spec::dest_specs))
  1374         ||>> PureThy.add_defs_i false (map Thm.no_attributes upd_specs)
  1375         |> swap
  1376     val (defs_thy, (([abs_inject, abs_inverse, abs_induct],ext_def::dest_defs),upd_defs)) =
  1377         timeit_msg "record extension type/selector/update defs:" mk_defs;
  1378 
  1379 
  1380     (* prepare propositions *)
  1381     val _ = timing_msg "record extension preparing propositions";
  1382     val vars_more = vars@[more];
  1383     val named_vars_more = (names@[full moreN])~~vars_more;
  1384     val variants = map (fn (Free (x,_))=>x) vars_more;
  1385     val ext = mk_ext vars_more;
  1386     val s     = Free (rN, extT);
  1387     val w     = Free (wN, extT);
  1388     val P = Free (Name.variant variants "P", extT-->HOLogic.boolT);
  1389     val C = Free (Name.variant variants "C", HOLogic.boolT);
  1390 
  1391     val inject_prop =
  1392       let val vars_more' = map (fn (Free (x,T)) => Free (x ^ "'",T)) vars_more;
  1393       in All (map dest_Free (vars_more@vars_more'))
  1394           ((HOLogic.eq_const extT $
  1395             mk_ext vars_more$mk_ext vars_more')
  1396            ===
  1397            foldr1 HOLogic.mk_conj (map HOLogic.mk_eq (vars_more ~~ vars_more')))
  1398       end;
  1399 
  1400     val induct_prop =
  1401       (All (map dest_Free vars_more) (Trueprop (P $ ext)), Trueprop (P $ s));
  1402 
  1403     val cases_prop =
  1404       (All (map dest_Free vars_more)
  1405         (Trueprop (HOLogic.mk_eq (s,ext)) ==> Trueprop C))
  1406       ==> Trueprop C;
  1407 
  1408     (*destructors*)
  1409     val dest_conv_props =
  1410        map (fn (c, x as Free (_,T)) => mk_sel ext (suffix ext_dest c,T) === x) named_vars_more;
  1411 
  1412     (*updates*)
  1413     fun mk_upd_prop (i,(c,T)) =
  1414       let val x' = Free (Name.variant variants (base c ^ "'"),T)
  1415           val args' = nth_update (i, x') vars_more
  1416       in mk_upd updN c x' ext === mk_ext args'  end;
  1417     val upd_conv_props = ListPair.map mk_upd_prop (idxms, fields_more);
  1418 
  1419     val surjective_prop =
  1420       let val args =
  1421            map (fn (c, Free (_,T)) => mk_sel s (suffix ext_dest c,T)) named_vars_more;
  1422       in s === mk_ext args end;
  1423 
  1424     val split_meta_prop =
  1425       let val P = Free (Name.variant variants "P", extT-->Term.propT) in
  1426         Logic.mk_equals
  1427          (All [dest_Free s] (P $ s), All (map dest_Free vars_more) (P $ ext))
  1428       end;
  1429 
  1430     fun prove stndrd = quick_and_dirty_prove stndrd defs_thy;
  1431     val prove_standard = quick_and_dirty_prove true defs_thy;
  1432     fun prove_simp stndrd simps =
  1433       let val tac = simp_all_tac HOL_ss simps
  1434       in fn prop => prove stndrd [] prop (K tac) end;
  1435 
  1436     fun inject_prf () = (prove_simp true [ext_def,abs_inject,Pair_eq] inject_prop);
  1437     val inject = timeit_msg "record extension inject proof:" inject_prf;
  1438 
  1439     fun induct_prf () =
  1440       let val (assm, concl) = induct_prop
  1441       in prove_standard [assm] concl (fn {prems, ...} =>
  1442            EVERY [try_param_tac rN abs_induct 1,
  1443                   simp_tac (HOL_ss addsimps [split_paired_all]) 1,
  1444                   resolve_tac (map (rewrite_rule [ext_def]) prems) 1])
  1445       end;
  1446     val induct = timeit_msg "record extension induct proof:" induct_prf;
  1447 
  1448     fun cases_prf_opt () =
  1449       let
  1450         val (_$(Pvar$_)) = concl_of induct;
  1451         val ind = cterm_instantiate
  1452                     [(cterm_of defs_thy Pvar, cterm_of defs_thy
  1453                             (lambda w (HOLogic.imp$HOLogic.mk_eq(r,w)$C)))]
  1454                     induct;
  1455         in standard (ObjectLogic.rulify (mp OF [ind, refl])) end;
  1456 
  1457     fun cases_prf_noopt () =
  1458         prove_standard [] cases_prop (fn prems =>
  1459          EVERY [asm_full_simp_tac (HOL_basic_ss addsimps [atomize_all, atomize_imp]) 1,
  1460                 try_param_tac rN induct 1,
  1461                 rtac impI 1,
  1462                 REPEAT (etac allE 1),
  1463                 etac mp 1,
  1464                 rtac refl 1])
  1465 
  1466     val cases_prf = quick_and_dirty_prf cases_prf_noopt cases_prf_opt;
  1467     val cases = timeit_msg "record extension cases proof:" cases_prf;
  1468 
  1469     fun dest_convs_prf () = map (prove_simp false
  1470                       ([ext_def,abs_inverse]@Pair_sel_convs@dest_defs)) dest_conv_props;
  1471     val dest_convs = timeit_msg "record extension dest_convs proof:" dest_convs_prf;
  1472     fun dest_convs_standard_prf () = map standard dest_convs;
  1473 
  1474     val dest_convs_standard =
  1475         timeit_msg "record extension dest_convs_standard proof:" dest_convs_standard_prf;
  1476 
  1477     fun upd_convs_prf_noopt () = map (prove_simp true (dest_convs_standard@upd_defs))
  1478                                        upd_conv_props;
  1479     fun upd_convs_prf_opt () =
  1480       let
  1481         fun mkrefl (c,T) = Thm.reflexive
  1482                             (cterm_of defs_thy (Free (Name.variant variants (base c ^ "'"),T)));
  1483         val refls = map mkrefl fields_more;
  1484         val constr_refl = Thm.reflexive (cterm_of defs_thy (head_of ext));
  1485         val dest_convs' = map mk_meta_eq dest_convs;
  1486 
  1487         fun mkthm (udef,(fld_refl,thms)) =
  1488           let val bdyeq = Library.foldl (uncurry Thm.combination) (constr_refl,thms);
  1489                (* (|N=N (|N=N,M=M,K=K,more=more|)
  1490                     M=M (|N=N,M=M,K=K,more=more|)
  1491                     K=K'
  1492                     more = more (|N=N,M=M,K=K,more=more|) =
  1493                   (|N=N,M=M,K=K',more=more|)
  1494                 *)
  1495               val (_$(_$v$r)$_) = prop_of udef;
  1496               val (_$v'$_) = prop_of fld_refl;
  1497               val udef' = cterm_instantiate
  1498                             [(cterm_of defs_thy v,cterm_of defs_thy v'),
  1499                              (cterm_of defs_thy r,cterm_of defs_thy ext)] udef;
  1500           in  standard (Thm.transitive udef' bdyeq) end;
  1501       in map mkthm (rev upd_defs  ~~ (mixit dest_convs' refls)) end;
  1502 
  1503     val upd_convs_prf = quick_and_dirty_prf upd_convs_prf_noopt upd_convs_prf_opt;
  1504 
  1505     val upd_convs =
  1506          timeit_msg "record extension upd_convs proof:" upd_convs_prf;
  1507 
  1508     fun surjective_prf () =
  1509       prove_standard [] surjective_prop (fn prems =>
  1510           (EVERY [try_param_tac rN induct 1,
  1511                   simp_tac (HOL_basic_ss addsimps dest_convs_standard) 1]));
  1512     val surjective = timeit_msg "record extension surjective proof:" surjective_prf;
  1513 
  1514     fun split_meta_prf () =
  1515         prove_standard [] split_meta_prop (fn prems =>
  1516          EVERY [rtac equal_intr_rule 1, norm_hhf_tac 1,
  1517                 etac meta_allE 1, atac 1,
  1518                 rtac (prop_subst OF [surjective]) 1,
  1519                 REPEAT (etac meta_allE 1), atac 1]);
  1520     val split_meta = timeit_msg "record extension split_meta proof:" split_meta_prf;
  1521 
  1522     val (([inject',induct',cases',surjective',split_meta'], [dest_convs',upd_convs']),
  1523       thm_thy) =
  1524       defs_thy
  1525       |> (PureThy.add_thms o map Thm.no_attributes)
  1526            [("ext_inject", inject),
  1527             ("ext_induct", induct),
  1528             ("ext_cases", cases),
  1529             ("ext_surjective", surjective),
  1530             ("ext_split", split_meta)]
  1531       ||>> (PureThy.add_thmss o map Thm.no_attributes)
  1532               [("dest_convs",dest_convs_standard),("upd_convs",upd_convs)]
  1533 
  1534   in (thm_thy,extT,induct',inject',dest_convs',split_meta',upd_convs')
  1535   end;
  1536 
  1537 fun chunks []      []   = []
  1538   | chunks []      xs   = [xs]
  1539   | chunks (l::ls) xs  = Library.take (l,xs)::chunks ls (Library.drop (l,xs));
  1540 
  1541 fun chop_last [] = error "last: list should not be empty"
  1542   | chop_last [x] = ([],x)
  1543   | chop_last (x::xs) = let val (tl,l) = chop_last xs in (x::tl,l) end;
  1544 
  1545 fun subst_last s []      = error "subst_last: list should not be empty"
  1546   | subst_last s ([x])   = [s]
  1547   | subst_last s (x::xs) = (x::subst_last s xs);
  1548 
  1549 (* mk_recordT builds up the record type from the current extension tpye extT and a list
  1550  * of parent extensions, starting with the root of the record hierarchy
  1551 *)
  1552 fun mk_recordT extT parent_exts =
  1553     foldr (fn ((parent,Ts),T) => Type (parent, subst_last T Ts)) extT parent_exts;
  1554 
  1555 
  1556 
  1557 fun obj_to_meta_all thm =
  1558   let
  1559     fun E thm = case (SOME (spec OF [thm]) handle THM _ => NONE) of
  1560                   SOME thm' => E thm'
  1561                 | NONE => thm;
  1562     val th1 = E thm;
  1563     val th2 = Drule.forall_intr_vars th1;
  1564   in th2 end;
  1565 
  1566 fun meta_to_obj_all thm =
  1567   let
  1568     val {sign, prop, ...} = rep_thm thm;
  1569     val params = Logic.strip_params prop;
  1570     val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl prop);
  1571     val ct = cterm_of sign
  1572       (HOLogic.mk_Trueprop (HOLogic.list_all (params, concl)));
  1573     val thm' = Seq.hd (REPEAT (rtac allI 1) (Thm.trivial ct));
  1574   in
  1575     Thm.implies_elim thm' thm
  1576   end;
  1577 
  1578 
  1579 
  1580 (* record_definition *)
  1581 fun record_definition (args, bname) parent (parents: parent_info list) raw_fields thy =
  1582   (* smlnj needs type annotation of parents *)
  1583   let
  1584     val sign = Theory.sign_of thy;
  1585 
  1586     val alphas = map fst args;
  1587     val name = Sign.full_name sign bname;
  1588     val full = Sign.full_name_path sign bname;
  1589     val base = Sign.base_name;
  1590 
  1591     val (bfields, field_syntax) = split_list (map (fn (x, T, mx) => ((x, T), mx)) raw_fields);
  1592 
  1593     val parent_fields = List.concat (map #fields parents);
  1594     val parent_chunks = map (length o #fields) parents;
  1595     val parent_names = map fst parent_fields;
  1596     val parent_types = map snd parent_fields;
  1597     val parent_fields_len = length parent_fields;
  1598     val parent_variants = Name.variant_list [moreN, rN, rN ^ "'", wN] (map base parent_names);
  1599     val parent_vars = ListPair.map Free (parent_variants, parent_types);
  1600     val parent_len = length parents;
  1601     val parents_idx = (map #name parents) ~~ (0 upto (parent_len - 1));
  1602 
  1603     val fields = map (apfst full) bfields;
  1604     val names = map fst fields;
  1605     val extN = full bname;
  1606     val types = map snd fields;
  1607     val alphas_fields = foldr add_typ_tfree_names [] types;
  1608     val alphas_ext = alphas inter alphas_fields;
  1609     val len = length fields;
  1610     val variants = Name.variant_list (moreN::rN::rN ^ "'"::wN::parent_variants) (map fst bfields);
  1611     val vars = ListPair.map Free (variants, types);
  1612     val named_vars = names ~~ vars;
  1613     val idxs = 0 upto (len - 1);
  1614     val idxms = 0 upto len;
  1615 
  1616     val all_fields = parent_fields @ fields;
  1617     val all_names = parent_names @ names;
  1618     val all_types = parent_types @ types;
  1619     val all_len = parent_fields_len + len;
  1620     val all_variants = parent_variants @ variants;
  1621     val all_vars = parent_vars @ vars;
  1622     val all_named_vars = (parent_names ~~ parent_vars) @ named_vars;
  1623 
  1624 
  1625     val zeta = Name.variant alphas "'z";
  1626     val moreT = TFree (zeta, HOLogic.typeS);
  1627     val more = Free (moreN, moreT);
  1628     val full_moreN = full moreN;
  1629     val bfields_more = bfields @ [(moreN,moreT)];
  1630     val fields_more = fields @ [(full_moreN,moreT)];
  1631     val vars_more = vars @ [more];
  1632     val named_vars_more = named_vars @[(full_moreN,more)];
  1633     val all_vars_more = all_vars @ [more];
  1634     val all_named_vars_more = all_named_vars @ [(full_moreN,more)];
  1635 
  1636     (* 1st stage: extension_thy *)
  1637     val (extension_thy,extT,ext_induct,ext_inject,ext_dest_convs,ext_split,u_convs) =
  1638       thy
  1639       |> Theory.add_path bname
  1640       |> extension_definition full extN fields names alphas_ext zeta moreT more vars;
  1641 
  1642     val _ = timing_msg "record preparing definitions";
  1643     val Type extension_scheme = extT;
  1644     val extension_name = unsuffix ext_typeN (fst extension_scheme);
  1645     val extension = let val (n,Ts) = extension_scheme in (n,subst_last HOLogic.unitT Ts) end;
  1646     val extension_names =
  1647          (map ((unsuffix ext_typeN) o fst o #extension) parents) @ [extN];
  1648     val extension_id = Library.foldl (op ^) ("",extension_names);
  1649 
  1650 
  1651     fun rec_schemeT n = mk_recordT extT (map #extension (prune n parents));
  1652     val rec_schemeT0 = rec_schemeT 0;
  1653 
  1654     fun recT n =
  1655       let val (c,Ts) = extension
  1656       in mk_recordT (Type (c,subst_last HOLogic.unitT Ts))(map #extension (prune n parents))
  1657       end;
  1658     val recT0 = recT 0;
  1659 
  1660     fun mk_rec args n =
  1661       let val (args',more) = chop_last args;
  1662           fun mk_ext' (((name,T),args),more) = mk_ext (name,T) (args@[more]);
  1663           fun build Ts =
  1664            foldr mk_ext' more (prune n (extension_names ~~ Ts ~~ (chunks parent_chunks args')))
  1665       in
  1666         if more = HOLogic.unit
  1667         then build (map recT (0 upto parent_len))
  1668         else build (map rec_schemeT (0 upto parent_len))
  1669       end;
  1670 
  1671     val r_rec0 = mk_rec all_vars_more 0;
  1672     val r_rec_unit0 = mk_rec (all_vars@[HOLogic.unit]) 0;
  1673 
  1674     fun r n = Free (rN, rec_schemeT n)
  1675     val r0 = r 0;
  1676     fun r_unit n = Free (rN, recT n)
  1677     val r_unit0 = r_unit 0;
  1678     val w = Free (wN, rec_schemeT 0)
  1679 
  1680     (* prepare print translation functions *)
  1681     val field_tr's =
  1682       print_translation (distinct (op =)
  1683         (List.concat (map NameSpace.accesses' (full_moreN :: names))));
  1684 
  1685     val adv_ext_tr's =
  1686     let
  1687       val trnames = NameSpace.accesses' extN;
  1688     in map (gen_record_tr') trnames end;
  1689 
  1690     val adv_record_type_abbr_tr's =
  1691       let val trnames = NameSpace.accesses' (hd extension_names);
  1692           val lastExt = (unsuffix ext_typeN (fst extension));
  1693       in map (gen_record_type_abbr_tr' name alphas zeta lastExt rec_schemeT0) trnames
  1694       end;
  1695 
  1696     val adv_record_type_tr's =
  1697       let val trnames = if parent_len > 0 then NameSpace.accesses' extN else [];
  1698                         (* avoid conflict with adv_record_type_abbr_tr's *)
  1699       in map (gen_record_type_tr') trnames
  1700       end;
  1701 
  1702 
  1703     (* prepare declarations *)
  1704 
  1705     val sel_decls = map (mk_selC rec_schemeT0) bfields_more;
  1706     val upd_decls = map (mk_updC updateN rec_schemeT0) bfields_more;
  1707     val make_decl = (makeN, all_types ---> recT0);
  1708     val fields_decl = (fields_selN, types ---> Type extension);
  1709     val extend_decl = (extendN, recT0 --> moreT --> rec_schemeT0);
  1710     val truncate_decl = (truncateN, rec_schemeT0 --> recT0);
  1711 
  1712     (* prepare definitions *)
  1713 
  1714     fun parent_more s =
  1715          if null parents then s
  1716          else mk_sel s (NameSpace.qualified (#name (List.last parents)) moreN, extT);
  1717 
  1718     fun parent_more_upd v s =
  1719       if null parents then v
  1720       else let val mp = NameSpace.qualified (#name (List.last parents)) moreN;
  1721            in mk_upd updateN mp v s end;
  1722 
  1723     (*record (scheme) type abbreviation*)
  1724     val recordT_specs =
  1725       [(suffix schemeN bname, alphas @ [zeta], rec_schemeT0, Syntax.NoSyn),
  1726         (bname, alphas, recT0, Syntax.NoSyn)];
  1727 
  1728     (*selectors*)
  1729     fun mk_sel_spec (c,T) =
  1730          Const (mk_selC rec_schemeT0 (c,T))
  1731           :== (lambda r0 (Const (mk_selC extT (suffix ext_dest c,T))$parent_more r0));
  1732     val sel_specs = map mk_sel_spec fields_more;
  1733 
  1734     (*updates*)
  1735 
  1736     fun mk_upd_spec (c,T) =
  1737       let
  1738         val new = mk_upd updN c (Free (base c,T)) (parent_more r0);
  1739       in Const (mk_updC updateN rec_schemeT0 (c,T))$(Free (base c,T))$r0
  1740           :== (parent_more_upd new r0)
  1741       end;
  1742     val upd_specs = map mk_upd_spec fields_more;
  1743 
  1744     (*derived operations*)
  1745     val make_spec = Const (full makeN, all_types ---> recT0) $$ all_vars :==
  1746       mk_rec (all_vars @ [HOLogic.unit]) 0;
  1747     val fields_spec = Const (full fields_selN, types ---> Type extension) $$ vars :==
  1748       mk_rec (all_vars @ [HOLogic.unit]) parent_len;
  1749     val extend_spec =
  1750       Const (full extendN, recT0-->moreT-->rec_schemeT0) $ r_unit0 $ more :==
  1751       mk_rec ((map (mk_sel r_unit0) all_fields) @ [more]) 0;
  1752     val truncate_spec = Const (full truncateN, rec_schemeT0 --> recT0) $ r0 :==
  1753       mk_rec ((map (mk_sel r0) all_fields) @ [HOLogic.unit]) 0;
  1754 
  1755     (* 2st stage: defs_thy *)
  1756 
  1757     fun mk_defs () =
  1758       extension_thy
  1759         |> Theory.add_trfuns
  1760             ([],[],field_tr's, [])
  1761         |> Theory.add_advanced_trfuns
  1762             ([],[],adv_ext_tr's @ adv_record_type_tr's @ adv_record_type_abbr_tr's,[])
  1763         |> Theory.parent_path
  1764         |> Theory.add_tyabbrs_i recordT_specs
  1765         |> Theory.add_path bname
  1766         |> Theory.add_consts_i
  1767             (map2 (fn (x, T) => fn mx => (x, T, mx)) sel_decls (field_syntax @ [Syntax.NoSyn]))
  1768         |> (Theory.add_consts_i o map Syntax.no_syn)
  1769             (upd_decls @ [make_decl, fields_decl, extend_decl, truncate_decl])
  1770         |> ((PureThy.add_defs_i false o map Thm.no_attributes) sel_specs)
  1771         ||>> ((PureThy.add_defs_i false o map Thm.no_attributes) upd_specs)
  1772         ||>> ((PureThy.add_defs_i false o map Thm.no_attributes)
  1773                [make_spec, fields_spec, extend_spec, truncate_spec])
  1774         |> swap
  1775     val (defs_thy,((sel_defs,upd_defs),derived_defs)) =
  1776         timeit_msg "record trfuns/tyabbrs/selectors/updates/make/fields/extend/truncate defs:"
  1777          mk_defs;
  1778 
  1779 
  1780     (* prepare propositions *)
  1781     val _ = timing_msg "record preparing propositions";
  1782     val P = Free (Name.variant all_variants "P", rec_schemeT0-->HOLogic.boolT);
  1783     val C = Free (Name.variant all_variants "C", HOLogic.boolT);
  1784     val P_unit = Free (Name.variant all_variants "P", recT0-->HOLogic.boolT);
  1785 
  1786     (*selectors*)
  1787     val sel_conv_props =
  1788        map (fn (c, x as Free (_,T)) => mk_sel r_rec0 (c,T) === x) named_vars_more;
  1789 
  1790     (*updates*)
  1791     fun mk_upd_prop (i,(c,T)) =
  1792       let val x' = Free (Name.variant all_variants (base c ^ "'"),T)
  1793           val args' = nth_update (parent_fields_len + i, x') all_vars_more
  1794       in mk_upd updateN c x' r_rec0 === mk_rec args' 0  end;
  1795     val upd_conv_props = ListPair.map mk_upd_prop (idxms, fields_more);
  1796 
  1797     (*induct*)
  1798     val induct_scheme_prop =
  1799       All (map dest_Free all_vars_more) (Trueprop (P $ r_rec0)) ==> Trueprop (P $ r0);
  1800     val induct_prop =
  1801       (All (map dest_Free all_vars) (Trueprop (P_unit $ r_rec_unit0)),
  1802        Trueprop (P_unit $ r_unit0));
  1803 
  1804     (*surjective*)
  1805     val surjective_prop =
  1806       let val args = map (fn (c,Free (_,T)) => mk_sel r0 (c,T)) all_named_vars_more
  1807       in r0 === mk_rec args 0 end;
  1808 
  1809     (*cases*)
  1810     val cases_scheme_prop =
  1811       (All (map dest_Free all_vars_more)
  1812         (Trueprop (HOLogic.mk_eq (r0,r_rec0)) ==> Trueprop C))
  1813       ==> Trueprop C;
  1814 
  1815     val cases_prop =
  1816       (All (map dest_Free all_vars)
  1817         (Trueprop (HOLogic.mk_eq (r_unit0,r_rec_unit0)) ==> Trueprop C))
  1818        ==> Trueprop C;
  1819 
  1820     (*split*)
  1821     val split_meta_prop =
  1822       let val P = Free (Name.variant all_variants "P", rec_schemeT0-->Term.propT) in
  1823         Logic.mk_equals
  1824          (All [dest_Free r0] (P $ r0), All (map dest_Free all_vars_more) (P $ r_rec0))
  1825       end;
  1826 
  1827     val split_object_prop =
  1828       let fun ALL vs t = foldr (fn ((v,T),t) => HOLogic.mk_all (v,T,t)) t vs
  1829       in (ALL [dest_Free r0] (P $ r0)) === (ALL (map dest_Free all_vars_more) (P $ r_rec0))
  1830       end;
  1831 
  1832 
  1833     val split_ex_prop =
  1834       let fun EX vs t = foldr (fn ((v,T),t) => HOLogic.mk_exists (v,T,t)) t vs
  1835       in (EX [dest_Free r0] (P $ r0)) === (EX (map dest_Free all_vars_more) (P $ r_rec0))
  1836       end;
  1837 
  1838     (*equality*)
  1839     val equality_prop =
  1840       let
  1841         val s' = Free (rN ^ "'", rec_schemeT0)
  1842         fun mk_sel_eq (c,Free (_,T)) =  mk_sel r0 (c,T) === mk_sel s' (c,T)
  1843         val seleqs = map mk_sel_eq all_named_vars_more
  1844       in All (map dest_Free [r0,s']) (Logic.list_implies (seleqs,r0 === s')) end;
  1845 
  1846     (* 3rd stage: thms_thy *)
  1847 
  1848     fun prove stndrd = quick_and_dirty_prove stndrd defs_thy;
  1849     val prove_standard = quick_and_dirty_prove true defs_thy;
  1850 
  1851     fun prove_simp stndrd ss simps =
  1852       let val tac = simp_all_tac ss simps
  1853       in fn prop => prove stndrd [] prop (K tac) end;
  1854 
  1855     val ss = get_simpset defs_thy;
  1856 
  1857     fun sel_convs_prf () = map (prove_simp false ss
  1858                            (sel_defs@ext_dest_convs)) sel_conv_props;
  1859     val sel_convs = timeit_msg "record sel_convs proof:" sel_convs_prf;
  1860     fun sel_convs_standard_prf () = map standard sel_convs
  1861     val sel_convs_standard =
  1862           timeit_msg "record sel_convs_standard proof:" sel_convs_standard_prf;
  1863 
  1864     fun upd_convs_prf () =
  1865           map (prove_simp true ss (upd_defs@u_convs)) upd_conv_props;
  1866 
  1867     val upd_convs = timeit_msg "record upd_convs proof:" upd_convs_prf;
  1868 
  1869     val parent_induct = if null parents then [] else [#induct (hd (rev parents))];
  1870 
  1871     fun induct_scheme_prf () = prove_standard [] induct_scheme_prop (fn prems =>
  1872           (EVERY [if null parent_induct
  1873                   then all_tac else try_param_tac rN (hd parent_induct) 1,
  1874                   try_param_tac rN ext_induct 1,
  1875                   asm_simp_tac HOL_basic_ss 1]));
  1876     val induct_scheme = timeit_msg "record induct_scheme proof:" induct_scheme_prf;
  1877 
  1878     fun induct_prf () =
  1879       let val (assm, concl) = induct_prop;
  1880       in
  1881         prove_standard [assm] concl (fn {prems, ...} =>
  1882           try_param_tac rN induct_scheme 1
  1883           THEN try_param_tac "more" unit_induct 1
  1884           THEN resolve_tac prems 1)
  1885       end;
  1886     val induct = timeit_msg "record induct proof:" induct_prf;
  1887 
  1888     fun surjective_prf () =
  1889       prove_standard [] surjective_prop (fn prems =>
  1890           (EVERY [try_param_tac rN induct_scheme 1,
  1891                   simp_tac (ss addsimps sel_convs_standard) 1]))
  1892     val surjective = timeit_msg "record surjective proof:" surjective_prf;
  1893 
  1894     fun cases_scheme_prf_opt () =
  1895       let
  1896         val (_$(Pvar$_)) = concl_of induct_scheme;
  1897         val ind = cterm_instantiate
  1898                     [(cterm_of defs_thy Pvar, cterm_of defs_thy
  1899                             (lambda w (HOLogic.imp$HOLogic.mk_eq(r0,w)$C)))]
  1900                     induct_scheme;
  1901         in standard (ObjectLogic.rulify (mp OF [ind, refl])) end;
  1902 
  1903     fun cases_scheme_prf_noopt () =
  1904         prove_standard [] cases_scheme_prop (fn prems =>
  1905          EVERY [asm_full_simp_tac (HOL_basic_ss addsimps [atomize_all, atomize_imp]) 1,
  1906                try_param_tac rN induct_scheme 1,
  1907                rtac impI 1,
  1908                REPEAT (etac allE 1),
  1909                etac mp 1,
  1910                rtac refl 1])
  1911     val cases_scheme_prf = quick_and_dirty_prf cases_scheme_prf_noopt cases_scheme_prf_opt;
  1912     val cases_scheme = timeit_msg "record cases_scheme proof:" cases_scheme_prf;
  1913 
  1914     fun cases_prf () =
  1915       prove_standard [] cases_prop  (fn _ =>
  1916         try_param_tac rN cases_scheme 1
  1917         THEN simp_all_tac HOL_basic_ss [unit_all_eq1]);
  1918     val cases = timeit_msg "record cases proof:" cases_prf;
  1919 
  1920     fun split_meta_prf () =
  1921         prove false [] split_meta_prop (fn prems =>
  1922          EVERY [rtac equal_intr_rule 1, norm_hhf_tac 1,
  1923                 etac meta_allE 1, atac 1,
  1924                 rtac (prop_subst OF [surjective]) 1,
  1925                 REPEAT (etac meta_allE 1), atac 1]);
  1926     val split_meta = timeit_msg "record split_meta proof:" split_meta_prf;
  1927     val split_meta_standard = standard split_meta;
  1928 
  1929     fun split_object_prf_opt () =
  1930       let
  1931         val cPI= cterm_of defs_thy (lambda r0 (Trueprop (P$r0)));
  1932         val (_$Abs(_,_,P$_)) = fst (Logic.dest_equals (concl_of split_meta_standard));
  1933         val cP = cterm_of defs_thy P;
  1934         val split_meta' = cterm_instantiate [(cP,cPI)] split_meta_standard;
  1935         val (l,r) = HOLogic.dest_eq (HOLogic.dest_Trueprop split_object_prop);
  1936         val cl = cterm_of defs_thy (HOLogic.mk_Trueprop l);
  1937         val cr = cterm_of defs_thy (HOLogic.mk_Trueprop r);
  1938         val thl = assume cl                 (*All r. P r*) (* 1 *)
  1939                 |> obj_to_meta_all          (*!!r. P r*)
  1940                 |> equal_elim split_meta'   (*!!n m more. P (ext n m more)*)
  1941                 |> meta_to_obj_all          (*All n m more. P (ext n m more)*) (* 2*)
  1942                 |> implies_intr cl          (* 1 ==> 2 *)
  1943         val thr = assume cr                           (*All n m more. P (ext n m more)*)
  1944                 |> obj_to_meta_all                    (*!!n m more. P (ext n m more)*)
  1945                 |> equal_elim (symmetric split_meta') (*!!r. P r*)
  1946                 |> meta_to_obj_all                    (*All r. P r*)
  1947                 |> implies_intr cr                    (* 2 ==> 1 *)
  1948      in standard (thr COMP (thl COMP iffI)) end;
  1949 
  1950     fun split_object_prf_noopt () =
  1951         prove_standard [] split_object_prop (fn prems =>
  1952          EVERY [rtac iffI 1,
  1953                 REPEAT (rtac allI 1), etac allE 1, atac 1,
  1954                 rtac allI 1, rtac induct_scheme 1,REPEAT (etac allE 1),atac 1]);
  1955 
  1956     val split_object_prf = quick_and_dirty_prf split_object_prf_noopt split_object_prf_opt;
  1957     val split_object = timeit_msg "record split_object proof:" split_object_prf;
  1958 
  1959 
  1960     fun split_ex_prf () =
  1961         prove_standard [] split_ex_prop (fn prems =>
  1962           EVERY [rtac iffI 1,
  1963                    etac exE 1,
  1964                    simp_tac (HOL_basic_ss addsimps [split_meta_standard]) 1,
  1965                    ex_inst_tac 1,
  1966                    (*REPEAT (rtac exI 1),*)
  1967                    atac 1,
  1968                  REPEAT (etac exE 1),
  1969                  rtac exI 1,
  1970                  atac 1]);
  1971     val split_ex = timeit_msg "record split_ex proof:" split_ex_prf;
  1972 
  1973     fun equality_tac thms =
  1974       let val (s'::s::eqs) = rev thms;
  1975           val ss' = ss addsimps (s'::s::sel_convs_standard);
  1976           val eqs' = map (simplify ss') eqs;
  1977       in simp_tac (HOL_basic_ss addsimps (s'::s::eqs')) 1 end;
  1978 
  1979    fun equality_prf () = prove_standard [] equality_prop (fn _ =>
  1980       fn st => let val [s, s'] = map #1 (rev (Tactic.innermost_params 1 st)) in
  1981         st |> (res_inst_tac [(rN, s)] cases_scheme 1
  1982         THEN res_inst_tac [(rN, s')] cases_scheme 1
  1983         THEN (METAHYPS equality_tac 1))
  1984              (* simp_all_tac ss (sel_convs) would also work but is less efficient *)
  1985       end);
  1986      val equality = timeit_msg "record equality proof:" equality_prf;
  1987 
  1988     val ((([sel_convs',upd_convs',sel_defs',upd_defs',[split_meta',split_object',split_ex'],derived_defs'],
  1989             [surjective',equality']),[induct_scheme',induct',cases_scheme',cases']), thms_thy) =
  1990       defs_thy
  1991       |> (PureThy.add_thmss o map Thm.no_attributes)
  1992          [("select_convs", sel_convs_standard),
  1993           ("update_convs", upd_convs),
  1994           ("select_defs", sel_defs),
  1995           ("update_defs", upd_defs),
  1996           ("splits", [split_meta_standard,split_object,split_ex]),
  1997           ("defs", derived_defs)]
  1998       ||>> (PureThy.add_thms o map Thm.no_attributes)
  1999           [("surjective", surjective),
  2000            ("equality", equality)]
  2001       ||>> PureThy.add_thms
  2002         [(("induct_scheme", induct_scheme), induct_type_global (suffix schemeN name)),
  2003          (("induct", induct), induct_type_global name),
  2004          (("cases_scheme", cases_scheme), cases_type_global (suffix schemeN name)),
  2005          (("cases", cases), cases_type_global name)];
  2006 
  2007 
  2008     val sel_upd_simps = sel_convs' @ upd_convs';
  2009     val iffs = [ext_inject]
  2010     val final_thy =
  2011       thms_thy
  2012       |> (snd oo PureThy.add_thmss)
  2013           [(("simps", sel_upd_simps), [Simplifier.simp_add]),
  2014            (("iffs",iffs), [iff_add])]
  2015       |> put_record name (make_record_info args parent fields extension induct_scheme')
  2016       |> put_sel_upd (names @ [full_moreN]) sel_upd_simps
  2017       |> add_record_equalities extension_id equality'
  2018       |> add_extinjects ext_inject
  2019       |> add_extsplit extension_name ext_split
  2020       |> add_record_splits extension_id (split_meta',split_object',split_ex',induct_scheme')
  2021       |> add_extfields extension_name (fields @ [(full_moreN,moreT)])
  2022       |> add_fieldext (extension_name,snd extension) (names @ [full_moreN])
  2023       |> Theory.parent_path;
  2024 
  2025   in final_thy
  2026   end;
  2027 
  2028 (* add_record *)
  2029 
  2030 (*we do all preparations and error checks here, deferring the real
  2031   work to record_definition*)
  2032 fun gen_add_record prep_typ prep_raw_parent (params, bname) raw_parent raw_fields thy =
  2033   let
  2034     val _ = Theory.requires thy "Record" "record definitions";
  2035     val sign = Theory.sign_of thy;
  2036     val _ = message ("Defining record " ^ quote bname ^ " ...");
  2037 
  2038 
  2039     (* parents *)
  2040 
  2041     fun prep_inst T = snd (cert_typ sign ([], T));
  2042 
  2043     val parent = Option.map (apfst (map prep_inst) o prep_raw_parent sign) raw_parent
  2044       handle ERROR msg => cat_error msg ("The error(s) above in parent record specification");
  2045     val parents = add_parents thy parent [];
  2046 
  2047     val init_env =
  2048       (case parent of
  2049         NONE => []
  2050       | SOME (types, _) => foldr Term.add_typ_tfrees [] types);
  2051 
  2052 
  2053     (* fields *)
  2054 
  2055     fun prep_field (env, (c, raw_T, mx)) =
  2056       let val (env', T) = prep_typ sign (env, raw_T) handle ERROR msg =>
  2057         cat_error msg ("The error(s) above occured in field " ^ quote c)
  2058       in (env', (c, T, mx)) end;
  2059 
  2060     val (envir, bfields) = foldl_map prep_field (init_env, raw_fields);
  2061     val envir_names = map fst envir;
  2062 
  2063 
  2064     (* args *)
  2065 
  2066     val defaultS = Sign.defaultS sign;
  2067     val args = map (fn x => (x, AList.lookup (op =) envir x |> the_default defaultS)) params;
  2068 
  2069 
  2070     (* errors *)
  2071 
  2072     val name = Sign.full_name sign bname;
  2073     val err_dup_record =
  2074       if is_none (get_record thy name) then []
  2075       else ["Duplicate definition of record " ^ quote name];
  2076 
  2077     val err_dup_parms =
  2078       (case duplicates (op =) params of
  2079         [] => []
  2080       | dups => ["Duplicate parameter(s) " ^ commas dups]);
  2081 
  2082     val err_extra_frees =
  2083       (case gen_rems (op =) (envir_names, params) of
  2084         [] => []
  2085       | extras => ["Extra free type variable(s) " ^ commas extras]);
  2086 
  2087     val err_no_fields = if null bfields then ["No fields present"] else [];
  2088 
  2089     val err_dup_fields =
  2090       (case duplicates (op =) (map #1 bfields) of
  2091         [] => []
  2092       | dups => ["Duplicate field(s) " ^ commas_quote dups]);
  2093 
  2094     val err_bad_fields =
  2095       if forall (not_equal moreN o #1) bfields then []
  2096       else ["Illegal field name " ^ quote moreN];
  2097 
  2098     val err_dup_sorts =
  2099       (case duplicates (op =) envir_names of
  2100         [] => []
  2101       | dups => ["Inconsistent sort constraints for " ^ commas dups]);
  2102 
  2103     val errs =
  2104       err_dup_record @ err_dup_parms @ err_extra_frees @ err_no_fields @
  2105       err_dup_fields @ err_bad_fields @ err_dup_sorts;
  2106   in
  2107     if null errs then () else error (cat_lines errs)  ;
  2108     thy |> record_definition (args, bname) parent parents bfields
  2109   end
  2110   handle ERROR msg => cat_error msg ("Failed to define record " ^ quote bname);
  2111 
  2112 val add_record = gen_add_record read_typ read_raw_parent;
  2113 val add_record_i = gen_add_record cert_typ (K I);
  2114 
  2115 (* setup theory *)
  2116 
  2117 val setup =
  2118   RecordsData.init #>
  2119   Theory.add_trfuns ([], parse_translation, [], []) #>
  2120   Theory.add_advanced_trfuns ([], adv_parse_translation, [], []) #>
  2121   (fn thy => (Simplifier.change_simpset_of thy
  2122     (fn ss => ss addsimprocs [record_simproc, record_upd_simproc, record_eq_simproc]); thy));
  2123 
  2124 (* outer syntax *)
  2125 
  2126 local structure P = OuterParse and K = OuterKeyword in
  2127 
  2128 val record_decl =
  2129   P.type_args -- P.name --
  2130     (P.$$$ "=" |-- Scan.option (P.typ --| P.$$$ "+") -- Scan.repeat1 P.const);
  2131 
  2132 val recordP =
  2133   OuterSyntax.command "record" "define extensible record" K.thy_decl
  2134     (record_decl >> (fn (x, (y, z)) => Toplevel.theory (add_record x y z)));
  2135 
  2136 val _ = OuterSyntax.add_parsers [recordP];
  2137 
  2138 end;
  2139 
  2140 end;
  2141 
  2142 
  2143 structure BasicRecordPackage: BASIC_RECORD_PACKAGE = RecordPackage;
  2144 open BasicRecordPackage;