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