src/HOL/Tools/record_package.ML
author wenzelm
Mon Mar 13 13:16:57 2000 +0100 (2000-03-13)
changeset 8428 be4c8a57cf7e
parent 8294 c50607ff9704
child 8574 bed3b994ab26
permissions -rw-r--r--
adapted to new PureThy.add_thms etc.;
     1 (*  Title:      HOL/Tools/record_package.ML
     2     ID:         $Id$
     3     Author:     Wolfgang Naraschewski and Markus Wenzel, TU Muenchen
     4 
     5 Extensible records with structural subtyping in HOL.
     6 *)
     7 
     8 signature BASIC_RECORD_PACKAGE =
     9 sig
    10   val record_simproc: simproc
    11   val record_split_tac: int -> tactic
    12   val record_split_name: string
    13   val record_split_wrapper: string * wrapper
    14 end;
    15 
    16 signature RECORD_PACKAGE =
    17 sig
    18   include BASIC_RECORD_PACKAGE
    19   val quiet_mode: bool ref
    20   val moreS: sort
    21   val mk_fieldT: (string * typ) * typ -> typ
    22   val dest_fieldT: typ -> (string * typ) * typ
    23   val mk_field: (string * term) * term -> term
    24   val mk_fst: term -> term
    25   val mk_snd: term -> term
    26   val mk_recordT: (string * typ) list * typ -> typ
    27   val dest_recordT: typ -> (string * typ) list * typ
    28   val mk_record: (string * term) list * term -> term
    29   val mk_sel: term -> string -> term
    30   val mk_update: term -> string * term -> term
    31   val print_records: theory -> unit
    32   val add_record: (string list * bstring) -> string option
    33     -> (bstring * string) list -> theory -> theory * {simps: thm list, iffs: thm list}
    34   val add_record_i: (string list * bstring) -> (typ list * string) option
    35     -> (bstring * typ) list -> theory -> theory * {simps: thm list, iffs: thm list}
    36   val setup: (theory -> theory) list
    37 end;
    38 
    39 
    40 structure RecordPackage: RECORD_PACKAGE =
    41 struct
    42 
    43 
    44 (*** utilities ***)
    45 
    46 (* messages *)
    47 
    48 val quiet_mode = ref false;
    49 fun message s = if ! quiet_mode then () else writeln s;
    50 
    51 
    52 (* definitions and equations *)
    53 
    54 infix 0 :== ===;
    55 
    56 val (op :==) = Logic.mk_defpair;
    57 val (op ===) = HOLogic.mk_Trueprop o HOLogic.mk_eq;
    58 
    59 
    60 (* proof by simplification *)
    61 
    62 fun prove_simp sign ss tacs simps =
    63   let
    64     val ss' = Simplifier.addsimps (ss, simps);
    65 
    66     fun prove goal =
    67       Goals.prove_goalw_cterm [] (Thm.cterm_of sign goal)
    68         (K (tacs @ [ALLGOALS (Simplifier.simp_tac ss')]))
    69       handle ERROR => error ("The error(s) above occurred while trying to prove "
    70         ^ quote (Sign.string_of_term sign goal));
    71   in prove end;
    72 
    73 
    74 
    75 (*** syntax operations ***)
    76 
    77 (** name components **)
    78 
    79 val recordN = "record";
    80 val moreN = "more";
    81 val schemeN = "_scheme";
    82 val fieldN = "_field";
    83 val raw_fieldN = "_raw_field";
    84 val field_typeN = "_field_type";
    85 val fstN = "_val";
    86 val sndN = "_more";
    87 val updateN = "_update";
    88 val makeN = "make";
    89 val make_schemeN = "make_scheme";
    90 
    91 (*see datatype package*)
    92 val caseN = "_case";
    93 
    94 
    95 
    96 (** generic operations **)
    97 
    98 (* adhoc priming of vars *)
    99 
   100 fun prime (Free (x, T)) = Free (x ^ "'", T)
   101   | prime t = raise TERM ("prime: no free variable", [t]);
   102 
   103 
   104 (* product case *)
   105 
   106 fun fst_fn T U = Abs ("x", T, Abs ("y", U, Bound 1));
   107 fun snd_fn T U = Abs ("x", T, Abs ("y", U, Bound 0));
   108 
   109 fun mk_prod_case name f p =
   110   let
   111     val fT as Type ("fun", [A, Type ("fun", [B, C])]) = fastype_of f;
   112     val pT = fastype_of p;
   113   in Const (suffix caseN name, fT --> pT --> C) $ f $ p end;
   114 
   115 
   116 
   117 (** tuple operations **)
   118 
   119 (* more type class *)
   120 
   121 val moreS = ["Record.more"];
   122 
   123 
   124 (* types *)
   125 
   126 fun mk_fieldT ((c, T), U) = Type (suffix field_typeN c, [T, U]);
   127 
   128 fun dest_fieldT (typ as Type (c_field_type, [T, U])) =
   129       (case try (unsuffix field_typeN) c_field_type of
   130         None => raise TYPE ("dest_fieldT", [typ], [])
   131       | Some c => ((c, T), U))
   132   | dest_fieldT typ = raise TYPE ("dest_fieldT", [typ], []);
   133 
   134 
   135 (* constructors *)
   136 
   137 fun mk_fieldC U (c, T) = (suffix fieldN c, T --> U --> mk_fieldT ((c, T), U));
   138 
   139 fun gen_mk_field sfx ((c, t), u) =
   140   let val T = fastype_of t and U = fastype_of u
   141   in Const (suffix sfx c, [T, U] ---> mk_fieldT ((c, T), U)) $ t $ u end;
   142 
   143 val mk_field = gen_mk_field fieldN;
   144 val mk_raw_field = gen_mk_field raw_fieldN;
   145 
   146 
   147 (* destructors *)
   148 
   149 fun mk_fstC U (c, T) = (suffix fstN c, mk_fieldT ((c, T), U) --> T);
   150 fun mk_sndC U (c, T) = (suffix sndN c, mk_fieldT ((c, T), U) --> U);
   151 
   152 fun dest_field fst_or_snd p =
   153   let
   154     val pT = fastype_of p;
   155     val ((c, T), U) = dest_fieldT pT;
   156     val (destN, destT) = if fst_or_snd then (fstN, T) else (sndN, U);
   157   in Const (suffix destN c, pT --> destT) $ p end;
   158 
   159 val mk_fst = dest_field true;
   160 val mk_snd = dest_field false;
   161 
   162 
   163 
   164 (** record operations **)
   165 
   166 (* types *)
   167 
   168 val mk_recordT = foldr mk_fieldT;
   169 
   170 fun dest_recordT T =
   171   (case try dest_fieldT T of
   172     None => ([], T)
   173   | Some (c_T, U) => apfst (cons c_T) (dest_recordT U));
   174 
   175 fun find_fieldT c rT =
   176   (case assoc (fst (dest_recordT rT), c) of
   177     None => raise TYPE ("find_field: " ^ c, [rT], [])
   178   | Some T => T);
   179 
   180 
   181 (* constructors *)
   182 
   183 val mk_record = foldr mk_field;
   184 
   185 
   186 (* selectors *)
   187 
   188 fun mk_selC rT (c, T) = (c, rT --> T);
   189 
   190 fun mk_sel r c =
   191   let val rT = fastype_of r
   192   in Const (mk_selC rT (c, find_fieldT c rT)) $ r end;
   193 
   194 val mk_moreC = mk_selC;
   195 
   196 fun mk_more r c =
   197   let val rT = fastype_of r
   198   in Const (mk_moreC rT (c, snd (dest_recordT rT))) $ r end;
   199 
   200 
   201 (* updates *)
   202 
   203 fun mk_updateC rT (c, T) = (suffix updateN c, T --> rT --> rT);
   204 
   205 fun mk_update r (c, x) =
   206   let val rT = fastype_of r
   207   in Const (mk_updateC rT (c, find_fieldT c rT)) $ x $ r end;
   208 
   209 val mk_more_updateC = mk_updateC;
   210 
   211 fun mk_more_update r (c, x) =
   212   let val rT = fastype_of r
   213   in Const (mk_more_updateC rT (c, snd (dest_recordT rT))) $ x $ r end;
   214 
   215 
   216 (* make *)
   217 
   218 fun mk_makeC rT (c, Ts) = (c, Ts ---> rT);
   219 
   220 
   221 
   222 (** concrete syntax for records **)
   223 
   224 (* parse translations *)
   225 
   226 fun gen_field_tr mark sfx (t as Const (c, _) $ Free (name, _) $ arg) =
   227       if c = mark then Syntax.const (suffix sfx name) $ arg
   228       else raise TERM ("gen_field_tr: " ^ mark, [t])
   229   | gen_field_tr mark _ t = raise TERM ("gen_field_tr: " ^ mark, [t]);
   230 
   231 fun gen_fields_tr sep mark sfx (tm as Const (c, _) $ t $ u) =
   232       if c = sep then gen_field_tr mark sfx t :: gen_fields_tr sep mark sfx u
   233       else [gen_field_tr mark sfx tm]
   234   | gen_fields_tr _ mark sfx tm = [gen_field_tr mark sfx tm];
   235 
   236 fun gen_record_tr sep mark sfx unit [t] = foldr (op $) (gen_fields_tr sep mark sfx t, unit)
   237   | gen_record_tr _ _ _ _ ts = raise TERM ("gen_record_tr", ts);
   238 
   239 fun gen_record_scheme_tr sep mark sfx [t, more] = foldr (op $) (gen_fields_tr sep mark sfx t, more)
   240   | gen_record_scheme_tr _ _ _ ts = raise TERM ("gen_record_scheme_tr", ts);
   241 
   242 
   243 val record_type_tr = gen_record_tr "_field_types" "_field_type" field_typeN (Syntax.const "unit");
   244 val record_type_scheme_tr = gen_record_scheme_tr "_field_types" "_field_type" field_typeN;
   245 
   246 val record_tr = gen_record_tr "_fields" "_field" fieldN HOLogic.unit;
   247 val record_scheme_tr = gen_record_scheme_tr "_fields" "_field" fieldN;
   248 
   249 fun record_update_tr [t, u] =
   250       foldr (op $) (rev (gen_fields_tr "_updates" "_update" updateN u), t)
   251   | record_update_tr ts = raise TERM ("record_update_tr", ts);
   252 
   253 
   254 val parse_translation =
   255  [("_record_type", record_type_tr),
   256   ("_record_type_scheme", record_type_scheme_tr),
   257   ("_record", record_tr),
   258   ("_record_scheme", record_scheme_tr),
   259   ("_record_update", record_update_tr)];
   260 
   261 
   262 (* print translations *)
   263 
   264 fun gen_fields_tr' mark sfx (tm as Const (name_field, _) $ t $ u) =
   265       (case try (unsuffix sfx) name_field of
   266         Some name =>
   267           apfst (cons (Syntax.const mark $ Syntax.free name $ t)) (gen_fields_tr' mark sfx u)
   268       | None => ([], tm))
   269   | gen_fields_tr' _ _ tm = ([], tm);
   270 
   271 fun gen_record_tr' sep mark sfx is_unit record record_scheme tm =
   272   let
   273     val (ts, u) = gen_fields_tr' mark sfx tm;
   274     val t' = foldr1 (fn (v, w) => Syntax.const sep $ v $ w) ts;
   275   in
   276     if is_unit u then Syntax.const record $ t'
   277     else Syntax.const record_scheme $ t' $ u
   278   end;
   279 
   280 
   281 val record_type_tr' =
   282   gen_record_tr' "_field_types" "_field_type" field_typeN
   283     (fn Const ("unit", _) => true | _ => false) "_record_type" "_record_type_scheme";
   284 
   285 val record_tr' =
   286   gen_record_tr' "_fields" "_field" fieldN HOLogic.is_unit "_record" "_record_scheme";
   287 
   288 fun record_update_tr' tm =
   289   let val (ts, u) = gen_fields_tr' "_update" updateN tm in
   290     Syntax.const "_record_update" $ u $
   291       foldr1 (fn (v, w) => Syntax.const "_updates" $ v $ w) (rev ts)
   292   end;
   293 
   294 
   295 fun gen_field_tr' sfx tr' name =
   296   let val name_sfx = suffix sfx name
   297   in (name_sfx, fn [t, u] => tr' (Syntax.const name_sfx $ t $ u) | _ => raise Match) end;
   298 
   299 fun print_translation names =
   300   map (gen_field_tr' field_typeN record_type_tr') names @
   301   map (gen_field_tr' fieldN record_tr') names @
   302   map (gen_field_tr' updateN record_update_tr') names;
   303 
   304 
   305 
   306 (*** extend theory by record definition ***)
   307 
   308 (** record info **)
   309 
   310 (* type record_info and parent_info *)
   311 
   312 type record_info =
   313  {args: (string * sort) list,
   314   parent: (typ list * string) option,
   315   fields: (string * typ) list,
   316   simps: thm list};
   317 
   318 type parent_info =
   319  {name: string,
   320   fields: (string * typ) list,
   321   simps: thm list};
   322 
   323 
   324 (* data kind 'HOL/records' *)
   325 
   326 type record_data =
   327  {records: record_info Symtab.table,
   328   sel_upd:
   329    {selectors: unit Symtab.table,
   330     updates: string Symtab.table,
   331     simpset: Simplifier.simpset},
   332   field_splits:
   333    {fields: unit Symtab.table,
   334     simpset: Simplifier.simpset}};
   335 
   336 fun make_record_data records sel_upd field_splits =
   337  {records = records, sel_upd = sel_upd, field_splits = field_splits}: record_data;
   338 
   339 structure RecordsArgs =
   340 struct
   341   val name = "HOL/records";
   342   type T = record_data;
   343 
   344   val empty =
   345     make_record_data Symtab.empty
   346       {selectors = Symtab.empty, updates = Symtab.empty, simpset = HOL_basic_ss}
   347       {fields = Symtab.empty, simpset = HOL_basic_ss};
   348 
   349   val copy = I;
   350   val prep_ext = I;
   351   fun merge
   352    ({records = recs1,
   353      sel_upd = {selectors = sels1, updates = upds1, simpset = ss1},
   354      field_splits = {fields = flds1, simpset = fld_ss1}},
   355     {records = recs2,
   356      sel_upd = {selectors = sels2, updates = upds2, simpset = ss2},
   357      field_splits = {fields = flds2, simpset = fld_ss2}}) =
   358     make_record_data
   359       (Symtab.merge (K true) (recs1, recs2))
   360       {selectors = Symtab.merge (K true) (sels1, sels2),
   361         updates = Symtab.merge (K true) (upds1, upds2),
   362         simpset = Simplifier.merge_ss (ss1, ss2)}
   363       {fields = Symtab.merge (K true) (flds1, flds2),
   364         simpset = Simplifier.merge_ss (fld_ss1, fld_ss2)};
   365 
   366   fun print sg ({records = recs, ...}: record_data) =
   367     let
   368       val prt_typ = Sign.pretty_typ sg;
   369       val ext_const = Sign.cond_extern sg Sign.constK;
   370 
   371       fun pretty_parent None = []
   372         | pretty_parent (Some (Ts, name)) =
   373             [Pretty.block [prt_typ (Type (name, Ts)), Pretty.str " +"]];
   374 
   375       fun pretty_field (c, T) = Pretty.block
   376         [Pretty.str (ext_const c), Pretty.str " ::", Pretty.brk 1, Pretty.quote (prt_typ T)];
   377 
   378       fun pretty_record (name, {args, parent, fields, simps = _}) = Pretty.block (Pretty.fbreaks
   379         (Pretty.block [prt_typ (Type (name, map TFree args)), Pretty.str " = "] ::
   380           pretty_parent parent @ map pretty_field fields));
   381     in seq (Pretty.writeln o pretty_record) (Sign.cond_extern_table sg Sign.typeK recs) end;
   382 end;
   383 
   384 structure RecordsData = TheoryDataFun(RecordsArgs);
   385 val print_records = RecordsData.print;
   386 
   387 
   388 (* access 'records' *)
   389 
   390 fun get_record thy name = Symtab.lookup (#records (RecordsData.get thy), name);
   391 
   392 fun put_record name info thy =
   393   let
   394     val {records, sel_upd, field_splits} = RecordsData.get thy;
   395     val data = make_record_data (Symtab.update ((name, info), records)) sel_upd field_splits;
   396   in RecordsData.put data thy end;
   397 
   398 
   399 (* access 'sel_upd' *)
   400 
   401 fun get_sel_upd sg = #sel_upd (RecordsData.get_sg sg);
   402 
   403 fun get_selectors sg name = Symtab.lookup (#selectors (get_sel_upd sg), name);
   404 fun get_updates sg name = Symtab.lookup (#updates (get_sel_upd sg), name);
   405 fun get_simpset sg = #simpset (get_sel_upd sg);
   406 
   407 
   408 fun put_sel_upd names simps thy =
   409   let
   410     val sels = map (rpair ()) names;
   411     val upds = map (suffix updateN) names ~~ names;
   412 
   413     val {records, sel_upd = {selectors, updates, simpset}, field_splits} = RecordsData.get thy;
   414     val data = make_record_data records
   415       {selectors = Symtab.extend (selectors, sels),
   416         updates = Symtab.extend (updates, upds),
   417         simpset = Simplifier.addsimps (simpset, simps)}
   418       field_splits;
   419   in RecordsData.put data thy end;
   420 
   421 
   422 (* access 'field_splits' *)
   423 
   424 fun add_record_splits splits thy =
   425   let
   426     val {records, sel_upd, field_splits = {fields, simpset}} = RecordsData.get thy;
   427     val flds = map (rpair () o fst) splits;
   428     val simps = map snd splits;
   429     val data = make_record_data records sel_upd
   430       {fields = Symtab.extend (fields, flds), simpset = Simplifier.addsimps (simpset, simps)};
   431   in RecordsData.put data thy end;
   432 
   433 
   434 (* parent records *)
   435 
   436 fun inst_record thy (types, name) =
   437   let
   438     val sign = Theory.sign_of thy;
   439     fun err msg = error (msg ^ " parent record " ^ quote name);
   440 
   441     val {args, parent, fields, simps} =
   442       (case get_record thy name of Some info => info | None => err "Unknown");
   443     val _ = if length types <> length args then err "Bad number of arguments for" else ();
   444 
   445     fun bad_inst ((x, S), T) =
   446       if Sign.of_sort sign (T, S) then None else Some x
   447     val bads = mapfilter bad_inst (args ~~ types);
   448 
   449     val inst = map fst args ~~ types;
   450     val subst = Term.map_type_tfree (fn (x, _) => the (assoc (inst, x)));
   451   in
   452     if not (null bads) then
   453       err ("Ill-sorted instantiation of " ^ commas bads ^ " in")
   454     else (apsome (apfst (map subst)) parent, map (apsnd subst) fields, simps)
   455   end;
   456 
   457 fun add_parents thy (None, parents) = parents
   458   | add_parents thy (Some (types, name), parents) =
   459       let val (pparent, pfields, psimps) = inst_record thy (types, name)
   460       in add_parents thy (pparent, {name = name, fields = pfields, simps = psimps} :: parents) end;
   461 
   462 
   463 
   464 (** record simproc **)
   465 
   466 local
   467 
   468 val sel_upd_pat = [Thm.read_cterm (Theory.sign_of HOL.thy) ("s (u k r)", HOLogic.termT)];
   469 
   470 fun proc sg _ t =
   471   (case t of (sel as Const (s, _)) $ ((upd as Const (u, _)) $ k $ r) =>
   472     (case get_selectors sg s of Some () =>
   473       (case get_updates sg u of Some u_name =>
   474         let
   475           fun atomize x t = Free (x, fastype_of t);
   476           val k' = atomize "k" k;
   477           val r' = atomize "r" r;
   478           val t' = sel $ (upd $ k' $ r');
   479           val prove = mk_meta_eq o prove_simp sg (get_simpset sg) [] [];
   480         in
   481           if u_name = s then Some (prove (t' === k'))
   482           else Some (prove (t' === sel $ r'))
   483         end
   484       | None => None)
   485     | None => None)
   486   | _ => None);
   487 
   488 in
   489 
   490 val record_simproc = Simplifier.mk_simproc "record_simp" sel_upd_pat proc;
   491 
   492 end;
   493 
   494 
   495 
   496 (** record field splitting **)
   497 
   498 (* tactic *)
   499 
   500 fun record_split_tac i st =
   501   let
   502     val {field_splits = {fields, simpset}, ...} = RecordsData.get_sg (Thm.sign_of_thm st);
   503 
   504     fun is_fieldT (_, Type (a, [_, _])) = is_some (Symtab.lookup (fields, a))
   505       | is_fieldT _ = false;
   506     val params = Logic.strip_params (Library.nth_elem (i - 1, Thm.prems_of st));
   507   in
   508     if exists is_fieldT params then Simplifier.full_simp_tac simpset i st
   509     else Seq.empty
   510   end handle Library.LIST _ => Seq.empty;
   511 
   512 
   513 (* wrapper *)
   514 
   515 val record_split_name = "record_split_tac";
   516 val record_split_wrapper = (record_split_name, fn tac => record_split_tac ORELSE' tac);
   517 
   518 
   519 (* method *)
   520 
   521 val record_split_method =
   522   ("record_split", Method.no_args (Method.METHOD0 (HEADGOAL record_split_tac)),
   523     "split record fields");
   524 
   525 
   526 
   527 (** internal theory extenders **)
   528 
   529 (* field_type_defs *)
   530 
   531 fun field_type_def ((thy, simps), (name, tname, vs, T, U)) =
   532   let
   533     val full = Sign.full_name (Theory.sign_of thy);
   534     val (thy', {simps = simps', ...}) =
   535       thy
   536       |> setmp DatatypePackage.quiet_mode true
   537         (DatatypePackage.add_datatype_i true [tname]
   538           [(vs, tname, Syntax.NoSyn, [(name, [T, U], Syntax.NoSyn)])]);
   539     val thy'' =
   540       thy'
   541       |> setmp AxClass.quiet_mode true
   542         (AxClass.add_inst_arity_i (full tname, [HOLogic.termS, moreS], moreS) [] [] None);
   543   in (thy'', simps' @ simps) end;
   544 
   545 fun field_type_defs args thy = foldl field_type_def ((thy, []), args);
   546 
   547 
   548 (* field_definitions *)
   549 
   550 fun field_definitions fields names zeta moreT more vars named_vars thy =
   551   let
   552     val sign = Theory.sign_of thy;
   553     val base = Sign.base_name;
   554     val full_path = Sign.full_name_path sign;
   555 
   556 
   557     (* prepare declarations and definitions *)
   558 
   559     (*field types*)
   560     fun mk_fieldT_spec c =
   561       (suffix raw_fieldN c, suffix field_typeN c,
   562         ["'a", zeta], TFree ("'a", HOLogic.termS), moreT);
   563     val fieldT_specs = map (mk_fieldT_spec o base) names;
   564 
   565     (*field constructors*)
   566     val field_decls = map (mk_fieldC moreT) fields;
   567 
   568     fun mk_field_spec (c, v) =
   569       mk_field ((c, v), more) :== mk_raw_field ((c, v), more);
   570     val field_specs = map mk_field_spec named_vars;
   571 
   572     (*field destructors*)
   573     val dest_decls = map (mk_fstC moreT) fields @ map (mk_sndC moreT) fields;
   574 
   575     fun mk_dest_spec dest f (c, T) =
   576       let val p = Free ("p", mk_fieldT ((c, T), moreT));
   577       in dest p :== mk_prod_case (suffix field_typeN c) (f T moreT) p end;
   578     val dest_specs =
   579       map (mk_dest_spec mk_fst fst_fn) fields @
   580       map (mk_dest_spec mk_snd snd_fn) fields;
   581 
   582 
   583     (* prepare theorems *)
   584 
   585     (*constructor injects*)
   586     fun mk_inject_prop (c, v) =
   587       HOLogic.mk_eq (mk_field ((c, v), more), mk_field ((c, prime v), prime more)) ===
   588         (HOLogic.conj $ HOLogic.mk_eq (v, prime v) $ HOLogic.mk_eq (more, prime more));
   589     val inject_props = map mk_inject_prop named_vars;
   590 
   591     (*destructor conversions*)
   592     fun mk_dest_prop dest dest' (c, v) =
   593       dest (mk_field ((c, v), more)) === dest' (v, more);
   594     val dest_props =
   595       map (mk_dest_prop mk_fst fst) named_vars @
   596       map (mk_dest_prop mk_snd snd) named_vars;
   597 
   598     (*surjective pairing*)
   599     fun mk_surj_prop (c, T) =
   600       let val p = Free ("p", mk_fieldT ((c, T), moreT));
   601       in p === mk_field ((c, mk_fst p), mk_snd p) end;
   602     val surj_props = map mk_surj_prop fields;
   603 
   604 
   605     (* 1st stage: types_thy *)
   606 
   607     val (types_thy, datatype_simps) =
   608       thy
   609       |> field_type_defs fieldT_specs;
   610 
   611 
   612     (* 2nd stage: defs_thy *)
   613 
   614     val (defs_thy, (field_defs, dest_defs)) =
   615       types_thy
   616        |> (Theory.add_consts_i o map (Syntax.no_syn o apfst base)) (field_decls @ dest_decls)
   617        |> (PureThy.add_defs_i o map (fn x => (x, [Drule.tag_internal]))) field_specs
   618        |>>> (PureThy.add_defs_i o map (fn x => (x, [Drule.tag_internal]))) dest_specs;
   619 
   620 
   621     (* 3rd stage: thms_thy *)
   622 
   623     val prove = prove_simp (Theory.sign_of defs_thy) HOL_basic_ss;
   624     val prove_std = prove [] (field_defs @ dest_defs @ datatype_simps);
   625 
   626     val field_injects = map prove_std inject_props;
   627     val dest_convs = map prove_std dest_props;
   628     val surj_pairs = map (prove [DatatypePackage.induct_tac "p" 1]
   629       (map Thm.symmetric field_defs @ dest_convs)) surj_props;
   630 
   631     fun mk_split th = SplitPairedAll.rule (th RS eq_reflection);
   632     val field_splits = map mk_split surj_pairs;
   633 
   634     val thms_thy =
   635       defs_thy
   636       |> (#1 oo (PureThy.add_thmss o map Thm.no_attributes))
   637         [("field_defs", field_defs),
   638           ("dest_defs", dest_defs),
   639           ("dest_convs", dest_convs),
   640           ("surj_pairs", surj_pairs),
   641           ("field_splits", field_splits)];
   642 
   643   in (thms_thy, dest_convs, field_injects, field_splits) end;
   644 
   645 
   646 (* record_definition *)
   647 
   648 fun record_definition (args, bname) parent (parents: parent_info list) bfields thy =
   649   let
   650     val sign = Theory.sign_of thy;
   651     val full = Sign.full_name_path sign bname;
   652     val base = Sign.base_name;
   653 
   654 
   655     (* basic components *)
   656 
   657     val alphas = map fst args;
   658     val name = Sign.full_name sign bname;       (*not made part of record name space!*)
   659 
   660     val parent_fields = flat (map #fields parents);
   661     val parent_names = map fst parent_fields;
   662     val parent_types = map snd parent_fields;
   663     val parent_len = length parent_fields;
   664     val parent_xs = variantlist (map (base o fst) parent_fields, [moreN, recordN]);
   665     val parent_vars = ListPair.map Free (parent_xs, parent_types);
   666     val parent_named_vars = parent_names ~~ parent_vars;
   667 
   668     val fields = map (apfst full) bfields;
   669     val names = map fst fields;
   670     val types = map snd fields;
   671     val len = length fields;
   672     val xs = variantlist (map fst bfields, moreN :: recordN :: parent_xs);
   673     val vars = ListPair.map Free (xs, types);
   674     val named_vars = names ~~ vars;
   675 
   676     val all_fields = parent_fields @ fields;
   677     val all_names = parent_names @ names;
   678     val all_types = parent_types @ types;
   679     val all_len = parent_len + len;
   680     val all_xs = parent_xs @ xs;
   681     val all_vars = parent_vars @ vars;
   682     val all_named_vars = parent_named_vars @ named_vars;
   683 
   684     val zeta = variant alphas "'z";
   685     val moreT = TFree (zeta, moreS);
   686     val more = Free (moreN, moreT);
   687     val full_moreN = full moreN;
   688     fun more_part t = mk_more t full_moreN;
   689     fun more_part_update t x = mk_more_update t (full_moreN, x);
   690 
   691     val parent_more = funpow parent_len mk_snd;
   692     val idxs = 0 upto (len - 1);
   693 
   694     val rec_schemeT = mk_recordT (all_fields, moreT);
   695     val rec_scheme = mk_record (all_named_vars, more);
   696     val r = Free (recordN, rec_schemeT);
   697     val recT = mk_recordT (all_fields, HOLogic.unitT);
   698 
   699 
   700     (* prepare print translation functions *)
   701 
   702     val field_tr's =
   703       print_translation (distinct (flat (map NameSpace.accesses (full_moreN :: names))));
   704 
   705 
   706     (* prepare declarations *)
   707 
   708     val sel_decls = map (mk_selC rec_schemeT) bfields @
   709       [mk_moreC rec_schemeT (moreN, moreT)];
   710     val update_decls = map (mk_updateC rec_schemeT) bfields @
   711       [mk_more_updateC rec_schemeT (moreN, moreT)];
   712     val make_decls =
   713       [(mk_makeC rec_schemeT (make_schemeN, all_types @ [moreT])),
   714        (mk_makeC recT (makeN, all_types))];
   715 
   716 
   717     (* prepare definitions *)
   718 
   719     (*record (scheme) type abbreviation*)
   720     val recordT_specs =
   721       [(suffix schemeN bname, alphas @ [zeta], rec_schemeT, Syntax.NoSyn),
   722         (bname, alphas, recT, Syntax.NoSyn)];
   723 
   724     (*selectors*)
   725     fun mk_sel_spec (i, c) =
   726       mk_sel r c :== mk_fst (funpow i mk_snd (parent_more r));
   727     val sel_specs =
   728       ListPair.map mk_sel_spec (idxs, names) @
   729         [more_part r :== funpow len mk_snd (parent_more r)];
   730 
   731     (*updates*)
   732     val all_sels = all_names ~~ map (mk_sel r) all_names;
   733     fun mk_upd_spec (i, (c, x)) =
   734       mk_update r (c, x) :==
   735         mk_record (nth_update (c, x) (parent_len + i, all_sels), more_part r)
   736     val update_specs =
   737       ListPair.map mk_upd_spec (idxs, named_vars) @
   738         [more_part_update r more :== mk_record (all_sels, more)];
   739 
   740     (*makes*)
   741     val make_scheme = Const (mk_makeC rec_schemeT (full make_schemeN, all_types @ [moreT]));
   742     val make = Const (mk_makeC recT (full makeN, all_types));
   743     val make_specs =
   744       [list_comb (make_scheme, all_vars) $ more :== rec_scheme,
   745         list_comb (make, all_vars) :== mk_record (all_named_vars, HOLogic.unit)];
   746 
   747 
   748     (* prepare propositions *)
   749 
   750     (*selectors*)
   751     val sel_props =
   752       map (fn (c, x) => mk_sel rec_scheme c === x) named_vars @
   753         [more_part rec_scheme === more];
   754 
   755     (*updates*)
   756     fun mk_upd_prop (i, (c, T)) =
   757       let val x' = Free (variant all_xs (base c ^ "'"), T) in
   758         mk_update rec_scheme (c, x') ===
   759           mk_record (nth_update (c, x') (parent_len + i, all_named_vars), more)
   760       end;
   761     val update_props =
   762       ListPair.map mk_upd_prop (idxs, fields) @
   763         let val more' = Free (variant all_xs (moreN ^ "'"), moreT)
   764         in [more_part_update rec_scheme more' === mk_record (all_named_vars, more')] end;
   765 
   766 
   767     (* 1st stage: fields_thy *)
   768 
   769     val (fields_thy, field_simps, field_injects, field_splits) =
   770       thy
   771       |> Theory.add_path bname
   772       |> field_definitions fields names zeta moreT more vars named_vars;
   773 
   774     val named_splits = map2 (fn (c, th) => (suffix field_typeN c, th)) (names, field_splits);
   775 
   776 
   777     (* 2nd stage: defs_thy *)
   778 
   779     val (defs_thy, ((sel_defs, update_defs), make_defs)) =
   780       fields_thy
   781       |> Theory.parent_path
   782       |> Theory.add_tyabbrs_i recordT_specs     (*not made part of record name space!*)
   783       |> Theory.add_path bname
   784       |> Theory.add_trfuns ([], [], field_tr's, [])
   785       |> (Theory.add_consts_i o map Syntax.no_syn)
   786         (sel_decls @ update_decls @ make_decls)
   787       |> (PureThy.add_defs_i o map (fn x => (x, [Drule.tag_internal]))) sel_specs
   788       |>>> (PureThy.add_defs_i o map (fn x => (x, [Drule.tag_internal]))) update_specs
   789       |>>> (PureThy.add_defs_i o map Thm.no_attributes) make_specs;
   790 
   791 
   792     (* 3rd stage: thms_thy *)
   793 
   794     val parent_simps = flat (map #simps parents);
   795     val prove = prove_simp (Theory.sign_of defs_thy) HOL_basic_ss [];
   796 
   797     val sel_convs = map (prove (parent_simps @ sel_defs @ field_simps)) sel_props;
   798     val update_convs = map (prove (parent_simps @ update_defs @ sel_convs)) update_props;
   799 
   800     val simps = field_simps @ sel_convs @ update_convs @ make_defs;
   801     val iffs = field_injects;
   802 
   803     val thms_thy =
   804       defs_thy
   805       |> (#1 oo (PureThy.add_thmss o map Thm.no_attributes))
   806         [("select_defs", sel_defs),
   807           ("update_defs", update_defs),
   808           ("make_defs", make_defs),
   809           ("select_convs", sel_convs),
   810           ("update_convs", update_convs)]
   811       |> (#1 oo PureThy.add_thmss)
   812         [(("simps", simps), [Simplifier.simp_add_global]),
   813          (("iffs", iffs), [iff_add_global])];
   814 
   815 
   816     (* 4th stage: final_thy *)
   817 
   818     val final_thy =
   819       thms_thy
   820       |> put_record name {args = args, parent = parent, fields = fields, simps = simps}
   821       |> put_sel_upd names (field_simps @ sel_defs @ update_defs)
   822       |> add_record_splits named_splits
   823       |> Theory.parent_path;
   824 
   825   in (final_thy, {simps = simps, iffs = iffs}) end;
   826 
   827 
   828 
   829 (** theory extender interface **)
   830 
   831 (* prepare arguments *)
   832 
   833 (*note: read_raw_typ avoids expanding type abbreviations*)
   834 fun read_raw_parent sign s =
   835   (case Sign.read_raw_typ (sign, K None) s handle TYPE (msg, _, _) => error msg of
   836     Type (name, Ts) => (Ts, name)
   837   | _ => error ("Bad parent record specification: " ^ quote s));
   838 
   839 fun read_typ sign (env, s) =
   840   let
   841     fun def_sort (x, ~1) = assoc (env, x)
   842       | def_sort _ = None;
   843     val T = Type.no_tvars (Sign.read_typ (sign, def_sort) s) handle TYPE (msg, _, _) => error msg;
   844   in (Term.add_typ_tfrees (T, env), T) end;
   845 
   846 fun cert_typ sign (env, raw_T) =
   847   let val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle TYPE (msg, _, _) => error msg
   848   in (Term.add_typ_tfrees (T, env), T) end;
   849 
   850 
   851 (* add_record *)
   852 
   853 (*we do all preparations and error checks here, deferring the real
   854   work to record_definition*)
   855 
   856 fun gen_add_record prep_typ prep_raw_parent (params, bname) raw_parent raw_fields thy =
   857   let
   858     val _ = Theory.requires thy "Record" "record definitions";
   859     val sign = Theory.sign_of thy;
   860     val _ = message ("Defining record " ^ quote bname ^ " ...");
   861 
   862 
   863     (* parents *)
   864 
   865     fun prep_inst T = snd (cert_typ sign ([], T));
   866 
   867     val parent = apsome (apfst (map prep_inst) o prep_raw_parent sign) raw_parent
   868       handle ERROR => error ("The error(s) above in parent record specification");
   869     val parents = add_parents thy (parent, []);
   870 
   871     val init_env =
   872       (case parent of
   873         None => []
   874       | Some (types, _) => foldr Term.add_typ_tfrees (types, []));
   875 
   876 
   877     (* fields *)
   878 
   879     fun prep_field (env, (c, raw_T)) =
   880       let val (env', T) = prep_typ sign (env, raw_T) handle ERROR =>
   881         error ("The error(s) above occured in field " ^ quote c)
   882       in (env', (c, T)) end;
   883 
   884     val (envir, bfields) = foldl_map prep_field (init_env, raw_fields);
   885     val envir_names = map fst envir;
   886 
   887 
   888     (* args *)
   889 
   890     val defaultS = Sign.defaultS sign;
   891     val args = map (fn x => (x, if_none (assoc (envir, x)) defaultS)) params;
   892 
   893 
   894     (* errors *)
   895 
   896     val name = Sign.full_name sign bname;
   897     val err_dup_record =
   898       if is_none (get_record thy name) then []
   899       else ["Duplicate definition of record " ^ quote name];
   900 
   901     val err_dup_parms =
   902       (case duplicates params of
   903         [] => []
   904       | dups => ["Duplicate parameter(s) " ^ commas dups]);
   905 
   906     val err_extra_frees =
   907       (case gen_rems (op =) (envir_names, params) of
   908         [] => []
   909       | extras => ["Extra free type variable(s) " ^ commas extras]);
   910 
   911     val err_no_fields = if null bfields then ["No fields present"] else [];
   912 
   913     val err_dup_fields =
   914       (case duplicates (map fst bfields) of
   915         [] => []
   916       | dups => ["Duplicate field(s) " ^ commas_quote dups]);
   917 
   918     val err_bad_fields =
   919       if forall (not_equal moreN o fst) bfields then []
   920       else ["Illegal field name " ^ quote moreN];
   921 
   922     val err_dup_sorts =
   923       (case duplicates envir_names of
   924         [] => []
   925       | dups => ["Inconsistent sort constraints for " ^ commas dups]);
   926 
   927     val errs =
   928       err_dup_record @ err_dup_parms @ err_extra_frees @ err_no_fields @
   929       err_dup_fields @ err_bad_fields @ err_dup_sorts;
   930   in
   931     if null errs then () else error (cat_lines errs);
   932     thy |> record_definition (args, bname) parent parents bfields
   933   end
   934   handle ERROR => error ("Failed to define record " ^ quote bname);
   935 
   936 val add_record = gen_add_record read_typ read_raw_parent;
   937 val add_record_i = gen_add_record cert_typ (K I);
   938 
   939 
   940 
   941 (** package setup **)
   942 
   943 (* setup theory *)
   944 
   945 val setup =
   946  [RecordsData.init,
   947   Theory.add_trfuns ([], parse_translation, [], []),
   948   Method.add_methods [record_split_method],
   949   Simplifier.change_simpset_of Simplifier.addsimprocs [record_simproc]];
   950 
   951 
   952 (* outer syntax *)
   953 
   954 local structure P = OuterParse and K = OuterSyntax.Keyword in
   955 
   956 val record_decl =
   957   P.type_args -- P.name -- (P.$$$ "=" |-- Scan.option (P.typ --| P.$$$ "+")
   958     -- Scan.repeat1 (P.name -- (P.$$$ "::" |-- P.typ) --| P.marg_comment));
   959 
   960 val recordP =
   961   OuterSyntax.command "record" "define extensible record" K.thy_decl
   962     (record_decl >> (fn (x, (y, z)) => Toplevel.theory (#1 o add_record x y z)));
   963 
   964 val _ = OuterSyntax.add_parsers [recordP];
   965 
   966 end;
   967 
   968 
   969 end;
   970 
   971 structure BasicRecordPackage: BASIC_RECORD_PACKAGE = RecordPackage;
   972 open BasicRecordPackage;