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