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