src/HOL/Tools/record_package.ML
author schirmer
Thu Nov 06 20:45:02 2003 +0100 (2003-11-06)
changeset 14255 e6e3e3f0deed
parent 14079 1c22e5499eeb
child 14358 233c5bd5b539
permissions -rw-r--r--
Records:
- Record types are now by default printed with their type abbreviation
instead of the list of all field types. This can be configured via
the reference "print_record_type_abbr".
- Simproc "record_upd_simproc" for simplification of multiple updates
added (not enabled by default).
- Tactic "record_split_simp_tac" to split and simplify records added.
- Bug-fix and optimisation of "record_simproc".
- "record_simproc" and "record_upd_simproc" are now sensitive to
quick_and_dirty flag.
wenzelm@4867
     1
(*  Title:      HOL/Tools/record_package.ML
wenzelm@4867
     2
    ID:         $Id$
wenzelm@4867
     3
    Author:     Wolfgang Naraschewski and Markus Wenzel, TU Muenchen
wenzelm@9230
     4
    License:    GPL (GNU GENERAL PUBLIC LICENSE)
wenzelm@4867
     5
wenzelm@4867
     6
Extensible records with structural subtyping in HOL.
wenzelm@5698
     7
*)
wenzelm@4867
     8
wenzelm@5698
     9
signature BASIC_RECORD_PACKAGE =
wenzelm@5698
    10
sig
wenzelm@7178
    11
  val record_simproc: simproc
berghofe@14079
    12
  val record_eq_simproc: simproc
wenzelm@5698
    13
  val record_split_tac: int -> tactic
wenzelm@5713
    14
  val record_split_name: string
wenzelm@5698
    15
  val record_split_wrapper: string * wrapper
schirmer@14255
    16
  val print_record_type_abbr: bool ref 
wenzelm@5698
    17
end;
wenzelm@4867
    18
wenzelm@4867
    19
signature RECORD_PACKAGE =
wenzelm@4867
    20
sig
wenzelm@5698
    21
  include BASIC_RECORD_PACKAGE
wenzelm@5698
    22
  val quiet_mode: bool ref
wenzelm@8574
    23
  val updateN: string
wenzelm@4890
    24
  val mk_fieldT: (string * typ) * typ -> typ
wenzelm@4890
    25
  val dest_fieldT: typ -> (string * typ) * typ
schirmer@14255
    26
  val dest_fieldTs: typ -> (string * typ) list
schirmer@14255
    27
  val last_fieldT: typ -> (string * typ) option
wenzelm@4890
    28
  val mk_field: (string * term) * term -> term
wenzelm@4890
    29
  val mk_fst: term -> term
wenzelm@4890
    30
  val mk_snd: term -> term
wenzelm@4890
    31
  val mk_recordT: (string * typ) list * typ -> typ
wenzelm@4890
    32
  val dest_recordT: typ -> (string * typ) list * typ
wenzelm@4890
    33
  val mk_record: (string * term) list * term -> term
wenzelm@4890
    34
  val mk_sel: term -> string -> term
wenzelm@4890
    35
  val mk_update: term -> string * term -> term
wenzelm@4867
    36
  val print_records: theory -> unit
wenzelm@4867
    37
  val add_record: (string list * bstring) -> string option
wenzelm@12506
    38
    -> (bstring * string * mixfix) list -> theory -> theory * {simps: thm list, iffs: thm list}
wenzelm@4867
    39
  val add_record_i: (string list * bstring) -> (typ list * string) option
wenzelm@12506
    40
    -> (bstring * typ * mixfix) list -> theory -> theory * {simps: thm list, iffs: thm list}
wenzelm@4867
    41
  val setup: (theory -> theory) list
schirmer@14255
    42
  val record_upd_simproc: simproc
schirmer@14255
    43
  val record_split_simproc: (term -> bool) -> simproc
schirmer@14255
    44
  val record_split_simp_tac: (term -> bool) -> int -> tactic
wenzelm@4867
    45
end;
wenzelm@4867
    46
schirmer@14255
    47
structure RecordPackage :RECORD_PACKAGE =
wenzelm@4867
    48
struct
wenzelm@4867
    49
wenzelm@4867
    50
wenzelm@11832
    51
(*** theory context references ***)
wenzelm@11832
    52
wenzelm@11832
    53
val product_typeN = "Record.product_type";
wenzelm@11832
    54
wenzelm@13419
    55
val product_type_intro = thm "product_type.intro";
wenzelm@13413
    56
val product_type_inject = thm "product_type.inject";
wenzelm@13413
    57
val product_type_conv1 = thm "product_type.conv1";
wenzelm@13413
    58
val product_type_conv2 = thm "product_type.conv2";
wenzelm@13413
    59
val product_type_induct = thm "product_type.induct";
wenzelm@13413
    60
val product_type_cases = thm "product_type.cases";
wenzelm@13413
    61
val product_type_split_paired_all = thm "product_type.split_paired_all";
berghofe@14079
    62
val product_type_split_paired_All = thm "product_type.split_paired_All";
wenzelm@11832
    63
wenzelm@11832
    64
wenzelm@11832
    65
wenzelm@4894
    66
(*** utilities ***)
wenzelm@4867
    67
wenzelm@5698
    68
(* messages *)
wenzelm@5698
    69
wenzelm@5698
    70
val quiet_mode = ref false;
wenzelm@5698
    71
fun message s = if ! quiet_mode then () else writeln s;
wenzelm@5698
    72
wenzelm@5698
    73
wenzelm@12255
    74
(* syntax *)
wenzelm@4867
    75
wenzelm@12247
    76
fun prune n xs = Library.drop (n, xs);
wenzelm@11832
    77
fun prefix_base s = NameSpace.map_base (fn bname => s ^ bname);
wenzelm@11832
    78
wenzelm@11927
    79
val Trueprop = HOLogic.mk_Trueprop;
wenzelm@11927
    80
fun All xs t = Term.list_all_free (xs, t);
wenzelm@4894
    81
wenzelm@11934
    82
infix 9 $$;
wenzelm@11934
    83
infix 0 :== ===;
wenzelm@11934
    84
infixr 0 ==>;
wenzelm@11934
    85
wenzelm@11934
    86
val (op $$) = Term.list_comb;
wenzelm@11927
    87
val (op :==) = Logic.mk_defpair;
wenzelm@11927
    88
val (op ===) = Trueprop o HOLogic.mk_eq;
wenzelm@11927
    89
val (op ==>) = Logic.mk_implies;
wenzelm@11927
    90
wenzelm@11927
    91
wenzelm@12255
    92
(* attributes *)
wenzelm@12255
    93
wenzelm@12302
    94
fun case_names_fields x = RuleCases.case_names ["fields"] x;
wenzelm@12255
    95
fun induct_type_global name = [case_names_fields, InductAttrib.induct_type_global name];
wenzelm@12255
    96
fun cases_type_global name = [case_names_fields, InductAttrib.cases_type_global name];
wenzelm@12255
    97
wenzelm@12255
    98
wenzelm@12255
    99
(* tactics *)
wenzelm@11927
   100
wenzelm@11967
   101
fun simp_all_tac ss simps = ALLGOALS (Simplifier.asm_full_simp_tac (ss addsimps simps));
wenzelm@4895
   102
berghofe@13904
   103
(* do case analysis / induction on last parameter of ith subgoal (or s) *)
berghofe@13904
   104
berghofe@13904
   105
fun try_param_tac s rule i st =
berghofe@13904
   106
  let
berghofe@13904
   107
    val cert = cterm_of (#sign (rep_thm st));
berghofe@13904
   108
    val g = nth_elem (i - 1, prems_of st);
berghofe@13904
   109
    val params = Logic.strip_params g;
berghofe@13904
   110
    val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl g);
berghofe@13904
   111
    val rule' = Thm.lift_rule (st, i) rule;
berghofe@13904
   112
    val (P, ys) = strip_comb (HOLogic.dest_Trueprop
berghofe@13904
   113
      (Logic.strip_assums_concl (prop_of rule')));
berghofe@13904
   114
    val (x, ca) = (case rev (drop (length params, ys)) of
berghofe@13904
   115
        [] => (head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
berghofe@13904
   116
          (hd (rev (Logic.strip_assums_hyp (hd (prems_of rule')))))))), true)
berghofe@13904
   117
      | [x] => (head_of x, false));
berghofe@13904
   118
    val rule'' = cterm_instantiate (map (pairself cert) (case (rev params) of
berghofe@13904
   119
        [] => (case assoc (map dest_Free (term_frees (prop_of st)), s) of
berghofe@13904
   120
          None => sys_error "try_param_tac: no such variable"
berghofe@13904
   121
        | Some T => [(P, if ca then concl else lambda (Free (s, T)) concl),
berghofe@13904
   122
            (x, Free (s, T))])
berghofe@13904
   123
      | (_, T) :: _ => [(P, list_abs (params, if ca then concl
berghofe@13904
   124
          else incr_boundvars 1 (Abs (s, T, concl)))),
berghofe@13904
   125
        (x, list_abs (params, Bound 0))])) rule'
berghofe@13904
   126
  in compose_tac (false, rule'', nprems_of rule) i st end;
wenzelm@4894
   127
wenzelm@4894
   128
wenzelm@4894
   129
berghofe@12449
   130
(*** code generator data ***)
berghofe@12449
   131
berghofe@12449
   132
val [prod_code, fst_code, snd_code] =
berghofe@12449
   133
  map (Codegen.parse_mixfix (K (Bound 0))) ["(_,/ _)", "fst", "snd"];
berghofe@12449
   134
val prodT_code = Codegen.parse_mixfix (K dummyT) "(_ */ _)";
berghofe@12449
   135
berghofe@12449
   136
berghofe@12449
   137
wenzelm@4894
   138
(*** syntax operations ***)
wenzelm@4894
   139
wenzelm@4894
   140
(** name components **)
wenzelm@4894
   141
wenzelm@11927
   142
val rN = "r";
wenzelm@4894
   143
val moreN = "more";
wenzelm@4894
   144
val schemeN = "_scheme";
wenzelm@11832
   145
val field_typeN = "_field_type";
wenzelm@4894
   146
val fieldN = "_field";
wenzelm@5698
   147
val fstN = "_val";
wenzelm@5698
   148
val sndN = "_more";
wenzelm@4894
   149
val updateN = "_update";
wenzelm@4894
   150
val makeN = "make";
wenzelm@12265
   151
val fieldsN = "fields";
wenzelm@11934
   152
val extendN = "extend";
wenzelm@11934
   153
val truncateN = "truncate";
wenzelm@11934
   154
wenzelm@4890
   155
wenzelm@11832
   156
(*see typedef_package.ML*)
wenzelm@11832
   157
val RepN = "Rep_";
wenzelm@11832
   158
val AbsN = "Abs_";
wenzelm@5698
   159
wenzelm@5698
   160
wenzelm@5713
   161
wenzelm@4867
   162
(** tuple operations **)
wenzelm@4867
   163
wenzelm@4867
   164
(* types *)
wenzelm@4867
   165
wenzelm@4867
   166
fun mk_fieldT ((c, T), U) = Type (suffix field_typeN c, [T, U]);
wenzelm@4867
   167
wenzelm@4867
   168
fun dest_fieldT (typ as Type (c_field_type, [T, U])) =
wenzelm@4867
   169
      (case try (unsuffix field_typeN) c_field_type of
wenzelm@4867
   170
        None => raise TYPE ("dest_fieldT", [typ], [])
wenzelm@4867
   171
      | Some c => ((c, T), U))
wenzelm@4867
   172
  | dest_fieldT typ = raise TYPE ("dest_fieldT", [typ], []);
wenzelm@4867
   173
berghofe@14079
   174
fun dest_fieldTs T =
berghofe@14079
   175
  let val ((c, T), U) = dest_fieldT T
berghofe@14079
   176
  in (c, T) :: dest_fieldTs U
berghofe@14079
   177
  end handle TYPE _ => [];
berghofe@14079
   178
schirmer@14255
   179
fun last_fieldT T =
schirmer@14255
   180
  let val ((c, T), U) = dest_fieldT T
schirmer@14255
   181
  in (case last_fieldT U of
schirmer@14255
   182
        None => Some (c,T)
schirmer@14255
   183
      | Some l => Some l)
schirmer@14255
   184
  end handle TYPE _ => None
wenzelm@4867
   185
wenzelm@11832
   186
(* morphisms *)
wenzelm@11832
   187
wenzelm@11832
   188
fun mk_Rep U (c, T) =
wenzelm@11832
   189
  Const (suffix field_typeN (prefix_base RepN c),
wenzelm@11832
   190
    mk_fieldT ((c, T), U) --> HOLogic.mk_prodT (T, U));
wenzelm@11832
   191
wenzelm@11832
   192
fun mk_Abs U (c, T) =
wenzelm@11832
   193
  Const (suffix field_typeN (prefix_base AbsN c),
wenzelm@11832
   194
    HOLogic.mk_prodT (T, U) --> mk_fieldT ((c, T), U));
wenzelm@11833
   195
wenzelm@11832
   196
wenzelm@4867
   197
(* constructors *)
wenzelm@4867
   198
wenzelm@4867
   199
fun mk_fieldC U (c, T) = (suffix fieldN c, T --> U --> mk_fieldT ((c, T), U));
wenzelm@4867
   200
wenzelm@11832
   201
fun mk_field ((c, t), u) =
wenzelm@4867
   202
  let val T = fastype_of t and U = fastype_of u
wenzelm@11832
   203
  in Const (suffix fieldN c, [T, U] ---> mk_fieldT ((c, T), U)) $ t $ u end;
wenzelm@4867
   204
wenzelm@4867
   205
wenzelm@4867
   206
(* destructors *)
wenzelm@4867
   207
wenzelm@4867
   208
fun mk_fstC U (c, T) = (suffix fstN c, mk_fieldT ((c, T), U) --> T);
wenzelm@4867
   209
fun mk_sndC U (c, T) = (suffix sndN c, mk_fieldT ((c, T), U) --> U);
wenzelm@4867
   210
wenzelm@4867
   211
fun dest_field fst_or_snd p =
wenzelm@4867
   212
  let
wenzelm@4867
   213
    val pT = fastype_of p;
wenzelm@4867
   214
    val ((c, T), U) = dest_fieldT pT;
wenzelm@4867
   215
    val (destN, destT) = if fst_or_snd then (fstN, T) else (sndN, U);
wenzelm@4867
   216
  in Const (suffix destN c, pT --> destT) $ p end;
wenzelm@4867
   217
wenzelm@4867
   218
val mk_fst = dest_field true;
wenzelm@4867
   219
val mk_snd = dest_field false;
wenzelm@4867
   220
wenzelm@4867
   221
wenzelm@4867
   222
wenzelm@4867
   223
(** record operations **)
wenzelm@4867
   224
wenzelm@4867
   225
(* types *)
wenzelm@4867
   226
wenzelm@4867
   227
val mk_recordT = foldr mk_fieldT;
wenzelm@4867
   228
wenzelm@4867
   229
fun dest_recordT T =
wenzelm@4867
   230
  (case try dest_fieldT T of
wenzelm@4867
   231
    None => ([], T)
wenzelm@4867
   232
  | Some (c_T, U) => apfst (cons c_T) (dest_recordT U));
wenzelm@4867
   233
wenzelm@4867
   234
fun find_fieldT c rT =
wenzelm@4867
   235
  (case assoc (fst (dest_recordT rT), c) of
wenzelm@4867
   236
    None => raise TYPE ("find_field: " ^ c, [rT], [])
wenzelm@4867
   237
  | Some T => T);
wenzelm@4867
   238
wenzelm@4867
   239
wenzelm@4867
   240
(* constructors *)
wenzelm@4867
   241
wenzelm@4867
   242
val mk_record = foldr mk_field;
wenzelm@4867
   243
wenzelm@4867
   244
wenzelm@4867
   245
(* selectors *)
wenzelm@4867
   246
wenzelm@4867
   247
fun mk_selC rT (c, T) = (c, rT --> T);
wenzelm@4867
   248
wenzelm@4890
   249
fun mk_sel r c =
wenzelm@4867
   250
  let val rT = fastype_of r
wenzelm@4867
   251
  in Const (mk_selC rT (c, find_fieldT c rT)) $ r end;
wenzelm@4867
   252
wenzelm@11934
   253
fun mk_named_sels names r = names ~~ map (mk_sel r) names;
wenzelm@11934
   254
wenzelm@4894
   255
val mk_moreC = mk_selC;
wenzelm@4894
   256
wenzelm@4894
   257
fun mk_more r c =
wenzelm@4894
   258
  let val rT = fastype_of r
wenzelm@4894
   259
  in Const (mk_moreC rT (c, snd (dest_recordT rT))) $ r end;
wenzelm@4894
   260
wenzelm@4867
   261
wenzelm@4867
   262
(* updates *)
wenzelm@4867
   263
wenzelm@4867
   264
fun mk_updateC rT (c, T) = (suffix updateN c, T --> rT --> rT);
wenzelm@4867
   265
wenzelm@4890
   266
fun mk_update r (c, x) =
wenzelm@4867
   267
  let val rT = fastype_of r
wenzelm@4867
   268
  in Const (mk_updateC rT (c, find_fieldT c rT)) $ x $ r end;
wenzelm@4867
   269
wenzelm@5197
   270
val mk_more_updateC = mk_updateC;
wenzelm@5197
   271
wenzelm@5197
   272
fun mk_more_update r (c, x) =
wenzelm@5197
   273
  let val rT = fastype_of r
wenzelm@5197
   274
  in Const (mk_more_updateC rT (c, snd (dest_recordT rT))) $ x $ r end;
wenzelm@5197
   275
wenzelm@4867
   276
wenzelm@4867
   277
wenzelm@4867
   278
(** concrete syntax for records **)
wenzelm@4867
   279
wenzelm@4867
   280
(* parse translations *)
wenzelm@4867
   281
wenzelm@11473
   282
fun gen_field_tr mark sfx (t as Const (c, _) $ Const (name, _) $ arg) =
wenzelm@5197
   283
      if c = mark then Syntax.const (suffix sfx name) $ arg
wenzelm@5197
   284
      else raise TERM ("gen_field_tr: " ^ mark, [t])
wenzelm@5197
   285
  | gen_field_tr mark _ t = raise TERM ("gen_field_tr: " ^ mark, [t]);
wenzelm@4867
   286
wenzelm@5197
   287
fun gen_fields_tr sep mark sfx (tm as Const (c, _) $ t $ u) =
wenzelm@5197
   288
      if c = sep then gen_field_tr mark sfx t :: gen_fields_tr sep mark sfx u
wenzelm@5201
   289
      else [gen_field_tr mark sfx tm]
wenzelm@5201
   290
  | gen_fields_tr _ mark sfx tm = [gen_field_tr mark sfx tm];
wenzelm@5197
   291
wenzelm@5197
   292
fun gen_record_tr sep mark sfx unit [t] = foldr (op $) (gen_fields_tr sep mark sfx t, unit)
wenzelm@5201
   293
  | gen_record_tr _ _ _ _ ts = raise TERM ("gen_record_tr", ts);
wenzelm@5197
   294
wenzelm@5197
   295
fun gen_record_scheme_tr sep mark sfx [t, more] = foldr (op $) (gen_fields_tr sep mark sfx t, more)
wenzelm@5201
   296
  | gen_record_scheme_tr _ _ _ ts = raise TERM ("gen_record_scheme_tr", ts);
wenzelm@5197
   297
wenzelm@4867
   298
wenzelm@5197
   299
val record_type_tr = gen_record_tr "_field_types" "_field_type" field_typeN (Syntax.const "unit");
wenzelm@5197
   300
val record_type_scheme_tr = gen_record_scheme_tr "_field_types" "_field_type" field_typeN;
wenzelm@5197
   301
wenzelm@5197
   302
val record_tr = gen_record_tr "_fields" "_field" fieldN HOLogic.unit;
wenzelm@5197
   303
val record_scheme_tr = gen_record_scheme_tr "_fields" "_field" fieldN;
wenzelm@4867
   304
wenzelm@5197
   305
fun record_update_tr [t, u] =
wenzelm@5197
   306
      foldr (op $) (rev (gen_fields_tr "_updates" "_update" updateN u), t)
wenzelm@5197
   307
  | record_update_tr ts = raise TERM ("record_update_tr", ts);
wenzelm@5197
   308
wenzelm@5197
   309
wenzelm@11934
   310
fun update_name_tr (Free (x, T) :: ts) = Free (suffix updateN x, T) $$ ts
wenzelm@11934
   311
  | update_name_tr (Const (x, T) :: ts) = Const (suffix updateN x, T) $$ ts
wenzelm@11833
   312
  | update_name_tr (((c as Const ("_constrain", _)) $ t $ ty) :: ts) =
wenzelm@11934
   313
      (c $ update_name_tr [t] $ (Syntax.const "fun" $ ty $ Syntax.const "dummy")) $$ ts
wenzelm@11833
   314
  | update_name_tr ts = raise TERM ("update_name_tr", ts);
wenzelm@11833
   315
wenzelm@11833
   316
wenzelm@5197
   317
val parse_translation =
wenzelm@5197
   318
 [("_record_type", record_type_tr),
wenzelm@5197
   319
  ("_record_type_scheme", record_type_scheme_tr),
wenzelm@5197
   320
  ("_record", record_tr),
wenzelm@5197
   321
  ("_record_scheme", record_scheme_tr),
wenzelm@11833
   322
  ("_record_update", record_update_tr),
wenzelm@11833
   323
  ("_update_name", update_name_tr)];
wenzelm@4867
   324
wenzelm@4867
   325
wenzelm@4890
   326
(* print translations *)
wenzelm@4867
   327
schirmer@14255
   328
schirmer@14255
   329
val print_record_type_abbr = ref true;
schirmer@14255
   330
wenzelm@5197
   331
fun gen_fields_tr' mark sfx (tm as Const (name_field, _) $ t $ u) =
wenzelm@5197
   332
      (case try (unsuffix sfx) name_field of
wenzelm@5197
   333
        Some name =>
wenzelm@5197
   334
          apfst (cons (Syntax.const mark $ Syntax.free name $ t)) (gen_fields_tr' mark sfx u)
wenzelm@5197
   335
      | None => ([], tm))
wenzelm@5197
   336
  | gen_fields_tr' _ _ tm = ([], tm);
wenzelm@5197
   337
wenzelm@5197
   338
fun gen_record_tr' sep mark sfx is_unit record record_scheme tm =
wenzelm@4867
   339
  let
wenzelm@5197
   340
    val (ts, u) = gen_fields_tr' mark sfx tm;
wenzelm@5197
   341
    val t' = foldr1 (fn (v, w) => Syntax.const sep $ v $ w) ts;
wenzelm@4867
   342
  in
wenzelm@5197
   343
    if is_unit u then Syntax.const record $ t'
wenzelm@5197
   344
    else Syntax.const record_scheme $ t' $ u
wenzelm@4867
   345
  end;
wenzelm@4867
   346
wenzelm@5197
   347
wenzelm@5197
   348
val record_type_tr' =
wenzelm@5197
   349
  gen_record_tr' "_field_types" "_field_type" field_typeN
wenzelm@5197
   350
    (fn Const ("unit", _) => true | _ => false) "_record_type" "_record_type_scheme";
wenzelm@5197
   351
schirmer@14255
   352
schirmer@14255
   353
(* record_type_abbr_tr' tries to reconstruct the record name type abbreviation from *)
schirmer@14255
   354
(* the (nested) field types.                                                        *)
schirmer@14255
   355
fun record_type_abbr_tr' sg abbr alphas zeta lastF recT rec_schemeT tm =
schirmer@14255
   356
  let
schirmer@14255
   357
      (* tm is term representation of a (nested) field type. We first reconstruct the      *)
schirmer@14255
   358
      (* type from tm so that we can continue on the type level rather then the term level.*)
schirmer@14255
   359
 
schirmer@14255
   360
      fun get_sort xs n = (case assoc (xs,n) of 
schirmer@14255
   361
                             Some s => s 
schirmer@14255
   362
                           | None => Sign.defaultS sg);
schirmer@14255
   363
schirmer@14255
   364
      val T = Sign.intern_typ sg (Syntax.typ_of_term (get_sort (Syntax.raw_term_sorts tm)) I tm) 
schirmer@14255
   365
      val {tsig,...} = Sign.rep_sg sg
schirmer@14255
   366
schirmer@14255
   367
      fun mk_type_abbr subst name alphas = 
schirmer@14255
   368
          let val abbrT = Type (name, map (fn a => TVar ((a,0),logicS)) alphas);
schirmer@14255
   369
          in Syntax.term_of_typ (! Syntax.show_sorts) (Envir.norm_type subst abbrT) end;    
schirmer@14255
   370
schirmer@14255
   371
      fun unify rT T = fst (Type.unify tsig (Vartab.empty,0) (Type.varifyT rT,T))
schirmer@14255
   372
schirmer@14255
   373
   in if !print_record_type_abbr
schirmer@14255
   374
      then (case last_fieldT T of
schirmer@14255
   375
             Some (name,_) 
schirmer@14255
   376
              => if name = lastF 
schirmer@14255
   377
                 then
schirmer@14255
   378
		   let val subst = unify rec_schemeT T 
schirmer@14255
   379
                   in 
schirmer@14255
   380
                    if HOLogic.is_unitT (Envir.norm_type subst (TVar((zeta,0),Sign.defaultS sg)))
schirmer@14255
   381
                    then mk_type_abbr subst abbr alphas
schirmer@14255
   382
                    else mk_type_abbr subst (suffix schemeN abbr) (alphas@[zeta])
schirmer@14255
   383
		   end handle TUNIFY => record_type_tr' tm
schirmer@14255
   384
                 else raise Match (* give print translation of specialised record a chance *)
schirmer@14255
   385
            | _ => record_type_tr' tm)
schirmer@14255
   386
       else record_type_tr' tm
schirmer@14255
   387
  end
schirmer@14255
   388
schirmer@14255
   389
     
schirmer@14255
   390
fun gen_record_type_abbr_tr' sg abbr alphas zeta lastF recT rec_schemeT name =
schirmer@14255
   391
  let val name_sfx = suffix field_typeN name
schirmer@14255
   392
      val tr' = record_type_abbr_tr' sg abbr alphas zeta lastF recT rec_schemeT 
schirmer@14255
   393
  in (name_sfx, fn [t,u] => tr' (Syntax.const name_sfx $ t $ u) | _ => raise Match) end;
schirmer@14255
   394
      
wenzelm@5197
   395
val record_tr' =
wenzelm@11927
   396
  gen_record_tr' "_fields" "_field" fieldN
wenzelm@11927
   397
    (fn Const ("Unity", _) => true | _ => false) "_record" "_record_scheme";
wenzelm@5197
   398
wenzelm@5197
   399
fun record_update_tr' tm =
wenzelm@5197
   400
  let val (ts, u) = gen_fields_tr' "_update" updateN tm in
wenzelm@5197
   401
    Syntax.const "_record_update" $ u $
wenzelm@5197
   402
      foldr1 (fn (v, w) => Syntax.const "_updates" $ v $ w) (rev ts)
wenzelm@5197
   403
  end;
wenzelm@5197
   404
wenzelm@5201
   405
fun gen_field_tr' sfx tr' name =
wenzelm@5201
   406
  let val name_sfx = suffix sfx name
wenzelm@5201
   407
  in (name_sfx, fn [t, u] => tr' (Syntax.const name_sfx $ t $ u) | _ => raise Match) end;
wenzelm@5201
   408
wenzelm@5197
   409
fun print_translation names =
wenzelm@5197
   410
  map (gen_field_tr' fieldN record_tr') names @
wenzelm@5197
   411
  map (gen_field_tr' updateN record_update_tr') names;
wenzelm@4867
   412
schirmer@14255
   413
fun print_translation_field_types names =
schirmer@14255
   414
  map (gen_field_tr' field_typeN record_type_tr') names
schirmer@14255
   415
wenzelm@4867
   416
wenzelm@4867
   417
wenzelm@4867
   418
(*** extend theory by record definition ***)
wenzelm@4867
   419
wenzelm@4867
   420
(** record info **)
wenzelm@4867
   421
schirmer@14255
   422
(* type record_info and parent_info  *)
wenzelm@4867
   423
wenzelm@4867
   424
type record_info =
wenzelm@4867
   425
 {args: (string * sort) list,
wenzelm@4867
   426
  parent: (typ list * string) option,
wenzelm@4867
   427
  fields: (string * typ) list,
wenzelm@12247
   428
  field_inducts: thm list,
wenzelm@12247
   429
  field_cases: thm list,
schirmer@14255
   430
  field_splits: thm list,
wenzelm@12247
   431
  simps: thm list};
wenzelm@11927
   432
schirmer@14255
   433
fun make_record_info args parent fields field_inducts field_cases field_splits simps =
wenzelm@12247
   434
 {args = args, parent = parent, fields = fields, field_inducts = field_inducts,
schirmer@14255
   435
  field_cases = field_cases, field_splits = field_splits, simps = simps}: record_info;
wenzelm@4867
   436
wenzelm@4867
   437
type parent_info =
wenzelm@4867
   438
 {name: string,
wenzelm@4867
   439
  fields: (string * typ) list,
wenzelm@12247
   440
  field_inducts: thm list,
wenzelm@12247
   441
  field_cases: thm list,
schirmer@14255
   442
  field_splits: thm list,
wenzelm@12247
   443
  simps: thm list};
wenzelm@11927
   444
schirmer@14255
   445
fun make_parent_info name fields field_inducts field_cases field_splits simps =
wenzelm@12247
   446
 {name = name, fields = fields, field_inducts = field_inducts,
schirmer@14255
   447
  field_cases = field_cases, field_splits = field_splits, simps = simps}: parent_info;
wenzelm@4867
   448
wenzelm@4867
   449
wenzelm@5052
   450
(* data kind 'HOL/records' *)
wenzelm@5001
   451
wenzelm@7178
   452
type record_data =
wenzelm@7178
   453
 {records: record_info Symtab.table,
wenzelm@7178
   454
  sel_upd:
wenzelm@7178
   455
   {selectors: unit Symtab.table,
wenzelm@7178
   456
    updates: string Symtab.table,
wenzelm@7178
   457
    simpset: Simplifier.simpset},
wenzelm@7178
   458
  field_splits:
wenzelm@7178
   459
   {fields: unit Symtab.table,
berghofe@14079
   460
    simpset: Simplifier.simpset},
schirmer@14255
   461
  equalities: thm Symtab.table,
schirmer@14255
   462
  splits: (thm*thm*thm*thm) Symtab.table (* !!,!,EX - split-equalities,induct rule *) 
schirmer@14255
   463
};
wenzelm@7178
   464
schirmer@14255
   465
fun make_record_data records sel_upd field_splits equalities splits =
berghofe@14079
   466
 {records = records, sel_upd = sel_upd, field_splits = field_splits,
schirmer@14255
   467
  equalities = equalities, splits = splits}: record_data;
wenzelm@7178
   468
wenzelm@5006
   469
structure RecordsArgs =
wenzelm@5006
   470
struct
wenzelm@5006
   471
  val name = "HOL/records";
wenzelm@7178
   472
  type T = record_data;
wenzelm@4867
   473
wenzelm@7178
   474
  val empty =
wenzelm@7178
   475
    make_record_data Symtab.empty
wenzelm@7178
   476
      {selectors = Symtab.empty, updates = Symtab.empty, simpset = HOL_basic_ss}
schirmer@14255
   477
      {fields = Symtab.empty, simpset = HOL_basic_ss} Symtab.empty Symtab.empty;
wenzelm@7178
   478
wenzelm@6556
   479
  val copy = I;
wenzelm@5006
   480
  val prep_ext = I;
wenzelm@7178
   481
  fun merge
wenzelm@7178
   482
   ({records = recs1,
wenzelm@7178
   483
     sel_upd = {selectors = sels1, updates = upds1, simpset = ss1},
berghofe@14079
   484
     field_splits = {fields = flds1, simpset = fld_ss1},
schirmer@14255
   485
     equalities = equalities1,
schirmer@14255
   486
     splits = splits1},
wenzelm@7178
   487
    {records = recs2,
wenzelm@7178
   488
     sel_upd = {selectors = sels2, updates = upds2, simpset = ss2},
berghofe@14079
   489
     field_splits = {fields = flds2, simpset = fld_ss2},
schirmer@14255
   490
     equalities = equalities2, 
schirmer@14255
   491
     splits = splits2}) =
schirmer@14255
   492
    make_record_data  
wenzelm@7178
   493
      (Symtab.merge (K true) (recs1, recs2))
wenzelm@7178
   494
      {selectors = Symtab.merge (K true) (sels1, sels2),
wenzelm@7178
   495
        updates = Symtab.merge (K true) (upds1, upds2),
wenzelm@7178
   496
        simpset = Simplifier.merge_ss (ss1, ss2)}
wenzelm@7178
   497
      {fields = Symtab.merge (K true) (flds1, flds2),
berghofe@14079
   498
        simpset = Simplifier.merge_ss (fld_ss1, fld_ss2)}
schirmer@14255
   499
      (Symtab.merge Thm.eq_thm (equalities1, equalities2))
schirmer@14255
   500
      (Symtab.merge (fn ((a,b,c,d),(w,x,y,z)) 
schirmer@14255
   501
                     => Thm.eq_thm (a,w) andalso Thm.eq_thm (b,x) andalso 
schirmer@14255
   502
                        Thm.eq_thm (c,y) andalso Thm.eq_thm (d,z)) 
schirmer@14255
   503
                    (splits1, splits2));
wenzelm@4867
   504
wenzelm@7178
   505
  fun print sg ({records = recs, ...}: record_data) =
wenzelm@4867
   506
    let
wenzelm@4867
   507
      val prt_typ = Sign.pretty_typ sg;
wenzelm@4867
   508
wenzelm@4867
   509
      fun pretty_parent None = []
wenzelm@4867
   510
        | pretty_parent (Some (Ts, name)) =
wenzelm@4867
   511
            [Pretty.block [prt_typ (Type (name, Ts)), Pretty.str " +"]];
wenzelm@4867
   512
wenzelm@4867
   513
      fun pretty_field (c, T) = Pretty.block
wenzelm@12129
   514
        [Pretty.str (Sign.cond_extern sg Sign.constK c), Pretty.str " ::",
wenzelm@12129
   515
          Pretty.brk 1, Pretty.quote (prt_typ T)];
wenzelm@4867
   516
wenzelm@12247
   517
      fun pretty_record (name, {args, parent, fields, ...}: record_info) =
wenzelm@11927
   518
        Pretty.block (Pretty.fbreaks (Pretty.block
wenzelm@11927
   519
          [prt_typ (Type (name, map TFree args)), Pretty.str " = "] ::
wenzelm@4867
   520
          pretty_parent parent @ map pretty_field fields));
wenzelm@12129
   521
    in map pretty_record (Symtab.dest recs) |> Pretty.chunks |> Pretty.writeln end;
wenzelm@4867
   522
end;
wenzelm@4867
   523
wenzelm@5006
   524
structure RecordsData = TheoryDataFun(RecordsArgs);
wenzelm@5006
   525
val print_records = RecordsData.print;
wenzelm@5006
   526
wenzelm@4867
   527
wenzelm@7178
   528
(* access 'records' *)
wenzelm@4867
   529
wenzelm@7178
   530
fun get_record thy name = Symtab.lookup (#records (RecordsData.get thy), name);
wenzelm@4867
   531
wenzelm@4890
   532
fun put_record name info thy =
wenzelm@7178
   533
  let
schirmer@14255
   534
    val {records, sel_upd, field_splits, equalities, splits} = RecordsData.get thy;
berghofe@14079
   535
    val data = make_record_data (Symtab.update ((name, info), records))
schirmer@14255
   536
      sel_upd field_splits equalities splits;
wenzelm@7178
   537
  in RecordsData.put data thy end;
wenzelm@7178
   538
wenzelm@7178
   539
wenzelm@7178
   540
(* access 'sel_upd' *)
wenzelm@7178
   541
wenzelm@7178
   542
fun get_sel_upd sg = #sel_upd (RecordsData.get_sg sg);
wenzelm@7178
   543
wenzelm@7178
   544
fun get_selectors sg name = Symtab.lookup (#selectors (get_sel_upd sg), name);
wenzelm@7178
   545
fun get_updates sg name = Symtab.lookup (#updates (get_sel_upd sg), name);
wenzelm@7178
   546
fun get_simpset sg = #simpset (get_sel_upd sg);
wenzelm@7178
   547
wenzelm@7178
   548
fun put_sel_upd names simps thy =
wenzelm@7178
   549
  let
wenzelm@7178
   550
    val sels = map (rpair ()) names;
wenzelm@7178
   551
    val upds = map (suffix updateN) names ~~ names;
wenzelm@7178
   552
berghofe@14079
   553
    val {records, sel_upd = {selectors, updates, simpset}, field_splits,
schirmer@14255
   554
      equalities, splits} = RecordsData.get thy;
wenzelm@7178
   555
    val data = make_record_data records
wenzelm@7178
   556
      {selectors = Symtab.extend (selectors, sels),
wenzelm@7178
   557
        updates = Symtab.extend (updates, upds),
wenzelm@7178
   558
        simpset = Simplifier.addsimps (simpset, simps)}
schirmer@14255
   559
      field_splits equalities splits;
wenzelm@7178
   560
  in RecordsData.put data thy end;
wenzelm@7178
   561
wenzelm@7178
   562
wenzelm@7178
   563
(* access 'field_splits' *)
wenzelm@5698
   564
schirmer@14255
   565
fun add_field_splits names simps thy =
wenzelm@5698
   566
  let
berghofe@14079
   567
    val {records, sel_upd, field_splits = {fields, simpset},
schirmer@14255
   568
      equalities, splits} = RecordsData.get thy;
berghofe@14079
   569
    val flds = map (rpair ()) names;
wenzelm@7178
   570
    val data = make_record_data records sel_upd
berghofe@14079
   571
      {fields = Symtab.extend (fields, flds),
schirmer@14255
   572
       simpset = Simplifier.addsimps (simpset, simps)} equalities splits;
wenzelm@7178
   573
  in RecordsData.put data thy end;
wenzelm@4867
   574
wenzelm@4867
   575
berghofe@14079
   576
(* access 'equalities' *)
berghofe@14079
   577
berghofe@14079
   578
fun add_record_equalities name thm thy =
berghofe@14079
   579
  let
schirmer@14255
   580
    val {records, sel_upd, field_splits, equalities, splits} = RecordsData.get thy;
berghofe@14079
   581
    val data = make_record_data records sel_upd field_splits
schirmer@14255
   582
      (Symtab.update_new ((name, thm), equalities)) splits;
berghofe@14079
   583
  in RecordsData.put data thy end;
berghofe@14079
   584
berghofe@14079
   585
fun get_equalities sg name =
berghofe@14079
   586
  Symtab.lookup (#equalities (RecordsData.get_sg sg), name);
berghofe@14079
   587
schirmer@14255
   588
(* access 'splits' *)
schirmer@14255
   589
schirmer@14255
   590
fun add_record_splits name thmP thy =
schirmer@14255
   591
  let
schirmer@14255
   592
    val {records, sel_upd, field_splits, equalities, splits} = RecordsData.get thy;
schirmer@14255
   593
    val data = make_record_data records sel_upd field_splits
schirmer@14255
   594
      equalities (Symtab.update_new ((name, thmP), splits));
schirmer@14255
   595
  in RecordsData.put data thy end;
schirmer@14255
   596
schirmer@14255
   597
fun get_splits sg name =
schirmer@14255
   598
  Symtab.lookup (#splits (RecordsData.get_sg sg), name);
schirmer@14255
   599
berghofe@14079
   600
wenzelm@4867
   601
(* parent records *)
wenzelm@4867
   602
wenzelm@12247
   603
fun add_parents thy None parents = parents
wenzelm@12247
   604
  | add_parents thy (Some (types, name)) parents =
wenzelm@12247
   605
      let
wenzelm@12247
   606
        val sign = Theory.sign_of thy;
wenzelm@12247
   607
        fun err msg = error (msg ^ " parent record " ^ quote name);
wenzelm@12255
   608
schirmer@14255
   609
        val {args, parent, fields, field_inducts, field_cases, field_splits, simps} =
wenzelm@12247
   610
          (case get_record thy name of Some info => info | None => err "Unknown");
wenzelm@12247
   611
        val _ = if length types <> length args then err "Bad number of arguments for" else ();
wenzelm@12255
   612
wenzelm@12247
   613
        fun bad_inst ((x, S), T) =
wenzelm@12247
   614
          if Sign.of_sort sign (T, S) then None else Some x
wenzelm@12247
   615
        val bads = mapfilter bad_inst (args ~~ types);
wenzelm@12255
   616
wenzelm@12247
   617
        val inst = map fst args ~~ types;
wenzelm@12247
   618
        val subst = Term.map_type_tfree (fn (x, _) => the (assoc (inst, x)));
wenzelm@12247
   619
        val parent' = apsome (apfst (map subst)) parent;
wenzelm@12247
   620
        val fields' = map (apsnd subst) fields;
wenzelm@12247
   621
      in
wenzelm@12255
   622
        conditional (not (null bads)) (fn () =>
wenzelm@12255
   623
          err ("Ill-sorted instantiation of " ^ commas bads ^ " in"));
wenzelm@12255
   624
        add_parents thy parent'
schirmer@14255
   625
          (make_parent_info name fields' field_inducts field_cases field_splits simps::parents)
wenzelm@12247
   626
      end;
wenzelm@4867
   627
wenzelm@4867
   628
schirmer@14255
   629
(** record simprocs **)
schirmer@14255
   630
 
schirmer@14255
   631
fun quick_and_dirty_prove sg xs asms prop tac =
schirmer@14255
   632
Tactic.prove sg xs asms prop
schirmer@14255
   633
    (if ! quick_and_dirty then (K (SkipProof.cheat_tac HOL.thy)) else tac);
wenzelm@4867
   634
schirmer@14255
   635
schirmer@14255
   636
fun prove_split_simp sg T prop =
schirmer@14255
   637
    (case last_fieldT T of
schirmer@14255
   638
      Some (name,_) => (case get_splits sg name of
schirmer@14255
   639
                         Some (all_thm,_,_,_) 
schirmer@14255
   640
                          => let val {sel_upd={simpset,...},...} = RecordsData.get_sg sg;
schirmer@14255
   641
                             in (quick_and_dirty_prove sg [] [] prop 
schirmer@14255
   642
                                  (K (simp_tac (simpset addsimps [all_thm]) 1)))
schirmer@14255
   643
                             end
schirmer@14255
   644
                      | _ => error "RecordPackage.prove_split_simp: code should never been reached")
schirmer@14255
   645
     | _ => error "RecordPackage.prove_split_simp: code should never been reached")
schirmer@14255
   646
wenzelm@7178
   647
schirmer@14255
   648
(* record_simproc *)
schirmer@14255
   649
(* Simplifies selections of an record update:
schirmer@14255
   650
 *  (1)  S (r(|S:=k|)) = k respectively
schirmer@14255
   651
 *  (2)  S (r(|X:=k|)) = S r
schirmer@14255
   652
 * The simproc skips multiple updates at once, eg:
schirmer@14255
   653
 *  S (r (|S:=k,X:=2,Y:=3|)) = k
schirmer@14255
   654
 * But be careful in (2) because of the extendibility of records.
schirmer@14255
   655
 * - If S is a more-selector we have to make sure that the update on component
schirmer@14255
   656
 *   X does not affect the selected subrecord.
schirmer@14255
   657
 * - If X is a more-selector we have to make sure that S is not in the updated
schirmer@14255
   658
 *   subrecord. 
schirmer@14255
   659
 *)
wenzelm@13462
   660
val record_simproc =
wenzelm@13462
   661
  Simplifier.simproc (Theory.sign_of HOL.thy) "record_simp" ["s (u k r)"]
wenzelm@13462
   662
    (fn sg => fn _ => fn t =>
schirmer@14255
   663
      (case t of (sel as Const (s, Type (_,[domS,rangeS]))) $ ((upd as Const (u, _)) $ k $ r) =>
wenzelm@13462
   664
        (case get_selectors sg s of Some () =>
wenzelm@13462
   665
          (case get_updates sg u of Some u_name =>
wenzelm@13462
   666
            let
schirmer@14255
   667
              fun mk_abs_var x t = (x, fastype_of t);
schirmer@14255
   668
              val {sel_upd={updates,...},...} = RecordsData.get_sg sg;
schirmer@14255
   669
schirmer@14255
   670
              fun mk_eq_terms ((upd as Const (u,Type(_,[updT,_]))) $ k $ r) =
schirmer@14255
   671
		  (case (Symtab.lookup (updates,u)) of
schirmer@14255
   672
                     None => None
schirmer@14255
   673
                   | Some u_name 
schirmer@14255
   674
                     => if u_name = s
schirmer@14255
   675
                        then let 
schirmer@14255
   676
                               val rv = mk_abs_var "r" r
schirmer@14255
   677
                               val rb = Bound 0
schirmer@14255
   678
                               val kv = mk_abs_var "k" k
schirmer@14255
   679
                               val kb = Bound 1 
schirmer@14255
   680
                             in Some (upd$kb$rb,kb,[kv,rv],true) end
schirmer@14255
   681
                        else if u_name mem (map fst (dest_fieldTs rangeS))
schirmer@14255
   682
                             orelse s mem (map fst (dest_fieldTs updT))
schirmer@14255
   683
                             then None
schirmer@14255
   684
			     else (case mk_eq_terms r of 
schirmer@14255
   685
                                     Some (trm,trm',vars,update_s) 
schirmer@14255
   686
                                     => let   
schirmer@14255
   687
					  val kv = mk_abs_var "k" k
schirmer@14255
   688
                                          val kb = Bound (length vars)
schirmer@14255
   689
		                        in Some (upd$kb$trm,trm',kv::vars,update_s) end
schirmer@14255
   690
                                   | None
schirmer@14255
   691
                                     => let 
schirmer@14255
   692
					  val rv = mk_abs_var "r" r
schirmer@14255
   693
                                          val rb = Bound 0
schirmer@14255
   694
                                          val kv = mk_abs_var "k" k
schirmer@14255
   695
                                          val kb = Bound 1 
schirmer@14255
   696
                                        in Some (upd$kb$rb,rb,[kv,rv],false) end))
schirmer@14255
   697
                | mk_eq_terms r = None     
wenzelm@13462
   698
            in
schirmer@14255
   699
	      (case mk_eq_terms (upd$k$r) of
schirmer@14255
   700
                 Some (trm,trm',vars,update_s) 
schirmer@14255
   701
                 => if update_s 
schirmer@14255
   702
		    then Some (prove_split_simp sg domS 
schirmer@14255
   703
                                 (list_all(vars,(Logic.mk_equals (sel$trm,trm')))))
schirmer@14255
   704
                    else Some (prove_split_simp sg domS 
schirmer@14255
   705
                                 (list_all(vars,(Logic.mk_equals (sel$trm,sel$trm')))))
schirmer@14255
   706
               | None => None)
wenzelm@13462
   707
            end
wenzelm@13462
   708
          | None => None)
wenzelm@13462
   709
        | None => None)
wenzelm@13462
   710
      | _ => None));
wenzelm@7178
   711
schirmer@14255
   712
(* record_eq_simproc *)
schirmer@14255
   713
(* looks up the most specific record-equality.
schirmer@14255
   714
 * Note on efficiency:
schirmer@14255
   715
 * Testing equality of records boils down to the test of equality of all components.
schirmer@14255
   716
 * Therefore the complexity is: #components * complexity for single component.
schirmer@14255
   717
 * Especially if a record has a lot of components it may be better to split up
schirmer@14255
   718
 * the record first and do simplification on that (record_split_simp_tac).
schirmer@14255
   719
 * e.g. r(|lots of updates|) = x
schirmer@14255
   720
 *
schirmer@14255
   721
 *               record_eq_simproc           record_split_simp_tac
schirmer@14255
   722
 * Complexity: #components * #updates     #updates   
schirmer@14255
   723
 *           
schirmer@14255
   724
 *)
berghofe@14079
   725
val record_eq_simproc =
berghofe@14079
   726
  Simplifier.simproc (Theory.sign_of HOL.thy) "record_eq_simp" ["r = s"]
berghofe@14079
   727
    (fn sg => fn _ => fn t =>
berghofe@14079
   728
      (case t of Const ("op =", Type (_, [T, _])) $ _ $ _ =>
schirmer@14255
   729
        (case last_fieldT T of
schirmer@14255
   730
           None => None
schirmer@14255
   731
         | Some (name, _) => (case get_equalities sg name of
schirmer@14255
   732
                                None => None
schirmer@14255
   733
                              | Some thm => Some (thm RS Eq_TrueI)))
berghofe@14079
   734
       | _ => None));
berghofe@14079
   735
wenzelm@7178
   736
schirmer@14255
   737
(* record_upd_simproc *)
schirmer@14255
   738
(* simplify multiple updates; for example: "r(|M:=3,N:=1,M:=2,N:=4|) == r(|M:=2,N:=4|)" *)
schirmer@14255
   739
val record_upd_simproc =
schirmer@14255
   740
  Simplifier.simproc (Theory.sign_of HOL.thy) "record_upd_simp" ["(u1 k1 (u2 k2 r))"]
schirmer@14255
   741
    (fn sg => fn _ => fn t =>
schirmer@14255
   742
      (case t of ((upd as Const (u, Type(_,[_,Type(_,[T,_])]))) $ k $ r) =>
schirmer@14255
   743
 	 let val {sel_upd={updates,...},...} = RecordsData.get_sg sg;
schirmer@14255
   744
	     fun mk_abs_var x t = (x, fastype_of t);
schirmer@14255
   745
schirmer@14255
   746
             fun mk_updterm upds already ((upd as Const (u,_)) $ k $ r) =
schirmer@14255
   747
		 if is_some (Symtab.lookup (upds,u))
schirmer@14255
   748
		 then let 
schirmer@14255
   749
			 fun rest already = mk_updterm upds already
schirmer@14255
   750
		      in if is_some (Symtab.lookup (already,u)) 
schirmer@14255
   751
			 then (case (rest already r) of
schirmer@14255
   752
				 None => let 
schirmer@14255
   753
				           val rv = mk_abs_var "r" r
schirmer@14255
   754
                                           val rb = Bound 0
schirmer@14255
   755
					   val kv = mk_abs_var "k" k
schirmer@14255
   756
                                           val kb = Bound 1	      
schirmer@14255
   757
                                         in Some (upd$kb$rb,rb,[kv,rv]) end
schirmer@14255
   758
                               | Some (trm,trm',vars) 
schirmer@14255
   759
				 => let 
schirmer@14255
   760
				     val kv = mk_abs_var "k" k
schirmer@14255
   761
                                     val kb = Bound (length vars)
schirmer@14255
   762
                                    in Some (upd$kb$trm,trm',kv::vars) end)
schirmer@14255
   763
	                 else (case rest (Symtab.update ((u,()),already)) r of 
schirmer@14255
   764
				 None => None
schirmer@14255
   765
		               | Some (trm,trm',vars) 
schirmer@14255
   766
                                  => let
schirmer@14255
   767
				      val kv = mk_abs_var "k" k
schirmer@14255
   768
                                      val kb = Bound (length vars)
schirmer@14255
   769
                                     in Some (upd$kb$trm,upd$kb$trm',kv::vars) end)
schirmer@14255
   770
		     end
schirmer@14255
   771
		 else None
schirmer@14255
   772
	       | mk_updterm _ _ _ = None;
schirmer@14255
   773
schirmer@14255
   774
	 in (case mk_updterm updates Symtab.empty t of
schirmer@14255
   775
	       Some (trm,trm',vars)
schirmer@14255
   776
                => Some (prove_split_simp sg T (list_all(vars,(Logic.mk_equals (trm,trm')))))
schirmer@14255
   777
             | None => None)
schirmer@14255
   778
	 end
schirmer@14255
   779
       | _ => None));
schirmer@14255
   780
schirmer@14255
   781
(* record_split_simproc *)
schirmer@14255
   782
(* splits quantified occurrences of records, for which P holds. P can peek on the 
schirmer@14255
   783
 * subterm starting at the quantified occurrence of the record (including the quantifier)
schirmer@14255
   784
 *)
schirmer@14255
   785
fun record_split_simproc P =
schirmer@14255
   786
  Simplifier.simproc (Theory.sign_of HOL.thy) "record_split_simp" ["(a t)"]
schirmer@14255
   787
    (fn sg => fn _ => fn t =>
schirmer@14255
   788
      (case t of (Const (quantifier, Type (_, [Type (_, [T, _]), _])))$trm =>
schirmer@14255
   789
         if quantifier = "All" orelse quantifier = "all" orelse quantifier = "Ex"
schirmer@14255
   790
         then (case last_fieldT T of
schirmer@14255
   791
                 None => None
schirmer@14255
   792
               | Some (name, _)
schirmer@14255
   793
                  => if P t 
schirmer@14255
   794
                     then (case get_splits sg name of
schirmer@14255
   795
                             None => None
schirmer@14255
   796
                           | Some (all_thm, All_thm, Ex_thm,_) 
schirmer@14255
   797
                              => Some (case quantifier of
schirmer@14255
   798
                                         "all" => all_thm
schirmer@14255
   799
                                       | "All" => All_thm RS HOL.eq_reflection
schirmer@14255
   800
                                       | "Ex"  => Ex_thm RS HOL.eq_reflection
schirmer@14255
   801
                                       | _     => error "record_split_simproc"))
schirmer@14255
   802
                     else None)
schirmer@14255
   803
         else None
schirmer@14255
   804
       | _ => None))
wenzelm@7178
   805
wenzelm@5698
   806
(** record field splitting **)
wenzelm@5698
   807
wenzelm@6358
   808
(* tactic *)
wenzelm@6358
   809
schirmer@14255
   810
fun is_fieldT fields (Type (a, [_, _])) = is_some (Symtab.lookup (fields, a))
schirmer@14255
   811
  | is_fieldT _ _ = false;
schirmer@14255
   812
wenzelm@5698
   813
fun record_split_tac i st =
wenzelm@5698
   814
  let
wenzelm@7178
   815
    val {field_splits = {fields, simpset}, ...} = RecordsData.get_sg (Thm.sign_of_thm st);
wenzelm@5698
   816
berghofe@14079
   817
    val has_field = exists_Const
berghofe@14079
   818
      (fn (s, Type (_, [Type (_, [T, _]), _])) =>
schirmer@14255
   819
          (s = "all" orelse s = "All") andalso is_fieldT fields T
berghofe@14079
   820
        | _ => false);
berghofe@14079
   821
berghofe@14079
   822
    val goal = Library.nth_elem (i - 1, Thm.prems_of st);
wenzelm@5698
   823
  in
berghofe@14079
   824
    if has_field goal then Simplifier.full_simp_tac simpset i st
wenzelm@5698
   825
    else Seq.empty
wenzelm@5698
   826
  end handle Library.LIST _ => Seq.empty;
wenzelm@5698
   827
wenzelm@6358
   828
schirmer@14255
   829
local
schirmer@14255
   830
val inductive_atomize = thms "induct_atomize";
schirmer@14255
   831
val inductive_rulify1 = thms "induct_rulify1";
schirmer@14255
   832
in
schirmer@14255
   833
(* record_split_simp_tac *)
schirmer@14255
   834
(* splits (and simplifies) all records in the goal for which P holds. 
schirmer@14255
   835
 * For quantified occurrences of a record
schirmer@14255
   836
 * P can peek on the whole subterm (including the quantifier); for free variables P
schirmer@14255
   837
 * can only peek on the variable itself. 
schirmer@14255
   838
 *)
schirmer@14255
   839
fun record_split_simp_tac P i st =
schirmer@14255
   840
  let
schirmer@14255
   841
    val sg = Thm.sign_of_thm st;
schirmer@14255
   842
    val {sel_upd={simpset,...},field_splits={fields,...},...} 
schirmer@14255
   843
            = RecordsData.get_sg sg;
schirmer@14255
   844
schirmer@14255
   845
    val has_field = exists_Const
schirmer@14255
   846
      (fn (s, Type (_, [Type (_, [T, _]), _])) =>
schirmer@14255
   847
          (s = "all" orelse s = "All" orelse s = "Ex") andalso is_fieldT fields T
schirmer@14255
   848
        | _ => false);
schirmer@14255
   849
schirmer@14255
   850
    val goal = Library.nth_elem (i - 1, Thm.prems_of st);
schirmer@14255
   851
    val frees = filter (is_fieldT fields o type_of) (term_frees goal);
schirmer@14255
   852
schirmer@14255
   853
    fun mk_split_free_tac free induct_thm i = 
schirmer@14255
   854
	let val cfree = cterm_of sg free;
schirmer@14255
   855
            val (_$(_$r)) = concl_of induct_thm;
schirmer@14255
   856
            val crec = cterm_of sg r;
schirmer@14255
   857
            val thm  = cterm_instantiate [(crec,cfree)] induct_thm;
schirmer@14255
   858
        in EVERY [simp_tac (HOL_basic_ss addsimps inductive_atomize) i,
schirmer@14255
   859
                  rtac thm i,
schirmer@14255
   860
                  simp_tac (HOL_basic_ss addsimps inductive_rulify1) i]
schirmer@14255
   861
	end;
schirmer@14255
   862
schirmer@14255
   863
    fun split_free_tac P i (free as Free (n,T)) = 
schirmer@14255
   864
	(case last_fieldT T of
schirmer@14255
   865
           None => None
schirmer@14255
   866
         | Some(name,_)=> if P free 
schirmer@14255
   867
                          then (case get_splits sg name of
schirmer@14255
   868
                                  None => None
schirmer@14255
   869
                                | Some (_,_,_,induct_thm)
schirmer@14255
   870
                                   => Some (mk_split_free_tac free induct_thm i))
schirmer@14255
   871
                          else None)
schirmer@14255
   872
     | split_free_tac _ _ _ = None;
schirmer@14255
   873
schirmer@14255
   874
    val split_frees_tacs = mapfilter (split_free_tac P i) frees;
schirmer@14255
   875
   
schirmer@14255
   876
    val simprocs = if has_field goal then [record_split_simproc P] else [];
schirmer@14255
   877
   
schirmer@14255
   878
  in st |> (EVERY split_frees_tacs) 
schirmer@14255
   879
           THEN (Simplifier.full_simp_tac (simpset addsimprocs simprocs) i)
schirmer@14255
   880
  end handle Library.LIST _ => Seq.empty;
schirmer@14255
   881
end;
schirmer@14255
   882
wenzelm@6358
   883
(* wrapper *)
wenzelm@6358
   884
wenzelm@5707
   885
val record_split_name = "record_split_tac";
wenzelm@5707
   886
val record_split_wrapper = (record_split_name, fn tac => record_split_tac ORELSE' tac);
wenzelm@5698
   887
wenzelm@5698
   888
wenzelm@6358
   889
(* method *)
wenzelm@6358
   890
wenzelm@6358
   891
val record_split_method =
wenzelm@9705
   892
  ("record_split", Method.no_args (Method.SIMPLE_METHOD' HEADGOAL record_split_tac),
wenzelm@6358
   893
    "split record fields");
wenzelm@6358
   894
wenzelm@6358
   895
wenzelm@12255
   896
wenzelm@4890
   897
(** internal theory extenders **)
wenzelm@4867
   898
wenzelm@11832
   899
(* field_typedefs *)
wenzelm@5698
   900
wenzelm@11832
   901
fun field_typedefs zeta moreT names theory =
wenzelm@5698
   902
  let
wenzelm@11832
   903
    val alpha = "'a";
wenzelm@12338
   904
    val aT = TFree (alpha, HOLogic.typeS);
wenzelm@11832
   905
    val UNIV = HOLogic.mk_UNIV (HOLogic.mk_prodT (aT, moreT));
wenzelm@5698
   906
wenzelm@11832
   907
    fun type_def (thy, name) =
wenzelm@11940
   908
      let val (thy', {type_definition, set_def = Some def, ...}) =
wenzelm@11940
   909
        thy |> setmp TypedefPackage.quiet_mode true
wenzelm@11832
   910
          (TypedefPackage.add_typedef_i true None
wenzelm@11832
   911
            (suffix field_typeN (Sign.base_name name), [alpha, zeta], Syntax.NoSyn) UNIV None
wenzelm@11832
   912
          (Tactic.rtac UNIV_witness 1))
wenzelm@11832
   913
      in (thy', Tactic.rewrite_rule [def] type_definition) end
wenzelm@11832
   914
  in foldl_map type_def (theory, names) end;
wenzelm@5698
   915
wenzelm@5698
   916
wenzelm@4894
   917
(* field_definitions *)
wenzelm@4867
   918
wenzelm@11832
   919
fun field_definitions fields names xs alphas zeta moreT more vars named_vars thy =
wenzelm@4890
   920
  let
wenzelm@5698
   921
    val sign = Theory.sign_of thy;
wenzelm@4890
   922
    val base = Sign.base_name;
wenzelm@4867
   923
wenzelm@12338
   924
    val xT = TFree (variant alphas "'x", HOLogic.typeS);
wenzelm@11832
   925
wenzelm@4867
   926
wenzelm@4890
   927
    (* prepare declarations and definitions *)
wenzelm@4867
   928
wenzelm@5698
   929
    (*field constructors*)
wenzelm@4890
   930
    val field_decls = map (mk_fieldC moreT) fields;
wenzelm@4890
   931
wenzelm@11832
   932
    fun mk_field_spec ((c, T), v) =
wenzelm@11832
   933
      Term.head_of (mk_field ((c, v), more)) :==
wenzelm@11832
   934
        lambda v (lambda more (mk_Abs moreT (c, T) $ (HOLogic.mk_prod (v, more))));
wenzelm@11832
   935
    val field_specs = map mk_field_spec (fields ~~ vars);
wenzelm@4890
   936
wenzelm@4890
   937
    (*field destructors*)
wenzelm@5698
   938
    val dest_decls = map (mk_fstC moreT) fields @ map (mk_sndC moreT) fields;
wenzelm@5698
   939
wenzelm@11832
   940
    fun mk_dest_spec dest sel (c, T) =
wenzelm@5698
   941
      let val p = Free ("p", mk_fieldT ((c, T), moreT));
wenzelm@11832
   942
      in Term.head_of (dest p) :== lambda p (sel (mk_Rep moreT (c, T) $ p)) end;
wenzelm@11832
   943
    val dest_specs1 = map (mk_dest_spec mk_fst HOLogic.mk_fst) fields;
wenzelm@11832
   944
    val dest_specs2 = map (mk_dest_spec mk_snd HOLogic.mk_snd) fields;
wenzelm@4890
   945
wenzelm@4890
   946
wenzelm@11832
   947
    (* 1st stage: defs_thy *)
wenzelm@5713
   948
wenzelm@11832
   949
    val (defs_thy, (((typedefs, field_defs), dest_defs1), dest_defs2)) =
wenzelm@11832
   950
      thy
wenzelm@11832
   951
      |> field_typedefs zeta moreT names
wenzelm@11832
   952
      |>> (Theory.add_consts_i o map (Syntax.no_syn o apfst base)) (field_decls @ dest_decls)
wenzelm@11832
   953
      |>>> (PureThy.add_defs_i false o map Thm.no_attributes) field_specs
wenzelm@11832
   954
      |>>> (PureThy.add_defs_i false o map Thm.no_attributes) dest_specs1
wenzelm@11832
   955
      |>>> (PureThy.add_defs_i false o map Thm.no_attributes) dest_specs2;
wenzelm@4890
   956
wenzelm@13419
   957
    val prod_types = map (fn (((a, b), c), d) => product_type_intro OF [a, b, c, d])
wenzelm@11832
   958
      (typedefs ~~ field_defs ~~ dest_defs1 ~~ dest_defs2);
wenzelm@4890
   959
wenzelm@5698
   960
wenzelm@11832
   961
    (* 2nd stage: thms_thy *)
wenzelm@5698
   962
berghofe@14079
   963
    fun make ren th = map (fn (prod_type, field) => Drule.standard
berghofe@14079
   964
      (Drule.rename_bvars (ren ~~ [base (fst field), moreN] handle LIST _ => [])
berghofe@14079
   965
        (th OF [prod_type]))) (prod_types ~~ fields);
wenzelm@4890
   966
berghofe@14079
   967
    val dest_convs = make [] product_type_conv1 @ make [] product_type_conv2;
berghofe@14079
   968
    val field_injects = make [] product_type_inject;
berghofe@14079
   969
    val field_inducts = make ["x", "y"] product_type_induct;
berghofe@14079
   970
    val field_cases = make ["x", "y"] product_type_cases;
berghofe@14079
   971
    val field_splits = make ["a", "b"] product_type_split_paired_all @
berghofe@14079
   972
      make ["a", "b"] product_type_split_paired_All;
wenzelm@4894
   973
wenzelm@11940
   974
    val (thms_thy, [field_defs', dest_defs', dest_convs', field_injects',
wenzelm@11940
   975
        field_splits', field_inducts', field_cases']) = defs_thy
berghofe@12449
   976
      |> Codegen.assoc_consts_i (flat (map (fn (s, _) =>
berghofe@12449
   977
           [(suffix fieldN s, None, prod_code),
berghofe@12449
   978
            (suffix fstN s, None, fst_code),
berghofe@12449
   979
            (suffix sndN s, None, snd_code)]) fields))
berghofe@12449
   980
      |> Codegen.assoc_types (map (fn (s, _) =>
berghofe@12449
   981
           (suffix field_typeN s, prodT_code)) fields)
wenzelm@11927
   982
      |> (PureThy.add_thmss o map Thm.no_attributes)
wenzelm@11940
   983
       [("field_defs", field_defs),
wenzelm@11940
   984
        ("dest_defs", dest_defs1 @ dest_defs2),
wenzelm@11940
   985
        ("dest_convs", dest_convs),
wenzelm@11940
   986
        ("field_injects", field_injects),
wenzelm@11940
   987
        ("field_splits", field_splits),
wenzelm@11940
   988
        ("field_inducts", field_inducts),
wenzelm@11940
   989
        ("field_cases", field_cases)];
wenzelm@4890
   990
wenzelm@11940
   991
  in (thms_thy, dest_convs', field_injects', field_splits', field_inducts', field_cases') end;
wenzelm@4890
   992
wenzelm@4890
   993
wenzelm@4890
   994
(* record_definition *)
wenzelm@4867
   995
wenzelm@12506
   996
fun record_definition (args, bname) parent (parents: parent_info list) raw_fields thy =
wenzelm@4867
   997
  let
wenzelm@4867
   998
    val sign = Theory.sign_of thy;
wenzelm@12247
   999
wenzelm@12247
  1000
    val alphas = map fst args;
wenzelm@12247
  1001
    val name = Sign.full_name sign bname;
wenzelm@4867
  1002
    val full = Sign.full_name_path sign bname;
wenzelm@4890
  1003
    val base = Sign.base_name;
wenzelm@4867
  1004
wenzelm@12506
  1005
    val (bfields, field_syntax) = split_list (map (fn (x, T, mx) => ((x, T), mx)) raw_fields);
wenzelm@12506
  1006
wenzelm@4867
  1007
wenzelm@4890
  1008
    (* basic components *)
wenzelm@4867
  1009
wenzelm@12247
  1010
    val ancestry = map (length o flat o map #fields) (Library.prefixes1 parents);
wenzelm@11927
  1011
wenzelm@4867
  1012
    val parent_fields = flat (map #fields parents);
wenzelm@4890
  1013
    val parent_names = map fst parent_fields;
wenzelm@4890
  1014
    val parent_types = map snd parent_fields;
wenzelm@4890
  1015
    val parent_len = length parent_fields;
wenzelm@11927
  1016
    val parent_xs = variantlist (map (base o fst) parent_fields, [moreN, rN]);
wenzelm@4890
  1017
    val parent_vars = ListPair.map Free (parent_xs, parent_types);
wenzelm@4894
  1018
    val parent_named_vars = parent_names ~~ parent_vars;
wenzelm@4890
  1019
wenzelm@4867
  1020
    val fields = map (apfst full) bfields;
wenzelm@4890
  1021
    val names = map fst fields;
wenzelm@4890
  1022
    val types = map snd fields;
wenzelm@4890
  1023
    val len = length fields;
wenzelm@11927
  1024
    val xs = variantlist (map fst bfields, moreN :: rN :: parent_xs);
wenzelm@4890
  1025
    val vars = ListPair.map Free (xs, types);
wenzelm@4894
  1026
    val named_vars = names ~~ vars;
wenzelm@4867
  1027
wenzelm@4867
  1028
    val all_fields = parent_fields @ fields;
wenzelm@4890
  1029
    val all_names = parent_names @ names;
wenzelm@4890
  1030
    val all_types = parent_types @ types;
wenzelm@4890
  1031
    val all_len = parent_len + len;
wenzelm@4890
  1032
    val all_xs = parent_xs @ xs;
wenzelm@4890
  1033
    val all_vars = parent_vars @ vars;
wenzelm@4894
  1034
    val all_named_vars = parent_named_vars @ named_vars;
wenzelm@4867
  1035
wenzelm@4867
  1036
    val zeta = variant alphas "'z";
wenzelm@12338
  1037
    val moreT = TFree (zeta, HOLogic.typeS);
wenzelm@4895
  1038
    val more = Free (moreN, moreT);
wenzelm@5197
  1039
    val full_moreN = full moreN;
wenzelm@5197
  1040
    fun more_part t = mk_more t full_moreN;
wenzelm@5197
  1041
    fun more_part_update t x = mk_more_update t (full_moreN, x);
wenzelm@11927
  1042
    val all_types_more = all_types @ [moreT];
wenzelm@11927
  1043
    val all_xs_more = all_xs @ [moreN];
wenzelm@4894
  1044
wenzelm@4894
  1045
    val parent_more = funpow parent_len mk_snd;
wenzelm@4894
  1046
    val idxs = 0 upto (len - 1);
wenzelm@4867
  1047
wenzelm@12265
  1048
    val fieldsT = mk_recordT (fields, HOLogic.unitT);
wenzelm@12247
  1049
    fun rec_schemeT n = mk_recordT (prune n all_fields, moreT);
wenzelm@12247
  1050
    fun rec_scheme n = mk_record (prune n all_named_vars, more);
wenzelm@12247
  1051
    fun recT n = mk_recordT (prune n all_fields, HOLogic.unitT);
wenzelm@12255
  1052
    fun rec_ n = mk_record (prune n all_named_vars, HOLogic.unit);
wenzelm@12247
  1053
    fun r_scheme n = Free (rN, rec_schemeT n);
wenzelm@12247
  1054
    fun r n = Free (rN, recT n);
wenzelm@4867
  1055
schirmer@14255
  1056
    
wenzelm@4867
  1057
wenzelm@4890
  1058
    (* prepare print translation functions *)
wenzelm@5698
  1059
    val field_tr's =
wenzelm@13333
  1060
      print_translation (distinct (flat (map NameSpace.accesses' (full_moreN :: names))));
wenzelm@4867
  1061
schirmer@14255
  1062
    val field_type_tr's = 
schirmer@14255
  1063
	let val fldnames = if parent_len = 0 then (tl names) else names;
schirmer@14255
  1064
        in print_translation_field_types (distinct (flat (map NameSpace.accesses' fldnames))) 
schirmer@14255
  1065
        end;
schirmer@14255
  1066
                          
schirmer@14255
  1067
    fun record_type_abbr_tr's thy =
schirmer@14255
  1068
	let val trnames = (distinct (flat (map NameSpace.accesses' [hd all_names])))
schirmer@14255
  1069
            val sg = Theory.sign_of thy
schirmer@14255
  1070
	in map (gen_record_type_abbr_tr' 
schirmer@14255
  1071
                 sg bname alphas zeta (hd (rev names)) (recT 0) (rec_schemeT 0)) trnames end;   
wenzelm@4867
  1072
wenzelm@4867
  1073
    (* prepare declarations *)
wenzelm@4867
  1074
wenzelm@12247
  1075
    val sel_decls = map (mk_selC (rec_schemeT 0)) bfields @
wenzelm@12247
  1076
      [mk_moreC (rec_schemeT 0) (moreN, moreT)];
wenzelm@12247
  1077
    val update_decls = map (mk_updateC (rec_schemeT 0)) bfields @
wenzelm@12247
  1078
      [mk_more_updateC (rec_schemeT 0) (moreN, moreT)];
wenzelm@12265
  1079
    val make_decl = (makeN, all_types ---> recT 0);
wenzelm@12265
  1080
    val fields_decl = (fieldsN, types ---> fieldsT);
wenzelm@12247
  1081
    val extend_decl = (extendN, recT 0 --> moreT --> rec_schemeT 0);
wenzelm@12247
  1082
    val truncate_decl = (truncateN, rec_schemeT 0 --> recT 0);
wenzelm@4867
  1083
wenzelm@4867
  1084
wenzelm@4867
  1085
    (* prepare definitions *)
wenzelm@4867
  1086
wenzelm@4895
  1087
    (*record (scheme) type abbreviation*)
wenzelm@4890
  1088
    val recordT_specs =
wenzelm@12247
  1089
      [(suffix schemeN bname, alphas @ [zeta], rec_schemeT 0, Syntax.NoSyn),
wenzelm@12247
  1090
        (bname, alphas, recT 0, Syntax.NoSyn)];
wenzelm@4867
  1091
wenzelm@4894
  1092
    (*selectors*)
wenzelm@4890
  1093
    fun mk_sel_spec (i, c) =
wenzelm@12247
  1094
      mk_sel (r_scheme 0) c :== mk_fst (funpow i mk_snd (parent_more (r_scheme 0)));
wenzelm@4894
  1095
    val sel_specs =
wenzelm@4894
  1096
      ListPair.map mk_sel_spec (idxs, names) @
wenzelm@12247
  1097
        [more_part (r_scheme 0) :== funpow len mk_snd (parent_more (r_scheme 0))];
wenzelm@4890
  1098
wenzelm@4890
  1099
    (*updates*)
wenzelm@12247
  1100
    val all_sels = mk_named_sels all_names (r_scheme 0);
wenzelm@4890
  1101
    fun mk_upd_spec (i, (c, x)) =
wenzelm@12247
  1102
      mk_update (r_scheme 0) (c, x) :==
wenzelm@12247
  1103
        mk_record (nth_update (c, x) (parent_len + i, all_sels), more_part (r_scheme 0))
wenzelm@5197
  1104
    val update_specs =
wenzelm@5197
  1105
      ListPair.map mk_upd_spec (idxs, named_vars) @
wenzelm@12247
  1106
        [more_part_update (r_scheme 0) more :== mk_record (all_sels, more)];
wenzelm@4867
  1107
wenzelm@11934
  1108
    (*derived operations*)
wenzelm@12265
  1109
    val make_spec = Const (full makeN, all_types ---> recT 0) $$ all_vars :==
wenzelm@12265
  1110
      mk_record (all_named_vars, HOLogic.unit);
wenzelm@12265
  1111
    val fields_spec = Const (full fieldsN, types ---> fieldsT) $$ vars :==
wenzelm@12265
  1112
      mk_record (named_vars, HOLogic.unit);
wenzelm@12247
  1113
    val extend_spec = Const (full extendN, recT 0 --> moreT --> rec_schemeT 0) $ r 0 $ more :==
wenzelm@12247
  1114
      mk_record (mk_named_sels all_names (r 0), more);
wenzelm@12247
  1115
    val truncate_spec = Const (full truncateN, rec_schemeT 0 --> recT 0) $ r_scheme 0 :==
wenzelm@11934
  1116
      mk_record (all_sels, HOLogic.unit);
wenzelm@4894
  1117
wenzelm@4894
  1118
wenzelm@4894
  1119
    (* prepare propositions *)
wenzelm@4894
  1120
wenzelm@4894
  1121
    (*selectors*)
wenzelm@4894
  1122
    val sel_props =
wenzelm@12247
  1123
      map (fn (c, x) => mk_sel (rec_scheme 0) c === x) named_vars @
wenzelm@12247
  1124
        [more_part (rec_scheme 0) === more];
wenzelm@4894
  1125
wenzelm@4894
  1126
    (*updates*)
wenzelm@4894
  1127
    fun mk_upd_prop (i, (c, T)) =
wenzelm@4894
  1128
      let val x' = Free (variant all_xs (base c ^ "'"), T) in
wenzelm@12247
  1129
        mk_update (rec_scheme 0) (c, x') ===
wenzelm@4894
  1130
          mk_record (nth_update (c, x') (parent_len + i, all_named_vars), more)
wenzelm@4894
  1131
      end;
wenzelm@5197
  1132
    val update_props =
wenzelm@5197
  1133
      ListPair.map mk_upd_prop (idxs, fields) @
wenzelm@5197
  1134
        let val more' = Free (variant all_xs (moreN ^ "'"), moreT)
wenzelm@12247
  1135
        in [more_part_update (rec_scheme 0) more' === mk_record (all_named_vars, more')] end;
wenzelm@4867
  1136
wenzelm@9626
  1137
    (*equality*)
wenzelm@9626
  1138
    fun mk_sel_eq (t, T) =
wenzelm@12247
  1139
      let val t' = Term.abstract_over (r_scheme 0, t)
wenzelm@11927
  1140
      in Trueprop (HOLogic.eq_const T $ Term.incr_boundvars 1 t' $ t') end;
wenzelm@12247
  1141
    val sel_eqs = map2 mk_sel_eq
wenzelm@12247
  1142
      (map (mk_sel (r_scheme 0)) all_names @ [more_part (r_scheme 0)], all_types @ [moreT]);
wenzelm@9626
  1143
    val equality_prop =
wenzelm@12247
  1144
      Term.all (rec_schemeT 0) $ (Abs ("r", rec_schemeT 0,
wenzelm@12247
  1145
        Term.all (rec_schemeT 0) $ (Abs ("r'", rec_schemeT 0,
wenzelm@9626
  1146
          Logic.list_implies (sel_eqs,
wenzelm@12247
  1147
            Trueprop (HOLogic.eq_const (rec_schemeT 0) $ Bound 1 $ Bound 0))))));
wenzelm@11927
  1148
wenzelm@11927
  1149
    (*induct*)
wenzelm@12247
  1150
    fun induct_scheme_prop n =
wenzelm@12247
  1151
      let val P = Free ("P", rec_schemeT n --> HOLogic.boolT) in
wenzelm@12247
  1152
        (All (prune n all_xs_more ~~ prune n all_types_more)
wenzelm@12247
  1153
          (Trueprop (P $ rec_scheme n)), Trueprop (P $ r_scheme n))
wenzelm@12247
  1154
      end;
wenzelm@12247
  1155
    fun induct_prop n =
wenzelm@12247
  1156
      let val P = Free ("P", recT n --> HOLogic.boolT) in
wenzelm@12247
  1157
        (All (prune n all_xs ~~ prune n all_types) (Trueprop (P $ rec_ n)), Trueprop (P $ r n))
wenzelm@12247
  1158
      end;
wenzelm@11927
  1159
wenzelm@11927
  1160
    (*cases*)
wenzelm@11927
  1161
    val C = Trueprop (Free (variant all_xs_more "C", HOLogic.boolT));
wenzelm@12247
  1162
    fun cases_scheme_prop n =
wenzelm@12247
  1163
      All (prune n all_xs_more ~~ prune n all_types_more)
wenzelm@12247
  1164
        ((r_scheme n === rec_scheme n) ==> C) ==> C;
wenzelm@12255
  1165
    fun cases_prop n = All (prune n all_xs ~~ prune n all_types) ((r n === rec_ n) ==> C) ==> C;
wenzelm@9626
  1166
schirmer@14255
  1167
    (*split*)
schirmer@14255
  1168
    fun split_scheme_meta_prop n =
schirmer@14255
  1169
      let val P = Free ("P", rec_schemeT n --> Term.propT) in
schirmer@14255
  1170
       equals (Term.propT) $
schirmer@14255
  1171
        (Term.list_all_free ([(rN,rec_schemeT n)],(P $ r_scheme n)))$
schirmer@14255
  1172
        (All (prune n all_xs_more ~~ prune n all_types_more) (P $ rec_scheme n))
schirmer@14255
  1173
      end;
wenzelm@4867
  1174
schirmer@14255
  1175
    fun split_scheme_object_prop n =
schirmer@14255
  1176
      let val P = Free ("P", rec_schemeT n --> HOLogic.boolT) 
schirmer@14255
  1177
          val ALL = foldr (fn ((v,T),t) => HOLogic.mk_all (v,T,t)) 
schirmer@14255
  1178
      in
schirmer@14255
  1179
	Trueprop (
schirmer@14255
  1180
           HOLogic.eq_const (HOLogic.boolT) $
schirmer@14255
  1181
            (HOLogic.mk_all ((rN,rec_schemeT n,P $ r_scheme n)))$
schirmer@14255
  1182
            (ALL (prune n all_xs_more ~~ prune n all_types_more,P $ rec_scheme n)))
schirmer@14255
  1183
      end;
schirmer@14255
  1184
schirmer@14255
  1185
      fun split_scheme_object_ex_prop n =
schirmer@14255
  1186
      let val P = Free ("P", rec_schemeT n --> HOLogic.boolT) 
schirmer@14255
  1187
          val EX = foldr (fn ((v,T),t) => HOLogic.mk_exists (v,T,t)) 
schirmer@14255
  1188
      in
schirmer@14255
  1189
	Trueprop (
schirmer@14255
  1190
           HOLogic.eq_const (HOLogic.boolT) $
schirmer@14255
  1191
            (HOLogic.mk_exists ((rN,rec_schemeT n,P $ r_scheme n)))$
schirmer@14255
  1192
            (EX (prune n all_xs_more ~~ prune n all_types_more,P $ rec_scheme n)))
schirmer@14255
  1193
      end;
wenzelm@4890
  1194
    (* 1st stage: fields_thy *)
wenzelm@4867
  1195
wenzelm@11927
  1196
    val (fields_thy, field_simps, field_injects, field_splits, field_inducts, field_cases) =
wenzelm@4867
  1197
      thy
wenzelm@4867
  1198
      |> Theory.add_path bname
wenzelm@11832
  1199
      |> field_definitions fields names xs alphas zeta moreT more vars named_vars;
wenzelm@4867
  1200
wenzelm@12247
  1201
    val all_field_inducts = flat (map #field_inducts parents) @ field_inducts;
wenzelm@12247
  1202
    val all_field_cases = flat (map #field_cases parents) @ field_cases;
schirmer@14255
  1203
    val all_field_splits = flat (map #field_splits parents) @ field_splits
wenzelm@4867
  1204
schirmer@14255
  1205
    
wenzelm@4890
  1206
    (* 2nd stage: defs_thy *)
wenzelm@4890
  1207
schirmer@14255
  1208
        
schirmer@14255
  1209
   
schirmer@14255
  1210
wenzelm@11934
  1211
    val (defs_thy, (((sel_defs, update_defs), derived_defs))) =
wenzelm@4890
  1212
      fields_thy
schirmer@14255
  1213
      |> Theory.add_trfuns 
schirmer@14255
  1214
           ([],[],record_type_abbr_tr's fields_thy @ field_type_tr's @ field_tr's, [])
schirmer@14255
  1215
      |> add_field_splits (map (suffix field_typeN) names) field_splits
wenzelm@4890
  1216
      |> Theory.parent_path
wenzelm@12255
  1217
      |> Theory.add_tyabbrs_i recordT_specs
wenzelm@4890
  1218
      |> Theory.add_path bname
wenzelm@12506
  1219
      |> Theory.add_consts_i
wenzelm@12506
  1220
        (map2 (fn ((x, T), mx) => (x, T, mx)) (sel_decls, field_syntax @ [Syntax.NoSyn]))
wenzelm@4894
  1221
      |> (Theory.add_consts_i o map Syntax.no_syn)
wenzelm@12506
  1222
        (update_decls @ [make_decl, fields_decl, extend_decl, truncate_decl])
wenzelm@11832
  1223
      |> (PureThy.add_defs_i false o map Thm.no_attributes) sel_specs
wenzelm@11832
  1224
      |>>> (PureThy.add_defs_i false o map Thm.no_attributes) update_specs
wenzelm@11934
  1225
      |>>> (PureThy.add_defs_i false o map Thm.no_attributes)
wenzelm@12590
  1226
        [make_spec, fields_spec, extend_spec, truncate_spec]
wenzelm@12590
  1227
      |>> Theory.hide_consts false [full makeN, full fieldsN, full extendN, full truncateN,
wenzelm@12590
  1228
        full moreN, full (suffix updateN moreN)];
wenzelm@11927
  1229
wenzelm@4890
  1230
wenzelm@4890
  1231
    (* 3rd stage: thms_thy *)
wenzelm@4890
  1232
wenzelm@12247
  1233
    val prove_standard = Tactic.prove_standard (Theory.sign_of defs_thy);
wenzelm@11967
  1234
    fun prove_simp simps =
wenzelm@11967
  1235
      let val tac = simp_all_tac HOL_basic_ss simps
wenzelm@11967
  1236
      in fn prop => prove_standard [] [] prop (K tac) end;
wenzelm@4890
  1237
wenzelm@11967
  1238
    val parent_simps = flat (map #simps parents);
wenzelm@11967
  1239
    val sel_convs = map (prove_simp (parent_simps @ sel_defs @ field_simps)) sel_props;
wenzelm@11967
  1240
    val update_convs = map (prove_simp (parent_simps @ update_defs @ sel_convs)) update_props;
wenzelm@4894
  1241
wenzelm@12247
  1242
    fun induct_scheme n =
wenzelm@12247
  1243
      let val (assm, concl) = induct_scheme_prop n in
wenzelm@12247
  1244
        prove_standard [] [assm] concl (fn prems =>
berghofe@13904
  1245
          EVERY (map (fn rule => try_param_tac rN rule 1) (prune n all_field_inducts))
wenzelm@12247
  1246
          THEN resolve_tac prems 1)
wenzelm@12247
  1247
      end;
wenzelm@11927
  1248
wenzelm@12247
  1249
    fun cases_scheme n =
wenzelm@12247
  1250
      prove_standard [] [] (cases_scheme_prop n) (fn _ =>
berghofe@13904
  1251
        EVERY (map (fn rule => try_param_tac rN rule 1) (prune n all_field_cases))
wenzelm@11967
  1252
        THEN simp_all_tac HOL_basic_ss []);
wenzelm@11927
  1253
schirmer@14255
  1254
    fun split_scheme_meta n =
schirmer@14255
  1255
      prove_standard [] [] (split_scheme_meta_prop n) (fn _ =>
schirmer@14255
  1256
        Simplifier.full_simp_tac (HOL_basic_ss addsimps all_field_splits) 1);
schirmer@14255
  1257
schirmer@14255
  1258
    fun split_scheme_object induct_scheme n =
schirmer@14255
  1259
      prove_standard [] [] (split_scheme_object_prop n) (fn _ =>
schirmer@14255
  1260
         EVERY [rtac iffI 1, 
schirmer@14255
  1261
                REPEAT (rtac allI 1), etac allE 1, atac 1,
schirmer@14255
  1262
                rtac allI 1, rtac induct_scheme 1,REPEAT (etac allE 1),atac 1]);
schirmer@14255
  1263
schirmer@14255
  1264
    fun split_scheme_object_ex split_scheme_meta n =
schirmer@14255
  1265
      prove_standard [] [] (split_scheme_object_ex_prop n) (fn _ =>
schirmer@14255
  1266
        fast_simp_tac (claset_of HOL.thy,
schirmer@14255
  1267
                       HOL_basic_ss addsimps [split_scheme_meta]) 1);
schirmer@14255
  1268
       
wenzelm@12247
  1269
    val induct_scheme0 = induct_scheme 0;
wenzelm@12247
  1270
    val cases_scheme0 = cases_scheme 0;
schirmer@14255
  1271
    val split_scheme_meta0 = split_scheme_meta 0;
schirmer@14255
  1272
    val split_scheme_object0 = split_scheme_object induct_scheme0 0;
schirmer@14255
  1273
    val split_scheme_object_ex0 = split_scheme_object_ex split_scheme_meta0 0;
wenzelm@12247
  1274
    val more_induct_scheme = map induct_scheme ancestry;
wenzelm@12247
  1275
    val more_cases_scheme = map cases_scheme ancestry;
wenzelm@11927
  1276
schirmer@14255
  1277
    val (thms_thy, (([sel_convs', update_convs', sel_defs', update_defs', _, 
schirmer@14255
  1278
                      [split_scheme_meta',split_scheme_object',
schirmer@14255
  1279
                       split_scheme_object_ex',split_scheme_free']],
wenzelm@12247
  1280
        [induct_scheme', cases_scheme']), [more_induct_scheme', more_cases_scheme'])) =
wenzelm@11940
  1281
      defs_thy
wenzelm@11940
  1282
      |> (PureThy.add_thmss o map Thm.no_attributes)
wenzelm@11940
  1283
       [("select_convs", sel_convs),
wenzelm@11940
  1284
        ("update_convs", update_convs),
wenzelm@11940
  1285
        ("select_defs", sel_defs),
wenzelm@11940
  1286
        ("update_defs", update_defs),
schirmer@14255
  1287
        ("defs", derived_defs),
schirmer@14255
  1288
        ("splits",[split_scheme_meta0,split_scheme_object0,
schirmer@14255
  1289
                   split_scheme_object_ex0,induct_scheme0])]
wenzelm@11940
  1290
      |>>> PureThy.add_thms
wenzelm@12255
  1291
       [(("induct_scheme", induct_scheme0), induct_type_global (suffix schemeN name)),
wenzelm@12255
  1292
        (("cases_scheme", cases_scheme0), cases_type_global (suffix schemeN name))]
wenzelm@12255
  1293
      |>>> PureThy.add_thmss
wenzelm@12255
  1294
        [(("more_induct_scheme", more_induct_scheme), induct_type_global ""),
wenzelm@12255
  1295
         (("more_cases_scheme", more_cases_scheme), cases_type_global "")];
wenzelm@12247
  1296
wenzelm@12247
  1297
wenzelm@12247
  1298
    (* 4th stage: more_thms_thy *)
wenzelm@12247
  1299
wenzelm@12247
  1300
    val prove_standard = Tactic.prove_standard (Theory.sign_of thms_thy);
wenzelm@11940
  1301
wenzelm@12247
  1302
    fun induct (n, scheme) =
wenzelm@12247
  1303
      let val (assm, concl) = induct_prop n in
wenzelm@12247
  1304
        prove_standard [] [assm] concl (fn prems =>
wenzelm@12247
  1305
          res_inst_tac [(rN, rN)] scheme 1
berghofe@13904
  1306
          THEN try_param_tac "more" unit_induct 1
wenzelm@12247
  1307
          THEN resolve_tac prems 1)
wenzelm@12247
  1308
      end;
wenzelm@12247
  1309
wenzelm@12247
  1310
    fun cases (n, scheme) =
wenzelm@12247
  1311
      prove_standard [] [] (cases_prop n) (fn _ =>
wenzelm@12247
  1312
        res_inst_tac [(rN, rN)] scheme 1
wenzelm@12247
  1313
        THEN simp_all_tac HOL_basic_ss [unit_all_eq1]);
wenzelm@12247
  1314
wenzelm@12247
  1315
    val induct0 = induct (0, induct_scheme');
wenzelm@12247
  1316
    val cases0 = cases (0, cases_scheme');
wenzelm@12247
  1317
    val more_induct = map induct (ancestry ~~ more_induct_scheme');
wenzelm@12247
  1318
    val more_cases = map cases (ancestry ~~ more_cases_scheme');
wenzelm@12247
  1319
wenzelm@12247
  1320
    val equality = prove_standard [] [] equality_prop (fn _ =>
wenzelm@11967
  1321
      fn st => let val [r, r'] = map #1 (rev (Tactic.innermost_params 1 st)) in
wenzelm@11967
  1322
        st |> (res_inst_tac [(rN, r)] cases_scheme' 1
wenzelm@11967
  1323
        THEN res_inst_tac [(rN, r')] cases_scheme' 1
wenzelm@11967
  1324
        THEN simp_all_tac HOL_basic_ss (parent_simps @ sel_convs))
wenzelm@11967
  1325
      end);
wenzelm@11967
  1326
wenzelm@12247
  1327
    val (more_thms_thy, [_, _, equality']) =
wenzelm@12247
  1328
      thms_thy |> PureThy.add_thms
wenzelm@12255
  1329
       [(("induct", induct0), induct_type_global name),
wenzelm@12255
  1330
        (("cases", cases0), cases_type_global name),
wenzelm@12374
  1331
        (("equality", equality), [ContextRules.intro_bang_global None])]
wenzelm@12255
  1332
      |>> (#1 oo PureThy.add_thmss)
wenzelm@12255
  1333
        [(("more_induct", more_induct), induct_type_global ""),
wenzelm@12255
  1334
         (("more_cases", more_cases), cases_type_global "")];
wenzelm@11967
  1335
berghofe@14079
  1336
    val simps = sel_convs' @ update_convs';
wenzelm@6519
  1337
    val iffs = field_injects;
wenzelm@4867
  1338
wenzelm@12247
  1339
    val more_thms_thy' =
wenzelm@12247
  1340
      more_thms_thy |> (#1 oo PureThy.add_thmss)
wenzelm@5707
  1341
        [(("simps", simps), [Simplifier.simp_add_global]),
wenzelm@6519
  1342
         (("iffs", iffs), [iff_add_global])];
wenzelm@4867
  1343
wenzelm@4867
  1344
wenzelm@12247
  1345
    (* 5th stage: final_thy *)
wenzelm@4867
  1346
wenzelm@4867
  1347
    val final_thy =
wenzelm@12247
  1348
      more_thms_thy'
wenzelm@12247
  1349
      |> put_record name (make_record_info args parent fields field_inducts field_cases
schirmer@14255
  1350
          field_splits (field_simps @ simps))
schirmer@14255
  1351
      |> put_sel_upd (names @ [full_moreN]) simps
berghofe@14079
  1352
      |> add_record_equalities (snd (split_last names)) equality'
schirmer@14255
  1353
      |> add_record_splits (snd (split_last names)) 
schirmer@14255
  1354
                           (split_scheme_meta',split_scheme_object',
schirmer@14255
  1355
                            split_scheme_object_ex',split_scheme_free')
wenzelm@4867
  1356
      |> Theory.parent_path;
wenzelm@4867
  1357
wenzelm@6519
  1358
  in (final_thy, {simps = simps, iffs = iffs}) end;
wenzelm@4867
  1359
wenzelm@4867
  1360
wenzelm@4867
  1361
wenzelm@4867
  1362
(** theory extender interface **)
wenzelm@4867
  1363
wenzelm@4867
  1364
(* prepare arguments *)
wenzelm@4867
  1365
wenzelm@4894
  1366
(*note: read_raw_typ avoids expanding type abbreviations*)
wenzelm@4867
  1367
fun read_raw_parent sign s =
wenzelm@4867
  1368
  (case Sign.read_raw_typ (sign, K None) s handle TYPE (msg, _, _) => error msg of
wenzelm@4867
  1369
    Type (name, Ts) => (Ts, name)
wenzelm@4867
  1370
  | _ => error ("Bad parent record specification: " ^ quote s));
wenzelm@4867
  1371
wenzelm@4867
  1372
fun read_typ sign (env, s) =
wenzelm@4867
  1373
  let
wenzelm@5060
  1374
    fun def_sort (x, ~1) = assoc (env, x)
wenzelm@5060
  1375
      | def_sort _ = None;
wenzelm@5060
  1376
    val T = Type.no_tvars (Sign.read_typ (sign, def_sort) s) handle TYPE (msg, _, _) => error msg;
wenzelm@4867
  1377
  in (Term.add_typ_tfrees (T, env), T) end;
wenzelm@4867
  1378
wenzelm@4867
  1379
fun cert_typ sign (env, raw_T) =
wenzelm@4867
  1380
  let val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle TYPE (msg, _, _) => error msg
wenzelm@4867
  1381
  in (Term.add_typ_tfrees (T, env), T) end;
wenzelm@4867
  1382
wenzelm@4867
  1383
wenzelm@4867
  1384
(* add_record *)
wenzelm@4867
  1385
wenzelm@4895
  1386
(*we do all preparations and error checks here, deferring the real
wenzelm@4895
  1387
  work to record_definition*)
wenzelm@4890
  1388
wenzelm@4867
  1389
fun gen_add_record prep_typ prep_raw_parent (params, bname) raw_parent raw_fields thy =
wenzelm@4867
  1390
  let
paulson@4970
  1391
    val _ = Theory.requires thy "Record" "record definitions";
wenzelm@4867
  1392
    val sign = Theory.sign_of thy;
wenzelm@5698
  1393
    val _ = message ("Defining record " ^ quote bname ^ " ...");
wenzelm@4867
  1394
wenzelm@4867
  1395
wenzelm@4867
  1396
    (* parents *)
wenzelm@4867
  1397
wenzelm@4867
  1398
    fun prep_inst T = snd (cert_typ sign ([], T));
wenzelm@4867
  1399
wenzelm@4867
  1400
    val parent = apsome (apfst (map prep_inst) o prep_raw_parent sign) raw_parent
wenzelm@4867
  1401
      handle ERROR => error ("The error(s) above in parent record specification");
wenzelm@12247
  1402
    val parents = add_parents thy parent [];
wenzelm@4867
  1403
wenzelm@4867
  1404
    val init_env =
wenzelm@4867
  1405
      (case parent of
wenzelm@4867
  1406
        None => []
wenzelm@4867
  1407
      | Some (types, _) => foldr Term.add_typ_tfrees (types, []));
wenzelm@4867
  1408
wenzelm@4867
  1409
wenzelm@4867
  1410
    (* fields *)
wenzelm@4867
  1411
wenzelm@12506
  1412
    fun prep_field (env, (c, raw_T, mx)) =
wenzelm@4967
  1413
      let val (env', T) = prep_typ sign (env, raw_T) handle ERROR =>
wenzelm@4967
  1414
        error ("The error(s) above occured in field " ^ quote c)
wenzelm@12506
  1415
      in (env', (c, T, mx)) end;
wenzelm@4867
  1416
wenzelm@4967
  1417
    val (envir, bfields) = foldl_map prep_field (init_env, raw_fields);
wenzelm@4867
  1418
    val envir_names = map fst envir;
wenzelm@4867
  1419
wenzelm@4867
  1420
wenzelm@4867
  1421
    (* args *)
wenzelm@4867
  1422
wenzelm@4867
  1423
    val defaultS = Sign.defaultS sign;
wenzelm@4867
  1424
    val args = map (fn x => (x, if_none (assoc (envir, x)) defaultS)) params;
wenzelm@4867
  1425
wenzelm@4867
  1426
wenzelm@4867
  1427
    (* errors *)
wenzelm@4867
  1428
wenzelm@4890
  1429
    val name = Sign.full_name sign bname;
wenzelm@4890
  1430
    val err_dup_record =
wenzelm@4890
  1431
      if is_none (get_record thy name) then []
wenzelm@4890
  1432
      else ["Duplicate definition of record " ^ quote name];
wenzelm@4890
  1433
wenzelm@4867
  1434
    val err_dup_parms =
wenzelm@4867
  1435
      (case duplicates params of
wenzelm@4867
  1436
        [] => []
wenzelm@4890
  1437
      | dups => ["Duplicate parameter(s) " ^ commas dups]);
wenzelm@4867
  1438
wenzelm@4867
  1439
    val err_extra_frees =
wenzelm@4867
  1440
      (case gen_rems (op =) (envir_names, params) of
wenzelm@4867
  1441
        [] => []
wenzelm@4890
  1442
      | extras => ["Extra free type variable(s) " ^ commas extras]);
wenzelm@4867
  1443
wenzelm@4890
  1444
    val err_no_fields = if null bfields then ["No fields present"] else [];
wenzelm@4867
  1445
wenzelm@4867
  1446
    val err_dup_fields =
wenzelm@12506
  1447
      (case duplicates (map #1 bfields) of
wenzelm@4867
  1448
        [] => []
wenzelm@4890
  1449
      | dups => ["Duplicate field(s) " ^ commas_quote dups]);
wenzelm@4890
  1450
wenzelm@4890
  1451
    val err_bad_fields =
wenzelm@12506
  1452
      if forall (not_equal moreN o #1) bfields then []
wenzelm@4890
  1453
      else ["Illegal field name " ^ quote moreN];
wenzelm@4867
  1454
wenzelm@4867
  1455
    val err_dup_sorts =
wenzelm@4867
  1456
      (case duplicates envir_names of
wenzelm@4867
  1457
        [] => []
wenzelm@4867
  1458
      | dups => ["Inconsistent sort constraints for " ^ commas dups]);
wenzelm@4867
  1459
wenzelm@4867
  1460
    val errs =
wenzelm@4890
  1461
      err_dup_record @ err_dup_parms @ err_extra_frees @ err_no_fields @
wenzelm@4890
  1462
      err_dup_fields @ err_bad_fields @ err_dup_sorts;
wenzelm@4867
  1463
  in
wenzelm@4890
  1464
    if null errs then () else error (cat_lines errs);
wenzelm@4867
  1465
    thy |> record_definition (args, bname) parent parents bfields
wenzelm@4867
  1466
  end
wenzelm@4867
  1467
  handle ERROR => error ("Failed to define record " ^ quote bname);
wenzelm@4867
  1468
wenzelm@4867
  1469
val add_record = gen_add_record read_typ read_raw_parent;
wenzelm@4867
  1470
val add_record_i = gen_add_record cert_typ (K I);
wenzelm@4867
  1471
wenzelm@4867
  1472
wenzelm@6358
  1473
(** package setup **)
wenzelm@6358
  1474
wenzelm@6358
  1475
(* setup theory *)
wenzelm@4867
  1476
wenzelm@4867
  1477
val setup =
wenzelm@5006
  1478
 [RecordsData.init,
wenzelm@11490
  1479
  Theory.add_trfuns ([], parse_translation, [], []),
wenzelm@6358
  1480
  Method.add_methods [record_split_method],
berghofe@14079
  1481
  Simplifier.change_simpset_of Simplifier.addsimprocs
berghofe@14079
  1482
    [record_simproc, record_eq_simproc]];
wenzelm@4867
  1483
wenzelm@4867
  1484
wenzelm@6358
  1485
(* outer syntax *)
wenzelm@6358
  1486
wenzelm@6723
  1487
local structure P = OuterParse and K = OuterSyntax.Keyword in
wenzelm@6358
  1488
wenzelm@6358
  1489
val record_decl =
wenzelm@12876
  1490
  P.type_args -- P.name --
wenzelm@12876
  1491
    (P.$$$ "=" |-- Scan.option (P.typ --| P.$$$ "+") -- Scan.repeat1 P.const);
wenzelm@6358
  1492
wenzelm@6358
  1493
val recordP =
wenzelm@6723
  1494
  OuterSyntax.command "record" "define extensible record" K.thy_decl
wenzelm@6519
  1495
    (record_decl >> (fn (x, (y, z)) => Toplevel.theory (#1 o add_record x y z)));
wenzelm@6358
  1496
wenzelm@6358
  1497
val _ = OuterSyntax.add_parsers [recordP];
wenzelm@6358
  1498
wenzelm@4867
  1499
end;
wenzelm@5698
  1500
wenzelm@6384
  1501
end;
wenzelm@6384
  1502
wenzelm@5698
  1503
structure BasicRecordPackage: BASIC_RECORD_PACKAGE = RecordPackage;
wenzelm@5698
  1504
open BasicRecordPackage;