src/HOL/Tools/ATP/atp_translate.ML
author blanchet
Tue Aug 23 23:18:13 2011 +0200 (2011-08-23)
changeset 44450 d848dd7b21f4
parent 44418 800baa1b1406
child 44460 5d0754cf994a
permissions -rw-r--r--
fixed "hBOOL" of existential variables, and generate more helpers
     1 (*  Title:      HOL/Tools/ATP/atp_translate.ML
     2     Author:     Fabian Immler, TU Muenchen
     3     Author:     Makarius
     4     Author:     Jasmin Blanchette, TU Muenchen
     5 
     6 Translation of HOL to FOL for Metis and Sledgehammer.
     7 *)
     8 
     9 signature ATP_TRANSLATE =
    10 sig
    11   type ('a, 'b) ho_term = ('a, 'b) ATP_Problem.ho_term
    12   type connective = ATP_Problem.connective
    13   type ('a, 'b, 'c) formula = ('a, 'b, 'c) ATP_Problem.formula
    14   type format = ATP_Problem.format
    15   type formula_kind = ATP_Problem.formula_kind
    16   type 'a problem = 'a ATP_Problem.problem
    17 
    18   datatype locality =
    19     General | Helper | Extensionality | Intro | Elim | Simp | Local | Assum |
    20     Chained
    21 
    22   datatype order = First_Order | Higher_Order
    23   datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
    24   datatype soundness = Unsound | Sound_Modulo_Infiniteness | Sound
    25   datatype type_level =
    26     All_Types |
    27     Noninf_Nonmono_Types of soundness |
    28     Fin_Nonmono_Types |
    29     Const_Arg_Types |
    30     No_Types
    31   datatype type_uniformity = Uniform | Nonuniform
    32 
    33   datatype type_enc =
    34     Simple_Types of order * type_level |
    35     Guards of polymorphism * type_level * type_uniformity |
    36     Tags of polymorphism * type_level * type_uniformity
    37 
    38   val no_lambdasN : string
    39   val concealedN : string
    40   val liftingN : string
    41   val combinatorsN : string
    42   val hybridN : string
    43   val lambdasN : string
    44   val smartN : string
    45   val schematic_var_prefix : string
    46   val fixed_var_prefix : string
    47   val tvar_prefix : string
    48   val tfree_prefix : string
    49   val const_prefix : string
    50   val type_const_prefix : string
    51   val class_prefix : string
    52   val polymorphic_free_prefix : string
    53   val skolem_const_prefix : string
    54   val old_skolem_const_prefix : string
    55   val new_skolem_const_prefix : string
    56   val type_decl_prefix : string
    57   val sym_decl_prefix : string
    58   val guards_sym_formula_prefix : string
    59   val tags_sym_formula_prefix : string
    60   val fact_prefix : string
    61   val conjecture_prefix : string
    62   val helper_prefix : string
    63   val class_rel_clause_prefix : string
    64   val arity_clause_prefix : string
    65   val tfree_clause_prefix : string
    66   val typed_helper_suffix : string
    67   val untyped_helper_suffix : string
    68   val type_tag_idempotence_helper_name : string
    69   val predicator_name : string
    70   val app_op_name : string
    71   val type_guard_name : string
    72   val type_tag_name : string
    73   val simple_type_prefix : string
    74   val prefixed_predicator_name : string
    75   val prefixed_app_op_name : string
    76   val prefixed_type_tag_name : string
    77   val ascii_of : string -> string
    78   val unascii_of : string -> string
    79   val strip_prefix_and_unascii : string -> string -> string option
    80   val proxy_table : (string * (string * (thm * (string * string)))) list
    81   val proxify_const : string -> (string * string) option
    82   val invert_const : string -> string
    83   val unproxify_const : string -> string
    84   val new_skolem_var_name_from_const : string -> string
    85   val atp_irrelevant_consts : string list
    86   val atp_schematic_consts_of : term -> typ list Symtab.table
    87   val type_enc_from_string : soundness -> string -> type_enc
    88   val is_type_enc_higher_order : type_enc -> bool
    89   val polymorphism_of_type_enc : type_enc -> polymorphism
    90   val level_of_type_enc : type_enc -> type_level
    91   val is_type_enc_quasi_sound : type_enc -> bool
    92   val is_type_enc_fairly_sound : type_enc -> bool
    93   val adjust_type_enc : format -> type_enc -> type_enc
    94   val mk_aconns :
    95     connective -> ('a, 'b, 'c) formula list -> ('a, 'b, 'c) formula
    96   val unmangled_const : string -> string * (string, 'b) ho_term list
    97   val unmangled_const_name : string -> string
    98   val helper_table : ((string * bool) * thm list) list
    99   val factsN : string
   100   val prepare_atp_problem :
   101     Proof.context -> format -> formula_kind -> formula_kind -> type_enc
   102     -> bool -> string -> bool -> bool -> term list -> term
   103     -> ((string * locality) * term) list
   104     -> string problem * string Symtab.table * int * int
   105        * (string * locality) list vector * int list * int Symtab.table
   106   val atp_problem_weights : string problem -> (string * real) list
   107 end;
   108 
   109 structure ATP_Translate : ATP_TRANSLATE =
   110 struct
   111 
   112 open ATP_Util
   113 open ATP_Problem
   114 
   115 type name = string * string
   116 
   117 val no_lambdasN = "no_lambdas"
   118 val concealedN = "concealed"
   119 val liftingN = "lifting"
   120 val combinatorsN = "combinators"
   121 val hybridN = "hybrid"
   122 val lambdasN = "lambdas"
   123 val smartN = "smart"
   124 
   125 val generate_info = false (* experimental *)
   126 
   127 fun isabelle_info s =
   128   if generate_info then SOME (ATerm ("[]", [ATerm ("isabelle_" ^ s, [])]))
   129   else NONE
   130 
   131 val introN = "intro"
   132 val elimN = "elim"
   133 val simpN = "simp"
   134 
   135 val bound_var_prefix = "B_"
   136 val all_bound_var_prefix = "BA_"
   137 val exist_bound_var_prefix = "BE_"
   138 val schematic_var_prefix = "V_"
   139 val fixed_var_prefix = "v_"
   140 val tvar_prefix = "T_"
   141 val tfree_prefix = "t_"
   142 val const_prefix = "c_"
   143 val type_const_prefix = "tc_"
   144 val class_prefix = "cl_"
   145 
   146 val polymorphic_free_prefix = "poly_free"
   147 
   148 val skolem_const_prefix = "ATP" ^ Long_Name.separator ^ "Sko"
   149 val old_skolem_const_prefix = skolem_const_prefix ^ "o"
   150 val new_skolem_const_prefix = skolem_const_prefix ^ "n"
   151 
   152 val type_decl_prefix = "ty_"
   153 val sym_decl_prefix = "sy_"
   154 val guards_sym_formula_prefix = "gsy_"
   155 val tags_sym_formula_prefix = "tsy_"
   156 val fact_prefix = "fact_"
   157 val conjecture_prefix = "conj_"
   158 val helper_prefix = "help_"
   159 val class_rel_clause_prefix = "clar_"
   160 val arity_clause_prefix = "arity_"
   161 val tfree_clause_prefix = "tfree_"
   162 
   163 val lambda_fact_prefix = "ATP.lambda_"
   164 val typed_helper_suffix = "_T"
   165 val untyped_helper_suffix = "_U"
   166 val type_tag_idempotence_helper_name = helper_prefix ^ "ti_idem"
   167 
   168 val predicator_name = "p"
   169 val app_op_name = "a"
   170 val type_guard_name = "g"
   171 val type_tag_name = "t"
   172 val simple_type_prefix = "ty_"
   173 
   174 val prefixed_predicator_name = const_prefix ^ predicator_name
   175 val prefixed_app_op_name = const_prefix ^ app_op_name
   176 val prefixed_type_tag_name = const_prefix ^ type_tag_name
   177 
   178 (* Freshness almost guaranteed! *)
   179 val atp_weak_prefix = "ATP:"
   180 
   181 (*Escaping of special characters.
   182   Alphanumeric characters are left unchanged.
   183   The character _ goes to __
   184   Characters in the range ASCII space to / go to _A to _P, respectively.
   185   Other characters go to _nnn where nnn is the decimal ASCII code.*)
   186 val upper_a_minus_space = Char.ord #"A" - Char.ord #" "
   187 
   188 fun stringN_of_int 0 _ = ""
   189   | stringN_of_int k n =
   190     stringN_of_int (k - 1) (n div 10) ^ string_of_int (n mod 10)
   191 
   192 fun ascii_of_char c =
   193   if Char.isAlphaNum c then
   194     String.str c
   195   else if c = #"_" then
   196     "__"
   197   else if #" " <= c andalso c <= #"/" then
   198     "_" ^ String.str (Char.chr (Char.ord c + upper_a_minus_space))
   199   else
   200     (* fixed width, in case more digits follow *)
   201     "_" ^ stringN_of_int 3 (Char.ord c)
   202 
   203 val ascii_of = String.translate ascii_of_char
   204 
   205 (** Remove ASCII armoring from names in proof files **)
   206 
   207 (* We don't raise error exceptions because this code can run inside a worker
   208    thread. Also, the errors are impossible. *)
   209 val unascii_of =
   210   let
   211     fun un rcs [] = String.implode(rev rcs)
   212       | un rcs [#"_"] = un (#"_" :: rcs) [] (* ERROR *)
   213         (* Three types of _ escapes: __, _A to _P, _nnn *)
   214       | un rcs (#"_" :: #"_" :: cs) = un (#"_" :: rcs) cs
   215       | un rcs (#"_" :: c :: cs) =
   216         if #"A" <= c andalso c<= #"P" then
   217           (* translation of #" " to #"/" *)
   218           un (Char.chr (Char.ord c - upper_a_minus_space) :: rcs) cs
   219         else
   220           let val digits = List.take (c :: cs, 3) handle General.Subscript => [] in
   221             case Int.fromString (String.implode digits) of
   222               SOME n => un (Char.chr n :: rcs) (List.drop (cs, 2))
   223             | NONE => un (c :: #"_" :: rcs) cs (* ERROR *)
   224           end
   225       | un rcs (c :: cs) = un (c :: rcs) cs
   226   in un [] o String.explode end
   227 
   228 (* If string s has the prefix s1, return the result of deleting it,
   229    un-ASCII'd. *)
   230 fun strip_prefix_and_unascii s1 s =
   231   if String.isPrefix s1 s then
   232     SOME (unascii_of (String.extract (s, size s1, NONE)))
   233   else
   234     NONE
   235 
   236 val proxy_table =
   237   [("c_False", (@{const_name False}, (@{thm fFalse_def},
   238        ("fFalse", @{const_name ATP.fFalse})))),
   239    ("c_True", (@{const_name True}, (@{thm fTrue_def},
   240        ("fTrue", @{const_name ATP.fTrue})))),
   241    ("c_Not", (@{const_name Not}, (@{thm fNot_def},
   242        ("fNot", @{const_name ATP.fNot})))),
   243    ("c_conj", (@{const_name conj}, (@{thm fconj_def},
   244        ("fconj", @{const_name ATP.fconj})))),
   245    ("c_disj", (@{const_name disj}, (@{thm fdisj_def},
   246        ("fdisj", @{const_name ATP.fdisj})))),
   247    ("c_implies", (@{const_name implies}, (@{thm fimplies_def},
   248        ("fimplies", @{const_name ATP.fimplies})))),
   249    ("equal", (@{const_name HOL.eq}, (@{thm fequal_def},
   250        ("fequal", @{const_name ATP.fequal})))),
   251    ("c_All", (@{const_name All}, (@{thm fAll_def},
   252        ("fAll", @{const_name ATP.fAll})))),
   253    ("c_Ex", (@{const_name Ex}, (@{thm fEx_def},
   254        ("fEx", @{const_name ATP.fEx}))))]
   255 
   256 val proxify_const = AList.lookup (op =) proxy_table #> Option.map (snd o snd)
   257 
   258 (* Readable names for the more common symbolic functions. Do not mess with the
   259    table unless you know what you are doing. *)
   260 val const_trans_table =
   261   [(@{type_name Product_Type.prod}, "prod"),
   262    (@{type_name Sum_Type.sum}, "sum"),
   263    (@{const_name False}, "False"),
   264    (@{const_name True}, "True"),
   265    (@{const_name Not}, "Not"),
   266    (@{const_name conj}, "conj"),
   267    (@{const_name disj}, "disj"),
   268    (@{const_name implies}, "implies"),
   269    (@{const_name HOL.eq}, "equal"),
   270    (@{const_name All}, "All"),
   271    (@{const_name Ex}, "Ex"),
   272    (@{const_name If}, "If"),
   273    (@{const_name Set.member}, "member"),
   274    (@{const_name Meson.COMBI}, "COMBI"),
   275    (@{const_name Meson.COMBK}, "COMBK"),
   276    (@{const_name Meson.COMBB}, "COMBB"),
   277    (@{const_name Meson.COMBC}, "COMBC"),
   278    (@{const_name Meson.COMBS}, "COMBS")]
   279   |> Symtab.make
   280   |> fold (Symtab.update o swap o snd o snd o snd) proxy_table
   281 
   282 (* Invert the table of translations between Isabelle and ATPs. *)
   283 val const_trans_table_inv =
   284   const_trans_table |> Symtab.dest |> map swap |> Symtab.make
   285 val const_trans_table_unprox =
   286   Symtab.empty
   287   |> fold (fn (_, (isa, (_, (_, atp)))) => Symtab.update (atp, isa)) proxy_table
   288 
   289 val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
   290 val unproxify_const = perhaps (Symtab.lookup const_trans_table_unprox)
   291 
   292 fun lookup_const c =
   293   case Symtab.lookup const_trans_table c of
   294     SOME c' => c'
   295   | NONE => ascii_of c
   296 
   297 fun ascii_of_indexname (v, 0) = ascii_of v
   298   | ascii_of_indexname (v, i) = ascii_of v ^ "_" ^ string_of_int i
   299 
   300 fun make_bound_var x = bound_var_prefix ^ ascii_of x
   301 fun make_all_bound_var x = all_bound_var_prefix ^ ascii_of x
   302 fun make_exist_bound_var x = exist_bound_var_prefix ^ ascii_of x
   303 fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
   304 fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
   305 
   306 fun make_schematic_type_var (x, i) =
   307       tvar_prefix ^ (ascii_of_indexname (unprefix "'" x, i))
   308 fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (unprefix "'" x))
   309 
   310 (* "HOL.eq" is mapped to the ATP's equality. *)
   311 fun make_fixed_const @{const_name HOL.eq} = tptp_old_equal
   312   | make_fixed_const c = const_prefix ^ lookup_const c
   313 
   314 fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
   315 
   316 fun make_type_class clas = class_prefix ^ ascii_of clas
   317 
   318 fun new_skolem_var_name_from_const s =
   319   let val ss = s |> space_explode Long_Name.separator in
   320     nth ss (length ss - 2)
   321   end
   322 
   323 (* These are either simplified away by "Meson.presimplify" (most of the time) or
   324    handled specially via "fFalse", "fTrue", ..., "fequal". *)
   325 val atp_irrelevant_consts =
   326   [@{const_name False}, @{const_name True}, @{const_name Not},
   327    @{const_name conj}, @{const_name disj}, @{const_name implies},
   328    @{const_name HOL.eq}, @{const_name If}, @{const_name Let}]
   329 
   330 val atp_monomorph_bad_consts =
   331   atp_irrelevant_consts @
   332   (* These are ignored anyway by the relevance filter (unless they appear in
   333      higher-order places) but not by the monomorphizer. *)
   334   [@{const_name all}, @{const_name "==>"}, @{const_name "=="},
   335    @{const_name Trueprop}, @{const_name All}, @{const_name Ex},
   336    @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}]
   337 
   338 fun add_schematic_const (x as (_, T)) =
   339   Monomorph.typ_has_tvars T ? Symtab.insert_list (op =) x
   340 val add_schematic_consts_of =
   341   Term.fold_aterms (fn Const (x as (s, _)) =>
   342                        not (member (op =) atp_monomorph_bad_consts s)
   343                        ? add_schematic_const x
   344                       | _ => I)
   345 fun atp_schematic_consts_of t = add_schematic_consts_of t Symtab.empty
   346 
   347 (** Definitions and functions for FOL clauses and formulas for TPTP **)
   348 
   349 (* The first component is the type class; the second is a "TVar" or "TFree". *)
   350 datatype type_literal =
   351   TyLitVar of name * name |
   352   TyLitFree of name * name
   353 
   354 
   355 (** Isabelle arities **)
   356 
   357 datatype arity_literal =
   358   TConsLit of name * name * name list |
   359   TVarLit of name * name
   360 
   361 fun gen_TVars 0 = []
   362   | gen_TVars n = ("T_" ^ string_of_int n) :: gen_TVars (n-1)
   363 
   364 val type_class = the_single @{sort type}
   365 
   366 fun add_packed_sort tvar =
   367   fold (fn s => s <> type_class ? cons (`make_type_class s, `I tvar))
   368 
   369 type arity_clause =
   370   {name : string,
   371    prem_lits : arity_literal list,
   372    concl_lits : arity_literal}
   373 
   374 (* Arity of type constructor "tcon :: (arg1, ..., argN) res" *)
   375 fun make_axiom_arity_clause (tcons, name, (cls, args)) =
   376   let
   377     val tvars = gen_TVars (length args)
   378     val tvars_srts = ListPair.zip (tvars, args)
   379   in
   380     {name = name,
   381      prem_lits = [] |> fold (uncurry add_packed_sort) tvars_srts |> map TVarLit,
   382      concl_lits = TConsLit (`make_type_class cls,
   383                             `make_fixed_type_const tcons,
   384                             tvars ~~ tvars)}
   385   end
   386 
   387 fun arity_clause _ _ (_, []) = []
   388   | arity_clause seen n (tcons, ("HOL.type", _) :: ars) =  (* ignore *)
   389     arity_clause seen n (tcons, ars)
   390   | arity_clause seen n (tcons, (ar as (class, _)) :: ars) =
   391     if member (op =) seen class then
   392       (* multiple arities for the same (tycon, class) pair *)
   393       make_axiom_arity_clause (tcons,
   394           lookup_const tcons ^ "___" ^ ascii_of class ^ "_" ^ string_of_int n,
   395           ar) ::
   396       arity_clause seen (n + 1) (tcons, ars)
   397     else
   398       make_axiom_arity_clause (tcons, lookup_const tcons ^ "___" ^
   399                                ascii_of class, ar) ::
   400       arity_clause (class :: seen) n (tcons, ars)
   401 
   402 fun multi_arity_clause [] = []
   403   | multi_arity_clause ((tcons, ars) :: tc_arlists) =
   404       arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
   405 
   406 (* Generate all pairs (tycon, class, sorts) such that tycon belongs to class in
   407    theory thy provided its arguments have the corresponding sorts. *)
   408 fun type_class_pairs thy tycons classes =
   409   let
   410     val alg = Sign.classes_of thy
   411     fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
   412     fun add_class tycon class =
   413       cons (class, domain_sorts tycon class)
   414       handle Sorts.CLASS_ERROR _ => I
   415     fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
   416   in map try_classes tycons end
   417 
   418 (*Proving one (tycon, class) membership may require proving others, so iterate.*)
   419 fun iter_type_class_pairs _ _ [] = ([], [])
   420   | iter_type_class_pairs thy tycons classes =
   421       let
   422         fun maybe_insert_class s =
   423           (s <> type_class andalso not (member (op =) classes s))
   424           ? insert (op =) s
   425         val cpairs = type_class_pairs thy tycons classes
   426         val newclasses =
   427           [] |> fold (fold (fold (fold maybe_insert_class) o snd) o snd) cpairs
   428         val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
   429       in (classes' @ classes, union (op =) cpairs' cpairs) end
   430 
   431 fun make_arity_clauses thy tycons =
   432   iter_type_class_pairs thy tycons ##> multi_arity_clause
   433 
   434 
   435 (** Isabelle class relations **)
   436 
   437 type class_rel_clause =
   438   {name : string,
   439    subclass : name,
   440    superclass : name}
   441 
   442 (* Generate all pairs (sub, super) such that sub is a proper subclass of super
   443    in theory "thy". *)
   444 fun class_pairs _ [] _ = []
   445   | class_pairs thy subs supers =
   446       let
   447         val class_less = Sorts.class_less (Sign.classes_of thy)
   448         fun add_super sub super = class_less (sub, super) ? cons (sub, super)
   449         fun add_supers sub = fold (add_super sub) supers
   450       in fold add_supers subs [] end
   451 
   452 fun make_class_rel_clause (sub, super) =
   453   {name = sub ^ "_" ^ super, subclass = `make_type_class sub,
   454    superclass = `make_type_class super}
   455 
   456 fun make_class_rel_clauses thy subs supers =
   457   map make_class_rel_clause (class_pairs thy subs supers)
   458 
   459 (* intermediate terms *)
   460 datatype iterm =
   461   IConst of name * typ * typ list |
   462   IVar of name * typ |
   463   IApp of iterm * iterm |
   464   IAbs of (name * typ) * iterm
   465 
   466 fun ityp_of (IConst (_, T, _)) = T
   467   | ityp_of (IVar (_, T)) = T
   468   | ityp_of (IApp (t1, _)) = snd (dest_funT (ityp_of t1))
   469   | ityp_of (IAbs ((_, T), tm)) = T --> ityp_of tm
   470 
   471 (*gets the head of a combinator application, along with the list of arguments*)
   472 fun strip_iterm_comb u =
   473   let
   474     fun stripc (IApp (t, u), ts) = stripc (t, u :: ts)
   475       | stripc x = x
   476   in stripc (u, []) end
   477 
   478 fun atyps_of T = fold_atyps (insert (op =)) T []
   479 
   480 fun new_skolem_const_name s num_T_args =
   481   [new_skolem_const_prefix, s, string_of_int num_T_args]
   482   |> space_implode Long_Name.separator
   483 
   484 (* Converts an Isabelle/HOL term (with combinators) into an intermediate term.
   485    Also accumulates sort infomation. *)
   486 fun iterm_from_term thy bs (P $ Q) =
   487     let
   488       val (P', P_atomics_Ts) = iterm_from_term thy bs P
   489       val (Q', Q_atomics_Ts) = iterm_from_term thy bs Q
   490     in (IApp (P', Q'), union (op =) P_atomics_Ts Q_atomics_Ts) end
   491   | iterm_from_term thy _ (Const (c, T)) =
   492     (IConst (`make_fixed_const c, T,
   493              if String.isPrefix old_skolem_const_prefix c then
   494                [] |> Term.add_tvarsT T |> map TVar
   495              else
   496                (c, T) |> Sign.const_typargs thy),
   497      atyps_of T)
   498   | iterm_from_term _ _ (Free (s, T)) =
   499     (IConst (`make_fixed_var s, T,
   500              if String.isPrefix polymorphic_free_prefix s then [T] else []),
   501      atyps_of T)
   502   | iterm_from_term _ _ (Var (v as (s, _), T)) =
   503     (if String.isPrefix Meson_Clausify.new_skolem_var_prefix s then
   504        let
   505          val Ts = T |> strip_type |> swap |> op ::
   506          val s' = new_skolem_const_name s (length Ts)
   507        in IConst (`make_fixed_const s', T, Ts) end
   508      else
   509        IVar ((make_schematic_var v, s), T), atyps_of T)
   510   | iterm_from_term _ bs (Bound j) =
   511     nth bs j |> (fn (_, (name, T)) => (IConst (name, T, []), atyps_of T))
   512   | iterm_from_term thy bs (Abs (s, T, t)) =
   513     let
   514       fun vary s = s |> AList.defined (op =) bs s ? vary o Symbol.bump_string
   515       val s = vary s
   516       val name = `make_bound_var s
   517       val (tm, atomic_Ts) = iterm_from_term thy ((s, (name, T)) :: bs) t
   518     in (IAbs ((name, T), tm), union (op =) atomic_Ts (atyps_of T)) end
   519 
   520 datatype locality =
   521   General | Helper | Extensionality | Intro | Elim | Simp | Local | Assum |
   522   Chained
   523 
   524 datatype order = First_Order | Higher_Order
   525 datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
   526 datatype soundness = Unsound | Sound_Modulo_Infiniteness | Sound
   527 datatype type_level =
   528   All_Types |
   529   Noninf_Nonmono_Types of soundness |
   530   Fin_Nonmono_Types |
   531   Const_Arg_Types |
   532   No_Types
   533 datatype type_uniformity = Uniform | Nonuniform
   534 
   535 datatype type_enc =
   536   Simple_Types of order * type_level |
   537   Guards of polymorphism * type_level * type_uniformity |
   538   Tags of polymorphism * type_level * type_uniformity
   539 
   540 fun try_unsuffixes ss s =
   541   fold (fn s' => fn NONE => try (unsuffix s') s | some => some) ss NONE
   542 
   543 fun type_enc_from_string soundness s =
   544   (case try (unprefix "poly_") s of
   545      SOME s => (SOME Polymorphic, s)
   546    | NONE =>
   547      case try (unprefix "mono_") s of
   548        SOME s => (SOME Monomorphic, s)
   549      | NONE =>
   550        case try (unprefix "mangled_") s of
   551          SOME s => (SOME Mangled_Monomorphic, s)
   552        | NONE => (NONE, s))
   553   ||> (fn s =>
   554           (* "_query" and "_bang" are for the ASCII-challenged Metis and
   555              Mirabelle. *)
   556           case try_unsuffixes ["?", "_query"] s of
   557             SOME s => (Noninf_Nonmono_Types soundness, s)
   558           | NONE =>
   559             case try_unsuffixes ["!", "_bang"] s of
   560               SOME s => (Fin_Nonmono_Types, s)
   561             | NONE => (All_Types, s))
   562   ||> apsnd (fn s =>
   563                 case try (unsuffix "_uniform") s of
   564                   SOME s => (Uniform, s)
   565                 | NONE => (Nonuniform, s))
   566   |> (fn (poly, (level, (uniformity, core))) =>
   567          case (core, (poly, level, uniformity)) of
   568            ("simple", (NONE, _, Nonuniform)) =>
   569            Simple_Types (First_Order, level)
   570          | ("simple_higher", (NONE, _, Nonuniform)) =>
   571            (case level of
   572               Noninf_Nonmono_Types _ => raise Same.SAME
   573             | _ => Simple_Types (Higher_Order, level))
   574          | ("guards", (SOME poly, _, _)) => Guards (poly, level, uniformity)
   575          | ("tags", (SOME Polymorphic, _, _)) =>
   576            Tags (Polymorphic, level, uniformity)
   577          | ("tags", (SOME poly, _, _)) => Tags (poly, level, uniformity)
   578          | ("args", (SOME poly, All_Types (* naja *), Nonuniform)) =>
   579            Guards (poly, Const_Arg_Types, Nonuniform)
   580          | ("erased", (NONE, All_Types (* naja *), Nonuniform)) =>
   581            Guards (Polymorphic, No_Types, Nonuniform)
   582          | _ => raise Same.SAME)
   583   handle Same.SAME => error ("Unknown type system: " ^ quote s ^ ".")
   584 
   585 fun is_type_enc_higher_order (Simple_Types (Higher_Order, _)) = true
   586   | is_type_enc_higher_order _ = false
   587 
   588 fun polymorphism_of_type_enc (Simple_Types _) = Mangled_Monomorphic
   589   | polymorphism_of_type_enc (Guards (poly, _, _)) = poly
   590   | polymorphism_of_type_enc (Tags (poly, _, _)) = poly
   591 
   592 fun level_of_type_enc (Simple_Types (_, level)) = level
   593   | level_of_type_enc (Guards (_, level, _)) = level
   594   | level_of_type_enc (Tags (_, level, _)) = level
   595 
   596 fun uniformity_of_type_enc (Simple_Types _) = Uniform
   597   | uniformity_of_type_enc (Guards (_, _, uniformity)) = uniformity
   598   | uniformity_of_type_enc (Tags (_, _, uniformity)) = uniformity
   599 
   600 fun is_type_level_quasi_sound All_Types = true
   601   | is_type_level_quasi_sound (Noninf_Nonmono_Types _) = true
   602   | is_type_level_quasi_sound _ = false
   603 val is_type_enc_quasi_sound =
   604   is_type_level_quasi_sound o level_of_type_enc
   605 
   606 fun is_type_level_fairly_sound level =
   607   is_type_level_quasi_sound level orelse level = Fin_Nonmono_Types
   608 val is_type_enc_fairly_sound = is_type_level_fairly_sound o level_of_type_enc
   609 
   610 fun is_type_level_monotonicity_based (Noninf_Nonmono_Types _) = true
   611   | is_type_level_monotonicity_based Fin_Nonmono_Types = true
   612   | is_type_level_monotonicity_based _ = false
   613 
   614 fun adjust_type_enc (THF _) type_enc = type_enc
   615   | adjust_type_enc TFF (Simple_Types (_, level)) =
   616     Simple_Types (First_Order, level)
   617   | adjust_type_enc format (Simple_Types (_, level)) =
   618     adjust_type_enc format (Guards (Mangled_Monomorphic, level, Uniform))
   619   | adjust_type_enc CNF_UEQ (type_enc as Guards stuff) =
   620     (if is_type_enc_fairly_sound type_enc then Tags else Guards) stuff
   621   | adjust_type_enc _ type_enc = type_enc
   622 
   623 fun lift_lambdas ctxt type_enc =
   624   map (close_form o Envir.eta_contract) #> rpair ctxt
   625   #-> Lambda_Lifting.lift_lambdas
   626           (if polymorphism_of_type_enc type_enc = Polymorphic then
   627              SOME polymorphic_free_prefix
   628            else
   629              NONE)
   630           Lambda_Lifting.is_quantifier
   631   #> fst
   632 
   633 fun intentionalize_def (Const (@{const_name All}, _) $ Abs (_, _, t)) =
   634     intentionalize_def t
   635   | intentionalize_def (Const (@{const_name HOL.eq}, _) $ t $ u) =
   636     let
   637       fun lam T t = Abs (Name.uu, T, t)
   638       val (head, args) = strip_comb t ||> rev
   639       val head_T = fastype_of head
   640       val n = length args
   641       val arg_Ts = head_T |> binder_types |> take n |> rev
   642       val u = u |> subst_atomic (args ~~ map Bound (0 upto n - 1))
   643     in HOLogic.eq_const head_T $ head $ fold lam arg_Ts u end
   644   | intentionalize_def t = t
   645 
   646 type translated_formula =
   647   {name : string,
   648    locality : locality,
   649    kind : formula_kind,
   650    iformula : (name, typ, iterm) formula,
   651    atomic_types : typ list}
   652 
   653 fun update_iformula f ({name, locality, kind, iformula, atomic_types}
   654                        : translated_formula) =
   655   {name = name, locality = locality, kind = kind, iformula = f iformula,
   656    atomic_types = atomic_types} : translated_formula
   657 
   658 fun fact_lift f ({iformula, ...} : translated_formula) = f iformula
   659 
   660 fun insert_type ctxt get_T x xs =
   661   let val T = get_T x in
   662     if exists (type_instance ctxt T o get_T) xs then xs
   663     else x :: filter_out (type_generalization ctxt T o get_T) xs
   664   end
   665 
   666 (* The Booleans indicate whether all type arguments should be kept. *)
   667 datatype type_arg_policy =
   668   Explicit_Type_Args of bool |
   669   Mangled_Type_Args of bool |
   670   No_Type_Args
   671 
   672 fun should_drop_arg_type_args (Simple_Types _) =
   673     false (* since TFF doesn't support overloading *)
   674   | should_drop_arg_type_args type_enc =
   675     level_of_type_enc type_enc = All_Types andalso
   676     uniformity_of_type_enc type_enc = Uniform
   677 
   678 fun type_arg_policy type_enc s =
   679   if s = type_tag_name then
   680     (if polymorphism_of_type_enc type_enc = Mangled_Monomorphic then
   681        Mangled_Type_Args
   682      else
   683        Explicit_Type_Args) false
   684   else case type_enc of
   685     Tags (_, All_Types, Uniform) => No_Type_Args
   686   | _ =>
   687     let val level = level_of_type_enc type_enc in
   688       if level = No_Types orelse s = @{const_name HOL.eq} orelse
   689          (s = app_op_name andalso level = Const_Arg_Types) then
   690         No_Type_Args
   691       else
   692         should_drop_arg_type_args type_enc
   693         |> (if polymorphism_of_type_enc type_enc = Mangled_Monomorphic then
   694               Mangled_Type_Args
   695             else
   696               Explicit_Type_Args)
   697     end
   698 
   699 (* Make literals for sorted type variables. *)
   700 fun generic_add_sorts_on_type (_, []) = I
   701   | generic_add_sorts_on_type ((x, i), s :: ss) =
   702     generic_add_sorts_on_type ((x, i), ss)
   703     #> (if s = the_single @{sort HOL.type} then
   704           I
   705         else if i = ~1 then
   706           insert (op =) (TyLitFree (`make_type_class s, `make_fixed_type_var x))
   707         else
   708           insert (op =) (TyLitVar (`make_type_class s,
   709                                    (make_schematic_type_var (x, i), x))))
   710 fun add_sorts_on_tfree (TFree (s, S)) = generic_add_sorts_on_type ((s, ~1), S)
   711   | add_sorts_on_tfree _ = I
   712 fun add_sorts_on_tvar (TVar z) = generic_add_sorts_on_type z
   713   | add_sorts_on_tvar _ = I
   714 
   715 fun type_literals_for_types type_enc add_sorts_on_typ Ts =
   716   [] |> level_of_type_enc type_enc <> No_Types ? fold add_sorts_on_typ Ts
   717 
   718 fun mk_aconns c phis =
   719   let val (phis', phi') = split_last phis in
   720     fold_rev (mk_aconn c) phis' phi'
   721   end
   722 fun mk_ahorn [] phi = phi
   723   | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
   724 fun mk_aquant _ [] phi = phi
   725   | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
   726     if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
   727   | mk_aquant q xs phi = AQuant (q, xs, phi)
   728 
   729 fun close_universally atom_vars phi =
   730   let
   731     fun formula_vars bounds (AQuant (_, xs, phi)) =
   732         formula_vars (map fst xs @ bounds) phi
   733       | formula_vars bounds (AConn (_, phis)) = fold (formula_vars bounds) phis
   734       | formula_vars bounds (AAtom tm) =
   735         union (op =) (atom_vars tm []
   736                       |> filter_out (member (op =) bounds o fst))
   737   in mk_aquant AForall (formula_vars [] phi []) phi end
   738 
   739 fun iterm_vars (IApp (tm1, tm2)) = fold iterm_vars [tm1, tm2]
   740   | iterm_vars (IConst _) = I
   741   | iterm_vars (IVar (name, T)) = insert (op =) (name, SOME T)
   742   | iterm_vars (IAbs (_, tm)) = iterm_vars tm
   743 fun close_iformula_universally phi = close_universally iterm_vars phi
   744 
   745 fun term_vars bounds (ATerm (name as (s, _), tms)) =
   746     (is_tptp_variable s andalso not (member (op =) bounds name))
   747     ? insert (op =) (name, NONE) #> fold (term_vars bounds) tms
   748   | term_vars bounds (AAbs ((name, _), tm)) = term_vars (name :: bounds) tm
   749 fun close_formula_universally phi = close_universally (term_vars []) phi
   750 
   751 val homo_infinite_type_name = @{type_name ind} (* any infinite type *)
   752 val homo_infinite_type = Type (homo_infinite_type_name, [])
   753 
   754 fun ho_term_from_typ format type_enc =
   755   let
   756     fun term (Type (s, Ts)) =
   757       ATerm (case (is_type_enc_higher_order type_enc, s) of
   758                (true, @{type_name bool}) => `I tptp_bool_type
   759              | (true, @{type_name fun}) => `I tptp_fun_type
   760              | _ => if s = homo_infinite_type_name andalso
   761                        is_format_typed format then
   762                       `I tptp_individual_type
   763                     else
   764                       `make_fixed_type_const s,
   765              map term Ts)
   766     | term (TFree (s, _)) = ATerm (`make_fixed_type_var s, [])
   767     | term (TVar ((x as (s, _)), _)) =
   768       ATerm ((make_schematic_type_var x, s), [])
   769   in term end
   770 
   771 fun ho_term_for_type_arg format type_enc T =
   772   if T = dummyT then NONE else SOME (ho_term_from_typ format type_enc T)
   773 
   774 (* This shouldn't clash with anything else. *)
   775 val mangled_type_sep = "\000"
   776 
   777 fun generic_mangled_type_name f (ATerm (name, [])) = f name
   778   | generic_mangled_type_name f (ATerm (name, tys)) =
   779     f name ^ "(" ^ space_implode "," (map (generic_mangled_type_name f) tys)
   780     ^ ")"
   781   | generic_mangled_type_name _ _ = raise Fail "unexpected type abstraction"
   782 
   783 fun mangled_type format type_enc =
   784   generic_mangled_type_name fst o ho_term_from_typ format type_enc
   785 
   786 val bool_atype = AType (`I tptp_bool_type)
   787 
   788 fun make_simple_type s =
   789   if s = tptp_bool_type orelse s = tptp_fun_type orelse
   790      s = tptp_individual_type then
   791     s
   792   else
   793     simple_type_prefix ^ ascii_of s
   794 
   795 fun ho_type_from_ho_term type_enc pred_sym ary =
   796   let
   797     fun to_atype ty =
   798       AType ((make_simple_type (generic_mangled_type_name fst ty),
   799               generic_mangled_type_name snd ty))
   800     fun to_afun f1 f2 tys = AFun (f1 (hd tys), f2 (nth tys 1))
   801     fun to_fo 0 ty = if pred_sym then bool_atype else to_atype ty
   802       | to_fo ary (ATerm (_, tys)) = to_afun to_atype (to_fo (ary - 1)) tys
   803       | to_fo _ _ = raise Fail "unexpected type abstraction"
   804     fun to_ho (ty as ATerm ((s, _), tys)) =
   805         if s = tptp_fun_type then to_afun to_ho to_ho tys else to_atype ty
   806       | to_ho _ = raise Fail "unexpected type abstraction"
   807   in if is_type_enc_higher_order type_enc then to_ho else to_fo ary end
   808 
   809 fun ho_type_from_typ format type_enc pred_sym ary =
   810   ho_type_from_ho_term type_enc pred_sym ary
   811   o ho_term_from_typ format type_enc
   812 
   813 fun mangled_const_name format type_enc T_args (s, s') =
   814   let
   815     val ty_args = T_args |> map_filter (ho_term_for_type_arg format type_enc)
   816     fun type_suffix f g =
   817       fold_rev (curry (op ^) o g o prefix mangled_type_sep
   818                 o generic_mangled_type_name f) ty_args ""
   819   in (s ^ type_suffix fst ascii_of, s' ^ type_suffix snd I) end
   820 
   821 val parse_mangled_ident =
   822   Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
   823 
   824 fun parse_mangled_type x =
   825   (parse_mangled_ident
   826    -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
   827                     [] >> ATerm) x
   828 and parse_mangled_types x =
   829   (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
   830 
   831 fun unmangled_type s =
   832   s |> suffix ")" |> raw_explode
   833     |> Scan.finite Symbol.stopper
   834            (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
   835                                                 quote s)) parse_mangled_type))
   836     |> fst
   837 
   838 val unmangled_const_name = space_explode mangled_type_sep #> hd
   839 fun unmangled_const s =
   840   let val ss = space_explode mangled_type_sep s in
   841     (hd ss, map unmangled_type (tl ss))
   842   end
   843 
   844 fun introduce_proxies type_enc =
   845   let
   846     fun tweak_ho_quant ho_quant T [IAbs _] = IConst (`I ho_quant, T, [])
   847       | tweak_ho_quant ho_quant (T as Type (_, [p_T as Type (_, [x_T, _]), _]))
   848                        _ =
   849         (* Eta-expand "!!" and "??", to work around LEO-II 1.2.8 parser
   850            limitation. This works in conjuction with special code in
   851            "ATP_Problem" that uses the syntactic sugar "!" and "?" whenever
   852            possible. *)
   853         IAbs ((`I "P", p_T),
   854               IApp (IConst (`I ho_quant, T, []),
   855                     IAbs ((`I "X", x_T),
   856                           IApp (IConst (`I "P", p_T, []),
   857                                 IConst (`I "X", x_T, [])))))
   858       | tweak_ho_quant _ _ _ = raise Fail "unexpected type for quantifier"
   859     fun intro top_level args (IApp (tm1, tm2)) =
   860         IApp (intro top_level (tm2 :: args) tm1, intro false [] tm2)
   861       | intro top_level args (IConst (name as (s, _), T, T_args)) =
   862         (case proxify_const s of
   863            SOME proxy_base =>
   864            if top_level orelse is_type_enc_higher_order type_enc then
   865              case (top_level, s) of
   866                (_, "c_False") => IConst (`I tptp_false, T, [])
   867              | (_, "c_True") => IConst (`I tptp_true, T, [])
   868              | (false, "c_Not") => IConst (`I tptp_not, T, [])
   869              | (false, "c_conj") => IConst (`I tptp_and, T, [])
   870              | (false, "c_disj") => IConst (`I tptp_or, T, [])
   871              | (false, "c_implies") => IConst (`I tptp_implies, T, [])
   872              | (false, "c_All") => tweak_ho_quant tptp_ho_forall T args
   873              | (false, "c_Ex") => tweak_ho_quant tptp_ho_exists T args
   874              | (false, s) =>
   875                if is_tptp_equal s andalso length args = 2 then
   876                  IConst (`I tptp_equal, T, [])
   877                else
   878                  (* Use a proxy even for partially applied THF equality, because
   879                     the LEO-II and Satallax parsers complain about not being
   880                     able to infer the type of "=". *)
   881                  IConst (proxy_base |>> prefix const_prefix, T, T_args)
   882              | _ => IConst (name, T, [])
   883            else
   884              IConst (proxy_base |>> prefix const_prefix, T, T_args)
   885           | NONE => IConst (name, T, T_args))
   886       | intro _ _ (IAbs (bound, tm)) = IAbs (bound, intro false [] tm)
   887       | intro _ _ tm = tm
   888   in intro true [] end
   889 
   890 fun iformula_from_prop thy type_enc eq_as_iff =
   891   let
   892     fun do_term bs t atomic_types =
   893       iterm_from_term thy bs (Envir.eta_contract t)
   894       |>> (introduce_proxies type_enc #> AAtom)
   895       ||> union (op =) atomic_types
   896     fun do_quant bs q pos s T t' =
   897       let
   898         val s = singleton (Name.variant_list (map fst bs)) s
   899         val universal = Option.map (q = AExists ? not) pos
   900         val name =
   901           s |> `(case universal of
   902                    SOME true => make_all_bound_var
   903                  | SOME false => make_exist_bound_var
   904                  | NONE => make_bound_var)
   905       in
   906         do_formula ((s, (name, T)) :: bs) pos t'
   907         #>> mk_aquant q [(name, SOME T)]
   908       end
   909     and do_conn bs c pos1 t1 pos2 t2 =
   910       do_formula bs pos1 t1 ##>> do_formula bs pos2 t2 #>> uncurry (mk_aconn c)
   911     and do_formula bs pos t =
   912       case t of
   913         @{const Trueprop} $ t1 => do_formula bs pos t1
   914       | @{const Not} $ t1 => do_formula bs (Option.map not pos) t1 #>> mk_anot
   915       | Const (@{const_name All}, _) $ Abs (s, T, t') =>
   916         do_quant bs AForall pos s T t'
   917       | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
   918         do_quant bs AExists pos s T t'
   919       | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd pos t1 pos t2
   920       | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr pos t1 pos t2
   921       | @{const HOL.implies} $ t1 $ t2 =>
   922         do_conn bs AImplies (Option.map not pos) t1 pos t2
   923       | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
   924         if eq_as_iff then do_conn bs AIff NONE t1 NONE t2 else do_term bs t
   925       | _ => do_term bs t
   926   in do_formula [] end
   927 
   928 fun presimplify_term _ [] t = t
   929   | presimplify_term ctxt presimp_consts t =
   930     t |> exists_Const (member (op =) presimp_consts o fst) t
   931          ? (Skip_Proof.make_thm (Proof_Context.theory_of ctxt)
   932             #> Meson.presimplify ctxt
   933             #> prop_of)
   934 
   935 fun concealed_bound_name j = atp_weak_prefix ^ string_of_int j
   936 fun conceal_bounds Ts t =
   937   subst_bounds (map (Free o apfst concealed_bound_name)
   938                     (0 upto length Ts - 1 ~~ Ts), t)
   939 fun reveal_bounds Ts =
   940   subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
   941                     (0 upto length Ts - 1 ~~ Ts))
   942 
   943 fun is_fun_equality (@{const_name HOL.eq},
   944                      Type (_, [Type (@{type_name fun}, _), _])) = true
   945   | is_fun_equality _ = false
   946 
   947 fun extensionalize_term ctxt t =
   948   if exists_Const is_fun_equality t then
   949     let val thy = Proof_Context.theory_of ctxt in
   950       t |> cterm_of thy |> Meson.extensionalize_conv ctxt
   951         |> prop_of |> Logic.dest_equals |> snd
   952     end
   953   else
   954     t
   955 
   956 fun simple_translate_lambdas do_lambdas ctxt t =
   957   let val thy = Proof_Context.theory_of ctxt in
   958     if Meson.is_fol_term thy t then
   959       t
   960     else
   961       let
   962         fun aux Ts t =
   963           case t of
   964             @{const Not} $ t1 => @{const Not} $ aux Ts t1
   965           | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
   966             t0 $ Abs (s, T, aux (T :: Ts) t')
   967           | (t0 as Const (@{const_name All}, _)) $ t1 =>
   968             aux Ts (t0 $ eta_expand Ts t1 1)
   969           | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
   970             t0 $ Abs (s, T, aux (T :: Ts) t')
   971           | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
   972             aux Ts (t0 $ eta_expand Ts t1 1)
   973           | (t0 as @{const HOL.conj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
   974           | (t0 as @{const HOL.disj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
   975           | (t0 as @{const HOL.implies}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
   976           | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
   977               $ t1 $ t2 =>
   978             t0 $ aux Ts t1 $ aux Ts t2
   979           | _ =>
   980             if not (exists_subterm (fn Abs _ => true | _ => false) t) then t
   981             else t |> Envir.eta_contract |> do_lambdas ctxt Ts
   982         val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
   983       in t |> aux [] |> singleton (Variable.export_terms ctxt' ctxt) end
   984   end
   985 
   986 fun do_cheaply_conceal_lambdas Ts (t1 $ t2) =
   987     do_cheaply_conceal_lambdas Ts t1
   988     $ do_cheaply_conceal_lambdas Ts t2
   989   | do_cheaply_conceal_lambdas Ts (Abs (_, T, t)) =
   990     Free (polymorphic_free_prefix ^ serial_string (),
   991           T --> fastype_of1 (T :: Ts, t))
   992   | do_cheaply_conceal_lambdas _ t = t
   993 
   994 fun do_introduce_combinators ctxt Ts t =
   995   let val thy = Proof_Context.theory_of ctxt in
   996     t |> conceal_bounds Ts
   997       |> cterm_of thy
   998       |> Meson_Clausify.introduce_combinators_in_cterm
   999       |> prop_of |> Logic.dest_equals |> snd
  1000       |> reveal_bounds Ts
  1001   end
  1002   (* A type variable of sort "{}" will make abstraction fail. *)
  1003   handle THM _ => t |> do_cheaply_conceal_lambdas Ts
  1004 val introduce_combinators = simple_translate_lambdas do_introduce_combinators
  1005 
  1006 fun preprocess_abstractions_in_terms trans_lambdas facts =
  1007   let
  1008     val (facts, lambda_ts) =
  1009       facts |> map (snd o snd) |> trans_lambdas 
  1010             |>> map2 (fn (name, (kind, _)) => fn t => (name, (kind, t))) facts
  1011     val lambda_facts =
  1012       map2 (fn t => fn j =>
  1013                ((lambda_fact_prefix ^ Int.toString j, Helper), (Axiom, t)))
  1014            lambda_ts (1 upto length lambda_ts)
  1015   in (facts, lambda_facts) end
  1016 
  1017 (* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
  1018    same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
  1019 fun freeze_term t =
  1020   let
  1021     fun aux (t $ u) = aux t $ aux u
  1022       | aux (Abs (s, T, t)) = Abs (s, T, aux t)
  1023       | aux (Var ((s, i), T)) =
  1024         Free (atp_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
  1025       | aux t = t
  1026   in t |> exists_subterm is_Var t ? aux end
  1027 
  1028 fun presimp_prop ctxt presimp_consts t =
  1029   let
  1030     val thy = Proof_Context.theory_of ctxt
  1031     val t = t |> Envir.beta_eta_contract
  1032               |> transform_elim_prop
  1033               |> Object_Logic.atomize_term thy
  1034     val need_trueprop = (fastype_of t = @{typ bool})
  1035   in
  1036     t |> need_trueprop ? HOLogic.mk_Trueprop
  1037       |> Raw_Simplifier.rewrite_term thy (Meson.unfold_set_const_simps ctxt) []
  1038       |> extensionalize_term ctxt
  1039       |> presimplify_term ctxt presimp_consts
  1040       |> perhaps (try (HOLogic.dest_Trueprop))
  1041   end
  1042 
  1043 (* making fact and conjecture formulas *)
  1044 fun make_formula thy type_enc eq_as_iff name loc kind t =
  1045   let
  1046     val (iformula, atomic_types) =
  1047       iformula_from_prop thy type_enc eq_as_iff (SOME (kind <> Conjecture)) t []
  1048   in
  1049     {name = name, locality = loc, kind = kind, iformula = iformula,
  1050      atomic_types = atomic_types}
  1051   end
  1052 
  1053 fun make_fact ctxt format type_enc eq_as_iff ((name, loc), t) =
  1054   let val thy = Proof_Context.theory_of ctxt in
  1055     case t |> make_formula thy type_enc (eq_as_iff andalso format <> CNF) name
  1056                            loc Axiom of
  1057       formula as {iformula = AAtom (IConst ((s, _), _, _)), ...} =>
  1058       if s = tptp_true then NONE else SOME formula
  1059     | formula => SOME formula
  1060   end
  1061 
  1062 fun make_conjecture ctxt format type_enc ps =
  1063   let
  1064     val thy = Proof_Context.theory_of ctxt
  1065     val last = length ps - 1
  1066   in
  1067     map2 (fn j => fn ((name, loc), (kind, t)) =>
  1068              t |> make_formula thy type_enc (format <> CNF) name loc kind
  1069                |> (j <> last) = (kind = Conjecture) ? update_iformula mk_anot)
  1070          (0 upto last) ps
  1071   end
  1072 
  1073 (** Finite and infinite type inference **)
  1074 
  1075 type monotonicity_info =
  1076   {maybe_finite_Ts : typ list,
  1077    surely_finite_Ts : typ list,
  1078    maybe_infinite_Ts : typ list,
  1079    surely_infinite_Ts : typ list,
  1080    maybe_nonmono_Ts : typ list}
  1081 
  1082 (* These types witness that the type classes they belong to allow infinite
  1083    models and hence that any types with these type classes is monotonic. *)
  1084 val known_infinite_types =
  1085   [@{typ nat}, Type ("Int.int", []), @{typ "nat => bool"}]
  1086 
  1087 fun is_type_surely_infinite' ctxt soundness cached_Ts T =
  1088   (* Unlike virtually any other polymorphic fact whose type variables can be
  1089      instantiated by a known infinite type, extensionality actually encodes a
  1090      cardinality constraints. *)
  1091   soundness <> Sound andalso
  1092   is_type_surely_infinite ctxt (soundness = Unsound) cached_Ts T
  1093 
  1094 (* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
  1095    dangerous because their "exhaust" properties can easily lead to unsound ATP
  1096    proofs. On the other hand, all HOL infinite types can be given the same
  1097    models in first-order logic (via Löwenheim-Skolem). *)
  1098 
  1099 fun should_encode_type _ (_ : monotonicity_info) All_Types _ = true
  1100   | should_encode_type ctxt {maybe_finite_Ts, surely_infinite_Ts,
  1101                              maybe_nonmono_Ts, ...}
  1102                        (Noninf_Nonmono_Types soundness) T =
  1103     exists (type_instance ctxt T orf type_generalization ctxt T)
  1104            maybe_nonmono_Ts andalso
  1105     not (exists (type_instance ctxt T) surely_infinite_Ts orelse
  1106          (not (member (type_aconv ctxt) maybe_finite_Ts T) andalso
  1107           is_type_surely_infinite' ctxt soundness surely_infinite_Ts T))
  1108   | should_encode_type ctxt {surely_finite_Ts, maybe_infinite_Ts,
  1109                              maybe_nonmono_Ts, ...}
  1110                        Fin_Nonmono_Types T =
  1111     exists (type_instance ctxt T orf type_generalization ctxt T)
  1112            maybe_nonmono_Ts andalso
  1113     (exists (type_instance ctxt T) surely_finite_Ts orelse
  1114      (not (member (type_aconv ctxt) maybe_infinite_Ts T) andalso
  1115       is_type_surely_finite ctxt T))
  1116   | should_encode_type _ _ _ _ = false
  1117 
  1118 fun should_guard_type ctxt mono (Guards (_, level, uniformity)) should_guard_var
  1119                       T =
  1120     (uniformity = Uniform orelse should_guard_var ()) andalso
  1121     should_encode_type ctxt mono level T
  1122   | should_guard_type _ _ _ _ _ = false
  1123 
  1124 fun is_maybe_universal_var (IConst ((s, _), _, _)) =
  1125     String.isPrefix bound_var_prefix s orelse
  1126     String.isPrefix all_bound_var_prefix s
  1127   | is_maybe_universal_var (IVar _) = true
  1128   | is_maybe_universal_var _ = false
  1129 
  1130 datatype tag_site =
  1131   Top_Level of bool option |
  1132   Eq_Arg of bool option |
  1133   Elsewhere
  1134 
  1135 fun should_tag_with_type _ _ _ (Top_Level _) _ _ = false
  1136   | should_tag_with_type ctxt mono (Tags (_, level, uniformity)) site u T =
  1137     (case uniformity of
  1138        Uniform => should_encode_type ctxt mono level T
  1139      | Nonuniform =>
  1140        case (site, is_maybe_universal_var u) of
  1141          (Eq_Arg _, true) => should_encode_type ctxt mono level T
  1142        | _ => false)
  1143   | should_tag_with_type _ _ _ _ _ _ = false
  1144 
  1145 fun homogenized_type ctxt mono level =
  1146   let
  1147     val should_encode = should_encode_type ctxt mono level
  1148     fun homo 0 T = if should_encode T then T else homo_infinite_type
  1149       | homo ary (Type (@{type_name fun}, [T1, T2])) =
  1150         homo 0 T1 --> homo (ary - 1) T2
  1151       | homo _ _ = raise Fail "expected function type"
  1152   in homo end
  1153 
  1154 (** predicators and application operators **)
  1155 
  1156 type sym_info =
  1157   {pred_sym : bool, min_ary : int, max_ary : int, types : typ list}
  1158 
  1159 fun add_iterm_syms_to_table ctxt explicit_apply =
  1160   let
  1161     fun consider_var_arity const_T var_T max_ary =
  1162       let
  1163         fun iter ary T =
  1164           if ary = max_ary orelse type_instance ctxt var_T T orelse
  1165              type_instance ctxt T var_T then
  1166             ary
  1167           else
  1168             iter (ary + 1) (range_type T)
  1169       in iter 0 const_T end
  1170     fun add_universal_var T (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
  1171       if explicit_apply = NONE andalso
  1172          (can dest_funT T orelse T = @{typ bool}) then
  1173         let
  1174           val bool_vars' = bool_vars orelse body_type T = @{typ bool}
  1175           fun repair_min_arity {pred_sym, min_ary, max_ary, types} =
  1176             {pred_sym = pred_sym andalso not bool_vars',
  1177              min_ary = fold (fn T' => consider_var_arity T' T) types min_ary,
  1178              max_ary = max_ary, types = types}
  1179           val fun_var_Ts' =
  1180             fun_var_Ts |> can dest_funT T ? insert_type ctxt I T
  1181         in
  1182           if bool_vars' = bool_vars andalso
  1183              pointer_eq (fun_var_Ts', fun_var_Ts) then
  1184             accum
  1185           else
  1186             ((bool_vars', fun_var_Ts'), Symtab.map (K repair_min_arity) sym_tab)
  1187         end
  1188       else
  1189         accum
  1190     fun add top_level tm (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
  1191       let val (head, args) = strip_iterm_comb tm in
  1192         (case head of
  1193            IConst ((s, _), T, _) =>
  1194            if String.isPrefix bound_var_prefix s orelse
  1195               String.isPrefix all_bound_var_prefix s then
  1196              add_universal_var T accum
  1197            else if String.isPrefix exist_bound_var_prefix s then
  1198              accum
  1199            else
  1200              let val ary = length args in
  1201                ((bool_vars, fun_var_Ts),
  1202                 case Symtab.lookup sym_tab s of
  1203                   SOME {pred_sym, min_ary, max_ary, types} =>
  1204                   let
  1205                     val pred_sym =
  1206                       pred_sym andalso top_level andalso not bool_vars
  1207                     val types' = types |> insert_type ctxt I T
  1208                     val min_ary =
  1209                       if is_some explicit_apply orelse
  1210                          pointer_eq (types', types) then
  1211                         min_ary
  1212                       else
  1213                         fold (consider_var_arity T) fun_var_Ts min_ary
  1214                   in
  1215                     Symtab.update (s, {pred_sym = pred_sym,
  1216                                        min_ary = Int.min (ary, min_ary),
  1217                                        max_ary = Int.max (ary, max_ary),
  1218                                        types = types'})
  1219                                   sym_tab
  1220                   end
  1221                 | NONE =>
  1222                   let
  1223                     val pred_sym = top_level andalso not bool_vars
  1224                     val min_ary =
  1225                       case explicit_apply of
  1226                         SOME true => 0
  1227                       | SOME false => ary
  1228                       | NONE => fold (consider_var_arity T) fun_var_Ts ary
  1229                   in
  1230                     Symtab.update_new (s, {pred_sym = pred_sym,
  1231                                            min_ary = min_ary, max_ary = ary,
  1232                                            types = [T]})
  1233                                       sym_tab
  1234                   end)
  1235              end
  1236          | IVar (_, T) => add_universal_var T accum
  1237          | IAbs ((_, T), tm) => accum |> add_universal_var T |> add false tm
  1238          | _ => accum)
  1239         |> fold (add false) args
  1240       end
  1241   in add true end
  1242 fun add_fact_syms_to_table ctxt explicit_apply =
  1243   formula_fold NONE (K (add_iterm_syms_to_table ctxt explicit_apply))
  1244   |> fact_lift
  1245 
  1246 val tvar_a = TVar (("'a", 0), HOLogic.typeS)
  1247 
  1248 val default_sym_tab_entries : (string * sym_info) list =
  1249   (prefixed_predicator_name,
  1250    {pred_sym = true, min_ary = 1, max_ary = 1, types = []}) ::
  1251   (make_fixed_const @{const_name undefined},
  1252    {pred_sym = false, min_ary = 0, max_ary = 0, types = []}) ::
  1253   ([tptp_false, tptp_true]
  1254    |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, types = []})) @
  1255   ([tptp_equal, tptp_old_equal]
  1256    |> map (rpair {pred_sym = true, min_ary = 2, max_ary = 2, types = []}))
  1257 
  1258 fun sym_table_for_facts ctxt explicit_apply facts =
  1259   ((false, []), Symtab.empty)
  1260   |> fold (add_fact_syms_to_table ctxt explicit_apply) facts |> snd
  1261   |> fold Symtab.update default_sym_tab_entries
  1262 
  1263 fun min_arity_of sym_tab s =
  1264   case Symtab.lookup sym_tab s of
  1265     SOME ({min_ary, ...} : sym_info) => min_ary
  1266   | NONE =>
  1267     case strip_prefix_and_unascii const_prefix s of
  1268       SOME s =>
  1269       let val s = s |> unmangled_const_name |> invert_const in
  1270         if s = predicator_name then 1
  1271         else if s = app_op_name then 2
  1272         else if s = type_guard_name then 1
  1273         else 0
  1274       end
  1275     | NONE => 0
  1276 
  1277 (* True if the constant ever appears outside of the top-level position in
  1278    literals, or if it appears with different arities (e.g., because of different
  1279    type instantiations). If false, the constant always receives all of its
  1280    arguments and is used as a predicate. *)
  1281 fun is_pred_sym sym_tab s =
  1282   case Symtab.lookup sym_tab s of
  1283     SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
  1284     pred_sym andalso min_ary = max_ary
  1285   | NONE => false
  1286 
  1287 val predicator_combconst =
  1288   IConst (`make_fixed_const predicator_name, @{typ "bool => bool"}, [])
  1289 fun predicator tm = IApp (predicator_combconst, tm)
  1290 
  1291 fun introduce_predicators_in_iterm sym_tab tm =
  1292   case strip_iterm_comb tm of
  1293     (IConst ((s, _), _, _), _) =>
  1294     if is_pred_sym sym_tab s then tm else predicator tm
  1295   | _ => predicator tm
  1296 
  1297 fun list_app head args = fold (curry (IApp o swap)) args head
  1298 
  1299 val app_op = `make_fixed_const app_op_name
  1300 
  1301 fun explicit_app arg head =
  1302   let
  1303     val head_T = ityp_of head
  1304     val (arg_T, res_T) = dest_funT head_T
  1305     val explicit_app = IConst (app_op, head_T --> head_T, [arg_T, res_T])
  1306   in list_app explicit_app [head, arg] end
  1307 fun list_explicit_app head args = fold explicit_app args head
  1308 
  1309 fun introduce_explicit_apps_in_iterm sym_tab =
  1310   let
  1311     fun aux tm =
  1312       case strip_iterm_comb tm of
  1313         (head as IConst ((s, _), _, _), args) =>
  1314         args |> map aux
  1315              |> chop (min_arity_of sym_tab s)
  1316              |>> list_app head
  1317              |-> list_explicit_app
  1318       | (head, args) => list_explicit_app head (map aux args)
  1319   in aux end
  1320 
  1321 fun chop_fun 0 T = ([], T)
  1322   | chop_fun n (Type (@{type_name fun}, [dom_T, ran_T])) =
  1323     chop_fun (n - 1) ran_T |>> cons dom_T
  1324   | chop_fun _ _ = raise Fail "unexpected non-function"
  1325 
  1326 fun filter_type_args _ _ _ [] = []
  1327   | filter_type_args thy s arity T_args =
  1328     let
  1329       (* will throw "TYPE" for pseudo-constants *)
  1330       val U = if s = app_op_name then
  1331                 @{typ "('a => 'b) => 'a => 'b"} |> Logic.varifyT_global
  1332               else
  1333                 s |> Sign.the_const_type thy
  1334     in
  1335       case Term.add_tvarsT (U |> chop_fun arity |> snd) [] of
  1336         [] => []
  1337       | res_U_vars =>
  1338         let val U_args = (s, U) |> Sign.const_typargs thy in
  1339           U_args ~~ T_args
  1340           |> map (fn (U, T) =>
  1341                      if member (op =) res_U_vars (dest_TVar U) then T
  1342                      else dummyT)
  1343         end
  1344     end
  1345     handle TYPE _ => T_args
  1346 
  1347 fun enforce_type_arg_policy_in_iterm ctxt format type_enc =
  1348   let
  1349     val thy = Proof_Context.theory_of ctxt
  1350     fun aux arity (IApp (tm1, tm2)) = IApp (aux (arity + 1) tm1, aux 0 tm2)
  1351       | aux arity (IConst (name as (s, _), T, T_args)) =
  1352         (case strip_prefix_and_unascii const_prefix s of
  1353            NONE =>
  1354            (name, if level_of_type_enc type_enc = No_Types then [] else T_args)
  1355          | SOME s'' =>
  1356            let
  1357              val s'' = invert_const s''
  1358              fun filtered_T_args false = T_args
  1359                | filtered_T_args true = filter_type_args thy s'' arity T_args
  1360            in
  1361              case type_arg_policy type_enc s'' of
  1362                Explicit_Type_Args drop_args =>
  1363                (name, filtered_T_args drop_args)
  1364              | Mangled_Type_Args drop_args =>
  1365                (mangled_const_name format type_enc (filtered_T_args drop_args)
  1366                                    name, [])
  1367              | No_Type_Args => (name, [])
  1368            end)
  1369         |> (fn (name, T_args) => IConst (name, T, T_args))
  1370       | aux _ (IAbs (bound, tm)) = IAbs (bound, aux 0 tm)
  1371       | aux _ tm = tm
  1372   in aux 0 end
  1373 
  1374 fun repair_iterm ctxt format type_enc sym_tab =
  1375   not (is_type_enc_higher_order type_enc)
  1376   ? (introduce_explicit_apps_in_iterm sym_tab
  1377      #> introduce_predicators_in_iterm sym_tab)
  1378   #> enforce_type_arg_policy_in_iterm ctxt format type_enc
  1379 fun repair_fact ctxt format type_enc sym_tab =
  1380   update_iformula (formula_map (repair_iterm ctxt format type_enc sym_tab))
  1381 
  1382 (** Helper facts **)
  1383 
  1384 val not_ffalse = @{lemma "~ fFalse" by (unfold fFalse_def) fast}
  1385 val ftrue = @{lemma "fTrue" by (unfold fTrue_def) fast}
  1386 
  1387 (* The Boolean indicates that a fairly sound type encoding is needed. *)
  1388 val helper_table =
  1389   [(("COMBI", false), @{thms Meson.COMBI_def}),
  1390    (("COMBK", false), @{thms Meson.COMBK_def}),
  1391    (("COMBB", false), @{thms Meson.COMBB_def}),
  1392    (("COMBC", false), @{thms Meson.COMBC_def}),
  1393    (("COMBS", false), @{thms Meson.COMBS_def}),
  1394    ((predicator_name, false), [not_ffalse, ftrue]),
  1395    (("fFalse", false), [not_ffalse]),
  1396    (("fFalse", true), @{thms True_or_False}),
  1397    (("fTrue", false), [ftrue]),
  1398    (("fTrue", true), @{thms True_or_False}),
  1399    (("fNot", false),
  1400     @{thms fNot_def [THEN Meson.iff_to_disjD, THEN conjunct1]
  1401            fNot_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
  1402    (("fconj", false),
  1403     @{lemma "~ P | ~ Q | fconj P Q" "~ fconj P Q | P" "~ fconj P Q | Q"
  1404         by (unfold fconj_def) fast+}),
  1405    (("fdisj", false),
  1406     @{lemma "~ P | fdisj P Q" "~ Q | fdisj P Q" "~ fdisj P Q | P | Q"
  1407         by (unfold fdisj_def) fast+}),
  1408    (("fimplies", false),
  1409     @{lemma "P | fimplies P Q" "~ Q | fimplies P Q" "~ fimplies P Q | ~ P | Q"
  1410         by (unfold fimplies_def) fast+}),
  1411    (("fequal", true),
  1412     (* This is a lie: Higher-order equality doesn't need a sound type encoding.
  1413        However, this is done so for backward compatibility: Including the
  1414        equality helpers by default in Metis breaks a few existing proofs. *)
  1415     @{thms fequal_def [THEN Meson.iff_to_disjD, THEN conjunct1]
  1416            fequal_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
  1417    (* Partial characterization of "fAll" and "fEx". A complete characterization
  1418       would require the axiom of choice for replay with Metis. *)
  1419    (("fAll", false), [@{lemma "~ fAll P | P x" by (auto simp: fAll_def)}]),
  1420    (("fEx", false), [@{lemma "~ P x | fEx P" by (auto simp: fEx_def)}]),
  1421    (("If", true), @{thms if_True if_False True_or_False})]
  1422   |> map (apsnd (map zero_var_indexes))
  1423 
  1424 fun fo_literal_from_type_literal (TyLitVar (class, name)) =
  1425     (true, ATerm (class, [ATerm (name, [])]))
  1426   | fo_literal_from_type_literal (TyLitFree (class, name)) =
  1427     (true, ATerm (class, [ATerm (name, [])]))
  1428 
  1429 fun formula_from_fo_literal (pos, t) = AAtom t |> not pos ? mk_anot
  1430 
  1431 fun bound_tvars type_enc Ts =
  1432   mk_ahorn (map (formula_from_fo_literal o fo_literal_from_type_literal)
  1433                 (type_literals_for_types type_enc add_sorts_on_tvar Ts))
  1434 
  1435 fun eq_formula type_enc atomic_Ts pred_sym tm1 tm2 =
  1436   (if pred_sym then AConn (AIff, [AAtom tm1, AAtom tm2])
  1437    else AAtom (ATerm (`I tptp_equal, [tm1, tm2])))
  1438   |> bound_tvars type_enc atomic_Ts
  1439   |> close_formula_universally
  1440 
  1441 val type_tag = `make_fixed_const type_tag_name
  1442 
  1443 fun type_tag_idempotence_fact type_enc =
  1444   let
  1445     fun var s = ATerm (`I s, [])
  1446     fun tag tm = ATerm (type_tag, [var "A", tm])
  1447     val tagged_var = tag (var "X")
  1448   in
  1449     Formula (type_tag_idempotence_helper_name, Axiom,
  1450              eq_formula type_enc [] false (tag tagged_var) tagged_var,
  1451              isabelle_info simpN, NONE)
  1452   end
  1453 
  1454 fun should_specialize_helper type_enc t =
  1455   polymorphism_of_type_enc type_enc = Mangled_Monomorphic andalso
  1456   level_of_type_enc type_enc <> No_Types andalso
  1457   not (null (Term.hidden_polymorphism t))
  1458 
  1459 fun helper_facts_for_sym ctxt format type_enc (s, {types, ...} : sym_info) =
  1460   case strip_prefix_and_unascii const_prefix s of
  1461     SOME mangled_s =>
  1462     let
  1463       val thy = Proof_Context.theory_of ctxt
  1464       val unmangled_s = mangled_s |> unmangled_const_name
  1465       fun dub needs_fairly_sound j k =
  1466         (unmangled_s ^ "_" ^ string_of_int j ^ "_" ^ string_of_int k ^
  1467          (if mangled_s = unmangled_s then "" else "_" ^ ascii_of mangled_s) ^
  1468          (if needs_fairly_sound then typed_helper_suffix
  1469           else untyped_helper_suffix),
  1470          Helper)
  1471       fun dub_and_inst needs_fairly_sound (th, j) =
  1472         let val t = prop_of th in
  1473           if should_specialize_helper type_enc t then
  1474             map (fn T => specialize_type thy (invert_const unmangled_s, T) t)
  1475                 types
  1476           else
  1477             [t]
  1478         end
  1479         |> map (fn (k, t) => (dub needs_fairly_sound j k, t)) o tag_list 1
  1480       val make_facts = map_filter (make_fact ctxt format type_enc false)
  1481       val fairly_sound = is_type_enc_fairly_sound type_enc
  1482     in
  1483       helper_table
  1484       |> maps (fn ((helper_s, needs_fairly_sound), ths) =>
  1485                   if helper_s <> unmangled_s orelse
  1486                      (needs_fairly_sound andalso not fairly_sound) then
  1487                     []
  1488                   else
  1489                     ths ~~ (1 upto length ths)
  1490                     |> maps (dub_and_inst needs_fairly_sound)
  1491                     |> make_facts)
  1492     end
  1493   | NONE => []
  1494 fun helper_facts_for_sym_table ctxt format type_enc sym_tab =
  1495   Symtab.fold_rev (append o helper_facts_for_sym ctxt format type_enc) sym_tab
  1496                   []
  1497 
  1498 (***************************************************************)
  1499 (* Type Classes Present in the Axiom or Conjecture Clauses     *)
  1500 (***************************************************************)
  1501 
  1502 fun set_insert (x, s) = Symtab.update (x, ()) s
  1503 
  1504 fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
  1505 
  1506 (* Remove this trivial type class (FIXME: similar code elsewhere) *)
  1507 fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset
  1508 
  1509 fun classes_of_terms get_Ts =
  1510   map (map snd o get_Ts)
  1511   #> List.foldl add_classes Symtab.empty
  1512   #> delete_type #> Symtab.keys
  1513 
  1514 val tfree_classes_of_terms = classes_of_terms Misc_Legacy.term_tfrees
  1515 val tvar_classes_of_terms = classes_of_terms Misc_Legacy.term_tvars
  1516 
  1517 fun fold_type_constrs f (Type (s, Ts)) x =
  1518     fold (fold_type_constrs f) Ts (f (s, x))
  1519   | fold_type_constrs _ _ x = x
  1520 
  1521 (* Type constructors used to instantiate overloaded constants are the only ones
  1522    needed. *)
  1523 fun add_type_constrs_in_term thy =
  1524   let
  1525     fun add (Const (@{const_name Meson.skolem}, _) $ _) = I
  1526       | add (t $ u) = add t #> add u
  1527       | add (Const (x as (s, _))) =
  1528         if String.isPrefix skolem_const_prefix s then I
  1529         else x |> Sign.const_typargs thy |> fold (fold_type_constrs set_insert)
  1530       | add (Free (s, T)) =
  1531         if String.isPrefix polymorphic_free_prefix s then
  1532           T |> fold_type_constrs set_insert
  1533         else
  1534           I
  1535       | add (Abs (_, _, u)) = add u
  1536       | add _ = I
  1537   in add end
  1538 
  1539 fun type_constrs_of_terms thy ts =
  1540   Symtab.keys (fold (add_type_constrs_in_term thy) ts Symtab.empty)
  1541 
  1542 fun translate_formulas ctxt format prem_kind type_enc trans_lambdas preproc
  1543                        hyp_ts concl_t facts =
  1544   let
  1545     val thy = Proof_Context.theory_of ctxt
  1546     val presimp_consts = Meson.presimplified_consts ctxt
  1547     val fact_ts = facts |> map snd
  1548     (* Remove existing facts from the conjecture, as this can dramatically
  1549        boost an ATP's performance (for some reason). *)
  1550     val hyp_ts =
  1551       hyp_ts
  1552       |> map (fn t => if member (op aconv) fact_ts t then @{prop True} else t)
  1553     val facts = facts |> map (apsnd (pair Axiom))
  1554     val conjs =
  1555       map (pair prem_kind) hyp_ts @ [(Conjecture, concl_t)]
  1556       |> map2 (pair o rpair Local o string_of_int) (0 upto length hyp_ts)
  1557     val ((conjs, facts), lambdas) =
  1558       if preproc then
  1559         conjs @ facts
  1560         |> map (apsnd (apsnd (presimp_prop ctxt presimp_consts)))
  1561         |> preprocess_abstractions_in_terms trans_lambdas
  1562         |>> chop (length conjs)
  1563         |>> apfst (map (apsnd (apsnd freeze_term)))
  1564       else
  1565         ((conjs, facts), [])
  1566     val conjs = conjs |> make_conjecture ctxt format type_enc
  1567     val (fact_names, facts) =
  1568       facts
  1569       |> map_filter (fn (name, (_, t)) =>
  1570                         make_fact ctxt format type_enc true (name, t)
  1571                         |> Option.map (pair name))
  1572       |> ListPair.unzip
  1573     val lambdas =
  1574       lambdas |> map_filter (make_fact ctxt format type_enc true o apsnd snd)
  1575     val all_ts = concl_t :: hyp_ts @ fact_ts
  1576     val subs = tfree_classes_of_terms all_ts
  1577     val supers = tvar_classes_of_terms all_ts
  1578     val tycons = type_constrs_of_terms thy all_ts
  1579     val (supers, arity_clauses) =
  1580       if level_of_type_enc type_enc = No_Types then ([], [])
  1581       else make_arity_clauses thy tycons supers
  1582     val class_rel_clauses = make_class_rel_clauses thy subs supers
  1583   in
  1584     (fact_names |> map single,
  1585      (conjs, facts @ lambdas, class_rel_clauses, arity_clauses))
  1586   end
  1587 
  1588 val type_guard = `make_fixed_const type_guard_name
  1589 
  1590 fun type_guard_iterm ctxt format type_enc T tm =
  1591   IApp (IConst (type_guard, T --> @{typ bool}, [T])
  1592         |> enforce_type_arg_policy_in_iterm ctxt format type_enc, tm)
  1593 
  1594 fun is_var_positively_naked_in_term _ (SOME false) _ accum = accum
  1595   | is_var_positively_naked_in_term name _ (ATerm ((s, _), tms)) accum =
  1596     accum orelse (is_tptp_equal s andalso member (op =) tms (ATerm (name, [])))
  1597   | is_var_positively_naked_in_term _ _ _ _ = true
  1598 
  1599 fun should_guard_var_in_formula pos phi (SOME true) name =
  1600     formula_fold pos (is_var_positively_naked_in_term name) phi false
  1601   | should_guard_var_in_formula _ _ _ _ = true
  1602 
  1603 fun should_generate_tag_bound_decl _ _ _ (SOME true) _ = false
  1604   | should_generate_tag_bound_decl ctxt mono (Tags (_, level, Nonuniform)) _ T =
  1605     should_encode_type ctxt mono level T
  1606   | should_generate_tag_bound_decl _ _ _ _ _ = false
  1607 
  1608 fun mk_aterm format type_enc name T_args args =
  1609   ATerm (name, map_filter (ho_term_for_type_arg format type_enc) T_args @ args)
  1610 
  1611 fun tag_with_type ctxt format mono type_enc pos T tm =
  1612   IConst (type_tag, T --> T, [T])
  1613   |> enforce_type_arg_policy_in_iterm ctxt format type_enc
  1614   |> ho_term_from_iterm ctxt format mono type_enc (Top_Level pos)
  1615   |> (fn ATerm (s, tms) => ATerm (s, tms @ [tm])
  1616        | _ => raise Fail "unexpected lambda-abstraction")
  1617 and ho_term_from_iterm ctxt format mono type_enc =
  1618   let
  1619     fun aux site u =
  1620       let
  1621         val (head, args) = strip_iterm_comb u
  1622         val pos =
  1623           case site of
  1624             Top_Level pos => pos
  1625           | Eq_Arg pos => pos
  1626           | Elsewhere => NONE
  1627         val t =
  1628           case head of
  1629             IConst (name as (s, _), _, T_args) =>
  1630             let
  1631               val arg_site = if is_tptp_equal s then Eq_Arg pos else Elsewhere
  1632             in
  1633               mk_aterm format type_enc name T_args (map (aux arg_site) args)
  1634             end
  1635           | IVar (name, _) =>
  1636             mk_aterm format type_enc name [] (map (aux Elsewhere) args)
  1637           | IAbs ((name, T), tm) =>
  1638             AAbs ((name, ho_type_from_typ format type_enc true 0 T),
  1639                   aux Elsewhere tm)
  1640           | IApp _ => raise Fail "impossible \"IApp\""
  1641         val T = ityp_of u
  1642       in
  1643         t |> (if should_tag_with_type ctxt mono type_enc site u T then
  1644                 tag_with_type ctxt format mono type_enc pos T
  1645               else
  1646                 I)
  1647       end
  1648   in aux end
  1649 and formula_from_iformula ctxt format mono type_enc should_guard_var =
  1650   let
  1651     val do_term = ho_term_from_iterm ctxt format mono type_enc o Top_Level
  1652     val do_bound_type =
  1653       case type_enc of
  1654         Simple_Types (_, level) =>
  1655         homogenized_type ctxt mono level 0
  1656         #> ho_type_from_typ format type_enc false 0 #> SOME
  1657       | _ => K NONE
  1658     fun do_out_of_bound_type pos phi universal (name, T) =
  1659       if should_guard_type ctxt mono type_enc
  1660              (fn () => should_guard_var pos phi universal name) T then
  1661         IVar (name, T)
  1662         |> type_guard_iterm ctxt format type_enc T
  1663         |> do_term pos |> AAtom |> SOME
  1664       else if should_generate_tag_bound_decl ctxt mono type_enc universal T then
  1665         let
  1666           val var = ATerm (name, [])
  1667           val tagged_var =
  1668             ATerm (type_tag, [ho_term_from_typ format type_enc T, var])
  1669         in SOME (AAtom (ATerm (`I tptp_equal, [tagged_var, var]))) end
  1670       else
  1671         NONE
  1672     fun do_formula pos (AQuant (q, xs, phi)) =
  1673         let
  1674           val phi = phi |> do_formula pos
  1675           val universal = Option.map (q = AExists ? not) pos
  1676         in
  1677           AQuant (q, xs |> map (apsnd (fn NONE => NONE
  1678                                         | SOME T => do_bound_type T)),
  1679                   (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
  1680                       (map_filter
  1681                            (fn (_, NONE) => NONE
  1682                              | (s, SOME T) =>
  1683                                do_out_of_bound_type pos phi universal (s, T))
  1684                            xs)
  1685                       phi)
  1686         end
  1687       | do_formula pos (AConn conn) = aconn_map pos do_formula conn
  1688       | do_formula pos (AAtom tm) = AAtom (do_term pos tm)
  1689   in do_formula end
  1690 
  1691 (* Each fact is given a unique fact number to avoid name clashes (e.g., because
  1692    of monomorphization). The TPTP explicitly forbids name clashes, and some of
  1693    the remote provers might care. *)
  1694 fun formula_line_for_fact ctxt format prefix encode freshen pos mono type_enc
  1695                           (j, {name, locality, kind, iformula, atomic_types}) =
  1696   (prefix ^ (if freshen then string_of_int j ^ "_" else "") ^ encode name, kind,
  1697    iformula
  1698    |> close_iformula_universally
  1699    |> formula_from_iformula ctxt format mono type_enc
  1700                             should_guard_var_in_formula
  1701                             (if pos then SOME true else NONE)
  1702    |> bound_tvars type_enc atomic_types
  1703    |> close_formula_universally,
  1704    NONE,
  1705    case locality of
  1706      Intro => isabelle_info introN
  1707    | Elim => isabelle_info elimN
  1708    | Simp => isabelle_info simpN
  1709    | _ => NONE)
  1710   |> Formula
  1711 
  1712 fun formula_line_for_class_rel_clause ({name, subclass, superclass, ...}
  1713                                        : class_rel_clause) =
  1714   let val ty_arg = ATerm (`I "T", []) in
  1715     Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
  1716              AConn (AImplies, [AAtom (ATerm (subclass, [ty_arg])),
  1717                                AAtom (ATerm (superclass, [ty_arg]))])
  1718              |> close_formula_universally, isabelle_info introN, NONE)
  1719   end
  1720 
  1721 fun fo_literal_from_arity_literal (TConsLit (c, t, args)) =
  1722     (true, ATerm (c, [ATerm (t, map (fn arg => ATerm (arg, [])) args)]))
  1723   | fo_literal_from_arity_literal (TVarLit (c, sort)) =
  1724     (false, ATerm (c, [ATerm (sort, [])]))
  1725 
  1726 fun formula_line_for_arity_clause ({name, prem_lits, concl_lits, ...}
  1727                                    : arity_clause) =
  1728   Formula (arity_clause_prefix ^ name, Axiom,
  1729            mk_ahorn (map (formula_from_fo_literal o apfst not
  1730                           o fo_literal_from_arity_literal) prem_lits)
  1731                     (formula_from_fo_literal
  1732                          (fo_literal_from_arity_literal concl_lits))
  1733            |> close_formula_universally, isabelle_info introN, NONE)
  1734 
  1735 fun formula_line_for_conjecture ctxt format mono type_enc
  1736         ({name, kind, iformula, atomic_types, ...} : translated_formula) =
  1737   Formula (conjecture_prefix ^ name, kind,
  1738            formula_from_iformula ctxt format mono type_enc
  1739                should_guard_var_in_formula (SOME false)
  1740                (close_iformula_universally iformula)
  1741            |> bound_tvars type_enc atomic_types
  1742            |> close_formula_universally, NONE, NONE)
  1743 
  1744 fun free_type_literals type_enc ({atomic_types, ...} : translated_formula) =
  1745   atomic_types |> type_literals_for_types type_enc add_sorts_on_tfree
  1746                |> map fo_literal_from_type_literal
  1747 
  1748 fun formula_line_for_free_type j lit =
  1749   Formula (tfree_clause_prefix ^ string_of_int j, Hypothesis,
  1750            formula_from_fo_literal lit, NONE, NONE)
  1751 fun formula_lines_for_free_types type_enc facts =
  1752   let
  1753     val litss = map (free_type_literals type_enc) facts
  1754     val lits = fold (union (op =)) litss []
  1755   in map2 formula_line_for_free_type (0 upto length lits - 1) lits end
  1756 
  1757 (** Symbol declarations **)
  1758 
  1759 fun should_declare_sym type_enc pred_sym s =
  1760   (case type_enc of
  1761      Guards _ => not pred_sym
  1762    | _ => true) andalso
  1763   is_tptp_user_symbol s
  1764 
  1765 fun sym_decl_table_for_facts ctxt format type_enc repaired_sym_tab
  1766                              (conjs, facts) =
  1767   let
  1768     fun add_iterm_syms in_conj tm =
  1769       let val (head, args) = strip_iterm_comb tm in
  1770         (case head of
  1771            IConst ((s, s'), T, T_args) =>
  1772            let val pred_sym = is_pred_sym repaired_sym_tab s in
  1773              if should_declare_sym type_enc pred_sym s then
  1774                Symtab.map_default (s, [])
  1775                    (insert_type ctxt #3 (s', T_args, T, pred_sym, length args,
  1776                                          in_conj))
  1777              else
  1778                I
  1779            end
  1780          | IAbs (_, tm) => add_iterm_syms in_conj tm
  1781          | _ => I)
  1782         #> fold (add_iterm_syms in_conj) args
  1783       end
  1784     fun add_fact_syms in_conj =
  1785       fact_lift (formula_fold NONE (K (add_iterm_syms in_conj)))
  1786     fun add_formula_var_types (AQuant (_, xs, phi)) =
  1787         fold (fn (_, SOME T) => insert_type ctxt I T | _ => I) xs
  1788         #> add_formula_var_types phi
  1789       | add_formula_var_types (AConn (_, phis)) =
  1790         fold add_formula_var_types phis
  1791       | add_formula_var_types _ = I
  1792     fun var_types () =
  1793       if polymorphism_of_type_enc type_enc = Polymorphic then [tvar_a]
  1794       else fold (fact_lift add_formula_var_types) (conjs @ facts) []
  1795     fun add_undefined_const T =
  1796       let
  1797         val (s, s') =
  1798           `make_fixed_const @{const_name undefined}
  1799           |> (case type_arg_policy type_enc @{const_name undefined} of
  1800                 Mangled_Type_Args _ => mangled_const_name format type_enc [T]
  1801               | _ => I)
  1802       in
  1803         Symtab.map_default (s, [])
  1804                            (insert_type ctxt #3 (s', [T], T, false, 0, false))
  1805       end
  1806   in
  1807     Symtab.empty
  1808     |> is_type_enc_fairly_sound type_enc
  1809        ? (fold (add_fact_syms true) conjs
  1810           #> fold (add_fact_syms false) facts
  1811           #> (case type_enc of
  1812                 Simple_Types _ => I
  1813               | _ => fold add_undefined_const (var_types ())))
  1814   end
  1815 
  1816 (* We add "bool" in case the helper "True_or_False" is included later. *)
  1817 val default_mono =
  1818   {maybe_finite_Ts = [@{typ bool}],
  1819    surely_finite_Ts = [@{typ bool}],
  1820    maybe_infinite_Ts = known_infinite_types,
  1821    surely_infinite_Ts = known_infinite_types,
  1822    maybe_nonmono_Ts = [@{typ bool}]}
  1823 
  1824 (* This inference is described in section 2.3 of Claessen et al.'s "Sorting it
  1825    out with monotonicity" paper presented at CADE 2011. *)
  1826 fun add_iterm_mononotonicity_info _ _ (SOME false) _ mono = mono
  1827   | add_iterm_mononotonicity_info ctxt level _
  1828         (IApp (IApp (IConst ((s, _), Type (_, [T, _]), _), tm1), tm2))
  1829         (mono as {maybe_finite_Ts, surely_finite_Ts, maybe_infinite_Ts,
  1830                   surely_infinite_Ts, maybe_nonmono_Ts}) =
  1831     if is_tptp_equal s andalso exists is_maybe_universal_var [tm1, tm2] then
  1832       case level of
  1833         Noninf_Nonmono_Types soundness =>
  1834         if exists (type_instance ctxt T) surely_infinite_Ts orelse
  1835            member (type_aconv ctxt) maybe_finite_Ts T then
  1836           mono
  1837         else if is_type_surely_infinite' ctxt soundness surely_infinite_Ts
  1838                                          T then
  1839           {maybe_finite_Ts = maybe_finite_Ts,
  1840            surely_finite_Ts = surely_finite_Ts,
  1841            maybe_infinite_Ts = maybe_infinite_Ts,
  1842            surely_infinite_Ts = surely_infinite_Ts |> insert_type ctxt I T,
  1843            maybe_nonmono_Ts = maybe_nonmono_Ts}
  1844         else
  1845           {maybe_finite_Ts = maybe_finite_Ts |> insert (type_aconv ctxt) T,
  1846            surely_finite_Ts = surely_finite_Ts,
  1847            maybe_infinite_Ts = maybe_infinite_Ts,
  1848            surely_infinite_Ts = surely_infinite_Ts,
  1849            maybe_nonmono_Ts = maybe_nonmono_Ts |> insert_type ctxt I T}
  1850       | Fin_Nonmono_Types =>
  1851         if exists (type_instance ctxt T) surely_finite_Ts orelse
  1852            member (type_aconv ctxt) maybe_infinite_Ts T then
  1853           mono
  1854         else if is_type_surely_finite ctxt T then
  1855           {maybe_finite_Ts = maybe_finite_Ts,
  1856            surely_finite_Ts = surely_finite_Ts |> insert_type ctxt I T,
  1857            maybe_infinite_Ts = maybe_infinite_Ts,
  1858            surely_infinite_Ts = surely_infinite_Ts,
  1859            maybe_nonmono_Ts = maybe_nonmono_Ts |> insert_type ctxt I T}
  1860         else
  1861           {maybe_finite_Ts = maybe_finite_Ts,
  1862            surely_finite_Ts = surely_finite_Ts,
  1863            maybe_infinite_Ts = maybe_infinite_Ts |> insert (type_aconv ctxt) T,
  1864            surely_infinite_Ts = surely_infinite_Ts,
  1865            maybe_nonmono_Ts = maybe_nonmono_Ts}
  1866       | _ => mono
  1867     else
  1868       mono
  1869   | add_iterm_mononotonicity_info _ _ _ _ mono = mono
  1870 fun add_fact_mononotonicity_info ctxt level
  1871         ({kind, iformula, ...} : translated_formula) =
  1872   formula_fold (SOME (kind <> Conjecture))
  1873                (add_iterm_mononotonicity_info ctxt level) iformula
  1874 fun mononotonicity_info_for_facts ctxt type_enc facts =
  1875   let val level = level_of_type_enc type_enc in
  1876     default_mono
  1877     |> is_type_level_monotonicity_based level
  1878        ? fold (add_fact_mononotonicity_info ctxt level) facts
  1879   end
  1880 
  1881 fun formula_line_for_guards_mono_type ctxt format mono type_enc T =
  1882   Formula (guards_sym_formula_prefix ^
  1883            ascii_of (mangled_type format type_enc T),
  1884            Axiom,
  1885            IConst (`make_bound_var "X", T, [])
  1886            |> type_guard_iterm ctxt format type_enc T
  1887            |> AAtom
  1888            |> formula_from_iformula ctxt format mono type_enc
  1889                                     (K (K (K (K true)))) (SOME true)
  1890            |> bound_tvars type_enc (atyps_of T)
  1891            |> close_formula_universally,
  1892            isabelle_info introN, NONE)
  1893 
  1894 fun formula_line_for_tags_mono_type ctxt format mono type_enc T =
  1895   let val x_var = ATerm (`make_bound_var "X", []) in
  1896     Formula (tags_sym_formula_prefix ^
  1897              ascii_of (mangled_type format type_enc T),
  1898              Axiom,
  1899              eq_formula type_enc (atyps_of T) false
  1900                         (tag_with_type ctxt format mono type_enc NONE T x_var)
  1901                         x_var,
  1902              isabelle_info simpN, NONE)
  1903   end
  1904 
  1905 fun problem_lines_for_mono_types ctxt format mono type_enc Ts =
  1906   case type_enc of
  1907     Simple_Types _ => []
  1908   | Guards _ =>
  1909     map (formula_line_for_guards_mono_type ctxt format mono type_enc) Ts
  1910   | Tags _ => map (formula_line_for_tags_mono_type ctxt format mono type_enc) Ts
  1911 
  1912 fun decl_line_for_sym ctxt format mono type_enc s
  1913                       (s', T_args, T, pred_sym, ary, _) =
  1914   let
  1915     val (T_arg_Ts, level) =
  1916       case type_enc of
  1917         Simple_Types (_, level) => ([], level)
  1918       | _ => (replicate (length T_args) homo_infinite_type, No_Types)
  1919   in
  1920     Decl (sym_decl_prefix ^ s, (s, s'),
  1921           (T_arg_Ts ---> (T |> homogenized_type ctxt mono level ary))
  1922           |> ho_type_from_typ format type_enc pred_sym (length T_arg_Ts + ary))
  1923   end
  1924 
  1925 fun formula_line_for_guards_sym_decl ctxt format conj_sym_kind mono type_enc n s
  1926                                      j (s', T_args, T, _, ary, in_conj) =
  1927   let
  1928     val (kind, maybe_negate) =
  1929       if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
  1930       else (Axiom, I)
  1931     val (arg_Ts, res_T) = chop_fun ary T
  1932     val num_args = length arg_Ts
  1933     val bound_names =
  1934       1 upto num_args |> map (`I o make_bound_var o string_of_int)
  1935     val bounds =
  1936       bound_names ~~ arg_Ts |> map (fn (name, T) => IConst (name, T, []))
  1937     val sym_needs_arg_types = exists (curry (op =) dummyT) T_args
  1938     fun should_keep_arg_type T =
  1939       sym_needs_arg_types andalso
  1940       should_guard_type ctxt mono type_enc (K true) T
  1941     val bound_Ts =
  1942       arg_Ts |> map (fn T => if should_keep_arg_type T then SOME T else NONE)
  1943   in
  1944     Formula (guards_sym_formula_prefix ^ s ^
  1945              (if n > 1 then "_" ^ string_of_int j else ""), kind,
  1946              IConst ((s, s'), T, T_args)
  1947              |> fold (curry (IApp o swap)) bounds
  1948              |> type_guard_iterm ctxt format type_enc res_T
  1949              |> AAtom |> mk_aquant AForall (bound_names ~~ bound_Ts)
  1950              |> formula_from_iformula ctxt format mono type_enc
  1951                                       (K (K (K (K true)))) (SOME true)
  1952              |> n > 1 ? bound_tvars type_enc (atyps_of T)
  1953              |> close_formula_universally
  1954              |> maybe_negate,
  1955              isabelle_info introN, NONE)
  1956   end
  1957 
  1958 fun formula_lines_for_nonuniform_tags_sym_decl ctxt format conj_sym_kind mono
  1959         type_enc n s (j, (s', T_args, T, pred_sym, ary, in_conj)) =
  1960   let
  1961     val ident_base =
  1962       tags_sym_formula_prefix ^ s ^
  1963       (if n > 1 then "_" ^ string_of_int j else "")
  1964     val (kind, maybe_negate) =
  1965       if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
  1966       else (Axiom, I)
  1967     val (arg_Ts, res_T) = chop_fun ary T
  1968     val bound_names =
  1969       1 upto length arg_Ts |> map (`I o make_bound_var o string_of_int)
  1970     val bounds = bound_names |> map (fn name => ATerm (name, []))
  1971     val cst = mk_aterm format type_enc (s, s') T_args
  1972     val eq = maybe_negate oo eq_formula type_enc (atyps_of T) pred_sym
  1973     val should_encode =
  1974       should_encode_type ctxt mono (level_of_type_enc type_enc)
  1975     val tag_with = tag_with_type ctxt format mono type_enc NONE
  1976     val add_formula_for_res =
  1977       if should_encode res_T then
  1978         cons (Formula (ident_base ^ "_res", kind,
  1979                        eq (tag_with res_T (cst bounds)) (cst bounds),
  1980                        isabelle_info simpN, NONE))
  1981       else
  1982         I
  1983     fun add_formula_for_arg k =
  1984       let val arg_T = nth arg_Ts k in
  1985         if should_encode arg_T then
  1986           case chop k bounds of
  1987             (bounds1, bound :: bounds2) =>
  1988             cons (Formula (ident_base ^ "_arg" ^ string_of_int (k + 1), kind,
  1989                            eq (cst (bounds1 @ tag_with arg_T bound :: bounds2))
  1990                               (cst bounds),
  1991                            isabelle_info simpN, NONE))
  1992           | _ => raise Fail "expected nonempty tail"
  1993         else
  1994           I
  1995       end
  1996   in
  1997     [] |> not pred_sym ? add_formula_for_res
  1998        |> fold add_formula_for_arg (ary - 1 downto 0)
  1999   end
  2000 
  2001 fun result_type_of_decl (_, _, T, _, ary, _) = chop_fun ary T |> snd
  2002 
  2003 fun problem_lines_for_sym_decls ctxt format conj_sym_kind mono type_enc
  2004                                 (s, decls) =
  2005   case type_enc of
  2006     Simple_Types _ =>
  2007     decls |> map (decl_line_for_sym ctxt format mono type_enc s)
  2008   | Guards (_, level, _) =>
  2009     let
  2010       val decls =
  2011         case decls of
  2012           decl :: (decls' as _ :: _) =>
  2013           let val T = result_type_of_decl decl in
  2014             if forall (type_generalization ctxt T o result_type_of_decl)
  2015                       decls' then
  2016               [decl]
  2017             else
  2018               decls
  2019           end
  2020         | _ => decls
  2021       val n = length decls
  2022       val decls =
  2023         decls |> filter (should_encode_type ctxt mono level
  2024                          o result_type_of_decl)
  2025     in
  2026       (0 upto length decls - 1, decls)
  2027       |-> map2 (formula_line_for_guards_sym_decl ctxt format conj_sym_kind mono
  2028                                                  type_enc n s)
  2029     end
  2030   | Tags (_, _, uniformity) =>
  2031     (case uniformity of
  2032        Uniform => []
  2033      | Nonuniform =>
  2034        let val n = length decls in
  2035          (0 upto n - 1 ~~ decls)
  2036          |> maps (formula_lines_for_nonuniform_tags_sym_decl ctxt format
  2037                       conj_sym_kind mono type_enc n s)
  2038        end)
  2039 
  2040 fun problem_lines_for_sym_decl_table ctxt format conj_sym_kind mono type_enc
  2041                                      sym_decl_tab =
  2042   let
  2043     val syms = sym_decl_tab |> Symtab.dest |> sort_wrt fst
  2044     val mono_Ts =
  2045       if polymorphism_of_type_enc type_enc = Polymorphic then
  2046         syms |> maps (map result_type_of_decl o snd)
  2047              |> filter_out (should_encode_type ctxt mono
  2048                                 (level_of_type_enc type_enc))
  2049              |> rpair [] |-> fold (insert_type ctxt I)
  2050       else
  2051         []
  2052     val mono_lines =
  2053       problem_lines_for_mono_types ctxt format mono type_enc mono_Ts
  2054     val decl_lines =
  2055       fold_rev (append o problem_lines_for_sym_decls ctxt format conj_sym_kind
  2056                                                      mono type_enc)
  2057                syms []
  2058   in mono_lines @ decl_lines end
  2059 
  2060 fun needs_type_tag_idempotence (Tags (poly, level, uniformity)) =
  2061     poly <> Mangled_Monomorphic andalso
  2062     ((level = All_Types andalso uniformity = Nonuniform) orelse
  2063      is_type_level_monotonicity_based level)
  2064   | needs_type_tag_idempotence _ = false
  2065 
  2066 fun offset_of_heading_in_problem _ [] j = j
  2067   | offset_of_heading_in_problem needle ((heading, lines) :: problem) j =
  2068     if heading = needle then j
  2069     else offset_of_heading_in_problem needle problem (j + length lines)
  2070 
  2071 val implicit_declsN = "Should-be-implicit typings"
  2072 val explicit_declsN = "Explicit typings"
  2073 val factsN = "Relevant facts"
  2074 val class_relsN = "Class relationships"
  2075 val aritiesN = "Arities"
  2076 val helpersN = "Helper facts"
  2077 val conjsN = "Conjectures"
  2078 val free_typesN = "Type variables"
  2079 
  2080 val explicit_apply = NONE (* for experiments *)
  2081 
  2082 fun prepare_atp_problem ctxt format conj_sym_kind prem_kind type_enc exporter
  2083         lambda_trans readable_names preproc hyp_ts concl_t facts =
  2084   let
  2085     val type_enc = type_enc |> adjust_type_enc format
  2086     val lambda_trans =
  2087       if lambda_trans = smartN then
  2088         if is_type_enc_higher_order type_enc then lambdasN else combinatorsN
  2089       else if lambda_trans = lambdasN andalso
  2090               not (is_type_enc_higher_order type_enc) then
  2091         error ("Lambda translation method incompatible with first-order \
  2092                \encoding.")
  2093       else
  2094         lambda_trans
  2095     val trans_lambdas =
  2096       if lambda_trans = no_lambdasN then
  2097         rpair []
  2098       else if lambda_trans = concealedN then
  2099         lift_lambdas ctxt type_enc ##> K []
  2100       else if lambda_trans = liftingN then
  2101         lift_lambdas ctxt type_enc
  2102       else if lambda_trans = combinatorsN then
  2103         map (introduce_combinators ctxt) #> rpair []
  2104       else if lambda_trans = hybridN then
  2105         lift_lambdas ctxt type_enc
  2106         ##> maps (fn t => [t, introduce_combinators ctxt
  2107                                   (intentionalize_def t)])
  2108       else if lambda_trans = lambdasN then
  2109         map (Envir.eta_contract) #> rpair []
  2110       else
  2111         error ("Unknown lambda translation method: " ^
  2112                quote lambda_trans ^ ".")
  2113     val (fact_names, (conjs, facts, class_rel_clauses, arity_clauses)) =
  2114       translate_formulas ctxt format prem_kind type_enc trans_lambdas preproc
  2115                          hyp_ts concl_t facts
  2116     val sym_tab = conjs @ facts |> sym_table_for_facts ctxt explicit_apply
  2117     val mono = conjs @ facts |> mononotonicity_info_for_facts ctxt type_enc
  2118     val repair = repair_fact ctxt format type_enc sym_tab
  2119     val (conjs, facts) = (conjs, facts) |> pairself (map repair)
  2120     val repaired_sym_tab =
  2121       conjs @ facts |> sym_table_for_facts ctxt (SOME false)
  2122     val helpers =
  2123       repaired_sym_tab |> helper_facts_for_sym_table ctxt format type_enc
  2124                        |> map repair
  2125     val sym_decl_lines =
  2126       (conjs, helpers @ facts)
  2127       |> sym_decl_table_for_facts ctxt format type_enc repaired_sym_tab
  2128       |> problem_lines_for_sym_decl_table ctxt format conj_sym_kind mono
  2129                                                type_enc
  2130     val helper_lines =
  2131       0 upto length helpers - 1 ~~ helpers
  2132       |> map (formula_line_for_fact ctxt format helper_prefix I false true mono
  2133                                     type_enc)
  2134       |> (if needs_type_tag_idempotence type_enc then
  2135             cons (type_tag_idempotence_fact type_enc)
  2136           else
  2137             I)
  2138     (* Reordering these might confuse the proof reconstruction code or the SPASS
  2139        FLOTTER hack. *)
  2140     val problem =
  2141       [(explicit_declsN, sym_decl_lines),
  2142        (factsN,
  2143         map (formula_line_for_fact ctxt format fact_prefix ascii_of
  2144                                    (not exporter) (not exporter) mono
  2145                                    type_enc)
  2146             (0 upto length facts - 1 ~~ facts)),
  2147        (class_relsN, map formula_line_for_class_rel_clause class_rel_clauses),
  2148        (aritiesN, map formula_line_for_arity_clause arity_clauses),
  2149        (helpersN, helper_lines),
  2150        (conjsN,
  2151         map (formula_line_for_conjecture ctxt format mono type_enc) conjs),
  2152        (free_typesN, formula_lines_for_free_types type_enc (facts @ conjs))]
  2153     val problem =
  2154       problem
  2155       |> (case format of
  2156             CNF => ensure_cnf_problem
  2157           | CNF_UEQ => filter_cnf_ueq_problem
  2158           | _ => I)
  2159       |> (if is_format_typed format then
  2160             declare_undeclared_syms_in_atp_problem type_decl_prefix
  2161                                                    implicit_declsN
  2162           else
  2163             I)
  2164     val (problem, pool) = problem |> nice_atp_problem readable_names
  2165     val helpers_offset = offset_of_heading_in_problem helpersN problem 0
  2166     val typed_helpers =
  2167       map_filter (fn (j, {name, ...}) =>
  2168                      if String.isSuffix typed_helper_suffix name then SOME j
  2169                      else NONE)
  2170                  ((helpers_offset + 1 upto helpers_offset + length helpers)
  2171                   ~~ helpers)
  2172     fun add_sym_arity (s, {min_ary, ...} : sym_info) =
  2173       if min_ary > 0 then
  2174         case strip_prefix_and_unascii const_prefix s of
  2175           SOME s => Symtab.insert (op =) (s, min_ary)
  2176         | NONE => I
  2177       else
  2178         I
  2179   in
  2180     (problem,
  2181      case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
  2182      offset_of_heading_in_problem conjsN problem 0,
  2183      offset_of_heading_in_problem factsN problem 0,
  2184      fact_names |> Vector.fromList,
  2185      typed_helpers,
  2186      Symtab.empty |> Symtab.fold add_sym_arity sym_tab)
  2187   end
  2188 
  2189 (* FUDGE *)
  2190 val conj_weight = 0.0
  2191 val hyp_weight = 0.1
  2192 val fact_min_weight = 0.2
  2193 val fact_max_weight = 1.0
  2194 val type_info_default_weight = 0.8
  2195 
  2196 fun add_term_weights weight (ATerm (s, tms)) =
  2197     is_tptp_user_symbol s ? Symtab.default (s, weight)
  2198     #> fold (add_term_weights weight) tms
  2199   | add_term_weights weight (AAbs (_, tm)) = add_term_weights weight tm
  2200 fun add_problem_line_weights weight (Formula (_, _, phi, _, _)) =
  2201     formula_fold NONE (K (add_term_weights weight)) phi
  2202   | add_problem_line_weights _ _ = I
  2203 
  2204 fun add_conjectures_weights [] = I
  2205   | add_conjectures_weights conjs =
  2206     let val (hyps, conj) = split_last conjs in
  2207       add_problem_line_weights conj_weight conj
  2208       #> fold (add_problem_line_weights hyp_weight) hyps
  2209     end
  2210 
  2211 fun add_facts_weights facts =
  2212   let
  2213     val num_facts = length facts
  2214     fun weight_of j =
  2215       fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
  2216                         / Real.fromInt num_facts
  2217   in
  2218     map weight_of (0 upto num_facts - 1) ~~ facts
  2219     |> fold (uncurry add_problem_line_weights)
  2220   end
  2221 
  2222 (* Weights are from 0.0 (most important) to 1.0 (least important). *)
  2223 fun atp_problem_weights problem =
  2224   let val get = these o AList.lookup (op =) problem in
  2225     Symtab.empty
  2226     |> add_conjectures_weights (get free_typesN @ get conjsN)
  2227     |> add_facts_weights (get factsN)
  2228     |> fold (fold (add_problem_line_weights type_info_default_weight) o get)
  2229             [explicit_declsN, class_relsN, aritiesN]
  2230     |> Symtab.dest
  2231     |> sort (prod_ord Real.compare string_ord o pairself swap)
  2232   end
  2233 
  2234 end;