src/HOL/Tools/Sledgehammer/sledgehammer_translate.ML
author blanchet
Wed Sep 01 23:10:01 2010 +0200 (2010-09-01)
changeset 39005 42fcb25de082
parent 39004 f1b465f889b5
child 39370 f8292d3020db
permissions -rw-r--r--
minor refactoring
blanchet@38282
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_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@38282
     6
Translation of HOL to FOL.
blanchet@38282
     7
*)
blanchet@38282
     8
blanchet@38282
     9
signature SLEDGEHAMMER_TRANSLATE =
blanchet@38282
    10
sig
blanchet@38282
    11
  type 'a problem = 'a ATP_Problem.problem
blanchet@39004
    12
  type fol_formula
blanchet@38282
    13
blanchet@38282
    14
  val axiom_prefix : string
blanchet@38282
    15
  val conjecture_prefix : string
blanchet@38282
    16
  val helper_prefix : string
blanchet@38282
    17
  val class_rel_clause_prefix : string
blanchet@38282
    18
  val arity_clause_prefix : string
blanchet@38282
    19
  val tfrees_name : string
blanchet@39004
    20
  val prepare_axiom :
blanchet@39005
    21
    Proof.context -> (string * 'a) * thm
blanchet@39005
    22
    -> term * ((string * 'a) * fol_formula) option
blanchet@38282
    23
  val prepare_problem :
blanchet@38282
    24
    Proof.context -> bool -> bool -> bool -> bool -> term list -> term
blanchet@39005
    25
    -> (term * ((string * 'a) * fol_formula) option) list
blanchet@38818
    26
    -> string problem * string Symtab.table * int * (string * 'a) list vector
blanchet@38282
    27
end;
blanchet@38282
    28
blanchet@38282
    29
structure Sledgehammer_Translate : SLEDGEHAMMER_TRANSLATE =
blanchet@38282
    30
struct
blanchet@38282
    31
blanchet@38282
    32
open ATP_Problem
blanchet@38282
    33
open Metis_Clauses
blanchet@38282
    34
open Sledgehammer_Util
blanchet@38282
    35
blanchet@38282
    36
val axiom_prefix = "ax_"
blanchet@38282
    37
val conjecture_prefix = "conj_"
blanchet@38282
    38
val helper_prefix = "help_"
blanchet@38282
    39
val class_rel_clause_prefix = "clrel_";
blanchet@38282
    40
val arity_clause_prefix = "arity_"
blanchet@38282
    41
val tfrees_name = "tfrees"
blanchet@38282
    42
blanchet@38282
    43
(* Freshness almost guaranteed! *)
blanchet@38282
    44
val sledgehammer_weak_prefix = "Sledgehammer:"
blanchet@38282
    45
blanchet@38752
    46
type fol_formula =
blanchet@38752
    47
  {name: string,
blanchet@38752
    48
   kind: kind,
blanchet@38752
    49
   combformula: (name, combterm) formula,
blanchet@38752
    50
   ctypes_sorts: typ list}
blanchet@38282
    51
blanchet@38282
    52
fun mk_anot phi = AConn (ANot, [phi])
blanchet@38282
    53
fun mk_aconn c phi1 phi2 = AConn (c, [phi1, phi2])
blanchet@38282
    54
fun mk_ahorn [] phi = phi
blanchet@38282
    55
  | mk_ahorn (phi :: phis) psi =
blanchet@38282
    56
    AConn (AImplies, [fold (mk_aconn AAnd) phis phi, psi])
blanchet@38282
    57
blanchet@38282
    58
fun combformula_for_prop thy =
blanchet@38282
    59
  let
blanchet@38282
    60
    val do_term = combterm_from_term thy
blanchet@38282
    61
    fun do_quant bs q s T t' =
blanchet@38518
    62
      let val s = Name.variant (map fst bs) s in
blanchet@38518
    63
        do_formula ((s, T) :: bs) t'
blanchet@38518
    64
        #>> (fn phi => AQuant (q, [`make_bound_var s], phi))
blanchet@38518
    65
      end
blanchet@38282
    66
    and do_conn bs c t1 t2 =
blanchet@38282
    67
      do_formula bs t1 ##>> do_formula bs t2
blanchet@38282
    68
      #>> (fn (phi1, phi2) => AConn (c, [phi1, phi2]))
blanchet@38282
    69
    and do_formula bs t =
blanchet@38282
    70
      case t of
blanchet@38282
    71
        @{const Not} $ t1 =>
blanchet@38282
    72
        do_formula bs t1 #>> (fn phi => AConn (ANot, [phi]))
blanchet@38282
    73
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@38282
    74
        do_quant bs AForall s T t'
blanchet@38282
    75
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@38282
    76
        do_quant bs AExists s T t'
haftmann@38795
    77
      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd t1 t2
haftmann@38795
    78
      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr t1 t2
haftmann@38786
    79
      | @{const HOL.implies} $ t1 $ t2 => do_conn bs AImplies t1 t2
haftmann@38864
    80
      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@38282
    81
        do_conn bs AIff t1 t2
blanchet@38282
    82
      | _ => (fn ts => do_term bs (Envir.eta_contract t)
blanchet@38282
    83
                       |>> AAtom ||> union (op =) ts)
blanchet@38282
    84
  in do_formula [] end
blanchet@38282
    85
blanchet@38618
    86
val presimplify_term = prop_of o Meson.presimplify oo Skip_Proof.make_thm
blanchet@38282
    87
blanchet@38282
    88
fun concealed_bound_name j = sledgehammer_weak_prefix ^ Int.toString j
blanchet@38282
    89
fun conceal_bounds Ts t =
blanchet@38282
    90
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@38282
    91
                    (0 upto length Ts - 1 ~~ Ts), t)
blanchet@38282
    92
fun reveal_bounds Ts =
blanchet@38282
    93
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@38282
    94
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@38282
    95
blanchet@38608
    96
(* Removes the lambdas from an equation of the form "t = (%x. u)".
blanchet@38608
    97
   (Cf. "extensionalize_theorem" in "Clausifier".) *)
blanchet@38608
    98
fun extensionalize_term t =
blanchet@38608
    99
  let
blanchet@38608
   100
    fun aux j (@{const Trueprop} $ t') = @{const Trueprop} $ aux j t'
blanchet@38608
   101
      | aux j (t as Const (s, Type (_, [Type (_, [_, T']),
blanchet@38608
   102
                                        Type (_, [_, res_T])]))
blanchet@38608
   103
                    $ t2 $ Abs (var_s, var_T, t')) =
haftmann@38864
   104
        if s = @{const_name HOL.eq} orelse s = @{const_name "=="} then
blanchet@38608
   105
          let val var_t = Var ((var_s, j), var_T) in
blanchet@38608
   106
            Const (s, T' --> T' --> res_T)
blanchet@38608
   107
              $ betapply (t2, var_t) $ subst_bound (var_t, t')
blanchet@38608
   108
            |> aux (j + 1)
blanchet@38608
   109
          end
blanchet@38608
   110
        else
blanchet@38608
   111
          t
blanchet@38608
   112
      | aux _ t = t
blanchet@38608
   113
  in aux (maxidx_of_term t + 1) t end
blanchet@38608
   114
blanchet@38282
   115
fun introduce_combinators_in_term ctxt kind t =
blanchet@38491
   116
  let val thy = ProofContext.theory_of ctxt in
blanchet@38491
   117
    if Meson.is_fol_term thy t then
blanchet@38491
   118
      t
blanchet@38491
   119
    else
blanchet@38491
   120
      let
blanchet@38491
   121
        fun aux Ts t =
blanchet@38491
   122
          case t of
blanchet@38491
   123
            @{const Not} $ t1 => @{const Not} $ aux Ts t1
blanchet@38491
   124
          | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@38491
   125
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38652
   126
          | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@38652
   127
            aux Ts (t0 $ eta_expand Ts t1 1)
blanchet@38491
   128
          | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@38491
   129
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38652
   130
          | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@38652
   131
            aux Ts (t0 $ eta_expand Ts t1 1)
haftmann@38795
   132
          | (t0 as @{const HOL.conj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@38795
   133
          | (t0 as @{const HOL.disj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@38786
   134
          | (t0 as @{const HOL.implies}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@38864
   135
          | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
blanchet@38491
   136
              $ t1 $ t2 =>
blanchet@38491
   137
            t0 $ aux Ts t1 $ aux Ts t2
blanchet@38491
   138
          | _ => if not (exists_subterm (fn Abs _ => true | _ => false) t) then
blanchet@38491
   139
                   t
blanchet@38491
   140
                 else
blanchet@38491
   141
                   t |> conceal_bounds Ts
blanchet@38491
   142
                     |> Envir.eta_contract
blanchet@38491
   143
                     |> cterm_of thy
blanchet@38491
   144
                     |> Clausifier.introduce_combinators_in_cterm
blanchet@38491
   145
                     |> prop_of |> Logic.dest_equals |> snd
blanchet@38491
   146
                     |> reveal_bounds Ts
blanchet@38491
   147
        val ([t], ctxt') = Variable.import_terms true [t] ctxt
blanchet@38491
   148
      in t |> aux [] |> singleton (Variable.export_terms ctxt' ctxt) end
blanchet@38491
   149
      handle THM _ =>
blanchet@38491
   150
             (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@38613
   151
             if kind = Conjecture then HOLogic.false_const
blanchet@38613
   152
             else HOLogic.true_const
blanchet@38491
   153
  end
blanchet@38282
   154
blanchet@38282
   155
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@38282
   156
   same in Sledgehammer to prevent the discovery of unreplable proofs. *)
blanchet@38282
   157
fun freeze_term t =
blanchet@38282
   158
  let
blanchet@38282
   159
    fun aux (t $ u) = aux t $ aux u
blanchet@38282
   160
      | aux (Abs (s, T, t)) = Abs (s, T, aux t)
blanchet@38282
   161
      | aux (Var ((s, i), T)) =
blanchet@38282
   162
        Free (sledgehammer_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
blanchet@38282
   163
      | aux t = t
blanchet@38282
   164
  in t |> exists_subterm is_Var t ? aux end
blanchet@38282
   165
blanchet@38604
   166
(* "Object_Logic.atomize_term" isn't as powerful as it could be; for example,
blanchet@38604
   167
    it leaves metaequalities over "prop"s alone. *)
blanchet@38605
   168
val atomize_term =
blanchet@38605
   169
  let
blanchet@38605
   170
    fun aux (@{const Trueprop} $ t1) = t1
blanchet@38605
   171
      | aux (Const (@{const_name all}, _) $ Abs (s, T, t')) =
blanchet@38605
   172
        HOLogic.all_const T $ Abs (s, T, aux t')
blanchet@38605
   173
      | aux (@{const "==>"} $ t1 $ t2) = HOLogic.mk_imp (pairself aux (t1, t2))
blanchet@38605
   174
      | aux (Const (@{const_name "=="}, Type (_, [@{typ prop}, _])) $ t1 $ t2) =
blanchet@38605
   175
        HOLogic.eq_const HOLogic.boolT $ aux t1 $ aux t2
blanchet@38605
   176
      | aux (Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2) =
blanchet@38605
   177
        HOLogic.eq_const T $ t1 $ t2
blanchet@38605
   178
      | aux _ = raise Fail "aux"
blanchet@38605
   179
  in perhaps (try aux) end
blanchet@38604
   180
blanchet@38282
   181
(* making axiom and conjecture formulas *)
blanchet@38613
   182
fun make_formula ctxt presimp name kind t =
blanchet@38282
   183
  let
blanchet@38282
   184
    val thy = ProofContext.theory_of ctxt
blanchet@38608
   185
    val t = t |> Envir.beta_eta_contract
blanchet@38652
   186
              |> transform_elim_term
blanchet@38604
   187
              |> atomize_term
blanchet@38652
   188
    val need_trueprop = (fastype_of t = HOLogic.boolT)
blanchet@38652
   189
    val t = t |> need_trueprop ? HOLogic.mk_Trueprop
blanchet@38282
   190
              |> extensionalize_term
blanchet@38282
   191
              |> presimp ? presimplify_term thy
blanchet@38282
   192
              |> perhaps (try (HOLogic.dest_Trueprop))
blanchet@38282
   193
              |> introduce_combinators_in_term ctxt kind
blanchet@38613
   194
              |> kind <> Axiom ? freeze_term
blanchet@38282
   195
    val (combformula, ctypes_sorts) = combformula_for_prop thy t []
blanchet@38282
   196
  in
blanchet@38752
   197
    {name = name, combformula = combformula, kind = kind,
blanchet@38752
   198
     ctypes_sorts = ctypes_sorts}
blanchet@38282
   199
  end
blanchet@38282
   200
blanchet@38752
   201
fun make_axiom ctxt presimp ((name, loc), th) =
blanchet@38618
   202
  case make_formula ctxt presimp name Axiom (prop_of th) of
blanchet@38752
   203
    {combformula = AAtom (CombConst (("c_True", _), _, _)), ...} => NONE
blanchet@38752
   204
  | formula => SOME ((name, loc), formula)
blanchet@38613
   205
fun make_conjecture ctxt ts =
blanchet@38613
   206
  let val last = length ts - 1 in
blanchet@38613
   207
    map2 (fn j => make_formula ctxt true (Int.toString j)
blanchet@38613
   208
                               (if j = last then Conjecture else Hypothesis))
blanchet@38613
   209
         (0 upto last) ts
blanchet@38613
   210
  end
blanchet@38282
   211
blanchet@38282
   212
(** Helper facts **)
blanchet@38282
   213
blanchet@38282
   214
fun count_combterm (CombConst ((s, _), _, _)) =
blanchet@38282
   215
    Symtab.map_entry s (Integer.add 1)
blanchet@38282
   216
  | count_combterm (CombVar _) = I
blanchet@38282
   217
  | count_combterm (CombApp (t1, t2)) = fold count_combterm [t1, t2]
blanchet@38282
   218
fun count_combformula (AQuant (_, _, phi)) = count_combformula phi
blanchet@38282
   219
  | count_combformula (AConn (_, phis)) = fold count_combformula phis
blanchet@38282
   220
  | count_combformula (AAtom tm) = count_combterm tm
blanchet@38752
   221
fun count_fol_formula ({combformula, ...} : fol_formula) =
blanchet@38282
   222
  count_combformula combformula
blanchet@38282
   223
blanchet@38282
   224
val optional_helpers =
blanchet@38890
   225
  [(["c_COMBI"], @{thms COMBI_def}),
blanchet@38890
   226
   (["c_COMBK"], @{thms COMBK_def}),
blanchet@38890
   227
   (["c_COMBB"], @{thms COMBB_def}),
blanchet@38890
   228
   (["c_COMBC"], @{thms COMBC_def}),
blanchet@38282
   229
   (["c_COMBS"], @{thms COMBS_def})]
blanchet@38282
   230
val optional_typed_helpers =
blanchet@38678
   231
  [(["c_True", "c_False", "c_If"], @{thms True_or_False}),
blanchet@38678
   232
   (["c_If"], @{thms if_True if_False})]
blanchet@38606
   233
val mandatory_helpers = @{thms fequal_def}
blanchet@38282
   234
blanchet@38282
   235
val init_counters =
blanchet@38687
   236
  [optional_helpers, optional_typed_helpers] |> maps (maps fst)
blanchet@38678
   237
  |> sort_distinct string_ord |> map (rpair 0) |> Symtab.make
blanchet@38282
   238
blanchet@38282
   239
fun get_helper_facts ctxt is_FO full_types conjectures axioms =
blanchet@38282
   240
  let
blanchet@38282
   241
    val ct = fold (fold count_fol_formula) [conjectures, axioms] init_counters
blanchet@38282
   242
    fun is_needed c = the (Symtab.lookup ct c) > 0
blanchet@38698
   243
    fun baptize th = ((Thm.get_name_hint th, false), th)
blanchet@38282
   244
  in
blanchet@38282
   245
    (optional_helpers
blanchet@38282
   246
     |> full_types ? append optional_typed_helpers
blanchet@38282
   247
     |> maps (fn (ss, ths) =>
blanchet@38698
   248
                 if exists is_needed ss then map baptize ths else [])) @
blanchet@38698
   249
    (if is_FO then [] else map baptize mandatory_helpers)
blanchet@38618
   250
    |> map_filter (Option.map snd o make_axiom ctxt false)
blanchet@38282
   251
  end
blanchet@38282
   252
blanchet@39005
   253
fun prepare_axiom ctxt (ax as (_, th)) = (prop_of th, make_axiom ctxt true ax)
blanchet@39004
   254
blanchet@39005
   255
fun prepare_formulas ctxt full_types hyp_ts concl_t axioms =
blanchet@38282
   256
  let
blanchet@38282
   257
    val thy = ProofContext.theory_of ctxt
blanchet@39005
   258
    val (axiom_ts, prepared_axioms) = ListPair.unzip axioms
blanchet@39005
   259
    (* Remove existing axioms from the conjecture, as this can dramatically
blanchet@39005
   260
       boost an ATP's performance (for some reason). *)
blanchet@39005
   261
    val hyp_ts = hyp_ts |> filter_out (member (op aconv) axiom_ts)
blanchet@38282
   262
    val goal_t = Logic.list_implies (hyp_ts, concl_t)
blanchet@38282
   263
    val is_FO = Meson.is_fol_term thy goal_t
blanchet@38282
   264
    val subs = tfree_classes_of_terms [goal_t]
blanchet@38282
   265
    val supers = tvar_classes_of_terms axiom_ts
blanchet@38282
   266
    val tycons = type_consts_of_terms thy (goal_t :: axiom_ts)
blanchet@38282
   267
    (* TFrees in the conjecture; TVars in the axioms *)
blanchet@38613
   268
    val conjectures = make_conjecture ctxt (hyp_ts @ [concl_t])
blanchet@39004
   269
    val (axiom_names, axioms) = ListPair.unzip (map_filter I prepared_axioms)
blanchet@38282
   270
    val helper_facts = get_helper_facts ctxt is_FO full_types conjectures axioms
blanchet@38282
   271
    val (supers', arity_clauses) = make_arity_clauses thy tycons supers
blanchet@38282
   272
    val class_rel_clauses = make_class_rel_clauses thy subs supers'
blanchet@38282
   273
  in
blanchet@38818
   274
    (axiom_names |> map single |> Vector.fromList,
blanchet@38282
   275
     (conjectures, axioms, helper_facts, class_rel_clauses, arity_clauses))
blanchet@38282
   276
  end
blanchet@38282
   277
blanchet@38282
   278
fun wrap_type ty t = ATerm ((type_wrapper_name, type_wrapper_name), [ty, t])
blanchet@38282
   279
blanchet@38282
   280
fun fo_term_for_combtyp (CombTVar name) = ATerm (name, [])
blanchet@38282
   281
  | fo_term_for_combtyp (CombTFree name) = ATerm (name, [])
blanchet@38282
   282
  | fo_term_for_combtyp (CombType (name, tys)) =
blanchet@38282
   283
    ATerm (name, map fo_term_for_combtyp tys)
blanchet@38282
   284
blanchet@38282
   285
fun fo_literal_for_type_literal (TyLitVar (class, name)) =
blanchet@38282
   286
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@38282
   287
  | fo_literal_for_type_literal (TyLitFree (class, name)) =
blanchet@38282
   288
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@38282
   289
blanchet@38282
   290
fun formula_for_fo_literal (pos, t) = AAtom t |> not pos ? mk_anot
blanchet@38282
   291
blanchet@38282
   292
fun fo_term_for_combterm full_types =
blanchet@38282
   293
  let
blanchet@38282
   294
    fun aux top_level u =
blanchet@38282
   295
      let
blanchet@38282
   296
        val (head, args) = strip_combterm_comb u
blanchet@38282
   297
        val (x, ty_args) =
blanchet@38282
   298
          case head of
blanchet@38282
   299
            CombConst (name as (s, s'), _, ty_args) =>
blanchet@38496
   300
            let val ty_args = if full_types then [] else ty_args in
blanchet@38496
   301
              if s = "equal" then
blanchet@38496
   302
                if top_level andalso length args = 2 then (name, [])
blanchet@38496
   303
                else (("c_fequal", @{const_name fequal}), ty_args)
blanchet@38496
   304
              else if top_level then
blanchet@38496
   305
                case s of
blanchet@38496
   306
                  "c_False" => (("$false", s'), [])
blanchet@38496
   307
                | "c_True" => (("$true", s'), [])
blanchet@38496
   308
                | _ => (name, ty_args)
blanchet@38496
   309
              else
blanchet@38496
   310
                (name, ty_args)
blanchet@38496
   311
            end
blanchet@38282
   312
          | CombVar (name, _) => (name, [])
blanchet@38282
   313
          | CombApp _ => raise Fail "impossible \"CombApp\""
blanchet@38282
   314
        val t = ATerm (x, map fo_term_for_combtyp ty_args @
blanchet@38282
   315
                          map (aux false) args)
blanchet@38282
   316
    in
blanchet@38282
   317
      if full_types then wrap_type (fo_term_for_combtyp (combtyp_of u)) t else t
blanchet@38282
   318
    end
blanchet@38282
   319
  in aux true end
blanchet@38282
   320
blanchet@38282
   321
fun formula_for_combformula full_types =
blanchet@38282
   322
  let
blanchet@38282
   323
    fun aux (AQuant (q, xs, phi)) = AQuant (q, xs, aux phi)
blanchet@38282
   324
      | aux (AConn (c, phis)) = AConn (c, map aux phis)
blanchet@38282
   325
      | aux (AAtom tm) = AAtom (fo_term_for_combterm full_types tm)
blanchet@38282
   326
  in aux end
blanchet@38282
   327
blanchet@38752
   328
fun formula_for_axiom full_types
blanchet@38752
   329
                      ({combformula, ctypes_sorts, ...} : fol_formula) =
blanchet@38282
   330
  mk_ahorn (map (formula_for_fo_literal o fo_literal_for_type_literal)
blanchet@38282
   331
                (type_literals_for_types ctypes_sorts))
blanchet@38282
   332
           (formula_for_combformula full_types combformula)
blanchet@38282
   333
blanchet@38752
   334
fun problem_line_for_fact prefix full_types (formula as {name, kind, ...}) =
blanchet@38282
   335
  Fof (prefix ^ ascii_of name, kind, formula_for_axiom full_types formula)
blanchet@38282
   336
blanchet@38282
   337
fun problem_line_for_class_rel_clause (ClassRelClause {name, subclass,
blanchet@38282
   338
                                                       superclass, ...}) =
blanchet@38282
   339
  let val ty_arg = ATerm (("T", "T"), []) in
blanchet@38282
   340
    Fof (class_rel_clause_prefix ^ ascii_of name, Axiom,
blanchet@38282
   341
         AConn (AImplies, [AAtom (ATerm (subclass, [ty_arg])),
blanchet@38282
   342
                           AAtom (ATerm (superclass, [ty_arg]))]))
blanchet@38282
   343
  end
blanchet@38282
   344
blanchet@38282
   345
fun fo_literal_for_arity_literal (TConsLit (c, t, args)) =
blanchet@38282
   346
    (true, ATerm (c, [ATerm (t, map (fn arg => ATerm (arg, [])) args)]))
blanchet@38282
   347
  | fo_literal_for_arity_literal (TVarLit (c, sort)) =
blanchet@38282
   348
    (false, ATerm (c, [ATerm (sort, [])]))
blanchet@38282
   349
blanchet@38282
   350
fun problem_line_for_arity_clause (ArityClause {name, conclLit, premLits,
blanchet@38282
   351
                                                ...}) =
blanchet@38282
   352
  Fof (arity_clause_prefix ^ ascii_of name, Axiom,
blanchet@38282
   353
       mk_ahorn (map (formula_for_fo_literal o apfst not
blanchet@38282
   354
                      o fo_literal_for_arity_literal) premLits)
blanchet@38282
   355
                (formula_for_fo_literal
blanchet@38282
   356
                     (fo_literal_for_arity_literal conclLit)))
blanchet@38282
   357
blanchet@38282
   358
fun problem_line_for_conjecture full_types
blanchet@38752
   359
                                ({name, kind, combformula, ...} : fol_formula) =
blanchet@38282
   360
  Fof (conjecture_prefix ^ name, kind,
blanchet@38282
   361
       formula_for_combformula full_types combformula)
blanchet@38282
   362
blanchet@38752
   363
fun free_type_literals_for_conjecture ({ctypes_sorts, ...} : fol_formula) =
blanchet@38282
   364
  map fo_literal_for_type_literal (type_literals_for_types ctypes_sorts)
blanchet@38282
   365
blanchet@38282
   366
fun problem_line_for_free_type lit =
blanchet@38613
   367
  Fof (tfrees_name, Hypothesis, formula_for_fo_literal lit)
blanchet@38282
   368
fun problem_lines_for_free_types conjectures =
blanchet@38282
   369
  let
blanchet@38282
   370
    val litss = map free_type_literals_for_conjecture conjectures
blanchet@38282
   371
    val lits = fold (union (op =)) litss []
blanchet@38282
   372
  in map problem_line_for_free_type lits end
blanchet@38282
   373
blanchet@38282
   374
(** "hBOOL" and "hAPP" **)
blanchet@38282
   375
blanchet@38282
   376
type const_info = {min_arity: int, max_arity: int, sub_level: bool}
blanchet@38282
   377
blanchet@38282
   378
fun consider_term top_level (ATerm ((s, _), ts)) =
blanchet@38282
   379
  (if is_tptp_variable s then
blanchet@38282
   380
     I
blanchet@38282
   381
   else
blanchet@38282
   382
     let val n = length ts in
blanchet@38282
   383
       Symtab.map_default
blanchet@38282
   384
           (s, {min_arity = n, max_arity = 0, sub_level = false})
blanchet@38282
   385
           (fn {min_arity, max_arity, sub_level} =>
blanchet@38282
   386
               {min_arity = Int.min (n, min_arity),
blanchet@38282
   387
                max_arity = Int.max (n, max_arity),
blanchet@38282
   388
                sub_level = sub_level orelse not top_level})
blanchet@38282
   389
     end)
blanchet@38282
   390
  #> fold (consider_term (top_level andalso s = type_wrapper_name)) ts
blanchet@38282
   391
fun consider_formula (AQuant (_, _, phi)) = consider_formula phi
blanchet@38282
   392
  | consider_formula (AConn (_, phis)) = fold consider_formula phis
blanchet@38282
   393
  | consider_formula (AAtom tm) = consider_term true tm
blanchet@38282
   394
blanchet@38282
   395
fun consider_problem_line (Fof (_, _, phi)) = consider_formula phi
blanchet@38282
   396
fun consider_problem problem = fold (fold consider_problem_line o snd) problem
blanchet@38282
   397
blanchet@38282
   398
fun const_table_for_problem explicit_apply problem =
blanchet@38282
   399
  if explicit_apply then NONE
blanchet@38282
   400
  else SOME (Symtab.empty |> consider_problem problem)
blanchet@38282
   401
blanchet@38282
   402
fun min_arity_of thy full_types NONE s =
blanchet@38282
   403
    (if s = "equal" orelse s = type_wrapper_name orelse
blanchet@38282
   404
        String.isPrefix type_const_prefix s orelse
blanchet@38282
   405
        String.isPrefix class_prefix s then
blanchet@38282
   406
       16383 (* large number *)
blanchet@38282
   407
     else if full_types then
blanchet@38282
   408
       0
blanchet@38748
   409
     else case strip_prefix_and_unascii const_prefix s of
blanchet@38282
   410
       SOME s' => num_type_args thy (invert_const s')
blanchet@38282
   411
     | NONE => 0)
blanchet@38282
   412
  | min_arity_of _ _ (SOME the_const_tab) s =
blanchet@38282
   413
    case Symtab.lookup the_const_tab s of
blanchet@38282
   414
      SOME ({min_arity, ...} : const_info) => min_arity
blanchet@38282
   415
    | NONE => 0
blanchet@38282
   416
blanchet@38282
   417
fun full_type_of (ATerm ((s, _), [ty, _])) =
blanchet@38282
   418
    if s = type_wrapper_name then ty else raise Fail "expected type wrapper"
blanchet@38282
   419
  | full_type_of _ = raise Fail "expected type wrapper"
blanchet@38282
   420
blanchet@38282
   421
fun list_hAPP_rev _ t1 [] = t1
blanchet@38282
   422
  | list_hAPP_rev NONE t1 (t2 :: ts2) =
blanchet@38282
   423
    ATerm (`I "hAPP", [list_hAPP_rev NONE t1 ts2, t2])
blanchet@38282
   424
  | list_hAPP_rev (SOME ty) t1 (t2 :: ts2) =
blanchet@38282
   425
    let val ty' = ATerm (`make_fixed_type_const @{type_name fun},
blanchet@38282
   426
                         [full_type_of t2, ty]) in
blanchet@38282
   427
      ATerm (`I "hAPP", [wrap_type ty' (list_hAPP_rev (SOME ty') t1 ts2), t2])
blanchet@38282
   428
    end
blanchet@38282
   429
blanchet@38282
   430
fun repair_applications_in_term thy full_types const_tab =
blanchet@38282
   431
  let
blanchet@38282
   432
    fun aux opt_ty (ATerm (name as (s, _), ts)) =
blanchet@38282
   433
      if s = type_wrapper_name then
blanchet@38282
   434
        case ts of
blanchet@38282
   435
          [t1, t2] => ATerm (name, [aux NONE t1, aux (SOME t1) t2])
blanchet@38282
   436
        | _ => raise Fail "malformed type wrapper"
blanchet@38282
   437
      else
blanchet@38282
   438
        let
blanchet@38282
   439
          val ts = map (aux NONE) ts
blanchet@38282
   440
          val (ts1, ts2) = chop (min_arity_of thy full_types const_tab s) ts
blanchet@38282
   441
        in list_hAPP_rev opt_ty (ATerm (name, ts1)) (rev ts2) end
blanchet@38282
   442
  in aux NONE end
blanchet@38282
   443
blanchet@38282
   444
fun boolify t = ATerm (`I "hBOOL", [t])
blanchet@38282
   445
blanchet@38282
   446
(* True if the constant ever appears outside of the top-level position in
blanchet@38282
   447
   literals, or if it appears with different arities (e.g., because of different
blanchet@38282
   448
   type instantiations). If false, the constant always receives all of its
blanchet@38282
   449
   arguments and is used as a predicate. *)
blanchet@38282
   450
fun is_predicate NONE s =
blanchet@38589
   451
    s = "equal" orelse s = "$false" orelse s = "$true" orelse
blanchet@38589
   452
    String.isPrefix type_const_prefix s orelse String.isPrefix class_prefix s
blanchet@38282
   453
  | is_predicate (SOME the_const_tab) s =
blanchet@38282
   454
    case Symtab.lookup the_const_tab s of
blanchet@38282
   455
      SOME {min_arity, max_arity, sub_level} =>
blanchet@38282
   456
      not sub_level andalso min_arity = max_arity
blanchet@38282
   457
    | NONE => false
blanchet@38282
   458
blanchet@38282
   459
fun repair_predicates_in_term const_tab (t as ATerm ((s, _), ts)) =
blanchet@38282
   460
  if s = type_wrapper_name then
blanchet@38282
   461
    case ts of
blanchet@38282
   462
      [_, t' as ATerm ((s', _), _)] =>
blanchet@38282
   463
      if is_predicate const_tab s' then t' else boolify t
blanchet@38282
   464
    | _ => raise Fail "malformed type wrapper"
blanchet@38282
   465
  else
blanchet@38282
   466
    t |> not (is_predicate const_tab s) ? boolify
blanchet@38282
   467
blanchet@38282
   468
fun close_universally phi =
blanchet@38282
   469
  let
blanchet@38282
   470
    fun term_vars bounds (ATerm (name as (s, _), tms)) =
blanchet@38282
   471
        (is_tptp_variable s andalso not (member (op =) bounds name))
blanchet@38282
   472
          ? insert (op =) name
blanchet@38282
   473
        #> fold (term_vars bounds) tms
blanchet@38678
   474
    fun formula_vars bounds (AQuant (_, xs, phi)) =
blanchet@38282
   475
        formula_vars (xs @ bounds) phi
blanchet@38282
   476
      | formula_vars bounds (AConn (_, phis)) = fold (formula_vars bounds) phis
blanchet@38282
   477
      | formula_vars bounds (AAtom tm) = term_vars bounds tm
blanchet@38282
   478
  in
blanchet@38282
   479
    case formula_vars [] phi [] of [] => phi | xs => AQuant (AForall, xs, phi)
blanchet@38282
   480
  end
blanchet@38282
   481
blanchet@38282
   482
fun repair_formula thy explicit_forall full_types const_tab =
blanchet@38282
   483
  let
blanchet@38282
   484
    fun aux (AQuant (q, xs, phi)) = AQuant (q, xs, aux phi)
blanchet@38282
   485
      | aux (AConn (c, phis)) = AConn (c, map aux phis)
blanchet@38282
   486
      | aux (AAtom tm) =
blanchet@38282
   487
        AAtom (tm |> repair_applications_in_term thy full_types const_tab
blanchet@38282
   488
                  |> repair_predicates_in_term const_tab)
blanchet@38282
   489
  in aux #> explicit_forall ? close_universally end
blanchet@38282
   490
blanchet@38282
   491
fun repair_problem_line thy explicit_forall full_types const_tab
blanchet@38282
   492
                        (Fof (ident, kind, phi)) =
blanchet@38282
   493
  Fof (ident, kind, repair_formula thy explicit_forall full_types const_tab phi)
blanchet@38282
   494
fun repair_problem_with_const_table thy =
blanchet@38282
   495
  map o apsnd o map ooo repair_problem_line thy
blanchet@38282
   496
blanchet@38282
   497
fun repair_problem thy explicit_forall full_types explicit_apply problem =
blanchet@38282
   498
  repair_problem_with_const_table thy explicit_forall full_types
blanchet@38282
   499
      (const_table_for_problem explicit_apply problem) problem
blanchet@38282
   500
blanchet@38282
   501
fun prepare_problem ctxt readable_names explicit_forall full_types
blanchet@39005
   502
                    explicit_apply hyp_ts concl_t axioms =
blanchet@38282
   503
  let
blanchet@38282
   504
    val thy = ProofContext.theory_of ctxt
blanchet@38282
   505
    val (axiom_names, (conjectures, axioms, helper_facts, class_rel_clauses,
blanchet@38282
   506
                       arity_clauses)) =
blanchet@39005
   507
      prepare_formulas ctxt full_types hyp_ts concl_t axioms
blanchet@38282
   508
    val axiom_lines = map (problem_line_for_fact axiom_prefix full_types) axioms
blanchet@38282
   509
    val helper_lines =
blanchet@38282
   510
      map (problem_line_for_fact helper_prefix full_types) helper_facts
blanchet@38282
   511
    val conjecture_lines =
blanchet@38282
   512
      map (problem_line_for_conjecture full_types) conjectures
blanchet@38282
   513
    val tfree_lines = problem_lines_for_free_types conjectures
blanchet@38282
   514
    val class_rel_lines =
blanchet@38282
   515
      map problem_line_for_class_rel_clause class_rel_clauses
blanchet@38282
   516
    val arity_lines = map problem_line_for_arity_clause arity_clauses
blanchet@38282
   517
    (* Reordering these might or might not confuse the proof reconstruction
blanchet@38282
   518
       code or the SPASS Flotter hack. *)
blanchet@38282
   519
    val problem =
blanchet@38282
   520
      [("Relevant facts", axiom_lines),
blanchet@38282
   521
       ("Class relationships", class_rel_lines),
blanchet@38282
   522
       ("Arity declarations", arity_lines),
blanchet@38282
   523
       ("Helper facts", helper_lines),
blanchet@38282
   524
       ("Conjectures", conjecture_lines),
blanchet@38282
   525
       ("Type variables", tfree_lines)]
blanchet@38282
   526
      |> repair_problem thy explicit_forall full_types explicit_apply
blanchet@38282
   527
    val (problem, pool) = nice_tptp_problem readable_names problem
blanchet@38282
   528
    val conjecture_offset =
blanchet@38282
   529
      length axiom_lines + length class_rel_lines + length arity_lines
blanchet@38282
   530
      + length helper_lines
blanchet@38282
   531
  in
blanchet@38282
   532
    (problem,
blanchet@38282
   533
     case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
blanchet@38282
   534
     conjecture_offset, axiom_names)
blanchet@38282
   535
  end
blanchet@38282
   536
blanchet@38282
   537
end;