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