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