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