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