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