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