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