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