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