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