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