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