src/HOL/Tools/ATP/atp_problem_generate.ML
changeset 46320 0b8b73b49848
parent 46301 e2e52c7d25c9
child 46338 b02ff6b17599
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/Tools/ATP/atp_problem_generate.ML	Mon Jan 23 17:40:32 2012 +0100
     1.3 @@ -0,0 +1,2557 @@
     1.4 +(*  Title:      HOL/Tools/ATP/atp_problem_generate.ML
     1.5 +    Author:     Fabian Immler, TU Muenchen
     1.6 +    Author:     Makarius
     1.7 +    Author:     Jasmin Blanchette, TU Muenchen
     1.8 +
     1.9 +Translation of HOL to FOL for Metis and Sledgehammer.
    1.10 +*)
    1.11 +
    1.12 +signature ATP_PROBLEM_GENERATE =
    1.13 +sig
    1.14 +  type ('a, 'b) ho_term = ('a, 'b) ATP_Problem.ho_term
    1.15 +  type connective = ATP_Problem.connective
    1.16 +  type ('a, 'b, 'c) formula = ('a, 'b, 'c) ATP_Problem.formula
    1.17 +  type atp_format = ATP_Problem.atp_format
    1.18 +  type formula_kind = ATP_Problem.formula_kind
    1.19 +  type 'a problem = 'a ATP_Problem.problem
    1.20 +
    1.21 +  datatype locality =
    1.22 +    General | Helper | Induction | Intro | Elim | Simp | Local | Assum | Chained
    1.23 +
    1.24 +  datatype polymorphism = Polymorphic | Raw_Monomorphic | Mangled_Monomorphic
    1.25 +  datatype strictness = Strict | Non_Strict
    1.26 +  datatype granularity = All_Vars | Positively_Naked_Vars | Ghost_Type_Arg_Vars
    1.27 +  datatype type_level =
    1.28 +    All_Types |
    1.29 +    Noninf_Nonmono_Types of strictness * granularity |
    1.30 +    Fin_Nonmono_Types of granularity |
    1.31 +    Const_Arg_Types |
    1.32 +    No_Types
    1.33 +  type type_enc
    1.34 +
    1.35 +  val type_tag_idempotence : bool Config.T
    1.36 +  val type_tag_arguments : bool Config.T
    1.37 +  val no_lamsN : string
    1.38 +  val hide_lamsN : string
    1.39 +  val lam_liftingN : string
    1.40 +  val combinatorsN : string
    1.41 +  val hybrid_lamsN : string
    1.42 +  val keep_lamsN : string
    1.43 +  val schematic_var_prefix : string
    1.44 +  val fixed_var_prefix : string
    1.45 +  val tvar_prefix : string
    1.46 +  val tfree_prefix : string
    1.47 +  val const_prefix : string
    1.48 +  val type_const_prefix : string
    1.49 +  val class_prefix : string
    1.50 +  val lam_lifted_prefix : string
    1.51 +  val lam_lifted_mono_prefix : string
    1.52 +  val lam_lifted_poly_prefix : string
    1.53 +  val skolem_const_prefix : string
    1.54 +  val old_skolem_const_prefix : string
    1.55 +  val new_skolem_const_prefix : string
    1.56 +  val combinator_prefix : string
    1.57 +  val type_decl_prefix : string
    1.58 +  val sym_decl_prefix : string
    1.59 +  val guards_sym_formula_prefix : string
    1.60 +  val tags_sym_formula_prefix : string
    1.61 +  val fact_prefix : string
    1.62 +  val conjecture_prefix : string
    1.63 +  val helper_prefix : string
    1.64 +  val class_rel_clause_prefix : string
    1.65 +  val arity_clause_prefix : string
    1.66 +  val tfree_clause_prefix : string
    1.67 +  val lam_fact_prefix : string
    1.68 +  val typed_helper_suffix : string
    1.69 +  val untyped_helper_suffix : string
    1.70 +  val type_tag_idempotence_helper_name : string
    1.71 +  val predicator_name : string
    1.72 +  val app_op_name : string
    1.73 +  val type_guard_name : string
    1.74 +  val type_tag_name : string
    1.75 +  val simple_type_prefix : string
    1.76 +  val prefixed_predicator_name : string
    1.77 +  val prefixed_app_op_name : string
    1.78 +  val prefixed_type_tag_name : string
    1.79 +  val ascii_of : string -> string
    1.80 +  val unascii_of : string -> string
    1.81 +  val unprefix_and_unascii : string -> string -> string option
    1.82 +  val proxy_table : (string * (string * (thm * (string * string)))) list
    1.83 +  val proxify_const : string -> (string * string) option
    1.84 +  val invert_const : string -> string
    1.85 +  val unproxify_const : string -> string
    1.86 +  val new_skolem_var_name_from_const : string -> string
    1.87 +  val atp_irrelevant_consts : string list
    1.88 +  val atp_schematic_consts_of : term -> typ list Symtab.table
    1.89 +  val is_type_enc_higher_order : type_enc -> bool
    1.90 +  val polymorphism_of_type_enc : type_enc -> polymorphism
    1.91 +  val level_of_type_enc : type_enc -> type_level
    1.92 +  val is_type_enc_quasi_sound : type_enc -> bool
    1.93 +  val is_type_enc_fairly_sound : type_enc -> bool
    1.94 +  val type_enc_from_string : strictness -> string -> type_enc
    1.95 +  val adjust_type_enc : atp_format -> type_enc -> type_enc
    1.96 +  val mk_aconns :
    1.97 +    connective -> ('a, 'b, 'c) formula list -> ('a, 'b, 'c) formula
    1.98 +  val unmangled_const : string -> string * (string, 'b) ho_term list
    1.99 +  val unmangled_const_name : string -> string
   1.100 +  val helper_table : ((string * bool) * thm list) list
   1.101 +  val trans_lams_from_string :
   1.102 +    Proof.context -> type_enc -> string -> term list -> term list * term list
   1.103 +  val factsN : string
   1.104 +  val prepare_atp_problem :
   1.105 +    Proof.context -> atp_format -> formula_kind -> formula_kind -> type_enc
   1.106 +    -> bool -> string -> bool -> bool -> term list -> term
   1.107 +    -> ((string * locality) * term) list
   1.108 +    -> string problem * string Symtab.table * (string * locality) list vector
   1.109 +       * (string * term) list * int Symtab.table
   1.110 +  val atp_problem_weights : string problem -> (string * real) list
   1.111 +end;
   1.112 +
   1.113 +structure ATP_Problem_Generate : ATP_PROBLEM_GENERATE =
   1.114 +struct
   1.115 +
   1.116 +open ATP_Util
   1.117 +open ATP_Problem
   1.118 +
   1.119 +type name = string * string
   1.120 +
   1.121 +val type_tag_idempotence =
   1.122 +  Attrib.setup_config_bool @{binding atp_type_tag_idempotence} (K false)
   1.123 +val type_tag_arguments =
   1.124 +  Attrib.setup_config_bool @{binding atp_type_tag_arguments} (K false)
   1.125 +
   1.126 +val no_lamsN = "no_lams" (* used internally; undocumented *)
   1.127 +val hide_lamsN = "hide_lams"
   1.128 +val lam_liftingN = "lam_lifting"
   1.129 +val combinatorsN = "combinators"
   1.130 +val hybrid_lamsN = "hybrid_lams"
   1.131 +val keep_lamsN = "keep_lams"
   1.132 +
   1.133 +(* It's still unclear whether all TFF1 implementations will support type
   1.134 +   signatures such as "!>[A : $tType] : $o", with ghost type variables. *)
   1.135 +val avoid_first_order_ghost_type_vars = false
   1.136 +
   1.137 +val bound_var_prefix = "B_"
   1.138 +val all_bound_var_prefix = "BA_"
   1.139 +val exist_bound_var_prefix = "BE_"
   1.140 +val schematic_var_prefix = "V_"
   1.141 +val fixed_var_prefix = "v_"
   1.142 +val tvar_prefix = "T_"
   1.143 +val tfree_prefix = "t_"
   1.144 +val const_prefix = "c_"
   1.145 +val type_const_prefix = "tc_"
   1.146 +val simple_type_prefix = "s_"
   1.147 +val class_prefix = "cl_"
   1.148 +
   1.149 +(* Freshness almost guaranteed! *)
   1.150 +val atp_weak_prefix = "ATP:"
   1.151 +
   1.152 +val lam_lifted_prefix = atp_weak_prefix ^ "Lam"
   1.153 +val lam_lifted_mono_prefix = lam_lifted_prefix ^ "m"
   1.154 +val lam_lifted_poly_prefix = lam_lifted_prefix ^ "p"
   1.155 +
   1.156 +val skolem_const_prefix = "ATP" ^ Long_Name.separator ^ "Sko"
   1.157 +val old_skolem_const_prefix = skolem_const_prefix ^ "o"
   1.158 +val new_skolem_const_prefix = skolem_const_prefix ^ "n"
   1.159 +
   1.160 +val combinator_prefix = "COMB"
   1.161 +
   1.162 +val type_decl_prefix = "ty_"
   1.163 +val sym_decl_prefix = "sy_"
   1.164 +val guards_sym_formula_prefix = "gsy_"
   1.165 +val tags_sym_formula_prefix = "tsy_"
   1.166 +val fact_prefix = "fact_"
   1.167 +val conjecture_prefix = "conj_"
   1.168 +val helper_prefix = "help_"
   1.169 +val class_rel_clause_prefix = "clar_"
   1.170 +val arity_clause_prefix = "arity_"
   1.171 +val tfree_clause_prefix = "tfree_"
   1.172 +
   1.173 +val lam_fact_prefix = "ATP.lambda_"
   1.174 +val typed_helper_suffix = "_T"
   1.175 +val untyped_helper_suffix = "_U"
   1.176 +val type_tag_idempotence_helper_name = helper_prefix ^ "ti_idem"
   1.177 +
   1.178 +val predicator_name = "pp"
   1.179 +val app_op_name = "aa"
   1.180 +val type_guard_name = "gg"
   1.181 +val type_tag_name = "tt"
   1.182 +
   1.183 +val prefixed_predicator_name = const_prefix ^ predicator_name
   1.184 +val prefixed_app_op_name = const_prefix ^ app_op_name
   1.185 +val prefixed_type_tag_name = const_prefix ^ type_tag_name
   1.186 +
   1.187 +(*Escaping of special characters.
   1.188 +  Alphanumeric characters are left unchanged.
   1.189 +  The character _ goes to __
   1.190 +  Characters in the range ASCII space to / go to _A to _P, respectively.
   1.191 +  Other characters go to _nnn where nnn is the decimal ASCII code.*)
   1.192 +val upper_a_minus_space = Char.ord #"A" - Char.ord #" "
   1.193 +
   1.194 +fun stringN_of_int 0 _ = ""
   1.195 +  | stringN_of_int k n =
   1.196 +    stringN_of_int (k - 1) (n div 10) ^ string_of_int (n mod 10)
   1.197 +
   1.198 +fun ascii_of_char c =
   1.199 +  if Char.isAlphaNum c then
   1.200 +    String.str c
   1.201 +  else if c = #"_" then
   1.202 +    "__"
   1.203 +  else if #" " <= c andalso c <= #"/" then
   1.204 +    "_" ^ String.str (Char.chr (Char.ord c + upper_a_minus_space))
   1.205 +  else
   1.206 +    (* fixed width, in case more digits follow *)
   1.207 +    "_" ^ stringN_of_int 3 (Char.ord c)
   1.208 +
   1.209 +val ascii_of = String.translate ascii_of_char
   1.210 +
   1.211 +(** Remove ASCII armoring from names in proof files **)
   1.212 +
   1.213 +(* We don't raise error exceptions because this code can run inside a worker
   1.214 +   thread. Also, the errors are impossible. *)
   1.215 +val unascii_of =
   1.216 +  let
   1.217 +    fun un rcs [] = String.implode(rev rcs)
   1.218 +      | un rcs [#"_"] = un (#"_" :: rcs) [] (* ERROR *)
   1.219 +        (* Three types of _ escapes: __, _A to _P, _nnn *)
   1.220 +      | un rcs (#"_" :: #"_" :: cs) = un (#"_" :: rcs) cs
   1.221 +      | un rcs (#"_" :: c :: cs) =
   1.222 +        if #"A" <= c andalso c<= #"P" then
   1.223 +          (* translation of #" " to #"/" *)
   1.224 +          un (Char.chr (Char.ord c - upper_a_minus_space) :: rcs) cs
   1.225 +        else
   1.226 +          let val digits = List.take (c :: cs, 3) handle General.Subscript => [] in
   1.227 +            case Int.fromString (String.implode digits) of
   1.228 +              SOME n => un (Char.chr n :: rcs) (List.drop (cs, 2))
   1.229 +            | NONE => un (c :: #"_" :: rcs) cs (* ERROR *)
   1.230 +          end
   1.231 +      | un rcs (c :: cs) = un (c :: rcs) cs
   1.232 +  in un [] o String.explode end
   1.233 +
   1.234 +(* If string s has the prefix s1, return the result of deleting it,
   1.235 +   un-ASCII'd. *)
   1.236 +fun unprefix_and_unascii s1 s =
   1.237 +  if String.isPrefix s1 s then
   1.238 +    SOME (unascii_of (String.extract (s, size s1, NONE)))
   1.239 +  else
   1.240 +    NONE
   1.241 +
   1.242 +val proxy_table =
   1.243 +  [("c_False", (@{const_name False}, (@{thm fFalse_def},
   1.244 +       ("fFalse", @{const_name ATP.fFalse})))),
   1.245 +   ("c_True", (@{const_name True}, (@{thm fTrue_def},
   1.246 +       ("fTrue", @{const_name ATP.fTrue})))),
   1.247 +   ("c_Not", (@{const_name Not}, (@{thm fNot_def},
   1.248 +       ("fNot", @{const_name ATP.fNot})))),
   1.249 +   ("c_conj", (@{const_name conj}, (@{thm fconj_def},
   1.250 +       ("fconj", @{const_name ATP.fconj})))),
   1.251 +   ("c_disj", (@{const_name disj}, (@{thm fdisj_def},
   1.252 +       ("fdisj", @{const_name ATP.fdisj})))),
   1.253 +   ("c_implies", (@{const_name implies}, (@{thm fimplies_def},
   1.254 +       ("fimplies", @{const_name ATP.fimplies})))),
   1.255 +   ("equal", (@{const_name HOL.eq}, (@{thm fequal_def},
   1.256 +       ("fequal", @{const_name ATP.fequal})))),
   1.257 +   ("c_All", (@{const_name All}, (@{thm fAll_def},
   1.258 +       ("fAll", @{const_name ATP.fAll})))),
   1.259 +   ("c_Ex", (@{const_name Ex}, (@{thm fEx_def},
   1.260 +       ("fEx", @{const_name ATP.fEx}))))]
   1.261 +
   1.262 +val proxify_const = AList.lookup (op =) proxy_table #> Option.map (snd o snd)
   1.263 +
   1.264 +(* Readable names for the more common symbolic functions. Do not mess with the
   1.265 +   table unless you know what you are doing. *)
   1.266 +val const_trans_table =
   1.267 +  [(@{type_name Product_Type.prod}, "prod"),
   1.268 +   (@{type_name Sum_Type.sum}, "sum"),
   1.269 +   (@{const_name False}, "False"),
   1.270 +   (@{const_name True}, "True"),
   1.271 +   (@{const_name Not}, "Not"),
   1.272 +   (@{const_name conj}, "conj"),
   1.273 +   (@{const_name disj}, "disj"),
   1.274 +   (@{const_name implies}, "implies"),
   1.275 +   (@{const_name HOL.eq}, "equal"),
   1.276 +   (@{const_name All}, "All"),
   1.277 +   (@{const_name Ex}, "Ex"),
   1.278 +   (@{const_name If}, "If"),
   1.279 +   (@{const_name Set.member}, "member"),
   1.280 +   (@{const_name Meson.COMBI}, combinator_prefix ^ "I"),
   1.281 +   (@{const_name Meson.COMBK}, combinator_prefix ^ "K"),
   1.282 +   (@{const_name Meson.COMBB}, combinator_prefix ^ "B"),
   1.283 +   (@{const_name Meson.COMBC}, combinator_prefix ^ "C"),
   1.284 +   (@{const_name Meson.COMBS}, combinator_prefix ^ "S")]
   1.285 +  |> Symtab.make
   1.286 +  |> fold (Symtab.update o swap o snd o snd o snd) proxy_table
   1.287 +
   1.288 +(* Invert the table of translations between Isabelle and ATPs. *)
   1.289 +val const_trans_table_inv =
   1.290 +  const_trans_table |> Symtab.dest |> map swap |> Symtab.make
   1.291 +val const_trans_table_unprox =
   1.292 +  Symtab.empty
   1.293 +  |> fold (fn (_, (isa, (_, (_, atp)))) => Symtab.update (atp, isa)) proxy_table
   1.294 +
   1.295 +val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
   1.296 +val unproxify_const = perhaps (Symtab.lookup const_trans_table_unprox)
   1.297 +
   1.298 +fun lookup_const c =
   1.299 +  case Symtab.lookup const_trans_table c of
   1.300 +    SOME c' => c'
   1.301 +  | NONE => ascii_of c
   1.302 +
   1.303 +fun ascii_of_indexname (v, 0) = ascii_of v
   1.304 +  | ascii_of_indexname (v, i) = ascii_of v ^ "_" ^ string_of_int i
   1.305 +
   1.306 +fun make_bound_var x = bound_var_prefix ^ ascii_of x
   1.307 +fun make_all_bound_var x = all_bound_var_prefix ^ ascii_of x
   1.308 +fun make_exist_bound_var x = exist_bound_var_prefix ^ ascii_of x
   1.309 +fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
   1.310 +fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
   1.311 +
   1.312 +fun make_schematic_type_var (x, i) =
   1.313 +  tvar_prefix ^ (ascii_of_indexname (unprefix "'" x, i))
   1.314 +fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (unprefix "'" x))
   1.315 +
   1.316 +(* "HOL.eq" and choice are mapped to the ATP's equivalents *)
   1.317 +local
   1.318 +  val choice_const = (fst o dest_Const o HOLogic.choice_const) Term.dummyT
   1.319 +  fun default c = const_prefix ^ lookup_const c
   1.320 +in
   1.321 +  fun make_fixed_const _ @{const_name HOL.eq} = tptp_old_equal
   1.322 +    | make_fixed_const (SOME (THF (_, _, THF_With_Choice))) c =
   1.323 +      if c = choice_const then tptp_choice else default c
   1.324 +    | make_fixed_const _ c = default c
   1.325 +end
   1.326 +
   1.327 +fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
   1.328 +
   1.329 +fun make_type_class clas = class_prefix ^ ascii_of clas
   1.330 +
   1.331 +fun new_skolem_var_name_from_const s =
   1.332 +  let val ss = s |> space_explode Long_Name.separator in
   1.333 +    nth ss (length ss - 2)
   1.334 +  end
   1.335 +
   1.336 +(* These are either simplified away by "Meson.presimplify" (most of the time) or
   1.337 +   handled specially via "fFalse", "fTrue", ..., "fequal". *)
   1.338 +val atp_irrelevant_consts =
   1.339 +  [@{const_name False}, @{const_name True}, @{const_name Not},
   1.340 +   @{const_name conj}, @{const_name disj}, @{const_name implies},
   1.341 +   @{const_name HOL.eq}, @{const_name If}, @{const_name Let}]
   1.342 +
   1.343 +val atp_monomorph_bad_consts =
   1.344 +  atp_irrelevant_consts @
   1.345 +  (* These are ignored anyway by the relevance filter (unless they appear in
   1.346 +     higher-order places) but not by the monomorphizer. *)
   1.347 +  [@{const_name all}, @{const_name "==>"}, @{const_name "=="},
   1.348 +   @{const_name Trueprop}, @{const_name All}, @{const_name Ex},
   1.349 +   @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}]
   1.350 +
   1.351 +fun add_schematic_const (x as (_, T)) =
   1.352 +  Monomorph.typ_has_tvars T ? Symtab.insert_list (op =) x
   1.353 +val add_schematic_consts_of =
   1.354 +  Term.fold_aterms (fn Const (x as (s, _)) =>
   1.355 +                       not (member (op =) atp_monomorph_bad_consts s)
   1.356 +                       ? add_schematic_const x
   1.357 +                      | _ => I)
   1.358 +fun atp_schematic_consts_of t = add_schematic_consts_of t Symtab.empty
   1.359 +
   1.360 +(** Definitions and functions for FOL clauses and formulas for TPTP **)
   1.361 +
   1.362 +(** Isabelle arities **)
   1.363 +
   1.364 +type arity_atom = name * name * name list
   1.365 +
   1.366 +val type_class = the_single @{sort type}
   1.367 +
   1.368 +type arity_clause =
   1.369 +  {name : string,
   1.370 +   prem_atoms : arity_atom list,
   1.371 +   concl_atom : arity_atom}
   1.372 +
   1.373 +fun add_prem_atom tvar =
   1.374 +  fold (fn s => s <> type_class ? cons (`make_type_class s, `I tvar, []))
   1.375 +
   1.376 +(* Arity of type constructor "tcon :: (arg1, ..., argN) res" *)
   1.377 +fun make_axiom_arity_clause (tcons, name, (cls, args)) =
   1.378 +  let
   1.379 +    val tvars = map (prefix tvar_prefix o string_of_int) (1 upto length args)
   1.380 +    val tvars_srts = ListPair.zip (tvars, args)
   1.381 +  in
   1.382 +    {name = name,
   1.383 +     prem_atoms = [] |> fold (uncurry add_prem_atom) tvars_srts,
   1.384 +     concl_atom = (`make_type_class cls, `make_fixed_type_const tcons,
   1.385 +                   tvars ~~ tvars)}
   1.386 +  end
   1.387 +
   1.388 +fun arity_clause _ _ (_, []) = []
   1.389 +  | arity_clause seen n (tcons, ("HOL.type", _) :: ars) =  (* ignore *)
   1.390 +    arity_clause seen n (tcons, ars)
   1.391 +  | arity_clause seen n (tcons, (ar as (class, _)) :: ars) =
   1.392 +    if member (op =) seen class then
   1.393 +      (* multiple arities for the same (tycon, class) pair *)
   1.394 +      make_axiom_arity_clause (tcons,
   1.395 +          lookup_const tcons ^ "___" ^ ascii_of class ^ "_" ^ string_of_int n,
   1.396 +          ar) ::
   1.397 +      arity_clause seen (n + 1) (tcons, ars)
   1.398 +    else
   1.399 +      make_axiom_arity_clause (tcons, lookup_const tcons ^ "___" ^
   1.400 +                               ascii_of class, ar) ::
   1.401 +      arity_clause (class :: seen) n (tcons, ars)
   1.402 +
   1.403 +fun multi_arity_clause [] = []
   1.404 +  | multi_arity_clause ((tcons, ars) :: tc_arlists) =
   1.405 +    arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
   1.406 +
   1.407 +(* Generate all pairs (tycon, class, sorts) such that tycon belongs to class in
   1.408 +   theory thy provided its arguments have the corresponding sorts. *)
   1.409 +fun type_class_pairs thy tycons classes =
   1.410 +  let
   1.411 +    val alg = Sign.classes_of thy
   1.412 +    fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
   1.413 +    fun add_class tycon class =
   1.414 +      cons (class, domain_sorts tycon class)
   1.415 +      handle Sorts.CLASS_ERROR _ => I
   1.416 +    fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
   1.417 +  in map try_classes tycons end
   1.418 +
   1.419 +(*Proving one (tycon, class) membership may require proving others, so iterate.*)
   1.420 +fun iter_type_class_pairs _ _ [] = ([], [])
   1.421 +  | iter_type_class_pairs thy tycons classes =
   1.422 +      let
   1.423 +        fun maybe_insert_class s =
   1.424 +          (s <> type_class andalso not (member (op =) classes s))
   1.425 +          ? insert (op =) s
   1.426 +        val cpairs = type_class_pairs thy tycons classes
   1.427 +        val newclasses =
   1.428 +          [] |> fold (fold (fold (fold maybe_insert_class) o snd) o snd) cpairs
   1.429 +        val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
   1.430 +      in (classes' @ classes, union (op =) cpairs' cpairs) end
   1.431 +
   1.432 +fun make_arity_clauses thy tycons =
   1.433 +  iter_type_class_pairs thy tycons ##> multi_arity_clause
   1.434 +
   1.435 +
   1.436 +(** Isabelle class relations **)
   1.437 +
   1.438 +type class_rel_clause =
   1.439 +  {name : string,
   1.440 +   subclass : name,
   1.441 +   superclass : name}
   1.442 +
   1.443 +(* Generate all pairs (sub, super) such that sub is a proper subclass of super
   1.444 +   in theory "thy". *)
   1.445 +fun class_pairs _ [] _ = []
   1.446 +  | class_pairs thy subs supers =
   1.447 +      let
   1.448 +        val class_less = Sorts.class_less (Sign.classes_of thy)
   1.449 +        fun add_super sub super = class_less (sub, super) ? cons (sub, super)
   1.450 +        fun add_supers sub = fold (add_super sub) supers
   1.451 +      in fold add_supers subs [] end
   1.452 +
   1.453 +fun make_class_rel_clause (sub, super) =
   1.454 +  {name = sub ^ "_" ^ super, subclass = `make_type_class sub,
   1.455 +   superclass = `make_type_class super}
   1.456 +
   1.457 +fun make_class_rel_clauses thy subs supers =
   1.458 +  map make_class_rel_clause (class_pairs thy subs supers)
   1.459 +
   1.460 +(* intermediate terms *)
   1.461 +datatype iterm =
   1.462 +  IConst of name * typ * typ list |
   1.463 +  IVar of name * typ |
   1.464 +  IApp of iterm * iterm |
   1.465 +  IAbs of (name * typ) * iterm
   1.466 +
   1.467 +fun ityp_of (IConst (_, T, _)) = T
   1.468 +  | ityp_of (IVar (_, T)) = T
   1.469 +  | ityp_of (IApp (t1, _)) = snd (dest_funT (ityp_of t1))
   1.470 +  | ityp_of (IAbs ((_, T), tm)) = T --> ityp_of tm
   1.471 +
   1.472 +(*gets the head of a combinator application, along with the list of arguments*)
   1.473 +fun strip_iterm_comb u =
   1.474 +  let
   1.475 +    fun stripc (IApp (t, u), ts) = stripc (t, u :: ts)
   1.476 +      | stripc x = x
   1.477 +  in stripc (u, []) end
   1.478 +
   1.479 +fun atomic_types_of T = fold_atyps (insert (op =)) T []
   1.480 +
   1.481 +val tvar_a_str = "'a"
   1.482 +val tvar_a = TVar ((tvar_a_str, 0), HOLogic.typeS)
   1.483 +val tvar_a_name = (make_schematic_type_var (tvar_a_str, 0), tvar_a_str)
   1.484 +val itself_name = `make_fixed_type_const @{type_name itself}
   1.485 +val TYPE_name = `(make_fixed_const NONE) @{const_name TYPE}
   1.486 +val tvar_a_atype = AType (tvar_a_name, [])
   1.487 +val a_itself_atype = AType (itself_name, [tvar_a_atype])
   1.488 +
   1.489 +fun new_skolem_const_name s num_T_args =
   1.490 +  [new_skolem_const_prefix, s, string_of_int num_T_args]
   1.491 +  |> space_implode Long_Name.separator
   1.492 +
   1.493 +fun robust_const_type thy s =
   1.494 +  if s = app_op_name then
   1.495 +    Logic.varifyT_global @{typ "('a => 'b) => 'a => 'b"}
   1.496 +  else if String.isPrefix lam_lifted_prefix s then
   1.497 +    Logic.varifyT_global @{typ "'a => 'b"}
   1.498 +  else
   1.499 +    (* Old Skolems throw a "TYPE" exception here, which will be caught. *)
   1.500 +    s |> Sign.the_const_type thy
   1.501 +
   1.502 +(* This function only makes sense if "T" is as general as possible. *)
   1.503 +fun robust_const_typargs thy (s, T) =
   1.504 +  if s = app_op_name then
   1.505 +    let val (T1, T2) = T |> domain_type |> dest_funT in [T1, T2] end
   1.506 +  else if String.isPrefix old_skolem_const_prefix s then
   1.507 +    [] |> Term.add_tvarsT T |> rev |> map TVar
   1.508 +  else if String.isPrefix lam_lifted_prefix s then
   1.509 +    if String.isPrefix lam_lifted_poly_prefix s then
   1.510 +      let val (T1, T2) = T |> dest_funT in [T1, T2] end
   1.511 +    else
   1.512 +      []
   1.513 +  else
   1.514 +    (s, T) |> Sign.const_typargs thy
   1.515 +
   1.516 +(* Converts an Isabelle/HOL term (with combinators) into an intermediate term.
   1.517 +   Also accumulates sort infomation. *)
   1.518 +fun iterm_from_term thy format bs (P $ Q) =
   1.519 +    let
   1.520 +      val (P', P_atomics_Ts) = iterm_from_term thy format bs P
   1.521 +      val (Q', Q_atomics_Ts) = iterm_from_term thy format bs Q
   1.522 +    in (IApp (P', Q'), union (op =) P_atomics_Ts Q_atomics_Ts) end
   1.523 +  | iterm_from_term thy format _ (Const (c, T)) =
   1.524 +    (IConst (`(make_fixed_const (SOME format)) c, T,
   1.525 +             robust_const_typargs thy (c, T)),
   1.526 +     atomic_types_of T)
   1.527 +  | iterm_from_term _ _ _ (Free (s, T)) =
   1.528 +    (IConst (`make_fixed_var s, T, []), atomic_types_of T)
   1.529 +  | iterm_from_term _ format _ (Var (v as (s, _), T)) =
   1.530 +    (if String.isPrefix Meson_Clausify.new_skolem_var_prefix s then
   1.531 +       let
   1.532 +         val Ts = T |> strip_type |> swap |> op ::
   1.533 +         val s' = new_skolem_const_name s (length Ts)
   1.534 +       in IConst (`(make_fixed_const (SOME format)) s', T, Ts) end
   1.535 +     else
   1.536 +       IVar ((make_schematic_var v, s), T), atomic_types_of T)
   1.537 +  | iterm_from_term _ _ bs (Bound j) =
   1.538 +    nth bs j |> (fn (_, (name, T)) => (IConst (name, T, []), atomic_types_of T))
   1.539 +  | iterm_from_term thy format bs (Abs (s, T, t)) =
   1.540 +    let
   1.541 +      fun vary s = s |> AList.defined (op =) bs s ? vary o Symbol.bump_string
   1.542 +      val s = vary s
   1.543 +      val name = `make_bound_var s
   1.544 +      val (tm, atomic_Ts) = iterm_from_term thy format ((s, (name, T)) :: bs) t
   1.545 +    in (IAbs ((name, T), tm), union (op =) atomic_Ts (atomic_types_of T)) end
   1.546 +
   1.547 +datatype locality =
   1.548 +  General | Helper | Induction | Intro | Elim | Simp | Local | Assum | Chained
   1.549 +
   1.550 +datatype order = First_Order | Higher_Order
   1.551 +datatype polymorphism = Polymorphic | Raw_Monomorphic | Mangled_Monomorphic
   1.552 +datatype strictness = Strict | Non_Strict
   1.553 +datatype granularity = All_Vars | Positively_Naked_Vars | Ghost_Type_Arg_Vars
   1.554 +datatype type_level =
   1.555 +  All_Types |
   1.556 +  Noninf_Nonmono_Types of strictness * granularity |
   1.557 +  Fin_Nonmono_Types of granularity |
   1.558 +  Const_Arg_Types |
   1.559 +  No_Types
   1.560 +
   1.561 +datatype type_enc =
   1.562 +  Simple_Types of order * polymorphism * type_level |
   1.563 +  Guards of polymorphism * type_level |
   1.564 +  Tags of polymorphism * type_level
   1.565 +
   1.566 +fun is_type_enc_higher_order (Simple_Types (Higher_Order, _, _)) = true
   1.567 +  | is_type_enc_higher_order _ = false
   1.568 +
   1.569 +fun polymorphism_of_type_enc (Simple_Types (_, poly, _)) = poly
   1.570 +  | polymorphism_of_type_enc (Guards (poly, _)) = poly
   1.571 +  | polymorphism_of_type_enc (Tags (poly, _)) = poly
   1.572 +
   1.573 +fun level_of_type_enc (Simple_Types (_, _, level)) = level
   1.574 +  | level_of_type_enc (Guards (_, level)) = level
   1.575 +  | level_of_type_enc (Tags (_, level)) = level
   1.576 +
   1.577 +fun granularity_of_type_level (Noninf_Nonmono_Types (_, grain)) = grain
   1.578 +  | granularity_of_type_level (Fin_Nonmono_Types grain) = grain
   1.579 +  | granularity_of_type_level _ = All_Vars
   1.580 +
   1.581 +fun is_type_level_quasi_sound All_Types = true
   1.582 +  | is_type_level_quasi_sound (Noninf_Nonmono_Types _) = true
   1.583 +  | is_type_level_quasi_sound _ = false
   1.584 +val is_type_enc_quasi_sound = is_type_level_quasi_sound o level_of_type_enc
   1.585 +
   1.586 +fun is_type_level_fairly_sound (Fin_Nonmono_Types _) = true
   1.587 +  | is_type_level_fairly_sound level = is_type_level_quasi_sound level
   1.588 +val is_type_enc_fairly_sound = is_type_level_fairly_sound o level_of_type_enc
   1.589 +
   1.590 +fun is_type_level_monotonicity_based (Noninf_Nonmono_Types _) = true
   1.591 +  | is_type_level_monotonicity_based (Fin_Nonmono_Types _) = true
   1.592 +  | is_type_level_monotonicity_based _ = false
   1.593 +
   1.594 +(* "_query", "_bang", and "_at" are for the ASCII-challenged Metis and
   1.595 +   Mirabelle. *)
   1.596 +val queries = ["?", "_query"]
   1.597 +val bangs = ["!", "_bang"]
   1.598 +val ats = ["@", "_at"]
   1.599 +
   1.600 +fun try_unsuffixes ss s =
   1.601 +  fold (fn s' => fn NONE => try (unsuffix s') s | some => some) ss NONE
   1.602 +
   1.603 +fun try_nonmono constr suffixes fallback s =
   1.604 +  case try_unsuffixes suffixes s of
   1.605 +    SOME s =>
   1.606 +    (case try_unsuffixes suffixes s of
   1.607 +       SOME s => (constr Positively_Naked_Vars, s)
   1.608 +     | NONE =>
   1.609 +       case try_unsuffixes ats s of
   1.610 +         SOME s => (constr Ghost_Type_Arg_Vars, s)
   1.611 +       | NONE => (constr All_Vars, s))
   1.612 +  | NONE => fallback s
   1.613 +
   1.614 +fun type_enc_from_string strictness s =
   1.615 +  (case try (unprefix "poly_") s of
   1.616 +     SOME s => (SOME Polymorphic, s)
   1.617 +   | NONE =>
   1.618 +     case try (unprefix "raw_mono_") s of
   1.619 +       SOME s => (SOME Raw_Monomorphic, s)
   1.620 +     | NONE =>
   1.621 +       case try (unprefix "mono_") s of
   1.622 +         SOME s => (SOME Mangled_Monomorphic, s)
   1.623 +       | NONE => (NONE, s))
   1.624 +  ||> (pair All_Types
   1.625 +       |> try_nonmono Fin_Nonmono_Types bangs
   1.626 +       |> try_nonmono (curry Noninf_Nonmono_Types strictness) queries)
   1.627 +  |> (fn (poly, (level, core)) =>
   1.628 +         case (core, (poly, level)) of
   1.629 +           ("simple", (SOME poly, _)) =>
   1.630 +           (case (poly, level) of
   1.631 +              (Polymorphic, All_Types) =>
   1.632 +              Simple_Types (First_Order, Polymorphic, All_Types)
   1.633 +            | (Mangled_Monomorphic, _) =>
   1.634 +              if granularity_of_type_level level = All_Vars then
   1.635 +                Simple_Types (First_Order, Mangled_Monomorphic, level)
   1.636 +              else
   1.637 +                raise Same.SAME
   1.638 +            | _ => raise Same.SAME)
   1.639 +         | ("simple_higher", (SOME poly, _)) =>
   1.640 +           (case (poly, level) of
   1.641 +              (Polymorphic, All_Types) =>
   1.642 +              Simple_Types (Higher_Order, Polymorphic, All_Types)
   1.643 +            | (_, Noninf_Nonmono_Types _) => raise Same.SAME
   1.644 +            | (Mangled_Monomorphic, _) =>
   1.645 +              if granularity_of_type_level level = All_Vars then
   1.646 +                Simple_Types (Higher_Order, Mangled_Monomorphic, level)
   1.647 +              else
   1.648 +                raise Same.SAME
   1.649 +            | _ => raise Same.SAME)
   1.650 +         | ("guards", (SOME poly, _)) =>
   1.651 +           if poly = Mangled_Monomorphic andalso
   1.652 +              granularity_of_type_level level = Ghost_Type_Arg_Vars then
   1.653 +             raise Same.SAME
   1.654 +           else
   1.655 +             Guards (poly, level)
   1.656 +         | ("tags", (SOME poly, _)) =>
   1.657 +           if granularity_of_type_level level = Ghost_Type_Arg_Vars then
   1.658 +             raise Same.SAME
   1.659 +           else
   1.660 +             Tags (poly, level)
   1.661 +         | ("args", (SOME poly, All_Types (* naja *))) =>
   1.662 +           Guards (poly, Const_Arg_Types)
   1.663 +         | ("erased", (NONE, All_Types (* naja *))) =>
   1.664 +           Guards (Polymorphic, No_Types)
   1.665 +         | _ => raise Same.SAME)
   1.666 +  handle Same.SAME => error ("Unknown type encoding: " ^ quote s ^ ".")
   1.667 +
   1.668 +fun adjust_type_enc (THF (TPTP_Monomorphic, _, _))
   1.669 +                    (Simple_Types (order, _, level)) =
   1.670 +    Simple_Types (order, Mangled_Monomorphic, level)
   1.671 +  | adjust_type_enc (THF _) type_enc = type_enc
   1.672 +  | adjust_type_enc (TFF (TPTP_Monomorphic, _)) (Simple_Types (_, _, level)) =
   1.673 +    Simple_Types (First_Order, Mangled_Monomorphic, level)
   1.674 +  | adjust_type_enc (DFG DFG_Sorted) (Simple_Types (_, _, level)) =
   1.675 +    Simple_Types (First_Order, Mangled_Monomorphic, level)
   1.676 +  | adjust_type_enc (TFF _) (Simple_Types (_, poly, level)) =
   1.677 +    Simple_Types (First_Order, poly, level)
   1.678 +  | adjust_type_enc format (Simple_Types (_, poly, level)) =
   1.679 +    adjust_type_enc format (Guards (poly, level))
   1.680 +  | adjust_type_enc CNF_UEQ (type_enc as Guards stuff) =
   1.681 +    (if is_type_enc_fairly_sound type_enc then Tags else Guards) stuff
   1.682 +  | adjust_type_enc _ type_enc = type_enc
   1.683 +
   1.684 +fun constify_lifted (t $ u) = constify_lifted t $ constify_lifted u
   1.685 +  | constify_lifted (Abs (s, T, t)) = Abs (s, T, constify_lifted t)
   1.686 +  | constify_lifted (Free (x as (s, _))) =
   1.687 +    (if String.isPrefix lam_lifted_prefix s then Const else Free) x
   1.688 +  | constify_lifted t = t
   1.689 +
   1.690 +(* Requires bound variables not to clash with any schematic variables (as should
   1.691 +   be the case right after lambda-lifting). *)
   1.692 +fun open_form (Const (@{const_name All}, _) $ Abs (s, T, t)) =
   1.693 +    let
   1.694 +      val names = Name.make_context (map fst (Term.add_var_names t []))
   1.695 +      val (s, _) = Name.variant s names
   1.696 +    in open_form (subst_bound (Var ((s, 0), T), t)) end
   1.697 +  | open_form t = t
   1.698 +
   1.699 +fun lift_lams_part_1 ctxt type_enc =
   1.700 +  map close_form #> rpair ctxt
   1.701 +  #-> Lambda_Lifting.lift_lambdas
   1.702 +          (SOME ((if polymorphism_of_type_enc type_enc = Polymorphic then
   1.703 +                    lam_lifted_poly_prefix
   1.704 +                  else
   1.705 +                    lam_lifted_mono_prefix) ^ "_a"))
   1.706 +          Lambda_Lifting.is_quantifier
   1.707 +  #> fst
   1.708 +val lift_lams_part_2 = pairself (map (open_form o constify_lifted))
   1.709 +val lift_lams = lift_lams_part_2 ooo lift_lams_part_1
   1.710 +
   1.711 +fun intentionalize_def (Const (@{const_name All}, _) $ Abs (_, _, t)) =
   1.712 +    intentionalize_def t
   1.713 +  | intentionalize_def (Const (@{const_name HOL.eq}, _) $ t $ u) =
   1.714 +    let
   1.715 +      fun lam T t = Abs (Name.uu, T, t)
   1.716 +      val (head, args) = strip_comb t ||> rev
   1.717 +      val head_T = fastype_of head
   1.718 +      val n = length args
   1.719 +      val arg_Ts = head_T |> binder_types |> take n |> rev
   1.720 +      val u = u |> subst_atomic (args ~~ map Bound (0 upto n - 1))
   1.721 +    in HOLogic.eq_const head_T $ head $ fold lam arg_Ts u end
   1.722 +  | intentionalize_def t = t
   1.723 +
   1.724 +type translated_formula =
   1.725 +  {name : string,
   1.726 +   locality : locality,
   1.727 +   kind : formula_kind,
   1.728 +   iformula : (name, typ, iterm) formula,
   1.729 +   atomic_types : typ list}
   1.730 +
   1.731 +fun update_iformula f ({name, locality, kind, iformula, atomic_types}
   1.732 +                       : translated_formula) =
   1.733 +  {name = name, locality = locality, kind = kind, iformula = f iformula,
   1.734 +   atomic_types = atomic_types} : translated_formula
   1.735 +
   1.736 +fun fact_lift f ({iformula, ...} : translated_formula) = f iformula
   1.737 +
   1.738 +fun insert_type ctxt get_T x xs =
   1.739 +  let val T = get_T x in
   1.740 +    if exists (type_instance ctxt T o get_T) xs then xs
   1.741 +    else x :: filter_out (type_generalization ctxt T o get_T) xs
   1.742 +  end
   1.743 +
   1.744 +(* The Booleans indicate whether all type arguments should be kept. *)
   1.745 +datatype type_arg_policy =
   1.746 +  Explicit_Type_Args of bool (* infer_from_term_args *) |
   1.747 +  Mangled_Type_Args |
   1.748 +  No_Type_Args
   1.749 +
   1.750 +fun type_arg_policy monom_constrs type_enc s =
   1.751 +  let val poly = polymorphism_of_type_enc type_enc in
   1.752 +    if s = type_tag_name then
   1.753 +      if poly = Mangled_Monomorphic then Mangled_Type_Args
   1.754 +      else Explicit_Type_Args false
   1.755 +    else case type_enc of
   1.756 +      Simple_Types (_, Polymorphic, _) => Explicit_Type_Args false
   1.757 +    | Tags (_, All_Types) => No_Type_Args
   1.758 +    | _ =>
   1.759 +      let val level = level_of_type_enc type_enc in
   1.760 +        if level = No_Types orelse s = @{const_name HOL.eq} orelse
   1.761 +           (s = app_op_name andalso level = Const_Arg_Types) then
   1.762 +          No_Type_Args
   1.763 +        else if poly = Mangled_Monomorphic then
   1.764 +          Mangled_Type_Args
   1.765 +        else if member (op =) monom_constrs s andalso
   1.766 +                granularity_of_type_level level = Positively_Naked_Vars then
   1.767 +          No_Type_Args
   1.768 +        else
   1.769 +          Explicit_Type_Args
   1.770 +              (level = All_Types orelse
   1.771 +               granularity_of_type_level level = Ghost_Type_Arg_Vars)
   1.772 +      end
   1.773 +  end
   1.774 +
   1.775 +(* Make atoms for sorted type variables. *)
   1.776 +fun generic_add_sorts_on_type (_, []) = I
   1.777 +  | generic_add_sorts_on_type ((x, i), s :: ss) =
   1.778 +    generic_add_sorts_on_type ((x, i), ss)
   1.779 +    #> (if s = the_single @{sort HOL.type} then
   1.780 +          I
   1.781 +        else if i = ~1 then
   1.782 +          insert (op =) (`make_type_class s, `make_fixed_type_var x)
   1.783 +        else
   1.784 +          insert (op =) (`make_type_class s,
   1.785 +                         (make_schematic_type_var (x, i), x)))
   1.786 +fun add_sorts_on_tfree (TFree (s, S)) = generic_add_sorts_on_type ((s, ~1), S)
   1.787 +  | add_sorts_on_tfree _ = I
   1.788 +fun add_sorts_on_tvar (TVar z) = generic_add_sorts_on_type z
   1.789 +  | add_sorts_on_tvar _ = I
   1.790 +
   1.791 +fun type_class_formula type_enc class arg =
   1.792 +  AAtom (ATerm (class, arg ::
   1.793 +      (case type_enc of
   1.794 +         Simple_Types (First_Order, Polymorphic, _) =>
   1.795 +         if avoid_first_order_ghost_type_vars then [ATerm (TYPE_name, [arg])]
   1.796 +         else []
   1.797 +       | _ => [])))
   1.798 +fun formulas_for_types type_enc add_sorts_on_typ Ts =
   1.799 +  [] |> level_of_type_enc type_enc <> No_Types ? fold add_sorts_on_typ Ts
   1.800 +     |> map (fn (class, name) =>
   1.801 +                type_class_formula type_enc class (ATerm (name, [])))
   1.802 +
   1.803 +fun mk_aconns c phis =
   1.804 +  let val (phis', phi') = split_last phis in
   1.805 +    fold_rev (mk_aconn c) phis' phi'
   1.806 +  end
   1.807 +fun mk_ahorn [] phi = phi
   1.808 +  | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
   1.809 +fun mk_aquant _ [] phi = phi
   1.810 +  | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
   1.811 +    if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
   1.812 +  | mk_aquant q xs phi = AQuant (q, xs, phi)
   1.813 +
   1.814 +fun close_universally add_term_vars phi =
   1.815 +  let
   1.816 +    fun add_formula_vars bounds (AQuant (_, xs, phi)) =
   1.817 +        add_formula_vars (map fst xs @ bounds) phi
   1.818 +      | add_formula_vars bounds (AConn (_, phis)) =
   1.819 +        fold (add_formula_vars bounds) phis
   1.820 +      | add_formula_vars bounds (AAtom tm) = add_term_vars bounds tm
   1.821 +  in mk_aquant AForall (add_formula_vars [] phi []) phi end
   1.822 +
   1.823 +fun add_term_vars bounds (ATerm (name as (s, _), tms)) =
   1.824 +    (if is_tptp_variable s andalso
   1.825 +        not (String.isPrefix tvar_prefix s) andalso
   1.826 +        not (member (op =) bounds name) then
   1.827 +       insert (op =) (name, NONE)
   1.828 +     else
   1.829 +       I)
   1.830 +    #> fold (add_term_vars bounds) tms
   1.831 +  | add_term_vars bounds (AAbs ((name, _), tm)) =
   1.832 +    add_term_vars (name :: bounds) tm
   1.833 +fun close_formula_universally phi = close_universally add_term_vars phi
   1.834 +
   1.835 +fun add_iterm_vars bounds (IApp (tm1, tm2)) =
   1.836 +    fold (add_iterm_vars bounds) [tm1, tm2]
   1.837 +  | add_iterm_vars _ (IConst _) = I
   1.838 +  | add_iterm_vars bounds (IVar (name, T)) =
   1.839 +    not (member (op =) bounds name) ? insert (op =) (name, SOME T)
   1.840 +  | add_iterm_vars bounds (IAbs (_, tm)) = add_iterm_vars bounds tm
   1.841 +fun close_iformula_universally phi = close_universally add_iterm_vars phi
   1.842 +
   1.843 +val fused_infinite_type_name = @{type_name ind} (* any infinite type *)
   1.844 +val fused_infinite_type = Type (fused_infinite_type_name, [])
   1.845 +
   1.846 +fun tvar_name (x as (s, _)) = (make_schematic_type_var x, s)
   1.847 +
   1.848 +fun ho_term_from_typ format type_enc =
   1.849 +  let
   1.850 +    fun term (Type (s, Ts)) =
   1.851 +      ATerm (case (is_type_enc_higher_order type_enc, s) of
   1.852 +               (true, @{type_name bool}) => `I tptp_bool_type
   1.853 +             | (true, @{type_name fun}) => `I tptp_fun_type
   1.854 +             | _ => if s = fused_infinite_type_name andalso
   1.855 +                       is_format_typed format then
   1.856 +                      `I tptp_individual_type
   1.857 +                    else
   1.858 +                      `make_fixed_type_const s,
   1.859 +             map term Ts)
   1.860 +    | term (TFree (s, _)) = ATerm (`make_fixed_type_var s, [])
   1.861 +    | term (TVar (x, _)) = ATerm (tvar_name x, [])
   1.862 +  in term end
   1.863 +
   1.864 +fun ho_term_for_type_arg format type_enc T =
   1.865 +  if T = dummyT then NONE else SOME (ho_term_from_typ format type_enc T)
   1.866 +
   1.867 +(* This shouldn't clash with anything else. *)
   1.868 +val mangled_type_sep = "\000"
   1.869 +
   1.870 +fun generic_mangled_type_name f (ATerm (name, [])) = f name
   1.871 +  | generic_mangled_type_name f (ATerm (name, tys)) =
   1.872 +    f name ^ "(" ^ space_implode "," (map (generic_mangled_type_name f) tys)
   1.873 +    ^ ")"
   1.874 +  | generic_mangled_type_name _ _ = raise Fail "unexpected type abstraction"
   1.875 +
   1.876 +fun mangled_type format type_enc =
   1.877 +  generic_mangled_type_name fst o ho_term_from_typ format type_enc
   1.878 +
   1.879 +fun make_simple_type s =
   1.880 +  if s = tptp_bool_type orelse s = tptp_fun_type orelse
   1.881 +     s = tptp_individual_type then
   1.882 +    s
   1.883 +  else
   1.884 +    simple_type_prefix ^ ascii_of s
   1.885 +
   1.886 +fun ho_type_from_ho_term type_enc pred_sym ary =
   1.887 +  let
   1.888 +    fun to_mangled_atype ty =
   1.889 +      AType ((make_simple_type (generic_mangled_type_name fst ty),
   1.890 +              generic_mangled_type_name snd ty), [])
   1.891 +    fun to_poly_atype (ATerm (name, tys)) = AType (name, map to_poly_atype tys)
   1.892 +      | to_poly_atype _ = raise Fail "unexpected type abstraction"
   1.893 +    val to_atype =
   1.894 +      if polymorphism_of_type_enc type_enc = Polymorphic then to_poly_atype
   1.895 +      else to_mangled_atype
   1.896 +    fun to_afun f1 f2 tys = AFun (f1 (hd tys), f2 (nth tys 1))
   1.897 +    fun to_fo 0 ty = if pred_sym then bool_atype else to_atype ty
   1.898 +      | to_fo ary (ATerm (_, tys)) = to_afun to_atype (to_fo (ary - 1)) tys
   1.899 +      | to_fo _ _ = raise Fail "unexpected type abstraction"
   1.900 +    fun to_ho (ty as ATerm ((s, _), tys)) =
   1.901 +        if s = tptp_fun_type then to_afun to_ho to_ho tys else to_atype ty
   1.902 +      | to_ho _ = raise Fail "unexpected type abstraction"
   1.903 +  in if is_type_enc_higher_order type_enc then to_ho else to_fo ary end
   1.904 +
   1.905 +fun ho_type_from_typ format type_enc pred_sym ary =
   1.906 +  ho_type_from_ho_term type_enc pred_sym ary
   1.907 +  o ho_term_from_typ format type_enc
   1.908 +
   1.909 +fun mangled_const_name format type_enc T_args (s, s') =
   1.910 +  let
   1.911 +    val ty_args = T_args |> map_filter (ho_term_for_type_arg format type_enc)
   1.912 +    fun type_suffix f g =
   1.913 +      fold_rev (curry (op ^) o g o prefix mangled_type_sep
   1.914 +                o generic_mangled_type_name f) ty_args ""
   1.915 +  in (s ^ type_suffix fst ascii_of, s' ^ type_suffix snd I) end
   1.916 +
   1.917 +val parse_mangled_ident =
   1.918 +  Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
   1.919 +
   1.920 +fun parse_mangled_type x =
   1.921 +  (parse_mangled_ident
   1.922 +   -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
   1.923 +                    [] >> ATerm) x
   1.924 +and parse_mangled_types x =
   1.925 +  (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
   1.926 +
   1.927 +fun unmangled_type s =
   1.928 +  s |> suffix ")" |> raw_explode
   1.929 +    |> Scan.finite Symbol.stopper
   1.930 +           (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
   1.931 +                                                quote s)) parse_mangled_type))
   1.932 +    |> fst
   1.933 +
   1.934 +val unmangled_const_name = space_explode mangled_type_sep #> hd
   1.935 +fun unmangled_const s =
   1.936 +  let val ss = space_explode mangled_type_sep s in
   1.937 +    (hd ss, map unmangled_type (tl ss))
   1.938 +  end
   1.939 +
   1.940 +fun introduce_proxies_in_iterm type_enc =
   1.941 +  let
   1.942 +    fun tweak_ho_quant ho_quant T [IAbs _] = IConst (`I ho_quant, T, [])
   1.943 +      | tweak_ho_quant ho_quant (T as Type (_, [p_T as Type (_, [x_T, _]), _]))
   1.944 +                       _ =
   1.945 +        (* Eta-expand "!!" and "??", to work around LEO-II 1.2.8 parser
   1.946 +           limitation. This works in conjuction with special code in
   1.947 +           "ATP_Problem" that uses the syntactic sugar "!" and "?" whenever
   1.948 +           possible. *)
   1.949 +        IAbs ((`I "P", p_T),
   1.950 +              IApp (IConst (`I ho_quant, T, []),
   1.951 +                    IAbs ((`I "X", x_T),
   1.952 +                          IApp (IConst (`I "P", p_T, []),
   1.953 +                                IConst (`I "X", x_T, [])))))
   1.954 +      | tweak_ho_quant _ _ _ = raise Fail "unexpected type for quantifier"
   1.955 +    fun intro top_level args (IApp (tm1, tm2)) =
   1.956 +        IApp (intro top_level (tm2 :: args) tm1, intro false [] tm2)
   1.957 +      | intro top_level args (IConst (name as (s, _), T, T_args)) =
   1.958 +        (case proxify_const s of
   1.959 +           SOME proxy_base =>
   1.960 +           if top_level orelse is_type_enc_higher_order type_enc then
   1.961 +             case (top_level, s) of
   1.962 +               (_, "c_False") => IConst (`I tptp_false, T, [])
   1.963 +             | (_, "c_True") => IConst (`I tptp_true, T, [])
   1.964 +             | (false, "c_Not") => IConst (`I tptp_not, T, [])
   1.965 +             | (false, "c_conj") => IConst (`I tptp_and, T, [])
   1.966 +             | (false, "c_disj") => IConst (`I tptp_or, T, [])
   1.967 +             | (false, "c_implies") => IConst (`I tptp_implies, T, [])
   1.968 +             | (false, "c_All") => tweak_ho_quant tptp_ho_forall T args
   1.969 +             | (false, "c_Ex") => tweak_ho_quant tptp_ho_exists T args
   1.970 +             | (false, s) =>
   1.971 +               if is_tptp_equal s andalso length args = 2 then
   1.972 +                 IConst (`I tptp_equal, T, [])
   1.973 +               else
   1.974 +                 (* Use a proxy even for partially applied THF0 equality,
   1.975 +                    because the LEO-II and Satallax parsers complain about not
   1.976 +                    being able to infer the type of "=". *)
   1.977 +                 IConst (proxy_base |>> prefix const_prefix, T, T_args)
   1.978 +             | _ => IConst (name, T, [])
   1.979 +           else
   1.980 +             IConst (proxy_base |>> prefix const_prefix, T, T_args)
   1.981 +          | NONE => if s = tptp_choice then tweak_ho_quant tptp_choice T args
   1.982 +                    else IConst (name, T, T_args))
   1.983 +      | intro _ _ (IAbs (bound, tm)) = IAbs (bound, intro false [] tm)
   1.984 +      | intro _ _ tm = tm
   1.985 +  in intro true [] end
   1.986 +
   1.987 +fun mangle_type_args_in_iterm format type_enc =
   1.988 +  if polymorphism_of_type_enc type_enc = Mangled_Monomorphic then
   1.989 +    let
   1.990 +      fun mangle (IApp (tm1, tm2)) = IApp (mangle tm1, mangle tm2)
   1.991 +        | mangle (tm as IConst (_, _, [])) = tm
   1.992 +        | mangle (tm as IConst (name as (s, _), T, T_args)) =
   1.993 +          (case unprefix_and_unascii const_prefix s of
   1.994 +             NONE => tm
   1.995 +           | SOME s'' =>
   1.996 +             case type_arg_policy [] type_enc (invert_const s'') of
   1.997 +               Mangled_Type_Args =>
   1.998 +               IConst (mangled_const_name format type_enc T_args name, T, [])
   1.999 +             | _ => tm)
  1.1000 +        | mangle (IAbs (bound, tm)) = IAbs (bound, mangle tm)
  1.1001 +        | mangle tm = tm
  1.1002 +    in mangle end
  1.1003 +  else
  1.1004 +    I
  1.1005 +
  1.1006 +fun chop_fun 0 T = ([], T)
  1.1007 +  | chop_fun n (Type (@{type_name fun}, [dom_T, ran_T])) =
  1.1008 +    chop_fun (n - 1) ran_T |>> cons dom_T
  1.1009 +  | chop_fun _ T = ([], T)
  1.1010 +
  1.1011 +fun filter_const_type_args _ _ _ [] = []
  1.1012 +  | filter_const_type_args thy s ary T_args =
  1.1013 +    let
  1.1014 +      val U = robust_const_type thy s
  1.1015 +      val arg_U_vars = fold Term.add_tvarsT (U |> chop_fun ary |> fst) []
  1.1016 +      val U_args = (s, U) |> robust_const_typargs thy
  1.1017 +    in
  1.1018 +      U_args ~~ T_args
  1.1019 +      |> map (fn (U, T) =>
  1.1020 +                 if member (op =) arg_U_vars (dest_TVar U) then dummyT else T)
  1.1021 +    end
  1.1022 +    handle TYPE _ => T_args
  1.1023 +
  1.1024 +fun filter_type_args_in_iterm thy monom_constrs type_enc =
  1.1025 +  let
  1.1026 +    fun filt ary (IApp (tm1, tm2)) = IApp (filt (ary + 1) tm1, filt 0 tm2)
  1.1027 +      | filt _ (tm as IConst (_, _, [])) = tm
  1.1028 +      | filt ary (IConst (name as (s, _), T, T_args)) =
  1.1029 +        (case unprefix_and_unascii const_prefix s of
  1.1030 +           NONE =>
  1.1031 +           (name,
  1.1032 +            if level_of_type_enc type_enc = No_Types orelse s = tptp_choice then
  1.1033 +              []
  1.1034 +            else
  1.1035 +              T_args)
  1.1036 +         | SOME s'' =>
  1.1037 +           let
  1.1038 +             val s'' = invert_const s''
  1.1039 +             fun filter_T_args false = T_args
  1.1040 +               | filter_T_args true = filter_const_type_args thy s'' ary T_args
  1.1041 +           in
  1.1042 +             case type_arg_policy monom_constrs type_enc s'' of
  1.1043 +               Explicit_Type_Args infer_from_term_args =>
  1.1044 +               (name, filter_T_args infer_from_term_args)
  1.1045 +             | No_Type_Args => (name, [])
  1.1046 +             | Mangled_Type_Args => raise Fail "unexpected (un)mangled symbol"
  1.1047 +           end)
  1.1048 +        |> (fn (name, T_args) => IConst (name, T, T_args))
  1.1049 +      | filt _ (IAbs (bound, tm)) = IAbs (bound, filt 0 tm)
  1.1050 +      | filt _ tm = tm
  1.1051 +  in filt 0 end
  1.1052 +
  1.1053 +fun iformula_from_prop ctxt format type_enc eq_as_iff =
  1.1054 +  let
  1.1055 +    val thy = Proof_Context.theory_of ctxt
  1.1056 +    fun do_term bs t atomic_Ts =
  1.1057 +      iterm_from_term thy format bs (Envir.eta_contract t)
  1.1058 +      |>> (introduce_proxies_in_iterm type_enc
  1.1059 +           #> mangle_type_args_in_iterm format type_enc
  1.1060 +           #> AAtom)
  1.1061 +      ||> union (op =) atomic_Ts
  1.1062 +    fun do_quant bs q pos s T t' =
  1.1063 +      let
  1.1064 +        val s = singleton (Name.variant_list (map fst bs)) s
  1.1065 +        val universal = Option.map (q = AExists ? not) pos
  1.1066 +        val name =
  1.1067 +          s |> `(case universal of
  1.1068 +                   SOME true => make_all_bound_var
  1.1069 +                 | SOME false => make_exist_bound_var
  1.1070 +                 | NONE => make_bound_var)
  1.1071 +      in
  1.1072 +        do_formula ((s, (name, T)) :: bs) pos t'
  1.1073 +        #>> mk_aquant q [(name, SOME T)]
  1.1074 +        ##> union (op =) (atomic_types_of T)
  1.1075 +      end
  1.1076 +    and do_conn bs c pos1 t1 pos2 t2 =
  1.1077 +      do_formula bs pos1 t1 ##>> do_formula bs pos2 t2 #>> uncurry (mk_aconn c)
  1.1078 +    and do_formula bs pos t =
  1.1079 +      case t of
  1.1080 +        @{const Trueprop} $ t1 => do_formula bs pos t1
  1.1081 +      | @{const Not} $ t1 => do_formula bs (Option.map not pos) t1 #>> mk_anot
  1.1082 +      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
  1.1083 +        do_quant bs AForall pos s T t'
  1.1084 +      | (t0 as Const (@{const_name All}, _)) $ t1 =>
  1.1085 +        do_formula bs pos (t0 $ eta_expand (map (snd o snd) bs) t1 1)
  1.1086 +      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
  1.1087 +        do_quant bs AExists pos s T t'
  1.1088 +      | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
  1.1089 +        do_formula bs pos (t0 $ eta_expand (map (snd o snd) bs) t1 1)
  1.1090 +      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd pos t1 pos t2
  1.1091 +      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr pos t1 pos t2
  1.1092 +      | @{const HOL.implies} $ t1 $ t2 =>
  1.1093 +        do_conn bs AImplies (Option.map not pos) t1 pos t2
  1.1094 +      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
  1.1095 +        if eq_as_iff then do_conn bs AIff NONE t1 NONE t2 else do_term bs t
  1.1096 +      | _ => do_term bs t
  1.1097 +  in do_formula [] end
  1.1098 +
  1.1099 +fun presimplify_term ctxt t =
  1.1100 +  t |> exists_Const (member (op =) Meson.presimplified_consts o fst) t
  1.1101 +       ? (Skip_Proof.make_thm (Proof_Context.theory_of ctxt)
  1.1102 +          #> Meson.presimplify
  1.1103 +          #> prop_of)
  1.1104 +
  1.1105 +fun concealed_bound_name j = atp_weak_prefix ^ string_of_int j
  1.1106 +fun conceal_bounds Ts t =
  1.1107 +  subst_bounds (map (Free o apfst concealed_bound_name)
  1.1108 +                    (0 upto length Ts - 1 ~~ Ts), t)
  1.1109 +fun reveal_bounds Ts =
  1.1110 +  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
  1.1111 +                    (0 upto length Ts - 1 ~~ Ts))
  1.1112 +
  1.1113 +fun is_fun_equality (@{const_name HOL.eq},
  1.1114 +                     Type (_, [Type (@{type_name fun}, _), _])) = true
  1.1115 +  | is_fun_equality _ = false
  1.1116 +
  1.1117 +fun extensionalize_term ctxt t =
  1.1118 +  if exists_Const is_fun_equality t then
  1.1119 +    let val thy = Proof_Context.theory_of ctxt in
  1.1120 +      t |> cterm_of thy |> Meson.extensionalize_conv ctxt
  1.1121 +        |> prop_of |> Logic.dest_equals |> snd
  1.1122 +    end
  1.1123 +  else
  1.1124 +    t
  1.1125 +
  1.1126 +fun simple_translate_lambdas do_lambdas ctxt t =
  1.1127 +  let val thy = Proof_Context.theory_of ctxt in
  1.1128 +    if Meson.is_fol_term thy t then
  1.1129 +      t
  1.1130 +    else
  1.1131 +      let
  1.1132 +        fun trans Ts t =
  1.1133 +          case t of
  1.1134 +            @{const Not} $ t1 => @{const Not} $ trans Ts t1
  1.1135 +          | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
  1.1136 +            t0 $ Abs (s, T, trans (T :: Ts) t')
  1.1137 +          | (t0 as Const (@{const_name All}, _)) $ t1 =>
  1.1138 +            trans Ts (t0 $ eta_expand Ts t1 1)
  1.1139 +          | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
  1.1140 +            t0 $ Abs (s, T, trans (T :: Ts) t')
  1.1141 +          | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
  1.1142 +            trans Ts (t0 $ eta_expand Ts t1 1)
  1.1143 +          | (t0 as @{const HOL.conj}) $ t1 $ t2 =>
  1.1144 +            t0 $ trans Ts t1 $ trans Ts t2
  1.1145 +          | (t0 as @{const HOL.disj}) $ t1 $ t2 =>
  1.1146 +            t0 $ trans Ts t1 $ trans Ts t2
  1.1147 +          | (t0 as @{const HOL.implies}) $ t1 $ t2 =>
  1.1148 +            t0 $ trans Ts t1 $ trans Ts t2
  1.1149 +          | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
  1.1150 +              $ t1 $ t2 =>
  1.1151 +            t0 $ trans Ts t1 $ trans Ts t2
  1.1152 +          | _ =>
  1.1153 +            if not (exists_subterm (fn Abs _ => true | _ => false) t) then t
  1.1154 +            else t |> Envir.eta_contract |> do_lambdas ctxt Ts
  1.1155 +        val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
  1.1156 +      in t |> trans [] |> singleton (Variable.export_terms ctxt' ctxt) end
  1.1157 +  end
  1.1158 +
  1.1159 +fun do_cheaply_conceal_lambdas Ts (t1 $ t2) =
  1.1160 +    do_cheaply_conceal_lambdas Ts t1
  1.1161 +    $ do_cheaply_conceal_lambdas Ts t2
  1.1162 +  | do_cheaply_conceal_lambdas Ts (Abs (_, T, t)) =
  1.1163 +    Const (lam_lifted_poly_prefix ^ serial_string (),
  1.1164 +           T --> fastype_of1 (T :: Ts, t))
  1.1165 +  | do_cheaply_conceal_lambdas _ t = t
  1.1166 +
  1.1167 +fun do_introduce_combinators ctxt Ts t =
  1.1168 +  let val thy = Proof_Context.theory_of ctxt in
  1.1169 +    t |> conceal_bounds Ts
  1.1170 +      |> cterm_of thy
  1.1171 +      |> Meson_Clausify.introduce_combinators_in_cterm
  1.1172 +      |> prop_of |> Logic.dest_equals |> snd
  1.1173 +      |> reveal_bounds Ts
  1.1174 +  end
  1.1175 +  (* A type variable of sort "{}" will make abstraction fail. *)
  1.1176 +  handle THM _ => t |> do_cheaply_conceal_lambdas Ts
  1.1177 +val introduce_combinators = simple_translate_lambdas do_introduce_combinators
  1.1178 +
  1.1179 +fun preprocess_abstractions_in_terms trans_lams facts =
  1.1180 +  let
  1.1181 +    val (facts, lambda_ts) =
  1.1182 +      facts |> map (snd o snd) |> trans_lams
  1.1183 +            |>> map2 (fn (name, (kind, _)) => fn t => (name, (kind, t))) facts
  1.1184 +    val lam_facts =
  1.1185 +      map2 (fn t => fn j =>
  1.1186 +               ((lam_fact_prefix ^ Int.toString j, Helper), (Axiom, t)))
  1.1187 +           lambda_ts (1 upto length lambda_ts)
  1.1188 +  in (facts, lam_facts) end
  1.1189 +
  1.1190 +(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
  1.1191 +   same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
  1.1192 +fun freeze_term t =
  1.1193 +  let
  1.1194 +    fun freeze (t $ u) = freeze t $ freeze u
  1.1195 +      | freeze (Abs (s, T, t)) = Abs (s, T, freeze t)
  1.1196 +      | freeze (Var ((s, i), T)) =
  1.1197 +        Free (atp_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
  1.1198 +      | freeze t = t
  1.1199 +  in t |> exists_subterm is_Var t ? freeze end
  1.1200 +
  1.1201 +fun presimp_prop ctxt role t =
  1.1202 +  (let
  1.1203 +     val thy = Proof_Context.theory_of ctxt
  1.1204 +     val t = t |> Envir.beta_eta_contract
  1.1205 +               |> transform_elim_prop
  1.1206 +               |> Object_Logic.atomize_term thy
  1.1207 +     val need_trueprop = (fastype_of t = @{typ bool})
  1.1208 +   in
  1.1209 +     t |> need_trueprop ? HOLogic.mk_Trueprop
  1.1210 +       |> extensionalize_term ctxt
  1.1211 +       |> presimplify_term ctxt
  1.1212 +       |> HOLogic.dest_Trueprop
  1.1213 +   end
  1.1214 +   handle TERM _ => if role = Conjecture then @{term False} else @{term True})
  1.1215 +  |> pair role
  1.1216 +
  1.1217 +fun make_formula ctxt format type_enc eq_as_iff name loc kind t =
  1.1218 +  let
  1.1219 +    val (iformula, atomic_Ts) =
  1.1220 +      iformula_from_prop ctxt format type_enc eq_as_iff
  1.1221 +                         (SOME (kind <> Conjecture)) t []
  1.1222 +      |>> close_iformula_universally
  1.1223 +  in
  1.1224 +    {name = name, locality = loc, kind = kind, iformula = iformula,
  1.1225 +     atomic_types = atomic_Ts}
  1.1226 +  end
  1.1227 +
  1.1228 +fun make_fact ctxt format type_enc eq_as_iff ((name, loc), t) =
  1.1229 +  case t |> make_formula ctxt format type_enc (eq_as_iff andalso format <> CNF)
  1.1230 +                         name loc Axiom of
  1.1231 +    formula as {iformula = AAtom (IConst ((s, _), _, _)), ...} =>
  1.1232 +    if s = tptp_true then NONE else SOME formula
  1.1233 +  | formula => SOME formula
  1.1234 +
  1.1235 +fun s_not_trueprop (@{const Trueprop} $ t) = @{const Trueprop} $ s_not t
  1.1236 +  | s_not_trueprop t =
  1.1237 +    if fastype_of t = @{typ bool} then s_not t else @{prop False} (* too meta *)
  1.1238 +
  1.1239 +fun make_conjecture ctxt format type_enc =
  1.1240 +  map (fn ((name, loc), (kind, t)) =>
  1.1241 +          t |> kind = Conjecture ? s_not_trueprop
  1.1242 +            |> make_formula ctxt format type_enc (format <> CNF) name loc kind)
  1.1243 +
  1.1244 +(** Finite and infinite type inference **)
  1.1245 +
  1.1246 +fun tvar_footprint thy s ary =
  1.1247 +  (case unprefix_and_unascii const_prefix s of
  1.1248 +     SOME s =>
  1.1249 +     s |> invert_const |> robust_const_type thy |> chop_fun ary |> fst
  1.1250 +       |> map (fn T => Term.add_tvarsT T [] |> map fst)
  1.1251 +   | NONE => [])
  1.1252 +  handle TYPE _ => []
  1.1253 +
  1.1254 +fun ghost_type_args thy s ary =
  1.1255 +  if is_tptp_equal s then
  1.1256 +    0 upto ary - 1
  1.1257 +  else
  1.1258 +    let
  1.1259 +      val footprint = tvar_footprint thy s ary
  1.1260 +      val eq = (s = @{const_name HOL.eq})
  1.1261 +      fun ghosts _ [] = []
  1.1262 +        | ghosts seen ((i, tvars) :: args) =
  1.1263 +          ghosts (union (op =) seen tvars) args
  1.1264 +          |> (eq orelse exists (fn tvar => not (member (op =) seen tvar)) tvars)
  1.1265 +             ? cons i
  1.1266 +    in
  1.1267 +      if forall null footprint then
  1.1268 +        []
  1.1269 +      else
  1.1270 +        0 upto length footprint - 1 ~~ footprint
  1.1271 +        |> sort (rev_order o list_ord Term_Ord.indexname_ord o pairself snd)
  1.1272 +        |> ghosts []
  1.1273 +    end
  1.1274 +
  1.1275 +type monotonicity_info =
  1.1276 +  {maybe_finite_Ts : typ list,
  1.1277 +   surely_finite_Ts : typ list,
  1.1278 +   maybe_infinite_Ts : typ list,
  1.1279 +   surely_infinite_Ts : typ list,
  1.1280 +   maybe_nonmono_Ts : typ list}
  1.1281 +
  1.1282 +(* These types witness that the type classes they belong to allow infinite
  1.1283 +   models and hence that any types with these type classes is monotonic. *)
  1.1284 +val known_infinite_types =
  1.1285 +  [@{typ nat}, HOLogic.intT, HOLogic.realT, @{typ "nat => bool"}]
  1.1286 +
  1.1287 +fun is_type_kind_of_surely_infinite ctxt strictness cached_Ts T =
  1.1288 +  strictness <> Strict andalso is_type_surely_infinite ctxt true cached_Ts T
  1.1289 +
  1.1290 +(* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
  1.1291 +   dangerous because their "exhaust" properties can easily lead to unsound ATP
  1.1292 +   proofs. On the other hand, all HOL infinite types can be given the same
  1.1293 +   models in first-order logic (via Löwenheim-Skolem). *)
  1.1294 +
  1.1295 +fun should_encode_type _ (_ : monotonicity_info) All_Types _ = true
  1.1296 +  | should_encode_type ctxt {maybe_finite_Ts, surely_infinite_Ts,
  1.1297 +                             maybe_nonmono_Ts, ...}
  1.1298 +                       (Noninf_Nonmono_Types (strictness, grain)) T =
  1.1299 +    grain = Ghost_Type_Arg_Vars orelse
  1.1300 +    (exists (type_intersect ctxt T) maybe_nonmono_Ts andalso
  1.1301 +     not (exists (type_instance ctxt T) surely_infinite_Ts orelse
  1.1302 +          (not (member (type_equiv ctxt) maybe_finite_Ts T) andalso
  1.1303 +           is_type_kind_of_surely_infinite ctxt strictness surely_infinite_Ts
  1.1304 +                                           T)))
  1.1305 +  | should_encode_type ctxt {surely_finite_Ts, maybe_infinite_Ts,
  1.1306 +                             maybe_nonmono_Ts, ...}
  1.1307 +                       (Fin_Nonmono_Types grain) T =
  1.1308 +    grain = Ghost_Type_Arg_Vars orelse
  1.1309 +    (exists (type_intersect ctxt T) maybe_nonmono_Ts andalso
  1.1310 +     (exists (type_generalization ctxt T) surely_finite_Ts orelse
  1.1311 +      (not (member (type_equiv ctxt) maybe_infinite_Ts T) andalso
  1.1312 +       is_type_surely_finite ctxt T)))
  1.1313 +  | should_encode_type _ _ _ _ = false
  1.1314 +
  1.1315 +fun should_guard_type ctxt mono (Guards (_, level)) should_guard_var T =
  1.1316 +    should_guard_var () andalso should_encode_type ctxt mono level T
  1.1317 +  | should_guard_type _ _ _ _ _ = false
  1.1318 +
  1.1319 +fun is_maybe_universal_var (IConst ((s, _), _, _)) =
  1.1320 +    String.isPrefix bound_var_prefix s orelse
  1.1321 +    String.isPrefix all_bound_var_prefix s
  1.1322 +  | is_maybe_universal_var (IVar _) = true
  1.1323 +  | is_maybe_universal_var _ = false
  1.1324 +
  1.1325 +datatype site =
  1.1326 +  Top_Level of bool option |
  1.1327 +  Eq_Arg of bool option |
  1.1328 +  Elsewhere
  1.1329 +
  1.1330 +fun should_tag_with_type _ _ _ (Top_Level _) _ _ = false
  1.1331 +  | should_tag_with_type ctxt mono (Tags (_, level)) site u T =
  1.1332 +    if granularity_of_type_level level = All_Vars then
  1.1333 +      should_encode_type ctxt mono level T
  1.1334 +    else
  1.1335 +      (case (site, is_maybe_universal_var u) of
  1.1336 +         (Eq_Arg _, true) => should_encode_type ctxt mono level T
  1.1337 +       | _ => false)
  1.1338 +  | should_tag_with_type _ _ _ _ _ _ = false
  1.1339 +
  1.1340 +fun fused_type ctxt mono level =
  1.1341 +  let
  1.1342 +    val should_encode = should_encode_type ctxt mono level
  1.1343 +    fun fuse 0 T = if should_encode T then T else fused_infinite_type
  1.1344 +      | fuse ary (Type (@{type_name fun}, [T1, T2])) =
  1.1345 +        fuse 0 T1 --> fuse (ary - 1) T2
  1.1346 +      | fuse _ _ = raise Fail "expected function type"
  1.1347 +  in fuse end
  1.1348 +
  1.1349 +(** predicators and application operators **)
  1.1350 +
  1.1351 +type sym_info =
  1.1352 +  {pred_sym : bool, min_ary : int, max_ary : int, types : typ list,
  1.1353 +   in_conj : bool}
  1.1354 +
  1.1355 +fun default_sym_tab_entries type_enc =
  1.1356 +  (make_fixed_const NONE @{const_name undefined},
  1.1357 +       {pred_sym = false, min_ary = 0, max_ary = 0, types = [],
  1.1358 +        in_conj = false}) ::
  1.1359 +  ([tptp_false, tptp_true]
  1.1360 +   |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, types = [],
  1.1361 +                  in_conj = false})) @
  1.1362 +  ([tptp_equal, tptp_old_equal]
  1.1363 +   |> map (rpair {pred_sym = true, min_ary = 2, max_ary = 2, types = [],
  1.1364 +                  in_conj = false}))
  1.1365 +  |> not (is_type_enc_higher_order type_enc)
  1.1366 +     ? cons (prefixed_predicator_name,
  1.1367 +             {pred_sym = true, min_ary = 1, max_ary = 1, types = [],
  1.1368 +              in_conj = false})
  1.1369 +
  1.1370 +fun sym_table_for_facts ctxt type_enc explicit_apply conjs facts =
  1.1371 +  let
  1.1372 +    fun consider_var_ary const_T var_T max_ary =
  1.1373 +      let
  1.1374 +        fun iter ary T =
  1.1375 +          if ary = max_ary orelse type_instance ctxt var_T T orelse
  1.1376 +             type_instance ctxt T var_T then
  1.1377 +            ary
  1.1378 +          else
  1.1379 +            iter (ary + 1) (range_type T)
  1.1380 +      in iter 0 const_T end
  1.1381 +    fun add_universal_var T (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
  1.1382 +      if explicit_apply = NONE andalso
  1.1383 +         (can dest_funT T orelse T = @{typ bool}) then
  1.1384 +        let
  1.1385 +          val bool_vars' = bool_vars orelse body_type T = @{typ bool}
  1.1386 +          fun repair_min_ary {pred_sym, min_ary, max_ary, types, in_conj} =
  1.1387 +            {pred_sym = pred_sym andalso not bool_vars',
  1.1388 +             min_ary = fold (fn T' => consider_var_ary T' T) types min_ary,
  1.1389 +             max_ary = max_ary, types = types, in_conj = in_conj}
  1.1390 +          val fun_var_Ts' =
  1.1391 +            fun_var_Ts |> can dest_funT T ? insert_type ctxt I T
  1.1392 +        in
  1.1393 +          if bool_vars' = bool_vars andalso
  1.1394 +             pointer_eq (fun_var_Ts', fun_var_Ts) then
  1.1395 +            accum
  1.1396 +          else
  1.1397 +            ((bool_vars', fun_var_Ts'), Symtab.map (K repair_min_ary) sym_tab)
  1.1398 +        end
  1.1399 +      else
  1.1400 +        accum
  1.1401 +    fun add_fact_syms conj_fact =
  1.1402 +      let
  1.1403 +        fun add_iterm_syms top_level tm
  1.1404 +                           (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
  1.1405 +          let val (head, args) = strip_iterm_comb tm in
  1.1406 +            (case head of
  1.1407 +               IConst ((s, _), T, _) =>
  1.1408 +               if String.isPrefix bound_var_prefix s orelse
  1.1409 +                  String.isPrefix all_bound_var_prefix s then
  1.1410 +                 add_universal_var T accum
  1.1411 +               else if String.isPrefix exist_bound_var_prefix s then
  1.1412 +                 accum
  1.1413 +               else
  1.1414 +                 let val ary = length args in
  1.1415 +                   ((bool_vars, fun_var_Ts),
  1.1416 +                    case Symtab.lookup sym_tab s of
  1.1417 +                      SOME {pred_sym, min_ary, max_ary, types, in_conj} =>
  1.1418 +                      let
  1.1419 +                        val pred_sym =
  1.1420 +                          pred_sym andalso top_level andalso not bool_vars
  1.1421 +                        val types' = types |> insert_type ctxt I T
  1.1422 +                        val in_conj = in_conj orelse conj_fact
  1.1423 +                        val min_ary =
  1.1424 +                          if is_some explicit_apply orelse
  1.1425 +                             pointer_eq (types', types) then
  1.1426 +                            min_ary
  1.1427 +                          else
  1.1428 +                            fold (consider_var_ary T) fun_var_Ts min_ary
  1.1429 +                      in
  1.1430 +                        Symtab.update (s, {pred_sym = pred_sym,
  1.1431 +                                           min_ary = Int.min (ary, min_ary),
  1.1432 +                                           max_ary = Int.max (ary, max_ary),
  1.1433 +                                           types = types', in_conj = in_conj})
  1.1434 +                                      sym_tab
  1.1435 +                      end
  1.1436 +                    | NONE =>
  1.1437 +                      let
  1.1438 +                        val pred_sym = top_level andalso not bool_vars
  1.1439 +                        val min_ary =
  1.1440 +                          case explicit_apply of
  1.1441 +                            SOME true => 0
  1.1442 +                          | SOME false => ary
  1.1443 +                          | NONE => fold (consider_var_ary T) fun_var_Ts ary
  1.1444 +                      in
  1.1445 +                        Symtab.update_new (s,
  1.1446 +                            {pred_sym = pred_sym, min_ary = min_ary,
  1.1447 +                             max_ary = ary, types = [T], in_conj = conj_fact})
  1.1448 +                            sym_tab
  1.1449 +                      end)
  1.1450 +                 end
  1.1451 +             | IVar (_, T) => add_universal_var T accum
  1.1452 +             | IAbs ((_, T), tm) =>
  1.1453 +               accum |> add_universal_var T |> add_iterm_syms false tm
  1.1454 +             | _ => accum)
  1.1455 +            |> fold (add_iterm_syms false) args
  1.1456 +          end
  1.1457 +      in K (add_iterm_syms true) |> formula_fold NONE |> fact_lift end
  1.1458 +  in
  1.1459 +    ((false, []), Symtab.empty)
  1.1460 +    |> fold (add_fact_syms true) conjs
  1.1461 +    |> fold (add_fact_syms false) facts
  1.1462 +    |> snd
  1.1463 +    |> fold Symtab.update (default_sym_tab_entries type_enc)
  1.1464 +  end
  1.1465 +
  1.1466 +fun min_ary_of sym_tab s =
  1.1467 +  case Symtab.lookup sym_tab s of
  1.1468 +    SOME ({min_ary, ...} : sym_info) => min_ary
  1.1469 +  | NONE =>
  1.1470 +    case unprefix_and_unascii const_prefix s of
  1.1471 +      SOME s =>
  1.1472 +      let val s = s |> unmangled_const_name |> invert_const in
  1.1473 +        if s = predicator_name then 1
  1.1474 +        else if s = app_op_name then 2
  1.1475 +        else if s = type_guard_name then 1
  1.1476 +        else 0
  1.1477 +      end
  1.1478 +    | NONE => 0
  1.1479 +
  1.1480 +(* True if the constant ever appears outside of the top-level position in
  1.1481 +   literals, or if it appears with different arities (e.g., because of different
  1.1482 +   type instantiations). If false, the constant always receives all of its
  1.1483 +   arguments and is used as a predicate. *)
  1.1484 +fun is_pred_sym sym_tab s =
  1.1485 +  case Symtab.lookup sym_tab s of
  1.1486 +    SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
  1.1487 +    pred_sym andalso min_ary = max_ary
  1.1488 +  | NONE => false
  1.1489 +
  1.1490 +val app_op = `(make_fixed_const NONE) app_op_name
  1.1491 +val predicator_combconst =
  1.1492 +  IConst (`(make_fixed_const NONE) predicator_name, @{typ "bool => bool"}, [])
  1.1493 +
  1.1494 +fun list_app head args = fold (curry (IApp o swap)) args head
  1.1495 +fun predicator tm = IApp (predicator_combconst, tm)
  1.1496 +
  1.1497 +fun firstorderize_fact thy monom_constrs format type_enc sym_tab =
  1.1498 +  let
  1.1499 +    fun do_app arg head =
  1.1500 +      let
  1.1501 +        val head_T = ityp_of head
  1.1502 +        val (arg_T, res_T) = dest_funT head_T
  1.1503 +        val app =
  1.1504 +          IConst (app_op, head_T --> head_T, [arg_T, res_T])
  1.1505 +          |> mangle_type_args_in_iterm format type_enc
  1.1506 +      in list_app app [head, arg] end
  1.1507 +    fun list_app_ops head args = fold do_app args head
  1.1508 +    fun introduce_app_ops tm =
  1.1509 +      case strip_iterm_comb tm of
  1.1510 +        (head as IConst ((s, _), _, _), args) =>
  1.1511 +        args |> map introduce_app_ops
  1.1512 +             |> chop (min_ary_of sym_tab s)
  1.1513 +             |>> list_app head
  1.1514 +             |-> list_app_ops
  1.1515 +      | (head, args) => list_app_ops head (map introduce_app_ops args)
  1.1516 +    fun introduce_predicators tm =
  1.1517 +      case strip_iterm_comb tm of
  1.1518 +        (IConst ((s, _), _, _), _) =>
  1.1519 +        if is_pred_sym sym_tab s then tm else predicator tm
  1.1520 +      | _ => predicator tm
  1.1521 +    val do_iterm =
  1.1522 +      not (is_type_enc_higher_order type_enc)
  1.1523 +      ? (introduce_app_ops #> introduce_predicators)
  1.1524 +      #> filter_type_args_in_iterm thy monom_constrs type_enc
  1.1525 +  in update_iformula (formula_map do_iterm) end
  1.1526 +
  1.1527 +(** Helper facts **)
  1.1528 +
  1.1529 +val not_ffalse = @{lemma "~ fFalse" by (unfold fFalse_def) fast}
  1.1530 +val ftrue = @{lemma "fTrue" by (unfold fTrue_def) fast}
  1.1531 +
  1.1532 +(* The Boolean indicates that a fairly sound type encoding is needed. *)
  1.1533 +val helper_table =
  1.1534 +  [(("COMBI", false), @{thms Meson.COMBI_def}),
  1.1535 +   (("COMBK", false), @{thms Meson.COMBK_def}),
  1.1536 +   (("COMBB", false), @{thms Meson.COMBB_def}),
  1.1537 +   (("COMBC", false), @{thms Meson.COMBC_def}),
  1.1538 +   (("COMBS", false), @{thms Meson.COMBS_def}),
  1.1539 +   ((predicator_name, false), [not_ffalse, ftrue]),
  1.1540 +   (("fFalse", false), [not_ffalse]),
  1.1541 +   (("fFalse", true), @{thms True_or_False}),
  1.1542 +   (("fTrue", false), [ftrue]),
  1.1543 +   (("fTrue", true), @{thms True_or_False}),
  1.1544 +   (("fNot", false),
  1.1545 +    @{thms fNot_def [THEN Meson.iff_to_disjD, THEN conjunct1]
  1.1546 +           fNot_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
  1.1547 +   (("fconj", false),
  1.1548 +    @{lemma "~ P | ~ Q | fconj P Q" "~ fconj P Q | P" "~ fconj P Q | Q"
  1.1549 +        by (unfold fconj_def) fast+}),
  1.1550 +   (("fdisj", false),
  1.1551 +    @{lemma "~ P | fdisj P Q" "~ Q | fdisj P Q" "~ fdisj P Q | P | Q"
  1.1552 +        by (unfold fdisj_def) fast+}),
  1.1553 +   (("fimplies", false),
  1.1554 +    @{lemma "P | fimplies P Q" "~ Q | fimplies P Q" "~ fimplies P Q | ~ P | Q"
  1.1555 +        by (unfold fimplies_def) fast+}),
  1.1556 +   (("fequal", true),
  1.1557 +    (* This is a lie: Higher-order equality doesn't need a sound type encoding.
  1.1558 +       However, this is done so for backward compatibility: Including the
  1.1559 +       equality helpers by default in Metis breaks a few existing proofs. *)
  1.1560 +    @{thms fequal_def [THEN Meson.iff_to_disjD, THEN conjunct1]
  1.1561 +           fequal_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
  1.1562 +   (* Partial characterization of "fAll" and "fEx". A complete characterization
  1.1563 +      would require the axiom of choice for replay with Metis. *)
  1.1564 +   (("fAll", false), [@{lemma "~ fAll P | P x" by (auto simp: fAll_def)}]),
  1.1565 +   (("fEx", false), [@{lemma "~ P x | fEx P" by (auto simp: fEx_def)}]),
  1.1566 +   (("If", true), @{thms if_True if_False True_or_False})]
  1.1567 +  |> map (apsnd (map zero_var_indexes))
  1.1568 +
  1.1569 +fun atype_of_type_vars (Simple_Types (_, Polymorphic, _)) = SOME atype_of_types
  1.1570 +  | atype_of_type_vars _ = NONE
  1.1571 +
  1.1572 +fun bound_tvars type_enc sorts Ts =
  1.1573 +  (sorts ? mk_ahorn (formulas_for_types type_enc add_sorts_on_tvar Ts))
  1.1574 +  #> mk_aquant AForall
  1.1575 +        (map_filter (fn TVar (x as (s, _), _) =>
  1.1576 +                        SOME ((make_schematic_type_var x, s),
  1.1577 +                              atype_of_type_vars type_enc)
  1.1578 +                      | _ => NONE) Ts)
  1.1579 +
  1.1580 +fun eq_formula type_enc atomic_Ts pred_sym tm1 tm2 =
  1.1581 +  (if pred_sym then AConn (AIff, [AAtom tm1, AAtom tm2])
  1.1582 +   else AAtom (ATerm (`I tptp_equal, [tm1, tm2])))
  1.1583 +  |> close_formula_universally
  1.1584 +  |> bound_tvars type_enc true atomic_Ts
  1.1585 +
  1.1586 +val type_tag = `(make_fixed_const NONE) type_tag_name
  1.1587 +
  1.1588 +fun type_tag_idempotence_fact format type_enc =
  1.1589 +  let
  1.1590 +    fun var s = ATerm (`I s, [])
  1.1591 +    fun tag tm = ATerm (type_tag, [var "A", tm])
  1.1592 +    val tagged_var = tag (var "X")
  1.1593 +  in
  1.1594 +    Formula (type_tag_idempotence_helper_name, Axiom,
  1.1595 +             eq_formula type_enc [] false (tag tagged_var) tagged_var,
  1.1596 +             isabelle_info format simpN, NONE)
  1.1597 +  end
  1.1598 +
  1.1599 +fun should_specialize_helper type_enc t =
  1.1600 +  polymorphism_of_type_enc type_enc <> Polymorphic andalso
  1.1601 +  level_of_type_enc type_enc <> No_Types andalso
  1.1602 +  not (null (Term.hidden_polymorphism t))
  1.1603 +
  1.1604 +fun helper_facts_for_sym ctxt format type_enc (s, {types, ...} : sym_info) =
  1.1605 +  case unprefix_and_unascii const_prefix s of
  1.1606 +    SOME mangled_s =>
  1.1607 +    let
  1.1608 +      val thy = Proof_Context.theory_of ctxt
  1.1609 +      val unmangled_s = mangled_s |> unmangled_const_name
  1.1610 +      fun dub needs_fairly_sound j k =
  1.1611 +        (unmangled_s ^ "_" ^ string_of_int j ^ "_" ^ string_of_int k ^
  1.1612 +         (if mangled_s = unmangled_s then "" else "_" ^ ascii_of mangled_s) ^
  1.1613 +         (if needs_fairly_sound then typed_helper_suffix
  1.1614 +          else untyped_helper_suffix),
  1.1615 +         Helper)
  1.1616 +      fun dub_and_inst needs_fairly_sound (th, j) =
  1.1617 +        let val t = prop_of th in
  1.1618 +          if should_specialize_helper type_enc t then
  1.1619 +            map (fn T => specialize_type thy (invert_const unmangled_s, T) t)
  1.1620 +                types
  1.1621 +          else
  1.1622 +            [t]
  1.1623 +        end
  1.1624 +        |> map (fn (k, t) => (dub needs_fairly_sound j k, t)) o tag_list 1
  1.1625 +      val make_facts = map_filter (make_fact ctxt format type_enc false)
  1.1626 +      val fairly_sound = is_type_enc_fairly_sound type_enc
  1.1627 +    in
  1.1628 +      helper_table
  1.1629 +      |> maps (fn ((helper_s, needs_fairly_sound), ths) =>
  1.1630 +                  if helper_s <> unmangled_s orelse
  1.1631 +                     (needs_fairly_sound andalso not fairly_sound) then
  1.1632 +                    []
  1.1633 +                  else
  1.1634 +                    ths ~~ (1 upto length ths)
  1.1635 +                    |> maps (dub_and_inst needs_fairly_sound)
  1.1636 +                    |> make_facts)
  1.1637 +    end
  1.1638 +  | NONE => []
  1.1639 +fun helper_facts_for_sym_table ctxt format type_enc sym_tab =
  1.1640 +  Symtab.fold_rev (append o helper_facts_for_sym ctxt format type_enc) sym_tab
  1.1641 +                  []
  1.1642 +
  1.1643 +(***************************************************************)
  1.1644 +(* Type Classes Present in the Axiom or Conjecture Clauses     *)
  1.1645 +(***************************************************************)
  1.1646 +
  1.1647 +fun set_insert (x, s) = Symtab.update (x, ()) s
  1.1648 +
  1.1649 +fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
  1.1650 +
  1.1651 +(* Remove this trivial type class (FIXME: similar code elsewhere) *)
  1.1652 +fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset
  1.1653 +
  1.1654 +fun classes_of_terms get_Ts =
  1.1655 +  map (map snd o get_Ts)
  1.1656 +  #> List.foldl add_classes Symtab.empty
  1.1657 +  #> delete_type #> Symtab.keys
  1.1658 +
  1.1659 +val tfree_classes_of_terms = classes_of_terms Misc_Legacy.term_tfrees
  1.1660 +val tvar_classes_of_terms = classes_of_terms Misc_Legacy.term_tvars
  1.1661 +
  1.1662 +fun fold_type_constrs f (Type (s, Ts)) x =
  1.1663 +    fold (fold_type_constrs f) Ts (f (s, x))
  1.1664 +  | fold_type_constrs _ _ x = x
  1.1665 +
  1.1666 +(* Type constructors used to instantiate overloaded constants are the only ones
  1.1667 +   needed. *)
  1.1668 +fun add_type_constrs_in_term thy =
  1.1669 +  let
  1.1670 +    fun add (Const (@{const_name Meson.skolem}, _) $ _) = I
  1.1671 +      | add (t $ u) = add t #> add u
  1.1672 +      | add (Const x) =
  1.1673 +        x |> robust_const_typargs thy |> fold (fold_type_constrs set_insert)
  1.1674 +      | add (Abs (_, _, u)) = add u
  1.1675 +      | add _ = I
  1.1676 +  in add end
  1.1677 +
  1.1678 +fun type_constrs_of_terms thy ts =
  1.1679 +  Symtab.keys (fold (add_type_constrs_in_term thy) ts Symtab.empty)
  1.1680 +
  1.1681 +fun extract_lambda_def (Const (@{const_name HOL.eq}, _) $ t $ u) =
  1.1682 +    let val (head, args) = strip_comb t in
  1.1683 +      (head |> dest_Const |> fst,
  1.1684 +       fold_rev (fn t as Var ((s, _), T) =>
  1.1685 +                    (fn u => Abs (s, T, abstract_over (t, u)))
  1.1686 +                  | _ => raise Fail "expected Var") args u)
  1.1687 +    end
  1.1688 +  | extract_lambda_def _ = raise Fail "malformed lifted lambda"
  1.1689 +
  1.1690 +fun trans_lams_from_string ctxt type_enc lam_trans =
  1.1691 +  if lam_trans = no_lamsN then
  1.1692 +    rpair []
  1.1693 +  else if lam_trans = hide_lamsN then
  1.1694 +    lift_lams ctxt type_enc ##> K []
  1.1695 +  else if lam_trans = lam_liftingN then
  1.1696 +    lift_lams ctxt type_enc
  1.1697 +  else if lam_trans = combinatorsN then
  1.1698 +    map (introduce_combinators ctxt) #> rpair []
  1.1699 +  else if lam_trans = hybrid_lamsN then
  1.1700 +    lift_lams_part_1 ctxt type_enc
  1.1701 +    ##> maps (fn t => [t, introduce_combinators ctxt (intentionalize_def t)])
  1.1702 +    #> lift_lams_part_2
  1.1703 +  else if lam_trans = keep_lamsN then
  1.1704 +    map (Envir.eta_contract) #> rpair []
  1.1705 +  else
  1.1706 +    error ("Unknown lambda translation scheme: " ^ quote lam_trans ^ ".")
  1.1707 +
  1.1708 +fun translate_formulas ctxt format prem_kind type_enc lam_trans presimp hyp_ts
  1.1709 +                       concl_t facts =
  1.1710 +  let
  1.1711 +    val thy = Proof_Context.theory_of ctxt
  1.1712 +    val trans_lams = trans_lams_from_string ctxt type_enc lam_trans
  1.1713 +    val fact_ts = facts |> map snd
  1.1714 +    (* Remove existing facts from the conjecture, as this can dramatically
  1.1715 +       boost an ATP's performance (for some reason). *)
  1.1716 +    val hyp_ts =
  1.1717 +      hyp_ts
  1.1718 +      |> map (fn t => if member (op aconv) fact_ts t then @{prop True} else t)
  1.1719 +    val facts = facts |> map (apsnd (pair Axiom))
  1.1720 +    val conjs =
  1.1721 +      map (pair prem_kind) hyp_ts @ [(Conjecture, s_not_trueprop concl_t)]
  1.1722 +      |> map (apsnd freeze_term)
  1.1723 +      |> map2 (pair o rpair Local o string_of_int) (0 upto length hyp_ts)
  1.1724 +    val ((conjs, facts), lam_facts) =
  1.1725 +      (conjs, facts)
  1.1726 +      |> presimp ? pairself (map (apsnd (uncurry (presimp_prop ctxt))))
  1.1727 +      |> (if lam_trans = no_lamsN then
  1.1728 +            rpair []
  1.1729 +          else
  1.1730 +            op @
  1.1731 +            #> preprocess_abstractions_in_terms trans_lams
  1.1732 +            #>> chop (length conjs))
  1.1733 +    val conjs = conjs |> make_conjecture ctxt format type_enc
  1.1734 +    val (fact_names, facts) =
  1.1735 +      facts
  1.1736 +      |> map_filter (fn (name, (_, t)) =>
  1.1737 +                        make_fact ctxt format type_enc true (name, t)
  1.1738 +                        |> Option.map (pair name))
  1.1739 +      |> ListPair.unzip
  1.1740 +    val lifted = lam_facts |> map (extract_lambda_def o snd o snd)
  1.1741 +    val lam_facts =
  1.1742 +      lam_facts |> map_filter (make_fact ctxt format type_enc true o apsnd snd)
  1.1743 +    val all_ts = concl_t :: hyp_ts @ fact_ts
  1.1744 +    val subs = tfree_classes_of_terms all_ts
  1.1745 +    val supers = tvar_classes_of_terms all_ts
  1.1746 +    val tycons = type_constrs_of_terms thy all_ts
  1.1747 +    val (supers, arity_clauses) =
  1.1748 +      if level_of_type_enc type_enc = No_Types then ([], [])
  1.1749 +      else make_arity_clauses thy tycons supers
  1.1750 +    val class_rel_clauses = make_class_rel_clauses thy subs supers
  1.1751 +  in
  1.1752 +    (fact_names |> map single, union (op =) subs supers, conjs,
  1.1753 +     facts @ lam_facts, class_rel_clauses, arity_clauses, lifted)
  1.1754 +  end
  1.1755 +
  1.1756 +val type_guard = `(make_fixed_const NONE) type_guard_name
  1.1757 +
  1.1758 +fun type_guard_iterm format type_enc T tm =
  1.1759 +  IApp (IConst (type_guard, T --> @{typ bool}, [T])
  1.1760 +        |> mangle_type_args_in_iterm format type_enc, tm)
  1.1761 +
  1.1762 +fun is_var_positively_naked_in_term _ (SOME false) _ accum = accum
  1.1763 +  | is_var_positively_naked_in_term name _ (ATerm ((s, _), tms)) accum =
  1.1764 +    accum orelse (is_tptp_equal s andalso member (op =) tms (ATerm (name, [])))
  1.1765 +  | is_var_positively_naked_in_term _ _ _ _ = true
  1.1766 +
  1.1767 +fun is_var_ghost_type_arg_in_term thy polym_constrs name pos tm accum =
  1.1768 +  is_var_positively_naked_in_term name pos tm accum orelse
  1.1769 +  let
  1.1770 +    val var = ATerm (name, [])
  1.1771 +    fun is_nasty_in_term (ATerm (_, [])) = false
  1.1772 +      | is_nasty_in_term (ATerm ((s, _), tms)) =
  1.1773 +        let
  1.1774 +          val ary = length tms
  1.1775 +          val polym_constr = member (op =) polym_constrs s
  1.1776 +          val ghosts = ghost_type_args thy s ary
  1.1777 +        in
  1.1778 +          exists (fn (j, tm) =>
  1.1779 +                     if polym_constr then
  1.1780 +                       member (op =) ghosts j andalso
  1.1781 +                       (tm = var orelse is_nasty_in_term tm)
  1.1782 +                     else
  1.1783 +                       tm = var andalso member (op =) ghosts j)
  1.1784 +                 (0 upto ary - 1 ~~ tms)
  1.1785 +          orelse (not polym_constr andalso exists is_nasty_in_term tms)
  1.1786 +        end
  1.1787 +      | is_nasty_in_term _ = true
  1.1788 +  in is_nasty_in_term tm end
  1.1789 +
  1.1790 +fun should_guard_var_in_formula thy polym_constrs level pos phi (SOME true)
  1.1791 +                                name =
  1.1792 +    (case granularity_of_type_level level of
  1.1793 +       All_Vars => true
  1.1794 +     | Positively_Naked_Vars =>
  1.1795 +       formula_fold pos (is_var_positively_naked_in_term name) phi false
  1.1796 +     | Ghost_Type_Arg_Vars =>
  1.1797 +       formula_fold pos (is_var_ghost_type_arg_in_term thy polym_constrs name)
  1.1798 +                    phi false)
  1.1799 +  | should_guard_var_in_formula _ _ _ _ _ _ _ = true
  1.1800 +
  1.1801 +fun always_guard_var_in_formula _ _ _ _ _ _ _ = true
  1.1802 +
  1.1803 +fun should_generate_tag_bound_decl _ _ _ (SOME true) _ = false
  1.1804 +  | should_generate_tag_bound_decl ctxt mono (Tags (_, level)) _ T =
  1.1805 +    granularity_of_type_level level <> All_Vars andalso
  1.1806 +    should_encode_type ctxt mono level T
  1.1807 +  | should_generate_tag_bound_decl _ _ _ _ _ = false
  1.1808 +
  1.1809 +fun mk_aterm format type_enc name T_args args =
  1.1810 +  ATerm (name, map_filter (ho_term_for_type_arg format type_enc) T_args @ args)
  1.1811 +
  1.1812 +fun tag_with_type ctxt format mono type_enc pos T tm =
  1.1813 +  IConst (type_tag, T --> T, [T])
  1.1814 +  |> mangle_type_args_in_iterm format type_enc
  1.1815 +  |> ho_term_from_iterm ctxt format mono type_enc pos
  1.1816 +  |> (fn ATerm (s, tms) => ATerm (s, tms @ [tm])
  1.1817 +       | _ => raise Fail "unexpected lambda-abstraction")
  1.1818 +and ho_term_from_iterm ctxt format mono type_enc =
  1.1819 +  let
  1.1820 +    fun term site u =
  1.1821 +      let
  1.1822 +        val (head, args) = strip_iterm_comb u
  1.1823 +        val pos =
  1.1824 +          case site of
  1.1825 +            Top_Level pos => pos
  1.1826 +          | Eq_Arg pos => pos
  1.1827 +          | _ => NONE
  1.1828 +        val t =
  1.1829 +          case head of
  1.1830 +            IConst (name as (s, _), _, T_args) =>
  1.1831 +            let
  1.1832 +              val arg_site = if is_tptp_equal s then Eq_Arg pos else Elsewhere
  1.1833 +            in
  1.1834 +              map (term arg_site) args |> mk_aterm format type_enc name T_args
  1.1835 +            end
  1.1836 +          | IVar (name, _) =>
  1.1837 +            map (term Elsewhere) args |> mk_aterm format type_enc name []
  1.1838 +          | IAbs ((name, T), tm) =>
  1.1839 +            AAbs ((name, ho_type_from_typ format type_enc true 0 T),
  1.1840 +                  term Elsewhere tm)
  1.1841 +          | IApp _ => raise Fail "impossible \"IApp\""
  1.1842 +        val T = ityp_of u
  1.1843 +      in
  1.1844 +        if should_tag_with_type ctxt mono type_enc site u T then
  1.1845 +          tag_with_type ctxt format mono type_enc pos T t
  1.1846 +        else
  1.1847 +          t
  1.1848 +      end
  1.1849 +  in term o Top_Level end
  1.1850 +and formula_from_iformula ctxt polym_constrs format mono type_enc
  1.1851 +                          should_guard_var =
  1.1852 +  let
  1.1853 +    val thy = Proof_Context.theory_of ctxt
  1.1854 +    val level = level_of_type_enc type_enc
  1.1855 +    val do_term = ho_term_from_iterm ctxt format mono type_enc
  1.1856 +    val do_bound_type =
  1.1857 +      case type_enc of
  1.1858 +        Simple_Types _ => fused_type ctxt mono level 0
  1.1859 +        #> ho_type_from_typ format type_enc false 0 #> SOME
  1.1860 +      | _ => K NONE
  1.1861 +    fun do_out_of_bound_type pos phi universal (name, T) =
  1.1862 +      if should_guard_type ctxt mono type_enc
  1.1863 +             (fn () => should_guard_var thy polym_constrs level pos phi
  1.1864 +                                        universal name) T then
  1.1865 +        IVar (name, T)
  1.1866 +        |> type_guard_iterm format type_enc T
  1.1867 +        |> do_term pos |> AAtom |> SOME
  1.1868 +      else if should_generate_tag_bound_decl ctxt mono type_enc universal T then
  1.1869 +        let
  1.1870 +          val var = ATerm (name, [])
  1.1871 +          val tagged_var = tag_with_type ctxt format mono type_enc pos T var
  1.1872 +        in SOME (AAtom (ATerm (`I tptp_equal, [tagged_var, var]))) end
  1.1873 +      else
  1.1874 +        NONE
  1.1875 +    fun do_formula pos (AQuant (q, xs, phi)) =
  1.1876 +        let
  1.1877 +          val phi = phi |> do_formula pos
  1.1878 +          val universal = Option.map (q = AExists ? not) pos
  1.1879 +        in
  1.1880 +          AQuant (q, xs |> map (apsnd (fn NONE => NONE
  1.1881 +                                        | SOME T => do_bound_type T)),
  1.1882 +                  (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
  1.1883 +                      (map_filter
  1.1884 +                           (fn (_, NONE) => NONE
  1.1885 +                             | (s, SOME T) =>
  1.1886 +                               do_out_of_bound_type pos phi universal (s, T))
  1.1887 +                           xs)
  1.1888 +                      phi)
  1.1889 +        end
  1.1890 +      | do_formula pos (AConn conn) = aconn_map pos do_formula conn
  1.1891 +      | do_formula pos (AAtom tm) = AAtom (do_term pos tm)
  1.1892 +  in do_formula end
  1.1893 +
  1.1894 +(* Each fact is given a unique fact number to avoid name clashes (e.g., because
  1.1895 +   of monomorphization). The TPTP explicitly forbids name clashes, and some of
  1.1896 +   the remote provers might care. *)
  1.1897 +fun formula_line_for_fact ctxt polym_constrs format prefix encode freshen pos
  1.1898 +        mono type_enc (j, {name, locality, kind, iformula, atomic_types}) =
  1.1899 +  (prefix ^ (if freshen then string_of_int j ^ "_" else "") ^ encode name, kind,
  1.1900 +   iformula
  1.1901 +   |> formula_from_iformula ctxt polym_constrs format mono type_enc
  1.1902 +          should_guard_var_in_formula (if pos then SOME true else NONE)
  1.1903 +   |> close_formula_universally
  1.1904 +   |> bound_tvars type_enc true atomic_types,
  1.1905 +   NONE,
  1.1906 +   case locality of
  1.1907 +     Intro => isabelle_info format introN
  1.1908 +   | Elim => isabelle_info format elimN
  1.1909 +   | Simp => isabelle_info format simpN
  1.1910 +   | _ => NONE)
  1.1911 +  |> Formula
  1.1912 +
  1.1913 +fun formula_line_for_class_rel_clause format type_enc
  1.1914 +        ({name, subclass, superclass, ...} : class_rel_clause) =
  1.1915 +  let val ty_arg = ATerm (tvar_a_name, []) in
  1.1916 +    Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
  1.1917 +             AConn (AImplies,
  1.1918 +                    [type_class_formula type_enc subclass ty_arg,
  1.1919 +                     type_class_formula type_enc superclass ty_arg])
  1.1920 +             |> mk_aquant AForall
  1.1921 +                          [(tvar_a_name, atype_of_type_vars type_enc)],
  1.1922 +             isabelle_info format introN, NONE)
  1.1923 +  end
  1.1924 +
  1.1925 +fun formula_from_arity_atom type_enc (class, t, args) =
  1.1926 +  ATerm (t, map (fn arg => ATerm (arg, [])) args)
  1.1927 +  |> type_class_formula type_enc class
  1.1928 +
  1.1929 +fun formula_line_for_arity_clause format type_enc
  1.1930 +        ({name, prem_atoms, concl_atom} : arity_clause) =
  1.1931 +  Formula (arity_clause_prefix ^ name, Axiom,
  1.1932 +           mk_ahorn (map (formula_from_arity_atom type_enc) prem_atoms)
  1.1933 +                    (formula_from_arity_atom type_enc concl_atom)
  1.1934 +           |> mk_aquant AForall
  1.1935 +                  (map (rpair (atype_of_type_vars type_enc)) (#3 concl_atom)),
  1.1936 +           isabelle_info format introN, NONE)
  1.1937 +
  1.1938 +fun formula_line_for_conjecture ctxt polym_constrs format mono type_enc
  1.1939 +        ({name, kind, iformula, atomic_types, ...} : translated_formula) =
  1.1940 +  Formula (conjecture_prefix ^ name, kind,
  1.1941 +           iformula
  1.1942 +           |> formula_from_iformula ctxt polym_constrs format mono type_enc
  1.1943 +                  should_guard_var_in_formula (SOME false)
  1.1944 +           |> close_formula_universally
  1.1945 +           |> bound_tvars type_enc true atomic_types, NONE, NONE)
  1.1946 +
  1.1947 +fun formula_line_for_free_type j phi =
  1.1948 +  Formula (tfree_clause_prefix ^ string_of_int j, Hypothesis, phi, NONE, NONE)
  1.1949 +fun formula_lines_for_free_types type_enc (facts : translated_formula list) =
  1.1950 +  let
  1.1951 +    val phis =
  1.1952 +      fold (union (op =)) (map #atomic_types facts) []
  1.1953 +      |> formulas_for_types type_enc add_sorts_on_tfree
  1.1954 +  in map2 formula_line_for_free_type (0 upto length phis - 1) phis end
  1.1955 +
  1.1956 +(** Symbol declarations **)
  1.1957 +
  1.1958 +fun decl_line_for_class order s =
  1.1959 +  let val name as (s, _) = `make_type_class s in
  1.1960 +    Decl (sym_decl_prefix ^ s, name,
  1.1961 +          if order = First_Order then
  1.1962 +            ATyAbs ([tvar_a_name],
  1.1963 +                    if avoid_first_order_ghost_type_vars then
  1.1964 +                      AFun (a_itself_atype, bool_atype)
  1.1965 +                    else
  1.1966 +                      bool_atype)
  1.1967 +          else
  1.1968 +            AFun (atype_of_types, bool_atype))
  1.1969 +  end
  1.1970 +
  1.1971 +fun decl_lines_for_classes type_enc classes =
  1.1972 +  case type_enc of
  1.1973 +    Simple_Types (order, Polymorphic, _) =>
  1.1974 +    map (decl_line_for_class order) classes
  1.1975 +  | _ => []
  1.1976 +
  1.1977 +fun sym_decl_table_for_facts ctxt format type_enc sym_tab (conjs, facts) =
  1.1978 +  let
  1.1979 +    fun add_iterm_syms tm =
  1.1980 +      let val (head, args) = strip_iterm_comb tm in
  1.1981 +        (case head of
  1.1982 +           IConst ((s, s'), T, T_args) =>
  1.1983 +           let
  1.1984 +             val (pred_sym, in_conj) =
  1.1985 +               case Symtab.lookup sym_tab s of
  1.1986 +                 SOME ({pred_sym, in_conj, ...} : sym_info) =>
  1.1987 +                 (pred_sym, in_conj)
  1.1988 +               | NONE => (false, false)
  1.1989 +             val decl_sym =
  1.1990 +               (case type_enc of
  1.1991 +                  Guards _ => not pred_sym
  1.1992 +                | _ => true) andalso
  1.1993 +               is_tptp_user_symbol s
  1.1994 +           in
  1.1995 +             if decl_sym then
  1.1996 +               Symtab.map_default (s, [])
  1.1997 +                   (insert_type ctxt #3 (s', T_args, T, pred_sym, length args,
  1.1998 +                                         in_conj))
  1.1999 +             else
  1.2000 +               I
  1.2001 +           end
  1.2002 +         | IAbs (_, tm) => add_iterm_syms tm
  1.2003 +         | _ => I)
  1.2004 +        #> fold add_iterm_syms args
  1.2005 +      end
  1.2006 +    val add_fact_syms = K add_iterm_syms |> formula_fold NONE |> fact_lift
  1.2007 +    fun add_formula_var_types (AQuant (_, xs, phi)) =
  1.2008 +        fold (fn (_, SOME T) => insert_type ctxt I T | _ => I) xs
  1.2009 +        #> add_formula_var_types phi
  1.2010 +      | add_formula_var_types (AConn (_, phis)) =
  1.2011 +        fold add_formula_var_types phis
  1.2012 +      | add_formula_var_types _ = I
  1.2013 +    fun var_types () =
  1.2014 +      if polymorphism_of_type_enc type_enc = Polymorphic then [tvar_a]
  1.2015 +      else fold (fact_lift add_formula_var_types) (conjs @ facts) []
  1.2016 +    fun add_undefined_const T =
  1.2017 +      let
  1.2018 +        val (s, s') =
  1.2019 +          `(make_fixed_const NONE) @{const_name undefined}
  1.2020 +          |> (case type_arg_policy [] type_enc @{const_name undefined} of
  1.2021 +                Mangled_Type_Args => mangled_const_name format type_enc [T]
  1.2022 +              | _ => I)
  1.2023 +      in
  1.2024 +        Symtab.map_default (s, [])
  1.2025 +                           (insert_type ctxt #3 (s', [T], T, false, 0, false))
  1.2026 +      end
  1.2027 +    fun add_TYPE_const () =
  1.2028 +      let val (s, s') = TYPE_name in
  1.2029 +        Symtab.map_default (s, [])
  1.2030 +            (insert_type ctxt #3
  1.2031 +                         (s', [tvar_a], @{typ "'a itself"}, false, 0, false))
  1.2032 +      end
  1.2033 +  in
  1.2034 +    Symtab.empty
  1.2035 +    |> is_type_enc_fairly_sound type_enc
  1.2036 +       ? (fold (fold add_fact_syms) [conjs, facts]
  1.2037 +          #> (case type_enc of
  1.2038 +                Simple_Types (First_Order, Polymorphic, _) =>
  1.2039 +                if avoid_first_order_ghost_type_vars then add_TYPE_const ()
  1.2040 +                else I
  1.2041 +              | Simple_Types _ => I
  1.2042 +              | _ => fold add_undefined_const (var_types ())))
  1.2043 +  end
  1.2044 +
  1.2045 +(* We add "bool" in case the helper "True_or_False" is included later. *)
  1.2046 +fun default_mono level =
  1.2047 +  {maybe_finite_Ts = [@{typ bool}],
  1.2048 +   surely_finite_Ts = [@{typ bool}],
  1.2049 +   maybe_infinite_Ts = known_infinite_types,
  1.2050 +   surely_infinite_Ts =
  1.2051 +     case level of
  1.2052 +       Noninf_Nonmono_Types (Strict, _) => []
  1.2053 +     | _ => known_infinite_types,
  1.2054 +   maybe_nonmono_Ts = [@{typ bool}]}
  1.2055 +
  1.2056 +(* This inference is described in section 2.3 of Claessen et al.'s "Sorting it
  1.2057 +   out with monotonicity" paper presented at CADE 2011. *)
  1.2058 +fun add_iterm_mononotonicity_info _ _ (SOME false) _ mono = mono
  1.2059 +  | add_iterm_mononotonicity_info ctxt level _
  1.2060 +        (IApp (IApp (IConst ((s, _), Type (_, [T, _]), _), tm1), tm2))
  1.2061 +        (mono as {maybe_finite_Ts, surely_finite_Ts, maybe_infinite_Ts,
  1.2062 +                  surely_infinite_Ts, maybe_nonmono_Ts}) =
  1.2063 +    if is_tptp_equal s andalso exists is_maybe_universal_var [tm1, tm2] then
  1.2064 +      case level of
  1.2065 +        Noninf_Nonmono_Types (strictness, _) =>
  1.2066 +        if exists (type_instance ctxt T) surely_infinite_Ts orelse
  1.2067 +           member (type_equiv ctxt) maybe_finite_Ts T then
  1.2068 +          mono
  1.2069 +        else if is_type_kind_of_surely_infinite ctxt strictness
  1.2070 +                                                surely_infinite_Ts T then
  1.2071 +          {maybe_finite_Ts = maybe_finite_Ts,
  1.2072 +           surely_finite_Ts = surely_finite_Ts,
  1.2073 +           maybe_infinite_Ts = maybe_infinite_Ts,
  1.2074 +           surely_infinite_Ts = surely_infinite_Ts |> insert_type ctxt I T,
  1.2075 +           maybe_nonmono_Ts = maybe_nonmono_Ts}
  1.2076 +        else
  1.2077 +          {maybe_finite_Ts = maybe_finite_Ts |> insert (type_equiv ctxt) T,
  1.2078 +           surely_finite_Ts = surely_finite_Ts,
  1.2079 +           maybe_infinite_Ts = maybe_infinite_Ts,
  1.2080 +           surely_infinite_Ts = surely_infinite_Ts,
  1.2081 +           maybe_nonmono_Ts = maybe_nonmono_Ts |> insert_type ctxt I T}
  1.2082 +      | Fin_Nonmono_Types _ =>
  1.2083 +        if exists (type_instance ctxt T) surely_finite_Ts orelse
  1.2084 +           member (type_equiv ctxt) maybe_infinite_Ts T then
  1.2085 +          mono
  1.2086 +        else if is_type_surely_finite ctxt T then
  1.2087 +          {maybe_finite_Ts = maybe_finite_Ts,
  1.2088 +           surely_finite_Ts = surely_finite_Ts |> insert_type ctxt I T,
  1.2089 +           maybe_infinite_Ts = maybe_infinite_Ts,
  1.2090 +           surely_infinite_Ts = surely_infinite_Ts,
  1.2091 +           maybe_nonmono_Ts = maybe_nonmono_Ts |> insert_type ctxt I T}
  1.2092 +        else
  1.2093 +          {maybe_finite_Ts = maybe_finite_Ts,
  1.2094 +           surely_finite_Ts = surely_finite_Ts,
  1.2095 +           maybe_infinite_Ts = maybe_infinite_Ts |> insert (type_equiv ctxt) T,
  1.2096 +           surely_infinite_Ts = surely_infinite_Ts,
  1.2097 +           maybe_nonmono_Ts = maybe_nonmono_Ts}
  1.2098 +      | _ => mono
  1.2099 +    else
  1.2100 +      mono
  1.2101 +  | add_iterm_mononotonicity_info _ _ _ _ mono = mono
  1.2102 +fun add_fact_mononotonicity_info ctxt level
  1.2103 +        ({kind, iformula, ...} : translated_formula) =
  1.2104 +  formula_fold (SOME (kind <> Conjecture))
  1.2105 +               (add_iterm_mononotonicity_info ctxt level) iformula
  1.2106 +fun mononotonicity_info_for_facts ctxt type_enc facts =
  1.2107 +  let val level = level_of_type_enc type_enc in
  1.2108 +    default_mono level
  1.2109 +    |> is_type_level_monotonicity_based level
  1.2110 +       ? fold (add_fact_mononotonicity_info ctxt level) facts
  1.2111 +  end
  1.2112 +
  1.2113 +fun add_iformula_monotonic_types ctxt mono type_enc =
  1.2114 +  let
  1.2115 +    val level = level_of_type_enc type_enc
  1.2116 +    val should_encode = should_encode_type ctxt mono level
  1.2117 +    fun add_type T = not (should_encode T) ? insert_type ctxt I T
  1.2118 +    fun add_args (IApp (tm1, tm2)) = add_args tm1 #> add_term tm2
  1.2119 +      | add_args _ = I
  1.2120 +    and add_term tm = add_type (ityp_of tm) #> add_args tm
  1.2121 +  in formula_fold NONE (K add_term) end
  1.2122 +fun add_fact_monotonic_types ctxt mono type_enc =
  1.2123 +  add_iformula_monotonic_types ctxt mono type_enc |> fact_lift
  1.2124 +fun monotonic_types_for_facts ctxt mono type_enc facts =
  1.2125 +  let val level = level_of_type_enc type_enc in
  1.2126 +    [] |> (polymorphism_of_type_enc type_enc = Polymorphic andalso
  1.2127 +           is_type_level_monotonicity_based level andalso
  1.2128 +           granularity_of_type_level level <> Ghost_Type_Arg_Vars)
  1.2129 +          ? fold (add_fact_monotonic_types ctxt mono type_enc) facts
  1.2130 +  end
  1.2131 +
  1.2132 +fun formula_line_for_guards_mono_type ctxt format mono type_enc T =
  1.2133 +  Formula (guards_sym_formula_prefix ^
  1.2134 +           ascii_of (mangled_type format type_enc T),
  1.2135 +           Axiom,
  1.2136 +           IConst (`make_bound_var "X", T, [])
  1.2137 +           |> type_guard_iterm format type_enc T
  1.2138 +           |> AAtom
  1.2139 +           |> formula_from_iformula ctxt [] format mono type_enc
  1.2140 +                                    always_guard_var_in_formula (SOME true)
  1.2141 +           |> close_formula_universally
  1.2142 +           |> bound_tvars type_enc true (atomic_types_of T),
  1.2143 +           isabelle_info format introN, NONE)
  1.2144 +
  1.2145 +fun formula_line_for_tags_mono_type ctxt format mono type_enc T =
  1.2146 +  let val x_var = ATerm (`make_bound_var "X", []) in
  1.2147 +    Formula (tags_sym_formula_prefix ^
  1.2148 +             ascii_of (mangled_type format type_enc T),
  1.2149 +             Axiom,
  1.2150 +             eq_formula type_enc (atomic_types_of T) false
  1.2151 +                  (tag_with_type ctxt format mono type_enc NONE T x_var) x_var,
  1.2152 +             isabelle_info format simpN, NONE)
  1.2153 +  end
  1.2154 +
  1.2155 +fun problem_lines_for_mono_types ctxt format mono type_enc Ts =
  1.2156 +  case type_enc of
  1.2157 +    Simple_Types _ => []
  1.2158 +  | Guards _ =>
  1.2159 +    map (formula_line_for_guards_mono_type ctxt format mono type_enc) Ts
  1.2160 +  | Tags _ => map (formula_line_for_tags_mono_type ctxt format mono type_enc) Ts
  1.2161 +
  1.2162 +fun decl_line_for_sym ctxt format mono type_enc s
  1.2163 +                      (s', T_args, T, pred_sym, ary, _) =
  1.2164 +  let
  1.2165 +    val thy = Proof_Context.theory_of ctxt
  1.2166 +    val (T, T_args) =
  1.2167 +      if null T_args then
  1.2168 +        (T, [])
  1.2169 +      else case unprefix_and_unascii const_prefix s of
  1.2170 +        SOME s' =>
  1.2171 +        let
  1.2172 +          val s' = s' |> invert_const
  1.2173 +          val T = s' |> robust_const_type thy
  1.2174 +        in (T, robust_const_typargs thy (s', T)) end
  1.2175 +      | NONE => raise Fail "unexpected type arguments"
  1.2176 +  in
  1.2177 +    Decl (sym_decl_prefix ^ s, (s, s'),
  1.2178 +          T |> fused_type ctxt mono (level_of_type_enc type_enc) ary
  1.2179 +            |> ho_type_from_typ format type_enc pred_sym ary
  1.2180 +            |> not (null T_args)
  1.2181 +               ? curry ATyAbs (map (tvar_name o fst o dest_TVar) T_args))
  1.2182 +  end
  1.2183 +
  1.2184 +fun formula_line_for_guards_sym_decl ctxt format conj_sym_kind mono type_enc n s
  1.2185 +                                     j (s', T_args, T, _, ary, in_conj) =
  1.2186 +  let
  1.2187 +    val thy = Proof_Context.theory_of ctxt
  1.2188 +    val (kind, maybe_negate) =
  1.2189 +      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
  1.2190 +      else (Axiom, I)
  1.2191 +    val (arg_Ts, res_T) = chop_fun ary T
  1.2192 +    val bound_names = 1 upto ary |> map (`I o make_bound_var o string_of_int)
  1.2193 +    val bounds =
  1.2194 +      bound_names ~~ arg_Ts |> map (fn (name, T) => IConst (name, T, []))
  1.2195 +    val bound_Ts =
  1.2196 +      if exists (curry (op =) dummyT) T_args then
  1.2197 +        case level_of_type_enc type_enc of
  1.2198 +          All_Types => map SOME arg_Ts
  1.2199 +        | level =>
  1.2200 +          if granularity_of_type_level level = Ghost_Type_Arg_Vars then
  1.2201 +            let val ghosts = ghost_type_args thy s ary in
  1.2202 +              map2 (fn j => if member (op =) ghosts j then SOME else K NONE)
  1.2203 +                   (0 upto ary - 1) arg_Ts
  1.2204 +            end
  1.2205 +          else
  1.2206 +            replicate ary NONE
  1.2207 +      else
  1.2208 +        replicate ary NONE
  1.2209 +  in
  1.2210 +    Formula (guards_sym_formula_prefix ^ s ^
  1.2211 +             (if n > 1 then "_" ^ string_of_int j else ""), kind,
  1.2212 +             IConst ((s, s'), T, T_args)
  1.2213 +             |> fold (curry (IApp o swap)) bounds
  1.2214 +             |> type_guard_iterm format type_enc res_T
  1.2215 +             |> AAtom |> mk_aquant AForall (bound_names ~~ bound_Ts)
  1.2216 +             |> formula_from_iformula ctxt [] format mono type_enc
  1.2217 +                                      always_guard_var_in_formula (SOME true)
  1.2218 +             |> close_formula_universally
  1.2219 +             |> bound_tvars type_enc (n > 1) (atomic_types_of T)
  1.2220 +             |> maybe_negate,
  1.2221 +             isabelle_info format introN, NONE)
  1.2222 +  end
  1.2223 +
  1.2224 +fun formula_lines_for_tags_sym_decl ctxt format conj_sym_kind mono type_enc n s
  1.2225 +        (j, (s', T_args, T, pred_sym, ary, in_conj)) =
  1.2226 +  let
  1.2227 +    val thy = Proof_Context.theory_of ctxt
  1.2228 +    val level = level_of_type_enc type_enc
  1.2229 +    val grain = granularity_of_type_level level
  1.2230 +    val ident_base =
  1.2231 +      tags_sym_formula_prefix ^ s ^
  1.2232 +      (if n > 1 then "_" ^ string_of_int j else "")
  1.2233 +    val (kind, maybe_negate) =
  1.2234 +      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
  1.2235 +      else (Axiom, I)
  1.2236 +    val (arg_Ts, res_T) = chop_fun ary T
  1.2237 +    val bound_names = 1 upto ary |> map (`I o make_bound_var o string_of_int)
  1.2238 +    val bounds = bound_names |> map (fn name => ATerm (name, []))
  1.2239 +    val cst = mk_aterm format type_enc (s, s') T_args
  1.2240 +    val eq = maybe_negate oo eq_formula type_enc (atomic_types_of T) pred_sym
  1.2241 +    val should_encode = should_encode_type ctxt mono level
  1.2242 +    val tag_with = tag_with_type ctxt format mono type_enc NONE
  1.2243 +    val add_formula_for_res =
  1.2244 +      if should_encode res_T then
  1.2245 +        let
  1.2246 +          val tagged_bounds =
  1.2247 +            if grain = Ghost_Type_Arg_Vars then
  1.2248 +              let val ghosts = ghost_type_args thy s ary in
  1.2249 +                map2 (fn (j, arg_T) => member (op =) ghosts j ? tag_with arg_T)
  1.2250 +                     (0 upto ary - 1 ~~ arg_Ts) bounds
  1.2251 +              end
  1.2252 +            else
  1.2253 +              bounds
  1.2254 +        in
  1.2255 +          cons (Formula (ident_base ^ "_res", kind,
  1.2256 +                         eq (tag_with res_T (cst bounds)) (cst tagged_bounds),
  1.2257 +                         isabelle_info format simpN, NONE))
  1.2258 +        end
  1.2259 +      else
  1.2260 +        I
  1.2261 +    fun add_formula_for_arg k =
  1.2262 +      let val arg_T = nth arg_Ts k in
  1.2263 +        if should_encode arg_T then
  1.2264 +          case chop k bounds of
  1.2265 +            (bounds1, bound :: bounds2) =>
  1.2266 +            cons (Formula (ident_base ^ "_arg" ^ string_of_int (k + 1), kind,
  1.2267 +                           eq (cst (bounds1 @ tag_with arg_T bound :: bounds2))
  1.2268 +                              (cst bounds),
  1.2269 +                           isabelle_info format simpN, NONE))
  1.2270 +          | _ => raise Fail "expected nonempty tail"
  1.2271 +        else
  1.2272 +          I
  1.2273 +      end
  1.2274 +  in
  1.2275 +    [] |> not pred_sym ? add_formula_for_res
  1.2276 +       |> (Config.get ctxt type_tag_arguments andalso
  1.2277 +           grain = Positively_Naked_Vars)
  1.2278 +          ? fold add_formula_for_arg (ary - 1 downto 0)
  1.2279 +  end
  1.2280 +
  1.2281 +fun result_type_of_decl (_, _, T, _, ary, _) = chop_fun ary T |> snd
  1.2282 +
  1.2283 +fun rationalize_decls ctxt (decls as decl :: (decls' as _ :: _)) =
  1.2284 +    let
  1.2285 +      val T = result_type_of_decl decl
  1.2286 +              |> map_type_tvar (fn (z, _) => TVar (z, HOLogic.typeS))
  1.2287 +    in
  1.2288 +      if forall (type_generalization ctxt T o result_type_of_decl) decls' then
  1.2289 +        [decl]
  1.2290 +      else
  1.2291 +        decls
  1.2292 +    end
  1.2293 +  | rationalize_decls _ decls = decls
  1.2294 +
  1.2295 +fun problem_lines_for_sym_decls ctxt format conj_sym_kind mono type_enc
  1.2296 +                                (s, decls) =
  1.2297 +  case type_enc of
  1.2298 +    Simple_Types _ => [decl_line_for_sym ctxt format mono type_enc s (hd decls)]
  1.2299 +  | Guards (_, level) =>
  1.2300 +    let
  1.2301 +      val decls = decls |> rationalize_decls ctxt
  1.2302 +      val n = length decls
  1.2303 +      val decls =
  1.2304 +        decls |> filter (should_encode_type ctxt mono level
  1.2305 +                         o result_type_of_decl)
  1.2306 +    in
  1.2307 +      (0 upto length decls - 1, decls)
  1.2308 +      |-> map2 (formula_line_for_guards_sym_decl ctxt format conj_sym_kind mono
  1.2309 +                                                 type_enc n s)
  1.2310 +    end
  1.2311 +  | Tags (_, level) =>
  1.2312 +    if granularity_of_type_level level = All_Vars then
  1.2313 +      []
  1.2314 +    else
  1.2315 +      let val n = length decls in
  1.2316 +        (0 upto n - 1 ~~ decls)
  1.2317 +        |> maps (formula_lines_for_tags_sym_decl ctxt format conj_sym_kind mono
  1.2318 +                                                 type_enc n s)
  1.2319 +      end
  1.2320 +
  1.2321 +fun problem_lines_for_sym_decl_table ctxt format conj_sym_kind mono type_enc
  1.2322 +                                     mono_Ts sym_decl_tab =
  1.2323 +  let
  1.2324 +    val syms = sym_decl_tab |> Symtab.dest |> sort_wrt fst
  1.2325 +    val mono_lines =
  1.2326 +      problem_lines_for_mono_types ctxt format mono type_enc mono_Ts
  1.2327 +    val decl_lines =
  1.2328 +      fold_rev (append o problem_lines_for_sym_decls ctxt format conj_sym_kind
  1.2329 +                             mono type_enc)
  1.2330 +               syms []
  1.2331 +  in mono_lines @ decl_lines end
  1.2332 +
  1.2333 +fun needs_type_tag_idempotence ctxt (Tags (poly, level)) =
  1.2334 +    Config.get ctxt type_tag_idempotence andalso
  1.2335 +    is_type_level_monotonicity_based level andalso
  1.2336 +    poly <> Mangled_Monomorphic
  1.2337 +  | needs_type_tag_idempotence _ _ = false
  1.2338 +
  1.2339 +val implicit_declsN = "Should-be-implicit typings"
  1.2340 +val explicit_declsN = "Explicit typings"
  1.2341 +val factsN = "Relevant facts"
  1.2342 +val class_relsN = "Class relationships"
  1.2343 +val aritiesN = "Arities"
  1.2344 +val helpersN = "Helper facts"
  1.2345 +val conjsN = "Conjectures"
  1.2346 +val free_typesN = "Type variables"
  1.2347 +
  1.2348 +(* TFF allows implicit declarations of types, function symbols, and predicate
  1.2349 +   symbols (with "$i" as the type of individuals), but some provers (e.g.,
  1.2350 +   SNARK) require explicit declarations. The situation is similar for THF. *)
  1.2351 +
  1.2352 +fun default_type type_enc pred_sym s =
  1.2353 +  let
  1.2354 +    val ind =
  1.2355 +      case type_enc of
  1.2356 +        Simple_Types _ =>
  1.2357 +        if String.isPrefix type_const_prefix s then atype_of_types
  1.2358 +        else individual_atype
  1.2359 +      | _ => individual_atype
  1.2360 +    fun typ 0 = if pred_sym then bool_atype else ind
  1.2361 +      | typ ary = AFun (ind, typ (ary - 1))
  1.2362 +  in typ end
  1.2363 +
  1.2364 +fun nary_type_constr_type n =
  1.2365 +  funpow n (curry AFun atype_of_types) atype_of_types
  1.2366 +
  1.2367 +fun undeclared_syms_in_problem type_enc problem =
  1.2368 +  let
  1.2369 +    val declared = declared_syms_in_problem problem
  1.2370 +    fun do_sym name ty =
  1.2371 +      if member (op =) declared name then I else AList.default (op =) (name, ty)
  1.2372 +    fun do_type (AType (name as (s, _), tys)) =
  1.2373 +        is_tptp_user_symbol s
  1.2374 +        ? do_sym name (fn () => nary_type_constr_type (length tys))
  1.2375 +        #> fold do_type tys
  1.2376 +      | do_type (AFun (ty1, ty2)) = do_type ty1 #> do_type ty2
  1.2377 +      | do_type (ATyAbs (_, ty)) = do_type ty
  1.2378 +    fun do_term pred_sym (ATerm (name as (s, _), tms)) =
  1.2379 +        is_tptp_user_symbol s
  1.2380 +        ? do_sym name (fn _ => default_type type_enc pred_sym s (length tms))
  1.2381 +        #> fold (do_term false) tms
  1.2382 +      | do_term _ (AAbs ((_, ty), tm)) = do_type ty #> do_term false tm
  1.2383 +    fun do_formula (AQuant (_, xs, phi)) =
  1.2384 +        fold do_type (map_filter snd xs) #> do_formula phi
  1.2385 +      | do_formula (AConn (_, phis)) = fold do_formula phis
  1.2386 +      | do_formula (AAtom tm) = do_term true tm
  1.2387 +    fun do_problem_line (Decl (_, _, ty)) = do_type ty
  1.2388 +      | do_problem_line (Formula (_, _, phi, _, _)) = do_formula phi
  1.2389 +  in
  1.2390 +    fold (fold do_problem_line o snd) problem []
  1.2391 +    |> filter_out (is_built_in_tptp_symbol o fst o fst)
  1.2392 +  end
  1.2393 +
  1.2394 +fun declare_undeclared_syms_in_atp_problem type_enc problem =
  1.2395 +  let
  1.2396 +    val decls =
  1.2397 +      problem
  1.2398 +      |> undeclared_syms_in_problem type_enc
  1.2399 +      |> sort_wrt (fst o fst)
  1.2400 +      |> map (fn (x as (s, _), ty) => Decl (type_decl_prefix ^ s, x, ty ()))
  1.2401 +  in (implicit_declsN, decls) :: problem end
  1.2402 +
  1.2403 +fun exists_subdtype P =
  1.2404 +  let
  1.2405 +    fun ex U = P U orelse
  1.2406 +      (case U of Datatype.DtType (_, Us) => exists ex Us | _ => false)
  1.2407 +  in ex end
  1.2408 +
  1.2409 +fun is_poly_constr (_, Us) =
  1.2410 +  exists (exists_subdtype (fn Datatype.DtTFree _ => true | _ => false)) Us
  1.2411 +
  1.2412 +fun all_constrs_of_polymorphic_datatypes thy =
  1.2413 +  Symtab.fold (snd
  1.2414 +               #> #descr
  1.2415 +               #> maps (snd #> #3)
  1.2416 +               #> (fn cs => exists is_poly_constr cs ? append cs))
  1.2417 +              (Datatype.get_all thy) []
  1.2418 +  |> List.partition is_poly_constr
  1.2419 +  |> pairself (map fst)
  1.2420 +
  1.2421 +(* Forcing explicit applications is expensive for polymorphic encodings, because
  1.2422 +   it takes only one existential variable ranging over "'a => 'b" to ruin
  1.2423 +   everything. Hence we do it only if there are few facts (is normally the case
  1.2424 +   for "metis" and the minimizer. *)
  1.2425 +val explicit_apply_threshold = 50
  1.2426 +
  1.2427 +fun prepare_atp_problem ctxt format conj_sym_kind prem_kind type_enc exporter
  1.2428 +                        lam_trans readable_names preproc hyp_ts concl_t facts =
  1.2429 +  let
  1.2430 +    val thy = Proof_Context.theory_of ctxt
  1.2431 +    val type_enc = type_enc |> adjust_type_enc format
  1.2432 +    val explicit_apply =
  1.2433 +      if polymorphism_of_type_enc type_enc <> Polymorphic orelse
  1.2434 +         length facts <= explicit_apply_threshold then
  1.2435 +        NONE
  1.2436 +      else
  1.2437 +        SOME false
  1.2438 +    val lam_trans =
  1.2439 +      if lam_trans = keep_lamsN andalso
  1.2440 +         not (is_type_enc_higher_order type_enc) then
  1.2441 +        error ("Lambda translation scheme incompatible with first-order \
  1.2442 +               \encoding.")
  1.2443 +      else
  1.2444 +        lam_trans
  1.2445 +    val (fact_names, classes, conjs, facts, class_rel_clauses, arity_clauses,
  1.2446 +         lifted) =
  1.2447 +      translate_formulas ctxt format prem_kind type_enc lam_trans preproc hyp_ts
  1.2448 +                         concl_t facts
  1.2449 +    val sym_tab = sym_table_for_facts ctxt type_enc explicit_apply conjs facts
  1.2450 +    val mono = conjs @ facts |> mononotonicity_info_for_facts ctxt type_enc
  1.2451 +    val (polym_constrs, monom_constrs) =
  1.2452 +      all_constrs_of_polymorphic_datatypes thy
  1.2453 +      |>> map (make_fixed_const (SOME format))
  1.2454 +    val firstorderize =
  1.2455 +      firstorderize_fact thy monom_constrs format type_enc sym_tab
  1.2456 +    val (conjs, facts) = (conjs, facts) |> pairself (map firstorderize)
  1.2457 +    val sym_tab = sym_table_for_facts ctxt type_enc (SOME false) conjs facts
  1.2458 +    val helpers =
  1.2459 +      sym_tab |> helper_facts_for_sym_table ctxt format type_enc
  1.2460 +              |> map firstorderize
  1.2461 +    val mono_Ts =
  1.2462 +      helpers @ conjs @ facts |> monotonic_types_for_facts ctxt mono type_enc
  1.2463 +    val class_decl_lines = decl_lines_for_classes type_enc classes
  1.2464 +    val sym_decl_lines =
  1.2465 +      (conjs, helpers @ facts)
  1.2466 +      |> sym_decl_table_for_facts ctxt format type_enc sym_tab
  1.2467 +      |> problem_lines_for_sym_decl_table ctxt format conj_sym_kind mono
  1.2468 +                                               type_enc mono_Ts
  1.2469 +    val helper_lines =
  1.2470 +      0 upto length helpers - 1 ~~ helpers
  1.2471 +      |> map (formula_line_for_fact ctxt polym_constrs format helper_prefix I
  1.2472 +                                    false true mono type_enc)
  1.2473 +      |> (if needs_type_tag_idempotence ctxt type_enc then
  1.2474 +            cons (type_tag_idempotence_fact format type_enc)
  1.2475 +          else
  1.2476 +            I)
  1.2477 +    (* Reordering these might confuse the proof reconstruction code or the SPASS
  1.2478 +       FLOTTER hack. *)
  1.2479 +    val problem =
  1.2480 +      [(explicit_declsN, class_decl_lines @ sym_decl_lines),
  1.2481 +       (factsN,
  1.2482 +        map (formula_line_for_fact ctxt polym_constrs format fact_prefix
  1.2483 +                 ascii_of (not exporter) (not exporter) mono type_enc)
  1.2484 +            (0 upto length facts - 1 ~~ facts)),
  1.2485 +       (class_relsN,
  1.2486 +        map (formula_line_for_class_rel_clause format type_enc)
  1.2487 +            class_rel_clauses),
  1.2488 +       (aritiesN,
  1.2489 +        map (formula_line_for_arity_clause format type_enc) arity_clauses),
  1.2490 +       (helpersN, helper_lines),
  1.2491 +       (conjsN,
  1.2492 +        map (formula_line_for_conjecture ctxt polym_constrs format mono
  1.2493 +                                         type_enc) conjs),
  1.2494 +       (free_typesN, formula_lines_for_free_types type_enc (facts @ conjs))]
  1.2495 +    val problem =
  1.2496 +      problem
  1.2497 +      |> (case format of
  1.2498 +            CNF => ensure_cnf_problem
  1.2499 +          | CNF_UEQ => filter_cnf_ueq_problem
  1.2500 +          | FOF => I
  1.2501 +          | TFF (_, TPTP_Implicit) => I
  1.2502 +          | THF (_, TPTP_Implicit, _) => I
  1.2503 +          | _ => declare_undeclared_syms_in_atp_problem type_enc)
  1.2504 +    val (problem, pool) = problem |> nice_atp_problem readable_names format
  1.2505 +    fun add_sym_ary (s, {min_ary, ...} : sym_info) =
  1.2506 +      min_ary > 0 ? Symtab.insert (op =) (s, min_ary)
  1.2507 +  in
  1.2508 +    (problem,
  1.2509 +     case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
  1.2510 +     fact_names |> Vector.fromList,
  1.2511 +     lifted,
  1.2512 +     Symtab.empty |> Symtab.fold add_sym_ary sym_tab)
  1.2513 +  end
  1.2514 +
  1.2515 +(* FUDGE *)
  1.2516 +val conj_weight = 0.0
  1.2517 +val hyp_weight = 0.1
  1.2518 +val fact_min_weight = 0.2
  1.2519 +val fact_max_weight = 1.0
  1.2520 +val type_info_default_weight = 0.8
  1.2521 +
  1.2522 +fun add_term_weights weight (ATerm (s, tms)) =
  1.2523 +    is_tptp_user_symbol s ? Symtab.default (s, weight)
  1.2524 +    #> fold (add_term_weights weight) tms
  1.2525 +  | add_term_weights weight (AAbs (_, tm)) = add_term_weights weight tm
  1.2526 +fun add_problem_line_weights weight (Formula (_, _, phi, _, _)) =
  1.2527 +    formula_fold NONE (K (add_term_weights weight)) phi
  1.2528 +  | add_problem_line_weights _ _ = I
  1.2529 +
  1.2530 +fun add_conjectures_weights [] = I
  1.2531 +  | add_conjectures_weights conjs =
  1.2532 +    let val (hyps, conj) = split_last conjs in
  1.2533 +      add_problem_line_weights conj_weight conj
  1.2534 +      #> fold (add_problem_line_weights hyp_weight) hyps
  1.2535 +    end
  1.2536 +
  1.2537 +fun add_facts_weights facts =
  1.2538 +  let
  1.2539 +    val num_facts = length facts
  1.2540 +    fun weight_of j =
  1.2541 +      fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
  1.2542 +                        / Real.fromInt num_facts
  1.2543 +  in
  1.2544 +    map weight_of (0 upto num_facts - 1) ~~ facts
  1.2545 +    |> fold (uncurry add_problem_line_weights)
  1.2546 +  end
  1.2547 +
  1.2548 +(* Weights are from 0.0 (most important) to 1.0 (least important). *)
  1.2549 +fun atp_problem_weights problem =
  1.2550 +  let val get = these o AList.lookup (op =) problem in
  1.2551 +    Symtab.empty
  1.2552 +    |> add_conjectures_weights (get free_typesN @ get conjsN)
  1.2553 +    |> add_facts_weights (get factsN)
  1.2554 +    |> fold (fold (add_problem_line_weights type_info_default_weight) o get)
  1.2555 +            [explicit_declsN, class_relsN, aritiesN]
  1.2556 +    |> Symtab.dest
  1.2557 +    |> sort (prod_ord Real.compare string_ord o pairself swap)
  1.2558 +  end
  1.2559 +
  1.2560 +end;