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