src/HOL/Tools/Sledgehammer/sledgehammer_atp_translate.ML
author blanchet
Tue, 17 May 2011 15:11:36 +0200
changeset 43701 1068d8fc1331
parent 43700 1558741f8a72
child 43702 c9b0968484fb
permissions -rw-r--r--
generate type classes predicates in new "shallow" encoding
blanchet@40358
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_atp_translate.ML
blanchet@38506
     2
    Author:     Fabian Immler, TU Muenchen
blanchet@38506
     3
    Author:     Makarius
blanchet@38506
     4
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@38506
     5
blanchet@39734
     6
Translation of HOL to FOL for Sledgehammer.
blanchet@38506
     7
*)
blanchet@38506
     8
blanchet@40249
     9
signature SLEDGEHAMMER_ATP_TRANSLATE =
blanchet@38506
    10
sig
blanchet@43088
    11
  type 'a fo_term = 'a ATP_Problem.fo_term
blanchet@43580
    12
  type formula_kind = ATP_Problem.formula_kind
blanchet@38506
    13
  type 'a problem = 'a ATP_Problem.problem
blanchet@43511
    14
  type locality = Sledgehammer_Filter.locality
blanchet@43484
    15
blanchet@43484
    16
  datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
blanchet@43484
    17
  datatype type_level =
blanchet@43484
    18
    All_Types | Nonmonotonic_Types | Finite_Types | Const_Arg_Types | No_Types
blanchet@43699
    19
  datatype type_depth = Deep | Shallow
blanchet@43484
    20
blanchet@43484
    21
  datatype type_system =
blanchet@43587
    22
    Simple_Types of type_level |
blanchet@43699
    23
    Preds of polymorphism * type_level * type_depth |
blanchet@43699
    24
    Tags of polymorphism * type_level * type_depth
blanchet@43484
    25
blanchet@40358
    26
  type translated_formula
blanchet@38506
    27
blanchet@43517
    28
  val readable_names : bool Config.T
blanchet@40445
    29
  val fact_prefix : string
blanchet@38506
    30
  val conjecture_prefix : string
blanchet@43439
    31
  val predicator_base : string
blanchet@43415
    32
  val explicit_app_base : string
blanchet@43420
    33
  val type_pred_base : string
blanchet@43433
    34
  val tff_type_prefix : string
blanchet@43484
    35
  val type_sys_from_string : string -> type_system
blanchet@43484
    36
  val polymorphism_of_type_sys : type_system -> polymorphism
blanchet@43484
    37
  val level_of_type_sys : type_system -> type_level
blanchet@43484
    38
  val is_type_sys_virtually_sound : type_system -> bool
blanchet@43484
    39
  val is_type_sys_fairly_sound : type_system -> bool
blanchet@43413
    40
  val unmangled_const : string -> string * string fo_term list
blanchet@41336
    41
  val translate_atp_fact :
blanchet@43511
    42
    Proof.context -> bool -> (string * locality) * thm
blanchet@43511
    43
    -> translated_formula option * ((string * locality) * thm)
blanchet@40240
    44
  val prepare_atp_problem :
blanchet@43580
    45
    Proof.context -> formula_kind -> formula_kind -> type_system -> bool
blanchet@43580
    46
    -> term list -> term
blanchet@41339
    47
    -> (translated_formula option * ((string * 'a) * thm)) list
blanchet@43412
    48
    -> string problem * string Symtab.table * int * int
blanchet@43620
    49
       * (string * 'a) list vector * int Symtab.table
blanchet@41561
    50
  val atp_problem_weights : string problem -> (string * real) list
blanchet@38506
    51
end;
blanchet@38506
    52
blanchet@41388
    53
structure Sledgehammer_ATP_Translate : SLEDGEHAMMER_ATP_TRANSLATE =
blanchet@38506
    54
struct
blanchet@38506
    55
blanchet@38506
    56
open ATP_Problem
blanchet@39734
    57
open Metis_Translate
blanchet@38506
    58
open Sledgehammer_Util
blanchet@43511
    59
open Sledgehammer_Filter
blanchet@43511
    60
blanchet@43511
    61
(* experimental *)
blanchet@43511
    62
val generate_useful_info = false
blanchet@38506
    63
blanchet@43439
    64
(* Readable names are often much shorter, especially if types are mangled in
blanchet@43460
    65
   names. Also, the logic for generating legal SNARK sort names is only
blanchet@43460
    66
   implemented for readable names. Finally, readable names are, well, more
blanchet@43460
    67
   readable. For these reason, they are enabled by default. *)
blanchet@43517
    68
val readable_names =
blanchet@43517
    69
  Attrib.setup_config_bool @{binding sledgehammer_atp_readable_names} (K true)
blanchet@43439
    70
blanchet@43414
    71
val type_decl_prefix = "type_"
blanchet@43414
    72
val sym_decl_prefix = "sym_"
blanchet@40445
    73
val fact_prefix = "fact_"
blanchet@38506
    74
val conjecture_prefix = "conj_"
blanchet@38506
    75
val helper_prefix = "help_"
blanchet@43414
    76
val class_rel_clause_prefix = "crel_";
blanchet@38506
    77
val arity_clause_prefix = "arity_"
blanchet@40156
    78
val tfree_prefix = "tfree_"
blanchet@38506
    79
blanchet@43439
    80
val predicator_base = "hBOOL"
blanchet@43415
    81
val explicit_app_base = "hAPP"
blanchet@43413
    82
val type_pred_base = "is"
blanchet@43433
    83
val tff_type_prefix = "ty_"
blanchet@43402
    84
blanchet@43433
    85
fun make_tff_type s = tff_type_prefix ^ ascii_of s
blanchet@43402
    86
blanchet@38506
    87
(* Freshness almost guaranteed! *)
blanchet@38506
    88
val sledgehammer_weak_prefix = "Sledgehammer:"
blanchet@38506
    89
blanchet@43484
    90
datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
blanchet@43484
    91
datatype type_level =
blanchet@43484
    92
  All_Types | Nonmonotonic_Types | Finite_Types | Const_Arg_Types | No_Types
blanchet@43699
    93
datatype type_depth = Deep | Shallow
blanchet@43484
    94
blanchet@43484
    95
datatype type_system =
blanchet@43587
    96
  Simple_Types of type_level |
blanchet@43699
    97
  Preds of polymorphism * type_level * type_depth |
blanchet@43699
    98
  Tags of polymorphism * type_level * type_depth
blanchet@43484
    99
blanchet@43559
   100
fun try_unsuffixes ss s =
blanchet@43559
   101
  fold (fn s' => fn NONE => try (unsuffix s') s | some => some) ss NONE
blanchet@43559
   102
blanchet@43484
   103
fun type_sys_from_string s =
blanchet@43587
   104
  (case try (unprefix "poly_") s of
blanchet@43587
   105
     SOME s => (SOME Polymorphic, s)
blanchet@43484
   106
   | NONE =>
blanchet@43484
   107
     case try (unprefix "mono_") s of
blanchet@43587
   108
       SOME s => (SOME Monomorphic, s)
blanchet@43587
   109
     | NONE =>
blanchet@43587
   110
       case try (unprefix "mangled_") s of
blanchet@43587
   111
         SOME s => (SOME Mangled_Monomorphic, s)
blanchet@43587
   112
       | NONE => (NONE, s))
blanchet@43484
   113
  ||> (fn s =>
blanchet@43559
   114
          (* "_query" and "_bang" are for the ASCII-challenged Mirabelle. *)
blanchet@43559
   115
          case try_unsuffixes ["?", "_query"] s of
blanchet@43484
   116
            SOME s => (Nonmonotonic_Types, s)
blanchet@43484
   117
          | NONE =>
blanchet@43559
   118
            case try_unsuffixes ["!", "_bang"] s of
blanchet@43484
   119
              SOME s => (Finite_Types, s)
blanchet@43484
   120
            | NONE => (All_Types, s))
blanchet@43699
   121
  ||> apsnd (fn s =>
blanchet@43699
   122
                case try (unsuffix "_shallow") s of
blanchet@43699
   123
                  SOME s => (Shallow, s)
blanchet@43699
   124
                | NONE => (Deep, s))
blanchet@43699
   125
  |> (fn (poly, (level, (depth, core))) =>
blanchet@43699
   126
         case (core, (poly, level, depth)) of
blanchet@43699
   127
           ("simple_types", (NONE, level, Deep (* naja *))) =>
blanchet@43699
   128
           Simple_Types level
blanchet@43699
   129
         | ("preds", (SOME Polymorphic, level, depth)) =>
blanchet@43699
   130
           if level = All_Types then Preds (Polymorphic, level, depth)
blanchet@43618
   131
           else raise Same.SAME
blanchet@43699
   132
         | ("preds", (SOME poly, level, depth)) => Preds (poly, level, depth)
blanchet@43699
   133
         | ("tags", (SOME Polymorphic, level, depth)) =>
blanchet@43618
   134
           if level = All_Types orelse level = Finite_Types then
blanchet@43699
   135
             Tags (Polymorphic, level, depth)
blanchet@43618
   136
           else
blanchet@43618
   137
             raise Same.SAME
blanchet@43699
   138
         | ("tags", (SOME poly, level, depth)) => Tags (poly, level, depth)
blanchet@43699
   139
         | ("args", (SOME poly, All_Types (* naja *), Deep (* naja *))) =>
blanchet@43699
   140
           Preds (poly, Const_Arg_Types, Shallow)
blanchet@43699
   141
         | ("erased", (NONE, All_Types (* naja *), Deep (* naja *))) =>
blanchet@43699
   142
           Preds (Polymorphic, No_Types, Shallow)
blanchet@43618
   143
         | _ => raise Same.SAME)
blanchet@43618
   144
  handle Same.SAME => error ("Unknown type system: " ^ quote s ^ ".")
blanchet@43484
   145
blanchet@43587
   146
fun polymorphism_of_type_sys (Simple_Types _) = Mangled_Monomorphic
blanchet@43699
   147
  | polymorphism_of_type_sys (Preds (poly, _, _)) = poly
blanchet@43699
   148
  | polymorphism_of_type_sys (Tags (poly, _, _)) = poly
blanchet@43484
   149
blanchet@43587
   150
fun level_of_type_sys (Simple_Types level) = level
blanchet@43699
   151
  | level_of_type_sys (Preds (_, level, _)) = level
blanchet@43699
   152
  | level_of_type_sys (Tags (_, level, _)) = level
blanchet@43699
   153
blanchet@43557
   154
fun is_type_level_virtually_sound level =
blanchet@43557
   155
  level = All_Types orelse level = Nonmonotonic_Types
blanchet@43484
   156
val is_type_sys_virtually_sound =
blanchet@43484
   157
  is_type_level_virtually_sound o level_of_type_sys
blanchet@43484
   158
blanchet@43484
   159
fun is_type_level_fairly_sound level =
blanchet@43484
   160
  is_type_level_virtually_sound level orelse level = Finite_Types
blanchet@43484
   161
val is_type_sys_fairly_sound = is_type_level_fairly_sound o level_of_type_sys
blanchet@43484
   162
blanchet@43557
   163
fun is_type_level_partial level =
blanchet@43557
   164
  level = Nonmonotonic_Types orelse level = Finite_Types
blanchet@43557
   165
blanchet@43444
   166
fun formula_map f (AQuant (q, xs, phi)) = AQuant (q, xs, formula_map f phi)
blanchet@43444
   167
  | formula_map f (AConn (c, phis)) = AConn (c, map (formula_map f) phis)
blanchet@43444
   168
  | formula_map f (AAtom tm) = AAtom (f tm)
blanchet@43444
   169
blanchet@43550
   170
fun formula_fold pos f =
blanchet@43547
   171
  let
blanchet@43547
   172
    fun aux pos (AQuant (_, _, phi)) = aux pos phi
blanchet@43550
   173
      | aux pos (AConn (ANot, [phi])) = aux (Option.map not pos) phi
blanchet@43547
   174
      | aux pos (AConn (AImplies, [phi1, phi2])) =
blanchet@43550
   175
        aux (Option.map not pos) phi1 #> aux pos phi2
blanchet@43550
   176
      | aux pos (AConn (AAnd, phis)) = fold (aux pos) phis
blanchet@43550
   177
      | aux pos (AConn (AOr, phis)) = fold (aux pos) phis
blanchet@43550
   178
      | aux _ (AConn (_, phis)) = fold (aux NONE) phis
blanchet@43547
   179
      | aux pos (AAtom tm) = f pos tm
blanchet@43550
   180
  in aux (SOME pos) end
blanchet@43444
   181
blanchet@40358
   182
type translated_formula =
blanchet@38991
   183
  {name: string,
blanchet@43511
   184
   locality: locality,
blanchet@43396
   185
   kind: formula_kind,
blanchet@43433
   186
   combformula: (name, typ, combterm) formula,
blanchet@43433
   187
   atomic_types: typ list}
blanchet@38506
   188
blanchet@43511
   189
fun update_combformula f ({name, locality, kind, combformula, atomic_types}
blanchet@43511
   190
                          : translated_formula) =
blanchet@43511
   191
  {name = name, locality = locality, kind = kind, combformula = f combformula,
blanchet@43433
   192
   atomic_types = atomic_types} : translated_formula
blanchet@43413
   193
blanchet@43429
   194
fun fact_lift f ({combformula, ...} : translated_formula) = f combformula
blanchet@43429
   195
blanchet@43443
   196
val boring_consts = [explicit_app_base, @{const_name Metis.fequal}]
blanchet@43443
   197
blanchet@43443
   198
fun should_omit_type_args type_sys s =
blanchet@43460
   199
  s <> type_pred_base andalso s <> type_tag_name andalso
blanchet@43460
   200
  (s = @{const_name HOL.eq} orelse level_of_type_sys type_sys = No_Types orelse
blanchet@43460
   201
   (case type_sys of
blanchet@43700
   202
      Tags (_, All_Types, Deep) => true
blanchet@43460
   203
    | _ => polymorphism_of_type_sys type_sys <> Mangled_Monomorphic andalso
blanchet@43460
   204
           member (op =) boring_consts s))
blanchet@43547
   205
blanchet@43618
   206
(* The Booleans indicate whether all type arguments should be kept. *)
blanchet@43618
   207
datatype type_arg_policy =
blanchet@43618
   208
  Explicit_Type_Args of bool |
blanchet@43618
   209
  Mangled_Type_Args of bool |
blanchet@43618
   210
  No_Type_Args
blanchet@41384
   211
blanchet@43460
   212
fun general_type_arg_policy type_sys =
blanchet@43460
   213
  if level_of_type_sys type_sys = No_Types then
blanchet@43460
   214
    No_Type_Args
blanchet@43460
   215
  else if polymorphism_of_type_sys type_sys = Mangled_Monomorphic then
blanchet@43618
   216
    Mangled_Type_Args (is_type_sys_virtually_sound type_sys)
blanchet@43460
   217
  else
blanchet@43618
   218
    Explicit_Type_Args (is_type_sys_virtually_sound type_sys)
blanchet@43434
   219
blanchet@43395
   220
fun type_arg_policy type_sys s =
blanchet@43443
   221
  if should_omit_type_args type_sys s then No_Type_Args
blanchet@43434
   222
  else general_type_arg_policy type_sys
blanchet@43088
   223
blanchet@43224
   224
fun atp_type_literals_for_types type_sys kind Ts =
blanchet@43460
   225
  if level_of_type_sys type_sys = No_Types then
blanchet@43224
   226
    []
blanchet@43224
   227
  else
blanchet@43224
   228
    Ts |> type_literals_for_types
blanchet@43224
   229
       |> filter (fn TyLitVar _ => kind <> Conjecture
blanchet@43224
   230
                   | TyLitFree _ => kind = Conjecture)
blanchet@41385
   231
blanchet@43580
   232
fun mk_anot phi = AConn (ANot, [phi])
blanchet@38506
   233
fun mk_aconn c phi1 phi2 = AConn (c, [phi1, phi2])
blanchet@43405
   234
fun mk_aconns c phis =
blanchet@43405
   235
  let val (phis', phi') = split_last phis in
blanchet@43405
   236
    fold_rev (mk_aconn c) phis' phi'
blanchet@43405
   237
  end
blanchet@38506
   238
fun mk_ahorn [] phi = phi
blanchet@43405
   239
  | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
blanchet@43393
   240
fun mk_aquant _ [] phi = phi
blanchet@43393
   241
  | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
blanchet@43393
   242
    if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
blanchet@43393
   243
  | mk_aquant q xs phi = AQuant (q, xs, phi)
blanchet@38506
   244
blanchet@43393
   245
fun close_universally atom_vars phi =
blanchet@41393
   246
  let
blanchet@41393
   247
    fun formula_vars bounds (AQuant (_, xs, phi)) =
blanchet@43397
   248
        formula_vars (map fst xs @ bounds) phi
blanchet@41393
   249
      | formula_vars bounds (AConn (_, phis)) = fold (formula_vars bounds) phis
blanchet@43393
   250
      | formula_vars bounds (AAtom tm) =
blanchet@43397
   251
        union (op =) (atom_vars tm []
blanchet@43397
   252
                      |> filter_out (member (op =) bounds o fst))
blanchet@43393
   253
  in mk_aquant AForall (formula_vars [] phi []) phi end
blanchet@43393
   254
blanchet@43402
   255
fun combterm_vars (CombApp (tm1, tm2)) = fold combterm_vars [tm1, tm2]
blanchet@43393
   256
  | combterm_vars (CombConst _) = I
blanchet@43445
   257
  | combterm_vars (CombVar (name, T)) = insert (op =) (name, SOME T)
blanchet@43545
   258
fun close_combformula_universally phi = close_universally combterm_vars phi
blanchet@43393
   259
blanchet@43393
   260
fun term_vars (ATerm (name as (s, _), tms)) =
blanchet@43402
   261
  is_atp_variable s ? insert (op =) (name, NONE)
blanchet@43397
   262
  #> fold term_vars tms
blanchet@43545
   263
fun close_formula_universally phi = close_universally term_vars phi
blanchet@41393
   264
blanchet@43433
   265
fun fo_term_from_typ (Type (s, Ts)) =
blanchet@43433
   266
    ATerm (`make_fixed_type_const s, map fo_term_from_typ Ts)
blanchet@43433
   267
  | fo_term_from_typ (TFree (s, _)) =
blanchet@43433
   268
    ATerm (`make_fixed_type_var s, [])
blanchet@43433
   269
  | fo_term_from_typ (TVar ((x as (s, _)), _)) =
blanchet@43433
   270
    ATerm ((make_schematic_type_var x, s), [])
blanchet@43433
   271
blanchet@43433
   272
(* This shouldn't clash with anything else. *)
blanchet@43413
   273
val mangled_type_sep = "\000"
blanchet@43413
   274
blanchet@43433
   275
fun generic_mangled_type_name f (ATerm (name, [])) = f name
blanchet@43433
   276
  | generic_mangled_type_name f (ATerm (name, tys)) =
blanchet@43626
   277
    f name ^ "(" ^ space_implode "," (map (generic_mangled_type_name f) tys)
blanchet@43626
   278
    ^ ")"
blanchet@43433
   279
val mangled_type_name =
blanchet@43433
   280
  fo_term_from_typ
blanchet@43433
   281
  #> (fn ty => (make_tff_type (generic_mangled_type_name fst ty),
blanchet@43433
   282
                generic_mangled_type_name snd ty))
blanchet@43413
   283
blanchet@43445
   284
fun generic_mangled_type_suffix f g Ts =
blanchet@43413
   285
  fold_rev (curry (op ^) o g o prefix mangled_type_sep
blanchet@43445
   286
            o generic_mangled_type_name f) Ts ""
blanchet@43433
   287
fun mangled_const_name T_args (s, s') =
blanchet@43433
   288
  let val ty_args = map fo_term_from_typ T_args in
blanchet@43433
   289
    (s ^ generic_mangled_type_suffix fst ascii_of ty_args,
blanchet@43433
   290
     s' ^ generic_mangled_type_suffix snd I ty_args)
blanchet@43433
   291
  end
blanchet@43413
   292
blanchet@43413
   293
val parse_mangled_ident =
blanchet@43413
   294
  Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
blanchet@43413
   295
blanchet@43413
   296
fun parse_mangled_type x =
blanchet@43413
   297
  (parse_mangled_ident
blanchet@43413
   298
   -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
blanchet@43413
   299
                    [] >> ATerm) x
blanchet@43413
   300
and parse_mangled_types x =
blanchet@43413
   301
  (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
blanchet@43413
   302
blanchet@43413
   303
fun unmangled_type s =
blanchet@43413
   304
  s |> suffix ")" |> raw_explode
blanchet@43413
   305
    |> Scan.finite Symbol.stopper
blanchet@43413
   306
           (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
blanchet@43413
   307
                                                quote s)) parse_mangled_type))
blanchet@43413
   308
    |> fst
blanchet@43413
   309
blanchet@43432
   310
val unmangled_const_name = space_explode mangled_type_sep #> hd
blanchet@43413
   311
fun unmangled_const s =
blanchet@43413
   312
  let val ss = space_explode mangled_type_sep s in
blanchet@43413
   313
    (hd ss, map unmangled_type (tl ss))
blanchet@43413
   314
  end
blanchet@43413
   315
blanchet@43545
   316
fun introduce_proxies tm =
blanchet@43439
   317
  let
blanchet@43439
   318
    fun aux top_level (CombApp (tm1, tm2)) =
blanchet@43439
   319
        CombApp (aux top_level tm1, aux false tm2)
blanchet@43445
   320
      | aux top_level (CombConst (name as (s, s'), T, T_args)) =
blanchet@43441
   321
        (case proxify_const s of
blanchet@43439
   322
           SOME proxy_base =>
blanchet@43439
   323
           if top_level then
blanchet@43439
   324
             (case s of
blanchet@43439
   325
                "c_False" => (tptp_false, s')
blanchet@43439
   326
              | "c_True" => (tptp_true, s')
blanchet@43439
   327
              | _ => name, [])
blanchet@43440
   328
           else
blanchet@43445
   329
             (proxy_base |>> prefix const_prefix, T_args)
blanchet@43445
   330
          | NONE => (name, T_args))
blanchet@43445
   331
        |> (fn (name, T_args) => CombConst (name, T, T_args))
blanchet@43439
   332
      | aux _ tm = tm
blanchet@43545
   333
  in aux true tm end
blanchet@43439
   334
blanchet@43433
   335
fun combformula_from_prop thy eq_as_iff =
blanchet@38506
   336
  let
blanchet@43439
   337
    fun do_term bs t atomic_types =
blanchet@41388
   338
      combterm_from_term thy bs (Envir.eta_contract t)
blanchet@43439
   339
      |>> (introduce_proxies #> AAtom)
blanchet@43439
   340
      ||> union (op =) atomic_types
blanchet@38506
   341
    fun do_quant bs q s T t' =
blanchet@38743
   342
      let val s = Name.variant (map fst bs) s in
blanchet@38743
   343
        do_formula ((s, T) :: bs) t'
blanchet@43433
   344
        #>> mk_aquant q [(`make_bound_var s, SOME T)]
blanchet@38743
   345
      end
blanchet@38506
   346
    and do_conn bs c t1 t2 =
blanchet@38506
   347
      do_formula bs t1 ##>> do_formula bs t2
blanchet@43402
   348
      #>> uncurry (mk_aconn c)
blanchet@38506
   349
    and do_formula bs t =
blanchet@38506
   350
      case t of
blanchet@43402
   351
        @{const Not} $ t1 => do_formula bs t1 #>> mk_anot
blanchet@38506
   352
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@38506
   353
        do_quant bs AForall s T t'
blanchet@38506
   354
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@38506
   355
        do_quant bs AExists s T t'
haftmann@39028
   356
      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd t1 t2
haftmann@39028
   357
      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr t1 t2
haftmann@39019
   358
      | @{const HOL.implies} $ t1 $ t2 => do_conn bs AImplies t1 t2
haftmann@39093
   359
      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@41388
   360
        if eq_as_iff then do_conn bs AIff t1 t2 else do_term bs t
blanchet@41388
   361
      | _ => do_term bs t
blanchet@38506
   362
  in do_formula [] end
blanchet@38506
   363
blanchet@43615
   364
fun presimplify_term ctxt =
blanchet@43615
   365
  Skip_Proof.make_thm (Proof_Context.theory_of ctxt)
blanchet@43615
   366
  #> Meson.presimplify ctxt
blanchet@43615
   367
  #> prop_of
blanchet@38506
   368
wenzelm@41739
   369
fun concealed_bound_name j = sledgehammer_weak_prefix ^ string_of_int j
blanchet@38506
   370
fun conceal_bounds Ts t =
blanchet@38506
   371
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@38506
   372
                    (0 upto length Ts - 1 ~~ Ts), t)
blanchet@38506
   373
fun reveal_bounds Ts =
blanchet@38506
   374
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@38506
   375
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@38506
   376
blanchet@43612
   377
fun extensionalize_term ctxt t =
blanchet@43612
   378
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43612
   379
    t |> cterm_of thy |> Meson.extensionalize_conv ctxt
blanchet@43612
   380
      |> prop_of |> Logic.dest_equals |> snd
blanchet@43612
   381
  end
blanchet@38831
   382
blanchet@38506
   383
fun introduce_combinators_in_term ctxt kind t =
wenzelm@43232
   384
  let val thy = Proof_Context.theory_of ctxt in
blanchet@38716
   385
    if Meson.is_fol_term thy t then
blanchet@38716
   386
      t
blanchet@38716
   387
    else
blanchet@38716
   388
      let
blanchet@38716
   389
        fun aux Ts t =
blanchet@38716
   390
          case t of
blanchet@38716
   391
            @{const Not} $ t1 => @{const Not} $ aux Ts t1
blanchet@38716
   392
          | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@38716
   393
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38890
   394
          | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@38890
   395
            aux Ts (t0 $ eta_expand Ts t1 1)
blanchet@38716
   396
          | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@38716
   397
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38890
   398
          | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@38890
   399
            aux Ts (t0 $ eta_expand Ts t1 1)
haftmann@39028
   400
          | (t0 as @{const HOL.conj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39028
   401
          | (t0 as @{const HOL.disj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39019
   402
          | (t0 as @{const HOL.implies}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39093
   403
          | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
blanchet@38716
   404
              $ t1 $ t2 =>
blanchet@38716
   405
            t0 $ aux Ts t1 $ aux Ts t2
blanchet@38716
   406
          | _ => if not (exists_subterm (fn Abs _ => true | _ => false) t) then
blanchet@38716
   407
                   t
blanchet@38716
   408
                 else
blanchet@38716
   409
                   t |> conceal_bounds Ts
blanchet@38716
   410
                     |> Envir.eta_contract
blanchet@38716
   411
                     |> cterm_of thy
blanchet@40071
   412
                     |> Meson_Clausify.introduce_combinators_in_cterm
blanchet@38716
   413
                     |> prop_of |> Logic.dest_equals |> snd
blanchet@38716
   414
                     |> reveal_bounds Ts
blanchet@39616
   415
        val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
blanchet@38716
   416
      in t |> aux [] |> singleton (Variable.export_terms ctxt' ctxt) end
blanchet@38716
   417
      handle THM _ =>
blanchet@38716
   418
             (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@38836
   419
             if kind = Conjecture then HOLogic.false_const
blanchet@38836
   420
             else HOLogic.true_const
blanchet@38716
   421
  end
blanchet@38506
   422
blanchet@38506
   423
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@43224
   424
   same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
blanchet@38506
   425
fun freeze_term t =
blanchet@38506
   426
  let
blanchet@38506
   427
    fun aux (t $ u) = aux t $ aux u
blanchet@38506
   428
      | aux (Abs (s, T, t)) = Abs (s, T, aux t)
blanchet@38506
   429
      | aux (Var ((s, i), T)) =
blanchet@38506
   430
        Free (sledgehammer_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
blanchet@38506
   431
      | aux t = t
blanchet@38506
   432
  in t |> exists_subterm is_Var t ? aux end
blanchet@38506
   433
blanchet@40445
   434
(* making fact and conjecture formulas *)
blanchet@43511
   435
fun make_formula ctxt eq_as_iff presimp name loc kind t =
blanchet@38506
   436
  let
wenzelm@43232
   437
    val thy = Proof_Context.theory_of ctxt
blanchet@38831
   438
    val t = t |> Envir.beta_eta_contract
blanchet@38890
   439
              |> transform_elim_term
blanchet@41459
   440
              |> Object_Logic.atomize_term thy
blanchet@43434
   441
    val need_trueprop = (fastype_of t = @{typ bool})
blanchet@38890
   442
    val t = t |> need_trueprop ? HOLogic.mk_Trueprop
blanchet@43607
   443
              |> Raw_Simplifier.rewrite_term thy
blanchet@43607
   444
                     (Meson.unfold_set_const_simps ctxt) []
blanchet@43612
   445
              |> extensionalize_term ctxt
blanchet@43615
   446
              |> presimp ? presimplify_term ctxt
blanchet@38506
   447
              |> perhaps (try (HOLogic.dest_Trueprop))
blanchet@38506
   448
              |> introduce_combinators_in_term ctxt kind
blanchet@38836
   449
              |> kind <> Axiom ? freeze_term
blanchet@43433
   450
    val (combformula, atomic_types) =
blanchet@43433
   451
      combformula_from_prop thy eq_as_iff t []
blanchet@38506
   452
  in
blanchet@43511
   453
    {name = name, locality = loc, kind = kind, combformula = combformula,
blanchet@43433
   454
     atomic_types = atomic_types}
blanchet@38506
   455
  end
blanchet@38506
   456
blanchet@43511
   457
fun make_fact ctxt keep_trivial eq_as_iff presimp ((name, loc), t) =
blanchet@43511
   458
  case (keep_trivial, make_formula ctxt eq_as_iff presimp name loc Axiom t) of
blanchet@42861
   459
    (false, {combformula = AAtom (CombConst (("c_True", _), _, _)), ...}) =>
blanchet@42861
   460
    NONE
blanchet@42861
   461
  | (_, formula) => SOME formula
blanchet@43432
   462
blanchet@43580
   463
fun make_conjecture ctxt prem_kind ts =
blanchet@38836
   464
  let val last = length ts - 1 in
blanchet@43580
   465
    map2 (fn j => fn t =>
blanchet@43580
   466
             let
blanchet@43580
   467
               val (kind, maybe_negate) =
blanchet@43580
   468
                 if j = last then
blanchet@43580
   469
                   (Conjecture, I)
blanchet@43580
   470
                 else
blanchet@43580
   471
                   (prem_kind,
blanchet@43580
   472
                    if prem_kind = Conjecture then update_combformula mk_anot
blanchet@43580
   473
                    else I)
blanchet@43580
   474
              in
blanchet@43580
   475
                make_formula ctxt true true (string_of_int j) Chained kind t
blanchet@43580
   476
                |> maybe_negate
blanchet@43580
   477
              end)
blanchet@38836
   478
         (0 upto last) ts
blanchet@38836
   479
  end
blanchet@38506
   480
blanchet@43552
   481
(** Finite and infinite type inference **)
blanchet@43552
   482
blanchet@43552
   483
(* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
blanchet@43552
   484
   dangerous because their "exhaust" properties can easily lead to unsound ATP
blanchet@43552
   485
   proofs. On the other hand, all HOL infinite types can be given the same
blanchet@43552
   486
   models in first-order logic (via Löwenheim-Skolem). *)
blanchet@43552
   487
blanchet@43552
   488
fun should_encode_type _ _ All_Types _ = true
blanchet@43552
   489
  | should_encode_type ctxt _ Finite_Types T = is_type_surely_finite ctxt T
blanchet@43552
   490
  | should_encode_type _ nonmono_Ts Nonmonotonic_Types T =
blanchet@43552
   491
    exists (curry Type.raw_instance T) nonmono_Ts
blanchet@43552
   492
  | should_encode_type _ _ _ _ = false
blanchet@43552
   493
blanchet@43700
   494
fun should_predicate_on_type ctxt nonmono_Ts (Preds (_, level, depth)) T =
blanchet@43700
   495
    (case depth of
blanchet@43700
   496
       Deep => should_encode_type ctxt nonmono_Ts level T
blanchet@43700
   497
     | Shallow => error "Not implemented yet.")
blanchet@43552
   498
  | should_predicate_on_type _ _ _ _ = false
blanchet@43552
   499
blanchet@43700
   500
datatype tag_site = Top_Level | Eq_Arg | Elsewhere
blanchet@43700
   501
blanchet@43700
   502
fun should_tag_with_type _ _ _ Top_Level _ _ = false
blanchet@43700
   503
  | should_tag_with_type ctxt nonmono_Ts (Tags (_, level, depth)) site u T =
blanchet@43700
   504
    (case depth of
blanchet@43700
   505
       Deep => should_encode_type ctxt nonmono_Ts level T
blanchet@43700
   506
     | Shallow =>
blanchet@43700
   507
       case (site, u) of
blanchet@43700
   508
         (Eq_Arg, CombVar _) => should_encode_type ctxt nonmono_Ts level T
blanchet@43700
   509
       | _ => false)
blanchet@43700
   510
  | should_tag_with_type _ _ _ _ _ _ = false
blanchet@43552
   511
blanchet@43552
   512
val homo_infinite_T = @{typ ind} (* any infinite type *)
blanchet@43552
   513
blanchet@43552
   514
fun homogenized_type ctxt nonmono_Ts level T =
blanchet@43552
   515
  if should_encode_type ctxt nonmono_Ts level T then T else homo_infinite_T
blanchet@43552
   516
blanchet@43444
   517
(** "hBOOL" and "hAPP" **)
blanchet@41561
   518
blanchet@43445
   519
type sym_info =
blanchet@43434
   520
  {pred_sym : bool, min_ary : int, max_ary : int, typ : typ option}
blanchet@43434
   521
blanchet@43445
   522
fun add_combterm_syms_to_table explicit_apply =
blanchet@43429
   523
  let
blanchet@43429
   524
    fun aux top_level tm =
blanchet@43429
   525
      let val (head, args) = strip_combterm_comb tm in
blanchet@43429
   526
        (case head of
blanchet@43434
   527
           CombConst ((s, _), T, _) =>
blanchet@43429
   528
           if String.isPrefix bound_var_prefix s then
blanchet@43429
   529
             I
blanchet@43429
   530
           else
blanchet@43434
   531
             let val ary = length args in
blanchet@43429
   532
               Symtab.map_default
blanchet@43429
   533
                   (s, {pred_sym = true,
blanchet@43434
   534
                        min_ary = if explicit_apply then 0 else ary,
blanchet@43434
   535
                        max_ary = 0, typ = SOME T})
blanchet@43434
   536
                   (fn {pred_sym, min_ary, max_ary, typ} =>
blanchet@43429
   537
                       {pred_sym = pred_sym andalso top_level,
blanchet@43434
   538
                        min_ary = Int.min (ary, min_ary),
blanchet@43434
   539
                        max_ary = Int.max (ary, max_ary),
blanchet@43434
   540
                        typ = if typ = SOME T then typ else NONE})
blanchet@43429
   541
            end
blanchet@43429
   542
         | _ => I)
blanchet@43429
   543
        #> fold (aux false) args
blanchet@43429
   544
      end
blanchet@43429
   545
  in aux true end
blanchet@43545
   546
fun add_fact_syms_to_table explicit_apply =
blanchet@43550
   547
  fact_lift (formula_fold true (K (add_combterm_syms_to_table explicit_apply)))
blanchet@38506
   548
blanchet@43546
   549
val default_sym_table_entries : (string * sym_info) list =
blanchet@43434
   550
  [("equal", {pred_sym = true, min_ary = 2, max_ary = 2, typ = NONE}),
blanchet@43439
   551
   (make_fixed_const predicator_base,
blanchet@43434
   552
    {pred_sym = true, min_ary = 1, max_ary = 1, typ = NONE})] @
blanchet@43439
   553
  ([tptp_false, tptp_true]
blanchet@43434
   554
   |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, typ = NONE}))
blanchet@41388
   555
blanchet@43415
   556
fun sym_table_for_facts explicit_apply facts =
blanchet@43439
   557
  Symtab.empty |> fold Symtab.default default_sym_table_entries
blanchet@43445
   558
               |> fold (add_fact_syms_to_table explicit_apply) facts
blanchet@38506
   559
blanchet@43429
   560
fun min_arity_of sym_tab s =
blanchet@43429
   561
  case Symtab.lookup sym_tab s of
blanchet@43445
   562
    SOME ({min_ary, ...} : sym_info) => min_ary
blanchet@43429
   563
  | NONE =>
blanchet@43429
   564
    case strip_prefix_and_unascii const_prefix s of
blanchet@43418
   565
      SOME s =>
blanchet@43441
   566
      let val s = s |> unmangled_const_name |> invert_const in
blanchet@43439
   567
        if s = predicator_base then 1
blanchet@43418
   568
        else if s = explicit_app_base then 2
blanchet@43418
   569
        else if s = type_pred_base then 1
blanchet@43428
   570
        else 0
blanchet@43418
   571
      end
blanchet@38506
   572
    | NONE => 0
blanchet@38506
   573
blanchet@38506
   574
(* True if the constant ever appears outside of the top-level position in
blanchet@38506
   575
   literals, or if it appears with different arities (e.g., because of different
blanchet@38506
   576
   type instantiations). If false, the constant always receives all of its
blanchet@38506
   577
   arguments and is used as a predicate. *)
blanchet@43429
   578
fun is_pred_sym sym_tab s =
blanchet@43429
   579
  case Symtab.lookup sym_tab s of
blanchet@43445
   580
    SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
blanchet@43445
   581
    pred_sym andalso min_ary = max_ary
blanchet@43429
   582
  | NONE => false
blanchet@38506
   583
blanchet@43439
   584
val predicator_combconst =
blanchet@43439
   585
  CombConst (`make_fixed_const predicator_base, @{typ "bool => bool"}, [])
blanchet@43439
   586
fun predicator tm = CombApp (predicator_combconst, tm)
blanchet@38506
   587
blanchet@43439
   588
fun introduce_predicators_in_combterm sym_tab tm =
blanchet@43413
   589
  case strip_combterm_comb tm of
blanchet@43413
   590
    (CombConst ((s, _), _, _), _) =>
blanchet@43439
   591
    if is_pred_sym sym_tab s then tm else predicator tm
blanchet@43439
   592
  | _ => predicator tm
blanchet@38506
   593
blanchet@43415
   594
fun list_app head args = fold (curry (CombApp o swap)) args head
blanchet@38506
   595
blanchet@43415
   596
fun explicit_app arg head =
blanchet@43415
   597
  let
blanchet@43433
   598
    val head_T = combtyp_of head
blanchet@43563
   599
    val (arg_T, res_T) = dest_funT head_T
blanchet@43415
   600
    val explicit_app =
blanchet@43433
   601
      CombConst (`make_fixed_const explicit_app_base, head_T --> head_T,
blanchet@43563
   602
                 [arg_T, res_T])
blanchet@43415
   603
  in list_app explicit_app [head, arg] end
blanchet@43415
   604
fun list_explicit_app head args = fold explicit_app args head
blanchet@43415
   605
blanchet@43436
   606
fun introduce_explicit_apps_in_combterm sym_tab =
blanchet@43415
   607
  let
blanchet@43415
   608
    fun aux tm =
blanchet@43415
   609
      case strip_combterm_comb tm of
blanchet@43415
   610
        (head as CombConst ((s, _), _, _), args) =>
blanchet@43415
   611
        args |> map aux
blanchet@43428
   612
             |> chop (min_arity_of sym_tab s)
blanchet@43415
   613
             |>> list_app head
blanchet@43415
   614
             |-> list_explicit_app
blanchet@43415
   615
      | (head, args) => list_explicit_app head (map aux args)
blanchet@43415
   616
  in aux end
blanchet@43415
   617
blanchet@43618
   618
fun chop_fun 0 T = ([], T)
blanchet@43618
   619
  | chop_fun n (Type (@{type_name fun}, [dom_T, ran_T])) =
blanchet@43618
   620
    chop_fun (n - 1) ran_T |>> cons dom_T
blanchet@43618
   621
  | chop_fun _ _ = raise Fail "unexpected non-function"
blanchet@43618
   622
blanchet@43651
   623
fun filter_type_args _ _ _ [] = []
blanchet@43651
   624
  | filter_type_args thy s arity T_args =
blanchet@43652
   625
    let val U = s |> Sign.the_const_type thy (* may throw "TYPE" *) in
blanchet@43652
   626
      case Term.add_tvarsT (U |> chop_fun arity |> snd) [] of
blanchet@43652
   627
        [] => []
blanchet@43652
   628
      | res_U_vars =>
blanchet@43652
   629
        let val U_args = (s, U) |> Sign.const_typargs thy in
blanchet@43652
   630
          U_args ~~ T_args
blanchet@43652
   631
          |> map_filter (fn (U, T) =>
blanchet@43652
   632
                            if member (op =) res_U_vars (dest_TVar U) then
blanchet@43652
   633
                              SOME T
blanchet@43652
   634
                            else
blanchet@43652
   635
                              NONE)
blanchet@43652
   636
        end
blanchet@43651
   637
    end
blanchet@43651
   638
    handle TYPE _ => T_args
blanchet@43618
   639
blanchet@43618
   640
fun enforce_type_arg_policy_in_combterm ctxt nonmono_Ts type_sys =
blanchet@43618
   641
  let
blanchet@43618
   642
    val thy = Proof_Context.theory_of ctxt
blanchet@43618
   643
    fun aux arity (CombApp (tm1, tm2)) =
blanchet@43618
   644
        CombApp (aux (arity + 1) tm1, aux 0 tm2)
blanchet@43618
   645
      | aux arity (CombConst (name as (s, _), T, T_args)) =
blanchet@43571
   646
        let
blanchet@43571
   647
          val level = level_of_type_sys type_sys
blanchet@43571
   648
          val (T, T_args) =
blanchet@43571
   649
            (* Aggressively merge most "hAPPs" if the type system is unsound
blanchet@43571
   650
               anyway, by distinguishing overloads only on the homogenized
blanchet@43571
   651
               result type. *)
blanchet@43571
   652
            if s = const_prefix ^ explicit_app_base andalso
blanchet@43591
   653
               length T_args = 2 andalso
blanchet@43571
   654
               not (is_type_sys_virtually_sound type_sys) then
blanchet@43571
   655
              T_args |> map (homogenized_type ctxt nonmono_Ts level)
blanchet@43571
   656
                     |> (fn Ts => let val T = hd Ts --> nth Ts 1 in
blanchet@43618
   657
                                    (T --> T, tl Ts) (* ### FIXME: need tl? *)
blanchet@43571
   658
                                  end)
blanchet@43571
   659
            else
blanchet@43571
   660
              (T, T_args)
blanchet@43571
   661
        in
blanchet@43571
   662
          (case strip_prefix_and_unascii const_prefix s of
blanchet@43571
   663
             NONE => (name, T_args)
blanchet@43571
   664
           | SOME s'' =>
blanchet@43618
   665
             let
blanchet@43618
   666
               val s'' = invert_const s''
blanchet@43618
   667
               fun filtered_T_args true = T_args
blanchet@43618
   668
                 | filtered_T_args false = filter_type_args thy s'' arity T_args
blanchet@43618
   669
             in
blanchet@43571
   670
               case type_arg_policy type_sys s'' of
blanchet@43618
   671
                 Explicit_Type_Args keep_all => (name, filtered_T_args keep_all)
blanchet@43618
   672
               | Mangled_Type_Args keep_all =>
blanchet@43618
   673
                 (mangled_const_name (filtered_T_args keep_all) name, [])
blanchet@43618
   674
               | No_Type_Args => (name, [])
blanchet@43571
   675
             end)
blanchet@43571
   676
          |> (fn (name, T_args) => CombConst (name, T, T_args))
blanchet@43571
   677
        end
blanchet@43618
   678
      | aux _ tm = tm
blanchet@43618
   679
  in aux 0 end
blanchet@43444
   680
blanchet@43571
   681
fun repair_combterm ctxt nonmono_Ts type_sys sym_tab =
blanchet@43436
   682
  introduce_explicit_apps_in_combterm sym_tab
blanchet@43439
   683
  #> introduce_predicators_in_combterm sym_tab
blanchet@43618
   684
  #> enforce_type_arg_policy_in_combterm ctxt nonmono_Ts type_sys
blanchet@43571
   685
fun repair_fact ctxt nonmono_Ts type_sys sym_tab =
blanchet@43571
   686
  update_combformula (formula_map
blanchet@43571
   687
      (repair_combterm ctxt nonmono_Ts type_sys sym_tab))
blanchet@43444
   688
blanchet@43444
   689
(** Helper facts **)
blanchet@43444
   690
blanchet@43444
   691
fun ti_ti_helper_fact () =
blanchet@43444
   692
  let
blanchet@43444
   693
    fun var s = ATerm (`I s, [])
blanchet@43460
   694
    fun tag tm = ATerm (`make_fixed_const type_tag_name, [var "X", tm])
blanchet@43444
   695
  in
blanchet@43483
   696
    Formula (helper_prefix ^ "ti_ti", Axiom,
blanchet@43444
   697
             AAtom (ATerm (`I "equal", [tag (tag (var "Y")), tag (var "Y")]))
blanchet@43444
   698
             |> close_formula_universally, NONE, NONE)
blanchet@43444
   699
  end
blanchet@43444
   700
blanchet@43445
   701
fun helper_facts_for_sym ctxt type_sys (s, {typ, ...} : sym_info) =
blanchet@43444
   702
  case strip_prefix_and_unascii const_prefix s of
blanchet@43444
   703
    SOME mangled_s =>
blanchet@43444
   704
    let
blanchet@43444
   705
      val thy = Proof_Context.theory_of ctxt
blanchet@43444
   706
      val unmangled_s = mangled_s |> unmangled_const_name
blanchet@43450
   707
      fun dub_and_inst c needs_some_types (th, j) =
blanchet@43450
   708
        ((c ^ "_" ^ string_of_int j ^ (if needs_some_types then "T" else ""),
blanchet@43511
   709
          Chained),
blanchet@43444
   710
         let val t = th |> prop_of in
blanchet@43618
   711
           t |> ((case general_type_arg_policy type_sys of
blanchet@43618
   712
                    Mangled_Type_Args _ => true
blanchet@43618
   713
                  | _ => false) andalso
blanchet@43444
   714
                 not (null (Term.hidden_polymorphism t)))
blanchet@43444
   715
                ? (case typ of
blanchet@43444
   716
                     SOME T => specialize_type thy (invert_const unmangled_s, T)
blanchet@43444
   717
                   | NONE => I)
blanchet@43444
   718
         end)
blanchet@43444
   719
      fun make_facts eq_as_iff =
blanchet@43444
   720
        map_filter (make_fact ctxt false eq_as_iff false)
blanchet@43460
   721
      val has_some_types = is_type_sys_fairly_sound type_sys
blanchet@43444
   722
    in
blanchet@43444
   723
      metis_helpers
blanchet@43450
   724
      |> maps (fn (metis_s, (needs_some_types, ths)) =>
blanchet@43444
   725
                  if metis_s <> unmangled_s orelse
blanchet@43460
   726
                     (needs_some_types andalso not has_some_types) then
blanchet@43444
   727
                    []
blanchet@43444
   728
                  else
blanchet@43444
   729
                    ths ~~ (1 upto length ths)
blanchet@43450
   730
                    |> map (dub_and_inst mangled_s needs_some_types)
blanchet@43450
   731
                    |> make_facts (not needs_some_types))
blanchet@43444
   732
    end
blanchet@43444
   733
  | NONE => []
blanchet@43444
   734
fun helper_facts_for_sym_table ctxt type_sys sym_tab =
blanchet@43444
   735
  Symtab.fold_rev (append o helper_facts_for_sym ctxt type_sys) sym_tab []
blanchet@43444
   736
blanchet@43444
   737
fun translate_atp_fact ctxt keep_trivial =
blanchet@43444
   738
  `(make_fact ctxt keep_trivial true true o apsnd prop_of)
blanchet@43444
   739
blanchet@43580
   740
fun translate_formulas ctxt prem_kind type_sys hyp_ts concl_t rich_facts =
blanchet@43444
   741
  let
blanchet@43444
   742
    val thy = Proof_Context.theory_of ctxt
blanchet@43444
   743
    val fact_ts = map (prop_of o snd o snd) rich_facts
blanchet@43444
   744
    val (facts, fact_names) =
blanchet@43444
   745
      rich_facts
blanchet@43444
   746
      |> map_filter (fn (NONE, _) => NONE
blanchet@43444
   747
                      | (SOME fact, (name, _)) => SOME (fact, name))
blanchet@43444
   748
      |> ListPair.unzip
blanchet@43444
   749
    (* Remove existing facts from the conjecture, as this can dramatically
blanchet@43444
   750
       boost an ATP's performance (for some reason). *)
blanchet@43444
   751
    val hyp_ts = hyp_ts |> filter_out (member (op aconv) fact_ts)
blanchet@43444
   752
    val goal_t = Logic.list_implies (hyp_ts, concl_t)
blanchet@43444
   753
    val all_ts = goal_t :: fact_ts
blanchet@43444
   754
    val subs = tfree_classes_of_terms all_ts
blanchet@43444
   755
    val supers = tvar_classes_of_terms all_ts
blanchet@43444
   756
    val tycons = type_consts_of_terms thy all_ts
blanchet@43580
   757
    val conjs = make_conjecture ctxt prem_kind (hyp_ts @ [concl_t])
blanchet@43444
   758
    val (supers', arity_clauses) =
blanchet@43460
   759
      if level_of_type_sys type_sys = No_Types then ([], [])
blanchet@43444
   760
      else make_arity_clauses thy tycons supers
blanchet@43444
   761
    val class_rel_clauses = make_class_rel_clauses thy subs supers'
blanchet@43444
   762
  in
blanchet@43444
   763
    (fact_names |> map single, (conjs, facts, class_rel_clauses, arity_clauses))
blanchet@43444
   764
  end
blanchet@43444
   765
blanchet@43444
   766
fun fo_literal_from_type_literal (TyLitVar (class, name)) =
blanchet@43444
   767
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@43444
   768
  | fo_literal_from_type_literal (TyLitFree (class, name)) =
blanchet@43444
   769
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@43444
   770
blanchet@43444
   771
fun formula_from_fo_literal (pos, t) = AAtom t |> not pos ? mk_anot
blanchet@43444
   772
blanchet@43571
   773
fun type_pred_combatom ctxt nonmono_Ts type_sys T tm =
blanchet@43444
   774
  CombApp (CombConst (`make_fixed_const type_pred_base, T --> @{typ bool}, [T]),
blanchet@43444
   775
           tm)
blanchet@43618
   776
  |> enforce_type_arg_policy_in_combterm ctxt nonmono_Ts type_sys
blanchet@43444
   777
  |> AAtom
blanchet@43444
   778
blanchet@43700
   779
fun tag_with_type ctxt nonmono_Ts type_sys T tm =
blanchet@43700
   780
  CombConst (`make_fixed_const type_tag_name, T --> T, [T])
blanchet@43700
   781
  |> enforce_type_arg_policy_in_combterm ctxt nonmono_Ts type_sys
blanchet@43700
   782
  |> term_from_combterm ctxt nonmono_Ts type_sys Top_Level
blanchet@43700
   783
  |> (fn ATerm (s, tms) => ATerm (s, tms @ [tm]))
blanchet@43700
   784
and term_from_combterm ctxt nonmono_Ts type_sys site u =
blanchet@43444
   785
  let
blanchet@43700
   786
    val (head, args) = strip_combterm_comb u
blanchet@43700
   787
    val (x as (s, _), T_args) =
blanchet@43700
   788
      case head of
blanchet@43700
   789
        CombConst (name, _, T_args) => (name, T_args)
blanchet@43700
   790
      | CombVar (name, _) => (name, [])
blanchet@43700
   791
      | CombApp _ => raise Fail "impossible \"CombApp\""
blanchet@43700
   792
    val arg_site = if site = Top_Level andalso s = "equal" then Eq_Arg
blanchet@43700
   793
                   else Elsewhere
blanchet@43700
   794
    val t = ATerm (x, map fo_term_from_typ T_args @
blanchet@43700
   795
                      map (term_from_combterm ctxt nonmono_Ts type_sys arg_site)
blanchet@43700
   796
                          args)
blanchet@43700
   797
    val T = combtyp_of u
blanchet@43700
   798
  in
blanchet@43700
   799
    t |> (if should_tag_with_type ctxt nonmono_Ts type_sys site u T then
blanchet@43700
   800
            tag_with_type ctxt nonmono_Ts type_sys T
blanchet@43700
   801
          else
blanchet@43700
   802
            I)
blanchet@43700
   803
  end
blanchet@43700
   804
and formula_from_combformula ctxt nonmono_Ts type_sys =
blanchet@43700
   805
  let
blanchet@43444
   806
    val do_bound_type =
blanchet@43552
   807
      case type_sys of
blanchet@43587
   808
        Simple_Types level =>
blanchet@43552
   809
        SOME o mangled_type_name o homogenized_type ctxt nonmono_Ts level
blanchet@43552
   810
      | _ => K NONE
blanchet@43444
   811
    fun do_out_of_bound_type (s, T) =
blanchet@43550
   812
      if should_predicate_on_type ctxt nonmono_Ts type_sys T then
blanchet@43571
   813
        type_pred_combatom ctxt nonmono_Ts type_sys T (CombVar (s, T))
blanchet@43444
   814
        |> do_formula |> SOME
blanchet@43444
   815
      else
blanchet@43444
   816
        NONE
blanchet@43444
   817
    and do_formula (AQuant (q, xs, phi)) =
blanchet@43444
   818
        AQuant (q, xs |> map (apsnd (fn NONE => NONE
blanchet@43445
   819
                                      | SOME T => do_bound_type T)),
blanchet@43444
   820
                (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
blanchet@43444
   821
                    (map_filter
blanchet@43444
   822
                         (fn (_, NONE) => NONE
blanchet@43445
   823
                           | (s, SOME T) => do_out_of_bound_type (s, T)) xs)
blanchet@43444
   824
                    (do_formula phi))
blanchet@43444
   825
      | do_formula (AConn (c, phis)) = AConn (c, map do_formula phis)
blanchet@43700
   826
      | do_formula (AAtom tm) =
blanchet@43700
   827
        AAtom (term_from_combterm ctxt nonmono_Ts type_sys Top_Level tm)
blanchet@43444
   828
  in do_formula end
blanchet@43444
   829
blanchet@43592
   830
fun bound_atomic_types type_sys Ts =
blanchet@43592
   831
  mk_ahorn (map (formula_from_fo_literal o fo_literal_from_type_literal)
blanchet@43592
   832
                (atp_type_literals_for_types type_sys Axiom Ts))
blanchet@43592
   833
blanchet@43550
   834
fun formula_for_fact ctxt nonmono_Ts type_sys
blanchet@43444
   835
                     ({combformula, atomic_types, ...} : translated_formula) =
blanchet@43592
   836
  combformula
blanchet@43592
   837
  |> close_combformula_universally
blanchet@43592
   838
  |> formula_from_combformula ctxt nonmono_Ts type_sys
blanchet@43592
   839
  |> bound_atomic_types type_sys atomic_types
blanchet@43444
   840
  |> close_formula_universally
blanchet@43444
   841
blanchet@43511
   842
fun useful_isabelle_info s = SOME (ATerm ("[]", [ATerm ("isabelle_" ^ s, [])]))
blanchet@43511
   843
blanchet@43444
   844
(* Each fact is given a unique fact number to avoid name clashes (e.g., because
blanchet@43444
   845
   of monomorphization). The TPTP explicitly forbids name clashes, and some of
blanchet@43444
   846
   the remote provers might care. *)
blanchet@43550
   847
fun formula_line_for_fact ctxt prefix nonmono_Ts type_sys
blanchet@43511
   848
                          (j, formula as {name, locality, kind, ...}) =
blanchet@43550
   849
  Formula (prefix ^ (if polymorphism_of_type_sys type_sys = Polymorphic then ""
blanchet@43550
   850
                     else string_of_int j ^ "_") ^
blanchet@43518
   851
           ascii_of name,
blanchet@43550
   852
           kind, formula_for_fact ctxt nonmono_Ts type_sys formula, NONE,
blanchet@43511
   853
           if generate_useful_info then
blanchet@43511
   854
             case locality of
blanchet@43511
   855
               Intro => useful_isabelle_info "intro"
blanchet@43511
   856
             | Elim => useful_isabelle_info "elim"
blanchet@43511
   857
             | Simp => useful_isabelle_info "simp"
blanchet@43511
   858
             | _ => NONE
blanchet@43511
   859
           else
blanchet@43511
   860
             NONE)
blanchet@43444
   861
blanchet@43444
   862
fun formula_line_for_class_rel_clause (ClassRelClause {name, subclass,
blanchet@43444
   863
                                                       superclass, ...}) =
blanchet@43444
   864
  let val ty_arg = ATerm (`I "T", []) in
blanchet@43448
   865
    Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
blanchet@43444
   866
             AConn (AImplies, [AAtom (ATerm (subclass, [ty_arg])),
blanchet@43444
   867
                               AAtom (ATerm (superclass, [ty_arg]))])
blanchet@43444
   868
             |> close_formula_universally, NONE, NONE)
blanchet@43444
   869
  end
blanchet@43444
   870
blanchet@43444
   871
fun fo_literal_from_arity_literal (TConsLit (c, t, args)) =
blanchet@43444
   872
    (true, ATerm (c, [ATerm (t, map (fn arg => ATerm (arg, [])) args)]))
blanchet@43444
   873
  | fo_literal_from_arity_literal (TVarLit (c, sort)) =
blanchet@43444
   874
    (false, ATerm (c, [ATerm (sort, [])]))
blanchet@43444
   875
blanchet@43444
   876
fun formula_line_for_arity_clause (ArityClause {name, conclLit, premLits,
blanchet@43444
   877
                                                ...}) =
blanchet@43448
   878
  Formula (arity_clause_prefix ^ ascii_of name, Axiom,
blanchet@43444
   879
           mk_ahorn (map (formula_from_fo_literal o apfst not
blanchet@43444
   880
                          o fo_literal_from_arity_literal) premLits)
blanchet@43444
   881
                    (formula_from_fo_literal
blanchet@43444
   882
                         (fo_literal_from_arity_literal conclLit))
blanchet@43444
   883
           |> close_formula_universally, NONE, NONE)
blanchet@43444
   884
blanchet@43550
   885
fun formula_line_for_conjecture ctxt nonmono_Ts type_sys
blanchet@43444
   886
        ({name, kind, combformula, ...} : translated_formula) =
blanchet@43448
   887
  Formula (conjecture_prefix ^ name, kind,
blanchet@43550
   888
           formula_from_combformula ctxt nonmono_Ts type_sys
blanchet@43444
   889
                                    (close_combformula_universally combformula)
blanchet@43444
   890
           |> close_formula_universally, NONE, NONE)
blanchet@43444
   891
blanchet@43444
   892
fun free_type_literals type_sys ({atomic_types, ...} : translated_formula) =
blanchet@43444
   893
  atomic_types |> atp_type_literals_for_types type_sys Conjecture
blanchet@43444
   894
               |> map fo_literal_from_type_literal
blanchet@43444
   895
blanchet@43444
   896
fun formula_line_for_free_type j lit =
blanchet@43448
   897
  Formula (tfree_prefix ^ string_of_int j, Hypothesis,
blanchet@43444
   898
           formula_from_fo_literal lit, NONE, NONE)
blanchet@43444
   899
fun formula_lines_for_free_types type_sys facts =
blanchet@43444
   900
  let
blanchet@43444
   901
    val litss = map (free_type_literals type_sys) facts
blanchet@43444
   902
    val lits = fold (union (op =)) litss []
blanchet@43444
   903
  in map2 formula_line_for_free_type (0 upto length lits - 1) lits end
blanchet@43444
   904
blanchet@43444
   905
(** Symbol declarations **)
blanchet@43415
   906
blanchet@43547
   907
fun insert_type get_T x xs =
blanchet@43547
   908
  let val T = get_T x in
blanchet@43547
   909
    if exists (curry Type.raw_instance T o get_T) xs then xs
blanchet@43547
   910
    else x :: filter_out ((fn T' => Type.raw_instance (T', T)) o get_T) xs
blanchet@43547
   911
  end
blanchet@43547
   912
blanchet@43445
   913
fun should_declare_sym type_sys pred_sym s =
blanchet@43413
   914
  not (String.isPrefix bound_var_prefix s) andalso s <> "equal" andalso
blanchet@43618
   915
  not (String.isPrefix tptp_special_prefix s) andalso
blanchet@43587
   916
  ((case type_sys of Simple_Types _ => true | _ => false) orelse not pred_sym)
blanchet@43413
   917
blanchet@43568
   918
fun sym_decl_table_for_facts type_sys repaired_sym_tab (conjs, facts) =
blanchet@43445
   919
  let
blanchet@43568
   920
    fun add_combterm in_conj tm =
blanchet@43445
   921
      let val (head, args) = strip_combterm_comb tm in
blanchet@43445
   922
        (case head of
blanchet@43445
   923
           CombConst ((s, s'), T, T_args) =>
blanchet@43445
   924
           let val pred_sym = is_pred_sym repaired_sym_tab s in
blanchet@43445
   925
             if should_declare_sym type_sys pred_sym s then
blanchet@43447
   926
               Symtab.map_default (s, [])
blanchet@43568
   927
                   (insert_type #3 (s', T_args, T, pred_sym, length args,
blanchet@43568
   928
                                    in_conj))
blanchet@43445
   929
             else
blanchet@43445
   930
               I
blanchet@43445
   931
           end
blanchet@43445
   932
         | _ => I)
blanchet@43568
   933
        #> fold (add_combterm in_conj) args
blanchet@43445
   934
      end
blanchet@43568
   935
    fun add_fact in_conj =
blanchet@43568
   936
      fact_lift (formula_fold true (K (add_combterm in_conj)))
blanchet@43568
   937
  in
blanchet@43568
   938
    Symtab.empty
blanchet@43568
   939
    |> is_type_sys_fairly_sound type_sys
blanchet@43568
   940
       ? (fold (add_fact true) conjs #> fold (add_fact false) facts)
blanchet@43568
   941
  end
blanchet@43445
   942
blanchet@43547
   943
fun is_var_or_bound_var (CombConst ((s, _), _, _)) =
blanchet@43547
   944
    String.isPrefix bound_var_prefix s
blanchet@43547
   945
  | is_var_or_bound_var (CombVar _) = true
blanchet@43547
   946
  | is_var_or_bound_var _ = false
blanchet@43547
   947
blanchet@43555
   948
(* This inference is described in section 2.3 of Claessen et al.'s "Sorting it
blanchet@43555
   949
   out with monotonicity" paper presented at CADE 2011. *)
blanchet@43700
   950
fun add_combterm_nonmonotonic_types _ _  (SOME false) _ = I
blanchet@43700
   951
  | add_combterm_nonmonotonic_types ctxt level _
blanchet@43550
   952
        (CombApp (CombApp (CombConst (("equal", _), Type (_, [T, _]), _), tm1),
blanchet@43550
   953
                  tm2)) =
blanchet@43550
   954
    (exists is_var_or_bound_var [tm1, tm2] andalso
blanchet@43700
   955
     (case level of
blanchet@43700
   956
        Nonmonotonic_Types => not (is_type_surely_infinite ctxt T)
blanchet@43700
   957
      | Finite_Types => is_type_surely_finite ctxt T
blanchet@43700
   958
      | _ => true)) ? insert_type I T
blanchet@43700
   959
  | add_combterm_nonmonotonic_types _ _ _ _ = I
blanchet@43700
   960
fun add_fact_nonmonotonic_types ctxt level ({kind, combformula, ...}
blanchet@43700
   961
                                            : translated_formula) =
blanchet@43700
   962
  formula_fold (kind <> Conjecture)
blanchet@43700
   963
               (add_combterm_nonmonotonic_types ctxt level) combformula
blanchet@43550
   964
fun add_nonmonotonic_types_for_facts ctxt type_sys facts =
blanchet@43700
   965
  let val level = level_of_type_sys type_sys in
blanchet@43700
   966
    (level = Nonmonotonic_Types orelse
blanchet@43700
   967
     (case type_sys of
blanchet@43700
   968
        Tags (poly, _, Shallow) => poly <> Polymorphic
blanchet@43700
   969
      | _ => false))
blanchet@43700
   970
    ? (fold (add_fact_nonmonotonic_types ctxt level) facts
blanchet@43700
   971
       (* in case helper "True_or_False" is included *)
blanchet@43700
   972
       #> insert_type I @{typ bool})
blanchet@43700
   973
  end
blanchet@43547
   974
blanchet@43618
   975
fun result_type_of_decl (_, _, T, _, ary, _) = chop_fun ary T |> snd
blanchet@43450
   976
blanchet@43619
   977
fun decl_line_for_sym ctxt nonmono_Ts level s (s', _, T, pred_sym, ary, _) =
blanchet@43619
   978
  let
blanchet@43619
   979
    val translate_type =
blanchet@43619
   980
      mangled_type_name o homogenized_type ctxt nonmono_Ts level
blanchet@43619
   981
    val (arg_tys, res_ty) =
blanchet@43619
   982
      T |> chop_fun ary |>> map translate_type ||> translate_type
blanchet@43619
   983
  in
blanchet@43619
   984
    Decl (sym_decl_prefix ^ s, (s, s'), arg_tys,
blanchet@43619
   985
          if pred_sym then `I tptp_tff_bool_type else res_ty)
blanchet@43450
   986
  end
blanchet@43450
   987
blanchet@43463
   988
fun is_polymorphic_type T = fold_atyps (fn TVar _ => K true | _ => I) T false
blanchet@43463
   989
blanchet@43700
   990
fun formula_line_for_pred_sym_decl ctxt conj_sym_kind nonmono_Ts type_sys n s j
blanchet@43700
   991
                                   (s', T_args, T, _, ary, in_conj) =
blanchet@43450
   992
  let
blanchet@43580
   993
    val (kind, maybe_negate) =
blanchet@43580
   994
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@43580
   995
      else (Axiom, I)
blanchet@43618
   996
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@43450
   997
    val bound_names =
blanchet@43450
   998
      1 upto length arg_Ts |> map (`I o make_bound_var o string_of_int)
blanchet@43700
   999
    val bounds =
blanchet@43450
  1000
      bound_names ~~ arg_Ts |> map (fn (name, T) => CombConst (name, T, []))
blanchet@43450
  1001
    val bound_Ts =
blanchet@43463
  1002
      arg_Ts |> map (fn T => if n > 1 orelse is_polymorphic_type T then SOME T
blanchet@43463
  1003
                             else NONE)
blanchet@43450
  1004
  in
blanchet@43483
  1005
    Formula (sym_decl_prefix ^ s ^
blanchet@43580
  1006
             (if n > 1 then "_" ^ string_of_int j else ""), kind,
blanchet@43450
  1007
             CombConst ((s, s'), T, T_args)
blanchet@43700
  1008
             |> fold (curry (CombApp o swap)) bounds
blanchet@43571
  1009
             |> type_pred_combatom ctxt nonmono_Ts type_sys res_T
blanchet@43450
  1010
             |> mk_aquant AForall (bound_names ~~ bound_Ts)
blanchet@43550
  1011
             |> formula_from_combformula ctxt nonmono_Ts type_sys
blanchet@43592
  1012
             |> n > 1 ? bound_atomic_types type_sys (atyps_of T)
blanchet@43580
  1013
             |> close_formula_universally
blanchet@43580
  1014
             |> maybe_negate,
blanchet@43450
  1015
             NONE, NONE)
blanchet@43450
  1016
  end
blanchet@43450
  1017
blanchet@43700
  1018
fun formula_lines_for_tag_sym_decl ctxt nonmono_Ts type_sys n s
blanchet@43700
  1019
                                   (j, (s', T_args, T, _, ary, _)) =
blanchet@43700
  1020
  let
blanchet@43700
  1021
    val ident_base =
blanchet@43700
  1022
      sym_decl_prefix ^ s ^ (if n > 1 then "_" ^ string_of_int j else "")
blanchet@43700
  1023
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@43700
  1024
    val bound_names =
blanchet@43700
  1025
      1 upto length arg_Ts |> map (`I o make_bound_var o string_of_int)
blanchet@43700
  1026
    val bounds = bound_names |> map (fn name => ATerm (name, []))
blanchet@43700
  1027
    fun const args = ATerm ((s, s'), map fo_term_from_typ T_args @ args)
blanchet@43701
  1028
    val atomic_Ts = atyps_of T
blanchet@43701
  1029
    fun eq tm1 tm2 =
blanchet@43701
  1030
      ATerm (`I "equal", [tm1, tm2])
blanchet@43701
  1031
      |> AAtom
blanchet@43701
  1032
      |> bound_atomic_types type_sys atomic_Ts
blanchet@43701
  1033
      |> close_formula_universally
blanchet@43700
  1034
    val should_encode =
blanchet@43700
  1035
      should_encode_type ctxt nonmono_Ts
blanchet@43700
  1036
          (if polymorphism_of_type_sys type_sys = Polymorphic then All_Types
blanchet@43700
  1037
           else Nonmonotonic_Types)
blanchet@43700
  1038
    val tag_with = tag_with_type ctxt nonmono_Ts type_sys
blanchet@43700
  1039
    val add_formula_for_res =
blanchet@43700
  1040
      if should_encode res_T then
blanchet@43700
  1041
        cons (Formula (ident_base ^ "_res", Axiom,
blanchet@43701
  1042
                       eq (tag_with res_T (const bounds)) (const bounds),
blanchet@43700
  1043
                       NONE, NONE))
blanchet@43700
  1044
      else
blanchet@43700
  1045
        I
blanchet@43700
  1046
    fun add_formula_for_arg k =
blanchet@43700
  1047
      let val arg_T = nth arg_Ts k in
blanchet@43700
  1048
        if should_encode arg_T then
blanchet@43700
  1049
          case chop k bounds of
blanchet@43700
  1050
            (bounds1, bound :: bounds2) =>
blanchet@43700
  1051
            cons (Formula (ident_base ^ "_arg" ^ string_of_int (k + 1), Axiom,
blanchet@43701
  1052
                           eq (const (bounds1 @ tag_with arg_T bound ::
blanchet@43701
  1053
                                      bounds2))
blanchet@43701
  1054
                              (const bounds),
blanchet@43700
  1055
                           NONE, NONE))
blanchet@43700
  1056
          | _ => raise Fail "expected nonempty tail"
blanchet@43700
  1057
        else
blanchet@43700
  1058
          I
blanchet@43700
  1059
      end
blanchet@43700
  1060
  in
blanchet@43700
  1061
    [] |> add_formula_for_res
blanchet@43700
  1062
       |> fold add_formula_for_arg (ary - 1 downto 0)
blanchet@43700
  1063
  end
blanchet@43700
  1064
blanchet@43580
  1065
fun problem_lines_for_sym_decls ctxt conj_sym_kind nonmono_Ts type_sys
blanchet@43580
  1066
                                (s, decls) =
blanchet@43552
  1067
  case type_sys of
blanchet@43619
  1068
    Simple_Types level => map (decl_line_for_sym ctxt nonmono_Ts level s) decls
blanchet@43700
  1069
  | Preds _ =>
blanchet@43445
  1070
    let
blanchet@43450
  1071
      val decls =
blanchet@43450
  1072
        case decls of
blanchet@43450
  1073
          decl :: (decls' as _ :: _) =>
blanchet@43463
  1074
          let val T = result_type_of_decl decl in
blanchet@43463
  1075
            if forall ((fn T' => Type.raw_instance (T', T))
blanchet@43463
  1076
                       o result_type_of_decl) decls' then
blanchet@43463
  1077
              [decl]
blanchet@43463
  1078
            else
blanchet@43463
  1079
              decls
blanchet@43463
  1080
          end
blanchet@43450
  1081
        | _ => decls
blanchet@43450
  1082
      val n = length decls
blanchet@43450
  1083
      val decls =
blanchet@43550
  1084
        decls |> filter (should_predicate_on_type ctxt nonmono_Ts type_sys
blanchet@43450
  1085
                         o result_type_of_decl)
blanchet@43445
  1086
    in
blanchet@43580
  1087
      (0 upto length decls - 1, decls)
blanchet@43700
  1088
      |-> map2 (formula_line_for_pred_sym_decl ctxt conj_sym_kind nonmono_Ts
blanchet@43700
  1089
                                               type_sys n s)
blanchet@43445
  1090
    end
blanchet@43700
  1091
  | Tags (_, _, depth) =>
blanchet@43700
  1092
    (case depth of
blanchet@43700
  1093
       Deep => []
blanchet@43700
  1094
     | Shallow =>
blanchet@43700
  1095
       let val n = length decls in
blanchet@43700
  1096
         (0 upto n - 1 ~~ decls)
blanchet@43700
  1097
         |> maps (formula_lines_for_tag_sym_decl ctxt nonmono_Ts type_sys n s)
blanchet@43700
  1098
       end)
blanchet@43450
  1099
blanchet@43580
  1100
fun problem_lines_for_sym_decl_table ctxt conj_sym_kind nonmono_Ts type_sys
blanchet@43580
  1101
                                     sym_decl_tab =
blanchet@43580
  1102
  Symtab.fold_rev (append o problem_lines_for_sym_decls ctxt conj_sym_kind
blanchet@43580
  1103
                                                        nonmono_Ts type_sys)
blanchet@43445
  1104
                  sym_decl_tab []
blanchet@43410
  1105
blanchet@43414
  1106
fun add_tff_types_in_formula (AQuant (_, xs, phi)) =
blanchet@43414
  1107
    union (op =) (map_filter snd xs) #> add_tff_types_in_formula phi
blanchet@43414
  1108
  | add_tff_types_in_formula (AConn (_, phis)) =
blanchet@43414
  1109
    fold add_tff_types_in_formula phis
blanchet@43414
  1110
  | add_tff_types_in_formula (AAtom _) = I
blanchet@43414
  1111
blanchet@43433
  1112
fun add_tff_types_in_problem_line (Decl (_, _, arg_Ts, res_T)) =
blanchet@43433
  1113
    union (op =) (res_T :: arg_Ts)
blanchet@43448
  1114
  | add_tff_types_in_problem_line (Formula (_, _, phi, _, _)) =
blanchet@43414
  1115
    add_tff_types_in_formula phi
blanchet@43414
  1116
blanchet@43414
  1117
fun tff_types_in_problem problem =
blanchet@43414
  1118
  fold (fold add_tff_types_in_problem_line o snd) problem []
blanchet@43414
  1119
blanchet@43416
  1120
fun decl_line_for_tff_type (s, s') =
blanchet@43439
  1121
  Decl (type_decl_prefix ^ ascii_of s, (s, s'), [], `I tptp_tff_type_of_types)
blanchet@43414
  1122
blanchet@43414
  1123
val type_declsN = "Types"
blanchet@43415
  1124
val sym_declsN = "Symbol types"
blanchet@41405
  1125
val factsN = "Relevant facts"
blanchet@41405
  1126
val class_relsN = "Class relationships"
blanchet@43414
  1127
val aritiesN = "Arities"
blanchet@41405
  1128
val helpersN = "Helper facts"
blanchet@41405
  1129
val conjsN = "Conjectures"
blanchet@41561
  1130
val free_typesN = "Type variables"
blanchet@41405
  1131
blanchet@41405
  1132
fun offset_of_heading_in_problem _ [] j = j
blanchet@41405
  1133
  | offset_of_heading_in_problem needle ((heading, lines) :: problem) j =
blanchet@41405
  1134
    if heading = needle then j
blanchet@41405
  1135
    else offset_of_heading_in_problem needle problem (j + length lines)
blanchet@41405
  1136
blanchet@43580
  1137
fun prepare_atp_problem ctxt conj_sym_kind prem_kind type_sys explicit_apply
blanchet@43580
  1138
                        hyp_ts concl_t facts =
blanchet@38506
  1139
  let
blanchet@41561
  1140
    val (fact_names, (conjs, facts, class_rel_clauses, arity_clauses)) =
blanchet@43580
  1141
      translate_formulas ctxt prem_kind type_sys hyp_ts concl_t facts
blanchet@43434
  1142
    val sym_tab = conjs @ facts |> sym_table_for_facts explicit_apply
blanchet@43552
  1143
    val nonmono_Ts =
blanchet@43552
  1144
      [] |> fold (add_nonmonotonic_types_for_facts ctxt type_sys) [facts, conjs]
blanchet@43571
  1145
    val repair = repair_fact ctxt nonmono_Ts type_sys sym_tab
blanchet@43552
  1146
    val (conjs, facts) = (conjs, facts) |> pairself (map repair)
blanchet@43550
  1147
    val repaired_sym_tab = conjs @ facts |> sym_table_for_facts false
blanchet@43444
  1148
    val helpers =
blanchet@43552
  1149
      repaired_sym_tab |> helper_facts_for_sym_table ctxt type_sys |> map repair
blanchet@43550
  1150
    val sym_decl_lines =
blanchet@43596
  1151
      (conjs, helpers @ facts)
blanchet@43550
  1152
      |> sym_decl_table_for_facts type_sys repaired_sym_tab
blanchet@43580
  1153
      |> problem_lines_for_sym_decl_table ctxt conj_sym_kind nonmono_Ts type_sys
blanchet@43393
  1154
    (* Reordering these might confuse the proof reconstruction code or the SPASS
blanchet@43393
  1155
       Flotter hack. *)
blanchet@38506
  1156
    val problem =
blanchet@43432
  1157
      [(sym_declsN, sym_decl_lines),
blanchet@43550
  1158
       (factsN, map (formula_line_for_fact ctxt fact_prefix nonmono_Ts type_sys)
blanchet@43051
  1159
                    (0 upto length facts - 1 ~~ facts)),
blanchet@43416
  1160
       (class_relsN, map formula_line_for_class_rel_clause class_rel_clauses),
blanchet@43416
  1161
       (aritiesN, map formula_line_for_arity_clause arity_clauses),
blanchet@43550
  1162
       (helpersN, map (formula_line_for_fact ctxt helper_prefix nonmono_Ts
blanchet@43550
  1163
                                             type_sys)
blanchet@43434
  1164
                      (0 upto length helpers - 1 ~~ helpers)
blanchet@43450
  1165
                  |> (case type_sys of
blanchet@43699
  1166
                        Tags (Polymorphic, level, _) =>
blanchet@43700
  1167
                        is_type_level_partial level (* ### FIXME *)
blanchet@43460
  1168
                        ? cons (ti_ti_helper_fact ())
blanchet@43450
  1169
                      | _ => I)),
blanchet@43550
  1170
       (conjsN, map (formula_line_for_conjecture ctxt nonmono_Ts type_sys)
blanchet@43550
  1171
                    conjs),
blanchet@43416
  1172
       (free_typesN, formula_lines_for_free_types type_sys (facts @ conjs))]
blanchet@43414
  1173
    val problem =
blanchet@43432
  1174
      problem
blanchet@43552
  1175
      |> (case type_sys of
blanchet@43587
  1176
            Simple_Types _ =>
blanchet@43432
  1177
            cons (type_declsN,
blanchet@43432
  1178
                  map decl_line_for_tff_type (tff_types_in_problem problem))
blanchet@43552
  1179
          | _ => I)
blanchet@43517
  1180
    val (problem, pool) =
blanchet@43517
  1181
      problem |> nice_atp_problem (Config.get ctxt readable_names)
blanchet@43649
  1182
    fun add_sym_arity (s, {min_ary, ...} : sym_info) =
blanchet@43620
  1183
      if min_ary > 0 then
blanchet@43620
  1184
        case strip_prefix_and_unascii const_prefix s of
blanchet@43620
  1185
          SOME s => Symtab.insert (op =) (s, min_ary)
blanchet@43620
  1186
        | NONE => I
blanchet@43620
  1187
      else
blanchet@43620
  1188
        I
blanchet@38506
  1189
  in
blanchet@38506
  1190
    (problem,
blanchet@38506
  1191
     case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
blanchet@43456
  1192
     offset_of_heading_in_problem conjsN problem 0,
blanchet@43412
  1193
     offset_of_heading_in_problem factsN problem 0,
blanchet@43620
  1194
     fact_names |> Vector.fromList,
blanchet@43620
  1195
     Symtab.empty |> Symtab.fold add_sym_arity sym_tab)
blanchet@38506
  1196
  end
blanchet@38506
  1197
blanchet@41561
  1198
(* FUDGE *)
blanchet@41561
  1199
val conj_weight = 0.0
blanchet@42641
  1200
val hyp_weight = 0.1
blanchet@42641
  1201
val fact_min_weight = 0.2
blanchet@41561
  1202
val fact_max_weight = 1.0
blanchet@43479
  1203
val type_info_default_weight = 0.8
blanchet@41561
  1204
blanchet@41561
  1205
fun add_term_weights weight (ATerm (s, tms)) =
blanchet@43599
  1206
  (not (is_atp_variable s) andalso s <> "equal" andalso
blanchet@43618
  1207
   not (String.isPrefix tptp_special_prefix s)) ? Symtab.default (s, weight)
blanchet@41561
  1208
  #> fold (add_term_weights weight) tms
blanchet@43448
  1209
fun add_problem_line_weights weight (Formula (_, _, phi, _, _)) =
blanchet@43550
  1210
    formula_fold true (K (add_term_weights weight)) phi
blanchet@43399
  1211
  | add_problem_line_weights _ _ = I
blanchet@41561
  1212
blanchet@41561
  1213
fun add_conjectures_weights [] = I
blanchet@41561
  1214
  | add_conjectures_weights conjs =
blanchet@41561
  1215
    let val (hyps, conj) = split_last conjs in
blanchet@41561
  1216
      add_problem_line_weights conj_weight conj
blanchet@41561
  1217
      #> fold (add_problem_line_weights hyp_weight) hyps
blanchet@41561
  1218
    end
blanchet@41561
  1219
blanchet@41561
  1220
fun add_facts_weights facts =
blanchet@41561
  1221
  let
blanchet@41561
  1222
    val num_facts = length facts
blanchet@41561
  1223
    fun weight_of j =
blanchet@41561
  1224
      fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
blanchet@41561
  1225
                        / Real.fromInt num_facts
blanchet@41561
  1226
  in
blanchet@41561
  1227
    map weight_of (0 upto num_facts - 1) ~~ facts
blanchet@41561
  1228
    |> fold (uncurry add_problem_line_weights)
blanchet@41561
  1229
  end
blanchet@41561
  1230
blanchet@41561
  1231
(* Weights are from 0.0 (most important) to 1.0 (least important). *)
blanchet@41561
  1232
fun atp_problem_weights problem =
blanchet@43479
  1233
  let val get = these o AList.lookup (op =) problem in
blanchet@43479
  1234
    Symtab.empty
blanchet@43479
  1235
    |> add_conjectures_weights (get free_typesN @ get conjsN)
blanchet@43479
  1236
    |> add_facts_weights (get factsN)
blanchet@43479
  1237
    |> fold (fold (add_problem_line_weights type_info_default_weight) o get)
blanchet@43479
  1238
            [sym_declsN, class_relsN, aritiesN]
blanchet@43479
  1239
    |> Symtab.dest
blanchet@43479
  1240
    |> sort (prod_ord Real.compare string_ord o pairself swap)
blanchet@43479
  1241
  end
blanchet@41561
  1242
blanchet@38506
  1243
end;