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