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