src/HOL/Tools/Sledgehammer/sledgehammer_atp_translate.ML
author blanchet
Sun, 01 May 2011 18:37:25 +0200
changeset 43456 723b9d1e8ba5
parent 43450 2552c09b1a72
child 43457 59e0ca92bb0b
permissions -rw-r--r--
fixed embarrassing bug where conjecture and fact offsets were swapped
blanchet@40358
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_atp_translate.ML
blanchet@38506
     2
    Author:     Fabian Immler, TU Muenchen
blanchet@38506
     3
    Author:     Makarius
blanchet@38506
     4
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@38506
     5
blanchet@39734
     6
Translation of HOL to FOL for Sledgehammer.
blanchet@38506
     7
*)
blanchet@38506
     8
blanchet@40249
     9
signature SLEDGEHAMMER_ATP_TRANSLATE =
blanchet@38506
    10
sig
blanchet@43088
    11
  type 'a fo_term = 'a ATP_Problem.fo_term
blanchet@38506
    12
  type 'a problem = 'a ATP_Problem.problem
blanchet@43450
    13
  type type_system = ATP_Systems.type_system
blanchet@40358
    14
  type translated_formula
blanchet@38506
    15
blanchet@43439
    16
  val readable_names : bool Unsynchronized.ref
blanchet@40445
    17
  val fact_prefix : string
blanchet@38506
    18
  val conjecture_prefix : string
blanchet@43439
    19
  val predicator_base : string
blanchet@43415
    20
  val explicit_app_base : string
blanchet@43420
    21
  val type_pred_base : string
blanchet@43433
    22
  val tff_type_prefix : string
blanchet@41384
    23
  val num_atp_type_args : theory -> type_system -> string -> int
blanchet@43413
    24
  val unmangled_const : string -> string * string fo_term list
blanchet@41336
    25
  val translate_atp_fact :
blanchet@43415
    26
    Proof.context -> bool -> (string * 'a) * thm
blanchet@41339
    27
    -> translated_formula option * ((string * 'a) * thm)
blanchet@40240
    28
  val prepare_atp_problem :
blanchet@43439
    29
    Proof.context -> type_system -> bool -> term list -> term
blanchet@41339
    30
    -> (translated_formula option * ((string * 'a) * thm)) list
blanchet@43412
    31
    -> string problem * string Symtab.table * int * int
blanchet@43412
    32
       * (string * 'a) list vector
blanchet@41561
    33
  val atp_problem_weights : string problem -> (string * real) list
blanchet@38506
    34
end;
blanchet@38506
    35
blanchet@41388
    36
structure Sledgehammer_ATP_Translate : SLEDGEHAMMER_ATP_TRANSLATE =
blanchet@38506
    37
struct
blanchet@38506
    38
blanchet@38506
    39
open ATP_Problem
blanchet@43450
    40
open ATP_Systems
blanchet@39734
    41
open Metis_Translate
blanchet@38506
    42
open Sledgehammer_Util
blanchet@38506
    43
blanchet@43439
    44
(* Readable names are often much shorter, especially if types are mangled in
blanchet@43439
    45
   names. For that reason, they are on by default. *)
blanchet@43439
    46
val readable_names = Unsynchronized.ref true
blanchet@43439
    47
blanchet@43414
    48
val type_decl_prefix = "type_"
blanchet@43414
    49
val sym_decl_prefix = "sym_"
blanchet@40445
    50
val fact_prefix = "fact_"
blanchet@38506
    51
val conjecture_prefix = "conj_"
blanchet@38506
    52
val helper_prefix = "help_"
blanchet@43414
    53
val class_rel_clause_prefix = "crel_";
blanchet@38506
    54
val arity_clause_prefix = "arity_"
blanchet@40156
    55
val tfree_prefix = "tfree_"
blanchet@38506
    56
blanchet@43439
    57
val predicator_base = "hBOOL"
blanchet@43415
    58
val explicit_app_base = "hAPP"
blanchet@43413
    59
val type_pred_base = "is"
blanchet@43433
    60
val tff_type_prefix = "ty_"
blanchet@43402
    61
blanchet@43433
    62
fun make_tff_type s = tff_type_prefix ^ ascii_of s
blanchet@43402
    63
blanchet@43439
    64
(* official TPTP syntax *)
blanchet@43439
    65
val tptp_tff_type_of_types = "$tType"
blanchet@43439
    66
val tptp_tff_bool_type = "$o"
blanchet@43439
    67
val tptp_false = "$false"
blanchet@43439
    68
val tptp_true = "$true"
blanchet@43405
    69
blanchet@38506
    70
(* Freshness almost guaranteed! *)
blanchet@38506
    71
val sledgehammer_weak_prefix = "Sledgehammer:"
blanchet@38506
    72
blanchet@43444
    73
fun formula_map f (AQuant (q, xs, phi)) = AQuant (q, xs, formula_map f phi)
blanchet@43444
    74
  | formula_map f (AConn (c, phis)) = AConn (c, map (formula_map f) phis)
blanchet@43444
    75
  | formula_map f (AAtom tm) = AAtom (f tm)
blanchet@43444
    76
blanchet@43444
    77
fun formula_fold f (AQuant (_, _, phi)) = formula_fold f phi
blanchet@43444
    78
  | formula_fold f (AConn (_, phis)) = fold (formula_fold f) phis
blanchet@43444
    79
  | formula_fold f (AAtom tm) = f tm
blanchet@43444
    80
blanchet@40358
    81
type translated_formula =
blanchet@38991
    82
  {name: string,
blanchet@43396
    83
   kind: formula_kind,
blanchet@43433
    84
   combformula: (name, typ, combterm) formula,
blanchet@43433
    85
   atomic_types: typ list}
blanchet@38506
    86
blanchet@43429
    87
fun update_combformula f
blanchet@43433
    88
        ({name, kind, combformula, atomic_types} : translated_formula) =
blanchet@43413
    89
  {name = name, kind = kind, combformula = f combformula,
blanchet@43433
    90
   atomic_types = atomic_types} : translated_formula
blanchet@43413
    91
blanchet@43429
    92
fun fact_lift f ({combformula, ...} : translated_formula) = f combformula
blanchet@43429
    93
blanchet@43450
    94
fun type_sys_declares_sym_types Many_Typed = true
blanchet@43450
    95
  | type_sys_declares_sym_types (Mangled level) = level <> Unsound
blanchet@43450
    96
  | type_sys_declares_sym_types (Args (_, level)) = level <> Unsound
blanchet@43450
    97
  | type_sys_declares_sym_types _ = false
blanchet@43444
    98
blanchet@43443
    99
val boring_consts = [explicit_app_base, @{const_name Metis.fequal}]
blanchet@43443
   100
blanchet@43443
   101
fun should_omit_type_args type_sys s =
blanchet@43413
   102
  s <> type_pred_base andalso
blanchet@43443
   103
  (s = @{const_name HOL.eq} orelse
blanchet@43402
   104
   case type_sys of
blanchet@43404
   105
     Many_Typed => false
blanchet@43419
   106
   | Mangled _ => false
blanchet@43450
   107
   | Tags (_, Sound) => true
blanchet@43443
   108
   | No_Types => true
blanchet@43443
   109
   | _ => member (op =) boring_consts s)
blanchet@41384
   110
blanchet@43419
   111
datatype type_arg_policy = No_Type_Args | Mangled_Types | Explicit_Type_Args
blanchet@43088
   112
blanchet@43434
   113
fun general_type_arg_policy Many_Typed = Mangled_Types
blanchet@43434
   114
  | general_type_arg_policy (Mangled _) = Mangled_Types
blanchet@43450
   115
  | general_type_arg_policy No_Types = No_Type_Args
blanchet@43434
   116
  | general_type_arg_policy _ = Explicit_Type_Args
blanchet@43434
   117
blanchet@43395
   118
fun type_arg_policy type_sys s =
blanchet@43443
   119
  if should_omit_type_args type_sys s then No_Type_Args
blanchet@43434
   120
  else general_type_arg_policy type_sys
blanchet@43088
   121
blanchet@41384
   122
fun num_atp_type_args thy type_sys s =
blanchet@43428
   123
  if type_arg_policy type_sys s = Explicit_Type_Args then num_type_args thy s
blanchet@43428
   124
  else 0
blanchet@41384
   125
blanchet@43224
   126
fun atp_type_literals_for_types type_sys kind Ts =
blanchet@43224
   127
  if type_sys = No_Types then
blanchet@43224
   128
    []
blanchet@43224
   129
  else
blanchet@43224
   130
    Ts |> type_literals_for_types
blanchet@43224
   131
       |> filter (fn TyLitVar _ => kind <> Conjecture
blanchet@43224
   132
                   | TyLitFree _ => kind = Conjecture)
blanchet@41385
   133
blanchet@38506
   134
fun mk_aconn c phi1 phi2 = AConn (c, [phi1, phi2])
blanchet@43405
   135
fun mk_aconns c phis =
blanchet@43405
   136
  let val (phis', phi') = split_last phis in
blanchet@43405
   137
    fold_rev (mk_aconn c) phis' phi'
blanchet@43405
   138
  end
blanchet@38506
   139
fun mk_ahorn [] phi = phi
blanchet@43405
   140
  | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
blanchet@43393
   141
fun mk_aquant _ [] phi = phi
blanchet@43393
   142
  | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
blanchet@43393
   143
    if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
blanchet@43393
   144
  | mk_aquant q xs phi = AQuant (q, xs, phi)
blanchet@38506
   145
blanchet@43393
   146
fun close_universally atom_vars phi =
blanchet@41393
   147
  let
blanchet@41393
   148
    fun formula_vars bounds (AQuant (_, xs, phi)) =
blanchet@43397
   149
        formula_vars (map fst xs @ bounds) phi
blanchet@41393
   150
      | formula_vars bounds (AConn (_, phis)) = fold (formula_vars bounds) phis
blanchet@43393
   151
      | formula_vars bounds (AAtom tm) =
blanchet@43397
   152
        union (op =) (atom_vars tm []
blanchet@43397
   153
                      |> filter_out (member (op =) bounds o fst))
blanchet@43393
   154
  in mk_aquant AForall (formula_vars [] phi []) phi end
blanchet@43393
   155
blanchet@43402
   156
fun combterm_vars (CombApp (tm1, tm2)) = fold combterm_vars [tm1, tm2]
blanchet@43393
   157
  | combterm_vars (CombConst _) = I
blanchet@43445
   158
  | combterm_vars (CombVar (name, T)) = insert (op =) (name, SOME T)
blanchet@43393
   159
val close_combformula_universally = close_universally combterm_vars
blanchet@43393
   160
blanchet@43393
   161
fun term_vars (ATerm (name as (s, _), tms)) =
blanchet@43402
   162
  is_atp_variable s ? insert (op =) (name, NONE)
blanchet@43397
   163
  #> fold term_vars tms
blanchet@43393
   164
val close_formula_universally = close_universally term_vars
blanchet@41393
   165
blanchet@43433
   166
fun fo_term_from_typ (Type (s, Ts)) =
blanchet@43433
   167
    ATerm (`make_fixed_type_const s, map fo_term_from_typ Ts)
blanchet@43433
   168
  | fo_term_from_typ (TFree (s, _)) =
blanchet@43433
   169
    ATerm (`make_fixed_type_var s, [])
blanchet@43433
   170
  | fo_term_from_typ (TVar ((x as (s, _)), _)) =
blanchet@43433
   171
    ATerm ((make_schematic_type_var x, s), [])
blanchet@43433
   172
blanchet@43433
   173
(* This shouldn't clash with anything else. *)
blanchet@43413
   174
val mangled_type_sep = "\000"
blanchet@43413
   175
blanchet@43433
   176
fun generic_mangled_type_name f (ATerm (name, [])) = f name
blanchet@43433
   177
  | generic_mangled_type_name f (ATerm (name, tys)) =
blanchet@43433
   178
    f name ^ "(" ^ commas (map (generic_mangled_type_name f) tys) ^ ")"
blanchet@43433
   179
val mangled_type_name =
blanchet@43433
   180
  fo_term_from_typ
blanchet@43433
   181
  #> (fn ty => (make_tff_type (generic_mangled_type_name fst ty),
blanchet@43433
   182
                generic_mangled_type_name snd ty))
blanchet@43413
   183
blanchet@43445
   184
fun generic_mangled_type_suffix f g Ts =
blanchet@43413
   185
  fold_rev (curry (op ^) o g o prefix mangled_type_sep
blanchet@43445
   186
            o generic_mangled_type_name f) Ts ""
blanchet@43433
   187
fun mangled_const_name T_args (s, s') =
blanchet@43433
   188
  let val ty_args = map fo_term_from_typ T_args in
blanchet@43433
   189
    (s ^ generic_mangled_type_suffix fst ascii_of ty_args,
blanchet@43433
   190
     s' ^ generic_mangled_type_suffix snd I ty_args)
blanchet@43433
   191
  end
blanchet@43413
   192
blanchet@43413
   193
val parse_mangled_ident =
blanchet@43413
   194
  Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
blanchet@43413
   195
blanchet@43413
   196
fun parse_mangled_type x =
blanchet@43413
   197
  (parse_mangled_ident
blanchet@43413
   198
   -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
blanchet@43413
   199
                    [] >> ATerm) x
blanchet@43413
   200
and parse_mangled_types x =
blanchet@43413
   201
  (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
blanchet@43413
   202
blanchet@43413
   203
fun unmangled_type s =
blanchet@43413
   204
  s |> suffix ")" |> raw_explode
blanchet@43413
   205
    |> Scan.finite Symbol.stopper
blanchet@43413
   206
           (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
blanchet@43413
   207
                                                quote s)) parse_mangled_type))
blanchet@43413
   208
    |> fst
blanchet@43413
   209
blanchet@43432
   210
val unmangled_const_name = space_explode mangled_type_sep #> hd
blanchet@43413
   211
fun unmangled_const s =
blanchet@43413
   212
  let val ss = space_explode mangled_type_sep s in
blanchet@43413
   213
    (hd ss, map unmangled_type (tl ss))
blanchet@43413
   214
  end
blanchet@43413
   215
blanchet@43439
   216
val introduce_proxies =
blanchet@43439
   217
  let
blanchet@43439
   218
    fun aux top_level (CombApp (tm1, tm2)) =
blanchet@43439
   219
        CombApp (aux top_level tm1, aux false tm2)
blanchet@43445
   220
      | aux top_level (CombConst (name as (s, s'), T, T_args)) =
blanchet@43441
   221
        (case proxify_const s of
blanchet@43439
   222
           SOME proxy_base =>
blanchet@43439
   223
           if top_level then
blanchet@43439
   224
             (case s of
blanchet@43439
   225
                "c_False" => (tptp_false, s')
blanchet@43439
   226
              | "c_True" => (tptp_true, s')
blanchet@43439
   227
              | _ => name, [])
blanchet@43440
   228
           else
blanchet@43445
   229
             (proxy_base |>> prefix const_prefix, T_args)
blanchet@43445
   230
          | NONE => (name, T_args))
blanchet@43445
   231
        |> (fn (name, T_args) => CombConst (name, T, T_args))
blanchet@43439
   232
      | aux _ tm = tm
blanchet@43439
   233
  in aux true end
blanchet@43439
   234
blanchet@43433
   235
fun combformula_from_prop thy eq_as_iff =
blanchet@38506
   236
  let
blanchet@43439
   237
    fun do_term bs t atomic_types =
blanchet@41388
   238
      combterm_from_term thy bs (Envir.eta_contract t)
blanchet@43439
   239
      |>> (introduce_proxies #> AAtom)
blanchet@43439
   240
      ||> union (op =) atomic_types
blanchet@38506
   241
    fun do_quant bs q s T t' =
blanchet@38743
   242
      let val s = Name.variant (map fst bs) s in
blanchet@38743
   243
        do_formula ((s, T) :: bs) t'
blanchet@43433
   244
        #>> mk_aquant q [(`make_bound_var s, SOME T)]
blanchet@38743
   245
      end
blanchet@38506
   246
    and do_conn bs c t1 t2 =
blanchet@38506
   247
      do_formula bs t1 ##>> do_formula bs t2
blanchet@43402
   248
      #>> uncurry (mk_aconn c)
blanchet@38506
   249
    and do_formula bs t =
blanchet@38506
   250
      case t of
blanchet@43402
   251
        @{const Not} $ t1 => do_formula bs t1 #>> mk_anot
blanchet@38506
   252
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@38506
   253
        do_quant bs AForall s T t'
blanchet@38506
   254
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@38506
   255
        do_quant bs AExists s T t'
haftmann@39028
   256
      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd t1 t2
haftmann@39028
   257
      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr t1 t2
haftmann@39019
   258
      | @{const HOL.implies} $ t1 $ t2 => do_conn bs AImplies t1 t2
haftmann@39093
   259
      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@41388
   260
        if eq_as_iff then do_conn bs AIff t1 t2 else do_term bs t
blanchet@41388
   261
      | _ => do_term bs t
blanchet@38506
   262
  in do_formula [] end
blanchet@38506
   263
blanchet@38841
   264
val presimplify_term = prop_of o Meson.presimplify oo Skip_Proof.make_thm
blanchet@38506
   265
wenzelm@41739
   266
fun concealed_bound_name j = sledgehammer_weak_prefix ^ string_of_int j
blanchet@38506
   267
fun conceal_bounds Ts t =
blanchet@38506
   268
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@38506
   269
                    (0 upto length Ts - 1 ~~ Ts), t)
blanchet@38506
   270
fun reveal_bounds Ts =
blanchet@38506
   271
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@38506
   272
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@38506
   273
blanchet@38831
   274
(* Removes the lambdas from an equation of the form "t = (%x. u)".
blanchet@40071
   275
   (Cf. "extensionalize_theorem" in "Meson_Clausify".) *)
blanchet@38831
   276
fun extensionalize_term t =
blanchet@38831
   277
  let
blanchet@38831
   278
    fun aux j (@{const Trueprop} $ t') = @{const Trueprop} $ aux j t'
blanchet@38831
   279
      | aux j (t as Const (s, Type (_, [Type (_, [_, T']),
blanchet@38831
   280
                                        Type (_, [_, res_T])]))
blanchet@38831
   281
                    $ t2 $ Abs (var_s, var_T, t')) =
haftmann@39093
   282
        if s = @{const_name HOL.eq} orelse s = @{const_name "=="} then
blanchet@38831
   283
          let val var_t = Var ((var_s, j), var_T) in
blanchet@38831
   284
            Const (s, T' --> T' --> res_T)
blanchet@38831
   285
              $ betapply (t2, var_t) $ subst_bound (var_t, t')
blanchet@38831
   286
            |> aux (j + 1)
blanchet@38831
   287
          end
blanchet@38831
   288
        else
blanchet@38831
   289
          t
blanchet@38831
   290
      | aux _ t = t
blanchet@38831
   291
  in aux (maxidx_of_term t + 1) t end
blanchet@38831
   292
blanchet@38506
   293
fun introduce_combinators_in_term ctxt kind t =
wenzelm@43232
   294
  let val thy = Proof_Context.theory_of ctxt in
blanchet@38716
   295
    if Meson.is_fol_term thy t then
blanchet@38716
   296
      t
blanchet@38716
   297
    else
blanchet@38716
   298
      let
blanchet@38716
   299
        fun aux Ts t =
blanchet@38716
   300
          case t of
blanchet@38716
   301
            @{const Not} $ t1 => @{const Not} $ aux Ts t1
blanchet@38716
   302
          | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@38716
   303
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38890
   304
          | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@38890
   305
            aux Ts (t0 $ eta_expand Ts t1 1)
blanchet@38716
   306
          | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@38716
   307
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38890
   308
          | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@38890
   309
            aux Ts (t0 $ eta_expand Ts t1 1)
haftmann@39028
   310
          | (t0 as @{const HOL.conj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39028
   311
          | (t0 as @{const HOL.disj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39019
   312
          | (t0 as @{const HOL.implies}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39093
   313
          | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
blanchet@38716
   314
              $ t1 $ t2 =>
blanchet@38716
   315
            t0 $ aux Ts t1 $ aux Ts t2
blanchet@38716
   316
          | _ => if not (exists_subterm (fn Abs _ => true | _ => false) t) then
blanchet@38716
   317
                   t
blanchet@38716
   318
                 else
blanchet@38716
   319
                   t |> conceal_bounds Ts
blanchet@38716
   320
                     |> Envir.eta_contract
blanchet@38716
   321
                     |> cterm_of thy
blanchet@40071
   322
                     |> Meson_Clausify.introduce_combinators_in_cterm
blanchet@38716
   323
                     |> prop_of |> Logic.dest_equals |> snd
blanchet@38716
   324
                     |> reveal_bounds Ts
blanchet@39616
   325
        val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
blanchet@38716
   326
      in t |> aux [] |> singleton (Variable.export_terms ctxt' ctxt) end
blanchet@38716
   327
      handle THM _ =>
blanchet@38716
   328
             (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@38836
   329
             if kind = Conjecture then HOLogic.false_const
blanchet@38836
   330
             else HOLogic.true_const
blanchet@38716
   331
  end
blanchet@38506
   332
blanchet@38506
   333
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@43224
   334
   same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
blanchet@38506
   335
fun freeze_term t =
blanchet@38506
   336
  let
blanchet@38506
   337
    fun aux (t $ u) = aux t $ aux u
blanchet@38506
   338
      | aux (Abs (s, T, t)) = Abs (s, T, aux t)
blanchet@38506
   339
      | aux (Var ((s, i), T)) =
blanchet@38506
   340
        Free (sledgehammer_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
blanchet@38506
   341
      | aux t = t
blanchet@38506
   342
  in t |> exists_subterm is_Var t ? aux end
blanchet@38506
   343
blanchet@40445
   344
(* making fact and conjecture formulas *)
blanchet@43415
   345
fun make_formula ctxt eq_as_iff presimp name kind t =
blanchet@38506
   346
  let
wenzelm@43232
   347
    val thy = Proof_Context.theory_of ctxt
blanchet@38831
   348
    val t = t |> Envir.beta_eta_contract
blanchet@38890
   349
              |> transform_elim_term
blanchet@41459
   350
              |> Object_Logic.atomize_term thy
blanchet@43434
   351
    val need_trueprop = (fastype_of t = @{typ bool})
blanchet@38890
   352
    val t = t |> need_trueprop ? HOLogic.mk_Trueprop
blanchet@38506
   353
              |> extensionalize_term
blanchet@38506
   354
              |> presimp ? presimplify_term thy
blanchet@38506
   355
              |> perhaps (try (HOLogic.dest_Trueprop))
blanchet@38506
   356
              |> introduce_combinators_in_term ctxt kind
blanchet@38836
   357
              |> kind <> Axiom ? freeze_term
blanchet@43433
   358
    val (combformula, atomic_types) =
blanchet@43433
   359
      combformula_from_prop thy eq_as_iff t []
blanchet@38506
   360
  in
blanchet@38991
   361
    {name = name, combformula = combformula, kind = kind,
blanchet@43433
   362
     atomic_types = atomic_types}
blanchet@38506
   363
  end
blanchet@38506
   364
blanchet@43432
   365
fun make_fact ctxt keep_trivial eq_as_iff presimp ((name, _), t) =
blanchet@43432
   366
  case (keep_trivial, make_formula ctxt eq_as_iff presimp name Axiom t) of
blanchet@42861
   367
    (false, {combformula = AAtom (CombConst (("c_True", _), _, _)), ...}) =>
blanchet@42861
   368
    NONE
blanchet@42861
   369
  | (_, formula) => SOME formula
blanchet@43432
   370
blanchet@43415
   371
fun make_conjecture ctxt ts =
blanchet@38836
   372
  let val last = length ts - 1 in
blanchet@43415
   373
    map2 (fn j => make_formula ctxt true true (string_of_int j)
blanchet@38836
   374
                               (if j = last then Conjecture else Hypothesis))
blanchet@38836
   375
         (0 upto last) ts
blanchet@38836
   376
  end
blanchet@38506
   377
blanchet@43444
   378
(** "hBOOL" and "hAPP" **)
blanchet@41561
   379
blanchet@43445
   380
type sym_info =
blanchet@43434
   381
  {pred_sym : bool, min_ary : int, max_ary : int, typ : typ option}
blanchet@43434
   382
blanchet@43445
   383
fun add_combterm_syms_to_table explicit_apply =
blanchet@43429
   384
  let
blanchet@43429
   385
    fun aux top_level tm =
blanchet@43429
   386
      let val (head, args) = strip_combterm_comb tm in
blanchet@43429
   387
        (case head of
blanchet@43434
   388
           CombConst ((s, _), T, _) =>
blanchet@43429
   389
           if String.isPrefix bound_var_prefix s then
blanchet@43429
   390
             I
blanchet@43429
   391
           else
blanchet@43434
   392
             let val ary = length args in
blanchet@43429
   393
               Symtab.map_default
blanchet@43429
   394
                   (s, {pred_sym = true,
blanchet@43434
   395
                        min_ary = if explicit_apply then 0 else ary,
blanchet@43434
   396
                        max_ary = 0, typ = SOME T})
blanchet@43434
   397
                   (fn {pred_sym, min_ary, max_ary, typ} =>
blanchet@43429
   398
                       {pred_sym = pred_sym andalso top_level,
blanchet@43434
   399
                        min_ary = Int.min (ary, min_ary),
blanchet@43434
   400
                        max_ary = Int.max (ary, max_ary),
blanchet@43434
   401
                        typ = if typ = SOME T then typ else NONE})
blanchet@43429
   402
            end
blanchet@43429
   403
         | _ => I)
blanchet@43429
   404
        #> fold (aux false) args
blanchet@43429
   405
      end
blanchet@43429
   406
  in aux true end
blanchet@43445
   407
val add_fact_syms_to_table =
blanchet@43445
   408
  fact_lift o formula_fold o add_combterm_syms_to_table
blanchet@38506
   409
blanchet@43428
   410
val default_sym_table_entries =
blanchet@43434
   411
  [("equal", {pred_sym = true, min_ary = 2, max_ary = 2, typ = NONE}),
blanchet@43439
   412
   (make_fixed_const predicator_base,
blanchet@43434
   413
    {pred_sym = true, min_ary = 1, max_ary = 1, typ = NONE})] @
blanchet@43439
   414
  ([tptp_false, tptp_true]
blanchet@43434
   415
   |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, typ = NONE}))
blanchet@41388
   416
blanchet@43415
   417
fun sym_table_for_facts explicit_apply facts =
blanchet@43439
   418
  Symtab.empty |> fold Symtab.default default_sym_table_entries
blanchet@43445
   419
               |> fold (add_fact_syms_to_table explicit_apply) facts
blanchet@38506
   420
blanchet@43429
   421
fun min_arity_of sym_tab s =
blanchet@43429
   422
  case Symtab.lookup sym_tab s of
blanchet@43445
   423
    SOME ({min_ary, ...} : sym_info) => min_ary
blanchet@43429
   424
  | NONE =>
blanchet@43429
   425
    case strip_prefix_and_unascii const_prefix s of
blanchet@43418
   426
      SOME s =>
blanchet@43441
   427
      let val s = s |> unmangled_const_name |> invert_const in
blanchet@43439
   428
        if s = predicator_base then 1
blanchet@43418
   429
        else if s = explicit_app_base then 2
blanchet@43418
   430
        else if s = type_pred_base then 1
blanchet@43428
   431
        else 0
blanchet@43418
   432
      end
blanchet@38506
   433
    | NONE => 0
blanchet@38506
   434
blanchet@38506
   435
(* True if the constant ever appears outside of the top-level position in
blanchet@38506
   436
   literals, or if it appears with different arities (e.g., because of different
blanchet@38506
   437
   type instantiations). If false, the constant always receives all of its
blanchet@38506
   438
   arguments and is used as a predicate. *)
blanchet@43429
   439
fun is_pred_sym sym_tab s =
blanchet@43429
   440
  case Symtab.lookup sym_tab s of
blanchet@43445
   441
    SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
blanchet@43445
   442
    pred_sym andalso min_ary = max_ary
blanchet@43429
   443
  | NONE => false
blanchet@38506
   444
blanchet@43439
   445
val predicator_combconst =
blanchet@43439
   446
  CombConst (`make_fixed_const predicator_base, @{typ "bool => bool"}, [])
blanchet@43439
   447
fun predicator tm = CombApp (predicator_combconst, tm)
blanchet@38506
   448
blanchet@43439
   449
fun introduce_predicators_in_combterm sym_tab tm =
blanchet@43413
   450
  case strip_combterm_comb tm of
blanchet@43413
   451
    (CombConst ((s, _), _, _), _) =>
blanchet@43439
   452
    if is_pred_sym sym_tab s then tm else predicator tm
blanchet@43439
   453
  | _ => predicator tm
blanchet@38506
   454
blanchet@43415
   455
fun list_app head args = fold (curry (CombApp o swap)) args head
blanchet@38506
   456
blanchet@43415
   457
fun explicit_app arg head =
blanchet@43415
   458
  let
blanchet@43433
   459
    val head_T = combtyp_of head
blanchet@43433
   460
    val (arg_T, res_T) = dest_funT head_T
blanchet@43415
   461
    val explicit_app =
blanchet@43433
   462
      CombConst (`make_fixed_const explicit_app_base, head_T --> head_T,
blanchet@43433
   463
                 [arg_T, res_T])
blanchet@43415
   464
  in list_app explicit_app [head, arg] end
blanchet@43415
   465
fun list_explicit_app head args = fold explicit_app args head
blanchet@43415
   466
blanchet@43436
   467
fun introduce_explicit_apps_in_combterm sym_tab =
blanchet@43415
   468
  let
blanchet@43415
   469
    fun aux tm =
blanchet@43415
   470
      case strip_combterm_comb tm of
blanchet@43415
   471
        (head as CombConst ((s, _), _, _), args) =>
blanchet@43415
   472
        args |> map aux
blanchet@43428
   473
             |> chop (min_arity_of sym_tab s)
blanchet@43415
   474
             |>> list_app head
blanchet@43415
   475
             |-> list_explicit_app
blanchet@43415
   476
      | (head, args) => list_explicit_app head (map aux args)
blanchet@43415
   477
  in aux end
blanchet@43415
   478
blanchet@43444
   479
fun impose_type_arg_policy_in_combterm type_sys =
blanchet@43444
   480
  let
blanchet@43444
   481
    fun aux (CombApp tmp) = CombApp (pairself aux tmp)
blanchet@43445
   482
      | aux (CombConst (name as (s, _), T, T_args)) =
blanchet@43444
   483
        (case strip_prefix_and_unascii const_prefix s of
blanchet@43445
   484
           NONE => (name, T_args)
blanchet@43444
   485
         | SOME s'' =>
blanchet@43444
   486
           let val s'' = invert_const s'' in
blanchet@43444
   487
             case type_arg_policy type_sys s'' of
blanchet@43444
   488
               No_Type_Args => (name, [])
blanchet@43445
   489
             | Mangled_Types => (mangled_const_name T_args name, [])
blanchet@43445
   490
             | Explicit_Type_Args => (name, T_args)
blanchet@43444
   491
           end)
blanchet@43445
   492
        |> (fn (name, T_args) => CombConst (name, T, T_args))
blanchet@43444
   493
      | aux tm = tm
blanchet@43444
   494
  in aux end
blanchet@43444
   495
blanchet@43444
   496
fun repair_combterm type_sys sym_tab =
blanchet@43436
   497
  introduce_explicit_apps_in_combterm sym_tab
blanchet@43439
   498
  #> introduce_predicators_in_combterm sym_tab
blanchet@43444
   499
  #> impose_type_arg_policy_in_combterm type_sys
blanchet@43444
   500
val repair_fact = update_combformula o formula_map oo repair_combterm
blanchet@43444
   501
blanchet@43444
   502
(** Helper facts **)
blanchet@43444
   503
blanchet@43444
   504
fun ti_ti_helper_fact () =
blanchet@43444
   505
  let
blanchet@43444
   506
    fun var s = ATerm (`I s, [])
blanchet@43444
   507
    fun tag tm = ATerm (`I type_tag_name, [var "X", tm])
blanchet@43444
   508
  in
blanchet@43448
   509
    Formula (helper_prefix ^ ascii_of "ti_ti", Axiom,
blanchet@43444
   510
             AAtom (ATerm (`I "equal", [tag (tag (var "Y")), tag (var "Y")]))
blanchet@43444
   511
             |> close_formula_universally, NONE, NONE)
blanchet@43444
   512
  end
blanchet@43444
   513
blanchet@43445
   514
fun helper_facts_for_sym ctxt type_sys (s, {typ, ...} : sym_info) =
blanchet@43444
   515
  case strip_prefix_and_unascii const_prefix s of
blanchet@43444
   516
    SOME mangled_s =>
blanchet@43444
   517
    let
blanchet@43444
   518
      val thy = Proof_Context.theory_of ctxt
blanchet@43444
   519
      val unmangled_s = mangled_s |> unmangled_const_name
blanchet@43450
   520
      fun dub_and_inst c needs_some_types (th, j) =
blanchet@43450
   521
        ((c ^ "_" ^ string_of_int j ^ (if needs_some_types then "T" else ""),
blanchet@43444
   522
          false),
blanchet@43444
   523
         let val t = th |> prop_of in
blanchet@43444
   524
           t |> (general_type_arg_policy type_sys = Mangled_Types andalso
blanchet@43444
   525
                 not (null (Term.hidden_polymorphism t)))
blanchet@43444
   526
                ? (case typ of
blanchet@43444
   527
                     SOME T => specialize_type thy (invert_const unmangled_s, T)
blanchet@43444
   528
                   | NONE => I)
blanchet@43444
   529
         end)
blanchet@43444
   530
      fun make_facts eq_as_iff =
blanchet@43444
   531
        map_filter (make_fact ctxt false eq_as_iff false)
blanchet@43444
   532
    in
blanchet@43444
   533
      metis_helpers
blanchet@43450
   534
      |> maps (fn (metis_s, (needs_some_types, ths)) =>
blanchet@43444
   535
                  if metis_s <> unmangled_s orelse
blanchet@43450
   536
                     (needs_some_types andalso
blanchet@43450
   537
                      level_of_type_sys type_sys = Unsound) then
blanchet@43444
   538
                    []
blanchet@43444
   539
                  else
blanchet@43444
   540
                    ths ~~ (1 upto length ths)
blanchet@43450
   541
                    |> map (dub_and_inst mangled_s needs_some_types)
blanchet@43450
   542
                    |> make_facts (not needs_some_types))
blanchet@43444
   543
    end
blanchet@43444
   544
  | NONE => []
blanchet@43444
   545
fun helper_facts_for_sym_table ctxt type_sys sym_tab =
blanchet@43444
   546
  Symtab.fold_rev (append o helper_facts_for_sym ctxt type_sys) sym_tab []
blanchet@43444
   547
blanchet@43444
   548
fun translate_atp_fact ctxt keep_trivial =
blanchet@43444
   549
  `(make_fact ctxt keep_trivial true true o apsnd prop_of)
blanchet@43444
   550
blanchet@43444
   551
fun translate_formulas ctxt type_sys hyp_ts concl_t rich_facts =
blanchet@43444
   552
  let
blanchet@43444
   553
    val thy = Proof_Context.theory_of ctxt
blanchet@43444
   554
    val fact_ts = map (prop_of o snd o snd) rich_facts
blanchet@43444
   555
    val (facts, fact_names) =
blanchet@43444
   556
      rich_facts
blanchet@43444
   557
      |> map_filter (fn (NONE, _) => NONE
blanchet@43444
   558
                      | (SOME fact, (name, _)) => SOME (fact, name))
blanchet@43444
   559
      |> ListPair.unzip
blanchet@43444
   560
    (* Remove existing facts from the conjecture, as this can dramatically
blanchet@43444
   561
       boost an ATP's performance (for some reason). *)
blanchet@43444
   562
    val hyp_ts = hyp_ts |> filter_out (member (op aconv) fact_ts)
blanchet@43444
   563
    val goal_t = Logic.list_implies (hyp_ts, concl_t)
blanchet@43444
   564
    val all_ts = goal_t :: fact_ts
blanchet@43444
   565
    val subs = tfree_classes_of_terms all_ts
blanchet@43444
   566
    val supers = tvar_classes_of_terms all_ts
blanchet@43444
   567
    val tycons = type_consts_of_terms thy all_ts
blanchet@43444
   568
    val conjs = make_conjecture ctxt (hyp_ts @ [concl_t])
blanchet@43444
   569
    val (supers', arity_clauses) =
blanchet@43444
   570
      if type_sys = No_Types then ([], [])
blanchet@43444
   571
      else make_arity_clauses thy tycons supers
blanchet@43444
   572
    val class_rel_clauses = make_class_rel_clauses thy subs supers'
blanchet@43444
   573
  in
blanchet@43444
   574
    (fact_names |> map single, (conjs, facts, class_rel_clauses, arity_clauses))
blanchet@43444
   575
  end
blanchet@43444
   576
blanchet@43445
   577
fun tag_with_type ty tm = ATerm (`I type_tag_name, [ty, tm])
blanchet@43444
   578
blanchet@43444
   579
fun fo_literal_from_type_literal (TyLitVar (class, name)) =
blanchet@43444
   580
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@43444
   581
  | fo_literal_from_type_literal (TyLitFree (class, name)) =
blanchet@43444
   582
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@43444
   583
blanchet@43444
   584
fun formula_from_fo_literal (pos, t) = AAtom t |> not pos ? mk_anot
blanchet@43444
   585
blanchet@43444
   586
(* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
blanchet@43444
   587
   considered dangerous because their "exhaust" properties can easily lead to
blanchet@43444
   588
   unsound ATP proofs. The checks below are an (unsound) approximation of
blanchet@43444
   589
   finiteness. *)
blanchet@43444
   590
blanchet@43444
   591
fun is_dtyp_dangerous _ (Datatype_Aux.DtTFree _) = true
blanchet@43444
   592
  | is_dtyp_dangerous ctxt (Datatype_Aux.DtType (s, Us)) =
blanchet@43444
   593
    is_type_constr_dangerous ctxt s andalso forall (is_dtyp_dangerous ctxt) Us
blanchet@43444
   594
  | is_dtyp_dangerous _ (Datatype_Aux.DtRec _) = false
blanchet@43444
   595
and is_type_dangerous ctxt (Type (s, Ts)) =
blanchet@43444
   596
    is_type_constr_dangerous ctxt s andalso forall (is_type_dangerous ctxt) Ts
blanchet@43444
   597
  | is_type_dangerous _ _ = false
blanchet@43444
   598
and is_type_constr_dangerous ctxt s =
blanchet@43444
   599
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43444
   600
    case Datatype_Data.get_info thy s of
blanchet@43444
   601
      SOME {descr, ...} =>
blanchet@43444
   602
      forall (fn (_, (_, _, constrs)) =>
blanchet@43444
   603
                 forall (forall (is_dtyp_dangerous ctxt) o snd) constrs) descr
blanchet@43444
   604
    | NONE =>
blanchet@43444
   605
      case Typedef.get_info ctxt s of
blanchet@43444
   606
        ({rep_type, ...}, _) :: _ => is_type_dangerous ctxt rep_type
blanchet@43444
   607
      | [] => true
blanchet@43444
   608
  end
blanchet@43444
   609
blanchet@43450
   610
fun should_encode_type _ Sound _ = true
blanchet@43450
   611
  | should_encode_type ctxt Half_Sound T = is_type_dangerous ctxt T
blanchet@43450
   612
  | should_encode_type _ Unsound _ = false
blanchet@43450
   613
blanchet@43450
   614
fun should_tag_with_type ctxt (Tags (_, level)) T =
blanchet@43450
   615
    should_encode_type ctxt level T
blanchet@43444
   616
  | should_tag_with_type _ _ _ = false
blanchet@43444
   617
blanchet@43450
   618
fun should_predicate_on_type ctxt (Mangled level) T =
blanchet@43450
   619
    should_encode_type ctxt level T
blanchet@43450
   620
  | should_predicate_on_type ctxt (Args (_, level)) T =
blanchet@43450
   621
    should_encode_type ctxt level T
blanchet@43450
   622
  | should_predicate_on_type _ _ _ = false
blanchet@43450
   623
blanchet@43444
   624
fun type_pred_combatom type_sys T tm =
blanchet@43444
   625
  CombApp (CombConst (`make_fixed_const type_pred_base, T --> @{typ bool}, [T]),
blanchet@43444
   626
           tm)
blanchet@43444
   627
  |> impose_type_arg_policy_in_combterm type_sys
blanchet@43444
   628
  |> AAtom
blanchet@43444
   629
blanchet@43444
   630
fun formula_from_combformula ctxt type_sys =
blanchet@43444
   631
  let
blanchet@43444
   632
    fun do_term top_level u =
blanchet@43444
   633
      let
blanchet@43444
   634
        val (head, args) = strip_combterm_comb u
blanchet@43445
   635
        val (x, T_args) =
blanchet@43444
   636
          case head of
blanchet@43445
   637
            CombConst (name, _, T_args) => (name, T_args)
blanchet@43444
   638
          | CombVar (name, _) => (name, [])
blanchet@43444
   639
          | CombApp _ => raise Fail "impossible \"CombApp\""
blanchet@43445
   640
        val t = ATerm (x, map fo_term_from_typ T_args @
blanchet@43444
   641
                          map (do_term false) args)
blanchet@43445
   642
        val T = combtyp_of u
blanchet@43444
   643
      in
blanchet@43445
   644
        t |> (if not top_level andalso should_tag_with_type ctxt type_sys T then
blanchet@43445
   645
                tag_with_type (fo_term_from_typ T)
blanchet@43444
   646
              else
blanchet@43444
   647
                I)
blanchet@43444
   648
      end
blanchet@43444
   649
    val do_bound_type =
blanchet@43444
   650
      if type_sys = Many_Typed then SOME o mangled_type_name else K NONE
blanchet@43444
   651
    fun do_out_of_bound_type (s, T) =
blanchet@43450
   652
      if should_predicate_on_type ctxt type_sys T then
blanchet@43444
   653
        type_pred_combatom type_sys T (CombVar (s, T))
blanchet@43444
   654
        |> do_formula |> SOME
blanchet@43444
   655
      else
blanchet@43444
   656
        NONE
blanchet@43444
   657
    and do_formula (AQuant (q, xs, phi)) =
blanchet@43444
   658
        AQuant (q, xs |> map (apsnd (fn NONE => NONE
blanchet@43445
   659
                                      | SOME T => do_bound_type T)),
blanchet@43444
   660
                (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
blanchet@43444
   661
                    (map_filter
blanchet@43444
   662
                         (fn (_, NONE) => NONE
blanchet@43445
   663
                           | (s, SOME T) => do_out_of_bound_type (s, T)) xs)
blanchet@43444
   664
                    (do_formula phi))
blanchet@43444
   665
      | do_formula (AConn (c, phis)) = AConn (c, map do_formula phis)
blanchet@43444
   666
      | do_formula (AAtom tm) = AAtom (do_term true tm)
blanchet@43444
   667
  in do_formula end
blanchet@43444
   668
blanchet@43444
   669
fun formula_for_fact ctxt type_sys
blanchet@43444
   670
                     ({combformula, atomic_types, ...} : translated_formula) =
blanchet@43444
   671
  mk_ahorn (map (formula_from_fo_literal o fo_literal_from_type_literal)
blanchet@43444
   672
                (atp_type_literals_for_types type_sys Axiom atomic_types))
blanchet@43444
   673
           (formula_from_combformula ctxt type_sys
blanchet@43444
   674
                (close_combformula_universally combformula))
blanchet@43444
   675
  |> close_formula_universally
blanchet@43444
   676
blanchet@43444
   677
(* Each fact is given a unique fact number to avoid name clashes (e.g., because
blanchet@43444
   678
   of monomorphization). The TPTP explicitly forbids name clashes, and some of
blanchet@43444
   679
   the remote provers might care. *)
blanchet@43444
   680
fun formula_line_for_fact ctxt prefix type_sys
blanchet@43444
   681
                          (j, formula as {name, kind, ...}) =
blanchet@43448
   682
  Formula (prefix ^ string_of_int j ^ "_" ^ ascii_of name, kind,
blanchet@43444
   683
           formula_for_fact ctxt type_sys formula, NONE, NONE)
blanchet@43444
   684
blanchet@43444
   685
fun formula_line_for_class_rel_clause (ClassRelClause {name, subclass,
blanchet@43444
   686
                                                       superclass, ...}) =
blanchet@43444
   687
  let val ty_arg = ATerm (`I "T", []) in
blanchet@43448
   688
    Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
blanchet@43444
   689
             AConn (AImplies, [AAtom (ATerm (subclass, [ty_arg])),
blanchet@43444
   690
                               AAtom (ATerm (superclass, [ty_arg]))])
blanchet@43444
   691
             |> close_formula_universally, NONE, NONE)
blanchet@43444
   692
  end
blanchet@43444
   693
blanchet@43444
   694
fun fo_literal_from_arity_literal (TConsLit (c, t, args)) =
blanchet@43444
   695
    (true, ATerm (c, [ATerm (t, map (fn arg => ATerm (arg, [])) args)]))
blanchet@43444
   696
  | fo_literal_from_arity_literal (TVarLit (c, sort)) =
blanchet@43444
   697
    (false, ATerm (c, [ATerm (sort, [])]))
blanchet@43444
   698
blanchet@43444
   699
fun formula_line_for_arity_clause (ArityClause {name, conclLit, premLits,
blanchet@43444
   700
                                                ...}) =
blanchet@43448
   701
  Formula (arity_clause_prefix ^ ascii_of name, Axiom,
blanchet@43444
   702
           mk_ahorn (map (formula_from_fo_literal o apfst not
blanchet@43444
   703
                          o fo_literal_from_arity_literal) premLits)
blanchet@43444
   704
                    (formula_from_fo_literal
blanchet@43444
   705
                         (fo_literal_from_arity_literal conclLit))
blanchet@43444
   706
           |> close_formula_universally, NONE, NONE)
blanchet@43444
   707
blanchet@43444
   708
fun formula_line_for_conjecture ctxt type_sys
blanchet@43444
   709
        ({name, kind, combformula, ...} : translated_formula) =
blanchet@43448
   710
  Formula (conjecture_prefix ^ name, kind,
blanchet@43444
   711
           formula_from_combformula ctxt type_sys
blanchet@43444
   712
                                    (close_combformula_universally combformula)
blanchet@43444
   713
           |> close_formula_universally, NONE, NONE)
blanchet@43444
   714
blanchet@43444
   715
fun free_type_literals type_sys ({atomic_types, ...} : translated_formula) =
blanchet@43444
   716
  atomic_types |> atp_type_literals_for_types type_sys Conjecture
blanchet@43444
   717
               |> map fo_literal_from_type_literal
blanchet@43444
   718
blanchet@43444
   719
fun formula_line_for_free_type j lit =
blanchet@43448
   720
  Formula (tfree_prefix ^ string_of_int j, Hypothesis,
blanchet@43444
   721
           formula_from_fo_literal lit, NONE, NONE)
blanchet@43444
   722
fun formula_lines_for_free_types type_sys facts =
blanchet@43444
   723
  let
blanchet@43444
   724
    val litss = map (free_type_literals type_sys) facts
blanchet@43444
   725
    val lits = fold (union (op =)) litss []
blanchet@43444
   726
  in map2 formula_line_for_free_type (0 upto length lits - 1) lits end
blanchet@43444
   727
blanchet@43444
   728
(** Symbol declarations **)
blanchet@43415
   729
blanchet@43445
   730
fun should_declare_sym type_sys pred_sym s =
blanchet@43413
   731
  not (String.isPrefix bound_var_prefix s) andalso s <> "equal" andalso
blanchet@43445
   732
  (type_sys = Many_Typed orelse not pred_sym)
blanchet@43413
   733
blanchet@43445
   734
fun add_combterm_syms_to_decl_table type_sys repaired_sym_tab =
blanchet@43445
   735
  let
blanchet@43447
   736
    fun declare_sym (decl as (_, _, T, _, _)) decls =
blanchet@43450
   737
      case type_sys of
blanchet@43450
   738
        Tags (false, Sound) =>
blanchet@43450
   739
        if exists (curry Type.raw_instance T o #3) decls then
blanchet@43450
   740
          decls
blanchet@43450
   741
        else
blanchet@43450
   742
          decl :: filter_out ((fn T' => Type.raw_instance (T', T)) o #3) decls
blanchet@43450
   743
      | _ => insert (op =) decl decls
blanchet@43447
   744
    fun do_term tm =
blanchet@43445
   745
      let val (head, args) = strip_combterm_comb tm in
blanchet@43445
   746
        (case head of
blanchet@43445
   747
           CombConst ((s, s'), T, T_args) =>
blanchet@43445
   748
           let val pred_sym = is_pred_sym repaired_sym_tab s in
blanchet@43445
   749
             if should_declare_sym type_sys pred_sym s then
blanchet@43447
   750
               Symtab.map_default (s, [])
blanchet@43447
   751
                   (declare_sym (s', T_args, T, pred_sym, length args))
blanchet@43445
   752
             else
blanchet@43445
   753
               I
blanchet@43445
   754
           end
blanchet@43445
   755
         | _ => I)
blanchet@43447
   756
        #> fold do_term args
blanchet@43445
   757
      end
blanchet@43447
   758
  in do_term end
blanchet@43445
   759
fun add_fact_syms_to_decl_table type_sys repaired_sym_tab =
blanchet@43445
   760
  fact_lift (formula_fold
blanchet@43445
   761
      (add_combterm_syms_to_decl_table type_sys repaired_sym_tab))
blanchet@43445
   762
fun sym_decl_table_for_facts type_sys repaired_sym_tab facts =
blanchet@43450
   763
  Symtab.empty |> type_sys_declares_sym_types type_sys
blanchet@43445
   764
                  ? fold (add_fact_syms_to_decl_table type_sys repaired_sym_tab)
blanchet@43445
   765
                         facts
blanchet@43445
   766
blanchet@43445
   767
fun n_ary_strip_type 0 T = ([], T)
blanchet@43445
   768
  | n_ary_strip_type n (Type (@{type_name fun}, [dom_T, ran_T])) =
blanchet@43445
   769
    n_ary_strip_type (n - 1) ran_T |>> cons dom_T
blanchet@43445
   770
  | n_ary_strip_type _ _ = raise Fail "unexpected non-function"
blanchet@43445
   771
blanchet@43450
   772
fun result_type_of_decl (_, _, T, _, ary) = n_ary_strip_type ary T |> snd
blanchet@43450
   773
blanchet@43450
   774
fun decl_line_for_sym_decl s (s', _, T, pred_sym, ary) =
blanchet@43450
   775
  let val (arg_Ts, res_T) = n_ary_strip_type ary T in
blanchet@43450
   776
    Decl (sym_decl_prefix ^ ascii_of s, (s, s'),
blanchet@43450
   777
          map mangled_type_name arg_Ts,
blanchet@43450
   778
          if pred_sym then `I tptp_tff_bool_type else mangled_type_name res_T)
blanchet@43450
   779
  end
blanchet@43450
   780
blanchet@43450
   781
fun formula_line_for_sym_decl ctxt type_sys n s j (s', T_args, T, _, ary) =
blanchet@43450
   782
  let
blanchet@43450
   783
    val (arg_Ts, res_T) = n_ary_strip_type ary T
blanchet@43450
   784
    val bound_names =
blanchet@43450
   785
      1 upto length arg_Ts |> map (`I o make_bound_var o string_of_int)
blanchet@43450
   786
    val bound_tms =
blanchet@43450
   787
      bound_names ~~ arg_Ts |> map (fn (name, T) => CombConst (name, T, []))
blanchet@43450
   788
    val bound_Ts =
blanchet@43450
   789
      arg_Ts |> map (if n > 1 then SOME else K NONE)
blanchet@43450
   790
    val freshener =
blanchet@43450
   791
      case type_sys of Args _ => string_of_int j ^ "_" | _ => ""
blanchet@43450
   792
  in
blanchet@43450
   793
    Formula (sym_decl_prefix ^ freshener ^ "_" ^ ascii_of s, Axiom,
blanchet@43450
   794
             CombConst ((s, s'), T, T_args)
blanchet@43450
   795
             |> fold (curry (CombApp o swap)) bound_tms
blanchet@43450
   796
             |> type_pred_combatom type_sys res_T
blanchet@43450
   797
             |> mk_aquant AForall (bound_names ~~ bound_Ts)
blanchet@43450
   798
             |> formula_from_combformula ctxt type_sys,
blanchet@43450
   799
             NONE, NONE)
blanchet@43450
   800
  end
blanchet@43450
   801
blanchet@43450
   802
fun problem_lines_for_sym_decls ctxt type_sys (s, decls) =
blanchet@43445
   803
  if type_sys = Many_Typed then
blanchet@43450
   804
    map (decl_line_for_sym_decl s) decls
blanchet@43445
   805
  else
blanchet@43445
   806
    let
blanchet@43450
   807
      val decls =
blanchet@43450
   808
        case decls of
blanchet@43450
   809
          decl :: (decls' as _ :: _) =>
blanchet@43450
   810
          if forall (curry (op =) (result_type_of_decl decl)
blanchet@43450
   811
                     o result_type_of_decl) decls' then
blanchet@43450
   812
            [decl]
blanchet@43450
   813
          else
blanchet@43450
   814
            decls
blanchet@43450
   815
        | _ => decls
blanchet@43450
   816
      val n = length decls
blanchet@43450
   817
      val decls =
blanchet@43450
   818
        decls |> filter (should_predicate_on_type ctxt type_sys
blanchet@43450
   819
                         o result_type_of_decl)
blanchet@43445
   820
    in
blanchet@43450
   821
      map2 (formula_line_for_sym_decl ctxt type_sys n s)
blanchet@43450
   822
           (0 upto length decls - 1) decls
blanchet@43445
   823
    end
blanchet@43450
   824
blanchet@43445
   825
fun problem_lines_for_sym_decl_table ctxt type_sys sym_decl_tab =
blanchet@43445
   826
  Symtab.fold_rev (append o problem_lines_for_sym_decls ctxt type_sys)
blanchet@43445
   827
                  sym_decl_tab []
blanchet@43410
   828
blanchet@43414
   829
fun add_tff_types_in_formula (AQuant (_, xs, phi)) =
blanchet@43414
   830
    union (op =) (map_filter snd xs) #> add_tff_types_in_formula phi
blanchet@43414
   831
  | add_tff_types_in_formula (AConn (_, phis)) =
blanchet@43414
   832
    fold add_tff_types_in_formula phis
blanchet@43414
   833
  | add_tff_types_in_formula (AAtom _) = I
blanchet@43414
   834
blanchet@43433
   835
fun add_tff_types_in_problem_line (Decl (_, _, arg_Ts, res_T)) =
blanchet@43433
   836
    union (op =) (res_T :: arg_Ts)
blanchet@43448
   837
  | add_tff_types_in_problem_line (Formula (_, _, phi, _, _)) =
blanchet@43414
   838
    add_tff_types_in_formula phi
blanchet@43414
   839
blanchet@43414
   840
fun tff_types_in_problem problem =
blanchet@43414
   841
  fold (fold add_tff_types_in_problem_line o snd) problem []
blanchet@43414
   842
blanchet@43416
   843
fun decl_line_for_tff_type (s, s') =
blanchet@43439
   844
  Decl (type_decl_prefix ^ ascii_of s, (s, s'), [], `I tptp_tff_type_of_types)
blanchet@43414
   845
blanchet@43414
   846
val type_declsN = "Types"
blanchet@43415
   847
val sym_declsN = "Symbol types"
blanchet@41405
   848
val factsN = "Relevant facts"
blanchet@41405
   849
val class_relsN = "Class relationships"
blanchet@43414
   850
val aritiesN = "Arities"
blanchet@41405
   851
val helpersN = "Helper facts"
blanchet@41405
   852
val conjsN = "Conjectures"
blanchet@41561
   853
val free_typesN = "Type variables"
blanchet@41405
   854
blanchet@41405
   855
fun offset_of_heading_in_problem _ [] j = j
blanchet@41405
   856
  | offset_of_heading_in_problem needle ((heading, lines) :: problem) j =
blanchet@41405
   857
    if heading = needle then j
blanchet@41405
   858
    else offset_of_heading_in_problem needle problem (j + length lines)
blanchet@41405
   859
blanchet@43439
   860
fun prepare_atp_problem ctxt type_sys explicit_apply hyp_ts concl_t facts =
blanchet@38506
   861
  let
blanchet@41561
   862
    val (fact_names, (conjs, facts, class_rel_clauses, arity_clauses)) =
blanchet@41382
   863
      translate_formulas ctxt type_sys hyp_ts concl_t facts
blanchet@43434
   864
    val sym_tab = conjs @ facts |> sym_table_for_facts explicit_apply
blanchet@43436
   865
    val (conjs, facts) =
blanchet@43444
   866
      (conjs, facts) |> pairself (map (repair_fact type_sys sym_tab))
blanchet@43444
   867
    val repaired_sym_tab = conjs @ facts |> sym_table_for_facts false
blanchet@43432
   868
    val sym_decl_lines =
blanchet@43445
   869
      conjs @ facts
blanchet@43445
   870
      |> sym_decl_table_for_facts type_sys repaired_sym_tab
blanchet@43445
   871
      |> problem_lines_for_sym_decl_table ctxt type_sys
blanchet@43444
   872
    val helpers =
blanchet@43444
   873
      helper_facts_for_sym_table ctxt type_sys repaired_sym_tab
blanchet@43444
   874
      |> map (repair_fact type_sys sym_tab)
blanchet@43393
   875
    (* Reordering these might confuse the proof reconstruction code or the SPASS
blanchet@43393
   876
       Flotter hack. *)
blanchet@38506
   877
    val problem =
blanchet@43432
   878
      [(sym_declsN, sym_decl_lines),
blanchet@43416
   879
       (factsN, map (formula_line_for_fact ctxt fact_prefix type_sys)
blanchet@43051
   880
                    (0 upto length facts - 1 ~~ facts)),
blanchet@43416
   881
       (class_relsN, map formula_line_for_class_rel_clause class_rel_clauses),
blanchet@43416
   882
       (aritiesN, map formula_line_for_arity_clause arity_clauses),
blanchet@43432
   883
       (helpersN, map (formula_line_for_fact ctxt helper_prefix type_sys)
blanchet@43434
   884
                      (0 upto length helpers - 1 ~~ helpers)
blanchet@43450
   885
                  |> (case type_sys of
blanchet@43450
   886
                        Tags (_, Half_Sound) => cons (ti_ti_helper_fact ())
blanchet@43450
   887
                      | _ => I)),
blanchet@43416
   888
       (conjsN, map (formula_line_for_conjecture ctxt type_sys) conjs),
blanchet@43416
   889
       (free_typesN, formula_lines_for_free_types type_sys (facts @ conjs))]
blanchet@43414
   890
    val problem =
blanchet@43432
   891
      problem
blanchet@43432
   892
      |> (if type_sys = Many_Typed then
blanchet@43432
   893
            cons (type_declsN,
blanchet@43432
   894
                  map decl_line_for_tff_type (tff_types_in_problem problem))
blanchet@43432
   895
          else
blanchet@43432
   896
            I)
blanchet@43439
   897
    val (problem, pool) = problem |> nice_atp_problem (!readable_names)
blanchet@38506
   898
  in
blanchet@38506
   899
    (problem,
blanchet@38506
   900
     case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
blanchet@43456
   901
     offset_of_heading_in_problem conjsN problem 0,
blanchet@43412
   902
     offset_of_heading_in_problem factsN problem 0,
blanchet@41405
   903
     fact_names |> Vector.fromList)
blanchet@38506
   904
  end
blanchet@38506
   905
blanchet@41561
   906
(* FUDGE *)
blanchet@41561
   907
val conj_weight = 0.0
blanchet@42641
   908
val hyp_weight = 0.1
blanchet@42641
   909
val fact_min_weight = 0.2
blanchet@41561
   910
val fact_max_weight = 1.0
blanchet@41561
   911
blanchet@41561
   912
fun add_term_weights weight (ATerm (s, tms)) =
blanchet@41561
   913
  (not (is_atp_variable s) andalso s <> "equal") ? Symtab.default (s, weight)
blanchet@41561
   914
  #> fold (add_term_weights weight) tms
blanchet@43448
   915
fun add_problem_line_weights weight (Formula (_, _, phi, _, _)) =
blanchet@43413
   916
    formula_fold (add_term_weights weight) phi
blanchet@43399
   917
  | add_problem_line_weights _ _ = I
blanchet@41561
   918
blanchet@41561
   919
fun add_conjectures_weights [] = I
blanchet@41561
   920
  | add_conjectures_weights conjs =
blanchet@41561
   921
    let val (hyps, conj) = split_last conjs in
blanchet@41561
   922
      add_problem_line_weights conj_weight conj
blanchet@41561
   923
      #> fold (add_problem_line_weights hyp_weight) hyps
blanchet@41561
   924
    end
blanchet@41561
   925
blanchet@41561
   926
fun add_facts_weights facts =
blanchet@41561
   927
  let
blanchet@41561
   928
    val num_facts = length facts
blanchet@41561
   929
    fun weight_of j =
blanchet@41561
   930
      fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
blanchet@41561
   931
                        / Real.fromInt num_facts
blanchet@41561
   932
  in
blanchet@41561
   933
    map weight_of (0 upto num_facts - 1) ~~ facts
blanchet@41561
   934
    |> fold (uncurry add_problem_line_weights)
blanchet@41561
   935
  end
blanchet@41561
   936
blanchet@41561
   937
(* Weights are from 0.0 (most important) to 1.0 (least important). *)
blanchet@41561
   938
fun atp_problem_weights problem =
blanchet@41561
   939
  Symtab.empty
blanchet@41561
   940
  |> add_conjectures_weights (these (AList.lookup (op =) problem conjsN))
blanchet@41561
   941
  |> add_facts_weights (these (AList.lookup (op =) problem factsN))
blanchet@41561
   942
  |> Symtab.dest
blanchet@42590
   943
  |> sort (prod_ord Real.compare string_ord o pairself swap)
blanchet@41561
   944
blanchet@38506
   945
end;