src/HOL/Tools/Nitpick/nitpick_hol.ML
author haftmann
Fri Feb 15 08:31:31 2013 +0100 (2013-02-15)
changeset 51143 0a2371e7ced3
parent 49985 5b4b0e4e5205
child 51706 0a4b4735d8bd
permissions -rw-r--r--
two target language numeral types: integer and natural, as replacement for code_numeral;
former theory HOL/Library/Code_Numeral_Types replaces HOL/Code_Numeral;
refined stack of theories implementing int and/or nat by target language numerals;
reduced number of target language numeral types to exactly one
blanchet@33978
     1
(*  Title:      HOL/Tools/Nitpick/nitpick_hol.ML
blanchet@33192
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@34982
     3
    Copyright   2008, 2009, 2010
blanchet@33192
     4
blanchet@33192
     5
Auxiliary HOL-related functions used by Nitpick.
blanchet@33192
     6
*)
blanchet@33192
     7
blanchet@33192
     8
signature NITPICK_HOL =
blanchet@33192
     9
sig
blanchet@33705
    10
  type styp = Nitpick_Util.styp
blanchet@33192
    11
  type const_table = term list Symtab.table
blanchet@33192
    12
  type special_fun = (styp * int list * term list) * styp
blanchet@33192
    13
  type unrolled = styp * styp
blanchet@33192
    14
  type wf_cache = (styp * (bool * bool)) list
blanchet@33192
    15
blanchet@36390
    16
  type hol_context =
blanchet@36390
    17
    {thy: theory,
blanchet@36390
    18
     ctxt: Proof.context,
blanchet@36390
    19
     max_bisim_depth: int,
blanchet@36390
    20
     boxes: (typ option * bool option) list,
blanchet@36390
    21
     stds: (typ option * bool) list,
blanchet@36390
    22
     wfs: (styp option * bool option) list,
blanchet@36390
    23
     user_axioms: bool option,
blanchet@36390
    24
     debug: bool,
blanchet@38209
    25
     whacks: term list,
blanchet@36390
    26
     binary_ints: bool option,
blanchet@36390
    27
     destroy_constrs: bool,
blanchet@36390
    28
     specialize: bool,
blanchet@36390
    29
     star_linear_preds: bool,
blanchet@41871
    30
     total_consts: bool option,
blanchet@41876
    31
     needs: term list option,
blanchet@36390
    32
     tac_timeout: Time.time option,
blanchet@36390
    33
     evals: term list,
blanchet@36390
    34
     case_names: (string * int) list,
blanchet@41791
    35
     def_tables: const_table * const_table,
blanchet@36390
    36
     nondef_table: const_table,
blanchet@42415
    37
     nondefs: term list,
blanchet@36390
    38
     simp_table: const_table Unsynchronized.ref,
blanchet@36390
    39
     psimp_table: const_table,
blanchet@36390
    40
     choice_spec_table: const_table,
blanchet@36390
    41
     intro_table: const_table,
blanchet@36390
    42
     ground_thm_table: term list Inttab.table,
blanchet@36390
    43
     ersatz_table: (string * string) list,
blanchet@36390
    44
     skolems: (string * string list) list Unsynchronized.ref,
blanchet@36390
    45
     special_funs: special_fun list Unsynchronized.ref,
blanchet@36390
    46
     unrolled_preds: unrolled list Unsynchronized.ref,
blanchet@36390
    47
     wf_cache: wf_cache Unsynchronized.ref,
blanchet@36390
    48
     constr_cache: (typ * styp list) list Unsynchronized.ref}
blanchet@33192
    49
blanchet@35070
    50
  datatype fixpoint_kind = Lfp | Gfp | NoFp
blanchet@35070
    51
  datatype boxability =
blanchet@35070
    52
    InConstr | InSel | InExpr | InPair | InFunLHS | InFunRHS1 | InFunRHS2
blanchet@35070
    53
blanchet@33192
    54
  val name_sep : string
blanchet@33192
    55
  val numeral_prefix : string
blanchet@35718
    56
  val base_prefix : string
blanchet@35718
    57
  val step_prefix : string
blanchet@35718
    58
  val unrolled_prefix : string
blanchet@35070
    59
  val ubfp_prefix : string
blanchet@35070
    60
  val lbfp_prefix : string
blanchet@35311
    61
  val quot_normal_prefix : string
blanchet@33192
    62
  val skolem_prefix : string
blanchet@35070
    63
  val special_prefix : string
blanchet@35070
    64
  val uncurry_prefix : string
blanchet@33192
    65
  val eval_prefix : string
blanchet@35718
    66
  val iter_var_prefix : string
blanchet@35718
    67
  val strip_first_name_sep : string -> string * string
blanchet@33192
    68
  val original_name : string -> string
blanchet@37476
    69
  val abs_var : indexname * typ -> term -> term
blanchet@34998
    70
  val s_conj : term * term -> term
blanchet@35070
    71
  val s_disj : term * term -> term
blanchet@35070
    72
  val strip_any_connective : term -> term list * term
blanchet@35070
    73
  val conjuncts_of : term -> term list
blanchet@35070
    74
  val disjuncts_of : term -> term list
blanchet@35665
    75
  val unarize_unbox_etc_type : typ -> typ
blanchet@35665
    76
  val uniterize_unarize_unbox_etc_type : typ -> typ
blanchet@33192
    77
  val string_for_type : Proof.context -> typ -> string
blanchet@38188
    78
  val pretty_for_type : Proof.context -> typ -> Pretty.T
blanchet@33192
    79
  val prefix_name : string -> string -> string
blanchet@34121
    80
  val shortest_name : string -> string
blanchet@33192
    81
  val short_name : string -> string
blanchet@34121
    82
  val shorten_names_in_term : term -> term
blanchet@35711
    83
  val strict_type_match : theory -> typ * typ -> bool
blanchet@33192
    84
  val type_match : theory -> typ * typ -> bool
blanchet@33192
    85
  val const_match : theory -> styp * styp -> bool
blanchet@33192
    86
  val term_match : theory -> term * term -> bool
blanchet@35711
    87
  val frac_from_term_pair : typ -> term -> term -> term
blanchet@33192
    88
  val is_TFree : typ -> bool
blanchet@33192
    89
  val is_fun_type : typ -> bool
blanchet@46115
    90
  val is_set_type : typ -> bool
blanchet@46115
    91
  val is_fun_or_set_type : typ -> bool
blanchet@46081
    92
  val is_set_like_type : typ -> bool
blanchet@33192
    93
  val is_pair_type : typ -> bool
blanchet@33192
    94
  val is_lfp_iterator_type : typ -> bool
blanchet@33192
    95
  val is_gfp_iterator_type : typ -> bool
blanchet@33192
    96
  val is_fp_iterator_type : typ -> bool
blanchet@35280
    97
  val is_iterator_type : typ -> bool
blanchet@33192
    98
  val is_boolean_type : typ -> bool
blanchet@33192
    99
  val is_integer_type : typ -> bool
blanchet@34124
   100
  val is_bit_type : typ -> bool
blanchet@34124
   101
  val is_word_type : typ -> bool
blanchet@35220
   102
  val is_integer_like_type : typ -> bool
blanchet@33192
   103
  val is_record_type : typ -> bool
blanchet@38240
   104
  val is_number_type : Proof.context -> typ -> bool
blanchet@41860
   105
  val is_higher_order_type : typ -> bool
blanchet@46081
   106
  val elem_type : typ -> typ
blanchet@46083
   107
  val pseudo_domain_type : typ -> typ
blanchet@46083
   108
  val pseudo_range_type : typ -> typ
blanchet@33192
   109
  val const_for_iterator_type : typ -> styp
blanchet@35070
   110
  val strip_n_binders : int -> typ -> typ list * typ
blanchet@33192
   111
  val nth_range_type : int -> typ -> typ
blanchet@33192
   112
  val num_factors_in_type : typ -> int
blanchet@33192
   113
  val num_binder_types : typ -> int
blanchet@33192
   114
  val curried_binder_types : typ -> typ list
blanchet@33192
   115
  val mk_flat_tuple : typ -> term list -> term
blanchet@33192
   116
  val dest_n_tuple : int -> term -> term list
blanchet@33978
   117
  val is_real_datatype : theory -> string -> bool
blanchet@35220
   118
  val is_standard_datatype : theory -> (typ option * bool) list -> typ -> bool
blanchet@38240
   119
  val is_codatatype : Proof.context -> typ -> bool
blanchet@38240
   120
  val is_quot_type : Proof.context -> typ -> bool
blanchet@37256
   121
  val is_pure_typedef : Proof.context -> typ -> bool
blanchet@37256
   122
  val is_univ_typedef : Proof.context -> typ -> bool
blanchet@37256
   123
  val is_datatype : Proof.context -> (typ option * bool) list -> typ -> bool
blanchet@33192
   124
  val is_record_constr : styp -> bool
blanchet@33192
   125
  val is_record_get : theory -> styp -> bool
blanchet@33192
   126
  val is_record_update : theory -> styp -> bool
blanchet@37256
   127
  val is_abs_fun : Proof.context -> styp -> bool
blanchet@37256
   128
  val is_rep_fun : Proof.context -> styp -> bool
blanchet@34936
   129
  val is_quot_abs_fun : Proof.context -> styp -> bool
blanchet@34936
   130
  val is_quot_rep_fun : Proof.context -> styp -> bool
blanchet@37256
   131
  val mate_of_rep_fun : Proof.context -> styp -> styp
blanchet@37256
   132
  val is_constr_like : Proof.context -> styp -> bool
blanchet@37256
   133
  val is_constr : Proof.context -> (typ option * bool) list -> styp -> bool
blanchet@33192
   134
  val is_sel : string -> bool
blanchet@34124
   135
  val is_sel_like_and_no_discr : string -> bool
blanchet@35070
   136
  val box_type : hol_context -> boxability -> typ -> typ
blanchet@35190
   137
  val binarize_nat_and_int_in_type : typ -> typ
blanchet@35190
   138
  val binarize_nat_and_int_in_term : term -> term
blanchet@33192
   139
  val discr_for_constr : styp -> styp
blanchet@33192
   140
  val num_sels_for_constr_type : typ -> int
blanchet@33192
   141
  val nth_sel_name_for_constr_name : string -> int -> string
blanchet@33192
   142
  val nth_sel_for_constr : styp -> int -> styp
blanchet@35190
   143
  val binarized_and_boxed_nth_sel_for_constr :
blanchet@35190
   144
    hol_context -> bool -> styp -> int -> styp
blanchet@33192
   145
  val sel_no_from_name : string -> int
blanchet@35078
   146
  val close_form : term -> term
blanchet@33192
   147
  val distinctness_formula : typ -> term list -> term
blanchet@38240
   148
  val register_frac_type :
blanchet@38284
   149
    string -> (string * string) list -> morphism -> Context.generic
blanchet@38284
   150
    -> Context.generic
blanchet@38240
   151
  val register_frac_type_global :
blanchet@38240
   152
    string -> (string * string) list -> theory -> theory
blanchet@38284
   153
  val unregister_frac_type :
blanchet@38284
   154
    string -> morphism -> Context.generic -> Context.generic
blanchet@38240
   155
  val unregister_frac_type_global : string -> theory -> theory
krauss@44012
   156
  val register_ersatz :
krauss@44012
   157
    (string * string) list -> morphism -> Context.generic -> Context.generic
krauss@44012
   158
  val register_ersatz_global : (string * string) list -> theory -> theory
blanchet@38240
   159
  val register_codatatype :
blanchet@38284
   160
    typ -> string -> styp list -> morphism -> Context.generic -> Context.generic
blanchet@38240
   161
  val register_codatatype_global :
blanchet@38240
   162
    typ -> string -> styp list -> theory -> theory
blanchet@38284
   163
  val unregister_codatatype :
blanchet@38284
   164
    typ -> morphism -> Context.generic -> Context.generic
blanchet@38240
   165
  val unregister_codatatype_global : typ -> theory -> theory
blanchet@35070
   166
  val datatype_constrs : hol_context -> typ -> styp list
blanchet@35190
   167
  val binarized_and_boxed_datatype_constrs :
blanchet@35190
   168
    hol_context -> bool -> typ -> styp list
blanchet@35070
   169
  val num_datatype_constrs : hol_context -> typ -> int
blanchet@33192
   170
  val constr_name_for_sel_like : string -> string
blanchet@35190
   171
  val binarized_and_boxed_constr_for_sel : hol_context -> bool -> styp -> styp
blanchet@41860
   172
  val card_of_type : (typ * int) list -> typ -> int
blanchet@41860
   173
  val bounded_card_of_type : int -> int -> (typ * int) list -> typ -> int
blanchet@41860
   174
  val bounded_exact_card_of_type :
blanchet@41860
   175
    hol_context -> typ list -> int -> int -> (typ * int) list -> typ -> int
blanchet@41860
   176
  val typical_card_of_type : typ -> int
blanchet@41860
   177
  val is_finite_type : hol_context -> typ -> bool
blanchet@41860
   178
  val is_special_eligible_arg : bool -> typ list -> term -> bool
blanchet@41860
   179
  val s_let :
blanchet@41860
   180
    typ list -> string -> int -> typ -> typ -> (term -> term) -> term -> term
blanchet@41860
   181
  val s_betapply : typ list -> term * term -> term
blanchet@41860
   182
  val s_betapplys : typ list -> term * term list -> term
blanchet@35070
   183
  val discriminate_value : hol_context -> styp -> term -> term
blanchet@35220
   184
  val select_nth_constr_arg :
blanchet@37256
   185
    Proof.context -> (typ option * bool) list -> styp -> term -> int -> typ
blanchet@37256
   186
    -> term
blanchet@35220
   187
  val construct_value :
blanchet@37256
   188
    Proof.context -> (typ option * bool) list -> styp -> term list -> term
blanchet@35665
   189
  val coerce_term : hol_context -> typ list -> typ -> typ -> term -> term
blanchet@35070
   190
  val special_bounds : term list -> (indexname * typ) list
blanchet@38240
   191
  val is_funky_typedef : Proof.context -> typ -> bool
blanchet@42415
   192
  val all_defs_of : theory -> (term * term) list -> term list
blanchet@42415
   193
  val all_nondefs_of : Proof.context -> (term * term) list -> term list
blanchet@35220
   194
  val arity_of_built_in_const :
blanchet@39359
   195
    theory -> (typ option * bool) list -> styp -> int option
blanchet@35220
   196
  val is_built_in_const :
blanchet@39359
   197
    theory -> (typ option * bool) list -> styp -> bool
blanchet@35070
   198
  val term_under_def : term -> term
blanchet@35220
   199
  val case_const_names :
blanchet@38240
   200
    Proof.context -> (typ option * bool) list -> (string * int) list
blanchet@35718
   201
  val unfold_defs_in_term : hol_context -> term -> term
blanchet@41791
   202
  val const_def_tables :
blanchet@41791
   203
    Proof.context -> (term * term) list -> term list
blanchet@41791
   204
    -> const_table * const_table
blanchet@33192
   205
  val const_nondef_table : term list -> const_table
blanchet@35335
   206
  val const_simp_table : Proof.context -> (term * term) list -> const_table
blanchet@35335
   207
  val const_psimp_table : Proof.context -> (term * term) list -> const_table
blanchet@35807
   208
  val const_choice_spec_table :
blanchet@35807
   209
    Proof.context -> (term * term) list -> const_table
blanchet@35335
   210
  val inductive_intro_table :
blanchet@41791
   211
    Proof.context -> (term * term) list -> const_table * const_table
blanchet@41791
   212
    -> const_table
blanchet@33192
   213
  val ground_theorem_table : theory -> term list Inttab.table
blanchet@38240
   214
  val ersatz_table : Proof.context -> (string * string) list
blanchet@35070
   215
  val add_simps : const_table Unsynchronized.ref -> string -> term list -> unit
blanchet@37256
   216
  val inverse_axioms_for_rep_fun : Proof.context -> styp -> term list
blanchet@37256
   217
  val optimized_typedef_axioms : Proof.context -> string * typ list -> term list
blanchet@35220
   218
  val optimized_quot_type_axioms :
blanchet@35311
   219
    Proof.context -> (typ option * bool) list -> string * typ list -> term list
blanchet@41791
   220
  val def_of_const : theory -> const_table * const_table -> styp -> term option
blanchet@35718
   221
  val fixpoint_kind_of_rhs : term -> fixpoint_kind
blanchet@35070
   222
  val fixpoint_kind_of_const :
blanchet@41791
   223
    theory -> const_table * const_table -> string * typ -> fixpoint_kind
blanchet@38205
   224
  val is_real_inductive_pred : hol_context -> styp -> bool
blanchet@41994
   225
  val is_constr_pattern : Proof.context -> term -> bool
blanchet@37256
   226
  val is_constr_pattern_lhs : Proof.context -> term -> bool
blanchet@37256
   227
  val is_constr_pattern_formula : Proof.context -> term -> bool
blanchet@35807
   228
  val nondef_props_for_const :
blanchet@35807
   229
    theory -> bool -> const_table -> styp -> term list
blanchet@35807
   230
  val is_choice_spec_fun : hol_context -> styp -> bool
blanchet@35807
   231
  val is_choice_spec_axiom : theory -> const_table -> term -> bool
blanchet@38205
   232
  val is_real_equational_fun : hol_context -> styp -> bool
blanchet@38202
   233
  val is_equational_fun_but_no_plain_def : hol_context -> styp -> bool
blanchet@35070
   234
  val codatatype_bisim_axioms : hol_context -> typ -> term list
blanchet@35070
   235
  val is_well_founded_inductive_pred : hol_context -> styp -> bool
blanchet@35070
   236
  val unrolled_inductive_pred_const : hol_context -> bool -> styp -> term
blanchet@35070
   237
  val equational_fun_axioms : hol_context -> styp -> term list
blanchet@35070
   238
  val is_equational_fun_surely_complete : hol_context -> styp -> bool
blanchet@38212
   239
  val merged_type_var_table_for_terms :
blanchet@38212
   240
    theory -> term list -> (sort * string) list
blanchet@38212
   241
  val merge_type_vars_in_term :
blanchet@38212
   242
    theory -> bool -> (sort * string) list -> term -> term
blanchet@35190
   243
  val ground_types_in_type : hol_context -> bool -> typ -> typ list
blanchet@35190
   244
  val ground_types_in_terms : hol_context -> bool -> term list -> typ list
blanchet@33192
   245
end;
blanchet@33192
   246
blanchet@33232
   247
structure Nitpick_HOL : NITPICK_HOL =
blanchet@33192
   248
struct
blanchet@33192
   249
blanchet@33232
   250
open Nitpick_Util
blanchet@33192
   251
blanchet@33192
   252
type const_table = term list Symtab.table
blanchet@33192
   253
type special_fun = (styp * int list * term list) * styp
blanchet@33192
   254
type unrolled = styp * styp
blanchet@33192
   255
type wf_cache = (styp * (bool * bool)) list
blanchet@33192
   256
blanchet@36390
   257
type hol_context =
blanchet@36390
   258
  {thy: theory,
blanchet@36390
   259
   ctxt: Proof.context,
blanchet@36390
   260
   max_bisim_depth: int,
blanchet@36390
   261
   boxes: (typ option * bool option) list,
blanchet@36390
   262
   stds: (typ option * bool) list,
blanchet@36390
   263
   wfs: (styp option * bool option) list,
blanchet@36390
   264
   user_axioms: bool option,
blanchet@36390
   265
   debug: bool,
blanchet@38209
   266
   whacks: term list,
blanchet@36390
   267
   binary_ints: bool option,
blanchet@36390
   268
   destroy_constrs: bool,
blanchet@36390
   269
   specialize: bool,
blanchet@36390
   270
   star_linear_preds: bool,
blanchet@41871
   271
   total_consts: bool option,
blanchet@41876
   272
   needs: term list option,
blanchet@36390
   273
   tac_timeout: Time.time option,
blanchet@36390
   274
   evals: term list,
blanchet@36390
   275
   case_names: (string * int) list,
blanchet@41791
   276
   def_tables: const_table * const_table,
blanchet@36390
   277
   nondef_table: const_table,
blanchet@42415
   278
   nondefs: term list,
blanchet@36390
   279
   simp_table: const_table Unsynchronized.ref,
blanchet@36390
   280
   psimp_table: const_table,
blanchet@36390
   281
   choice_spec_table: const_table,
blanchet@36390
   282
   intro_table: const_table,
blanchet@36390
   283
   ground_thm_table: term list Inttab.table,
blanchet@36390
   284
   ersatz_table: (string * string) list,
blanchet@36390
   285
   skolems: (string * string list) list Unsynchronized.ref,
blanchet@36390
   286
   special_funs: special_fun list Unsynchronized.ref,
blanchet@36390
   287
   unrolled_preds: unrolled list Unsynchronized.ref,
blanchet@36390
   288
   wf_cache: wf_cache Unsynchronized.ref,
blanchet@36390
   289
   constr_cache: (typ * styp list) list Unsynchronized.ref}
blanchet@33192
   290
blanchet@35070
   291
datatype fixpoint_kind = Lfp | Gfp | NoFp
blanchet@35070
   292
datatype boxability =
blanchet@35070
   293
  InConstr | InSel | InExpr | InPair | InFunLHS | InFunRHS1 | InFunRHS2
blanchet@35070
   294
wenzelm@41472
   295
structure Data = Generic_Data
wenzelm@41472
   296
(
blanchet@33192
   297
  type T = {frac_types: (string * (string * string) list) list,
krauss@44012
   298
            ersatz_table: (string * string) list,
blanchet@33192
   299
            codatatypes: (string * (string * styp list)) list}
krauss@44012
   300
  val empty = {frac_types = [], ersatz_table = [], codatatypes = []}
blanchet@33192
   301
  val extend = I
krauss@44012
   302
  fun merge ({frac_types = fs1, ersatz_table = et1, codatatypes = cs1},
krauss@44012
   303
             {frac_types = fs2, ersatz_table = et2, codatatypes = cs2}) : T =
wenzelm@33699
   304
    {frac_types = AList.merge (op =) (K true) (fs1, fs2),
krauss@44012
   305
     ersatz_table = AList.merge (op =) (K true) (et1, et2),
wenzelm@41472
   306
     codatatypes = AList.merge (op =) (K true) (cs1, cs2)}
wenzelm@41472
   307
)
blanchet@33192
   308
blanchet@33192
   309
val name_sep = "$"
blanchet@33192
   310
val numeral_prefix = nitpick_prefix ^ "num" ^ name_sep
blanchet@33192
   311
val sel_prefix = nitpick_prefix ^ "sel"
blanchet@33192
   312
val discr_prefix = nitpick_prefix ^ "is" ^ name_sep
blanchet@33192
   313
val set_prefix = nitpick_prefix ^ "set" ^ name_sep
blanchet@33192
   314
val lfp_iterator_prefix = nitpick_prefix ^ "lfpit" ^ name_sep
blanchet@33192
   315
val gfp_iterator_prefix = nitpick_prefix ^ "gfpit" ^ name_sep
blanchet@33192
   316
val unrolled_prefix = nitpick_prefix ^ "unroll" ^ name_sep
blanchet@33192
   317
val base_prefix = nitpick_prefix ^ "base" ^ name_sep
blanchet@33192
   318
val step_prefix = nitpick_prefix ^ "step" ^ name_sep
blanchet@33192
   319
val ubfp_prefix = nitpick_prefix ^ "ubfp" ^ name_sep
blanchet@33192
   320
val lbfp_prefix = nitpick_prefix ^ "lbfp" ^ name_sep
blanchet@35311
   321
val quot_normal_prefix = nitpick_prefix ^ "qn" ^ name_sep
blanchet@33192
   322
val skolem_prefix = nitpick_prefix ^ "sk"
blanchet@33192
   323
val special_prefix = nitpick_prefix ^ "sp"
blanchet@33192
   324
val uncurry_prefix = nitpick_prefix ^ "unc"
blanchet@33192
   325
val eval_prefix = nitpick_prefix ^ "eval"
blanchet@33192
   326
val iter_var_prefix = "i"
blanchet@35718
   327
blanchet@35718
   328
(** Constant/type information and term/type manipulation **)
blanchet@33192
   329
blanchet@33192
   330
fun sel_prefix_for j = sel_prefix ^ string_of_int j ^ name_sep
blanchet@35311
   331
fun quot_normal_name_for_type ctxt T =
blanchet@35311
   332
  quot_normal_prefix ^ unyxml (Syntax.string_of_typ ctxt T)
blanchet@33192
   333
blanchet@33192
   334
val strip_first_name_sep =
blanchet@33192
   335
  Substring.full #> Substring.position name_sep ##> Substring.triml 1
blanchet@33192
   336
  #> pairself Substring.string
blanchet@33192
   337
fun original_name s =
blanchet@33192
   338
  if String.isPrefix nitpick_prefix s then
blanchet@33192
   339
    case strip_first_name_sep s of (s1, "") => s1 | (_, s2) => original_name s2
blanchet@33192
   340
  else
blanchet@33192
   341
    s
blanchet@35718
   342
blanchet@34998
   343
fun s_conj (t1, @{const True}) = t1
blanchet@34998
   344
  | s_conj (@{const True}, t2) = t2
blanchet@34998
   345
  | s_conj (t1, t2) =
blanchet@34998
   346
    if t1 = @{const False} orelse t2 = @{const False} then @{const False}
blanchet@34998
   347
    else HOLogic.mk_conj (t1, t2)
blanchet@34998
   348
fun s_disj (t1, @{const False}) = t1
blanchet@34998
   349
  | s_disj (@{const False}, t2) = t2
blanchet@34998
   350
  | s_disj (t1, t2) =
blanchet@34998
   351
    if t1 = @{const True} orelse t2 = @{const True} then @{const True}
blanchet@34998
   352
    else HOLogic.mk_disj (t1, t2)
blanchet@34998
   353
blanchet@34998
   354
fun strip_connective conn_t (t as (t0 $ t1 $ t2)) =
blanchet@34998
   355
    if t0 = conn_t then strip_connective t0 t2 @ strip_connective t0 t1 else [t]
blanchet@34998
   356
  | strip_connective _ t = [t]
blanchet@35280
   357
fun strip_any_connective (t as (t0 $ _ $ _)) =
haftmann@38795
   358
    if t0 = @{const HOL.conj} orelse t0 = @{const HOL.disj} then
blanchet@34998
   359
      (strip_connective t0 t, t0)
blanchet@34998
   360
    else
blanchet@34998
   361
      ([t], @{const Not})
blanchet@34998
   362
  | strip_any_connective t = ([t], @{const Not})
haftmann@38795
   363
val conjuncts_of = strip_connective @{const HOL.conj}
haftmann@38795
   364
val disjuncts_of = strip_connective @{const HOL.disj}
blanchet@34998
   365
blanchet@33192
   366
(* When you add constants to these lists, make sure to handle them in
blanchet@33232
   367
   "Nitpick_Nut.nut_from_term", and perhaps in "Nitpick_Mono.consider_term" as
blanchet@33192
   368
   well. *)
blanchet@33192
   369
val built_in_consts =
blanchet@33192
   370
  [(@{const_name all}, 1),
blanchet@33192
   371
   (@{const_name "=="}, 2),
blanchet@33192
   372
   (@{const_name "==>"}, 2),
blanchet@33192
   373
   (@{const_name Pure.conjunction}, 2),
blanchet@33192
   374
   (@{const_name Trueprop}, 1),
blanchet@33192
   375
   (@{const_name Not}, 1),
blanchet@33192
   376
   (@{const_name False}, 0),
blanchet@33192
   377
   (@{const_name True}, 0),
blanchet@33192
   378
   (@{const_name All}, 1),
blanchet@33192
   379
   (@{const_name Ex}, 1),
haftmann@38864
   380
   (@{const_name HOL.eq}, 1),
haftmann@38795
   381
   (@{const_name HOL.conj}, 2),
haftmann@38795
   382
   (@{const_name HOL.disj}, 2),
haftmann@38786
   383
   (@{const_name HOL.implies}, 2),
blanchet@33192
   384
   (@{const_name If}, 3),
blanchet@33192
   385
   (@{const_name Let}, 2),
blanchet@33192
   386
   (@{const_name Pair}, 2),
blanchet@33192
   387
   (@{const_name fst}, 1),
blanchet@33192
   388
   (@{const_name snd}, 1),
blanchet@46083
   389
   (@{const_name Set.member}, 2),
blanchet@46083
   390
   (@{const_name Collect}, 1),
blanchet@33192
   391
   (@{const_name Id}, 0),
blanchet@33192
   392
   (@{const_name converse}, 1),
blanchet@33192
   393
   (@{const_name trancl}, 1),
griff@47433
   394
   (@{const_name relcomp}, 2),
blanchet@33192
   395
   (@{const_name finite}, 1),
blanchet@34936
   396
   (@{const_name unknown}, 0),
blanchet@34936
   397
   (@{const_name is_unknown}, 1),
blanchet@35671
   398
   (@{const_name safe_The}, 1),
blanchet@47909
   399
   (@{const_name Nitpick.Frac}, 0),
blanchet@47909
   400
   (@{const_name Nitpick.norm_frac}, 0)]
blanchet@35220
   401
val built_in_nat_consts =
blanchet@35220
   402
  [(@{const_name Suc}, 0),
blanchet@35220
   403
   (@{const_name nat}, 0),
blanchet@47909
   404
   (@{const_name Nitpick.nat_gcd}, 0),
blanchet@47909
   405
   (@{const_name Nitpick.nat_lcm}, 0)]
blanchet@33192
   406
val built_in_typed_consts =
blanchet@35220
   407
  [((@{const_name zero_class.zero}, int_T), 0),
blanchet@35220
   408
   ((@{const_name one_class.one}, int_T), 0),
blanchet@35220
   409
   ((@{const_name plus_class.plus}, int_T --> int_T --> int_T), 0),
blanchet@35220
   410
   ((@{const_name minus_class.minus}, int_T --> int_T --> int_T), 0),
blanchet@35220
   411
   ((@{const_name times_class.times}, int_T --> int_T --> int_T), 0),
blanchet@35220
   412
   ((@{const_name div_class.div}, int_T --> int_T --> int_T), 0),
blanchet@35220
   413
   ((@{const_name uminus_class.uminus}, int_T --> int_T), 0),
blanchet@35220
   414
   ((@{const_name ord_class.less}, int_T --> int_T --> bool_T), 2),
blanchet@35220
   415
   ((@{const_name ord_class.less_eq}, int_T --> int_T --> bool_T), 2)]
blanchet@35220
   416
val built_in_typed_nat_consts =
blanchet@35220
   417
  [((@{const_name zero_class.zero}, nat_T), 0),
blanchet@35220
   418
   ((@{const_name one_class.one}, nat_T), 0),
blanchet@35220
   419
   ((@{const_name plus_class.plus}, nat_T --> nat_T --> nat_T), 0),
blanchet@35220
   420
   ((@{const_name minus_class.minus}, nat_T --> nat_T --> nat_T), 0),
blanchet@35220
   421
   ((@{const_name times_class.times}, nat_T --> nat_T --> nat_T), 0),
blanchet@35220
   422
   ((@{const_name div_class.div}, nat_T --> nat_T --> nat_T), 0),
blanchet@35220
   423
   ((@{const_name ord_class.less}, nat_T --> nat_T --> bool_T), 2),
blanchet@35220
   424
   ((@{const_name ord_class.less_eq}, nat_T --> nat_T --> bool_T), 2),
blanchet@35220
   425
   ((@{const_name of_nat}, nat_T --> int_T), 0)]
blanchet@46081
   426
val built_in_set_like_consts =
blanchet@37476
   427
  [(@{const_name ord_class.less_eq}, 2)]
blanchet@33192
   428
blanchet@35190
   429
fun unarize_type @{typ "unsigned_bit word"} = nat_T
blanchet@35190
   430
  | unarize_type @{typ "signed_bit word"} = int_T
blanchet@35190
   431
  | unarize_type (Type (s, Ts as _ :: _)) = Type (s, map unarize_type Ts)
blanchet@35190
   432
  | unarize_type T = T
blanchet@41052
   433
fun unarize_unbox_etc_type (Type (@{type_name fun_box}, Ts)) =
blanchet@35665
   434
    unarize_unbox_etc_type (Type (@{type_name fun}, Ts))
blanchet@35665
   435
  | unarize_unbox_etc_type (Type (@{type_name pair_box}, Ts)) =
blanchet@38190
   436
    Type (@{type_name prod}, map unarize_unbox_etc_type Ts)
blanchet@35665
   437
  | unarize_unbox_etc_type @{typ "unsigned_bit word"} = nat_T
blanchet@35665
   438
  | unarize_unbox_etc_type @{typ "signed_bit word"} = int_T
blanchet@35665
   439
  | unarize_unbox_etc_type (Type (s, Ts as _ :: _)) =
blanchet@35665
   440
    Type (s, map unarize_unbox_etc_type Ts)
blanchet@35665
   441
  | unarize_unbox_etc_type T = T
blanchet@35280
   442
fun uniterize_type (Type (s, Ts as _ :: _)) = Type (s, map uniterize_type Ts)
blanchet@35280
   443
  | uniterize_type @{typ bisim_iterator} = nat_T
blanchet@35280
   444
  | uniterize_type T = T
blanchet@35665
   445
val uniterize_unarize_unbox_etc_type = uniterize_type o unarize_unbox_etc_type
blanchet@35280
   446
blanchet@35665
   447
fun string_for_type ctxt = Syntax.string_of_typ ctxt o unarize_unbox_etc_type
blanchet@38188
   448
fun pretty_for_type ctxt = Syntax.pretty_typ ctxt o unarize_unbox_etc_type
blanchet@33192
   449
blanchet@33192
   450
val prefix_name = Long_Name.qualify o Long_Name.base_name
blanchet@34121
   451
fun shortest_name s = List.last (space_explode "." s) handle List.Empty => ""
blanchet@33192
   452
val prefix_abs_vars = Term.map_abs_vars o prefix_name
blanchet@34121
   453
fun short_name s =
blanchet@33192
   454
  case space_explode name_sep s of
blanchet@33192
   455
    [_] => s |> String.isPrefix nitpick_prefix s ? unprefix nitpick_prefix
blanchet@34121
   456
  | ss => map shortest_name ss |> space_implode "_"
blanchet@34121
   457
fun shorten_names_in_type (Type (s, Ts)) =
blanchet@34121
   458
    Type (short_name s, map shorten_names_in_type Ts)
blanchet@34121
   459
  | shorten_names_in_type T = T
blanchet@34121
   460
val shorten_names_in_term =
blanchet@34121
   461
  map_aterms (fn Const (s, T) => Const (short_name s, T) | t => t)
blanchet@34121
   462
  #> map_types shorten_names_in_type
blanchet@33192
   463
blanchet@35665
   464
fun strict_type_match thy (T1, T2) =
blanchet@33192
   465
  (Sign.typ_match thy (T2, T1) Vartab.empty; true)
blanchet@33192
   466
  handle Type.TYPE_MATCH => false
blanchet@35665
   467
fun type_match thy = strict_type_match thy o pairself unarize_unbox_etc_type
blanchet@33192
   468
fun const_match thy ((s1, T1), (s2, T2)) =
blanchet@33192
   469
  s1 = s2 andalso type_match thy (T1, T2)
blanchet@33192
   470
fun term_match thy (Const x1, Const x2) = const_match thy (x1, x2)
blanchet@33192
   471
  | term_match thy (Free (s1, T1), Free (s2, T2)) =
blanchet@34121
   472
    const_match thy ((shortest_name s1, T1), (shortest_name s2, T2))
blanchet@35280
   473
  | term_match _ (t1, t2) = t1 aconv t2
blanchet@33192
   474
blanchet@35711
   475
fun frac_from_term_pair T t1 t2 =
blanchet@35711
   476
  case snd (HOLogic.dest_number t1) of
blanchet@35711
   477
    0 => HOLogic.mk_number T 0
blanchet@35711
   478
  | n1 => case snd (HOLogic.dest_number t2) of
blanchet@35711
   479
            1 => HOLogic.mk_number T n1
blanchet@35711
   480
          | n2 => Const (@{const_name divide}, T --> T --> T)
blanchet@35711
   481
                  $ HOLogic.mk_number T n1 $ HOLogic.mk_number T n2
blanchet@35711
   482
blanchet@33192
   483
fun is_TFree (TFree _) = true
blanchet@33192
   484
  | is_TFree _ = false
blanchet@35665
   485
fun is_fun_type (Type (@{type_name fun}, _)) = true
blanchet@33192
   486
  | is_fun_type _ = false
blanchet@46115
   487
fun is_set_type (Type (@{type_name set}, _)) = true
blanchet@46115
   488
  | is_set_type _ = false
blanchet@46115
   489
val is_fun_or_set_type = is_fun_type orf is_set_type
blanchet@46115
   490
fun is_set_like_type (Type (@{type_name fun}, [_, T'])) =
blanchet@46115
   491
    (body_type T' = bool_T)
blanchet@46081
   492
  | is_set_like_type (Type (@{type_name set}, _)) = true
blanchet@46081
   493
  | is_set_like_type _ = false
blanchet@38190
   494
fun is_pair_type (Type (@{type_name prod}, _)) = true
blanchet@33192
   495
  | is_pair_type _ = false
blanchet@33192
   496
fun is_lfp_iterator_type (Type (s, _)) = String.isPrefix lfp_iterator_prefix s
blanchet@33192
   497
  | is_lfp_iterator_type _ = false
blanchet@33192
   498
fun is_gfp_iterator_type (Type (s, _)) = String.isPrefix gfp_iterator_prefix s
blanchet@33192
   499
  | is_gfp_iterator_type _ = false
blanchet@33192
   500
val is_fp_iterator_type = is_lfp_iterator_type orf is_gfp_iterator_type
blanchet@35280
   501
fun is_iterator_type T =
blanchet@35280
   502
  (T = @{typ bisim_iterator} orelse is_fp_iterator_type T)
blanchet@34121
   503
fun is_boolean_type T = (T = prop_T orelse T = bool_T)
blanchet@35220
   504
fun is_integer_type T = (T = nat_T orelse T = int_T)
blanchet@34124
   505
fun is_bit_type T = (T = @{typ unsigned_bit} orelse T = @{typ signed_bit})
blanchet@34124
   506
fun is_word_type (Type (@{type_name word}, _)) = true
blanchet@34124
   507
  | is_word_type _ = false
blanchet@35280
   508
val is_integer_like_type = is_iterator_type orf is_integer_type orf is_word_type
blanchet@33192
   509
val is_record_type = not o null o Record.dest_recTs
blanchet@38240
   510
fun is_frac_type ctxt (Type (s, [])) =
krauss@44012
   511
    s |> AList.defined (op =) (#frac_types (Data.get (Context.Proof ctxt)))
blanchet@33192
   512
  | is_frac_type _ _ = false
blanchet@38240
   513
fun is_number_type ctxt = is_integer_like_type orf is_frac_type ctxt
blanchet@41860
   514
fun is_higher_order_type (Type (@{type_name fun}, _)) = true
blanchet@46115
   515
  | is_higher_order_type (Type (@{type_name set}, _)) = true
blanchet@41860
   516
  | is_higher_order_type (Type (_, Ts)) = exists is_higher_order_type Ts
blanchet@41860
   517
  | is_higher_order_type _ = false
blanchet@33192
   518
blanchet@46083
   519
fun elem_type (Type (@{type_name set}, [T'])) = T'
blanchet@46081
   520
  | elem_type T = raise TYPE ("Nitpick_HOL.elem_type", [T], [])
blanchet@46083
   521
fun pseudo_domain_type (Type (@{type_name fun}, [T1, _])) = T1
blanchet@46083
   522
  | pseudo_domain_type T = elem_type T
blanchet@46083
   523
fun pseudo_range_type (Type (@{type_name fun}, [_, T2])) = T2
blanchet@46083
   524
  | pseudo_range_type (Type (@{type_name set}, _)) = bool_T
blanchet@46083
   525
  | pseudo_range_type T = raise TYPE ("Nitpick_HOL.pseudo_range_type", [T], [])
blanchet@46081
   526
blanchet@33192
   527
fun iterator_type_for_const gfp (s, T) =
blanchet@33192
   528
  Type ((if gfp then gfp_iterator_prefix else lfp_iterator_prefix) ^ s,
blanchet@33192
   529
        binder_types T)
blanchet@35718
   530
fun const_for_iterator_type (Type (s, Ts)) =
blanchet@35718
   531
    (strip_first_name_sep s |> snd, Ts ---> bool_T)
blanchet@33192
   532
  | const_for_iterator_type T =
blanchet@33232
   533
    raise TYPE ("Nitpick_HOL.const_for_iterator_type", [T], [])
blanchet@33192
   534
blanchet@33192
   535
fun strip_n_binders 0 T = ([], T)
blanchet@35665
   536
  | strip_n_binders n (Type (@{type_name fun}, [T1, T2])) =
blanchet@33192
   537
    strip_n_binders (n - 1) T2 |>> cons T1
blanchet@33192
   538
  | strip_n_binders n (Type (@{type_name fun_box}, Ts)) =
blanchet@35665
   539
    strip_n_binders n (Type (@{type_name fun}, Ts))
blanchet@33232
   540
  | strip_n_binders _ T = raise TYPE ("Nitpick_HOL.strip_n_binders", [T], [])
blanchet@33192
   541
val nth_range_type = snd oo strip_n_binders
blanchet@33192
   542
blanchet@38190
   543
fun num_factors_in_type (Type (@{type_name prod}, [T1, T2])) =
blanchet@33192
   544
    fold (Integer.add o num_factors_in_type) [T1, T2] 0
blanchet@33192
   545
  | num_factors_in_type _ = 1
blanchet@35665
   546
fun num_binder_types (Type (@{type_name fun}, [_, T2])) =
blanchet@35665
   547
    1 + num_binder_types T2
blanchet@33192
   548
  | num_binder_types _ = 0
blanchet@33192
   549
val curried_binder_types = maps HOLogic.flatten_tupleT o binder_types
blanchet@33192
   550
fun maybe_curried_binder_types T =
blanchet@33192
   551
  (if is_pair_type (body_type T) then binder_types else curried_binder_types) T
blanchet@33192
   552
blanchet@33192
   553
fun mk_flat_tuple _ [t] = t
blanchet@38190
   554
  | mk_flat_tuple (Type (@{type_name prod}, [T1, T2])) (t :: ts) =
blanchet@33192
   555
    HOLogic.pair_const T1 T2 $ t $ (mk_flat_tuple T2 ts)
blanchet@33232
   556
  | mk_flat_tuple T ts = raise TYPE ("Nitpick_HOL.mk_flat_tuple", [T], ts)
blanchet@33192
   557
fun dest_n_tuple 1 t = [t]
blanchet@33192
   558
  | dest_n_tuple n t = HOLogic.dest_prod t ||> dest_n_tuple (n - 1) |> op ::
blanchet@33192
   559
blanchet@35220
   560
type typedef_info =
blanchet@35220
   561
  {rep_type: typ, abs_type: typ, Rep_name: string, Abs_name: string,
wenzelm@49833
   562
   prop_of_Rep: thm, set_name: string, Abs_inverse: thm option, Rep_inverse: thm option}
blanchet@35220
   563
blanchet@37256
   564
fun typedef_info ctxt s =
blanchet@38240
   565
  if is_frac_type ctxt (Type (s, [])) then
blanchet@38240
   566
    SOME {abs_type = Type (s, []), rep_type = @{typ "int * int"},
blanchet@47909
   567
          Abs_name = @{const_name Nitpick.Abs_Frac},
blanchet@47909
   568
          Rep_name = @{const_name Nitpick.Rep_Frac},
blanchet@47909
   569
          prop_of_Rep = @{prop "Nitpick.Rep_Frac x \<in> Collect Nitpick.Frac"}
blanchet@47909
   570
                        |> Logic.varify_global,
blanchet@47909
   571
          set_name = @{const_name Nitpick.Frac}, Abs_inverse = NONE,
blanchet@47909
   572
          Rep_inverse = NONE}
blanchet@38240
   573
  else case Typedef.get_info ctxt s of
blanchet@38240
   574
    (* When several entries are returned, it shouldn't matter much which one
blanchet@38240
   575
       we take (according to Florian Haftmann). *)
blanchet@39315
   576
    (* The "Logic.varifyT_global" calls are a temporary hack because these
blanchet@39315
   577
       types's type variables sometimes clash with locally fixed type variables.
blanchet@39315
   578
       Remove these calls once "Typedef" is fully localized. *)
blanchet@38240
   579
    ({abs_type, rep_type, Abs_name, Rep_name, ...},
wenzelm@49833
   580
     {Rep, Abs_inverse, Rep_inverse, ...}) :: _ =>
blanchet@39315
   581
    SOME {abs_type = Logic.varifyT_global abs_type,
blanchet@39315
   582
          rep_type = Logic.varifyT_global rep_type, Abs_name = Abs_name,
wenzelm@49833
   583
          Rep_name = Rep_name, prop_of_Rep = prop_of Rep,
blanchet@38240
   584
          set_name = set_prefix ^ s, Abs_inverse = SOME Abs_inverse,
blanchet@38240
   585
          Rep_inverse = SOME Rep_inverse}
blanchet@38240
   586
  | _ => NONE
blanchet@35220
   587
blanchet@35220
   588
val is_typedef = is_some oo typedef_info
blanchet@35220
   589
val is_real_datatype = is_some oo Datatype.get_info
blanchet@35220
   590
fun is_standard_datatype thy = the oo triple_lookup (type_match thy)
blanchet@35220
   591
haftmann@51143
   592
(* FIXME: Use antiquotation for "natural" below or detect "rep_datatype",
blanchet@34121
   593
   e.g., by adding a field to "Datatype_Aux.info". *)
blanchet@35220
   594
fun is_basic_datatype thy stds s =
blanchet@46083
   595
  member (op =) [@{type_name prod}, @{type_name set}, @{type_name bool},
haftmann@51143
   596
                 @{type_name int}, @{type_name natural}, @{type_name integer}] s orelse
blanchet@35220
   597
  (s = @{type_name nat} andalso is_standard_datatype thy stds nat_T)
blanchet@34121
   598
blanchet@38240
   599
fun repair_constr_type ctxt body_T' T =
blanchet@38240
   600
  varify_and_instantiate_type ctxt (body_type T) body_T' T
blanchet@33192
   601
blanchet@38240
   602
fun register_frac_type_generic frac_s ersaetze generic =
blanchet@33192
   603
  let
krauss@44012
   604
    val {frac_types, ersatz_table, codatatypes} = Data.get generic
blanchet@33192
   605
    val frac_types = AList.update (op =) (frac_s, ersaetze) frac_types
krauss@44012
   606
  in Data.put {frac_types = frac_types, ersatz_table = ersatz_table,
krauss@44012
   607
               codatatypes = codatatypes} generic end
blanchet@38284
   608
(* TODO: Consider morphism. *)
blanchet@38284
   609
fun register_frac_type frac_s ersaetze (_ : morphism) =
blanchet@38284
   610
  register_frac_type_generic frac_s ersaetze
blanchet@38240
   611
val register_frac_type_global = Context.theory_map oo register_frac_type_generic
blanchet@33192
   612
blanchet@38240
   613
fun unregister_frac_type_generic frac_s = register_frac_type_generic frac_s []
blanchet@38284
   614
(* TODO: Consider morphism. *)
blanchet@38284
   615
fun unregister_frac_type frac_s (_ : morphism) =
blanchet@38284
   616
  unregister_frac_type_generic frac_s
blanchet@38240
   617
val unregister_frac_type_global =
blanchet@38240
   618
  Context.theory_map o unregister_frac_type_generic
blanchet@38240
   619
krauss@44012
   620
fun register_ersatz_generic ersatz generic =
krauss@44012
   621
  let
krauss@44012
   622
    val {frac_types, ersatz_table, codatatypes} = Data.get generic
krauss@44012
   623
    val ersatz_table = AList.merge (op =) (K true) (ersatz_table, ersatz)
krauss@44012
   624
  in Data.put {frac_types = frac_types, ersatz_table = ersatz_table,
krauss@44012
   625
               codatatypes = codatatypes} generic end
krauss@44012
   626
(* TODO: Consider morphism. *)
krauss@44012
   627
fun register_ersatz ersatz (_ : morphism) =
krauss@44012
   628
  register_ersatz_generic ersatz
krauss@44012
   629
val register_ersatz_global = Context.theory_map o register_ersatz_generic
krauss@44012
   630
blanchet@38240
   631
fun register_codatatype_generic co_T case_name constr_xs generic =
blanchet@33192
   632
  let
blanchet@38240
   633
    val ctxt = Context.proof_of generic
blanchet@38240
   634
    val thy = Context.theory_of generic
krauss@44012
   635
    val {frac_types, ersatz_table, codatatypes} = Data.get generic
blanchet@38240
   636
    val constr_xs = map (apsnd (repair_constr_type ctxt co_T)) constr_xs
blanchet@33192
   637
    val (co_s, co_Ts) = dest_Type co_T
blanchet@33192
   638
    val _ =
blanchet@34936
   639
      if forall is_TFree co_Ts andalso not (has_duplicates (op =) co_Ts) andalso
blanchet@35665
   640
         co_s <> @{type_name fun} andalso
blanchet@35220
   641
         not (is_basic_datatype thy [(NONE, true)] co_s) then
blanchet@34121
   642
        ()
blanchet@34121
   643
      else
blanchet@38242
   644
        raise TYPE ("Nitpick_HOL.register_codatatype_generic", [co_T], [])
blanchet@33192
   645
    val codatatypes = AList.update (op =) (co_s, (case_name, constr_xs))
blanchet@33192
   646
                                   codatatypes
krauss@44012
   647
  in Data.put {frac_types = frac_types, ersatz_table = ersatz_table,
krauss@44012
   648
               codatatypes = codatatypes} generic end
blanchet@38284
   649
(* TODO: Consider morphism. *)
blanchet@38284
   650
fun register_codatatype co_T case_name constr_xs (_ : morphism) =
blanchet@38284
   651
  register_codatatype_generic co_T case_name constr_xs
blanchet@38240
   652
val register_codatatype_global =
blanchet@38240
   653
  Context.theory_map ooo register_codatatype_generic
blanchet@33192
   654
blanchet@38240
   655
fun unregister_codatatype_generic co_T = register_codatatype_generic co_T "" []
blanchet@38284
   656
(* TODO: Consider morphism. *)
blanchet@38284
   657
fun unregister_codatatype co_T (_ : morphism) =
blanchet@38284
   658
  unregister_codatatype_generic co_T
blanchet@38240
   659
val unregister_codatatype_global =
blanchet@38240
   660
  Context.theory_map o unregister_codatatype_generic
blanchet@38240
   661
blanchet@38240
   662
fun is_codatatype ctxt (Type (s, _)) =
blanchet@38240
   663
    s |> AList.lookup (op =) (#codatatypes (Data.get (Context.Proof ctxt)))
blanchet@38240
   664
      |> Option.map snd |> these |> null |> not
blanchet@33192
   665
  | is_codatatype _ _ = false
blanchet@47909
   666
fun is_registered_type ctxt T = is_frac_type ctxt T orelse is_codatatype ctxt T
wenzelm@45280
   667
fun is_real_quot_type ctxt (Type (s, _)) =
wenzelm@45280
   668
    is_some (Quotient_Info.lookup_quotients ctxt s)
blanchet@38215
   669
  | is_real_quot_type _ _ = false
blanchet@38240
   670
fun is_quot_type ctxt T =
blanchet@48812
   671
  is_real_quot_type ctxt T andalso not (is_registered_type ctxt T) andalso
blanchet@48812
   672
  T <> @{typ int}
blanchet@37256
   673
fun is_pure_typedef ctxt (T as Type (s, _)) =
wenzelm@42361
   674
    let val thy = Proof_Context.theory_of ctxt in
blanchet@47909
   675
      is_frac_type ctxt T orelse
blanchet@47909
   676
      (is_typedef ctxt s andalso
blanchet@47909
   677
       not (is_real_datatype thy s orelse is_real_quot_type ctxt T orelse
blanchet@47909
   678
            is_codatatype ctxt T orelse is_record_type T orelse
blanchet@47909
   679
            is_integer_like_type T))
blanchet@37256
   680
    end
blanchet@33192
   681
  | is_pure_typedef _ _ = false
blanchet@37256
   682
fun is_univ_typedef ctxt (Type (s, _)) =
blanchet@37256
   683
    (case typedef_info ctxt s of
wenzelm@49833
   684
       SOME {prop_of_Rep, ...} =>
blanchet@35332
   685
       let
blanchet@35332
   686
         val t_opt =
wenzelm@49833
   687
           try (snd o HOLogic.dest_mem o HOLogic.dest_Trueprop) prop_of_Rep
blanchet@35332
   688
       in
blanchet@35332
   689
         case t_opt of
blanchet@35332
   690
           SOME (Const (@{const_name top}, _)) => true
blanchet@35386
   691
           (* "Multiset.multiset" *)
blanchet@35332
   692
         | SOME (Const (@{const_name Collect}, _)
blanchet@35332
   693
                 $ Abs (_, _, Const (@{const_name finite}, _) $ _)) => true
blanchet@35386
   694
           (* "FinFun.finfun" *)
blanchet@35386
   695
         | SOME (Const (@{const_name Collect}, _) $ Abs (_, _,
blanchet@35386
   696
                     Const (@{const_name Ex}, _) $ Abs (_, _,
blanchet@35386
   697
                         Const (@{const_name finite}, _) $ _))) => true
blanchet@35332
   698
         | _ => false
blanchet@35332
   699
       end
blanchet@33192
   700
     | NONE => false)
blanchet@33192
   701
  | is_univ_typedef _ _ = false
blanchet@37256
   702
fun is_datatype ctxt stds (T as Type (s, _)) =
wenzelm@42361
   703
    let val thy = Proof_Context.theory_of ctxt in
blanchet@47909
   704
      (is_typedef ctxt s orelse is_registered_type ctxt T orelse
wenzelm@45280
   705
       T = @{typ ind} orelse is_real_quot_type ctxt T) andalso
blanchet@38240
   706
      not (is_basic_datatype thy stds s)
blanchet@37256
   707
    end
blanchet@35220
   708
  | is_datatype _ _ _ = false
blanchet@33192
   709
blanchet@33192
   710
fun all_record_fields thy T =
blanchet@33192
   711
  let val (recs, more) = Record.get_extT_fields thy T in
blanchet@33192
   712
    recs @ more :: all_record_fields thy (snd more)
blanchet@33192
   713
  end
blanchet@33192
   714
  handle TYPE _ => []
blanchet@35280
   715
fun is_record_constr (s, T) =
blanchet@33192
   716
  String.isSuffix Record.extN s andalso
blanchet@33192
   717
  let val dataT = body_type T in
blanchet@33192
   718
    is_record_type dataT andalso
blanchet@33192
   719
    s = unsuffix Record.ext_typeN (fst (dest_Type dataT)) ^ Record.extN
blanchet@33192
   720
  end
blanchet@33192
   721
val num_record_fields = Integer.add 1 o length o fst oo Record.get_extT_fields
blanchet@33192
   722
fun no_of_record_field thy s T1 =
blanchet@34121
   723
  find_index (curry (op =) s o fst)
blanchet@34121
   724
             (Record.get_extT_fields thy T1 ||> single |> op @)
blanchet@35665
   725
fun is_record_get thy (s, Type (@{type_name fun}, [T1, _])) =
blanchet@34121
   726
    exists (curry (op =) s o fst) (all_record_fields thy T1)
blanchet@33192
   727
  | is_record_get _ _ = false
blanchet@33192
   728
fun is_record_update thy (s, T) =
blanchet@33192
   729
  String.isSuffix Record.updateN s andalso
blanchet@34121
   730
  exists (curry (op =) (unsuffix Record.updateN s) o fst)
blanchet@33192
   731
         (all_record_fields thy (body_type T))
blanchet@33192
   732
  handle TYPE _ => false
blanchet@37256
   733
fun is_abs_fun ctxt (s, Type (@{type_name fun}, [_, Type (s', _)])) =
blanchet@37256
   734
    (case typedef_info ctxt s' of
blanchet@33192
   735
       SOME {Abs_name, ...} => s = Abs_name
blanchet@33192
   736
     | NONE => false)
blanchet@33192
   737
  | is_abs_fun _ _ = false
blanchet@37256
   738
fun is_rep_fun ctxt (s, Type (@{type_name fun}, [Type (s', _), _])) =
blanchet@37256
   739
    (case typedef_info ctxt s' of
blanchet@33192
   740
       SOME {Rep_name, ...} => s = Rep_name
blanchet@33192
   741
     | NONE => false)
blanchet@33192
   742
  | is_rep_fun _ _ = false
blanchet@38215
   743
fun is_quot_abs_fun ctxt (x as (_, Type (@{type_name fun},
blanchet@38215
   744
                                         [_, abs_T as Type (s', _)]))) =
kuncar@45797
   745
    try (Quotient_Term.absrep_const_chk ctxt Quotient_Term.AbsF) s'
blanchet@47909
   746
    = SOME (Const x) andalso not (is_registered_type ctxt abs_T)
blanchet@34936
   747
  | is_quot_abs_fun _ _ = false
blanchet@46819
   748
fun is_quot_rep_fun ctxt (s, Type (@{type_name fun},
blanchet@46819
   749
                                   [abs_T as Type (abs_s, _), _])) =
blanchet@46746
   750
    (case try (Quotient_Term.absrep_const_chk ctxt Quotient_Term.RepF) abs_s of
blanchet@47909
   751
       SOME (Const (s', _)) =>
blanchet@47909
   752
       s = s' andalso not (is_registered_type ctxt abs_T)
blanchet@48811
   753
     | _ => false)
blanchet@34936
   754
  | is_quot_rep_fun _ _ = false
blanchet@33192
   755
blanchet@37256
   756
fun mate_of_rep_fun ctxt (x as (_, Type (@{type_name fun},
blanchet@37256
   757
                                         [T1 as Type (s', _), T2]))) =
blanchet@37256
   758
    (case typedef_info ctxt s' of
blanchet@35665
   759
       SOME {Abs_name, ...} => (Abs_name, Type (@{type_name fun}, [T2, T1]))
blanchet@33232
   760
     | NONE => raise TERM ("Nitpick_HOL.mate_of_rep_fun", [Const x]))
blanchet@33232
   761
  | mate_of_rep_fun _ x = raise TERM ("Nitpick_HOL.mate_of_rep_fun", [Const x])
wenzelm@45280
   762
fun rep_type_for_quot_type ctxt (T as Type (s, _)) =
wenzelm@45280
   763
    let
wenzelm@45280
   764
      val thy = Proof_Context.theory_of ctxt
wenzelm@45280
   765
      val {qtyp, rtyp, ...} = the (Quotient_Info.lookup_quotients ctxt s)
wenzelm@45280
   766
    in
blanchet@39345
   767
      instantiate_type thy qtyp T rtyp
blanchet@39345
   768
    end
blanchet@39345
   769
  | rep_type_for_quot_type _ T =
blanchet@39345
   770
    raise TYPE ("Nitpick_HOL.rep_type_for_quot_type", [T], [])
blanchet@35284
   771
fun equiv_relation_for_quot_type thy (Type (s, Ts)) =
blanchet@35284
   772
    let
blanchet@46745
   773
      val {qtyp, equiv_rel, equiv_thm, ...} =
blanchet@46745
   774
        the (Quotient_Info.lookup_quotients thy s)
blanchet@38243
   775
      val partial =
blanchet@38243
   776
        case prop_of equiv_thm of
blanchet@38243
   777
          @{const Trueprop} $ (Const (@{const_name equivp}, _) $ _) => false
blanchet@38243
   778
        | @{const Trueprop} $ (Const (@{const_name part_equivp}, _) $ _) => true
blanchet@38243
   779
        | _ => raise NOT_SUPPORTED "Ill-formed quotient type equivalence \
blanchet@38243
   780
                                   \relation theorem"
blanchet@35284
   781
      val Ts' = qtyp |> dest_Type |> snd
blanchet@38243
   782
    in (subst_atomic_types (Ts' ~~ Ts) equiv_rel, partial) end
blanchet@34936
   783
  | equiv_relation_for_quot_type _ T =
blanchet@34936
   784
    raise TYPE ("Nitpick_HOL.equiv_relation_for_quot_type", [T], [])
blanchet@33192
   785
blanchet@38240
   786
fun is_coconstr ctxt (s, T) =
blanchet@38240
   787
  case body_type T of
blanchet@38240
   788
    co_T as Type (co_s, _) =>
blanchet@38240
   789
    let val {codatatypes, ...} = Data.get (Context.Proof ctxt) in
blanchet@38240
   790
      exists (fn (s', T') => s = s' andalso repair_constr_type ctxt co_T T' = T)
blanchet@38240
   791
             (AList.lookup (op =) codatatypes co_s |> Option.map snd |> these)
blanchet@38240
   792
    end
blanchet@38240
   793
  | _ => false
blanchet@37256
   794
fun is_constr_like ctxt (s, T) =
blanchet@41052
   795
  member (op =) [@{const_name FunBox}, @{const_name PairBox},
blanchet@41052
   796
                 @{const_name Quot}, @{const_name Zero_Rep},
blanchet@41052
   797
                 @{const_name Suc_Rep}] s orelse
blanchet@37256
   798
  let
wenzelm@42361
   799
    val thy = Proof_Context.theory_of ctxt
blanchet@37256
   800
    val (x as (_, T)) = (s, unarize_unbox_etc_type T)
blanchet@37256
   801
  in
blanchet@37260
   802
    is_real_constr thy x orelse is_record_constr x orelse
blanchet@37256
   803
    (is_abs_fun ctxt x andalso is_pure_typedef ctxt (range_type T)) orelse
blanchet@38240
   804
    is_coconstr ctxt x
blanchet@33192
   805
  end
blanchet@47909
   806
fun is_stale_constr ctxt (x as (s, T)) =
blanchet@47909
   807
  is_registered_type ctxt (body_type T) andalso is_constr_like ctxt x andalso
blanchet@47909
   808
  not (s = @{const_name Nitpick.Abs_Frac} orelse is_coconstr ctxt x)
blanchet@37256
   809
fun is_constr ctxt stds (x as (_, T)) =
wenzelm@42361
   810
  let val thy = Proof_Context.theory_of ctxt in
blanchet@37256
   811
    is_constr_like ctxt x andalso
blanchet@37256
   812
    not (is_basic_datatype thy stds
blanchet@35220
   813
                         (fst (dest_Type (unarize_type (body_type T))))) andalso
blanchet@37256
   814
    not (is_stale_constr ctxt x)
blanchet@37256
   815
  end
blanchet@33192
   816
val is_sel = String.isPrefix discr_prefix orf String.isPrefix sel_prefix
blanchet@33192
   817
val is_sel_like_and_no_discr =
blanchet@35665
   818
  String.isPrefix sel_prefix orf
blanchet@35665
   819
  (member (op =) [@{const_name fst}, @{const_name snd}])
blanchet@33192
   820
blanchet@33192
   821
fun in_fun_lhs_for InConstr = InSel
blanchet@33192
   822
  | in_fun_lhs_for _ = InFunLHS
blanchet@33192
   823
fun in_fun_rhs_for InConstr = InConstr
blanchet@33192
   824
  | in_fun_rhs_for InSel = InSel
blanchet@33192
   825
  | in_fun_rhs_for InFunRHS1 = InFunRHS2
blanchet@33192
   826
  | in_fun_rhs_for _ = InFunRHS1
blanchet@33192
   827
blanchet@35070
   828
fun is_boxing_worth_it (hol_ctxt : hol_context) boxy T =
blanchet@33192
   829
  case T of
blanchet@35665
   830
    Type (@{type_name fun}, _) =>
blanchet@34936
   831
    (boxy = InPair orelse boxy = InFunLHS) andalso
blanchet@34936
   832
    not (is_boolean_type (body_type T))
blanchet@38190
   833
  | Type (@{type_name prod}, Ts) =>
blanchet@34936
   834
    boxy = InPair orelse boxy = InFunRHS1 orelse boxy = InFunRHS2 orelse
blanchet@34936
   835
    ((boxy = InExpr orelse boxy = InFunLHS) andalso
blanchet@35070
   836
     exists (is_boxing_worth_it hol_ctxt InPair)
blanchet@35070
   837
            (map (box_type hol_ctxt InPair) Ts))
blanchet@33192
   838
  | _ => false
blanchet@35280
   839
and should_box_type (hol_ctxt as {thy, boxes, ...}) boxy z =
blanchet@33192
   840
  case triple_lookup (type_match thy) boxes (Type z) of
blanchet@33192
   841
    SOME (SOME box_me) => box_me
blanchet@35070
   842
  | _ => is_boxing_worth_it hol_ctxt boxy (Type z)
blanchet@35070
   843
and box_type hol_ctxt boxy T =
blanchet@33192
   844
  case T of
blanchet@35665
   845
    Type (z as (@{type_name fun}, [T1, T2])) =>
blanchet@34936
   846
    if boxy <> InConstr andalso boxy <> InSel andalso
blanchet@35070
   847
       should_box_type hol_ctxt boxy z then
blanchet@33192
   848
      Type (@{type_name fun_box},
blanchet@35070
   849
            [box_type hol_ctxt InFunLHS T1, box_type hol_ctxt InFunRHS1 T2])
blanchet@33192
   850
    else
blanchet@35070
   851
      box_type hol_ctxt (in_fun_lhs_for boxy) T1
blanchet@35070
   852
      --> box_type hol_ctxt (in_fun_rhs_for boxy) T2
blanchet@38190
   853
  | Type (z as (@{type_name prod}, Ts)) =>
blanchet@34982
   854
    if boxy <> InConstr andalso boxy <> InSel
blanchet@35070
   855
       andalso should_box_type hol_ctxt boxy z then
blanchet@35070
   856
      Type (@{type_name pair_box}, map (box_type hol_ctxt InSel) Ts)
blanchet@33192
   857
    else
blanchet@38190
   858
      Type (@{type_name prod},
blanchet@35665
   859
            map (box_type hol_ctxt
blanchet@34121
   860
                          (if boxy = InConstr orelse boxy = InSel then boxy
blanchet@34121
   861
                           else InPair)) Ts)
blanchet@33192
   862
  | _ => T
blanchet@33192
   863
blanchet@35190
   864
fun binarize_nat_and_int_in_type @{typ nat} = @{typ "unsigned_bit word"}
blanchet@35190
   865
  | binarize_nat_and_int_in_type @{typ int} = @{typ "signed_bit word"}
blanchet@35190
   866
  | binarize_nat_and_int_in_type (Type (s, Ts)) =
blanchet@35190
   867
    Type (s, map binarize_nat_and_int_in_type Ts)
blanchet@35190
   868
  | binarize_nat_and_int_in_type T = T
blanchet@35190
   869
val binarize_nat_and_int_in_term = map_types binarize_nat_and_int_in_type
blanchet@35190
   870
blanchet@33192
   871
fun discr_for_constr (s, T) = (discr_prefix ^ s, body_type T --> bool_T)
blanchet@33192
   872
blanchet@33192
   873
fun num_sels_for_constr_type T = length (maybe_curried_binder_types T)
blanchet@33192
   874
fun nth_sel_name_for_constr_name s n =
blanchet@33192
   875
  if s = @{const_name Pair} then
blanchet@33192
   876
    if n = 0 then @{const_name fst} else @{const_name snd}
blanchet@33192
   877
  else
blanchet@33192
   878
    sel_prefix_for n ^ s
blanchet@33192
   879
fun nth_sel_for_constr x ~1 = discr_for_constr x
blanchet@33192
   880
  | nth_sel_for_constr (s, T) n =
blanchet@33192
   881
    (nth_sel_name_for_constr_name s n,
blanchet@33192
   882
     body_type T --> nth (maybe_curried_binder_types T) n)
blanchet@35190
   883
fun binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize =
blanchet@35190
   884
  apsnd ((binarize ? binarize_nat_and_int_in_type) o box_type hol_ctxt InSel)
blanchet@35190
   885
  oo nth_sel_for_constr
blanchet@33192
   886
blanchet@33192
   887
fun sel_no_from_name s =
blanchet@33192
   888
  if String.isPrefix discr_prefix s then
blanchet@33192
   889
    ~1
blanchet@33192
   890
  else if String.isPrefix sel_prefix s then
blanchet@33192
   891
    s |> unprefix sel_prefix |> Int.fromString |> the
blanchet@33192
   892
  else if s = @{const_name snd} then
blanchet@33192
   893
    1
blanchet@33192
   894
  else
blanchet@33192
   895
    0
blanchet@33192
   896
blanchet@35078
   897
val close_form =
blanchet@35078
   898
  let
blanchet@35078
   899
    fun close_up zs zs' =
blanchet@35078
   900
      fold (fn (z as ((s, _), T)) => fn t' =>
wenzelm@46217
   901
               Logic.all_const T $ Abs (s, T, abstract_over (Var z, t')))
blanchet@35078
   902
           (take (length zs' - length zs) zs')
blanchet@35078
   903
    fun aux zs (@{const "==>"} $ t1 $ t2) =
blanchet@35078
   904
        let val zs' = Term.add_vars t1 zs in
blanchet@35078
   905
          close_up zs zs' (Logic.mk_implies (t1, aux zs' t2))
blanchet@35078
   906
        end
blanchet@35078
   907
      | aux zs t = close_up zs (Term.add_vars t zs) t
blanchet@35078
   908
  in aux [] end
blanchet@35078
   909
blanchet@33192
   910
fun distinctness_formula T =
blanchet@33192
   911
  all_distinct_unordered_pairs_of
blanchet@33192
   912
  #> map (fn (t1, t2) => @{const Not} $ (HOLogic.eq_const T $ t1 $ t2))
blanchet@33192
   913
  #> List.foldr (s_conj o swap) @{const True}
blanchet@33192
   914
blanchet@35220
   915
fun zero_const T = Const (@{const_name zero_class.zero}, T)
blanchet@33192
   916
fun suc_const T = Const (@{const_name Suc}, T --> T)
blanchet@33192
   917
blanchet@37256
   918
fun uncached_datatype_constrs ({thy, ctxt, stds, ...} : hol_context)
blanchet@35220
   919
                              (T as Type (s, Ts)) =
blanchet@38240
   920
    (case AList.lookup (op =) (#codatatypes (Data.get (Context.Proof ctxt)))
blanchet@38240
   921
                       s of
blanchet@38240
   922
       SOME (_, xs' as (_ :: _)) => map (apsnd (repair_constr_type ctxt T)) xs'
blanchet@33581
   923
     | _ =>
blanchet@47909
   924
       if is_frac_type ctxt T then
blanchet@47909
   925
         case typedef_info ctxt s of
blanchet@47909
   926
           SOME {abs_type, rep_type, Abs_name, ...} =>
blanchet@47909
   927
           [(Abs_name,
blanchet@47909
   928
             varify_and_instantiate_type ctxt abs_type T rep_type --> T)]
blanchet@47909
   929
         | NONE => [] (* impossible *)
blanchet@47909
   930
       else if is_datatype ctxt stds T then
blanchet@33581
   931
         case Datatype.get_info thy s of
blanchet@33581
   932
           SOME {index, descr, ...} =>
blanchet@33581
   933
           let
blanchet@33581
   934
             val (_, dtyps, constrs) = AList.lookup (op =) descr index |> the
blanchet@33581
   935
           in
blanchet@37260
   936
             map (apsnd (fn Us =>
blanchet@37260
   937
                            map (typ_of_dtyp descr (dtyps ~~ Ts)) Us ---> T))
blanchet@37260
   938
                 constrs
blanchet@33581
   939
           end
blanchet@33581
   940
         | NONE =>
blanchet@33581
   941
           if is_record_type T then
blanchet@33581
   942
             let
blanchet@33581
   943
               val s' = unsuffix Record.ext_typeN s ^ Record.extN
blanchet@33581
   944
               val T' = (Record.get_extT_fields thy T
blanchet@33581
   945
                        |> apsnd single |> uncurry append |> map snd) ---> T
blanchet@33581
   946
             in [(s', T')] end
wenzelm@45280
   947
           else if is_real_quot_type ctxt T then
wenzelm@45280
   948
             [(@{const_name Quot}, rep_type_for_quot_type ctxt T --> T)]
blanchet@37256
   949
           else case typedef_info ctxt s of
blanchet@33581
   950
             SOME {abs_type, rep_type, Abs_name, ...} =>
blanchet@35311
   951
             [(Abs_name,
blanchet@38240
   952
               varify_and_instantiate_type ctxt abs_type T rep_type --> T)]
blanchet@33581
   953
           | NONE =>
blanchet@33581
   954
             if T = @{typ ind} then
blanchet@33581
   955
               [dest_Const @{const Zero_Rep}, dest_Const @{const Suc_Rep}]
blanchet@33581
   956
             else
blanchet@33581
   957
               []
blanchet@33581
   958
       else
blanchet@33581
   959
         [])
blanchet@33580
   960
  | uncached_datatype_constrs _ _ = []
blanchet@35220
   961
fun datatype_constrs (hol_ctxt as {constr_cache, ...}) T =
blanchet@33580
   962
  case AList.lookup (op =) (!constr_cache) T of
blanchet@33580
   963
    SOME xs => xs
blanchet@33580
   964
  | NONE =>
blanchet@35220
   965
    let val xs = uncached_datatype_constrs hol_ctxt T in
blanchet@33580
   966
      (Unsynchronized.change constr_cache (cons (T, xs)); xs)
blanchet@33580
   967
    end
blanchet@35190
   968
fun binarized_and_boxed_datatype_constrs hol_ctxt binarize =
blanchet@35190
   969
  map (apsnd ((binarize ? binarize_nat_and_int_in_type)
blanchet@35190
   970
              o box_type hol_ctxt InConstr)) o datatype_constrs hol_ctxt
blanchet@33192
   971
val num_datatype_constrs = length oo datatype_constrs
blanchet@33192
   972
blanchet@33192
   973
fun constr_name_for_sel_like @{const_name fst} = @{const_name Pair}
blanchet@33192
   974
  | constr_name_for_sel_like @{const_name snd} = @{const_name Pair}
blanchet@33192
   975
  | constr_name_for_sel_like s' = original_name s'
blanchet@35190
   976
fun binarized_and_boxed_constr_for_sel hol_ctxt binarize (s', T') =
blanchet@33192
   977
  let val s = constr_name_for_sel_like s' in
blanchet@35190
   978
    AList.lookup (op =)
blanchet@35190
   979
        (binarized_and_boxed_datatype_constrs hol_ctxt binarize (domain_type T'))
blanchet@35190
   980
        s
blanchet@33192
   981
    |> the |> pair s
blanchet@33192
   982
  end
blanchet@34982
   983
blanchet@41860
   984
fun card_of_type assigns (Type (@{type_name fun}, [T1, T2])) =
blanchet@41860
   985
    reasonable_power (card_of_type assigns T2) (card_of_type assigns T1)
blanchet@41860
   986
  | card_of_type assigns (Type (@{type_name prod}, [T1, T2])) =
blanchet@41860
   987
    card_of_type assigns T1 * card_of_type assigns T2
blanchet@46083
   988
  | card_of_type assigns (Type (@{type_name set}, [T'])) =
blanchet@46083
   989
    reasonable_power 2 (card_of_type assigns T')
blanchet@41860
   990
  | card_of_type _ (Type (@{type_name itself}, _)) = 1
blanchet@41860
   991
  | card_of_type _ @{typ prop} = 2
blanchet@41860
   992
  | card_of_type _ @{typ bool} = 2
blanchet@41860
   993
  | card_of_type assigns T =
blanchet@41860
   994
    case AList.lookup (op =) assigns T of
blanchet@41860
   995
      SOME k => k
blanchet@41860
   996
    | NONE => if T = @{typ bisim_iterator} then 0
blanchet@41860
   997
              else raise TYPE ("Nitpick_HOL.card_of_type", [T], [])
blanchet@41860
   998
blanchet@41860
   999
fun bounded_card_of_type max default_card assigns
blanchet@41860
  1000
                         (Type (@{type_name fun}, [T1, T2])) =
blanchet@41860
  1001
    let
blanchet@41860
  1002
      val k1 = bounded_card_of_type max default_card assigns T1
blanchet@41860
  1003
      val k2 = bounded_card_of_type max default_card assigns T2
blanchet@41860
  1004
    in
blanchet@41860
  1005
      if k1 = max orelse k2 = max then max
blanchet@41860
  1006
      else Int.min (max, reasonable_power k2 k1)
blanchet@47668
  1007
      handle TOO_LARGE _ => max
blanchet@41860
  1008
    end
blanchet@41860
  1009
  | bounded_card_of_type max default_card assigns
blanchet@41860
  1010
                         (Type (@{type_name prod}, [T1, T2])) =
blanchet@41860
  1011
    let
blanchet@41860
  1012
      val k1 = bounded_card_of_type max default_card assigns T1
blanchet@41860
  1013
      val k2 = bounded_card_of_type max default_card assigns T2
blanchet@41860
  1014
    in if k1 = max orelse k2 = max then max else Int.min (max, k1 * k2) end
blanchet@46083
  1015
  | bounded_card_of_type max default_card assigns
blanchet@46083
  1016
                         (Type (@{type_name set}, [T'])) =
blanchet@46083
  1017
    bounded_card_of_type max default_card assigns (T' --> bool_T)
blanchet@41860
  1018
  | bounded_card_of_type max default_card assigns T =
blanchet@41860
  1019
    Int.min (max, if default_card = ~1 then
blanchet@41860
  1020
                    card_of_type assigns T
blanchet@41860
  1021
                  else
blanchet@41860
  1022
                    card_of_type assigns T
blanchet@41860
  1023
                    handle TYPE ("Nitpick_HOL.card_of_type", _, _) =>
blanchet@41860
  1024
                           default_card)
blanchet@41860
  1025
blanchet@46320
  1026
(* Similar to "ATP_Util.tiny_card_of_type". *)
blanchet@41860
  1027
fun bounded_exact_card_of_type hol_ctxt finitizable_dataTs max default_card
blanchet@41860
  1028
                               assigns T =
blanchet@41860
  1029
  let
blanchet@41860
  1030
    fun aux avoid T =
blanchet@41860
  1031
      (if member (op =) avoid T then
blanchet@41860
  1032
         0
blanchet@41860
  1033
       else if member (op =) finitizable_dataTs T then
blanchet@41860
  1034
         raise SAME ()
blanchet@41860
  1035
       else case T of
blanchet@41860
  1036
         Type (@{type_name fun}, [T1, T2]) =>
blanchet@42679
  1037
         (case (aux avoid T1, aux avoid T2) of
blanchet@42679
  1038
            (_, 1) => 1
blanchet@42679
  1039
          | (0, _) => 0
blanchet@42679
  1040
          | (_, 0) => 0
blanchet@42679
  1041
          | (k1, k2) =>
blanchet@42679
  1042
            if k1 >= max orelse k2 >= max then max
blanchet@42679
  1043
            else Int.min (max, reasonable_power k2 k1))
blanchet@41860
  1044
       | Type (@{type_name prod}, [T1, T2]) =>
blanchet@42679
  1045
         (case (aux avoid T1, aux avoid T2) of
blanchet@42679
  1046
            (0, _) => 0
blanchet@42679
  1047
          | (_, 0) => 0
blanchet@42679
  1048
          | (k1, k2) =>
blanchet@42679
  1049
            if k1 >= max orelse k2 >= max then max
blanchet@42679
  1050
            else Int.min (max, k1 * k2))
blanchet@46083
  1051
       | Type (@{type_name set}, [T']) => aux avoid (T' --> bool_T)
blanchet@41860
  1052
       | Type (@{type_name itself}, _) => 1
blanchet@41860
  1053
       | @{typ prop} => 2
blanchet@41860
  1054
       | @{typ bool} => 2
blanchet@41860
  1055
       | Type _ =>
blanchet@41860
  1056
         (case datatype_constrs hol_ctxt T of
blanchet@41860
  1057
            [] => if is_integer_type T orelse is_bit_type T then 0
blanchet@41860
  1058
                  else raise SAME ()
blanchet@41860
  1059
          | constrs =>
blanchet@41860
  1060
            let
blanchet@41860
  1061
              val constr_cards =
blanchet@41860
  1062
                map (Integer.prod o map (aux (T :: avoid)) o binder_types o snd)
blanchet@41860
  1063
                    constrs
blanchet@41860
  1064
            in
blanchet@41860
  1065
              if exists (curry (op =) 0) constr_cards then 0
blanchet@42679
  1066
              else Int.min (max, Integer.sum constr_cards)
blanchet@41860
  1067
            end)
blanchet@41860
  1068
       | _ => raise SAME ())
blanchet@41860
  1069
      handle SAME () =>
blanchet@41860
  1070
             AList.lookup (op =) assigns T |> the_default default_card
blanchet@41860
  1071
  in Int.min (max, aux [] T) end
blanchet@41860
  1072
blanchet@41860
  1073
val typical_atomic_card = 4
blanchet@41898
  1074
val typical_card_of_type = bounded_card_of_type 16777217 typical_atomic_card []
blanchet@41860
  1075
blanchet@41860
  1076
fun is_finite_type hol_ctxt T =
blanchet@41860
  1077
  bounded_exact_card_of_type hol_ctxt [] 1 2 [] T > 0
blanchet@41860
  1078
blanchet@41860
  1079
fun is_special_eligible_arg strict Ts t =
blanchet@41860
  1080
  case map snd (Term.add_vars t []) @ map (nth Ts) (loose_bnos t) of
blanchet@41860
  1081
    [] => true
blanchet@41860
  1082
  | bad_Ts =>
blanchet@41860
  1083
    let
blanchet@41898
  1084
      val bad_Ts_cost =
blanchet@41898
  1085
        if strict then fold (curry (op *) o typical_card_of_type) bad_Ts 1
blanchet@41898
  1086
        else fold (Integer.max o typical_card_of_type) bad_Ts 0
blanchet@41860
  1087
      val T_cost = typical_card_of_type (fastype_of1 (Ts, t))
blanchet@41860
  1088
    in (bad_Ts_cost, T_cost) |> (if strict then op < else op <=) end
blanchet@41860
  1089
blanchet@41860
  1090
fun abs_var ((s, j), T) body = Abs (s, T, abstract_over (Var ((s, j), T), body))
blanchet@41860
  1091
blanchet@41860
  1092
fun let_var s = (nitpick_prefix ^ s, 999)
blanchet@41860
  1093
val let_inline_threshold = 20
blanchet@41860
  1094
blanchet@41860
  1095
fun s_let Ts s n abs_T body_T f t =
blanchet@41860
  1096
  if (n - 1) * (size_of_term t - 1) <= let_inline_threshold orelse
blanchet@41860
  1097
     is_special_eligible_arg false Ts t then
blanchet@41860
  1098
    f t
blanchet@41860
  1099
  else
blanchet@41860
  1100
    let val z = (let_var s, abs_T) in
blanchet@41860
  1101
      Const (@{const_name Let}, abs_T --> (abs_T --> body_T) --> body_T)
blanchet@41860
  1102
      $ t $ abs_var z (incr_boundvars 1 (f (Var z)))
blanchet@41860
  1103
    end
blanchet@41860
  1104
blanchet@41860
  1105
fun loose_bvar1_count (Bound i, k) = if i = k then 1 else 0
blanchet@41860
  1106
  | loose_bvar1_count (t1 $ t2, k) =
blanchet@41860
  1107
    loose_bvar1_count (t1, k) + loose_bvar1_count (t2, k)
blanchet@41860
  1108
  | loose_bvar1_count (Abs (_, _, t), k) = loose_bvar1_count (t, k + 1)
blanchet@41860
  1109
  | loose_bvar1_count _ = 0
blanchet@41860
  1110
blanchet@42414
  1111
fun s_betapply _ (t1 as Const (@{const_name "=="}, _) $ t1', t2) =
blanchet@42414
  1112
    if t1' aconv t2 then @{prop True} else t1 $ t2
blanchet@42414
  1113
  | s_betapply _ (t1 as Const (@{const_name HOL.eq}, _) $ t1', t2) =
blanchet@42414
  1114
    if t1' aconv t2 then @{term True} else t1 $ t2
blanchet@42414
  1115
  | s_betapply _ (Const (@{const_name If}, _) $ @{const True} $ t1', _) = t1'
blanchet@41860
  1116
  | s_betapply _ (Const (@{const_name If}, _) $ @{const False} $ _, t2) = t2
blanchet@41860
  1117
  | s_betapply Ts (Const (@{const_name Let},
blanchet@41860
  1118
                          Type (_, [bound_T, Type (_, [_, body_T])]))
blanchet@41860
  1119
                   $ t12 $ Abs (s, T, t13'), t2) =
blanchet@41860
  1120
    let val body_T' = range_type body_T in
blanchet@41860
  1121
      Const (@{const_name Let}, bound_T --> (bound_T --> body_T') --> body_T')
blanchet@41860
  1122
      $ t12 $ Abs (s, T, s_betapply (T :: Ts) (t13', incr_boundvars 1 t2))
blanchet@41860
  1123
    end
blanchet@41860
  1124
  | s_betapply Ts (t1 as Abs (s1, T1, t1'), t2) =
blanchet@41860
  1125
    (s_let Ts s1 (loose_bvar1_count (t1', 0)) T1 (fastype_of1 (T1 :: Ts, t1'))
blanchet@42958
  1126
           (curry betapply t1) t2
blanchet@42958
  1127
     (* FIXME: fix all "s_betapply []" calls *)
blanchet@42958
  1128
     handle TERM _ => betapply (t1, t2)
blanchet@42958
  1129
          | General.Subscript => betapply (t1, t2))
blanchet@41860
  1130
  | s_betapply _ (t1, t2) = t1 $ t2
blanchet@41860
  1131
fun s_betapplys Ts = Library.foldl (s_betapply Ts)
blanchet@41860
  1132
blanchet@41860
  1133
fun s_beta_norm Ts t =
blanchet@41860
  1134
  let
blanchet@41860
  1135
    fun aux _ (Var _) = raise Same.SAME
blanchet@41860
  1136
      | aux Ts (Abs (s, T, t')) = Abs (s, T, aux (T :: Ts) t')
blanchet@41860
  1137
      | aux Ts ((t1 as Abs _) $ t2) =
blanchet@41860
  1138
        Same.commit (aux Ts) (s_betapply Ts (t1, t2))
blanchet@41860
  1139
      | aux Ts (t1 $ t2) =
blanchet@41860
  1140
        ((case aux Ts t1 of
blanchet@41860
  1141
           t1 as Abs _ => Same.commit (aux Ts) (s_betapply Ts (t1, t2))
blanchet@41860
  1142
         | t1 => t1 $ Same.commit (aux Ts) t2)
blanchet@41860
  1143
        handle Same.SAME => t1 $ aux Ts t2)
blanchet@41860
  1144
      | aux _ _ = raise Same.SAME
blanchet@41860
  1145
  in aux Ts t handle Same.SAME => t end
blanchet@41860
  1146
blanchet@35070
  1147
fun discr_term_for_constr hol_ctxt (x as (s, T)) =
blanchet@33192
  1148
  let val dataT = body_type T in
blanchet@33192
  1149
    if s = @{const_name Suc} then
blanchet@33192
  1150
      Abs (Name.uu, dataT,
blanchet@33192
  1151
           @{const Not} $ HOLogic.mk_eq (zero_const dataT, Bound 0))
blanchet@35070
  1152
    else if num_datatype_constrs hol_ctxt dataT >= 2 then
blanchet@33192
  1153
      Const (discr_for_constr x)
blanchet@33192
  1154
    else
blanchet@33192
  1155
      Abs (Name.uu, dataT, @{const True})
blanchet@33192
  1156
  end
blanchet@37256
  1157
fun discriminate_value (hol_ctxt as {ctxt, ...}) x t =
blanchet@35280
  1158
  case head_of t of
blanchet@35280
  1159
    Const x' =>
blanchet@33192
  1160
    if x = x' then @{const True}
blanchet@37256
  1161
    else if is_constr_like ctxt x' then @{const False}
blanchet@37476
  1162
    else s_betapply [] (discr_term_for_constr hol_ctxt x, t)
blanchet@37476
  1163
  | _ => s_betapply [] (discr_term_for_constr hol_ctxt x, t)
blanchet@33192
  1164
blanchet@35220
  1165
fun nth_arg_sel_term_for_constr thy stds (x as (s, T)) n =
blanchet@33192
  1166
  let val (arg_Ts, dataT) = strip_type T in
blanchet@35220
  1167
    if dataT = nat_T andalso is_standard_datatype thy stds nat_T then
blanchet@35220
  1168
      @{term "%n::nat. n - 1"}
blanchet@33192
  1169
    else if is_pair_type dataT then
blanchet@33192
  1170
      Const (nth_sel_for_constr x n)
blanchet@33192
  1171
    else
blanchet@33192
  1172
      let
blanchet@38190
  1173
        fun aux m (Type (@{type_name prod}, [T1, T2])) =
blanchet@33192
  1174
            let
blanchet@33192
  1175
              val (m, t1) = aux m T1
blanchet@33192
  1176
              val (m, t2) = aux m T2
blanchet@33192
  1177
            in (m, HOLogic.mk_prod (t1, t2)) end
blanchet@33192
  1178
          | aux m T =
blanchet@33192
  1179
            (m + 1, Const (nth_sel_name_for_constr_name s m, dataT --> T)
blanchet@33192
  1180
                    $ Bound 0)
blanchet@33192
  1181
        val m = fold (Integer.add o num_factors_in_type)
blanchet@33192
  1182
                     (List.take (arg_Ts, n)) 0
blanchet@33192
  1183
      in Abs ("x", dataT, aux m (nth arg_Ts n) |> snd) end
blanchet@33192
  1184
  end
blanchet@37256
  1185
fun select_nth_constr_arg ctxt stds x t n res_T =
wenzelm@42361
  1186
  let val thy = Proof_Context.theory_of ctxt in
blanchet@37256
  1187
    (case strip_comb t of
blanchet@37256
  1188
       (Const x', args) =>
blanchet@37256
  1189
       if x = x' then nth args n
blanchet@37256
  1190
       else if is_constr_like ctxt x' then Const (@{const_name unknown}, res_T)
blanchet@37256
  1191
       else raise SAME ()
blanchet@37256
  1192
     | _ => raise SAME())
blanchet@37476
  1193
    handle SAME () =>
blanchet@37476
  1194
           s_betapply [] (nth_arg_sel_term_for_constr thy stds x n, t)
blanchet@37256
  1195
  end
blanchet@33192
  1196
blanchet@35220
  1197
fun construct_value _ _ x [] = Const x
blanchet@37256
  1198
  | construct_value ctxt stds (x as (s, _)) args =
blanchet@33192
  1199
    let val args = map Envir.eta_contract args in
blanchet@33192
  1200
      case hd args of
blanchet@35280
  1201
        Const (s', _) $ t =>
blanchet@34936
  1202
        if is_sel_like_and_no_discr s' andalso
blanchet@34936
  1203
           constr_name_for_sel_like s' = s andalso
blanchet@35220
  1204
           forall (fn (n, t') =>
blanchet@37256
  1205
                      select_nth_constr_arg ctxt stds x t n dummyT = t')
blanchet@34936
  1206
                  (index_seq 0 (length args) ~~ args) then
blanchet@33192
  1207
          t
blanchet@33192
  1208
        else
blanchet@33192
  1209
          list_comb (Const x, args)
blanchet@33192
  1210
      | _ => list_comb (Const x, args)
blanchet@33192
  1211
    end
blanchet@33192
  1212
blanchet@37256
  1213
fun constr_expand (hol_ctxt as {ctxt, stds, ...}) T t =
blanchet@35665
  1214
  (case head_of t of
blanchet@37256
  1215
     Const x => if is_constr_like ctxt x then t else raise SAME ()
blanchet@35665
  1216
   | _ => raise SAME ())
blanchet@35665
  1217
  handle SAME () =>
blanchet@35665
  1218
         let
blanchet@35665
  1219
           val x' as (_, T') =
blanchet@35665
  1220
             if is_pair_type T then
blanchet@35665
  1221
               let val (T1, T2) = HOLogic.dest_prodT T in
blanchet@35665
  1222
                 (@{const_name Pair}, T1 --> T2 --> T)
blanchet@35665
  1223
               end
blanchet@35665
  1224
             else
blanchet@35665
  1225
               datatype_constrs hol_ctxt T |> hd
blanchet@35665
  1226
           val arg_Ts = binder_types T'
blanchet@35665
  1227
         in
blanchet@37256
  1228
           list_comb (Const x', map2 (select_nth_constr_arg ctxt stds x' t)
blanchet@35665
  1229
                                     (index_seq 0 (length arg_Ts)) arg_Ts)
blanchet@35665
  1230
         end
blanchet@35665
  1231
blanchet@35665
  1232
fun coerce_bound_no f j t =
blanchet@35665
  1233
  case t of
blanchet@35665
  1234
    t1 $ t2 => coerce_bound_no f j t1 $ coerce_bound_no f j t2
blanchet@35665
  1235
  | Abs (s, T, t') => Abs (s, T, coerce_bound_no f (j + 1) t')
blanchet@35665
  1236
  | Bound j' => if j' = j then f t else t
blanchet@35665
  1237
  | _ => t
blanchet@35665
  1238
fun coerce_bound_0_in_term hol_ctxt new_T old_T =
blanchet@35665
  1239
  old_T <> new_T ? coerce_bound_no (coerce_term hol_ctxt [new_T] old_T new_T) 0
blanchet@39345
  1240
and coerce_term (hol_ctxt as {ctxt, stds, ...}) Ts new_T old_T t =
blanchet@35665
  1241
  if old_T = new_T then
blanchet@35665
  1242
    t
blanchet@35665
  1243
  else
blanchet@35665
  1244
    case (new_T, old_T) of
blanchet@35665
  1245
      (Type (new_s, new_Ts as [new_T1, new_T2]),
blanchet@35665
  1246
       Type (@{type_name fun}, [old_T1, old_T2])) =>
blanchet@35665
  1247
      (case eta_expand Ts t 1 of
blanchet@35665
  1248
         Abs (s, _, t') =>
blanchet@35665
  1249
         Abs (s, new_T1,
blanchet@35665
  1250
              t' |> coerce_bound_0_in_term hol_ctxt new_T1 old_T1
blanchet@35665
  1251
                 |> coerce_term hol_ctxt (new_T1 :: Ts) new_T2 old_T2)
blanchet@35665
  1252
         |> Envir.eta_contract
blanchet@35665
  1253
         |> new_s <> @{type_name fun}
blanchet@37256
  1254
            ? construct_value ctxt stds
blanchet@41052
  1255
                  (@{const_name FunBox},
blanchet@35665
  1256
                   Type (@{type_name fun}, new_Ts) --> new_T)
blanchet@35665
  1257
              o single
blanchet@35665
  1258
       | t' => raise TERM ("Nitpick_HOL.coerce_term", [t']))
blanchet@35665
  1259
    | (Type (new_s, new_Ts as [new_T1, new_T2]),
blanchet@35665
  1260
       Type (old_s, old_Ts as [old_T1, old_T2])) =>
blanchet@41052
  1261
      if old_s = @{type_name fun_box} orelse
blanchet@38190
  1262
         old_s = @{type_name pair_box} orelse old_s = @{type_name prod} then
blanchet@35665
  1263
        case constr_expand hol_ctxt old_T t of
blanchet@35665
  1264
          Const (old_s, _) $ t1 =>
blanchet@35665
  1265
          if new_s = @{type_name fun} then
blanchet@35665
  1266
            coerce_term hol_ctxt Ts new_T (Type (@{type_name fun}, old_Ts)) t1
blanchet@35665
  1267
          else
blanchet@37256
  1268
            construct_value ctxt stds
blanchet@35665
  1269
                (old_s, Type (@{type_name fun}, new_Ts) --> new_T)
blanchet@35665
  1270
                [coerce_term hol_ctxt Ts (Type (@{type_name fun}, new_Ts))
blanchet@35665
  1271
                             (Type (@{type_name fun}, old_Ts)) t1]
blanchet@35665
  1272
        | Const _ $ t1 $ t2 =>
blanchet@37256
  1273
          construct_value ctxt stds
blanchet@38190
  1274
              (if new_s = @{type_name prod} then @{const_name Pair}
blanchet@35665
  1275
               else @{const_name PairBox}, new_Ts ---> new_T)
blanchet@35665
  1276
              (map3 (coerce_term hol_ctxt Ts) [new_T1, new_T2] [old_T1, old_T2]
blanchet@35665
  1277
                    [t1, t2])
blanchet@35665
  1278
        | t' => raise TERM ("Nitpick_HOL.coerce_term", [t'])
blanchet@35665
  1279
      else
blanchet@35665
  1280
        raise TYPE ("Nitpick_HOL.coerce_term", [new_T, old_T], [t])
blanchet@35665
  1281
    | _ => raise TYPE ("Nitpick_HOL.coerce_term", [new_T, old_T], [t])
blanchet@35665
  1282
blanchet@33192
  1283
fun is_ground_term (t1 $ t2) = is_ground_term t1 andalso is_ground_term t2
blanchet@33192
  1284
  | is_ground_term (Const _) = true
blanchet@33192
  1285
  | is_ground_term _ = false
blanchet@33192
  1286
blanchet@33192
  1287
fun special_bounds ts =
wenzelm@35408
  1288
  fold Term.add_vars ts [] |> sort (Term_Ord.fast_indexname_ord o pairself fst)
blanchet@33192
  1289
blanchet@38190
  1290
(* FIXME: detect "rep_datatype"? *)
blanchet@38240
  1291
fun is_funky_typedef_name ctxt s =
blanchet@46083
  1292
  member (op =) [@{type_name unit}, @{type_name prod}, @{type_name set},
blanchet@38190
  1293
                 @{type_name Sum_Type.sum}, @{type_name int}] s orelse
blanchet@38240
  1294
  is_frac_type ctxt (Type (s, []))
blanchet@38240
  1295
fun is_funky_typedef ctxt (Type (s, _)) = is_funky_typedef_name ctxt s
blanchet@33571
  1296
  | is_funky_typedef _ _ = false
blanchet@33192
  1297
blanchet@42415
  1298
fun all_defs_of thy subst =
blanchet@33192
  1299
  let
blanchet@42415
  1300
    val def_names =
blanchet@42415
  1301
      thy |> Theory.defs_of
blanchet@42415
  1302
          |> Defs.all_specifications_of
blanchet@42415
  1303
          |> maps snd |> map_filter #def
blanchet@42415
  1304
          |> Ord_List.make fast_string_ord
blanchet@42415
  1305
  in
wenzelm@42425
  1306
    Theory.nodes_of thy
blanchet@42418
  1307
    |> maps Thm.axioms_of
blanchet@42418
  1308
    |> map (apsnd (subst_atomic subst o prop_of))
blanchet@42418
  1309
    |> sort (fast_string_ord o pairself fst)
blanchet@42418
  1310
    |> Ord_List.inter (fast_string_ord o apsnd fst) def_names
blanchet@42418
  1311
    |> map snd
blanchet@42415
  1312
  end
blanchet@42415
  1313
blanchet@49985
  1314
(* Ideally we would check against "Complex_Main", not "Hilbert_Choice", but any
blanchet@49985
  1315
   theory will do as long as it contains all the "axioms" and "axiomatization"
blanchet@42418
  1316
   commands. *)
blanchet@49985
  1317
fun is_built_in_theory thy = Theory.subthy (thy, @{theory Hilbert_Choice})
blanchet@42418
  1318
blanchet@42415
  1319
fun all_nondefs_of ctxt subst =
blanchet@42415
  1320
  ctxt |> Spec_Rules.get
blanchet@42415
  1321
       |> filter (curry (op =) Spec_Rules.Unknown o fst)
blanchet@42415
  1322
       |> maps (snd o snd)
blanchet@42415
  1323
       |> filter_out (is_built_in_theory o theory_of_thm)
blanchet@42415
  1324
       |> map (subst_atomic subst o prop_of)
blanchet@33192
  1325
blanchet@39359
  1326
fun arity_of_built_in_const thy stds (s, T) =
blanchet@33192
  1327
  if s = @{const_name If} then
blanchet@33192
  1328
    if nth_range_type 3 T = @{typ bool} then NONE else SOME 3
blanchet@35220
  1329
  else
blanchet@35220
  1330
    let val std_nats = is_standard_datatype thy stds nat_T in
blanchet@35220
  1331
      case AList.lookup (op =)
blanchet@35220
  1332
                    (built_in_consts
blanchet@39359
  1333
                     |> std_nats ? append built_in_nat_consts) s of
blanchet@35220
  1334
        SOME n => SOME n
blanchet@35220
  1335
      | NONE =>
blanchet@35220
  1336
        case AList.lookup (op =)
blanchet@35220
  1337
                 (built_in_typed_consts
blanchet@35220
  1338
                  |> std_nats ? append built_in_typed_nat_consts)
blanchet@35220
  1339
                 (s, unarize_type T) of
blanchet@35220
  1340
          SOME n => SOME n
blanchet@35220
  1341
        | NONE =>
blanchet@35280
  1342
          case s of
blanchet@35280
  1343
            @{const_name zero_class.zero} =>
blanchet@35280
  1344
            if is_iterator_type T then SOME 0 else NONE
blanchet@35280
  1345
          | @{const_name Suc} =>
blanchet@35280
  1346
            if is_iterator_type (domain_type T) then SOME 0 else NONE
blanchet@46081
  1347
          | _ => if is_fun_type T andalso is_set_like_type (domain_type T) then
blanchet@46081
  1348
                   AList.lookup (op =) built_in_set_like_consts s
blanchet@35280
  1349
                 else
blanchet@35280
  1350
                   NONE
blanchet@35220
  1351
    end
blanchet@39359
  1352
val is_built_in_const = is_some ooo arity_of_built_in_const
blanchet@33192
  1353
blanchet@33192
  1354
(* This function is designed to work for both real definition axioms and
blanchet@33192
  1355
   simplification rules (equational specifications). *)
blanchet@33192
  1356
fun term_under_def t =
blanchet@33192
  1357
  case t of
blanchet@33192
  1358
    @{const "==>"} $ _ $ t2 => term_under_def t2
blanchet@33192
  1359
  | Const (@{const_name "=="}, _) $ t1 $ _ => term_under_def t1
blanchet@33192
  1360
  | @{const Trueprop} $ t1 => term_under_def t1
haftmann@38864
  1361
  | Const (@{const_name HOL.eq}, _) $ t1 $ _ => term_under_def t1
blanchet@33192
  1362
  | Abs (_, _, t') => term_under_def t'
blanchet@33192
  1363
  | t1 $ _ => term_under_def t1
blanchet@33192
  1364
  | _ => t
blanchet@33192
  1365
blanchet@36555
  1366
(* Here we crucially rely on "specialize_type" performing a preorder traversal
blanchet@36555
  1367
   of the term, without which the wrong occurrence of a constant could be
blanchet@36555
  1368
   matched in the face of overloading. *)
blanchet@39359
  1369
fun def_props_for_const thy stds table (x as (s, _)) =
blanchet@39359
  1370
  if is_built_in_const thy stds x then
blanchet@33192
  1371
    []
blanchet@33192
  1372
  else
blanchet@33192
  1373
    these (Symtab.lookup table s)
blanchet@36555
  1374
    |> map_filter (try (specialize_type thy x))
blanchet@34121
  1375
    |> filter (curry (op =) (Const x) o term_under_def)
blanchet@33192
  1376
blanchet@35280
  1377
fun normalized_rhs_of t =
blanchet@33192
  1378
  let
blanchet@33743
  1379
    fun aux (v as Var _) (SOME t) = SOME (lambda v t)
blanchet@35280
  1380
      | aux (c as Const (@{const_name TYPE}, _)) (SOME t) = SOME (lambda c t)
blanchet@33743
  1381
      | aux _ _ = NONE
blanchet@33192
  1382
    val (lhs, rhs) =
blanchet@33192
  1383
      case t of
blanchet@33192
  1384
        Const (@{const_name "=="}, _) $ t1 $ t2 => (t1, t2)
haftmann@38864
  1385
      | @{const Trueprop} $ (Const (@{const_name HOL.eq}, _) $ t1 $ t2) =>
blanchet@33192
  1386
        (t1, t2)
blanchet@33232
  1387
      | _ => raise TERM ("Nitpick_HOL.normalized_rhs_of", [t])
blanchet@33192
  1388
    val args = strip_comb lhs |> snd
blanchet@33743
  1389
  in fold_rev aux args (SOME rhs) end
blanchet@33192
  1390
blanchet@41791
  1391
fun get_def_of_const thy table (x as (s, _)) =
blanchet@41791
  1392
  x |> def_props_for_const thy [(NONE, false)] table |> List.last
blanchet@41791
  1393
    |> normalized_rhs_of |> Option.map (prefix_abs_vars s)
blanchet@41791
  1394
  handle List.Empty => NONE
blanchet@41791
  1395
blanchet@41791
  1396
fun def_of_const_ext thy (unfold_table, fallback_table) (x as (s, _)) =
blanchet@41791
  1397
  if is_built_in_const thy [(NONE, false)] x orelse original_name s <> s then
blanchet@33192
  1398
    NONE
blanchet@41791
  1399
  else case get_def_of_const thy unfold_table x of
blanchet@41791
  1400
    SOME def => SOME (true, def)
blanchet@41791
  1401
  | NONE => get_def_of_const thy fallback_table x |> Option.map (pair false)
blanchet@41791
  1402
blanchet@41791
  1403
val def_of_const = Option.map snd ooo def_of_const_ext
blanchet@33192
  1404
blanchet@33192
  1405
fun fixpoint_kind_of_rhs (Abs (_, _, t)) = fixpoint_kind_of_rhs t
blanchet@33192
  1406
  | fixpoint_kind_of_rhs (Const (@{const_name lfp}, _) $ Abs _) = Lfp
blanchet@33192
  1407
  | fixpoint_kind_of_rhs (Const (@{const_name gfp}, _) $ Abs _) = Gfp
blanchet@33192
  1408
  | fixpoint_kind_of_rhs _ = NoFp
blanchet@33192
  1409
blanchet@33192
  1410
fun is_mutually_inductive_pred_def thy table t =
blanchet@33192
  1411
  let
blanchet@33192
  1412
    fun is_good_arg (Bound _) = true
blanchet@33192
  1413
      | is_good_arg (Const (s, _)) =
blanchet@34936
  1414
        s = @{const_name True} orelse s = @{const_name False} orelse
blanchet@34936
  1415
        s = @{const_name undefined}
blanchet@33192
  1416
      | is_good_arg _ = false
blanchet@33192
  1417
  in
blanchet@33192
  1418
    case t |> strip_abs_body |> strip_comb of
blanchet@33192
  1419
      (Const x, ts as (_ :: _)) =>
blanchet@33192
  1420
      (case def_of_const thy table x of
blanchet@38180
  1421
         SOME t' => fixpoint_kind_of_rhs t' <> NoFp andalso
blanchet@38180
  1422
                    forall is_good_arg ts
blanchet@33192
  1423
       | NONE => false)
blanchet@33192
  1424
    | _ => false
blanchet@33192
  1425
  end
blanchet@33192
  1426
fun unfold_mutually_inductive_preds thy table =
blanchet@33192
  1427
  map_aterms (fn t as Const x =>
blanchet@33192
  1428
                 (case def_of_const thy table x of
blanchet@33192
  1429
                    SOME t' =>
blanchet@33192
  1430
                    let val t' = Envir.eta_contract t' in
blanchet@33192
  1431
                      if is_mutually_inductive_pred_def thy table t' then t'
blanchet@33192
  1432
                      else t
blanchet@33192
  1433
                    end
blanchet@33192
  1434
                 | NONE => t)
blanchet@33192
  1435
               | t => t)
blanchet@33192
  1436
blanchet@38240
  1437
fun case_const_names ctxt stds =
wenzelm@42361
  1438
  let val thy = Proof_Context.theory_of ctxt in
blanchet@38240
  1439
    Symtab.fold (fn (dtype_s, {index, descr, case_name, ...}) =>
blanchet@38240
  1440
                    if is_basic_datatype thy stds dtype_s then
blanchet@38240
  1441
                      I
blanchet@38240
  1442
                    else
blanchet@38240
  1443
                      cons (case_name, AList.lookup (op =) descr index
blanchet@38240
  1444
                                       |> the |> #3 |> length))
blanchet@38240
  1445
                (Datatype.get_all thy) [] @
blanchet@38240
  1446
    map (apsnd length o snd) (#codatatypes (Data.get (Context.Proof ctxt)))
blanchet@38240
  1447
  end
blanchet@33192
  1448
blanchet@35718
  1449
fun fixpoint_kind_of_const thy table x =
blanchet@39359
  1450
  if is_built_in_const thy [(NONE, false)] x then NoFp
blanchet@39359
  1451
  else fixpoint_kind_of_rhs (the (def_of_const thy table x))
blanchet@39359
  1452
  handle Option.Option => NoFp
blanchet@33192
  1453
blanchet@41791
  1454
fun is_real_inductive_pred ({thy, stds, def_tables, intro_table, ...}
blanchet@39359
  1455
                            : hol_context) x =
blanchet@41791
  1456
  fixpoint_kind_of_const thy def_tables x <> NoFp andalso
blanchet@39359
  1457
  not (null (def_props_for_const thy stds intro_table x))
blanchet@38205
  1458
fun is_inductive_pred hol_ctxt (x as (s, _)) =
blanchet@38205
  1459
  is_real_inductive_pred hol_ctxt x orelse String.isPrefix ubfp_prefix s orelse
blanchet@38205
  1460
  String.isPrefix lbfp_prefix s
blanchet@33192
  1461
blanchet@35718
  1462
fun lhs_of_equation t =
blanchet@35718
  1463
  case t of
blanchet@35718
  1464
    Const (@{const_name all}, _) $ Abs (_, _, t1) => lhs_of_equation t1
blanchet@35718
  1465
  | Const (@{const_name "=="}, _) $ t1 $ _ => SOME t1
blanchet@35718
  1466
  | @{const "==>"} $ _ $ t2 => lhs_of_equation t2
blanchet@35718
  1467
  | @{const Trueprop} $ t1 => lhs_of_equation t1
blanchet@35718
  1468
  | Const (@{const_name All}, _) $ Abs (_, _, t1) => lhs_of_equation t1
haftmann@38864
  1469
  | Const (@{const_name HOL.eq}, _) $ t1 $ _ => SOME t1
haftmann@38786
  1470
  | @{const HOL.implies} $ _ $ t2 => lhs_of_equation t2
blanchet@35718
  1471
  | _ => NONE
blanchet@35718
  1472
fun is_constr_pattern _ (Bound _) = true
blanchet@35718
  1473
  | is_constr_pattern _ (Var _) = true
blanchet@37256
  1474
  | is_constr_pattern ctxt t =
blanchet@35718
  1475
    case strip_comb t of
blanchet@35718
  1476
      (Const x, args) =>
blanchet@37256
  1477
      is_constr_like ctxt x andalso forall (is_constr_pattern ctxt) args
blanchet@35718
  1478
    | _ => false
blanchet@37256
  1479
fun is_constr_pattern_lhs ctxt t =
blanchet@37256
  1480
  forall (is_constr_pattern ctxt) (snd (strip_comb t))
blanchet@37256
  1481
fun is_constr_pattern_formula ctxt t =
blanchet@35718
  1482
  case lhs_of_equation t of
blanchet@37256
  1483
    SOME t' => is_constr_pattern_lhs ctxt t'
blanchet@35718
  1484
  | NONE => false
blanchet@35718
  1485
blanchet@36555
  1486
(* Similar to "specialize_type" but returns all matches rather than only the
blanchet@36555
  1487
   first (preorder) match. *)
blanchet@35807
  1488
fun multi_specialize_type thy slack (s, T) t =
blanchet@35807
  1489
  let
blanchet@35807
  1490
    fun aux (Const (s', T')) ys =
blanchet@35807
  1491
        if s = s' then
blanchet@35807
  1492
          ys |> (if AList.defined (op =) ys T' then
blanchet@35807
  1493
                   I
blanchet@35807
  1494
                 else
blanchet@36555
  1495
                   cons (T', monomorphic_term (Sign.typ_match thy (T', T)
blanchet@36555
  1496
                                                              Vartab.empty) t)
blanchet@35807
  1497
                   handle Type.TYPE_MATCH => I
blanchet@36575
  1498
                        | TERM _ =>
blanchet@35807
  1499
                          if slack then
blanchet@35807
  1500
                            I
blanchet@35807
  1501
                          else
blanchet@37253
  1502
                            raise NOT_SUPPORTED
blanchet@37253
  1503
                                      ("too much polymorphism in axiom \"" ^
blanchet@37253
  1504
                                       Syntax.string_of_term_global thy t ^
blanchet@37253
  1505
                                       "\" involving " ^ quote s))
blanchet@35807
  1506
        else
blanchet@35807
  1507
          ys
blanchet@35807
  1508
      | aux _ ys = ys
blanchet@35807
  1509
  in map snd (fold_aterms aux t []) end
blanchet@35807
  1510
fun nondef_props_for_const thy slack table (x as (s, _)) =
blanchet@35807
  1511
  these (Symtab.lookup table s) |> maps (multi_specialize_type thy slack x)
blanchet@35807
  1512
blanchet@35807
  1513
fun unvarify_term (t1 $ t2) = unvarify_term t1 $ unvarify_term t2
blanchet@35807
  1514
  | unvarify_term (Var ((s, 0), T)) = Free (s, T)
blanchet@35807
  1515
  | unvarify_term (Abs (s, T, t')) = Abs (s, T, unvarify_term t')
blanchet@35807
  1516
  | unvarify_term t = t
blanchet@35807
  1517
fun axiom_for_choice_spec thy =
blanchet@35807
  1518
  unvarify_term
blanchet@35807
  1519
  #> Object_Logic.atomize_term thy
blanchet@35807
  1520
  #> Choice_Specification.close_form
blanchet@35807
  1521
  #> HOLogic.mk_Trueprop
blanchet@41791
  1522
fun is_choice_spec_fun ({thy, def_tables, nondef_table, choice_spec_table, ...}
blanchet@35807
  1523
                        : hol_context) x =
blanchet@35807
  1524
  case nondef_props_for_const thy true choice_spec_table x of
blanchet@35807
  1525
    [] => false
blanchet@41791
  1526
  | ts => case def_of_const thy def_tables x of
blanchet@35807
  1527
            SOME (Const (@{const_name Eps}, _) $ _) => true
blanchet@35807
  1528
          | SOME _ => false
blanchet@35807
  1529
          | NONE =>
blanchet@35807
  1530
            let val ts' = nondef_props_for_const thy true nondef_table x in
blanchet@35807
  1531
              length ts' = length ts andalso
blanchet@35807
  1532
              forall (fn t =>
blanchet@35807
  1533
                         exists (curry (op aconv) (axiom_for_choice_spec thy t))
blanchet@35807
  1534
                                ts') ts
blanchet@35807
  1535
            end
blanchet@35807
  1536
blanchet@35807
  1537
fun is_choice_spec_axiom thy choice_spec_table t =
blanchet@35807
  1538
  Symtab.exists (fn (_, ts) =>
blanchet@35807
  1539
                    exists (curry (op aconv) t o axiom_for_choice_spec thy) ts)
blanchet@35807
  1540
                choice_spec_table
blanchet@35807
  1541
blanchet@39359
  1542
fun is_real_equational_fun ({thy, stds, simp_table, psimp_table, ...}
blanchet@39359
  1543
                            : hol_context) x =
blanchet@39359
  1544
  exists (fn table => not (null (def_props_for_const thy stds table x)))
blanchet@38205
  1545
         [!simp_table, psimp_table]
blanchet@38202
  1546
fun is_equational_fun_but_no_plain_def hol_ctxt =
blanchet@38205
  1547
  is_real_equational_fun hol_ctxt orf is_inductive_pred hol_ctxt
blanchet@38202
  1548
blanchet@35718
  1549
(** Constant unfolding **)
blanchet@33192
  1550
blanchet@42958
  1551
fun constr_case_body ctxt stds Ts (func_t, (x as (_, T))) =
blanchet@33192
  1552
  let val arg_Ts = binder_types T in
blanchet@42958
  1553
    s_betapplys Ts (func_t, map2 (select_nth_constr_arg ctxt stds x (Bound 0))
blanchet@37476
  1554
                                 (index_seq 0 (length arg_Ts)) arg_Ts)
blanchet@33192
  1555
  end
blanchet@37476
  1556
fun add_constr_case res_T (body_t, guard_t) res_t =
blanchet@37476
  1557
  if res_T = bool_T then
blanchet@37476
  1558
    s_conj (HOLogic.mk_imp (guard_t, body_t), res_t)
blanchet@37476
  1559
  else
blanchet@37476
  1560
    Const (@{const_name If}, bool_T --> res_T --> res_T --> res_T)
blanchet@37476
  1561
    $ guard_t $ body_t $ res_t
blanchet@42958
  1562
fun optimized_case_def (hol_ctxt as {ctxt, stds, ...}) Ts dataT res_T func_ts =
blanchet@33192
  1563
  let
blanchet@35070
  1564
    val xs = datatype_constrs hol_ctxt dataT
blanchet@37476
  1565
    val cases =
blanchet@37476
  1566
      func_ts ~~ xs
blanchet@37476
  1567
      |> map (fn (func_t, x) =>
blanchet@42958
  1568
                 (constr_case_body ctxt stds (dataT :: Ts)
blanchet@42958
  1569
                                   (incr_boundvars 1 func_t, x),
blanchet@37476
  1570
                  discriminate_value hol_ctxt x (Bound 0)))
blanchet@37476
  1571
      |> AList.group (op aconv)
blanchet@37476
  1572
      |> map (apsnd (List.foldl s_disj @{const False}))
blanchet@37482
  1573
      |> sort (int_ord o pairself (size_of_term o snd))
blanchet@37476
  1574
      |> rev
blanchet@33192
  1575
  in
blanchet@37476
  1576
    if res_T = bool_T then
blanchet@37476
  1577
      if forall (member (op =) [@{const False}, @{const True}] o fst) cases then
blanchet@37476
  1578
        case cases of
blanchet@37476
  1579
          [(body_t, _)] => body_t
blanchet@37476
  1580
        | [_, (@{const True}, head_t2)] => head_t2
blanchet@37476
  1581
        | [_, (@{const False}, head_t2)] => @{const Not} $ head_t2
blanchet@37476
  1582
        | _ => raise BAD ("Nitpick_HOL.optimized_case_def", "impossible cases")
blanchet@39315
  1583
      else
blanchet@37476
  1584
        @{const True} |> fold_rev (add_constr_case res_T) cases
blanchet@37476
  1585
    else
blanchet@37476
  1586
      fst (hd cases) |> fold_rev (add_constr_case res_T) (tl cases)
blanchet@33192
  1587
  end
wenzelm@44241
  1588
  |> absdummy dataT
blanchet@37476
  1589
blanchet@37256
  1590
fun optimized_record_get (hol_ctxt as {thy, ctxt, stds, ...}) s rec_T res_T t =
blanchet@35070
  1591
  let val constr_x = hd (datatype_constrs hol_ctxt rec_T) in
blanchet@33192
  1592
    case no_of_record_field thy s rec_T of
blanchet@33192
  1593
      ~1 => (case rec_T of
blanchet@33192
  1594
               Type (_, Ts as _ :: _) =>
blanchet@33192
  1595
               let
blanchet@33192
  1596
                 val rec_T' = List.last Ts
blanchet@33192
  1597
                 val j = num_record_fields thy rec_T - 1
blanchet@33192
  1598
               in
blanchet@37256
  1599
                 select_nth_constr_arg ctxt stds constr_x t j res_T
blanchet@35070
  1600
                 |> optimized_record_get hol_ctxt s rec_T' res_T
blanchet@33192
  1601
               end
blanchet@33232
  1602
             | _ => raise TYPE ("Nitpick_HOL.optimized_record_get", [rec_T],
blanchet@33232
  1603
                                []))
blanchet@37256
  1604
    | j => select_nth_constr_arg ctxt stds constr_x t j res_T
blanchet@33192
  1605
  end
blanchet@37256
  1606
fun optimized_record_update (hol_ctxt as {thy, ctxt, stds, ...}) s rec_T fun_t
blanchet@37256
  1607
                            rec_t =
blanchet@33192
  1608
  let
blanchet@35070
  1609
    val constr_x as (_, constr_T) = hd (datatype_constrs hol_ctxt rec_T)
blanchet@33192
  1610
    val Ts = binder_types constr_T
blanchet@33192
  1611
    val n = length Ts
blanchet@33192
  1612
    val special_j = no_of_record_field thy s rec_T
blanchet@35220
  1613
    val ts =
blanchet@35220
  1614
      map2 (fn j => fn T =>
blanchet@37256
  1615
               let val t = select_nth_constr_arg ctxt stds constr_x rec_t j T in
blanchet@35220
  1616
                 if j = special_j then
blanchet@37476
  1617
                   s_betapply [] (fun_t, t)
blanchet@35220
  1618
                 else if j = n - 1 andalso special_j = ~1 then
blanchet@35220
  1619
                   optimized_record_update hol_ctxt s
blanchet@35220
  1620
                       (rec_T |> dest_Type |> snd |> List.last) fun_t t
blanchet@35220
  1621
                 else
blanchet@35220
  1622
                   t
blanchet@35220
  1623
               end) (index_seq 0 n) Ts
blanchet@33192
  1624
  in list_comb (Const constr_x, ts) end
blanchet@33192
  1625
blanchet@35070
  1626
(* Prevents divergence in case of cyclic or infinite definition dependencies. *)
blanchet@33747
  1627
val unfold_max_depth = 255
blanchet@33192
  1628
blanchet@38206
  1629
(* Inline definitions or define as an equational constant? Booleans tend to
blanchet@41871
  1630
   benefit more from inlining, due to the polarity analysis. (However, if
blanchet@41871
  1631
   "total_consts" is set, the polarity analysis is likely not to be so
blanchet@41871
  1632
   crucial.) *)
blanchet@41793
  1633
val def_inline_threshold_for_booleans = 60
blanchet@38206
  1634
val def_inline_threshold_for_non_booleans = 20
blanchet@38202
  1635
blanchet@38209
  1636
fun unfold_defs_in_term
blanchet@41871
  1637
        (hol_ctxt as {thy, ctxt, stds, whacks, total_consts, case_names,
blanchet@41871
  1638
                      def_tables, ground_thm_table, ersatz_table, ...}) =
blanchet@33192
  1639
  let
blanchet@47109
  1640
    fun do_numeral depth Ts mult T t0 t1 =
blanchet@47109
  1641
      (if is_number_type ctxt T then
blanchet@47109
  1642
         let
blanchet@47109
  1643
           val j = mult * (HOLogic.dest_num t1)
blanchet@47109
  1644
                   |> T = nat_T ? Integer.max 0
blanchet@47109
  1645
         in
blanchet@47782
  1646
           if j = 1 then
blanchet@47782
  1647
             raise SAME ()
blanchet@47109
  1648
           else
blanchet@47782
  1649
             let
blanchet@47782
  1650
               val s = numeral_prefix ^ signed_string_of_int j
blanchet@47782
  1651
             in
blanchet@47782
  1652
               if is_integer_like_type T then
blanchet@47782
  1653
                 if is_standard_datatype thy stds T then Const (s, T)
blanchet@47782
  1654
                 else funpow j (curry (op $) (suc_const T)) (zero_const T)
blanchet@47782
  1655
               else
blanchet@47782
  1656
                 do_term depth Ts (Const (@{const_name of_int}, int_T --> T)
blanchet@47782
  1657
                                   $ Const (s, int_T))
blanchet@47782
  1658
             end
blanchet@47109
  1659
         end
blanchet@47109
  1660
         handle TERM _ => raise SAME ()
blanchet@47109
  1661
       else
blanchet@47109
  1662
         raise SAME ())
blanchet@47109
  1663
      handle SAME () => s_betapply [] (do_term depth Ts t0, do_term depth Ts t1)
blanchet@47109
  1664
    and do_term depth Ts t =
blanchet@33192
  1665
      case t of
blanchet@47109
  1666
        (t0 as Const (@{const_name Num.neg_numeral_class.neg_numeral},
blanchet@35665
  1667
                      Type (@{type_name fun}, [_, ran_T]))) $ t1 =>
blanchet@47109
  1668
        do_numeral depth Ts ~1 ran_T t0 t1
blanchet@47109
  1669
      | (t0 as Const (@{const_name Num.numeral_class.numeral},
blanchet@47109
  1670
                      Type (@{type_name fun}, [_, ran_T]))) $ t1 =>
blanchet@47109
  1671
        do_numeral depth Ts 1 ran_T t0 t1
blanchet@33864
  1672
      | Const (@{const_name refl_on}, T) $ Const (@{const_name top}, _) $ t2 =>
blanchet@33192
  1673
        do_const depth Ts t (@{const_name refl'}, range_type T) [t2]
blanchet@41046
  1674
      | (t0 as Const (@{const_name Sigma}, Type (_, [T1, Type (_, [T2, T3])])))
blanchet@41046
  1675
        $ t1 $ (t2 as Abs (_, _, t2')) =>
blanchet@41046
  1676
        if loose_bvar1 (t2', 0) then
blanchet@41046
  1677
          s_betapplys Ts (do_term depth Ts t0, map (do_term depth Ts) [t1, t2])
blanchet@41046
  1678
        else
blanchet@41046
  1679
          do_term depth Ts
blanchet@41046
  1680
                  (Const (@{const_name prod}, T1 --> range_type T2 --> T3)
blanchet@41046
  1681
                   $ t1 $ incr_boundvars ~1 t2')
blanchet@33192
  1682
      | Const (x as (@{const_name distinct},
blanchet@35665
  1683
               Type (@{type_name fun}, [Type (@{type_name list}, [T']), _])))
blanchet@33192
  1684
        $ (t1 as _ $ _) =>
blanchet@33192
  1685
        (t1 |> HOLogic.dest_list |> distinctness_formula T'
blanchet@33192
  1686
         handle TERM _ => do_const depth Ts t x [t1])
blanchet@35280
  1687
      | Const (x as (@{const_name If}, _)) $ t1 $ t2 $ t3 =>
blanchet@34936
  1688
        if is_ground_term t1 andalso
blanchet@34936
  1689
           exists (Pattern.matches thy o rpair t1)
blanchet@34936
  1690
                  (Inttab.lookup_list ground_thm_table (hash_term t1)) then
blanchet@33192
  1691
          do_term depth Ts t2
blanchet@33192
  1692
        else
blanchet@33192
  1693
          do_const depth Ts t x [t1, t2, t3]
blanchet@41045
  1694
      | Const (@{const_name Let}, _) $ t1 $ t2 =>
blanchet@41045
  1695
        s_betapply Ts (pairself (do_term depth Ts) (t2, t1))
blanchet@33192
  1696
      | Const x => do_const depth Ts t x []
blanchet@37476
  1697
      | t1 $ t2 =>
blanchet@37476
  1698
        (case strip_comb t of
blanchet@37476
  1699
           (Const x, ts) => do_const depth Ts t x ts
blanchet@37476
  1700
         | _ => s_betapply [] (do_term depth Ts t1, do_term depth Ts t2))
blanchet@33192
  1701
      | Bound _ => t
blanchet@33192
  1702
      | Abs (s, T, body) => Abs (s, T, do_term depth (T :: Ts) body)
blanchet@38209
  1703
      | _ => if member (term_match thy) whacks t then
blanchet@38209
  1704
               Const (@{const_name unknown}, fastype_of1 (Ts, t))
blanchet@38209
  1705
             else
blanchet@38209
  1706
               t
blanchet@33192
  1707
    and select_nth_constr_arg_with_args _ _ (x as (_, T)) [] n res_T =
blanchet@33192
  1708
        (Abs (Name.uu, body_type T,
blanchet@37256
  1709
              select_nth_constr_arg ctxt stds x (Bound 0) n res_T), [])
blanchet@33192
  1710
      | select_nth_constr_arg_with_args depth Ts x (t :: ts) n res_T =
blanchet@37256
  1711
        (select_nth_constr_arg ctxt stds x (do_term depth Ts t) n res_T, ts)
blanchet@38207
  1712
    and quot_rep_of depth Ts abs_T rep_T ts =
blanchet@38207
  1713
      select_nth_constr_arg_with_args depth Ts
blanchet@38207
  1714
          (@{const_name Quot}, rep_T --> abs_T) ts 0 rep_T
blanchet@33192
  1715
    and do_const depth Ts t (x as (s, T)) ts =
blanchet@38209
  1716
      if member (term_match thy) whacks (Const x) then
blanchet@38209
  1717
        Const (@{const_name unknown}, fastype_of1 (Ts, t))
blanchet@38209
  1718
      else case AList.lookup (op =) ersatz_table s of
blanchet@33192
  1719
        SOME s' =>
blanchet@33192
  1720
        do_const (depth + 1) Ts (list_comb (Const (s', T), ts)) (s', T) ts
blanchet@33192
  1721
      | NONE =>
blanchet@33192
  1722
        let
blanchet@38206
  1723
          fun def_inline_threshold () =
blanchet@47990
  1724
            if is_boolean_type (body_type T) andalso
blanchet@41871
  1725
               total_consts <> SOME true then
blanchet@38206
  1726
              def_inline_threshold_for_booleans
blanchet@38206
  1727
            else
blanchet@38206
  1728
              def_inline_threshold_for_non_booleans
blanchet@33192
  1729
          val (const, ts) =
blanchet@39359
  1730
            if is_built_in_const thy stds x then
blanchet@33877
  1731
              (Const x, ts)
blanchet@33192
  1732
            else case AList.lookup (op =) case_names s of
blanchet@33192
  1733
              SOME n =>
blanchet@37476
  1734
              if length ts < n then
blanchet@37476
  1735
                (do_term depth Ts (eta_expand Ts t (n - length ts)), [])
blanchet@37476
  1736
              else
blanchet@37476
  1737
                let
blanchet@37476
  1738
                  val (dataT, res_T) = nth_range_type n T
blanchet@37476
  1739
                                       |> pairf domain_type range_type
blanchet@37476
  1740
                in
blanchet@42958
  1741
                  (optimized_case_def hol_ctxt Ts dataT res_T
blanchet@37476
  1742
                                      (map (do_term depth Ts) (take n ts)),
blanchet@37476
  1743
                   drop n ts)
blanchet@37476
  1744
                end
blanchet@33192
  1745
            | _ =>
blanchet@37256
  1746
              if is_constr ctxt stds x then
blanchet@33192
  1747
                (Const x, ts)
blanchet@37256
  1748
              else if is_stale_constr ctxt x then
blanchet@34936
  1749
                raise NOT_SUPPORTED ("(non-co)constructors of codatatypes \
blanchet@33581
  1750
                                     \(\"" ^ s ^ "\")")
blanchet@35284
  1751
              else if is_quot_abs_fun ctxt x then
blanchet@34936
  1752
                let
blanchet@34936
  1753
                  val rep_T = domain_type T
blanchet@34936
  1754
                  val abs_T = range_type T
blanchet@34936
  1755
                in
blanchet@34936
  1756
                  (Abs (Name.uu, rep_T,
blanchet@34936
  1757
                        Const (@{const_name Quot}, rep_T --> abs_T)
blanchet@35311
  1758
                               $ (Const (quot_normal_name_for_type ctxt abs_T,
blanchet@34936
  1759
                                         rep_T --> rep_T) $ Bound 0)), ts)
blanchet@34936
  1760
                end
blanchet@35284
  1761
              else if is_quot_rep_fun ctxt x then
blanchet@38207
  1762
                quot_rep_of depth Ts (domain_type T) (range_type T) ts
blanchet@33192
  1763
              else if is_record_get thy x then
blanchet@33192
  1764
                case length ts of
blanchet@33192
  1765
                  0 => (do_term depth Ts (eta_expand Ts t 1), [])
blanchet@35070
  1766
                | _ => (optimized_record_get hol_ctxt s (domain_type T)
blanchet@34982
  1767
                            (range_type T) (do_term depth Ts (hd ts)), tl ts)
blanchet@33192
  1768
              else if is_record_update thy x then
blanchet@33192
  1769
                case length ts of
blanchet@35070
  1770
                  2 => (optimized_record_update hol_ctxt
blanchet@33580
  1771
                            (unsuffix Record.updateN s) (nth_range_type 2 T)
blanchet@33580
  1772
                            (do_term depth Ts (hd ts))
blanchet@33580
  1773
                            (do_term depth Ts (nth ts 1)), [])
blanchet@33192
  1774
                | n => (do_term depth Ts (eta_expand Ts t (2 - n)), [])
blanchet@38207
  1775
              else if is_abs_fun ctxt x andalso
blanchet@38240
  1776
                      is_quot_type ctxt (range_type T) then
blanchet@38207
  1777
                let
blanchet@38207
  1778
                  val abs_T = range_type T
blanchet@46819
  1779
                  val rep_T = elem_type (domain_type T)
blanchet@38207
  1780
                  val eps_fun = Const (@{const_name Eps},
blanchet@38207
  1781
                                       (rep_T --> bool_T) --> rep_T)
blanchet@39315
  1782
                  val normal_fun =
blanchet@38207
  1783
                    Const (quot_normal_name_for_type ctxt abs_T,
blanchet@38207
  1784
                           rep_T --> rep_T)
blanchet@38207
  1785
                  val abs_fun = Const (@{const_name Quot}, rep_T --> abs_T)
blanchet@46819
  1786
                  val pred =
blanchet@46819
  1787
                    Abs (Name.uu, rep_T,
blanchet@46819
  1788
                         Const (@{const_name Set.member},
blanchet@46819
  1789
                                rep_T --> domain_type T --> bool_T)
blanchet@46819
  1790
                         $ Bound 0 $ Bound 1)
blanchet@38207
  1791
                in
blanchet@46819
  1792
                  (Abs (Name.uu, HOLogic.mk_setT rep_T,
blanchet@46819
  1793
                        abs_fun $ (normal_fun $ (eps_fun $ pred)))
blanchet@38207
  1794
                   |> do_term (depth + 1) Ts, ts)
blanchet@38207
  1795
                end
blanchet@37256
  1796
              else if is_rep_fun ctxt x then
blanchet@37256
  1797
                let val x' = mate_of_rep_fun ctxt x in
blanchet@37256
  1798
                  if is_constr ctxt stds x' then
blanchet@33192
  1799
                    select_nth_constr_arg_with_args depth Ts x' ts 0
blanchet@33192
  1800
                                                    (range_type T)
blanchet@38240
  1801
                  else if is_quot_type ctxt (domain_type T) then
blanchet@38207
  1802
                    let
blanchet@38207
  1803
                      val abs_T = domain_type T
blanchet@46745
  1804
                      val rep_T = elem_type (range_type T)
blanchet@38207
  1805
                      val (rep_fun, _) = quot_rep_of depth Ts abs_T rep_T []
blanchet@38243
  1806
                      val (equiv_rel, _) =
wenzelm@45280
  1807
                        equiv_relation_for_quot_type ctxt abs_T
blanchet@38207
  1808
                    in
blanchet@46745
  1809
                      (Abs (Name.uu, abs_T,
blanchet@46745
  1810
                            HOLogic.Collect_const rep_T
blanchet@46745
  1811
                            $ (equiv_rel $ (rep_fun $ Bound 0))),
blanchet@38207
  1812
                       ts)
blanchet@38207
  1813
                    end
blanchet@33192
  1814
                  else
blanchet@38208
  1815
                    (Const x, ts)
blanchet@33192
  1816
                end
blanchet@38202
  1817
              else if is_equational_fun_but_no_plain_def hol_ctxt x orelse
blanchet@35807
  1818
                      is_choice_spec_fun hol_ctxt x then
blanchet@33192
  1819
                (Const x, ts)
blanchet@41791
  1820
              else case def_of_const_ext thy def_tables x of
blanchet@41791
  1821
                SOME (unfold, def) =>
blanchet@33192
  1822
                if depth > unfold_max_depth then
blanchet@34124
  1823
                  raise TOO_LARGE ("Nitpick_HOL.unfold_defs_in_term",
blanchet@34124
  1824
                                   "too many nested definitions (" ^
blanchet@34124
  1825
                                   string_of_int depth ^ ") while expanding " ^
blanchet@34124
  1826
                                   quote s)
krauss@44017
  1827
                else if s = "Wfrec.wfrec'" (* FIXME unchecked! *) then
blanchet@37476
  1828
                  (do_term (depth + 1) Ts (s_betapplys Ts (def, ts)), [])
blanchet@41791
  1829
                else if not unfold andalso
blanchet@41791
  1830
                     size_of_term def > def_inline_threshold () then
blanchet@38202
  1831
                  (Const x, ts)
blanchet@33192
  1832
                else
blanchet@33192
  1833
                  (do_term (depth + 1) Ts def, ts)
blanchet@33192
  1834
              | NONE => (Const x, ts)
blanchet@37476
  1835
        in
blanchet@37476
  1836
          s_betapplys Ts (const, map (do_term depth Ts) ts)
blanchet@37476
  1837
          |> s_beta_norm Ts
blanchet@37476
  1838
        end
blanchet@33192
  1839
  in do_term 0 [] end
blanchet@33192
  1840
blanchet@35718
  1841
(** Axiom extraction/generation **)
blanchet@35718
  1842
blanchet@46086
  1843
fun extensional_equal j T t1 t2 =
blanchet@46244
  1844
  if is_fun_type T then
blanchet@46086
  1845
    let
blanchet@46086
  1846
      val dom_T = pseudo_domain_type T
blanchet@46086
  1847
      val ran_T = pseudo_range_type T
blanchet@46086
  1848
      val var_t = Var (("x", j), dom_T)
blanchet@46244
  1849
    in
blanchet@46244
  1850
      extensional_equal (j + 1) ran_T (betapply (t1, var_t))
blanchet@46244
  1851
                        (betapply (t2, var_t))
blanchet@46244
  1852
    end
blanchet@46086
  1853
  else
haftmann@38864
  1854
    Const (@{const_name HOL.eq}, T --> T --> bool_T) $ t1 $ t2
blanchet@38206
  1855
blanchet@46091
  1856
(* FIXME: needed? *)
blanchet@38202
  1857
fun equationalize_term ctxt tag t =
blanchet@38206
  1858
  let
blanchet@38206
  1859
    val j = maxidx_of_term t + 1
blanchet@38206
  1860
    val (prems, concl) = Logic.strip_horn t
blanchet@38206
  1861
  in
blanchet@38174
  1862
    Logic.list_implies (prems,
blanchet@38200
  1863
        case concl of
haftmann@38864
  1864
          @{const Trueprop} $ (Const (@{const_name HOL.eq}, Type (_, [T, _]))
blanchet@38206
  1865
                               $ t1 $ t2) =>
blanchet@38206
  1866
          @{const Trueprop} $ extensional_equal j T t1 t2
blanchet@38200
  1867
        | @{const Trueprop} $ t' =>
blanchet@38200
  1868
          @{const Trueprop} $ HOLogic.mk_eq (t', @{const True})
blanchet@38201
  1869
        | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38206
  1870
          @{const Trueprop} $ extensional_equal j T t1 t2
blanchet@46086
  1871
        | _ => (warning ("Ignoring " ^ quote tag ^ " for non-equation " ^
blanchet@38201
  1872
                         quote (Syntax.string_of_term ctxt t) ^ ".");
blanchet@38201
  1873
                raise SAME ()))
blanchet@38201
  1874
    |> SOME
blanchet@38200
  1875
  end
blanchet@38201
  1876
  handle SAME () => NONE
blanchet@38172
  1877
blanchet@35807
  1878
fun pair_for_prop t =
blanchet@35807
  1879
  case term_under_def t of
blanchet@35807
  1880
    Const (s, _) => (s, t)
blanchet@35807
  1881
  | t' => raise TERM ("Nitpick_HOL.pair_for_prop", [t, t'])
blanchet@38172
  1882
blanchet@35807
  1883
fun def_table_for get ctxt subst =
blanchet@35807
  1884
  ctxt |> get |> map (pair_for_prop o subst_atomic subst)
blanchet@35807
  1885
       |> AList.group (op =) |> Symtab.make
blanchet@38172
  1886
blanchet@41791
  1887
fun const_def_tables ctxt subst ts =
blanchet@41792
  1888
  (def_table_for (map prop_of o Nitpick_Unfolds.get) ctxt subst,
blanchet@41791
  1889
   fold (fn (s, t) => Symtab.map_default (s, []) (cons t))
blanchet@41791
  1890
        (map pair_for_prop ts) Symtab.empty)
blanchet@38172
  1891
blanchet@38172
  1892
fun paired_with_consts t = map (rpair t) (Term.add_const_names t [])
blanchet@35718
  1893
fun const_nondef_table ts =
blanchet@35807
  1894
  fold (append o paired_with_consts) ts [] |> AList.group (op =) |> Symtab.make
blanchet@38172
  1895
blanchet@38201
  1896
fun const_simp_table ctxt =
blanchet@38202
  1897
  def_table_for (map_filter (equationalize_term ctxt "nitpick_simp" o prop_of)
blanchet@38201
  1898
                 o Nitpick_Simps.get) ctxt
blanchet@38201
  1899
fun const_psimp_table ctxt =
blanchet@38202
  1900
  def_table_for (map_filter (equationalize_term ctxt "nitpick_psimp" o prop_of)
blanchet@38201
  1901
                 o Nitpick_Psimps.get) ctxt
blanchet@38172
  1902
blanchet@35807
  1903
fun const_choice_spec_table ctxt subst =
blanchet@35807
  1904
  map (subst_atomic subst o prop_of) (Nitpick_Choice_Specs.get ctxt)
blanchet@35807
  1905
  |> const_nondef_table
blanchet@38172
  1906
blanchet@41791
  1907
fun inductive_intro_table ctxt subst def_tables =
wenzelm@42361
  1908
  let val thy = Proof_Context.theory_of ctxt in
blanchet@37264
  1909
    def_table_for
blanchet@41791
  1910
        (maps (map (unfold_mutually_inductive_preds thy def_tables o prop_of)
blanchet@37264
  1911
               o snd o snd)
blanchet@37264
  1912
         o filter (fn (cat, _) => cat = Spec_Rules.Inductive orelse
blanchet@37264
  1913
                                  cat = Spec_Rules.Co_Inductive)
blanchet@37264
  1914
         o Spec_Rules.get) ctxt subst
blanchet@37264
  1915
  end
blanchet@38172
  1916
blanchet@35718
  1917
fun ground_theorem_table thy =
blanchet@35718
  1918
  fold ((fn @{const Trueprop} $ t1 =>
blanchet@35718
  1919
            is_ground_term t1 ? Inttab.map_default (hash_term t1, []) (cons t1)
wenzelm@39557
  1920
          | _ => I) o prop_of o snd) (Global_Theory.all_thms_of thy) Inttab.empty
blanchet@35718
  1921
blanchet@38240
  1922
fun ersatz_table ctxt =
krauss@44016
  1923
 #ersatz_table (Data.get (Context.Proof ctxt))
blanchet@38240
  1924
 |> fold (append o snd) (#frac_types (Data.get (Context.Proof ctxt)))
blanchet@35718
  1925
blanchet@35718
  1926
fun add_simps simp_table s eqs =
blanchet@35718
  1927
  Unsynchronized.change simp_table
blanchet@35718
  1928
      (Symtab.update (s, eqs @ these (Symtab.lookup (!simp_table) s)))
blanchet@35718
  1929
blanchet@37256
  1930
fun inverse_axioms_for_rep_fun ctxt (x as (_, T)) =
blanchet@37256
  1931
  let
wenzelm@42361
  1932
    val thy = Proof_Context.theory_of ctxt
blanchet@37256
  1933
    val abs_T = domain_type T
blanchet@37256
  1934
  in
blanchet@37256
  1935
    typedef_info ctxt (fst (dest_Type abs_T)) |> the
blanchet@35718
  1936
    |> pairf #Abs_inverse #Rep_inverse
blanchet@36555
  1937
    |> pairself (specialize_type thy x o prop_of o the)
blanchet@35718
  1938
    ||> single |> op ::
blanchet@35718
  1939
  end
blanchet@37256
  1940
fun optimized_typedef_axioms ctxt (abs_z as (abs_s, _)) =
blanchet@37256
  1941
  let
wenzelm@42361
  1942
    val thy = Proof_Context.theory_of ctxt
blanchet@37256
  1943
    val abs_T = Type abs_z
blanchet@37256
  1944
  in
blanchet@37256
  1945
    if is_univ_typedef ctxt abs_T then
blanchet@35718
  1946
      []
blanchet@37256
  1947
    else case typedef_info ctxt abs_s of
blanchet@35718
  1948
      SOME {abs_type, rep_type, Rep_name, prop_of_Rep, set_name, ...} =>
blanchet@35718
  1949
      let
blanchet@38240
  1950
        val rep_T = varify_and_instantiate_type ctxt abs_type abs_T rep_type
blanchet@35718
  1951
        val rep_t = Const (Rep_name, abs_T --> rep_T)
blanchet@46089
  1952
        val set_t = Const (set_name, HOLogic.mk_setT rep_T)
blanchet@35718
  1953
        val set_t' =
blanchet@35718
  1954
          prop_of_Rep |> HOLogic.dest_Trueprop
blanchet@36555
  1955
                      |> specialize_type thy (dest_Const rep_t)
blanchet@35718
  1956
                      |> HOLogic.dest_mem |> snd
blanchet@35718
  1957
      in
blanchet@35718
  1958
        [HOLogic.all_const abs_T
blanchet@46088
  1959
         $ Abs (Name.uu, abs_T, HOLogic.mk_mem (rep_t $ Bound 0, set_t))]
blanchet@35718
  1960
        |> set_t <> set_t' ? cons (HOLogic.mk_eq (set_t, set_t'))
blanchet@35718
  1961
        |> map HOLogic.mk_Trueprop
blanchet@35718
  1962
      end
blanchet@35718
  1963
    | NONE => []
blanchet@35718
  1964
  end
blanchet@35718
  1965
fun optimized_quot_type_axioms ctxt stds abs_z =
blanchet@35718
  1966
  let
blanchet@35718
  1967
    val abs_T = Type abs_z
wenzelm@45280
  1968
    val rep_T = rep_type_for_quot_type ctxt abs_T
wenzelm@45280
  1969
    val (equiv_rel, partial) = equiv_relation_for_quot_type ctxt abs_T
blanchet@35718
  1970
    val a_var = Var (("a", 0), abs_T)
blanchet@35718
  1971
    val x_var = Var (("x", 0), rep_T)
blanchet@35718
  1972
    val y_var = Var (("y", 0), rep_T)
blanchet@35718
  1973
    val x = (@{const_name Quot}, rep_T --> abs_T)
blanchet@37256
  1974
    val sel_a_t = select_nth_constr_arg ctxt stds x a_var 0 rep_T
blanchet@38207
  1975
    val normal_fun =
blanchet@38207
  1976
      Const (quot_normal_name_for_type ctxt abs_T, rep_T --> rep_T)
blanchet@38207
  1977
    val normal_x = normal_fun $ x_var
blanchet@38207
  1978
    val normal_y = normal_fun $ y_var
blanchet@35718
  1979
    val is_unknown_t = Const (@{const_name is_unknown}, rep_T --> bool_T)
blanchet@35718
  1980
  in
blanchet@38207
  1981
    [Logic.mk_equals (normal_fun $ sel_a_t, sel_a_t),
blanchet@35718
  1982
     Logic.list_implies
blanchet@35718
  1983
         ([@{const Not} $ (is_unknown_t $ normal_x),
blanchet@35718
  1984
           @{const Not} $ (is_unknown_t $ normal_y),
blanchet@35718
  1985
           equiv_rel $ x_var $ y_var] |> map HOLogic.mk_Trueprop,
blanchet@35718
  1986
           Logic.mk_equals (normal_x, normal_y)),
blanchet@35718
  1987
     Logic.list_implies
blanchet@35718
  1988
         ([HOLogic.mk_Trueprop (@{const Not} $ (is_unknown_t $ normal_x)),
blanchet@35718
  1989
           HOLogic.mk_Trueprop (@{const Not} $ HOLogic.mk_eq (normal_x, x_var))],
blanchet@35718
  1990
          HOLogic.mk_Trueprop (equiv_rel $ x_var $ normal_x))]
blanchet@38243
  1991
    |> partial ? cons (HOLogic.mk_Trueprop (equiv_rel $ sel_a_t $ sel_a_t))
blanchet@35718
  1992
  end
blanchet@35718
  1993
blanchet@39345
  1994
fun codatatype_bisim_axioms (hol_ctxt as {ctxt, stds, ...}) T =
blanchet@33192
  1995
  let
blanchet@35070
  1996
    val xs = datatype_constrs hol_ctxt T
blanchet@46101
  1997
    val pred_T = T --> bool_T
blanchet@33192
  1998
    val iter_T = @{typ bisim_iterator}
blanchet@33192
  1999
    val bisim_max = @{const bisim_iterator_max}
blanchet@33192
  2000
    val n_var = Var (("n", 0), iter_T)
blanchet@33192
  2001
    val n_var_minus_1 =
blanchet@35671
  2002
      Const (@{const_name safe_The}, (iter_T --> bool_T) --> iter_T)
blanchet@33192
  2003
      $ Abs ("m", iter_T, HOLogic.eq_const iter_T
blanchet@33192
  2004
                          $ (suc_const iter_T $ Bound 0) $ n_var)
blanchet@33192
  2005
    val x_var = Var (("x", 0), T)
blanchet@33192
  2006
    val y_var = Var (("y", 0), T)
blanchet@46113
  2007
    fun bisim_const T = Const (@{const_name bisim}, [iter_T, T, T] ---> bool_T)
blanchet@33192
  2008
    fun nth_sub_bisim x n nth_T =
blanchet@38240
  2009
      (if is_codatatype ctxt nth_T then bisim_const nth_T $ n_var_minus_1
blanchet@33192
  2010
       else HOLogic.eq_const nth_T)
blanchet@37256
  2011
      $ select_nth_constr_arg ctxt stds x x_var n nth_T
blanchet@37256
  2012
      $ select_nth_constr_arg ctxt stds x y_var n nth_T
blanchet@33192
  2013
    fun case_func (x as (_, T)) =
blanchet@33192
  2014
      let
blanchet@33192
  2015
        val arg_Ts = binder_types T
blanchet@33192
  2016
        val core_t =
blanchet@35070
  2017
          discriminate_value hol_ctxt x y_var ::
blanchet@33192
  2018
          map2 (nth_sub_bisim x) (index_seq 0 (length arg_Ts)) arg_Ts
blanchet@33192
  2019
          |> foldr1 s_conj
wenzelm@44241
  2020
      in fold_rev absdummy arg_Ts core_t end
blanchet@33192
  2021
  in
blanchet@38163
  2022
    [HOLogic.mk_imp
blanchet@38163
  2023
       (HOLogic.mk_disj (HOLogic.eq_const iter_T $ n_var $ zero_const iter_T,
blanchet@42958
  2024
            s_betapply [] (optimized_case_def hol_ctxt [] T bool_T
blanchet@38163
  2025
                                              (map case_func xs), x_var)),
blanchet@38163
  2026
        bisim_const T $ n_var $ x_var $ y_var),
blanchet@46101
  2027
     HOLogic.eq_const pred_T $ (bisim_const T $ bisim_max $ x_var)
blanchet@46107
  2028
     $ Abs (Name.uu, T, HOLogic.mk_eq (x_var, Bound 0))]
blanchet@33192
  2029
    |> map HOLogic.mk_Trueprop
blanchet@33192
  2030
  end
blanchet@33192
  2031
blanchet@33192
  2032
exception NO_TRIPLE of unit
blanchet@33192
  2033
blanchet@33192
  2034
fun triple_for_intro_rule thy x t =
blanchet@33192
  2035
  let
wenzelm@35625
  2036
    val prems = Logic.strip_imp_prems t |> map (Object_Logic.atomize_term thy)
wenzelm@35625
  2037
    val concl = Logic.strip_imp_concl t |> Object_Logic.atomize_term thy
blanchet@34121
  2038
    val (main, side) = List.partition (exists_Const (curry (op =) x)) prems
blanchet@36385
  2039
    val is_good_head = curry (op =) (Const x) o head_of
blanchet@33192
  2040
  in
blanchet@33192
  2041
    if forall is_good_head main then (side, main, concl) else raise NO_TRIPLE ()
blanchet@33192
  2042
  end
blanchet@33192
  2043
blanchet@33192
  2044
val tuple_for_args = HOLogic.mk_tuple o snd o strip_comb
blanchet@33192
  2045
fun wf_constraint_for rel side concl main =
blanchet@33192
  2046
  let
blanchet@37269
  2047
    val core = HOLogic.mk_mem (HOLogic.mk_prod
blanchet@37269
  2048
                               (pairself tuple_for_args (main, concl)), Var rel)
blanchet@33192
  2049
    val t = List.foldl HOLogic.mk_imp core side
blanchet@37269
  2050
    val vars = filter_out (curry (op =) rel) (Term.add_vars t [])
blanchet@33192
  2051
  in
blanchet@33192
  2052
    Library.foldl (fn (t', ((x, j), T)) =>
blanchet@33192
  2053
                      HOLogic.all_const T
blanchet@33192
  2054
                      $ Abs (x, T, abstract_over (Var ((x, j), T), t')))
blanchet@33192
  2055
                  (t, vars)
blanchet@33192
  2056
  end
blanchet@33192
  2057
fun wf_constraint_for_triple rel (side, main, concl) =
blanchet@33192
  2058
  map (wf_constraint_for rel side concl) main |> foldr1 s_conj
blanchet@33192
  2059
blanchet@33192
  2060
fun terminates_by ctxt timeout goal tac =
wenzelm@42793
  2061
  can (SINGLE (Classical.safe_tac ctxt) #> the
wenzelm@42793
  2062
       #> SINGLE (DETERM_TIMEOUT timeout (tac ctxt (auto_tac ctxt)))
blanchet@33192
  2063
       #> the #> Goal.finish ctxt) goal
blanchet@33192
  2064
blanchet@35181
  2065
val max_cached_wfs = 50
blanchet@35181
  2066
val cached_timeout =
blanchet@35181
  2067
  Synchronized.var "Nitpick_HOL.cached_timeout" (SOME Time.zeroTime)
blanchet@35181
  2068
val cached_wf_props =
blanchet@35181
  2069
  Synchronized.var "Nitpick_HOL.cached_wf_props" ([] : (term * bool) list)
blanchet@33192
  2070
krauss@33351
  2071
val termination_tacs = [Lexicographic_Order.lex_order_tac true,
blanchet@33192
  2072
                        ScnpReconstruct.sizechange_tac]
blanchet@33192
  2073
blanchet@33580
  2074
fun uncached_is_well_founded_inductive_pred
blanchet@39359
  2075
        ({thy, ctxt, stds, debug, tac_timeout, intro_table, ...} : hol_context)
blanchet@39359
  2076
        (x as (_, T)) =
blanchet@39359
  2077
  case def_props_for_const thy stds intro_table x of
blanchet@33580
  2078
    [] => raise TERM ("Nitpick_HOL.uncached_is_well_founded_inductive",
blanchet@33232
  2079
                      [Const x])
blanchet@33192
  2080
  | intro_ts =>
blanchet@33192
  2081
    (case map (triple_for_intro_rule thy x) intro_ts
blanchet@33192
  2082
          |> filter_out (null o #2) of
blanchet@33192
  2083
       [] => true
blanchet@33192
  2084
     | triples =>
blanchet@33192
  2085
       let
blanchet@33192
  2086
         val binders_T = HOLogic.mk_tupleT (binder_types T)
blanchet@46089
  2087
         val rel_T = HOLogic.mk_setT (HOLogic.mk_prodT (binders_T, binders_T))
blanchet@33882
  2088
         val j = fold Integer.max (map maxidx_of_term intro_ts) 0 + 1
blanchet@33192
  2089
         val rel = (("R", j), rel_T)
blanchet@33192
  2090
         val prop = Const (@{const_name wf}, rel_T --> bool_T) $ Var rel ::
blanchet@33192
  2091
                    map (wf_constraint_for_triple rel) triples
blanchet@33192
  2092
                    |> foldr1 s_conj |> HOLogic.mk_Trueprop
blanchet@33192
  2093
         val _ = if debug then
wenzelm@40132
  2094
                   Output.urgent_message ("Wellfoundedness goal: " ^
blanchet@33192
  2095
                             Syntax.string_of_term ctxt prop ^ ".")
blanchet@33192
  2096
                 else
blanchet@33192
  2097
                   ()
blanchet@33192
  2098
       in
blanchet@35181
  2099
         if tac_timeout = Synchronized.value cached_timeout andalso
blanchet@35181
  2100
            length (Synchronized.value cached_wf_props) < max_cached_wfs then
blanchet@33557
  2101
           ()
blanchet@33557
  2102
         else
blanchet@35181
  2103
           (Synchronized.change cached_wf_props (K []);
blanchet@35181
  2104
            Synchronized.change cached_timeout (K tac_timeout));
blanchet@35181
  2105
         case AList.lookup (op =) (Synchronized.value cached_wf_props) prop of
blanchet@33192
  2106
           SOME wf => wf
blanchet@33192
  2107
         | NONE =>
blanchet@33192
  2108
           let
blanchet@33192
  2109
             val goal = prop |> cterm_of thy |> Goal.init
blanchet@33705
  2110
             val wf = exists (terminates_by ctxt tac_timeout goal)
blanchet@33705
  2111
                             termination_tacs
blanchet@35181
  2112
           in Synchronized.change cached_wf_props (cons (prop, wf)); wf end
blanchet@33192
  2113
       end)
blanchet@35309
  2114
    handle List.Empty => false | NO_TRIPLE () => false
blanchet@33192
  2115
blanchet@35070
  2116
(* The type constraint below is a workaround for a Poly/ML crash. *)
blanchet@33192
  2117
blanchet@33192
  2118
fun is_well_founded_inductive_pred
blanchet@41791
  2119
        (hol_ctxt as {thy, wfs, def_tables, wf_cache, ...} : hol_context)
blanchet@33192
  2120
        (x as (s, _)) =
blanchet@33192
  2121
  case triple_lookup (const_match thy) wfs x of
blanchet@33192
  2122
    SOME (SOME b) => b
blanchet@34936
  2123
  | _ => s = @{const_name Nats} orelse s = @{const_name fold_graph'} orelse
blanchet@34936
  2124
         case AList.lookup (op =) (!wf_cache) x of
blanchet@35181
  2125
           SOME (_, wf) => wf
blanchet@35181
  2126
         | NONE =>
blanchet@35181
  2127
           let
blanchet@41791
  2128
             val gfp = (fixpoint_kind_of_const thy def_tables x = Gfp)
blanchet@35181
  2129
             val wf = uncached_is_well_founded_inductive_pred hol_ctxt x
blanchet@35181
  2130
           in
blanchet@35181
  2131
             Unsynchronized.change wf_cache (cons (x, (gfp, wf))); wf
blanchet@35181
  2132
           end
blanchet@33192
  2133
blanchet@35280
  2134
fun ap_curry [_] _ t = t
blanchet@35280
  2135
  | ap_curry arg_Ts tuple_T t =
blanchet@33192
  2136
    let val n = length arg_Ts in
wenzelm@46219
  2137
      fold_rev (Term.abs o pair "c") arg_Ts
wenzelm@46219
  2138
                (incr_boundvars n t $ mk_flat_tuple tuple_T (map Bound (n - 1 downto 0)))
blanchet@33192
  2139
    end
blanchet@33192
  2140
blanchet@33192
  2141
fun num_occs_of_bound_in_term j (t1 $ t2) =
blanchet@33192
  2142
    op + (pairself (num_occs_of_bound_in_term j) (t1, t2))
blanchet@35280
  2143
  | num_occs_of_bound_in_term j (Abs (_, _, t')) =
blanchet@33192
  2144
    num_occs_of_bound_in_term (j + 1) t'
blanchet@33192
  2145
  | num_occs_of_bound_in_term j (Bound j') = if j' = j then 1 else 0
blanchet@33192
  2146
  | num_occs_of_bound_in_term _ _ = 0
blanchet@33192
  2147
blanchet@33192
  2148
val is_linear_inductive_pred_def =
blanchet@33192
  2149
  let
blanchet@33192
  2150
    fun do_disjunct j (Const (@{const_name Ex}, _) $ Abs (_, _, t2)) =
blanchet@33192
  2151
        do_disjunct (j + 1) t2
blanchet@33192
  2152
      | do_disjunct j t =
blanchet@33192
  2153
        case num_occs_of_bound_in_term j t of
blanchet@33192
  2154
          0 => true
blanchet@35070
  2155
        | 1 => exists (curry (op =) (Bound j) o head_of) (conjuncts_of t)
blanchet@33192
  2156
        | _ => false
blanchet@33192
  2157
    fun do_lfp_def (Const (@{const_name lfp}, _) $ t2) =
blanchet@33192
  2158
        let val (xs, body) = strip_abs t2 in
blanchet@33192
  2159
          case length xs of
blanchet@33192
  2160
            1 => false
blanchet@35070
  2161
          | n => forall (do_disjunct (n - 1)) (disjuncts_of body)
blanchet@33192
  2162
        end
blanchet@33192
  2163
      | do_lfp_def _ = false
blanchet@33192
  2164
  in do_lfp_def o strip_abs_body end
blanchet@33192
  2165
blanchet@33851
  2166
fun n_ptuple_paths 0 = []
blanchet@33851
  2167
  | n_ptuple_paths 1 = []
blanchet@33851
  2168
  | n_ptuple_paths n = [] :: map (cons 2) (n_ptuple_paths (n - 1))
blanchet@33851
  2169
val ap_n_split = HOLogic.mk_psplits o n_ptuple_paths
blanchet@33192
  2170
blanchet@33192
  2171
val linear_pred_base_and_step_rhss =
blanchet@33192
  2172
  let
blanchet@33192
  2173
    fun aux (Const (@{const_name lfp}, _) $ t2) =
blanchet@33192
  2174
        let
blanchet@33192
  2175
          val (xs, body) = strip_abs t2
blanchet@33192
  2176
          val arg_Ts = map snd (tl xs)