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