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