src/HOL/Tools/record.ML
author wenzelm
Sat Apr 16 15:25:25 2011 +0200 (2011-04-16)
changeset 42359 6ca5407863ed
parent 42358 b47d41d9f4b5
child 42361 23f352990944
permissions -rw-r--r--
prefer local name spaces;
tuned signatures;
tuned;
haftmann@31723
     1
(*  Title:      HOL/Tools/record.ML
wenzelm@32763
     2
    Author:     Wolfgang Naraschewski, TU Muenchen
wenzelm@32763
     3
    Author:     Markus Wenzel, TU Muenchen
wenzelm@32763
     4
    Author:     Norbert Schirmer, TU Muenchen
wenzelm@32763
     5
    Author:     Thomas Sewell, NICTA
wenzelm@32763
     6
wenzelm@32763
     7
Extensible records with structural subtyping.
wenzelm@5698
     8
*)
wenzelm@4867
     9
haftmann@38012
    10
signature RECORD =
wenzelm@5698
    11
sig
haftmann@38012
    12
  val print_type_abbr: bool Unsynchronized.ref
haftmann@38012
    13
  val print_type_as_fields: bool Unsynchronized.ref
haftmann@38012
    14
  val timing: bool Unsynchronized.ref
haftmann@38012
    15
haftmann@38012
    16
  type info =
wenzelm@35138
    17
   {args: (string * sort) list,
wenzelm@35138
    18
    parent: (typ list * string) option,
wenzelm@35138
    19
    fields: (string * typ) list,
wenzelm@35138
    20
    extension: (string * typ list),
wenzelm@35138
    21
    ext_induct: thm, ext_inject: thm, ext_surjective: thm, ext_split: thm, ext_def: thm,
wenzelm@35138
    22
    select_convs: thm list, update_convs: thm list, select_defs: thm list, update_defs: thm list,
wenzelm@35138
    23
    fold_congs: thm list, unfold_congs: thm list, splits: thm list, defs: thm list,
wenzelm@35138
    24
    surjective: thm, equality: thm, induct_scheme: thm, induct: thm, cases_scheme: thm,
wenzelm@35138
    25
    cases: thm, simps: thm list, iffs: thm list}
haftmann@38012
    26
  val get_info: theory -> string -> info option
haftmann@38012
    27
  val the_info: theory -> string -> info
wenzelm@41591
    28
  val get_hierarchy: theory -> (string * typ list) -> (string * ((string * sort) * typ) list) list
haftmann@38012
    29
  val add_record: bool -> (string * sort) list * binding -> (typ list * string) option ->
haftmann@38012
    30
    (binding * typ * mixfix) list -> theory -> theory
haftmann@38012
    31
schirmer@14700
    32
  val last_extT: typ -> (string * typ list) option
wenzelm@32972
    33
  val dest_recTs: typ -> (string * typ list) list
wenzelm@32761
    34
  val get_extT_fields: theory -> typ -> (string * typ) list * (string * typ)
wenzelm@32761
    35
  val get_recT_fields: theory -> typ -> (string * typ) list * (string * typ)
wenzelm@26088
    36
  val get_parent: theory -> string -> (typ list * string) option
wenzelm@26088
    37
  val get_extension: theory -> string -> (string * typ list) option
wenzelm@16458
    38
  val get_extinjects: theory -> thm list
wenzelm@16458
    39
  val get_simpset: theory -> simpset
haftmann@38012
    40
  val simproc: simproc
haftmann@38012
    41
  val eq_simproc: simproc
haftmann@38012
    42
  val upd_simproc: simproc
haftmann@38012
    43
  val split_simproc: (term -> int) -> simproc
haftmann@38012
    44
  val ex_sel_eq_simproc: simproc
haftmann@38012
    45
  val split_tac: int -> tactic
haftmann@38012
    46
  val split_simp_tac: thm list -> (term -> int) -> int -> tactic
haftmann@38012
    47
  val split_wrapper: string * wrapper
haftmann@38012
    48
haftmann@38012
    49
  val updateN: string
haftmann@38012
    50
  val ext_typeN: string
haftmann@38012
    51
  val extN: string
wenzelm@27278
    52
  val read_typ: Proof.context -> string -> (string * sort) list -> typ * (string * sort) list
wenzelm@27278
    53
  val cert_typ: Proof.context -> typ -> (string * sort) list -> typ * (string * sort) list
wenzelm@18708
    54
  val setup: theory -> theory
wenzelm@4867
    55
end;
wenzelm@4867
    56
schirmer@14700
    57
haftmann@34151
    58
signature ISO_TUPLE_SUPPORT =
tsewell@32752
    59
sig
haftmann@37470
    60
  val add_iso_tuple_type: binding * (string * sort) list ->
wenzelm@36151
    61
    typ * typ -> theory -> (term * term) * theory
wenzelm@32761
    62
  val mk_cons_tuple: term * term -> term
wenzelm@32761
    63
  val dest_cons_tuple: term -> term * term
haftmann@34151
    64
  val iso_tuple_intros_tac: int -> tactic
wenzelm@32761
    65
  val named_cterm_instantiate: (string * cterm) list -> thm -> thm
tsewell@32752
    66
end;
tsewell@32752
    67
haftmann@34151
    68
structure Iso_Tuple_Support: ISO_TUPLE_SUPPORT =
tsewell@32752
    69
struct
tsewell@32752
    70
haftmann@34151
    71
val isoN = "_Tuple_Iso";
haftmann@34151
    72
haftmann@34151
    73
val iso_tuple_intro = @{thm isomorphic_tuple_intro};
haftmann@34151
    74
val iso_tuple_intros = Tactic.build_net @{thms isomorphic_tuple.intros};
haftmann@34151
    75
haftmann@37470
    76
val tuple_iso_tuple = (@{const_name Record.tuple_iso_tuple}, @{thm tuple_iso_tuple});
tsewell@32752
    77
wenzelm@38252
    78
fun named_cterm_instantiate values thm =  (* FIXME eliminate *)
wenzelm@32761
    79
  let
wenzelm@35135
    80
    fun match name ((name', _), _) = name = name';
wenzelm@32761
    81
    fun getvar name =
wenzelm@32761
    82
      (case find_first (match name) (Term.add_vars (prop_of thm) []) of
wenzelm@32761
    83
        SOME var => cterm_of (theory_of_thm thm) (Var var)
wenzelm@32761
    84
      | NONE => raise THM ("named_cterm_instantiate: " ^ name, 0, [thm]));
tsewell@32752
    85
  in
tsewell@32752
    86
    cterm_instantiate (map (apfst getvar) values) thm
tsewell@32752
    87
  end;
tsewell@32752
    88
haftmann@34151
    89
structure Iso_Tuple_Thms = Theory_Data
tsewell@32752
    90
(
tsewell@32752
    91
  type T = thm Symtab.table;
haftmann@34151
    92
  val empty = Symtab.make [tuple_iso_tuple];
tsewell@32752
    93
  val extend = I;
wenzelm@33522
    94
  fun merge data = Symtab.merge Thm.eq_thm_prop data;   (* FIXME handle Symtab.DUP ?? *)
tsewell@32752
    95
);
tsewell@32752
    96
wenzelm@41575
    97
fun get_typedef_info tyco vs
wenzelm@41575
    98
    (({rep_type, Abs_name, ...}, {Rep_inject, Abs_inverse, ... }) : Typedef.info) thy =
haftmann@38529
    99
  let
haftmann@38529
   100
    val exists_thm =
haftmann@38529
   101
      UNIV_I
haftmann@38529
   102
      |> Drule.instantiate' [SOME (ctyp_of thy (Logic.varifyT_global rep_type))] [];
haftmann@38529
   103
    val proj_constr = Abs_inverse OF [exists_thm];
haftmann@38534
   104
    val absT = Type (tyco, map TFree vs);
haftmann@38529
   105
  in
haftmann@38529
   106
    thy
haftmann@38534
   107
    |> pair (tyco, ((Rep_inject, proj_constr), Const (Abs_name, rep_type --> absT), absT))
haftmann@38529
   108
  end
haftmann@38529
   109
haftmann@38534
   110
fun do_typedef raw_tyco repT raw_vs thy =
haftmann@38529
   111
  let
haftmann@38534
   112
    val ctxt = ProofContext.init_global thy |> Variable.declare_typ repT;
haftmann@38529
   113
    val vs = map (ProofContext.check_tfree ctxt) raw_vs;
haftmann@38529
   114
    val tac = Tactic.rtac UNIV_witness 1;
haftmann@38529
   115
  in
haftmann@38529
   116
    thy
haftmann@38529
   117
    |> Typedef.add_typedef_global false (SOME raw_tyco) (raw_tyco, vs, NoSyn)
haftmann@38534
   118
        (HOLogic.mk_UNIV repT) NONE tac
haftmann@38534
   119
    |-> (fn (tyco, info) => get_typedef_info tyco vs info)
tsewell@32752
   120
  end;
tsewell@32752
   121
wenzelm@32761
   122
fun mk_cons_tuple (left, right) =
wenzelm@32761
   123
  let
tsewell@32752
   124
    val (leftT, rightT) = (fastype_of left, fastype_of right);
wenzelm@32761
   125
    val prodT = HOLogic.mk_prodT (leftT, rightT);
wenzelm@32972
   126
    val isomT = Type (@{type_name tuple_isomorphism}, [prodT, leftT, rightT]);
tsewell@32752
   127
  in
haftmann@37470
   128
    Const (@{const_name Record.iso_tuple_cons}, isomT --> leftT --> rightT --> prodT) $
haftmann@34151
   129
      Const (fst tuple_iso_tuple, isomT) $ left $ right
tsewell@32752
   130
  end;
tsewell@32752
   131
haftmann@37470
   132
fun dest_cons_tuple (Const (@{const_name Record.iso_tuple_cons}, _) $ Const _ $ t $ u) = (t, u)
wenzelm@32972
   133
  | dest_cons_tuple t = raise TERM ("dest_cons_tuple", [t]);
tsewell@32752
   134
haftmann@37470
   135
fun add_iso_tuple_type (b, alphas) (leftT, rightT) thy =
wenzelm@32761
   136
  let
wenzelm@32761
   137
    val repT = HOLogic.mk_prodT (leftT, rightT);
wenzelm@32761
   138
haftmann@38534
   139
    val ((_, ((rep_inject, abs_inverse), absC, absT)), typ_thy) =
wenzelm@32761
   140
      thy
haftmann@37470
   141
      |> do_typedef b repT alphas
haftmann@37470
   142
      ||> Sign.add_path (Binding.name_of b); (*FIXME proper prefixing instead*)
wenzelm@32761
   143
wenzelm@32761
   144
    (*construct a type and body for the isomorphism constant by
wenzelm@32761
   145
      instantiating the theorem to which the definition will be applied*)
wenzelm@32761
   146
    val intro_inst =
haftmann@34151
   147
      rep_inject RS named_cterm_instantiate [("abst", cterm_of typ_thy absC)] iso_tuple_intro;
wenzelm@32761
   148
    val (_, body) = Logic.dest_equals (List.last (prems_of intro_inst));
wenzelm@32761
   149
    val isomT = fastype_of body;
haftmann@37470
   150
    val isom_binding = Binding.suffix_name isoN b;
wenzelm@35239
   151
    val isom_name = Sign.full_name typ_thy isom_binding;
wenzelm@32972
   152
    val isom = Const (isom_name, isomT);
wenzelm@32761
   153
wenzelm@32761
   154
    val ([isom_def], cdef_thy) =
wenzelm@32761
   155
      typ_thy
wenzelm@35239
   156
      |> Sign.declare_const ((isom_binding, isomT), NoSyn) |> snd
wenzelm@39557
   157
      |> Global_Theory.add_defs false
wenzelm@35239
   158
        [((Binding.conceal (Thm.def_binding isom_binding), Logic.mk_equals (isom, body)), [])];
wenzelm@32761
   159
haftmann@34151
   160
    val iso_tuple = isom_def RS (abs_inverse RS (rep_inject RS iso_tuple_intro));
haftmann@37470
   161
    val cons = Const (@{const_name Record.iso_tuple_cons}, isomT --> leftT --> rightT --> absT);
wenzelm@32761
   162
wenzelm@32761
   163
    val thm_thy =
wenzelm@32761
   164
      cdef_thy
haftmann@34151
   165
      |> Iso_Tuple_Thms.map (Symtab.insert Thm.eq_thm_prop (isom_name, iso_tuple))
wenzelm@35239
   166
      |> Sign.restore_naming thy
wenzelm@32761
   167
  in
wenzelm@32972
   168
    ((isom, cons $ isom), thm_thy)
wenzelm@32761
   169
  end;
wenzelm@32761
   170
wenzelm@35133
   171
val iso_tuple_intros_tac =
wenzelm@35133
   172
  resolve_from_net_tac iso_tuple_intros THEN'
wenzelm@32975
   173
  CSUBGOAL (fn (cgoal, i) =>
wenzelm@32975
   174
    let
wenzelm@32975
   175
      val thy = Thm.theory_of_cterm cgoal;
wenzelm@32975
   176
      val goal = Thm.term_of cgoal;
wenzelm@32975
   177
haftmann@34151
   178
      val isthms = Iso_Tuple_Thms.get thy;
haftmann@34151
   179
      fun err s t = raise TERM ("iso_tuple_intros_tac: " ^ s, [t]);
wenzelm@32975
   180
wenzelm@32975
   181
      val goal' = Envir.beta_eta_contract goal;
wenzelm@32975
   182
      val is =
wenzelm@32975
   183
        (case goal' of
wenzelm@32975
   184
          Const (@{const_name Trueprop}, _) $
wenzelm@32975
   185
            (Const (@{const_name isomorphic_tuple}, _) $ Const is) => is
wenzelm@32975
   186
        | _ => err "unexpected goal format" goal');
wenzelm@32975
   187
      val isthm =
wenzelm@32975
   188
        (case Symtab.lookup isthms (#1 is) of
wenzelm@32975
   189
          SOME isthm => isthm
wenzelm@32975
   190
        | NONE => err "no thm found for constant" (Const is));
wenzelm@32975
   191
    in rtac isthm i end);
tsewell@32752
   192
tsewell@32752
   193
end;
tsewell@32752
   194
wenzelm@32761
   195
haftmann@31723
   196
structure Record: RECORD =
wenzelm@4867
   197
struct
wenzelm@4867
   198
wenzelm@32764
   199
val eq_reflection = @{thm eq_reflection};
wenzelm@32764
   200
val meta_allE = @{thm Pure.meta_allE};
wenzelm@32764
   201
val prop_subst = @{thm prop_subst};
wenzelm@32764
   202
val K_record_comp = @{thm K_record_comp};
wenzelm@35136
   203
val K_comp_convs = [@{thm o_apply}, K_record_comp];
wenzelm@32764
   204
val o_assoc = @{thm o_assoc};
tsewell@32743
   205
val id_apply = @{thm id_apply};
tsewell@32743
   206
val id_o_apps = [@{thm id_apply}, @{thm id_o}, @{thm o_id}];
tsewell@32752
   207
val Not_eq_iff = @{thm Not_eq_iff};
tsewell@32743
   208
wenzelm@32764
   209
val refl_conj_eq = @{thm refl_conj_eq};
tsewell@32743
   210
wenzelm@35133
   211
val surject_assistI = @{thm iso_tuple_surjective_proof_assistI};
wenzelm@35133
   212
val surject_assist_idE = @{thm iso_tuple_surjective_proof_assist_idE};
wenzelm@35133
   213
wenzelm@35133
   214
val updacc_accessor_eqE = @{thm update_accessor_accessor_eqE};
wenzelm@35133
   215
val updacc_updator_eqE = @{thm update_accessor_updator_eqE};
wenzelm@35133
   216
val updacc_eq_idI = @{thm iso_tuple_update_accessor_eq_assist_idI};
wenzelm@35133
   217
val updacc_eq_triv = @{thm iso_tuple_update_accessor_eq_assist_triv};
wenzelm@35133
   218
wenzelm@35133
   219
val updacc_foldE = @{thm update_accessor_congruence_foldE};
wenzelm@35133
   220
val updacc_unfoldE = @{thm update_accessor_congruence_unfoldE};
wenzelm@35133
   221
val updacc_noopE = @{thm update_accessor_noopE};
wenzelm@35133
   222
val updacc_noop_compE = @{thm update_accessor_noop_compE};
wenzelm@35133
   223
val updacc_cong_idI = @{thm update_accessor_cong_assist_idI};
wenzelm@35133
   224
val updacc_cong_triv = @{thm update_accessor_cong_assist_triv};
wenzelm@35133
   225
val updacc_cong_from_eq = @{thm iso_tuple_update_accessor_cong_from_eq};
tsewell@32743
   226
wenzelm@32764
   227
val o_eq_dest = @{thm o_eq_dest};
wenzelm@32764
   228
val o_eq_id_dest = @{thm o_eq_id_dest};
wenzelm@32764
   229
val o_eq_dest_lhs = @{thm o_eq_dest_lhs};
wenzelm@11832
   230
wenzelm@32761
   231
wenzelm@32761
   232
schirmer@14700
   233
(** name components **)
schirmer@14700
   234
schirmer@14700
   235
val rN = "r";
schirmer@15215
   236
val wN = "w";
schirmer@14700
   237
val moreN = "more";
schirmer@14700
   238
val schemeN = "_scheme";
haftmann@38531
   239
val ext_typeN = "_ext";
haftmann@38531
   240
val inner_typeN = "_inner";
schirmer@14700
   241
val extN ="_ext";
schirmer@14700
   242
val updateN = "_update";
schirmer@14700
   243
val makeN = "make";
schirmer@14700
   244
val fields_selN = "fields";
schirmer@14700
   245
val extendN = "extend";
schirmer@14700
   246
val truncateN = "truncate";
schirmer@14700
   247
wenzelm@32335
   248
wenzelm@32335
   249
wenzelm@4894
   250
(*** utilities ***)
wenzelm@4867
   251
schirmer@19748
   252
fun varifyT midx =
schirmer@19748
   253
  let fun varify (a, S) = TVar ((a, midx + 1), S);
schirmer@19748
   254
  in map_type_tfree varify end;
schirmer@19748
   255
wenzelm@32335
   256
schirmer@15012
   257
(* timing *)
schirmer@15012
   258
wenzelm@32740
   259
val timing = Unsynchronized.ref false;
wenzelm@32761
   260
fun timeit_msg s x = if ! timing then (warning s; timeit x) else x ();
wenzelm@32761
   261
fun timing_msg s = if ! timing then warning s else ();
wenzelm@17261
   262
wenzelm@32335
   263
wenzelm@12255
   264
(* syntax *)
wenzelm@4867
   265
wenzelm@11927
   266
val Trueprop = HOLogic.mk_Trueprop;
wenzelm@11927
   267
fun All xs t = Term.list_all_free (xs, t);
wenzelm@4894
   268
wenzelm@11934
   269
infix 0 :== ===;
wenzelm@11934
   270
infixr 0 ==>;
wenzelm@11934
   271
wenzelm@37781
   272
val op :== = Misc_Legacy.mk_defpair;
wenzelm@32799
   273
val op === = Trueprop o HOLogic.mk_eq;
wenzelm@32799
   274
val op ==> = Logic.mk_implies;
wenzelm@4867
   275
wenzelm@32335
   276
schirmer@14700
   277
(* constructor *)
wenzelm@4867
   278
wenzelm@32761
   279
fun mk_ext (name, T) ts =
schirmer@14700
   280
  let val Ts = map fastype_of ts
wenzelm@35239
   281
  in list_comb (Const (suffix extN name, Ts ---> T), ts) end;
wenzelm@4867
   282
wenzelm@32335
   283
schirmer@14700
   284
(* selector *)
schirmer@14700
   285
wenzelm@32761
   286
fun mk_selC sT (c, T) = (c, sT --> T);
wenzelm@32761
   287
wenzelm@32761
   288
fun mk_sel s (c, T) =
schirmer@14700
   289
  let val sT = fastype_of s
wenzelm@32761
   290
  in Const (mk_selC sT (c, T)) $ s end;
wenzelm@4867
   291
wenzelm@32335
   292
schirmer@14700
   293
(* updates *)
schirmer@14700
   294
wenzelm@32761
   295
fun mk_updC sfx sT (c, T) = (suffix sfx c, (T --> T) --> sT --> sT);
wenzelm@4867
   296
schirmer@21226
   297
fun mk_upd' sfx c v sT =
schirmer@21226
   298
  let val vT = domain_type (fastype_of v);
wenzelm@32761
   299
  in Const (mk_updC sfx sT (c, vT)) $ v end;
wenzelm@32761
   300
wenzelm@32761
   301
fun mk_upd sfx c v s = mk_upd' sfx c v (fastype_of s) $ s;
wenzelm@4867
   302
wenzelm@32335
   303
wenzelm@4867
   304
(* types *)
wenzelm@4867
   305
wenzelm@32799
   306
fun dest_recT (typ as Type (c_ext_type, Ts as (_ :: _))) =
schirmer@14700
   307
      (case try (unsuffix ext_typeN) c_ext_type of
haftmann@31723
   308
        NONE => raise TYPE ("Record.dest_recT", [typ], [])
skalberg@15570
   309
      | SOME c => ((c, Ts), List.last Ts))
haftmann@31723
   310
  | dest_recT typ = raise TYPE ("Record.dest_recT", [typ], []);
wenzelm@5197
   311
wenzelm@32975
   312
val is_recT = can dest_recT;
wenzelm@11833
   313
schirmer@14700
   314
fun dest_recTs T =
schirmer@14700
   315
  let val ((c, Ts), U) = dest_recT T
schirmer@14700
   316
  in (c, Ts) :: dest_recTs U
schirmer@14700
   317
  end handle TYPE _ => [];
schirmer@14255
   318
schirmer@14700
   319
fun last_extT T =
wenzelm@32761
   320
  let val ((c, Ts), U) = dest_recT T in
wenzelm@32761
   321
    (case last_extT U of
wenzelm@32761
   322
      NONE => SOME (c, Ts)
wenzelm@32761
   323
    | SOME l => SOME l)
wenzelm@32761
   324
  end handle TYPE _ => NONE;
schirmer@14255
   325
wenzelm@17261
   326
fun rec_id i T =
wenzelm@32761
   327
  let
wenzelm@32761
   328
    val rTs = dest_recTs T;
haftmann@33957
   329
    val rTs' = if i < 0 then rTs else take i rTs;
wenzelm@32764
   330
  in implode (map #1 rTs') end;
wenzelm@4867
   331
wenzelm@32335
   332
wenzelm@32335
   333
wenzelm@4867
   334
(*** extend theory by record definition ***)
wenzelm@4867
   335
wenzelm@4867
   336
(** record info **)
wenzelm@4867
   337
haftmann@38012
   338
(* type info and parent_info *)
haftmann@38012
   339
haftmann@38012
   340
type info =
wenzelm@4867
   341
 {args: (string * sort) list,
wenzelm@4867
   342
  parent: (typ list * string) option,
wenzelm@4867
   343
  fields: (string * typ) list,
schirmer@14700
   344
  extension: (string * typ list),
wenzelm@35138
   345
wenzelm@35138
   346
  ext_induct: thm,
wenzelm@35138
   347
  ext_inject: thm,
wenzelm@35138
   348
  ext_surjective: thm,
wenzelm@35138
   349
  ext_split: thm,
wenzelm@35138
   350
  ext_def: thm,
wenzelm@35138
   351
wenzelm@35138
   352
  select_convs: thm list,
wenzelm@35138
   353
  update_convs: thm list,
wenzelm@35138
   354
  select_defs: thm list,
wenzelm@35138
   355
  update_defs: thm list,
wenzelm@35138
   356
  fold_congs: thm list,
wenzelm@35138
   357
  unfold_congs: thm list,
wenzelm@35138
   358
  splits: thm list,
wenzelm@35138
   359
  defs: thm list,
wenzelm@35138
   360
wenzelm@35138
   361
  surjective: thm,
wenzelm@35138
   362
  equality: thm,
wenzelm@35138
   363
  induct_scheme: thm,
tsewell@32743
   364
  induct: thm,
wenzelm@35138
   365
  cases_scheme: thm,
wenzelm@35138
   366
  cases: thm,
wenzelm@35138
   367
wenzelm@35138
   368
  simps: thm list,
wenzelm@35138
   369
  iffs: thm list};
wenzelm@35138
   370
haftmann@38012
   371
fun make_info args parent fields extension
wenzelm@35138
   372
    ext_induct ext_inject ext_surjective ext_split ext_def
wenzelm@35138
   373
    select_convs update_convs select_defs update_defs fold_congs unfold_congs splits defs
wenzelm@35138
   374
    surjective equality induct_scheme induct cases_scheme cases
haftmann@38012
   375
    simps iffs : info =
wenzelm@17261
   376
 {args = args, parent = parent, fields = fields, extension = extension,
wenzelm@35138
   377
  ext_induct = ext_induct, ext_inject = ext_inject, ext_surjective = ext_surjective,
wenzelm@35138
   378
  ext_split = ext_split, ext_def = ext_def, select_convs = select_convs,
wenzelm@35138
   379
  update_convs = update_convs, select_defs = select_defs, update_defs = update_defs,
wenzelm@35138
   380
  fold_congs = fold_congs, unfold_congs = unfold_congs, splits = splits, defs = defs,
wenzelm@35138
   381
  surjective = surjective, equality = equality, induct_scheme = induct_scheme,
wenzelm@35138
   382
  induct = induct, cases_scheme = cases_scheme, cases = cases, simps = simps, iffs = iffs};
wenzelm@4867
   383
wenzelm@4867
   384
type parent_info =
wenzelm@4867
   385
 {name: string,
wenzelm@4867
   386
  fields: (string * typ) list,
schirmer@14700
   387
  extension: (string * typ list),
wenzelm@35138
   388
  induct_scheme: thm,
wenzelm@35138
   389
  ext_def: thm};
wenzelm@35138
   390
wenzelm@35138
   391
fun make_parent_info name fields extension ext_def induct_scheme : parent_info =
tsewell@32743
   392
 {name = name, fields = fields, extension = extension,
wenzelm@35138
   393
  ext_def = ext_def, induct_scheme = induct_scheme};
wenzelm@4867
   394
wenzelm@22846
   395
wenzelm@22846
   396
(* theory data *)
wenzelm@5001
   397
haftmann@38012
   398
type data =
haftmann@38012
   399
 {records: info Symtab.table,
wenzelm@7178
   400
  sel_upd:
tsewell@32744
   401
   {selectors: (int * bool) Symtab.table,
wenzelm@7178
   402
    updates: string Symtab.table,
tsewell@32744
   403
    simpset: Simplifier.simpset,
tsewell@32744
   404
    defset: Simplifier.simpset,
tsewell@32744
   405
    foldcong: Simplifier.simpset,
tsewell@32744
   406
    unfoldcong: Simplifier.simpset},
schirmer@14255
   407
  equalities: thm Symtab.table,
schirmer@15015
   408
  extinjects: thm list,
wenzelm@32764
   409
  extsplit: thm Symtab.table,  (*maps extension name to split rule*)
wenzelm@35135
   410
  splits: (thm * thm * thm * thm) Symtab.table,  (*!!, ALL, EX - split-equalities, induct rule*)
wenzelm@32764
   411
  extfields: (string * typ) list Symtab.table,  (*maps extension to its fields*)
wenzelm@32764
   412
  fieldext: (string * typ list) Symtab.table};  (*maps field to its extension*)
wenzelm@7178
   413
haftmann@38012
   414
fun make_data
wenzelm@32761
   415
    records sel_upd equalities extinjects extsplit splits extfields fieldext =
wenzelm@17261
   416
 {records = records, sel_upd = sel_upd,
wenzelm@17261
   417
  equalities = equalities, extinjects=extinjects, extsplit = extsplit, splits = splits,
haftmann@38012
   418
  extfields = extfields, fieldext = fieldext }: data;
wenzelm@7178
   419
wenzelm@38758
   420
structure Data = Theory_Data
wenzelm@22846
   421
(
haftmann@38012
   422
  type T = data;
wenzelm@7178
   423
  val empty =
haftmann@38012
   424
    make_data Symtab.empty
tsewell@32743
   425
      {selectors = Symtab.empty, updates = Symtab.empty,
tsewell@32743
   426
          simpset = HOL_basic_ss, defset = HOL_basic_ss,
tsewell@32743
   427
          foldcong = HOL_basic_ss, unfoldcong = HOL_basic_ss}
schirmer@15015
   428
       Symtab.empty [] Symtab.empty Symtab.empty Symtab.empty Symtab.empty;
wenzelm@16458
   429
  val extend = I;
wenzelm@33522
   430
  fun merge
wenzelm@7178
   431
   ({records = recs1,
wenzelm@32761
   432
     sel_upd =
wenzelm@32761
   433
      {selectors = sels1, updates = upds1,
wenzelm@32761
   434
       simpset = ss1, defset = ds1,
wenzelm@32761
   435
       foldcong = fc1, unfoldcong = uc1},
schirmer@14255
   436
     equalities = equalities1,
wenzelm@17261
   437
     extinjects = extinjects1,
schirmer@15015
   438
     extsplit = extsplit1,
schirmer@14700
   439
     splits = splits1,
schirmer@14700
   440
     extfields = extfields1,
schirmer@14700
   441
     fieldext = fieldext1},
wenzelm@7178
   442
    {records = recs2,
wenzelm@32761
   443
     sel_upd =
wenzelm@32761
   444
      {selectors = sels2, updates = upds2,
wenzelm@32761
   445
       simpset = ss2, defset = ds2,
wenzelm@32761
   446
       foldcong = fc2, unfoldcong = uc2},
schirmer@15015
   447
     equalities = equalities2,
wenzelm@17261
   448
     extinjects = extinjects2,
wenzelm@17261
   449
     extsplit = extsplit2,
schirmer@14700
   450
     splits = splits2,
schirmer@14700
   451
     extfields = extfields2,
schirmer@14700
   452
     fieldext = fieldext2}) =
haftmann@38012
   453
    make_data
wenzelm@7178
   454
      (Symtab.merge (K true) (recs1, recs2))
wenzelm@7178
   455
      {selectors = Symtab.merge (K true) (sels1, sels2),
wenzelm@7178
   456
        updates = Symtab.merge (K true) (upds1, upds2),
tsewell@32743
   457
        simpset = Simplifier.merge_ss (ss1, ss2),
tsewell@32743
   458
        defset = Simplifier.merge_ss (ds1, ds2),
tsewell@32743
   459
        foldcong = Simplifier.merge_ss (fc1, fc2),
tsewell@32743
   460
        unfoldcong = Simplifier.merge_ss (uc1, uc2)}
haftmann@22634
   461
      (Symtab.merge Thm.eq_thm_prop (equalities1, equalities2))
wenzelm@33522
   462
      (Thm.merge_thms (extinjects1, extinjects2))
wenzelm@32761
   463
      (Symtab.merge Thm.eq_thm_prop (extsplit1, extsplit2))
wenzelm@32761
   464
      (Symtab.merge (fn ((a, b, c, d), (w, x, y, z)) =>
wenzelm@32761
   465
          Thm.eq_thm (a, w) andalso Thm.eq_thm (b, x) andalso
wenzelm@32761
   466
          Thm.eq_thm (c, y) andalso Thm.eq_thm (d, z)) (splits1, splits2))
wenzelm@32761
   467
      (Symtab.merge (K true) (extfields1, extfields2))
wenzelm@32761
   468
      (Symtab.merge (K true) (fieldext1, fieldext2));
wenzelm@22846
   469
);
wenzelm@4867
   470
wenzelm@16458
   471
wenzelm@7178
   472
(* access 'records' *)
wenzelm@4867
   473
wenzelm@38758
   474
val get_info = Symtab.lookup o #records o Data.get;
haftmann@38012
   475
haftmann@38012
   476
fun the_info thy name =
haftmann@38012
   477
  (case get_info thy name of
wenzelm@35138
   478
    SOME info => info
wenzelm@35138
   479
  | NONE => error ("Unknown record type " ^ quote name));
wenzelm@35138
   480
wenzelm@38758
   481
fun put_record name info =
wenzelm@38758
   482
  Data.map (fn {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =>
wenzelm@38758
   483
    make_data (Symtab.update (name, info) records)
wenzelm@38758
   484
      sel_upd equalities extinjects extsplit splits extfields fieldext);
wenzelm@7178
   485
wenzelm@22846
   486
wenzelm@7178
   487
(* access 'sel_upd' *)
wenzelm@7178
   488
wenzelm@38758
   489
val get_sel_upd = #sel_upd o Data.get;
wenzelm@7178
   490
wenzelm@17510
   491
val is_selector = Symtab.defined o #selectors o get_sel_upd;
wenzelm@17412
   492
val get_updates = Symtab.lookup o #updates o get_sel_upd;
wenzelm@35232
   493
fun get_ss_with_context getss thy = Simplifier.global_context thy (getss (get_sel_upd thy));
wenzelm@32764
   494
wenzelm@32764
   495
val get_simpset = get_ss_with_context #simpset;
wenzelm@32764
   496
val get_sel_upd_defs = get_ss_with_context #defset;
tsewell@32743
   497
wenzelm@32761
   498
fun get_update_details u thy =
wenzelm@32761
   499
  let val sel_upd = get_sel_upd thy in
wenzelm@32761
   500
    (case Symtab.lookup (#updates sel_upd) u of
wenzelm@32761
   501
      SOME s =>
wenzelm@32761
   502
        let val SOME (dep, ismore) = Symtab.lookup (#selectors sel_upd) s
wenzelm@32761
   503
        in SOME (s, dep, ismore) end
wenzelm@32761
   504
    | NONE => NONE)
wenzelm@32761
   505
  end;
wenzelm@7178
   506
tsewell@32744
   507
fun put_sel_upd names more depth simps defs (folds, unfolds) thy =
tsewell@32744
   508
  let
wenzelm@32761
   509
    val all = names @ [more];
tsewell@32744
   510
    val sels = map (rpair (depth, false)) names @ [(more, (depth, true))];
tsewell@32744
   511
    val upds = map (suffix updateN) all ~~ all;
tsewell@32744
   512
wenzelm@32761
   513
    val {records, sel_upd = {selectors, updates, simpset, defset, foldcong, unfoldcong},
wenzelm@38758
   514
      equalities, extinjects, extsplit, splits, extfields, fieldext} = Data.get thy;
haftmann@38012
   515
    val data = make_data records
tsewell@32744
   516
      {selectors = fold Symtab.update_new sels selectors,
tsewell@32744
   517
        updates = fold Symtab.update_new upds updates,
tsewell@32744
   518
        simpset = Simplifier.addsimps (simpset, simps),
tsewell@32744
   519
        defset = Simplifier.addsimps (defset, defs),
tsewell@32744
   520
        foldcong = foldcong addcongs folds,
tsewell@32744
   521
        unfoldcong = unfoldcong addcongs unfolds}
tsewell@32744
   522
       equalities extinjects extsplit splits extfields fieldext;
wenzelm@38758
   523
  in Data.put data thy end;
wenzelm@22846
   524
wenzelm@32761
   525
berghofe@14079
   526
(* access 'equalities' *)
berghofe@14079
   527
wenzelm@38758
   528
fun add_equalities name thm =
wenzelm@38758
   529
  Data.map (fn {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =>
wenzelm@38758
   530
    make_data records sel_upd
wenzelm@38758
   531
      (Symtab.update_new (name, thm) equalities) extinjects extsplit splits extfields fieldext);
wenzelm@38758
   532
wenzelm@38758
   533
val get_equalities = Symtab.lookup o #equalities o Data.get;
berghofe@14079
   534
wenzelm@22846
   535
schirmer@15015
   536
(* access 'extinjects' *)
schirmer@15015
   537
wenzelm@38758
   538
fun add_extinjects thm =
wenzelm@38758
   539
  Data.map (fn {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =>
wenzelm@38758
   540
    make_data records sel_upd equalities (insert Thm.eq_thm_prop thm extinjects)
wenzelm@38758
   541
      extsplit splits extfields fieldext);
wenzelm@38758
   542
wenzelm@38758
   543
val get_extinjects = rev o #extinjects o Data.get;
schirmer@15015
   544
wenzelm@22846
   545
schirmer@15015
   546
(* access 'extsplit' *)
schirmer@15015
   547
wenzelm@38758
   548
fun add_extsplit name thm =
wenzelm@38758
   549
  Data.map (fn {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =>
wenzelm@38758
   550
    make_data records sel_upd equalities extinjects
wenzelm@38758
   551
      (Symtab.update_new (name, thm) extsplit) splits extfields fieldext);
schirmer@15015
   552
wenzelm@26088
   553
schirmer@14255
   554
(* access 'splits' *)
schirmer@14255
   555
wenzelm@38758
   556
fun add_splits name thmP =
wenzelm@38758
   557
  Data.map (fn {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =>
wenzelm@38758
   558
    make_data records sel_upd equalities extinjects extsplit
wenzelm@38758
   559
      (Symtab.update_new (name, thmP) splits) extfields fieldext);
wenzelm@38758
   560
wenzelm@38758
   561
val get_splits = Symtab.lookup o #splits o Data.get;
schirmer@14255
   562
schirmer@15015
   563
wenzelm@26088
   564
(* parent/extension of named record *)
schirmer@15015
   565
wenzelm@38758
   566
val get_parent = (Option.join o Option.map #parent) oo (Symtab.lookup o #records o Data.get);
wenzelm@38758
   567
val get_extension = Option.map #extension oo (Symtab.lookup o #records o Data.get);
wenzelm@17261
   568
berghofe@14079
   569
schirmer@14700
   570
(* access 'extfields' *)
schirmer@14700
   571
wenzelm@38758
   572
fun add_extfields name fields =
wenzelm@38758
   573
  Data.map (fn {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =>
wenzelm@38758
   574
    make_data records sel_upd equalities extinjects extsplit splits
wenzelm@38758
   575
      (Symtab.update_new (name, fields) extfields) fieldext);
wenzelm@38758
   576
wenzelm@38758
   577
val get_extfields = Symtab.lookup o #extfields o Data.get;
schirmer@14700
   578
wenzelm@18858
   579
fun get_extT_fields thy T =
schirmer@15059
   580
  let
wenzelm@32761
   581
    val ((name, Ts), moreT) = dest_recT T;
wenzelm@32761
   582
    val recname =
wenzelm@32799
   583
      let val (nm :: _ :: rst) = rev (Long_Name.explode name)   (* FIXME !? *)
wenzelm@32761
   584
      in Long_Name.implode (rev (nm :: rst)) end;
wenzelm@32761
   585
    val midx = maxidx_of_typs (moreT :: Ts);
schirmer@19748
   586
    val varifyT = varifyT midx;
wenzelm@38758
   587
    val {records, extfields, ...} = Data.get thy;
wenzelm@35149
   588
    val (fields, (more, _)) = split_last (Symtab.lookup_list extfields name);
wenzelm@17412
   589
    val args = map varifyT (snd (#extension (the (Symtab.lookup records recname))));
schirmer@15058
   590
wenzelm@41489
   591
    val subst = fold (Sign.typ_match thy) (#1 (split_last args) ~~ #1 (split_last Ts)) Vartab.empty;
wenzelm@35149
   592
    val fields' = map (apsnd (Envir.norm_type subst o varifyT)) fields;
wenzelm@35149
   593
  in (fields', (more, moreT)) end;
schirmer@15058
   594
wenzelm@18858
   595
fun get_recT_fields thy T =
wenzelm@17261
   596
  let
wenzelm@35149
   597
    val (root_fields, (root_more, root_moreT)) = get_extT_fields thy T;
wenzelm@35149
   598
    val (rest_fields, rest_more) =
wenzelm@32761
   599
      if is_recT root_moreT then get_recT_fields thy root_moreT
wenzelm@32761
   600
      else ([], (root_more, root_moreT));
wenzelm@35149
   601
  in (root_fields @ rest_fields, rest_more) end;
schirmer@15059
   602
schirmer@15058
   603
schirmer@14700
   604
(* access 'fieldext' *)
schirmer@14700
   605
wenzelm@38758
   606
fun add_fieldext extname_types fields =
wenzelm@38758
   607
  Data.map (fn {records, sel_upd, equalities, extinjects, extsplit, splits, extfields, fieldext} =>
wenzelm@38758
   608
    let
wenzelm@38758
   609
      val fieldext' =
wenzelm@38758
   610
        fold (fn field => Symtab.update_new (field, extname_types)) fields fieldext;
wenzelm@38758
   611
    in make_data records sel_upd equalities extinjects extsplit splits extfields fieldext' end);
wenzelm@38758
   612
wenzelm@38758
   613
val get_fieldext = Symtab.lookup o #fieldext o Data.get;
schirmer@14700
   614
wenzelm@21962
   615
wenzelm@4867
   616
(* parent records *)
wenzelm@4867
   617
wenzelm@41577
   618
local
wenzelm@41577
   619
wenzelm@41577
   620
fun add_parents _ NONE = I
wenzelm@41577
   621
  | add_parents thy (SOME (types, name)) =
wenzelm@12247
   622
      let
wenzelm@12247
   623
        fun err msg = error (msg ^ " parent record " ^ quote name);
wenzelm@12255
   624
wenzelm@41577
   625
        val {args, parent, ...} =
haftmann@38012
   626
          (case get_info 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@22578
   630
          if Sign.of_sort thy (T, S) then NONE else SOME x
wenzelm@32952
   631
        val bads = map_filter bad_inst (args ~~ types);
wenzelm@21962
   632
        val _ = null bads orelse err ("Ill-sorted instantiation of " ^ commas bads ^ " in");
wenzelm@12255
   633
wenzelm@41591
   634
        val inst = args ~~ types;
wenzelm@41591
   635
        val subst = Term.map_type_tfree (the o AList.lookup (op =) inst);
skalberg@15570
   636
        val parent' = Option.map (apfst (map subst)) parent;
wenzelm@41577
   637
      in cons (name, inst) #> add_parents thy parent' end;
wenzelm@41577
   638
wenzelm@41577
   639
in
wenzelm@41577
   640
wenzelm@41577
   641
fun get_hierarchy thy (name, types) = add_parents thy (SOME (types, name)) [];
wenzelm@41577
   642
wenzelm@41577
   643
fun get_parent_info thy parent =
wenzelm@41577
   644
  add_parents thy parent [] |> map (fn (name, inst) =>
wenzelm@41577
   645
    let
wenzelm@41591
   646
      val subst = Term.map_type_tfree (the o AList.lookup (op =) inst);
wenzelm@41577
   647
      val {fields, extension, induct_scheme, ext_def, ...} = the_info thy name;
wenzelm@41577
   648
      val fields' = map (apsnd subst) fields;
wenzelm@41577
   649
      val extension' = apsnd (map subst) extension;
wenzelm@41577
   650
    in make_parent_info name fields' extension' ext_def induct_scheme end);
wenzelm@41577
   651
wenzelm@41577
   652
end;
wenzelm@4867
   653
wenzelm@4867
   654
wenzelm@21962
   655
schirmer@14700
   656
(** concrete syntax for records **)
schirmer@14700
   657
wenzelm@22693
   658
(* decode type *)
wenzelm@22693
   659
wenzelm@22693
   660
fun decode_type thy t =
wenzelm@22693
   661
  let
wenzelm@35144
   662
    fun get_sort env xi =
wenzelm@35144
   663
      the_default (Sign.defaultS thy) (AList.lookup (op =) env (xi: indexname));
wenzelm@22693
   664
  in
wenzelm@42243
   665
    Syntax_Phases.typ_of_term (get_sort (Syntax_Phases.term_sorts t)) t
wenzelm@22693
   666
  end;
wenzelm@22693
   667
wenzelm@22693
   668
schirmer@14700
   669
(* parse translations *)
schirmer@14700
   670
wenzelm@35144
   671
local
wenzelm@35144
   672
wenzelm@35146
   673
fun field_type_tr ((Const (@{syntax_const "_field_type"}, _) $ Const (name, _) $ arg)) =
wenzelm@35146
   674
      (name, arg)
wenzelm@35146
   675
  | field_type_tr t = raise TERM ("field_type_tr", [t]);
wenzelm@35146
   676
wenzelm@35146
   677
fun field_types_tr (Const (@{syntax_const "_field_types"}, _) $ t $ u) =
wenzelm@35146
   678
      field_type_tr t :: field_types_tr u
wenzelm@35146
   679
  | field_types_tr t = [field_type_tr t];
wenzelm@35146
   680
wenzelm@35146
   681
fun record_field_types_tr more ctxt t =
wenzelm@17261
   682
  let
wenzelm@21772
   683
    val thy = ProofContext.theory_of ctxt;
wenzelm@35146
   684
    fun err msg = raise TERM ("Error in record-type input: " ^ msg, [t]);
wenzelm@35146
   685
wenzelm@35146
   686
    fun split_args (field :: fields) ((name, arg) :: fargs) =
wenzelm@32761
   687
          if can (unsuffix name) field then
wenzelm@35146
   688
            let val (args, rest) = split_args fields fargs
wenzelm@32761
   689
            in (arg :: args, rest) end
wenzelm@35135
   690
          else err ("expecting field " ^ field ^ " but got " ^ name)
wenzelm@35146
   691
      | split_args [] (fargs as (_ :: _)) = ([], fargs)
wenzelm@35146
   692
      | split_args (_ :: _) [] = err "expecting more fields"
wenzelm@35146
   693
      | split_args _ _ = ([], []);
wenzelm@32761
   694
wenzelm@32799
   695
    fun mk_ext (fargs as (name, _) :: _) =
wenzelm@42359
   696
          (case get_fieldext thy (ProofContext.intern_const ctxt name) of
wenzelm@32761
   697
            SOME (ext, alphas) =>
wenzelm@18858
   698
              (case get_extfields thy ext of
wenzelm@35146
   699
                SOME fields =>
wenzelm@35146
   700
                  let
wenzelm@41489
   701
                    val (fields', _) = split_last fields;
wenzelm@35146
   702
                    val types = map snd fields';
wenzelm@35146
   703
                    val (args, rest) = split_args (map fst fields') fargs;
wenzelm@32761
   704
                    val argtypes = map (Sign.certify_typ thy o decode_type thy) args;
wenzelm@33029
   705
                    val midx = fold Term.maxidx_typ argtypes 0;
wenzelm@32761
   706
                    val varifyT = varifyT midx;
wenzelm@32761
   707
                    val vartypes = map varifyT types;
wenzelm@32761
   708
wenzelm@36159
   709
                    val subst = Type.raw_matches (vartypes, argtypes) Vartab.empty
wenzelm@35146
   710
                      handle Type.TYPE_MATCH => err "type is no proper record (extension)";
wenzelm@32761
   711
                    val alphas' =
wenzelm@42247
   712
                      map (Syntax_Phases.term_of_typ ctxt o Envir.norm_type subst o varifyT)
wenzelm@42247
   713
                        (#1 (split_last alphas));
wenzelm@32761
   714
wenzelm@32761
   715
                    val more' = mk_ext rest;
wenzelm@32761
   716
                  in
wenzelm@35430
   717
                    list_comb
wenzelm@42290
   718
                      (Syntax.const (Lexicon.mark_type (suffix ext_typeN ext)), alphas' @ [more'])
wenzelm@35146
   719
                  end
wenzelm@35135
   720
              | NONE => err ("no fields defined for " ^ ext))
wenzelm@35135
   721
          | NONE => err (name ^ " is no proper field"))
wenzelm@32761
   722
      | mk_ext [] = more;
wenzelm@35146
   723
  in
wenzelm@35146
   724
    mk_ext (field_types_tr t)
wenzelm@35146
   725
  end;
wenzelm@35146
   726
wenzelm@35363
   727
fun record_type_tr ctxt [t] = record_field_types_tr (Syntax.const @{type_syntax unit}) ctxt t
wenzelm@35146
   728
  | record_type_tr _ ts = raise TERM ("record_type_tr", ts);
wenzelm@35146
   729
wenzelm@35146
   730
fun record_type_scheme_tr ctxt [t, more] = record_field_types_tr more ctxt t
wenzelm@35146
   731
  | record_type_scheme_tr _ ts = raise TERM ("record_type_scheme_tr", ts);
wenzelm@35146
   732
wenzelm@35147
   733
wenzelm@35147
   734
fun field_tr ((Const (@{syntax_const "_field"}, _) $ Const (name, _) $ arg)) = (name, arg)
wenzelm@35147
   735
  | field_tr t = raise TERM ("field_tr", [t]);
wenzelm@35147
   736
wenzelm@35147
   737
fun fields_tr (Const (@{syntax_const "_fields"}, _) $ t $ u) = field_tr t :: fields_tr u
wenzelm@35147
   738
  | fields_tr t = [field_tr t];
wenzelm@35147
   739
wenzelm@35147
   740
fun record_fields_tr more ctxt t =
wenzelm@35147
   741
  let
wenzelm@35147
   742
    val thy = ProofContext.theory_of ctxt;
wenzelm@35147
   743
    fun err msg = raise TERM ("Error in record input: " ^ msg, [t]);
wenzelm@35147
   744
wenzelm@35147
   745
    fun split_args (field :: fields) ((name, arg) :: fargs) =
wenzelm@35147
   746
          if can (unsuffix name) field
wenzelm@35147
   747
          then
wenzelm@35147
   748
            let val (args, rest) = split_args fields fargs
wenzelm@35147
   749
            in (arg :: args, rest) end
wenzelm@35147
   750
          else err ("expecting field " ^ field ^ " but got " ^ name)
wenzelm@35147
   751
      | split_args [] (fargs as (_ :: _)) = ([], fargs)
wenzelm@35147
   752
      | split_args (_ :: _) [] = err "expecting more fields"
wenzelm@35147
   753
      | split_args _ _ = ([], []);
wenzelm@35147
   754
wenzelm@35147
   755
    fun mk_ext (fargs as (name, _) :: _) =
wenzelm@42359
   756
          (case get_fieldext thy (ProofContext.intern_const ctxt name) of
wenzelm@35147
   757
            SOME (ext, _) =>
wenzelm@35147
   758
              (case get_extfields thy ext of
wenzelm@35147
   759
                SOME fields =>
wenzelm@35147
   760
                  let
wenzelm@41489
   761
                    val (args, rest) = split_args (map fst (fst (split_last fields))) fargs;
wenzelm@35147
   762
                    val more' = mk_ext rest;
wenzelm@42290
   763
                  in list_comb (Syntax.const (Lexicon.mark_const (ext ^ extN)), args @ [more']) end
wenzelm@35147
   764
              | NONE => err ("no fields defined for " ^ ext))
wenzelm@35147
   765
          | NONE => err (name ^ " is no proper field"))
wenzelm@35147
   766
      | mk_ext [] = more;
wenzelm@35147
   767
  in mk_ext (fields_tr t) end;
wenzelm@35147
   768
wenzelm@35147
   769
fun record_tr ctxt [t] = record_fields_tr (Syntax.const @{const_syntax Unity}) ctxt t
wenzelm@35147
   770
  | record_tr _ ts = raise TERM ("record_tr", ts);
wenzelm@35147
   771
wenzelm@35147
   772
fun record_scheme_tr ctxt [t, more] = record_fields_tr more ctxt t
wenzelm@35147
   773
  | record_scheme_tr _ ts = raise TERM ("record_scheme_tr", ts);
wenzelm@35147
   774
wenzelm@35147
   775
wenzelm@35147
   776
fun field_update_tr (Const (@{syntax_const "_field_update"}, _) $ Const (name, _) $ arg) =
wenzelm@35147
   777
      Syntax.const (suffix updateN name) $ Abs ("_", dummyT, arg)
wenzelm@35147
   778
  | field_update_tr t = raise TERM ("field_update_tr", [t]);
wenzelm@35147
   779
wenzelm@35147
   780
fun field_updates_tr (Const (@{syntax_const "_field_updates"}, _) $ t $ u) =
wenzelm@35147
   781
      field_update_tr t :: field_updates_tr u
wenzelm@35147
   782
  | field_updates_tr t = [field_update_tr t];
wenzelm@35147
   783
wenzelm@35147
   784
fun record_update_tr [t, u] = fold (curry op $) (field_updates_tr u) t
wenzelm@35147
   785
  | record_update_tr ts = raise TERM ("record_update_tr", ts);
wenzelm@35147
   786
wenzelm@35146
   787
in
schirmer@15215
   788
wenzelm@24867
   789
val parse_translation =
wenzelm@35145
   790
 [(@{syntax_const "_record_update"}, record_update_tr)];
schirmer@14700
   791
wenzelm@35146
   792
val advanced_parse_translation =
wenzelm@35146
   793
 [(@{syntax_const "_record"}, record_tr),
wenzelm@35146
   794
  (@{syntax_const "_record_scheme"}, record_scheme_tr),
wenzelm@35146
   795
  (@{syntax_const "_record_type"}, record_type_tr),
wenzelm@35146
   796
  (@{syntax_const "_record_type_scheme"}, record_type_scheme_tr)];
wenzelm@35146
   797
wenzelm@35146
   798
end;
schirmer@14700
   799
schirmer@21226
   800
schirmer@14700
   801
(* print translations *)
schirmer@14700
   802
haftmann@38012
   803
val print_type_abbr = Unsynchronized.ref true;
haftmann@38012
   804
val print_type_as_fields = Unsynchronized.ref true;
schirmer@14700
   805
wenzelm@35149
   806
wenzelm@35149
   807
local
wenzelm@35149
   808
wenzelm@35149
   809
(* FIXME early extern (!??) *)
wenzelm@35149
   810
(* FIXME Syntax.free (??) *)
wenzelm@35149
   811
fun field_type_tr' (c, t) = Syntax.const @{syntax_const "_field_type"} $ Syntax.const c $ t;
wenzelm@35149
   812
wenzelm@35149
   813
fun field_types_tr' (t, u) = Syntax.const @{syntax_const "_field_types"} $ t $ u;
wenzelm@35149
   814
wenzelm@35149
   815
fun record_type_tr' ctxt t =
wenzelm@32761
   816
  let
wenzelm@35149
   817
    val thy = ProofContext.theory_of ctxt;
wenzelm@35149
   818
wenzelm@35149
   819
    val T = decode_type thy t;
wenzelm@35149
   820
    val varifyT = varifyT (Term.maxidx_of_typ T);
wenzelm@35149
   821
wenzelm@35149
   822
    fun strip_fields T =
wenzelm@35149
   823
      (case T of
wenzelm@35615
   824
        Type (ext, args as _ :: _) =>
wenzelm@35149
   825
          (case try (unsuffix ext_typeN) ext of
wenzelm@35149
   826
            SOME ext' =>
wenzelm@35149
   827
              (case get_extfields thy ext' of
wenzelm@35615
   828
                SOME (fields as (x, _) :: _) =>
wenzelm@35615
   829
                  (case get_fieldext thy x of
wenzelm@35149
   830
                    SOME (_, alphas) =>
wenzelm@35149
   831
                     (let
wenzelm@41489
   832
                        val (f :: fs, _) = split_last fields;
wenzelm@35149
   833
                        val fields' =
wenzelm@42359
   834
                          apfst (ProofContext.extern_const ctxt) f ::
wenzelm@42359
   835
                            map (apfst Long_Name.base_name) fs;
wenzelm@35149
   836
                        val (args', more) = split_last args;
wenzelm@41489
   837
                        val alphavars = map varifyT (#1 (split_last alphas));
wenzelm@36159
   838
                        val subst = Type.raw_matches (alphavars, args') Vartab.empty;
wenzelm@35149
   839
                        val fields'' = (map o apsnd) (Envir.norm_type subst o varifyT) fields';
wenzelm@35149
   840
                      in fields'' @ strip_fields more end
wenzelm@36159
   841
                      handle Type.TYPE_MATCH => [("", T)])
wenzelm@35615
   842
                  | _ => [("", T)])
wenzelm@35615
   843
              | _ => [("", T)])
wenzelm@35615
   844
          | _ => [("", T)])
wenzelm@35149
   845
      | _ => [("", T)]);
wenzelm@35149
   846
wenzelm@35149
   847
    val (fields, (_, moreT)) = split_last (strip_fields T);
wenzelm@35149
   848
    val _ = null fields andalso raise Match;
wenzelm@42247
   849
    val u =
wenzelm@42247
   850
      foldr1 field_types_tr'
wenzelm@42247
   851
        (map (field_type_tr' o apsnd (Syntax_Phases.term_of_typ ctxt)) fields);
wenzelm@35149
   852
  in
haftmann@38012
   853
    if not (! print_type_as_fields) orelse null fields then raise Match
wenzelm@35149
   854
    else if moreT = HOLogic.unitT then Syntax.const @{syntax_const "_record_type"} $ u
wenzelm@42247
   855
    else
wenzelm@42247
   856
      Syntax.const @{syntax_const "_record_type_scheme"} $ u $
wenzelm@42247
   857
        Syntax_Phases.term_of_typ ctxt moreT
wenzelm@35149
   858
  end;
wenzelm@32761
   859
wenzelm@32761
   860
(*try to reconstruct the record name type abbreviation from
wenzelm@32761
   861
  the (nested) extension types*)
wenzelm@35149
   862
fun record_type_abbr_tr' abbr alphas zeta last_ext schemeT ctxt tm =
schirmer@14700
   863
  let
wenzelm@32761
   864
    val thy = ProofContext.theory_of ctxt;
wenzelm@35614
   865
    val T = decode_type thy tm;
wenzelm@32761
   866
    val midx = maxidx_of_typ T;
wenzelm@32761
   867
    val varifyT = varifyT midx;
wenzelm@32761
   868
wenzelm@36151
   869
    fun mk_type_abbr subst name args =
wenzelm@36151
   870
      let val abbrT = Type (name, map (varifyT o TFree) args)
wenzelm@42247
   871
      in Syntax_Phases.term_of_typ ctxt (Envir.norm_type subst abbrT) end;
wenzelm@32761
   872
wenzelm@36159
   873
    fun match rT T = Type.raw_match (varifyT rT, T) Vartab.empty;
wenzelm@32761
   874
  in
haftmann@38012
   875
    if ! print_type_abbr then
wenzelm@32761
   876
      (case last_extT T of
wenzelm@32761
   877
        SOME (name, _) =>
wenzelm@35148
   878
          if name = last_ext then
wenzelm@35149
   879
            let val subst = match schemeT T in
wenzelm@36151
   880
              if HOLogic.is_unitT (Envir.norm_type subst (varifyT (TFree zeta)))
wenzelm@32335
   881
              then mk_type_abbr subst abbr alphas
wenzelm@32335
   882
              else mk_type_abbr subst (suffix schemeN abbr) (alphas @ [zeta])
wenzelm@35149
   883
            end handle Type.TYPE_MATCH => record_type_tr' ctxt tm
wenzelm@32761
   884
          else raise Match (*give print translation of specialised record a chance*)
wenzelm@32761
   885
      | _ => raise Match)
wenzelm@35149
   886
    else record_type_tr' ctxt tm
wenzelm@32761
   887
  end;
schirmer@14700
   888
wenzelm@35149
   889
in
wenzelm@35149
   890
wenzelm@35149
   891
fun record_ext_type_tr' name =
schirmer@14700
   892
  let
wenzelm@42290
   893
    val ext_type_name = Lexicon.mark_type (suffix ext_typeN name);
wenzelm@35149
   894
    fun tr' ctxt ts =
wenzelm@35149
   895
      record_type_tr' ctxt (list_comb (Syntax.const ext_type_name, ts));
wenzelm@35149
   896
  in (ext_type_name, tr') end;
wenzelm@35149
   897
wenzelm@35149
   898
fun record_ext_type_abbr_tr' abbr alphas zeta last_ext schemeT name =
wenzelm@32761
   899
  let
wenzelm@42290
   900
    val ext_type_name = Lexicon.mark_type (suffix ext_typeN name);
wenzelm@32761
   901
    fun tr' ctxt ts =
wenzelm@35149
   902
      record_type_abbr_tr' abbr alphas zeta last_ext schemeT ctxt
wenzelm@35149
   903
        (list_comb (Syntax.const ext_type_name, ts));
wenzelm@35149
   904
  in (ext_type_name, tr') end;
wenzelm@35149
   905
wenzelm@35149
   906
end;
schirmer@14700
   907
wenzelm@32335
   908
wenzelm@35240
   909
local
wenzelm@35240
   910
wenzelm@35240
   911
(* FIXME Syntax.free (??) *)
wenzelm@35240
   912
fun field_tr' (c, t) = Syntax.const @{syntax_const "_field"} $ Syntax.const c $ t;
wenzelm@35240
   913
fun fields_tr' (t, u) = Syntax.const @{syntax_const "_fields"} $ t $ u;
wenzelm@35240
   914
wenzelm@35240
   915
fun record_tr' ctxt t =
wenzelm@35240
   916
  let
wenzelm@35240
   917
    val thy = ProofContext.theory_of ctxt;
wenzelm@35240
   918
wenzelm@35240
   919
    fun strip_fields t =
wenzelm@35240
   920
      (case strip_comb t of
wenzelm@35240
   921
        (Const (ext, _), args as (_ :: _)) =>
wenzelm@42290
   922
          (case try (Lexicon.unmark_const o unsuffix extN) ext of
wenzelm@35240
   923
            SOME ext' =>
wenzelm@35240
   924
              (case get_extfields thy ext' of
wenzelm@35240
   925
                SOME fields =>
wenzelm@35240
   926
                 (let
wenzelm@41489
   927
                    val (f :: fs, _) = split_last (map fst fields);
wenzelm@42359
   928
                    val fields' = ProofContext.extern_const ctxt f :: map Long_Name.base_name fs;
wenzelm@35240
   929
                    val (args', more) = split_last args;
wenzelm@35240
   930
                  in (fields' ~~ args') @ strip_fields more end
wenzelm@40722
   931
                  handle ListPair.UnequalLengths => [("", t)])
wenzelm@35240
   932
              | NONE => [("", t)])
wenzelm@35240
   933
          | NONE => [("", t)])
wenzelm@35240
   934
       | _ => [("", t)]);
wenzelm@35240
   935
wenzelm@35240
   936
    val (fields, (_, more)) = split_last (strip_fields t);
wenzelm@35240
   937
    val _ = null fields andalso raise Match;
wenzelm@35240
   938
    val u = foldr1 fields_tr' (map field_tr' fields);
wenzelm@35240
   939
  in
wenzelm@35240
   940
    case more of
wenzelm@35240
   941
      Const (@{const_syntax Unity}, _) => Syntax.const @{syntax_const "_record"} $ u
wenzelm@35240
   942
    | _ => Syntax.const @{syntax_const "_record_scheme"} $ u $ more
wenzelm@35240
   943
  end;
wenzelm@35240
   944
wenzelm@35240
   945
in
wenzelm@35240
   946
wenzelm@35240
   947
fun record_ext_tr' name =
wenzelm@35240
   948
  let
wenzelm@42290
   949
    val ext_name = Lexicon.mark_const (name ^ extN);
wenzelm@35240
   950
    fun tr' ctxt ts = record_tr' ctxt (list_comb (Syntax.const ext_name, ts));
wenzelm@35240
   951
  in (ext_name, tr') end;
wenzelm@35240
   952
wenzelm@35240
   953
end;
wenzelm@35240
   954
wenzelm@35240
   955
wenzelm@35240
   956
local
wenzelm@35240
   957
wenzelm@41578
   958
fun dest_update ctxt c =
wenzelm@42290
   959
  (case try Lexicon.unmark_const c of
wenzelm@42359
   960
    SOME d => try (unsuffix updateN) (ProofContext.extern_const ctxt d)
wenzelm@41578
   961
  | NONE => NONE);
wenzelm@41578
   962
wenzelm@35240
   963
fun field_updates_tr' ctxt (tm as Const (c, _) $ k $ u) =
wenzelm@41578
   964
      (case dest_update ctxt c of
wenzelm@41578
   965
        SOME name =>
wenzelm@42284
   966
          (case try Syntax_Trans.const_abs_tr' k of
wenzelm@42086
   967
            SOME t =>
wenzelm@42086
   968
              apfst (cons (Syntax.const @{syntax_const "_field_update"} $ Syntax.free name $ t))
wenzelm@42086
   969
                (field_updates_tr' ctxt u)
wenzelm@42086
   970
          | NONE => ([], tm))
wenzelm@41578
   971
      | NONE => ([], tm))
wenzelm@35240
   972
  | field_updates_tr' _ tm = ([], tm);
wenzelm@35240
   973
wenzelm@35240
   974
fun record_update_tr' ctxt tm =
wenzelm@35240
   975
  (case field_updates_tr' ctxt tm of
wenzelm@35240
   976
    ([], _) => raise Match
wenzelm@35240
   977
  | (ts, u) =>
wenzelm@35240
   978
      Syntax.const @{syntax_const "_record_update"} $ u $
wenzelm@35240
   979
        foldr1 (fn (v, w) => Syntax.const @{syntax_const "_field_updates"} $ v $ w) (rev ts));
wenzelm@35240
   980
wenzelm@35240
   981
in
wenzelm@35240
   982
wenzelm@35240
   983
fun field_update_tr' name =
wenzelm@35240
   984
  let
wenzelm@42290
   985
    val update_name = Lexicon.mark_const (name ^ updateN);
wenzelm@35240
   986
    fun tr' ctxt [t, u] = record_update_tr' ctxt (Syntax.const update_name $ t $ u)
wenzelm@35240
   987
      | tr' _ _ = raise Match;
wenzelm@35240
   988
  in (update_name, tr') end;
wenzelm@35240
   989
wenzelm@35240
   990
end;
wenzelm@35240
   991
wenzelm@35240
   992
wenzelm@32335
   993
schirmer@15015
   994
(** record simprocs **)
schirmer@14358
   995
schirmer@33691
   996
fun future_forward_prf_standard thy prf prop () =
wenzelm@33711
   997
  let val thm =
wenzelm@33711
   998
    if ! quick_and_dirty then Skip_Proof.make_thm thy prop
wenzelm@33711
   999
    else if Goal.future_enabled () then
wenzelm@37186
  1000
      Goal.future_result (ProofContext.init_global thy) (Goal.fork prf) prop
wenzelm@33711
  1001
    else prf ()
wenzelm@35021
  1002
  in Drule.export_without_context thm end;
schirmer@33691
  1003
schirmer@33691
  1004
fun prove_common immediate stndrd thy asms prop tac =
wenzelm@33711
  1005
  let
wenzelm@33711
  1006
    val prv =
wenzelm@33711
  1007
      if ! quick_and_dirty then Skip_Proof.prove
wenzelm@33711
  1008
      else if immediate orelse not (Goal.future_enabled ()) then Goal.prove
wenzelm@33711
  1009
      else Goal.prove_future;
wenzelm@36610
  1010
    val prf = prv (ProofContext.init_global thy) [] asms prop tac;
wenzelm@35021
  1011
  in if stndrd then Drule.export_without_context prf else prf end;
schirmer@33691
  1012
schirmer@33691
  1013
val prove_future_global = prove_common false;
schirmer@33691
  1014
val prove_global = prove_common true;
wenzelm@32761
  1015
wenzelm@32799
  1016
fun is_sel_upd_pair thy (Const (s, _)) (Const (u, t')) =
wenzelm@32761
  1017
  (case get_updates thy u of
wenzelm@32761
  1018
    SOME u_name => u_name = s
wenzelm@32761
  1019
  | NONE => raise TERM ("is_sel_upd_pair: not update", [Const (u, t')]));
wenzelm@32761
  1020
wenzelm@32761
  1021
fun mk_comp_id f =
wenzelm@32761
  1022
  let val T = range_type (fastype_of f)
wenzelm@40845
  1023
  in HOLogic.mk_comp (Const (@{const_name Fun.id}, T --> T), f) end;
tsewell@32743
  1024
tsewell@32752
  1025
fun get_upd_funs (upd $ _ $ t) = upd :: get_upd_funs t
wenzelm@32761
  1026
  | get_upd_funs _ = [];
wenzelm@32761
  1027
wenzelm@32975
  1028
fun get_accupd_simps thy term defset =
wenzelm@32761
  1029
  let
tsewell@32743
  1030
    val (acc, [body]) = strip_comb term;
wenzelm@35408
  1031
    val upd_funs = sort_distinct Term_Ord.fast_term_ord (get_upd_funs body);
wenzelm@32761
  1032
    fun get_simp upd =
wenzelm@32761
  1033
      let
wenzelm@35133
  1034
        (* FIXME fresh "f" (!?) *)
wenzelm@32761
  1035
        val T = domain_type (fastype_of upd);
wenzelm@40845
  1036
        val lhs = HOLogic.mk_comp (acc, upd $ Free ("f", T));
wenzelm@32761
  1037
        val rhs =
wenzelm@32761
  1038
          if is_sel_upd_pair thy acc upd
wenzelm@40845
  1039
          then HOLogic.mk_comp (Free ("f", T), acc)
wenzelm@32761
  1040
          else mk_comp_id acc;
wenzelm@32799
  1041
        val prop = lhs === rhs;
wenzelm@32761
  1042
        val othm =
wenzelm@36610
  1043
          Goal.prove (ProofContext.init_global thy) [] [] prop
wenzelm@32799
  1044
            (fn _ =>
wenzelm@32975
  1045
              simp_tac defset 1 THEN
haftmann@34151
  1046
              REPEAT_DETERM (Iso_Tuple_Support.iso_tuple_intros_tac 1) THEN
wenzelm@32975
  1047
              TRY (simp_tac (HOL_ss addsimps id_o_apps) 1));
wenzelm@32761
  1048
        val dest =
wenzelm@32761
  1049
          if is_sel_upd_pair thy acc upd
wenzelm@32761
  1050
          then o_eq_dest
wenzelm@32761
  1051
          else o_eq_id_dest;
wenzelm@35021
  1052
      in Drule.export_without_context (othm RS dest) end;
tsewell@32752
  1053
  in map get_simp upd_funs end;
tsewell@32743
  1054
wenzelm@32975
  1055
fun get_updupd_simp thy defset u u' comp =
wenzelm@32761
  1056
  let
wenzelm@35133
  1057
    (* FIXME fresh "f" (!?) *)
wenzelm@32761
  1058
    val f = Free ("f", domain_type (fastype_of u));
wenzelm@32761
  1059
    val f' = Free ("f'", domain_type (fastype_of u'));
wenzelm@40845
  1060
    val lhs = HOLogic.mk_comp (u $ f, u' $ f');
wenzelm@32761
  1061
    val rhs =
wenzelm@32761
  1062
      if comp
wenzelm@40845
  1063
      then u $ HOLogic.mk_comp (f, f')
wenzelm@40845
  1064
      else HOLogic.mk_comp (u' $ f', u $ f);
wenzelm@32799
  1065
    val prop = lhs === rhs;
wenzelm@32761
  1066
    val othm =
wenzelm@36610
  1067
      Goal.prove (ProofContext.init_global thy) [] [] prop
wenzelm@32799
  1068
        (fn _ =>
wenzelm@32975
  1069
          simp_tac defset 1 THEN
haftmann@34151
  1070
          REPEAT_DETERM (Iso_Tuple_Support.iso_tuple_intros_tac 1) THEN
wenzelm@32975
  1071
          TRY (simp_tac (HOL_ss addsimps [id_apply]) 1));
tsewell@32743
  1072
    val dest = if comp then o_eq_dest_lhs else o_eq_dest;
wenzelm@35021
  1073
  in Drule.export_without_context (othm RS dest) end;
tsewell@32743
  1074
wenzelm@32975
  1075
fun get_updupd_simps thy term defset =
wenzelm@32761
  1076
  let
wenzelm@32761
  1077
    val upd_funs = get_upd_funs term;
wenzelm@32761
  1078
    val cname = fst o dest_Const;
wenzelm@32975
  1079
    fun getswap u u' = get_updupd_simp thy defset u u' (cname u = cname u');
wenzelm@32799
  1080
    fun build_swaps_to_eq _ [] swaps = swaps
wenzelm@32761
  1081
      | build_swaps_to_eq upd (u :: us) swaps =
wenzelm@32761
  1082
          let
wenzelm@32761
  1083
            val key = (cname u, cname upd);
wenzelm@32761
  1084
            val newswaps =
wenzelm@32764
  1085
              if Symreltab.defined swaps key then swaps
wenzelm@32764
  1086
              else Symreltab.insert (K true) (key, getswap u upd) swaps;
wenzelm@32761
  1087
          in
wenzelm@32761
  1088
            if cname u = cname upd then newswaps
wenzelm@32761
  1089
            else build_swaps_to_eq upd us newswaps
wenzelm@32761
  1090
          end;
wenzelm@32799
  1091
    fun swaps_needed [] _ _ swaps = map snd (Symreltab.dest swaps)
wenzelm@32761
  1092
      | swaps_needed (u :: us) prev seen swaps =
wenzelm@32761
  1093
          if Symtab.defined seen (cname u)
wenzelm@32761
  1094
          then swaps_needed us prev seen (build_swaps_to_eq u prev swaps)
wenzelm@32761
  1095
          else swaps_needed us (u :: prev) (Symtab.insert (K true) (cname u, ()) seen) swaps;
wenzelm@32764
  1096
  in swaps_needed upd_funs [] Symtab.empty Symreltab.empty end;
tsewell@32743
  1097
haftmann@34151
  1098
val named_cterm_instantiate = Iso_Tuple_Support.named_cterm_instantiate;
tsewell@32743
  1099
wenzelm@32799
  1100
fun prove_unfold_defs thy ex_simps ex_simprs prop =
schirmer@21226
  1101
  let
tsewell@32743
  1102
    val defset = get_sel_upd_defs thy;
wenzelm@32761
  1103
    val prop' = Envir.beta_eta_contract prop;
wenzelm@32799
  1104
    val (lhs, _) = Logic.dest_equals (Logic.strip_assums_concl prop');
wenzelm@32799
  1105
    val (_, args) = strip_comb lhs;
wenzelm@32975
  1106
    val simps = (if length args = 1 then get_accupd_simps else get_updupd_simps) thy lhs defset;
wenzelm@16973
  1107
  in
wenzelm@36610
  1108
    Goal.prove (ProofContext.init_global thy) [] [] prop'
wenzelm@32799
  1109
      (fn _ =>
wenzelm@32761
  1110
        simp_tac (HOL_basic_ss addsimps (simps @ [K_record_comp])) 1 THEN
wenzelm@32761
  1111
        TRY (simp_tac (HOL_basic_ss addsimps ex_simps addsimprocs ex_simprs) 1))
schirmer@15203
  1112
  end;
schirmer@15015
  1113
schirmer@15215
  1114
schirmer@15059
  1115
local
wenzelm@32761
  1116
wenzelm@32761
  1117
fun eq (s1: string) (s2: string) = (s1 = s2);
wenzelm@32761
  1118
schirmer@16822
  1119
fun has_field extfields f T =
wenzelm@32761
  1120
  exists (fn (eN, _) => exists (eq f o fst) (Symtab.lookup_list extfields eN)) (dest_recTs T);
wenzelm@32761
  1121
wenzelm@32761
  1122
fun K_skeleton n (T as Type (_, [_, kT])) (b as Bound i) (Abs (x, xT, t)) =
wenzelm@32761
  1123
      if null (loose_bnos t) then ((n, kT), (Abs (x, xT, Bound (i + 1)))) else ((n, T), b)
wenzelm@32761
  1124
  | K_skeleton n T b _ = ((n, T), b);
schirmer@25705
  1125
schirmer@15059
  1126
in
wenzelm@32761
  1127
haftmann@38012
  1128
(* simproc *)
wenzelm@32761
  1129
wenzelm@32761
  1130
(*
wenzelm@32761
  1131
  Simplify selections of an record update:
wenzelm@32761
  1132
    (1)  S (S_update k r) = k (S r)
wenzelm@32761
  1133
    (2)  S (X_update k r) = S r
wenzelm@32761
  1134
wenzelm@32761
  1135
  The simproc skips multiple updates at once, eg:
wenzelm@32761
  1136
   S (X_update x (Y_update y (S_update k r))) = k (S r)
wenzelm@32761
  1137
wenzelm@32761
  1138
  But be careful in (2) because of the extensibility of records.
wenzelm@32761
  1139
  - If S is a more-selector we have to make sure that the update on component
wenzelm@32761
  1140
    X does not affect the selected subrecord.
wenzelm@32761
  1141
  - If X is a more-selector we have to make sure that S is not in the updated
wenzelm@32761
  1142
    subrecord.
wenzelm@32761
  1143
*)
haftmann@38012
  1144
val simproc =
wenzelm@38715
  1145
  Simplifier.simproc_global @{theory HOL} "record_simp" ["x"]
wenzelm@32799
  1146
    (fn thy => fn _ => fn t =>
wenzelm@32761
  1147
      (case t of
wenzelm@32799
  1148
        (sel as Const (s, Type (_, [_, rangeS]))) $
wenzelm@32761
  1149
            ((upd as Const (u, Type (_, [_, Type (_, [rT, _])]))) $ k $ r) =>
wenzelm@32799
  1150
          if is_selector thy s andalso is_some (get_updates thy u) then
wenzelm@32799
  1151
            let
wenzelm@38758
  1152
              val {sel_upd = {updates, ...}, extfields, ...} = Data.get thy;
wenzelm@32799
  1153
wenzelm@32799
  1154
              fun mk_eq_terms ((upd as Const (u, Type(_, [kT, _]))) $ k $ r) =
wenzelm@32799
  1155
                    (case Symtab.lookup updates u of
wenzelm@32799
  1156
                      NONE => NONE
wenzelm@32799
  1157
                    | SOME u_name =>
wenzelm@32799
  1158
                        if u_name = s then
wenzelm@32799
  1159
                          (case mk_eq_terms r of
wenzelm@32799
  1160
                            NONE =>
wenzelm@32799
  1161
                              let
wenzelm@32799
  1162
                                val rv = ("r", rT);
wenzelm@32799
  1163
                                val rb = Bound 0;
wenzelm@32799
  1164
                                val (kv, kb) = K_skeleton "k" kT (Bound 1) k;
wenzelm@32799
  1165
                              in SOME (upd $ kb $ rb, kb $ (sel $ rb), [kv, rv]) end
wenzelm@32799
  1166
                          | SOME (trm, trm', vars) =>
wenzelm@32799
  1167
                              let
wenzelm@32799
  1168
                                val (kv, kb) = K_skeleton "k" kT (Bound (length vars)) k;
wenzelm@32799
  1169
                              in SOME (upd $ kb $ trm, kb $ trm', kv :: vars) end)
wenzelm@32799
  1170
                        else if has_field extfields u_name rangeS orelse
wenzelm@32799
  1171
                          has_field extfields s (domain_type kT) then NONE
wenzelm@32799
  1172
                        else
wenzelm@32799
  1173
                          (case mk_eq_terms r of
wenzelm@32799
  1174
                            SOME (trm, trm', vars) =>
wenzelm@32799
  1175
                              let val (kv, kb) = K_skeleton "k" kT (Bound (length vars)) k
wenzelm@32799
  1176
                              in SOME (upd $ kb $ trm, trm', kv :: vars) end
wenzelm@32799
  1177
                          | NONE =>
wenzelm@32799
  1178
                              let
wenzelm@32799
  1179
                                val rv = ("r", rT);
wenzelm@32799
  1180
                                val rb = Bound 0;
wenzelm@32799
  1181
                                val (kv, kb) = K_skeleton "k" kT (Bound 1) k;
wenzelm@32799
  1182
                              in SOME (upd $ kb $ rb, sel $ rb, [kv, rv]) end))
wenzelm@32799
  1183
                | mk_eq_terms _ = NONE;
wenzelm@32799
  1184
            in
wenzelm@32799
  1185
              (case mk_eq_terms (upd $ k $ r) of
wenzelm@32799
  1186
                SOME (trm, trm', vars) =>
wenzelm@32799
  1187
                  SOME
wenzelm@32799
  1188
                    (prove_unfold_defs thy [] []
wenzelm@32799
  1189
                      (list_all (vars, Logic.mk_equals (sel $ trm, trm'))))
wenzelm@32799
  1190
              | NONE => NONE)
wenzelm@32799
  1191
            end
wenzelm@32761
  1192
          else NONE
skalberg@15531
  1193
      | _ => NONE));
wenzelm@7178
  1194
wenzelm@32761
  1195
fun get_upd_acc_cong_thm upd acc thy simpset =
wenzelm@32761
  1196
  let
haftmann@38401
  1197
    val insts = [("upd", cterm_of thy upd), ("ac", cterm_of thy acc)];
wenzelm@32975
  1198
    val prop = Thm.concl_of (named_cterm_instantiate insts updacc_cong_triv);
wenzelm@32761
  1199
  in
wenzelm@36610
  1200
    Goal.prove (ProofContext.init_global thy) [] [] prop
wenzelm@32799
  1201
      (fn _ =>
wenzelm@32975
  1202
        simp_tac simpset 1 THEN
haftmann@34151
  1203
        REPEAT_DETERM (Iso_Tuple_Support.iso_tuple_intros_tac 1) THEN
wenzelm@32975
  1204
        TRY (resolve_tac [updacc_cong_idI] 1))
tsewell@32743
  1205
  end;
tsewell@32743
  1206
wenzelm@32761
  1207
haftmann@38012
  1208
(* upd_simproc *)
wenzelm@32761
  1209
wenzelm@32761
  1210
(*Simplify multiple updates:
wenzelm@32761
  1211
    (1) "N_update y (M_update g (N_update x (M_update f r))) =
schirmer@21226
  1212
          (N_update (y o x) (M_update (g o f) r))"
wenzelm@32761
  1213
    (2)  "r(|M:= M r|) = r"
wenzelm@32761
  1214
wenzelm@32761
  1215
  In both cases "more" updates complicate matters: for this reason
wenzelm@32761
  1216
  we omit considering further updates if doing so would introduce
wenzelm@32761
  1217
  both a more update and an update to a field within it.*)
haftmann@38012
  1218
val upd_simproc =
wenzelm@38715
  1219
  Simplifier.simproc_global @{theory HOL} "record_upd_simp" ["x"]
wenzelm@32799
  1220
    (fn thy => fn _ => fn t =>
tsewell@32743
  1221
      let
wenzelm@32761
  1222
        (*We can use more-updators with other updators as long
wenzelm@32761
  1223
          as none of the other updators go deeper than any more
wenzelm@32761
  1224
          updator. min here is the depth of the deepest other
wenzelm@32761
  1225
          updator, max the depth of the shallowest more updator.*)
tsewell@32743
  1226
        fun include_depth (dep, true) (min, max) =
wenzelm@32761
  1227
              if min <= dep
wenzelm@32761
  1228
              then SOME (min, if dep <= max orelse max = ~1 then dep else max)
wenzelm@32761
  1229
              else NONE
tsewell@32743
  1230
          | include_depth (dep, false) (min, max) =
wenzelm@32761
  1231
              if dep <= max orelse max = ~1
wenzelm@32761
  1232
              then SOME (if min <= dep then dep else min, max)
wenzelm@32761
  1233
              else NONE;
tsewell@32743
  1234
wenzelm@32799
  1235
        fun getupdseq (term as (upd as Const (u, _)) $ f $ tm) min max =
wenzelm@32761
  1236
              (case get_update_details u thy of
wenzelm@32761
  1237
                SOME (s, dep, ismore) =>
wenzelm@32761
  1238
                  (case include_depth (dep, ismore) (min, max) of
wenzelm@32761
  1239
                    SOME (min', max') =>
wenzelm@32761
  1240
                      let val (us, bs, _) = getupdseq tm min' max'
tsewell@32743
  1241
                      in ((upd, s, f) :: us, bs, fastype_of term) end
wenzelm@32761
  1242
                  | NONE => ([], term, HOLogic.unitT))
wenzelm@32761
  1243
              | NONE => ([], term, HOLogic.unitT))
tsewell@32743
  1244
          | getupdseq term _ _ = ([], term, HOLogic.unitT);
tsewell@32743
  1245
tsewell@32743
  1246
        val (upds, base, baseT) = getupdseq t 0 ~1;
tsewell@32743
  1247
wenzelm@32799
  1248
        fun is_upd_noop s (Abs (n, T, Const (s', T') $ tm')) tm =
wenzelm@32761
  1249
              if s = s' andalso null (loose_bnos tm')
wenzelm@32761
  1250
                andalso subst_bound (HOLogic.unit, tm') = tm
wenzelm@32761
  1251
              then (true, Abs (n, T, Const (s', T') $ Bound 1))
wenzelm@32761
  1252
              else (false, HOLogic.unit)
wenzelm@32799
  1253
          | is_upd_noop _ _ _ = (false, HOLogic.unit);
wenzelm@32799
  1254
wenzelm@32799
  1255
        fun get_noop_simps (upd as Const _) (Abs (_, _, (acc as Const _) $ _)) =
wenzelm@32761
  1256
          let
wenzelm@32761
  1257
            val ss = get_sel_upd_defs thy;
tsewell@32743
  1258
            val uathm = get_upd_acc_cong_thm upd acc thy ss;
wenzelm@32761
  1259
          in
wenzelm@35021
  1260
           [Drule.export_without_context (uathm RS updacc_noopE),
wenzelm@35021
  1261
            Drule.export_without_context (uathm RS updacc_noop_compE)]
wenzelm@32761
  1262
          end;
wenzelm@32761
  1263
wenzelm@32974
  1264
        (*If f is constant then (f o g) = f.  We know that K_skeleton
wenzelm@32761
  1265
          only returns constant abstractions thus when we see an
wenzelm@32761
  1266
          abstraction we can discard inner updates.*)
tsewell@32743
  1267
        fun add_upd (f as Abs _) fs = [f]
tsewell@32743
  1268
          | add_upd f fs = (f :: fs);
tsewell@32743
  1269
wenzelm@32761
  1270
        (*mk_updterm returns
wenzelm@32761
  1271
          (orig-term-skeleton, simplified-skeleton,
wenzelm@32761
  1272
            variables, duplicate-updates, simp-flag, noop-simps)
wenzelm@32761
  1273
wenzelm@32761
  1274
          where duplicate-updates is a table used to pass upward
wenzelm@32761
  1275
          the list of update functions which can be composed
wenzelm@32761
  1276
          into an update above them, simp-flag indicates whether
wenzelm@32761
  1277
          any simplification was achieved, and noop-simps are
wenzelm@32761
  1278
          used for eliminating case (2) defined above*)
wenzelm@32761
  1279
        fun mk_updterm ((upd as Const (u, T), s, f) :: upds) above term =
wenzelm@32761
  1280
              let
wenzelm@32761
  1281
                val (lhs, rhs, vars, dups, simp, noops) =
tsewell@32743
  1282
                  mk_updterm upds (Symtab.update (u, ()) above) term;
wenzelm@32761
  1283
                val (fvar, skelf) =
wenzelm@32761
  1284
                  K_skeleton (Long_Name.base_name s) (domain_type T) (Bound (length vars)) f;
wenzelm@32761
  1285
                val (isnoop, skelf') = is_upd_noop s f term;
wenzelm@32761
  1286
                val funT = domain_type T;
wenzelm@35133
  1287
                fun mk_comp_local (f, f') =
wenzelm@35133
  1288
                  Const (@{const_name Fun.comp}, funT --> funT --> funT) $ f $ f';
wenzelm@32761
  1289
              in
wenzelm@32761
  1290
                if isnoop then
wenzelm@32761
  1291
                  (upd $ skelf' $ lhs, rhs, vars,
tsewell@32743
  1292
                    Symtab.update (u, []) dups, true,
tsewell@32743
  1293
                    if Symtab.defined noops u then noops
tsewell@32743
  1294
                    else Symtab.update (u, get_noop_simps upd skelf') noops)
wenzelm@32761
  1295
                else if Symtab.defined above u then
wenzelm@32761
  1296
                  (upd $ skelf $ lhs, rhs, fvar :: vars,
tsewell@32743
  1297
                    Symtab.map_default (u, []) (add_upd skelf) dups,
tsewell@32743
  1298
                    true, noops)
wenzelm@32761
  1299
                else
wenzelm@32761
  1300
                  (case Symtab.lookup dups u of
wenzelm@32761
  1301
                    SOME fs =>
wenzelm@32761
  1302
                     (upd $ skelf $ lhs,
wenzelm@32761
  1303
                      upd $ foldr1 mk_comp_local (add_upd skelf fs) $ rhs,
wenzelm@32761
  1304
                      fvar :: vars, dups, true, noops)
wenzelm@32761
  1305
                  | NONE => (upd $ skelf $ lhs, upd $ skelf $ rhs, fvar :: vars, dups, simp, noops))
wenzelm@32761
  1306
              end
wenzelm@32799
  1307
          | mk_updterm [] _ _ =
wenzelm@32761
  1308
              (Bound 0, Bound 0, [("r", baseT)], Symtab.empty, false, Symtab.empty)
wenzelm@32799
  1309
          | mk_updterm us _ _ = raise TERM ("mk_updterm match", map (fn (x, _, _) => x) us);
wenzelm@32799
  1310
wenzelm@32799
  1311
        val (lhs, rhs, vars, _, simp, noops) = mk_updterm upds Symtab.empty base;
wenzelm@32952
  1312
        val noops' = maps snd (Symtab.dest noops);
tsewell@32743
  1313
      in
tsewell@32743
  1314
        if simp then
wenzelm@32761
  1315
          SOME
haftmann@38012
  1316
            (prove_unfold_defs thy noops' [simproc]
wenzelm@32761
  1317
              (list_all (vars, Logic.mk_equals (lhs, rhs))))
tsewell@32743
  1318
        else NONE
wenzelm@32761
  1319
      end);
wenzelm@32761
  1320
wenzelm@32761
  1321
end;
schirmer@15015
  1322
tsewell@32743
  1323
haftmann@38012
  1324
(* eq_simproc *)
wenzelm@32761
  1325
wenzelm@32974
  1326
(*Look up the most specific record-equality.
wenzelm@32761
  1327
wenzelm@32761
  1328
 Note on efficiency:
wenzelm@32761
  1329
 Testing equality of records boils down to the test of equality of all components.
wenzelm@32761
  1330
 Therefore the complexity is: #components * complexity for single component.
wenzelm@32761
  1331
 Especially if a record has a lot of components it may be better to split up
haftmann@38012
  1332
 the record first and do simplification on that (split_simp_tac).
wenzelm@32761
  1333
 e.g. r(|lots of updates|) = x
wenzelm@32761
  1334
haftmann@38012
  1335
             eq_simproc          split_simp_tac
wenzelm@32761
  1336
 Complexity: #components * #updates     #updates
wenzelm@32761
  1337
*)
haftmann@38012
  1338
val eq_simproc =
wenzelm@38715
  1339
  Simplifier.simproc_global @{theory HOL} "record_eq_simp" ["r = s"]
wenzelm@18858
  1340
    (fn thy => fn _ => fn t =>
haftmann@38864
  1341
      (case t of Const (@{const_name HOL.eq}, Type (_, [T, _])) $ _ $ _ =>
wenzelm@32761
  1342
        (case rec_id ~1 T of
wenzelm@32761
  1343
          "" => NONE
wenzelm@32761
  1344
        | name =>
wenzelm@32761
  1345
            (case get_equalities thy name of
wenzelm@32761
  1346
              NONE => NONE
wenzelm@35410
  1347
            | SOME thm => SOME (thm RS @{thm Eq_TrueI})))
wenzelm@32761
  1348
      | _ => NONE));
wenzelm@32761
  1349
berghofe@14079
  1350
haftmann@38012
  1351
(* split_simproc *)
wenzelm@32761
  1352
wenzelm@32761
  1353
(*Split quantified occurrences of records, for which P holds.  P can peek on the
wenzelm@32761
  1354
  subterm starting at the quantified occurrence of the record (including the quantifier):
wenzelm@32761
  1355
    P t = 0: do not split
wenzelm@32761
  1356
    P t = ~1: completely split
wenzelm@32761
  1357
    P t > 0: split up to given bound of record extensions.*)
haftmann@38012
  1358
fun split_simproc P =
wenzelm@38715
  1359
  Simplifier.simproc_global @{theory HOL} "record_split_simp" ["x"]
wenzelm@18858
  1360
    (fn thy => fn _ => fn t =>
wenzelm@32761
  1361
      (case t of
wenzelm@32799
  1362
        Const (quantifier, Type (_, [Type (_, [T, _]), _])) $ _ =>
wenzelm@35147
  1363
          if quantifier = @{const_name all} orelse
wenzelm@35147
  1364
            quantifier = @{const_name All} orelse
wenzelm@35133
  1365
            quantifier = @{const_name Ex}
wenzelm@35133
  1366
          then
wenzelm@32761
  1367
            (case rec_id ~1 T of
wenzelm@32761
  1368
              "" => NONE
wenzelm@32799
  1369
            | _ =>
wenzelm@32761
  1370
                let val split = P t in
wenzelm@32761
  1371
                  if split <> 0 then
wenzelm@32761
  1372
                    (case get_splits thy (rec_id split T) of
wenzelm@32761
  1373
                      NONE => NONE
wenzelm@32761
  1374
                    | SOME (all_thm, All_thm, Ex_thm, _) =>
wenzelm@32761
  1375
                        SOME
wenzelm@32761
  1376
                          (case quantifier of
wenzelm@35133
  1377
                            @{const_name all} => all_thm
wenzelm@35133
  1378
                          | @{const_name All} => All_thm RS eq_reflection
wenzelm@35133
  1379
                          | @{const_name Ex} => Ex_thm RS eq_reflection
haftmann@38012
  1380
                          | _ => error "split_simproc"))
wenzelm@32761
  1381
                  else NONE
wenzelm@32761
  1382
                end)
wenzelm@32761
  1383
          else NONE
wenzelm@32761
  1384
      | _ => NONE));
wenzelm@7178
  1385
haftmann@38012
  1386
val ex_sel_eq_simproc =
wenzelm@38715
  1387
  Simplifier.simproc_global @{theory HOL} "ex_sel_eq_simproc" ["Ex t"]
wenzelm@18858
  1388
    (fn thy => fn ss => fn t =>
wenzelm@32761
  1389
      let
wenzelm@32761
  1390
        fun prove prop =
schirmer@33691
  1391
          prove_global true thy [] prop
wenzelm@32761
  1392
            (fn _ => simp_tac (Simplifier.inherit_context ss (get_simpset thy)
haftmann@38012
  1393
                addsimps @{thms simp_thms} addsimprocs [split_simproc (K ~1)]) 1);
wenzelm@32761
  1394
wenzelm@32761
  1395
        fun mkeq (lr, Teq, (sel, Tsel), x) i =
wenzelm@32761
  1396
          if is_selector thy sel then
wenzelm@32761
  1397
            let
wenzelm@32761
  1398
              val x' =
wenzelm@32761
  1399
                if not (loose_bvar1 (x, 0))
wenzelm@32761
  1400
                then Free ("x" ^ string_of_int i, range_type Tsel)
wenzelm@32761
  1401
                else raise TERM ("", [x]);
wenzelm@32761
  1402
              val sel' = Const (sel, Tsel) $ Bound 0;
wenzelm@32761
  1403
              val (l, r) = if lr then (sel', x') else (x', sel');
haftmann@38864
  1404
            in Const (@{const_name HOL.eq}, Teq) $ l $ r end
wenzelm@32761
  1405
          else raise TERM ("", [Const (sel, Tsel)]);
wenzelm@32761
  1406
haftmann@38864
  1407
        fun dest_sel_eq (Const (@{const_name HOL.eq}, Teq) $ (Const (sel, Tsel) $ Bound 0) $ X) =
wenzelm@32761
  1408
              (true, Teq, (sel, Tsel), X)
haftmann@38864
  1409
          | dest_sel_eq (Const (@{const_name HOL.eq}, Teq) $ X $ (Const (sel, Tsel) $ Bound 0)) =
wenzelm@32761
  1410
              (false, Teq, (sel, Tsel), X)
wenzelm@32761
  1411
          | dest_sel_eq _ = raise TERM ("", []);
wenzelm@32761
  1412
      in
wenzelm@32761
  1413
        (case t of
wenzelm@35133
  1414
          Const (@{const_name Ex}, Tex) $ Abs (s, T, t) =>
wenzelm@32761
  1415
           (let
wenzelm@35133
  1416
             val eq = mkeq (dest_sel_eq t) 0;
wenzelm@35133
  1417
             val prop =
wenzelm@35133
  1418
               list_all ([("r", T)],
wenzelm@35133
  1419
                 Logic.mk_equals
wenzelm@35133
  1420
                  (Const (@{const_name Ex}, Tex) $ Abs (s, T, eq), HOLogic.true_const));
wenzelm@32761
  1421
            in SOME (prove prop) end
wenzelm@32761
  1422
            handle TERM _ => NONE)
wenzelm@32761
  1423
        | _ => NONE)
wenzelm@32761
  1424
      end);
schirmer@14427
  1425
wenzelm@5698
  1426
haftmann@38012
  1427
(* split_simp_tac *)
wenzelm@32761
  1428
wenzelm@32761
  1429
(*Split (and simplify) all records in the goal for which P holds.
wenzelm@32761
  1430
  For quantified occurrences of a record
wenzelm@32761
  1431
  P can peek on the whole subterm (including the quantifier); for free variables P
wenzelm@32761
  1432
  can only peek on the variable itself.
wenzelm@32761
  1433
  P t = 0: do not split
wenzelm@32761
  1434
  P t = ~1: completely split
wenzelm@32761
  1435
  P t > 0: split up to given bound of record extensions.*)
haftmann@38012
  1436
fun split_simp_tac thms P = CSUBGOAL (fn (cgoal, i) =>
schirmer@14255
  1437
  let
wenzelm@32975
  1438
    val thy = Thm.theory_of_cterm cgoal;
wenzelm@32975
  1439
wenzelm@32975
  1440
    val goal = term_of cgoal;
wenzelm@32975
  1441
    val frees = filter (is_recT o #2) (Term.add_frees goal []);
schirmer@14255
  1442
schirmer@14700
  1443
    val has_rec = exists_Const
schirmer@14255
  1444
      (fn (s, Type (_, [Type (_, [T, _]), _])) =>
wenzelm@35133
  1445
          (s = @{const_name all} orelse s = @{const_name All} orelse s = @{const_name Ex}) andalso
wenzelm@35133
  1446
          is_recT T
schirmer@14255
  1447
        | _ => false);
schirmer@14255
  1448
wenzelm@17261
  1449
    fun mk_split_free_tac free induct_thm i =
wenzelm@32761
  1450
      let
wenzelm@32761
  1451
        val cfree = cterm_of thy free;
wenzelm@32761
  1452
        val _$ (_ $ r) = concl_of induct_thm;
wenzelm@32761
  1453
        val crec = cterm_of thy r;
wenzelm@32761
  1454
        val thm = cterm_instantiate [(crec, cfree)] induct_thm;
wenzelm@32761
  1455
      in
wenzelm@32975
  1456
        simp_tac (HOL_basic_ss addsimps @{thms induct_atomize}) i THEN
wenzelm@32975
  1457
        rtac thm i THEN
wenzelm@32975
  1458
        simp_tac (HOL_basic_ss addsimps @{thms induct_rulify}) i
wenzelm@32761
  1459
      end;
wenzelm@32761
  1460
wenzelm@32975
  1461
    val split_frees_tacs =
wenzelm@32975
  1462
      frees |> map_filter (fn (x, T) =>
wenzelm@32975
  1463
        (case rec_id ~1 T of
wenzelm@32975
  1464
          "" => NONE
wenzelm@32975
  1465
        | _ =>
wenzelm@32975
  1466
            let
wenzelm@32975
  1467
              val free = Free (x, T);
wenzelm@32975
  1468
              val split = P free;
wenzelm@32975
  1469
            in
wenzelm@32975
  1470
              if split <> 0 then
wenzelm@32975
  1471
                (case get_splits thy (rec_id split T) of
wenzelm@32975
  1472
                  NONE => NONE
wenzelm@32975
  1473
                | SOME (_, _, _, induct_thm) =>
wenzelm@32975
  1474
                    SOME (mk_split_free_tac free induct_thm i))
wenzelm@32975
  1475
              else NONE
wenzelm@32975
  1476
            end));
wenzelm@17261
  1477
haftmann@38012
  1478
    val simprocs = if has_rec goal then [split_simproc P] else [];
wenzelm@32761
  1479
    val thms' = K_comp_convs @ thms;
wenzelm@32761
  1480
  in
wenzelm@32975
  1481
    EVERY split_frees_tacs THEN
wenzelm@32975
  1482
    Simplifier.full_simp_tac (get_simpset thy addsimps thms' addsimprocs simprocs) i
wenzelm@32975
  1483
  end);
schirmer@14255
  1484
schirmer@14700
  1485
haftmann@38012
  1486
(* split_tac *)
wenzelm@32761
  1487
wenzelm@35147
  1488
(*Split all records in the goal, which are quantified by !! or ALL.*)
haftmann@38012
  1489
val split_tac = CSUBGOAL (fn (cgoal, i) =>
schirmer@14700
  1490
  let
wenzelm@32975
  1491
    val goal = term_of cgoal;
wenzelm@32975
  1492
schirmer@14700
  1493
    val has_rec = exists_Const
schirmer@14700
  1494
      (fn (s, Type (_, [Type (_, [T, _]), _])) =>
wenzelm@35147
  1495
          (s = @{const_name all} orelse s = @{const_name All}) andalso is_recT T
schirmer@14700
  1496
        | _ => false);
wenzelm@17261
  1497
wenzelm@35240
  1498
    fun is_all (Const (@{const_name all}, _) $ _) = ~1
wenzelm@35240
  1499
      | is_all (Const (@{const_name All}, _) $ _) = ~1
wenzelm@35240
  1500
      | is_all _ = 0;
wenzelm@32761
  1501
  in
wenzelm@32761
  1502
    if has_rec goal then
haftmann@38012
  1503
      Simplifier.full_simp_tac (HOL_basic_ss addsimprocs [split_simproc is_all]) i
wenzelm@32975
  1504
    else no_tac
wenzelm@32975
  1505
  end);
schirmer@14700
  1506
wenzelm@32335
  1507
wenzelm@6358
  1508
(* wrapper *)
wenzelm@6358
  1509
haftmann@38012
  1510
val split_name = "record_split_tac";
haftmann@38012
  1511
val split_wrapper = (split_name, fn tac => split_tac ORELSE' tac);
wenzelm@5698
  1512
wenzelm@16330
  1513
wenzelm@16330
  1514
wenzelm@4867
  1515
(** theory extender interface **)
wenzelm@4867
  1516
wenzelm@4867
  1517
(* prepare arguments *)
wenzelm@4867
  1518
wenzelm@27278
  1519
fun read_typ ctxt raw_T env =
wenzelm@4867
  1520
  let
wenzelm@27278
  1521
    val ctxt' = fold (Variable.declare_typ o TFree) env ctxt;
wenzelm@27278
  1522
    val T = Syntax.read_typ ctxt' raw_T;
wenzelm@29270
  1523
    val env' = OldTerm.add_typ_tfrees (T, env);
wenzelm@27278
  1524
  in (T, env') end;
wenzelm@4867
  1525
wenzelm@27278
  1526
fun cert_typ ctxt raw_T env =
wenzelm@27278
  1527
  let
wenzelm@27278
  1528
    val thy = ProofContext.theory_of ctxt;
wenzelm@32761
  1529
    val T = Type.no_tvars (Sign.certify_typ thy raw_T)
wenzelm@32761
  1530
      handle TYPE (msg, _, _) => error msg;
wenzelm@29270
  1531
    val env' = OldTerm.add_typ_tfrees (T, env);
wenzelm@27278
  1532
  in (T, env') end;
wenzelm@27278
  1533
wenzelm@4867
  1534
schirmer@14700
  1535
(* attributes *)
schirmer@14700
  1536
wenzelm@33368
  1537
fun case_names_fields x = Rule_Cases.case_names ["fields"] x;
wenzelm@24830
  1538
fun induct_type_global name = [case_names_fields, Induct.induct_type name];
wenzelm@24830
  1539
fun cases_type_global name = [case_names_fields, Induct.cases_type name];
schirmer@14700
  1540
wenzelm@32335
  1541
schirmer@14700
  1542
(* tactics *)
schirmer@14700
  1543
schirmer@14700
  1544
fun simp_all_tac ss simps = ALLGOALS (Simplifier.asm_full_simp_tac (ss addsimps simps));
schirmer@14700
  1545
wenzelm@32761
  1546
(*Do case analysis / induction according to rule on last parameter of ith subgoal
wenzelm@32761
  1547
  (or on s if there are no parameters).
wenzelm@32761
  1548
  Instatiation of record variable (and predicate) in rule is calculated to
wenzelm@32761
  1549
  avoid problems with higher order unification.*)
wenzelm@32975
  1550
fun try_param_tac s rule = CSUBGOAL (fn (cgoal, i) =>
schirmer@14700
  1551
  let
wenzelm@32975
  1552
    val cert = Thm.cterm_of (Thm.theory_of_cterm cgoal);
wenzelm@32975
  1553
wenzelm@32975
  1554
    val g = Thm.term_of cgoal;
schirmer@14700
  1555
    val params = Logic.strip_params g;
schirmer@14700
  1556
    val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl g);
wenzelm@32975
  1557
    val rule' = Thm.lift_rule cgoal rule;
schirmer@14700
  1558
    val (P, ys) = strip_comb (HOLogic.dest_Trueprop
schirmer@14700
  1559
      (Logic.strip_assums_concl (prop_of rule')));
wenzelm@32761
  1560
    (*ca indicates if rule is a case analysis or induction rule*)
wenzelm@32761
  1561
    val (x, ca) =
haftmann@33957
  1562
      (case rev (drop (length params) ys) of
schirmer@14700
  1563
        [] => (head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
schirmer@14700
  1564
          (hd (rev (Logic.strip_assums_hyp (hd (prems_of rule')))))))), true)
schirmer@14700
  1565
      | [x] => (head_of x, false));
wenzelm@38758
  1566
    val rule'' =
wenzelm@38758
  1567
      cterm_instantiate
wenzelm@38758
  1568
        (map (pairself cert)
wenzelm@38758
  1569
          (case rev params of
wenzelm@38758
  1570
            [] =>
wenzelm@38758
  1571
              (case AList.lookup (op =) (Term.add_frees g []) s of
wenzelm@40315
  1572
                NONE => error "try_param_tac: no such variable"
wenzelm@38758
  1573
              | SOME T => [(P, if ca then concl else lambda (Free (s, T)) concl), (x, Free (s, T))])
wenzelm@38758
  1574
          | (_, T) :: _ =>
wenzelm@38758
  1575
              [(P, list_abs (params, if ca then concl else incr_boundvars 1 (Abs (s, T, concl)))),
wenzelm@38758
  1576
                (x, list_abs (params, Bound 0))])) rule';
wenzelm@32975
  1577
  in compose_tac (false, rule'', nprems_of rule) i end);
schirmer@14700
  1578
schirmer@15215
  1579
wenzelm@32799
  1580
fun extension_definition name fields alphas zeta moreT more vars thy =
wenzelm@17261
  1581
  let
wenzelm@35239
  1582
    val base_name = Long_Name.base_name name;
wenzelm@35239
  1583
wenzelm@32977
  1584
    val fieldTs = map snd fields;
wenzelm@35239
  1585
    val fields_moreTs = fieldTs @ [moreT];
wenzelm@35239
  1586
wenzelm@32761
  1587
    val alphas_zeta = alphas @ [zeta];
wenzelm@35239
  1588
wenzelm@35239
  1589
    val ext_binding = Binding.name (suffix extN base_name);
wenzelm@35239
  1590
    val ext_name = suffix extN name;
haftmann@38533
  1591
    val ext_tyco = suffix ext_typeN name
haftmann@38533
  1592
    val extT = Type (ext_tyco, map TFree alphas_zeta);
wenzelm@35239
  1593
    val ext_type = fields_moreTs ---> extT;
wenzelm@35239
  1594
wenzelm@35239
  1595
wenzelm@35239
  1596
    (* the tree of new types that will back the record extension *)
wenzelm@32767
  1597
haftmann@34151
  1598
    val mktreeV = Balanced_Tree.make Iso_Tuple_Support.mk_cons_tuple;
haftmann@34151
  1599
haftmann@34151
  1600
    fun mk_iso_tuple (left, right) (thy, i) =
wenzelm@32761
  1601
      let
wenzelm@32761
  1602
        val suff = if i = 0 then ext_typeN else inner_typeN ^ string_of_int i;
wenzelm@35239
  1603
        val ((_, cons), thy') = thy
wenzelm@35239
  1604
          |> Iso_Tuple_Support.add_iso_tuple_type
wenzelm@38758
  1605
            (Binding.suffix_name suff (Binding.name base_name), alphas_zeta)
wenzelm@38758
  1606
              (fastype_of left, fastype_of right);
wenzelm@32761
  1607
      in
wenzelm@32764
  1608
        (cons $ left $ right, (thy', i + 1))
wenzelm@32761
  1609
      end;
wenzelm@32761
  1610
haftmann@34151
  1611
    (*trying to create a 1-element iso_tuple will fail, and is pointless anyway*)
haftmann@34151
  1612
    fun mk_even_iso_tuple [arg] = pair arg
haftmann@34151
  1613
      | mk_even_iso_tuple args = mk_iso_tuple (Iso_Tuple_Support.dest_cons_tuple (mktreeV args));
tsewell@32743
  1614
tsewell@32743
  1615
    fun build_meta_tree_type i thy vars more =
wenzelm@32761
  1616
      let val len = length vars in
wenzelm@32764
  1617
        if len < 1 then raise TYPE ("meta_tree_type args too short", [], vars)
wenzelm@32761
  1618
        else if len > 16 then
wenzelm@32761
  1619
          let
wenzelm@32761
  1620
            fun group16 [] = []
haftmann@33957
  1621
              | group16 xs = take 16 xs :: group16 (drop 16 xs);
wenzelm@32761
  1622
            val vars' = group16 vars;
haftmann@34151
  1623
            val (composites, (thy', i')) = fold_map mk_even_iso_tuple vars' (thy, i);
wenzelm@32761
  1624
          in
wenzelm@32761
  1625
            build_meta_tree_type i' thy' composites more
wenzelm@32761
  1626
          end
wenzelm@32761
  1627
        else
haftmann@34151
  1628
          let val (term, (thy', _)) = mk_iso_tuple (mktreeV vars, more) (thy, 0)
wenzelm@32761
  1629
          in (term, thy') end
wenzelm@32761
  1630
      end;
tsewell@32743
  1631
tsewell@32743
  1632
    val _ = timing_msg "record extension preparing definitions";
tsewell@32743
  1633
wenzelm@32761
  1634
tsewell@32743
  1635
    (* 1st stage part 1: introduce the tree of new types *)
wenzelm@32761
  1636
tsewell@32743
  1637
    fun get_meta_tree () = build_meta_tree_type 1 thy vars more;
tsewell@32743
  1638
    val (ext_body, typ_thy) =
tsewell@32743
  1639
      timeit_msg "record extension nested type def:" get_meta_tree;
tsewell@32743
  1640
wenzelm@32761
  1641
schirmer@14700
  1642
    (* prepare declarations and definitions *)
wenzelm@17261
  1643
tsewell@32743
  1644
    (* 1st stage part 2: define the ext constant *)
wenzelm@32761
  1645
wenzelm@35239
  1646
    fun mk_ext args = list_comb (Const (ext_name, ext_type), args);
wenzelm@35239
  1647
    val ext_spec = Logic.mk_equals (mk_ext (vars @ [more]), ext_body);
wenzelm@35239
  1648
schirmer@16379
  1649
    fun mk_defs () =
tsewell@32743
  1650
      typ_thy
wenzelm@35239
  1651
      |> Sign.declare_const ((ext_binding, ext_type), NoSyn) |> snd
wenzelm@39557
  1652
      |> Global_Theory.add_defs false [((Thm.def_binding ext_binding, ext_spec), [])]
schirmer@33691
  1653
      ||> Theory.checkpoint
tsewell@32743
  1654
    val ([ext_def], defs_thy) =
tsewell@32743
  1655
      timeit_msg "record extension constructor def:" mk_defs;
wenzelm@17261
  1656
wenzelm@32799
  1657
schirmer@14700
  1658
    (* prepare propositions *)
wenzelm@32799
  1659
schirmer@16379
  1660
    val _ = timing_msg "record extension preparing propositions";
wenzelm@32761
  1661
    val vars_more = vars @ [more];
wenzelm@32761
  1662
    val variants = map (fn Free (x, _) => x) vars_more;
schirmer@15215
  1663
    val ext = mk_ext vars_more;
wenzelm@32761
  1664
    val s = Free (rN, extT);
wenzelm@32764
  1665
    val P = Free (Name.variant variants "P", extT --> HOLogic.boolT);
wenzelm@17261
  1666
schirmer@14700
  1667
    val inject_prop =
wenzelm@32761
  1668
      let val vars_more' = map (fn (Free (x, T)) => Free (x ^ "'", T)) vars_more in
wenzelm@32761
  1669
        HOLogic.mk_conj (HOLogic.eq_const extT $
wenzelm@32761
  1670
          mk_ext vars_more $ mk_ext vars_more', HOLogic.true_const)
wenzelm@32761
  1671
        ===
wenzelm@32761
  1672
        foldr1 HOLogic.mk_conj
wenzelm@32761
  1673
          (map HOLogic.mk_eq (vars_more ~~ vars_more') @ [HOLogic.true_const])
schirmer@14700
  1674
      end;
wenzelm@17261
  1675
schirmer@14700
  1676
    val induct_prop =
schirmer@15012
  1677
      (All (map dest_Free vars_more) (Trueprop (P $ ext)), Trueprop (P $ s));
schirmer@15012
  1678
schirmer@15015
  1679
    val split_meta_prop =
wenzelm@32799
  1680
      let val P = Free (Name.variant variants "P", extT --> Term.propT) in
wenzelm@17261
  1681
        Logic.mk_equals
schirmer@15015
  1682
         (All [dest_Free s] (P $ s), All (map dest_Free vars_more) (P $ ext))
wenzelm@17261
  1683
      end;
schirmer@15015
  1684
schirmer@33691
  1685
    val prove_standard = prove_future_global true defs_thy;
wenzelm@17261
  1686
tsewell@32743
  1687
    fun inject_prf () =
wenzelm@32761
  1688
      simplify HOL_ss
wenzelm@32761
  1689
        (prove_standard [] inject_prop
wenzelm@32799
  1690
          (fn _ =>
wenzelm@32975
  1691
            simp_tac (HOL_basic_ss addsimps [ext_def]) 1 THEN
wenzelm@32975
  1692
            REPEAT_DETERM
wenzelm@32975
  1693
              (rtac refl_conj_eq 1 ORELSE
haftmann@34151
  1694
                Iso_Tuple_Support.iso_tuple_intros_tac 1 ORELSE
wenzelm@32975
  1695
                rtac refl 1)));
tsewell@32743
  1696
schirmer@15012
  1697
    val inject = timeit_msg "record extension inject proof:" inject_prf;
schirmer@14700
  1698
wenzelm@32761
  1699
    (*We need a surjection property r = (| f = f r, g = g r ... |)
wenzelm@32761
  1700
      to prove other theorems. We haven't given names to the accessors
wenzelm@32761
  1701
      f, g etc yet however, so we generate an ext structure with
wenzelm@32761
  1702
      free variables as all arguments and allow the introduction tactic to
wenzelm@35021
  1703
      operate on it as far as it can. We then use Drule.export_without_context
wenzelm@35021
  1704
      to convert the free variables into unifiable variables and unify them with
wenzelm@32761
  1705
      (roughly) the definition of the accessor.*)
wenzelm@32761
  1706
    fun surject_prf () =
wenzelm@32761
  1707
      let
tsewell@32743
  1708
        val cterm_ext = cterm_of defs_thy ext;
wenzelm@32761
  1709
        val start = named_cterm_instantiate [("y", cterm_ext)] surject_assist_idE;
wenzelm@32761
  1710
        val tactic1 =
wenzelm@32761
  1711
          simp_tac (HOL_basic_ss addsimps [ext_def]) 1 THEN
haftmann@34151
  1712
          REPEAT_ALL_NEW Iso_Tuple_Support.iso_tuple_intros_tac 1;
wenzelm@32761
  1713
        val tactic2 = REPEAT (rtac surject_assistI 1 THEN rtac refl 1);
wenzelm@32972
  1714
        val [halfway] = Seq.list_of (tactic1 start);
wenzelm@35021
  1715
        val [surject] = Seq.list_of (tactic2 (Drule.export_without_context halfway));
tsewell@32743
  1716
      in
tsewell@32743
  1717
        surject
tsewell@32743
  1718
      end;
tsewell@32743
  1719
    val surject = timeit_msg "record extension surjective proof:" surject_prf;
tsewell@32743
  1720
tsewell@32743
  1721
    fun split_meta_prf () =
wenzelm@32761
  1722
      prove_standard [] split_meta_prop
wenzelm@32799
  1723
        (fn _ =>
wenzelm@32975
  1724
          EVERY1
wenzelm@32975
  1725
           [rtac equal_intr_rule, Goal.norm_hhf_tac,
wenzelm@32975
  1726
            etac meta_allE, atac,
wenzelm@32975
  1727
            rtac (prop_subst OF [surject]),
wenzelm@32975
  1728
            REPEAT o etac meta_allE, atac]);
tsewell@32743
  1729
    val split_meta = timeit_msg "record extension split_meta proof:" split_meta_prf;
tsewell@32743
  1730
schirmer@15012
  1731
    fun induct_prf () =
wenzelm@32761
  1732
      let val (assm, concl) = induct_prop in
wenzelm@32761
  1733
        prove_standard [assm] concl
wenzelm@32761
  1734
          (fn {prems, ...} =>
wenzelm@32975
  1735
            cut_rules_tac [split_meta RS Drule.equal_elim_rule2] 1 THEN
wenzelm@32975
  1736
            resolve_tac prems 2 THEN
wenzelm@32975
  1737
            asm_simp_tac HOL_ss 1)
wenzelm@32761
  1738
      end;
schirmer@15012
  1739
    val induct = timeit_msg "record extension induct proof:" induct_prf;
schirmer@14700
  1740
wenzelm@35138
  1741
    val ([induct', inject', surjective', split_meta'], thm_thy) =
wenzelm@17261
  1742
      defs_thy
wenzelm@39557
  1743
      |> Global_Theory.add_thms (map (Thm.no_attributes o apfst Binding.name)
wenzelm@35138
  1744
           [("ext_induct", induct),
wenzelm@35138
  1745
            ("ext_inject", inject),
tsewell@32744
  1746
            ("ext_surjective", surject),
haftmann@38533
  1747
            ("ext_split", split_meta)]);
haftmann@38533
  1748
wenzelm@38758
  1749
  in
wenzelm@38758
  1750
    (((ext_name, ext_type), (ext_tyco, alphas_zeta),
wenzelm@38758
  1751
      extT, induct', inject', surjective', split_meta', ext_def), thm_thy)
wenzelm@38758
  1752
  end;
wenzelm@32761
  1753
wenzelm@32761
  1754
fun chunks [] [] = []
wenzelm@32761
  1755
  | chunks [] xs = [xs]
haftmann@33957
  1756
  | chunks (l :: ls) xs = take l xs :: chunks ls (drop l xs);
wenzelm@17261
  1757
wenzelm@32764
  1758
fun chop_last [] = error "chop_last: list should not be empty"
wenzelm@32761
  1759
  | chop_last [x] = ([], x)
wenzelm@32761
  1760
  | chop_last (x :: xs) = let val (tl, l) = chop_last xs in (x :: tl, l) end;
wenzelm@32761
  1761
wenzelm@32799
  1762
fun subst_last _ [] = error "subst_last: list should not be empty"
wenzelm@32799
  1763
  | subst_last s [_] = [s]
wenzelm@32761
  1764
  | subst_last s (x :: xs) = x :: subst_last s xs;
wenzelm@32761
  1765
wenzelm@32761
  1766
wenzelm@32761
  1767
(* mk_recordT *)
wenzelm@32761
  1768
wenzelm@38758
  1769
(*build up the record type from the current extension tpye extT and a list
wenzelm@32761
  1770
  of parent extensions, starting with the root of the record hierarchy*)
haftmann@21078
  1771
fun mk_recordT extT =
wenzelm@32761
  1772
  fold_rev (fn (parent, Ts) => fn T => Type (parent, subst_last T Ts)) extT;
schirmer@15215
  1773
schirmer@15215
  1774
schirmer@15215
  1775
fun obj_to_meta_all thm =
schirmer@15215
  1776
  let
wenzelm@32761
  1777
    fun E thm =  (* FIXME proper name *)
wenzelm@35239
  1778
      (case SOME (spec OF [thm]) handle THM _ => NONE of
wenzelm@32761
  1779
        SOME thm' => E thm'
wenzelm@32761
  1780
      | NONE => thm);
schirmer@15215
  1781
    val th1 = E thm;
schirmer@15215
  1782
    val th2 = Drule.forall_intr_vars th1;
schirmer@15215
  1783
  in th2 end;
schirmer@15215
  1784
schirmer@15215
  1785
fun meta_to_obj_all thm =
schirmer@15215
  1786
  let
wenzelm@26626
  1787
    val thy = Thm.theory_of_thm thm;
wenzelm@26626
  1788
    val prop = Thm.prop_of thm;
schirmer@15215
  1789
    val params = Logic.strip_params prop;
schirmer@15215
  1790
    val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl prop);
wenzelm@32761
  1791
    val ct = cterm_of thy (HOLogic.mk_Trueprop (HOLogic.list_all (params, concl)));
schirmer@15215
  1792
    val thm' = Seq.hd (REPEAT (rtac allI 1) (Thm.trivial ct));
wenzelm@32761
  1793
  in Thm.implies_elim thm' thm end;
schirmer@15215
  1794
schirmer@15215
  1795
haftmann@38533
  1796
(* code generation *)
haftmann@38533
  1797
haftmann@38544
  1798
fun instantiate_random_record tyco vs extN Ts thy =
haftmann@38544
  1799
  let
haftmann@38544
  1800
    val size = @{term "i::code_numeral"};
haftmann@38544
  1801
    fun termifyT T = HOLogic.mk_prodT (T, @{typ "unit => term"});
haftmann@38544
  1802
    val T = Type (tyco, map TFree vs);
haftmann@38544
  1803
    val Tm = termifyT T;
haftmann@38544
  1804
    val params = Name.names Name.context "x" Ts;
haftmann@38544
  1805
    val lhs = HOLogic.mk_random T size;
haftmann@38544
  1806
    val tc = HOLogic.mk_return Tm @{typ Random.seed}
haftmann@38544
  1807
      (HOLogic.mk_valtermify_app extN params T);
wenzelm@38758
  1808
    val rhs =
wenzelm@38758
  1809
      HOLogic.mk_ST
wenzelm@38758
  1810
        (map (fn (v, T') =>
wenzelm@38758
  1811
          ((HOLogic.mk_random T' size, @{typ Random.seed}), SOME (v, termifyT T'))) params)
haftmann@38544
  1812
        tc @{typ Random.seed} (SOME Tm, @{typ Random.seed});
haftmann@38544
  1813
    val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
wenzelm@41576
  1814
  in
haftmann@38544
  1815
    thy
haftmann@38544
  1816
    |> Class.instantiation ([tyco], vs, @{sort random})
haftmann@38544
  1817
    |> `(fn lthy => Syntax.check_term lthy eq)
haftmann@38544
  1818
    |-> (fn eq => Specification.definition (NONE, (apfst Binding.conceal Attrib.empty_binding, eq)))
haftmann@38544
  1819
    |> snd
haftmann@38544
  1820
    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
haftmann@38544
  1821
  end;
haftmann@38544
  1822
haftmann@38544
  1823
fun ensure_random_record ext_tyco vs extN Ts thy =
haftmann@38544
  1824
  let
haftmann@38544
  1825
    val algebra = Sign.classes_of thy;
haftmann@38544
  1826
    val has_inst = can (Sorts.mg_domain algebra ext_tyco) @{sort random};
wenzelm@41576
  1827
  in
wenzelm@41576
  1828
    if has_inst then thy
wenzelm@41576
  1829
    else
bulwahn@41928
  1830
      (case Quickcheck_Common.perhaps_constrain thy (map (rpair @{sort random}) Ts) vs of
wenzelm@41576
  1831
        SOME constrain =>
wenzelm@41576
  1832
          instantiate_random_record ext_tyco (map constrain vs) extN
wenzelm@41576
  1833
            ((map o map_atyps) (fn TFree v => TFree (constrain v)) Ts) thy
wenzelm@41576
  1834
      | NONE => thy)
haftmann@38544
  1835
  end;
haftmann@38544
  1836
haftmann@38533
  1837
fun add_code ext_tyco vs extT ext simps inject thy =
haftmann@38533
  1838
  let
wenzelm@38758
  1839
    val eq =
wenzelm@38758
  1840
      (HOLogic.mk_Trueprop o HOLogic.mk_eq)
haftmann@38857
  1841
        (Const (@{const_name HOL.equal}, extT --> extT --> HOLogic.boolT),
haftmann@38864
  1842
         Const (@{const_name HOL.eq}, extT --> extT --> HOLogic.boolT));
wenzelm@38758
  1843
    fun tac eq_def =
wenzelm@38758
  1844
      Class.intro_classes_tac []
haftmann@38533
  1845
      THEN (Simplifier.rewrite_goals_tac [Simpdata.mk_eq eq_def])
haftmann@38533
  1846
      THEN ALLGOALS (rtac @{thm refl});
haftmann@38533
  1847
    fun mk_eq thy eq_def = Simplifier.rewrite_rule
haftmann@38533
  1848
      [(AxClass.unoverload thy o Thm.symmetric o Simpdata.mk_eq) eq_def] inject;
wenzelm@38758
  1849
    fun mk_eq_refl thy =
haftmann@38857
  1850
      @{thm equal_refl}
haftmann@38533
  1851
      |> Thm.instantiate
wenzelm@41576
  1852
        ([pairself (ctyp_of thy) (TVar (("'a", 0), @{sort equal}), Logic.varifyT_global extT)], [])
haftmann@38533
  1853
      |> AxClass.unoverload thy;
haftmann@38533
  1854
  in
haftmann@38533
  1855
    thy
haftmann@38533
  1856
    |> Code.add_datatype [ext]
haftmann@38533
  1857
    |> fold Code.add_default_eqn simps
haftmann@38857
  1858
    |> Class.instantiation ([ext_tyco], vs, [HOLogic.class_equal])
haftmann@38533
  1859
    |> `(fn lthy => Syntax.check_term lthy eq)
haftmann@38533
  1860
    |-> (fn eq => Specification.definition
wenzelm@41576
  1861
          (NONE, (Attrib.empty_binding, eq)))
haftmann@38533
  1862
    |-> (fn (_, (_, eq_def)) =>
haftmann@38533
  1863
       Class.prove_instantiation_exit_result Morphism.thm
wenzelm@41576
  1864
          (fn _ => fn eq_def => tac eq_def) eq_def)
wenzelm@41576
  1865
    |-> (fn eq_def => fn thy =>
wenzelm@41576
  1866
          thy |> Code.del_eqn eq_def |> Code.add_default_eqn (mk_eq thy eq_def))
haftmann@38533
  1867
    |> (fn thy => Code.add_nbe_default_eqn (mk_eq_refl thy) thy)
wenzelm@40844
  1868
    |> ensure_random_record ext_tyco vs (fst ext) (binder_types (snd ext))
haftmann@38533
  1869
  end;
haftmann@38533
  1870
haftmann@38533
  1871
haftmann@38012
  1872
(* definition *)
haftmann@38012
  1873
haftmann@38012
  1874
fun definition (alphas, binding) parent (parents: parent_info list) raw_fields thy =
schirmer@14700
  1875
  let
haftmann@37470
  1876
    val prefix = Binding.name_of binding;
wenzelm@35239
  1877
    val name = Sign.full_name thy binding;
haftmann@37470
  1878
    val full = Sign.full_name_path thy prefix;
schirmer@14700
  1879
wenzelm@35136
  1880
    val bfields = map (fn (x, T, _) => (x, T)) raw_fields;
wenzelm@35136
  1881
    val field_syntax = map #3 raw_fields;
schirmer@14700
  1882
wenzelm@32952
  1883
    val parent_fields = maps #fields parents;
schirmer@14700
  1884
    val parent_chunks = map (length o #fields) parents;
schirmer@14700
  1885
    val parent_names = map fst parent_fields;
schirmer@14700
  1886
    val parent_types = map snd parent_fields;
schirmer@14700
  1887
    val parent_fields_len = length parent_fields;
wenzelm@35239
  1888
    val parent_variants =
wenzelm@35239
  1889
      Name.variant_list [moreN, rN, rN ^ "'", wN] (map Long_Name.base_name parent_names);
haftmann@37470
  1890
    val parent_vars = map2 (curry Free) parent_variants parent_types;
schirmer@14700
  1891
    val parent_len = length parents;
schirmer@14700
  1892
schirmer@14700
  1893
    val fields = map (apfst full) bfields;
schirmer@14700
  1894
    val names = map fst fields;
schirmer@14700
  1895
    val types = map snd fields;
wenzelm@36151
  1896
    val alphas_fields = fold Term.add_tfreesT types [];
haftmann@33049
  1897
    val alphas_ext = inter (op =) alphas_fields alphas;
schirmer@14700
  1898
    val len = length fields;
wenzelm@30715
  1899
    val variants =
wenzelm@32764
  1900
      Name.variant_list (moreN :: rN :: (rN ^ "'") :: wN :: parent_variants)
wenzelm@35136
  1901
        (map (Binding.name_of o fst) bfields);
haftmann@37470
  1902
    val vars = map2 (curry Free) variants types;
schirmer@14700
  1903
    val named_vars = names ~~ vars;
schirmer@14700
  1904
    val idxms = 0 upto len;
schirmer@14700
  1905
schirmer@14700
  1906
    val all_fields = parent_fields @ fields;
schirmer@14700
  1907
    val all_types = parent_types @ types;
schirmer@14700
  1908
    val all_variants = parent_variants @ variants;
schirmer@14700
  1909
    val all_vars = parent_vars @ vars;
schirmer@14700
  1910
    val all_named_vars = (parent_names ~~ parent_vars) @ named_vars;
schirmer@14700
  1911
wenzelm@36151
  1912
    val zeta = (Name.variant (map #1 alphas) "'z", HOLogic.typeS);
wenzelm@36151
  1913
    val moreT = TFree zeta;
schirmer@14700
  1914
    val more = Free (moreN, moreT);
wenzelm@35136
  1915
    val full_moreN = full (Binding.name moreN);
wenzelm@35136
  1916
    val bfields_more = bfields @ [(Binding.name moreN, moreT)];
wenzelm@32761
  1917
    val fields_more = fields @ [(full_moreN, moreT)];
wenzelm@32761
  1918
    val named_vars_more = named_vars @ [(full_moreN, more)];
schirmer@14700
  1919
    val all_vars_more = all_vars @ [more];
wenzelm@32761
  1920
    val all_named_vars_more = all_named_vars @ [(full_moreN, more)];
wenzelm@32761
  1921
wenzelm@17261
  1922
wenzelm@35239
  1923
    (* 1st stage: ext_thy *)
wenzelm@35239
  1924
wenzelm@35239
  1925
    val extension_name = full binding;
wenzelm@35239
  1926
wenzelm@38758
  1927
    val ((ext, (ext_tyco, vs),
wenzelm@38758
  1928
        extT, ext_induct, ext_inject, ext_surjective, ext_split, ext_def), ext_thy) =
schirmer@14700
  1929
      thy
wenzelm@35239
  1930
      |> Sign.qualified_path false binding
wenzelm@35239
  1931
      |> extension_definition extension_name fields alphas_ext zeta moreT more vars;
schirmer@14700
  1932
wenzelm@17261
  1933
    val _ = timing_msg "record preparing definitions";
schirmer@14700
  1934
    val Type extension_scheme = extT;
schirmer@14700
  1935
    val extension_name = unsuffix ext_typeN (fst extension_scheme);
wenzelm@32761
  1936
    val extension = let val (n, Ts) = extension_scheme in (n, subst_last HOLogic.unitT Ts) end;
wenzelm@35239
  1937
    val extension_names = map (unsuffix ext_typeN o fst o #extension) parents @ [extension_name];
wenzelm@32764
  1938
    val extension_id = implode extension_names;
wenzelm@17261
  1939
haftmann@33957
  1940
    fun rec_schemeT n = mk_recordT (map #extension (drop n parents)) extT;
schirmer@14700
  1941
    val rec_schemeT0 = rec_schemeT 0;
schirmer@14700
  1942
wenzelm@17261
  1943
    fun recT n =
wenzelm@32972
  1944
      let val (c, Ts) = extension in
haftmann@33957
  1945
        mk_recordT (map #extension (drop n parents))
wenzelm@32972
  1946
          (Type (c, subst_last HOLogic.unitT Ts))
wenzelm@32972
  1947
      end;
schirmer@14700
  1948
    val recT0 = recT 0;
wenzelm@17261
  1949
schirmer@14700
  1950
    fun mk_rec args n =
wenzelm@32761
  1951
      let
wenzelm@32761
  1952
        val (args', more) = chop_last args;
wenzelm@32974
  1953
        fun mk_ext' ((name, T), args) more = mk_ext (name, T) (args @ [more]);
wenzelm@32761
  1954
        fun build Ts =
wenzelm@35430
  1955
          fold_rev mk_ext' (drop n ((extension_names ~~ Ts) ~~ chunks parent_chunks args')) more;
wenzelm@17261
  1956
      in
wenzelm@17261
  1957
        if more = HOLogic.unit
haftmann@33063
  1958
        then build (map_range recT (parent_len + 1))
haftmann@33063
  1959
        else build (map_range rec_schemeT (parent_len + 1))
schirmer@14700
  1960
      end;
wenzelm@17261
  1961
schirmer@14700
  1962
    val r_rec0 = mk_rec all_vars_more 0;
wenzelm@32761
  1963
    val r_rec_unit0 = mk_rec (all_vars @ [HOLogic.unit]) 0;
schirmer@14700
  1964
wenzelm@35430
  1965
    fun r n = Free (rN, rec_schemeT n);
schirmer@14700
  1966
    val r0 = r 0;
wenzelm@35430
  1967
    fun r_unit n = Free (rN, recT n);
schirmer@14700
  1968
    val r_unit0 = r_unit 0;
wenzelm@35430
  1969
    val w = Free (wN, rec_schemeT 0);
schirmer@14700
  1970
wenzelm@32761
  1971
wenzelm@35239
  1972
    (* print translations *)
wenzelm@35239
  1973
wenzelm@35149
  1974
    val record_ext_type_abbr_tr's =
wenzelm@32761
  1975
      let
wenzelm@35430
  1976
        val trname = hd extension_names;
wenzelm@35148
  1977
        val last_ext = unsuffix ext_typeN (fst extension);
wenzelm@35430
  1978
      in [record_ext_type_abbr_tr' name alphas zeta last_ext rec_schemeT0 trname] end;
wenzelm@35149
  1979
wenzelm@35149
  1980
    val record_ext_type_tr's =
wenzelm@32761
  1981
      let
wenzelm@35149
  1982
        (*avoid conflict with record_type_abbr_tr's*)
wenzelm@35430
  1983
        val trnames = if parent_len > 0 then [extension_name] else [];
wenzelm@35149
  1984
      in map record_ext_type_tr' trnames end;
schirmer@14700
  1985
wenzelm@35239
  1986
    val advanced_print_translation =
wenzelm@35239
  1987
      map field_update_tr' (full_moreN :: names) @ [record_ext_tr' extension_name] @
wenzelm@35239
  1988
      record_ext_type_tr's @ record_ext_type_abbr_tr's;
wenzelm@35239
  1989
wenzelm@17261
  1990
schirmer@14700
  1991
    (* prepare declarations *)
schirmer@14700
  1992
wenzelm@35136
  1993
    val sel_decls = map (mk_selC rec_schemeT0 o apfst Binding.name_of) bfields_more;
wenzelm@35136
  1994
    val upd_decls = map (mk_updC updateN rec_schemeT0 o apfst Binding.name_of) bfields_more;
schirmer@14700
  1995
    val make_decl = (makeN, all_types ---> recT0);
wenzelm@17261
  1996
    val fields_decl = (fields_selN, types ---> Type extension);
schirmer@14700
  1997
    val extend_decl = (extendN, recT0 --> moreT --> rec_schemeT0);
schirmer@14700
  1998
    val truncate_decl = (truncateN, rec_schemeT0 --> recT0);
schirmer@14700
  1999
wenzelm@35133
  2000
schirmer@14700
  2001
    (* prepare definitions *)
wenzelm@17261
  2002
wenzelm@35138
  2003
    val ext_defs = ext_def :: map #ext_def parents;
tsewell@32743
  2004
haftmann@34151
  2005
    (*Theorems from the iso_tuple intros.
wenzelm@32761
  2006
      By unfolding ext_defs from r_rec0 we create a tree of constructor
wenzelm@32761
  2007
      calls (many of them Pair, but others as well). The introduction
wenzelm@32761
  2008
      rules for update_accessor_eq_assist can unify two different ways
wenzelm@32761
  2009
      on these constructors. If we take the complete result sequence of
wenzelm@32761
  2010
      running a the introduction tactic, we get one theorem for each upd/acc
wenzelm@32761
  2011
      pair, from which we can derive the bodies of our selector and
wenzelm@32761
  2012
      updator and their convs.*)
wenzelm@32761
  2013
    fun get_access_update_thms () =
wenzelm@32761
  2014
      let
wenzelm@32761
  2015
        val r_rec0_Vars =
wenzelm@32761
  2016
          let
wenzelm@32761
  2017
            (*pick variable indices of 1 to avoid possible variable
wenzelm@32761
  2018
              collisions with existing variables in updacc_eq_triv*)
tsewell@32757
  2019
            fun to_Var (Free (c, T)) = Var ((c, 1), T);
tsewell@32757
  2020
          in mk_rec (map to_Var all_vars_more) 0 end;
tsewell@32757
  2021
wenzelm@35239
  2022
        val cterm_rec = cterm_of ext_thy r_rec0;
wenzelm@35239
  2023
        val cterm_vrs = cterm_of ext_thy r_rec0_Vars;
wenzelm@32761
  2024
        val insts = [("v", cterm_rec), ("v'", cterm_vrs)];
wenzelm@32761
  2025
        val init_thm = named_cterm_instantiate insts updacc_eq_triv;
wenzelm@32761
  2026
        val terminal = rtac updacc_eq_idI 1 THEN rtac refl 1;
wenzelm@32761
  2027
        val tactic =
wenzelm@32761
  2028
          simp_tac (HOL_basic_ss addsimps ext_defs) 1 THEN
haftmann@34151
  2029
          REPEAT (Iso_Tuple_Support.iso_tuple_intros_tac 1 ORELSE terminal);
wenzelm@32972
  2030
        val updaccs = Seq.list_of (tactic init_thm);
tsewell@32743
  2031
      in
tsewell@32743
  2032
        (updaccs RL [updacc_accessor_eqE],
tsewell@32743
  2033
         updaccs RL [updacc_updator_eqE],
tsewell@32743
  2034
         updaccs RL [updacc_cong_from_eq])
tsewell@32743
  2035
      end;
tsewell@32743
  2036
    val (accessor_thms, updator_thms, upd_acc_cong_assists) =
wenzelm@32761
  2037
      timeit_msg "record getting tree access/updates:" get_access_update_thms;
tsewell@32743
  2038
haftmann@33957
  2039
    fun lastN xs = drop parent_fields_len xs;
tsewell@32743
  2040
wenzelm@17261
  2041
    (*selectors*)
wenzelm@32761
  2042
    fun mk_sel_spec ((c, T), thm) =
tsewell@32743
  2043
      let
wenzelm@35239
  2044
        val (acc $ arg, _) =
wenzelm@35239
  2045
          HOLogic.dest_eq (HOLogic.dest_Trueprop (Envir.beta_eta_contract (Thm.concl_of thm)));
wenzelm@32761
  2046
        val _ =
wenzelm@35239
  2047
          if arg aconv r_rec0 then ()
wenzelm@32761
  2048
          else raise TERM ("mk_sel_spec: different arg", [arg]);
tsewell@32743
  2049
      in
wenzelm@32761
  2050
        Const (mk_selC rec_schemeT0 (c, T)) :== acc
tsewell@32743
  2051
      end;
tsewell@32743
  2052
    val sel_specs = map mk_sel_spec (fields_more ~~ lastN accessor_thms);
schirmer@14700
  2053
schirmer@14700
  2054
    (*updates*)
wenzelm@32761
  2055
    fun mk_upd_spec ((c, T), thm) =
wenzelm@17261
  2056
      let
wenzelm@35239
  2057
        val (upd $ _ $ arg, _) =
wenzelm@35239
  2058
          HOLogic.dest_eq (HOLogic.dest_Trueprop (Envir.beta_eta_contract (Thm.concl_of thm)));
wenzelm@32761
  2059
        val _ =
wenzelm@35135
  2060
          if arg aconv r_rec0 then ()
wenzelm@32761
  2061
          else raise TERM ("mk_sel_spec: different arg", [arg]);
wenzelm@32761
  2062
      in Const (mk_updC updateN rec_schemeT0 (c, T)) :== upd end;
tsewell@32743
  2063
    val upd_specs = map mk_upd_spec (fields_more ~~ lastN updator_thms);
schirmer@14700
  2064
schirmer@14700
  2065
    (*derived operations*)
wenzelm@35144
  2066
    val make_spec =
wenzelm@35144
  2067
      list_comb (Const (full (Binding.name makeN), all_types ---> recT0), all_vars) :==
wenzelm@35144
  2068
        mk_rec (all_vars @ [HOLogic.unit]) 0;
wenzelm@35144
  2069
    val fields_spec =
wenzelm@35144
  2070
      list_comb (Const (full (Binding.name fields_selN), types ---> Type extension), vars) :==
wenzelm@35144
  2071
        mk_rec (all_vars @ [HOLogic.unit]) parent_len;
wenzelm@17261
  2072
    val extend_spec =
wenzelm@35136
  2073
      Const (full (Binding.name extendN), recT0 --> moreT --> rec_schemeT0) $ r_unit0 $ more :==
wenzelm@35144
  2074
        mk_rec ((map (mk_sel r_unit0) all_fields) @ [more]) 0;
wenzelm@35144
  2075
    val truncate_spec =
wenzelm@35144
  2076
      Const (full (Binding.name truncateN), rec_schemeT0 --> recT0) $ r0 :==
wenzelm@35144
  2077
        mk_rec ((map (mk_sel r0) all_fields) @ [HOLogic.unit]) 0;
schirmer@14700
  2078
wenzelm@32761
  2079
schirmer@14700
  2080
    (* 2st stage: defs_thy *)
wenzelm@17261
  2081
schirmer@16379
  2082
    fun mk_defs () =
wenzelm@35239
  2083
      ext_thy
wenzelm@35239
  2084
      |> Sign.add_advanced_trfuns ([], [], advanced_print_translation, [])
wenzelm@35239
  2085
      |> Sign.restore_naming thy
wenzelm@36173
  2086
      |> Typedecl.abbrev_global (binding, map #1 alphas, NoSyn) recT0 |> snd
wenzelm@36173
  2087
      |> Typedecl.abbrev_global
wenzelm@36173
  2088
        (Binding.suffix_name schemeN binding, map #1 (alphas @ [zeta]), NoSyn) rec_schemeT0 |> snd
wenzelm@35239
  2089
      |> Sign.qualified_path false binding
wenzelm@35239
  2090
      |> fold (fn ((x, T), mx) => snd o Sign.declare_const ((Binding.name x, T), mx))
wenzelm@35239
  2091
        (sel_decls ~~ (field_syntax @ [NoSyn]))
wenzelm@35239
  2092
      |> fold (fn (x, T) => snd o Sign.declare_const ((Binding.name x, T), NoSyn))
wenzelm@35239
  2093
        (upd_decls @ [make_decl, fields_decl, extend_decl, truncate_decl])
wenzelm@39557
  2094
      |> (Global_Theory.add_defs false o
wenzelm@39557
  2095
            map (Thm.no_attributes o apfst (Binding.conceal o Binding.name))) sel_specs
wenzelm@39557
  2096
      ||>> (Global_Theory.add_defs false o
wenzelm@39557
  2097
            map (Thm.no_attributes o apfst (Binding.conceal o Binding.name))) upd_specs
wenzelm@39557
  2098
      ||>> (Global_Theory.add_defs false o
wenzelm@39557
  2099
            map (Thm.no_attributes o apfst (Binding.conceal o Binding.name)))
wenzelm@35142
  2100
        [make_spec, fields_spec, extend_spec, truncate_spec]
schirmer@33691
  2101
      ||> Theory.checkpoint
haftmann@22747
  2102
    val (((sel_defs, upd_defs), derived_defs), defs_thy) =
haftmann@22747
  2103
      timeit_msg "record trfuns/tyabbrs/selectors/updates/make/fields/extend/truncate defs:"
haftmann@22747
  2104
        mk_defs;
wenzelm@17261
  2105
schirmer@14700
  2106
    (* prepare propositions *)
wenzelm@17261
  2107
    val _ = timing_msg "record preparing propositions";
wenzelm@32761
  2108
    val P = Free (Name.variant all_variants "P", rec_schemeT0 --> HOLogic.boolT);
wenzelm@20071
  2109
    val C = Free (Name.variant all_variants "C", HOLogic.boolT);
wenzelm@32761
  2110
    val P_unit = Free (Name.variant all_variants "P", recT0 --> HOLogic.boolT);
schirmer@14700
  2111
wenzelm@17261
  2112
    (*selectors*)
schirmer@14700
  2113
    val sel_conv_props =
wenzelm@32761
  2114
       map (fn (c, x as Free (_, T)) => mk_sel r_rec0 (c, T) === x) named_vars_more;
schirmer@14700
  2115
wenzelm@17261
  2116
    (*updates*)
haftmann@37470
  2117
    fun mk_upd_prop i (c, T) =
wenzelm@32761
  2118
      let
wenzelm@35239
  2119
        val x' = Free (Name.variant all_variants (Long_Name.base_name c ^ "'"), T --> T);
wenzelm@32761
  2120
        val n = parent_fields_len + i;
wenzelm@35239
  2121
        val args' = nth_map n (K (x' $ nth all_vars_more n)) all_vars_more;
wenzelm@32761
  2122
      in mk_upd updateN c x' r_rec0 === mk_rec args' 0 end;
haftmann@37470
  2123
    val upd_conv_props = map2 mk_upd_prop idxms fields_more;
schirmer@14700
  2124
schirmer@14700
  2125
    (*induct*)
schirmer@14700
  2126
    val induct_scheme_prop =
schirmer@14700
  2127
      All (map dest_Free all_vars_more) (Trueprop (P $ r_rec0)) ==> Trueprop (P $ r0);
wenzelm@17261
  2128
    val induct_prop =
schirmer@14700
  2129
      (All (map dest_Free all_vars) (Trueprop (P_unit $ r_rec_unit0)),
wenzelm@32761
  2130
        Trueprop (P_unit $ r_unit0));
schirmer@14700
  2131
schirmer@14700
  2132
    (*surjective*)
schirmer@14700
  2133
    val surjective_prop =
wenzelm@32761
  2134
      let val args = map (fn (c, Free (_, T)) => mk_sel r0 (c, T)) all_named_vars_more
schirmer@14700
  2135
      in r0 === mk_rec args 0 end;
wenzelm@17261
  2136
schirmer@14700
  2137
    (*cases*)
schirmer@14700
  2138
    val cases_scheme_prop =
wenzelm@32809
  2139
      (All (map dest_Free all_vars_more) ((r0 === r_rec0) ==> Trueprop C))
wenzelm@32799
  2140
        ==> Trueprop C;
schirmer@14700
  2141
schirmer@14700
  2142
    val cases_prop =
wenzelm@32809
  2143
      (All (map dest_Free all_vars) ((r_unit0 === r_rec_unit0) ==> Trueprop C))
wenzelm@32799
  2144
         ==> Trueprop C;
schirmer@14700
  2145
schirmer@14700
  2146
    (*split*)
schirmer@14700
  2147
    val split_meta_prop =
wenzelm@20071
  2148
      let val P = Free (Name.variant all_variants "P", rec_schemeT0-->Term.propT) in
wenzelm@17261
  2149
        Logic.mk_equals
schirmer@14700
  2150
         (All [dest_Free r0] (P $ r0), All (map dest_Free all_vars_more) (P $ r_rec0))
wenzelm@17261
  2151
      end;
schirmer@14700
  2152
schirmer@14700
  2153
    val split_object_prop =
wenzelm@32974
  2154
      let val ALL = fold_rev (fn (v, T) => fn t => HOLogic.mk_all (v, T, t))
wenzelm@32974
  2155
      in ALL [dest_Free r0] (P $ r0) === ALL (map dest_Free all_vars_more) (P $ r_rec0) end;
schirmer@14700
  2156
schirmer@14700
  2157
    val split_ex_prop =
wenzelm@32974
  2158
      let val EX = fold_rev (fn (v, T) => fn t => HOLogic.mk_exists (v, T, t))
wenzelm@32974
  2159
      in EX [dest_Free r0] (P $ r0) === EX (map dest_Free all_vars_more) (P $ r_rec0) end;
schirmer@14700
  2160
schirmer@14700
  2161
    (*equality*)
schirmer@14700
  2162
    val equality_prop =
wenzelm@17261
  2163
      let
wenzelm@32761
  2164
        val s' = Free (rN ^ "'", rec_schemeT0);
wenzelm@32761
  2165
        fun mk_sel_eq (c, Free (_, T)) = mk_sel r0 (c, T) === mk_sel s' (c, T);
wenzelm@32761
  2166
        val seleqs = map mk_sel_eq all_named_vars_more;
wenzelm@32761
  2167
      in All (map dest_Free [r0, s']) (Logic.list_implies (seleqs, r0 === s')) end;
wenzelm@32761
  2168
schirmer@14700
  2169
schirmer@14700
  2170
    (* 3rd stage: thms_thy *)
schirmer@14700
  2171
schirmer@33691
  2172
    fun prove stndrd = prove_future_global stndrd defs_thy;
schirmer@33691
  2173
    val prove_standard = prove_future_global true defs_thy;
schirmer@33691
  2174
    val future_forward_prf = future_forward_prf_standard defs_thy;
wenzelm@17261
  2175
schirmer@15215
  2176
    fun prove_simp stndrd ss simps =
schirmer@14700
  2177
      let val tac = simp_all_tac ss simps
schirmer@15215
  2178
      in fn prop => prove stndrd [] prop (K tac) end;
schirmer@14700
  2179
wenzelm@17510
  2180
    val ss = get_simpset defs_thy;
schirmer@15012
  2181
wenzelm@32761
  2182
    fun sel_convs_prf () =
wenzelm@32761
  2183
      map (prove_simp false ss (sel_defs @ accessor_thms)) sel_conv_props;
schirmer@15012
  2184
    val sel_convs = timeit_msg "record sel_convs proof:" sel_convs_prf;
wenzelm@35021
  2185
    fun sel_convs_standard_prf () = map Drule.export_without_context sel_convs;
wenzelm@17261
  2186
    val sel_convs_standard =
wenzelm@32761
  2187
      timeit_msg "record sel_convs_standard proof:" sel_convs_standard_prf;
wenzelm@32761
  2188
wenzelm@32761
  2189
    fun upd_convs_prf () =
wenzelm@32761
  2190
      map (prove_simp false ss (upd_defs @ updator_thms)) upd_conv_props;
schirmer@15012
  2191
    val upd_convs = timeit_msg "record upd_convs proof:" upd_convs_prf;
wenzelm@35021
  2192
    fun upd_convs_standard_prf () = map Drule.export_without_context upd_convs;
tsewell@32743
  2193
    val upd_convs_standard =
wenzelm@32761
  2194
      timeit_msg "record upd_convs_standard proof:" upd_convs_standard_prf;
wenzelm@32761
  2195
wenzelm@32761
  2196
    fun get_upd_acc_congs () =
wenzelm@32761
  2197
      let
wenzelm@36945
  2198
        val symdefs = map Thm.symmetric (sel_defs @ upd_defs);
wenzelm@32761
  2199
        val fold_ss = HOL_basic_ss addsimps symdefs;
wenzelm@35021
  2200
        val ua_congs = map (Drule.export_without_context o simplify fold_ss) upd_acc_cong_assists;
tsewell@32743
  2201
      in (ua_congs RL [updacc_foldE], ua_congs RL [updacc_unfoldE]) end;
tsewell@32743
  2202
    val (fold_congs, unfold_congs) =
wenzelm@32761
  2203
      timeit_msg "record upd fold/unfold congs:" get_upd_acc_congs;
schirmer@15012
  2204
wenzelm@35138
  2205
    val parent_induct = Option.map #induct_scheme (try List.last parents);
schirmer@14700
  2206
wenzelm@32761
  2207
    fun induct_scheme_prf () =
wenzelm@32761
  2208
      prove_standard [] induct_scheme_prop
wenzelm@32761
  2209
        (fn _ =>
wenzelm@32761
  2210
          EVERY
wenzelm@35138
  2211
           [case parent_induct of NONE => all_tac | SOME ind => try_param_tac rN ind 1,
wenzelm@32761
  2212
            try_param_tac rN ext_induct 1,
wenzelm@32761
  2213
            asm_simp_tac HOL_basic_ss 1]);
schirmer@15012
  2214
    val induct_scheme = timeit_msg "record induct_scheme proof:" induct_scheme_prf;
schirmer@14700
  2215
schirmer@15012
  2216
    fun induct_prf () =
wenzelm@32761
  2217
      let val (assm, concl) = induct_prop in
wenzelm@20248
  2218
        prove_standard [assm] concl (fn {prems, ...} =>
schirmer@14700
  2219
          try_param_tac rN induct_scheme 1
haftmann@27104
  2220
          THEN try_param_tac "more" @{thm unit.induct} 1
schirmer@14700
  2221
          THEN resolve_tac prems 1)
schirmer@14700
  2222
      end;
schirmer@15012
  2223
    val induct = timeit_msg "record induct proof:" induct_prf;
schirmer@14700
  2224
schirmer@33691
  2225
    fun cases_scheme_prf () =
wenzelm@17261
  2226
      let
wenzelm@32761
  2227
        val _ $ (Pvar $ _) = concl_of induct_scheme;
wenzelm@32761
  2228
        val ind =
wenzelm@32761
  2229
          cterm_instantiate
wenzelm@32761
  2230
            [(cterm_of defs_thy Pvar, cterm_of defs_thy
wenzelm@32761
  2231
              (lambda w (HOLogic.imp $ HOLogic.mk_eq (r0, w) $ C)))]
wenzelm@32761
  2232
            induct_scheme;
wenzelm@35625
  2233
        in Object_Logic.rulify (mp OF [ind, refl]) end;
schirmer@33691
  2234
schirmer@33691
  2235
    val cases_scheme_prf = future_forward_prf cases_scheme_prf cases_scheme_prop;
schirmer@15012
  2236
    val cases_scheme = timeit_msg "record cases_scheme proof:" cases_scheme_prf;
schirmer@14700
  2237
schirmer@15012
  2238
    fun cases_prf () =
wenzelm@32761
  2239
      prove_standard [] cases_prop
wenzelm@32761
  2240
        (fn _ =>
wenzelm@32761
  2241
          try_param_tac rN cases_scheme 1 THEN
haftmann@37136
  2242
          simp_all_tac HOL_basic_ss [@{thm unit_all_eq1}]);
schirmer@15012
  2243
    val cases = timeit_msg "record cases proof:" cases_prf;
schirmer@14700
  2244
wenzelm@32761
  2245
    fun surjective_prf () =
wenzelm@32761
  2246
      let
wenzelm@32761
  2247
        val leaf_ss = get_sel_upd_defs defs_thy addsimps (sel_defs @ (o_assoc :: id_o_apps));
wenzelm@32761
  2248
        val init_ss = HOL_basic_ss addsimps ext_defs;
tsewell@32743
  2249
      in
wenzelm@32761
  2250
        prove_standard [] surjective_prop
wenzelm@32799
  2251
          (fn _ =>
wenzelm@32761
  2252
            EVERY
wenzelm@32761
  2253
             [rtac surject_assist_idE 1,
wenzelm@32761
  2254
              simp_tac init_ss 1,
wenzelm@32975
  2255
              REPEAT
haftmann@34151
  2256
                (Iso_Tuple_Support.iso_tuple_intros_tac 1 ORELSE
wenzelm@32975
  2257
                  (rtac surject_assistI 1 THEN simp_tac leaf_ss 1))])
tsewell@32743
  2258
      end;
tsewell@32743
  2259
    val surjective = timeit_msg "record surjective proof:" surjective_prf;
tsewell@32743
  2260
schirmer@15012
  2261
    fun split_meta_prf () =
wenzelm@32761
  2262
      prove false [] split_meta_prop
wenzelm@32799
  2263
        (fn _ =>
wenzelm@32975
  2264
          EVERY1
wenzelm@32975
  2265
           [rtac equal_intr_rule, Goal.norm_hhf_tac,
wenzelm@32975
  2266
            etac meta_allE, atac,
wenzelm@32975
  2267
            rtac (prop_subst OF [surjective]),
wenzelm@32975
  2268
            REPEAT o etac meta_allE, atac]);
schirmer@15012
  2269
    val split_meta = timeit_msg "record split_meta proof:" split_meta_prf;
wenzelm@35021
  2270
    fun split_meta_standardise () = Drule.export_without_context split_meta;
wenzelm@32761
  2271
    val split_meta_standard =
wenzelm@32761
  2272
      timeit_msg "record split_meta standard:" split_meta_standardise;
schirmer@14700
  2273
schirmer@33691
  2274
    fun split_object_prf () =
wenzelm@17261
  2275
      let
wenzelm@32761
  2276
        val cPI= cterm_of defs_thy (lambda r0 (Trueprop (P $ r0)));
wenzelm@32761
  2277
        val _ $ Abs (_, _, P $ _) = fst (Logic.dest_equals (concl_of split_meta_standard));
wenzelm@18858
  2278
        val cP = cterm_of defs_thy P;
wenzelm@32761
  2279
        val split_meta' = cterm_instantiate [(cP, cPI)] split_meta_standard;
wenzelm@32761
  2280
        val (l, r) = HOLogic.dest_eq (HOLogic.dest_Trueprop split_object_prop);
wenzelm@18858
  2281
        val cl = cterm_of defs_thy (HOLogic.mk_Trueprop l);
wenzelm@18858
  2282
        val cr = cterm_of defs_thy (HOLogic.mk_Trueprop r);
wenzelm@32761
  2283
        val thl =
wenzelm@36945
  2284
          Thm.assume cl                   (*All r. P r*) (* 1 *)
wenzelm@36945
  2285
          |> obj_to_meta_all              (*!!r. P r*)
wenzelm@36945
  2286
          |> Thm.equal_elim split_meta'   (*!!n m more. P (ext n m more)*)
wenzelm@36945
  2287
          |> meta_to_obj_all              (*All n m more. P (ext n m more)*) (* 2*)
wenzelm@36945
  2288
          |> Thm.implies_intr cl          (* 1 ==> 2 *)
wenzelm@32761
  2289
        val thr =
wenzelm@36945
  2290
          Thm.assume cr                                 (*All n m more. P (ext n m more)*)
wenzelm@36945
  2291
          |> obj_to_meta_all                            (*!!n m more. P (ext n m more)*)
wenzelm@36945
  2292
          |> Thm.equal_elim (Thm.symmetric split_meta') (*!!r. P r*)
wenzelm@36945
  2293
          |> meta_to_obj_all                            (*All r. P r*)
wenzelm@36945
  2294
          |> Thm.implies_intr cr                        (* 2 ==> 1 *)
schirmer@33691
  2295
     in thr COMP (thl COMP iffI) end;
schirmer@33691
  2296
schirmer@33691
  2297
schirmer@33691
  2298
    val split_object_prf = future_forward_prf split_object_prf split_object_prop;
schirmer@15012
  2299
    val split_object = timeit_msg "record split_object proof:" split_object_prf;
schirmer@14700
  2300
schirmer@15012
  2301
wenzelm@17261
  2302
    fun split_ex_prf () =
tsewell@32743
  2303
      let
wenzelm@32761
  2304
        val ss = HOL_basic_ss addsimps [not_ex RS sym, Not_eq_iff];
wenzelm@32761
  2305
        val P_nm = fst (dest_Free P);
tsewell@32752
  2306
        val not_P = cterm_of defs_thy (lambda r0 (HOLogic.mk_not (P $ r0)));
wenzelm@32761
  2307
        val so' = named_cterm_instantiate ([(P_nm, not_P)]) split_object;
wenzelm@32761
  2308
        val so'' = simplify ss so';
tsewell@32743
  2309
      in
wenzelm@32799
  2310
        prove_standard [] split_ex_prop (fn _ => resolve_tac [so''] 1)
tsewell@32743
  2311
      end;
schirmer@15012
  2312
    val split_ex = timeit_msg "record split_ex proof:" split_ex_prf;
schirmer@14700
  2313
wenzelm@17261
  2314
    fun equality_tac thms =
wenzelm@32761
  2315
      let
wenzelm@32761
  2316
        val s' :: s :: eqs = rev thms;
wenzelm@32761
  2317
        val ss' = ss addsimps (s' :: s :: sel_convs_standard);
wenzelm@32761
  2318
        val eqs' = map (simplify ss') eqs;
wenzelm@32761
  2319
      in simp_tac (HOL_basic_ss addsimps (s' :: s :: eqs')) 1 end;
wenzelm@32761
  2320
wenzelm@32761
  2321
    fun equality_prf () =
wenzelm@32761
  2322
      prove_standard [] equality_prop (fn {context, ...} =>
wenzelm@32761
  2323
        fn st =>
wenzelm@32761
  2324
          let val [s, s'] = map #1 (rev (Tactic.innermost_params 1 st)) in
wenzelm@32761
  2325
            st |> (res_inst_tac context [((rN, 0), s)] cases_scheme 1 THEN
wenzelm@32761
  2326
              res_inst_tac context [((rN, 0), s')] cases_scheme 1 THEN
wenzelm@32761
  2327
              Subgoal.FOCUS (fn {prems, ...} => equality_tac prems) context 1)
wenzelm@32761
  2328
             (*simp_all_tac ss (sel_convs) would also work but is less efficient*)
wenzelm@32761
  2329
          end);
wenzelm@32761
  2330
    val equality = timeit_msg "record equality proof:" equality_prf;
schirmer@14700
  2331
wenzelm@32335
  2332
    val ((([sel_convs', upd_convs', sel_defs', upd_defs',
tsewell@32744
  2333
            fold_congs', unfold_congs',
wenzelm@35138
  2334
          splits' as [split_meta', split_object', split_ex'], derived_defs'],
wenzelm@32335
  2335
          [surjective', equality']),
wenzelm@32335
  2336
          [induct_scheme', induct', cases_scheme', cases']), thms_thy) =
schirmer@14700
  2337
      defs_thy
wenzelm@39557
  2338
      |> (Global_Theory.add_thmss o map (Thm.no_attributes o apfst Binding.name))
schirmer@15215
  2339
         [("select_convs", sel_convs_standard),
tsewell@32744
  2340
          ("update_convs", upd_convs_standard),
schirmer@14700
  2341
          ("select_defs", sel_defs),
schirmer@14700
  2342
          ("update_defs", upd_defs),
tsewell@32744
  2343
          ("fold_congs", fold_congs),
tsewell@32744
  2344
          ("unfold_congs", unfold_congs),
wenzelm@32761
  2345
          ("splits", [split_meta_standard, split_object, split_ex]),
schirmer@14700
  2346
          ("defs", derived_defs)]
wenzelm@39557
  2347
      ||>> (Global_Theory.add_thms o map (Thm.no_attributes o apfst Binding.name))
schirmer@14700
  2348
          [("surjective", surjective),
schirmer@14700
  2349
           ("equality", equality)]
wenzelm@39557
  2350
      ||>> (Global_Theory.add_thms o (map o apfst o apfst) Binding.name)
schirmer@14700
  2351
        [(("induct_scheme", induct_scheme), induct_type_global (suffix schemeN name)),
schirmer@14700
  2352
         (("induct", induct), induct_type_global name),
schirmer@14700
  2353
         (("cases_scheme", cases_scheme), cases_type_global (suffix schemeN name)),
schirmer@14700
  2354
         (("cases", cases), cases_type_global name)];
schirmer@14700
  2355
schirmer@14700
  2356
    val sel_upd_simps = sel_convs' @ upd_convs';
tsewell@32743
  2357
    val sel_upd_defs = sel_defs' @ upd_defs';
schirmer@14700
  2358
    val iffs = [ext_inject]
tsewell@32743
  2359
    val depth = parent_len + 1;
wenzelm@35138
  2360
wenzelm@35138
  2361
    val ([simps', iffs'], thms_thy') =
schirmer@14700
  2362
      thms_thy
wenzelm@39557
  2363
      |> Global_Theory.add_thmss
blanchet@33053
  2364
          [((Binding.name "simps", sel_upd_simps), [Simplifier.simp_add]),
wenzelm@35138
  2365
           ((Binding.name "iffs", iffs), [iff_add])];
wenzelm@35138
  2366
wenzelm@35138
  2367
    val info =
haftmann@38012
  2368
      make_info alphas parent fields extension
wenzelm@35138
  2369
        ext_induct ext_inject ext_surjective ext_split ext_def
wenzelm@35138
  2370
        sel_convs' upd_convs' sel_defs' upd_defs' fold_congs' unfold_congs' splits' derived_defs'
wenzelm@35138
  2371
        surjective' equality' induct_scheme' induct' cases_scheme' cases' simps' iffs';
wenzelm@35138
  2372
wenzelm@35138
  2373
    val final_thy =
wenzelm@35138
  2374
      thms_thy'
wenzelm@35138
  2375
      |> put_record name info