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