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