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