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