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