src/HOL/Tools/Sledgehammer/sledgehammer.ML
author blanchet
Thu Jul 29 22:43:46 2010 +0200 (2010-07-29 ago)
changeset 38100 e458a0dd3dc1
parent 38098 db90d313cf53
child 38102 019a49759829
permissions -rw-r--r--
use "explicit_apply" in the minimizer whenever it might make a difference to prevent freak failures;
this replaces the previous, somewhat messy solution of adding "extra" clauses
blanchet@38021
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer.ML
wenzelm@28477
     2
    Author:     Fabian Immler, TU Muenchen
wenzelm@32996
     3
    Author:     Makarius
blanchet@35969
     4
    Author:     Jasmin Blanchette, TU Muenchen
wenzelm@28477
     5
blanchet@38021
     6
Sledgehammer's heart.
wenzelm@28477
     7
*)
wenzelm@28477
     8
blanchet@38021
     9
signature SLEDGEHAMMER =
wenzelm@28477
    10
sig
blanchet@38023
    11
  type failure = ATP_Systems.failure
blanchet@35969
    12
  type relevance_override = Sledgehammer_Fact_Filter.relevance_override
blanchet@36281
    13
  type minimize_command = Sledgehammer_Proof_Reconstruct.minimize_command
blanchet@35969
    14
  type params =
blanchet@35969
    15
    {debug: bool,
blanchet@35969
    16
     verbose: bool,
blanchet@36143
    17
     overlord: bool,
blanchet@35969
    18
     atps: string list,
blanchet@35969
    19
     full_types: bool,
blanchet@36235
    20
     explicit_apply: bool,
blanchet@35969
    21
     relevance_threshold: real,
blanchet@36922
    22
     relevance_convergence: real,
blanchet@36220
    23
     theory_relevant: bool option,
blanchet@36922
    24
     defs_relevant: bool,
blanchet@35969
    25
     isar_proof: bool,
blanchet@36924
    26
     isar_shrink_factor: int,
blanchet@35969
    27
     timeout: Time.time,
blanchet@35969
    28
     minimize_timeout: Time.time}
blanchet@35867
    29
  type problem =
blanchet@35969
    30
    {subgoal: int,
blanchet@35969
    31
     goal: Proof.context * (thm list * thm),
blanchet@35969
    32
     relevance_override: relevance_override,
blanchet@38084
    33
     axioms: (string * thm) list option}
blanchet@35867
    34
  type prover_result =
blanchet@36370
    35
    {outcome: failure option,
blanchet@35969
    36
     message: string,
blanchet@37926
    37
     pool: string Symtab.table,
blanchet@38015
    38
     used_thm_names: string list,
blanchet@35969
    39
     atp_run_time_in_msecs: int,
blanchet@36369
    40
     output: string,
blanchet@35969
    41
     proof: string,
blanchet@35969
    42
     internal_thm_names: string Vector.vector,
blanchet@38083
    43
     conjecture_shape: int list list}
blanchet@38100
    44
  type prover = params -> minimize_command -> problem -> prover_result
blanchet@35867
    45
blanchet@38023
    46
  val dest_dir : string Config.T
blanchet@38023
    47
  val problem_prefix : string Config.T
blanchet@38023
    48
  val measure_runtime : bool Config.T
blanchet@35969
    49
  val kill_atps: unit -> unit
blanchet@35969
    50
  val running_atps: unit -> unit
wenzelm@29112
    51
  val messages: int option -> unit
blanchet@38023
    52
  val get_prover_fun : theory -> string -> prover
blanchet@38044
    53
  val run_sledgehammer :
blanchet@38044
    54
    params -> int -> relevance_override -> (string -> minimize_command)
blanchet@38044
    55
    -> Proof.state -> unit
blanchet@38023
    56
  val setup : theory -> theory
wenzelm@28477
    57
end;
wenzelm@28477
    58
blanchet@38021
    59
structure Sledgehammer : SLEDGEHAMMER =
wenzelm@28477
    60
struct
wenzelm@28477
    61
blanchet@38028
    62
open ATP_Problem
blanchet@38028
    63
open ATP_Systems
blanchet@37578
    64
open Metis_Clauses
blanchet@38023
    65
open Sledgehammer_Util
blanchet@36063
    66
open Sledgehammer_Fact_Filter
blanchet@36063
    67
open Sledgehammer_Proof_Reconstruct
blanchet@37583
    68
blanchet@38023
    69
blanchet@37583
    70
(** The Sledgehammer **)
blanchet@37583
    71
blanchet@37585
    72
val das_Tool = "Sledgehammer"
blanchet@37585
    73
blanchet@37585
    74
fun kill_atps () = Async_Manager.kill_threads das_Tool "ATPs"
blanchet@37585
    75
fun running_atps () = Async_Manager.running_threads das_Tool "ATPs"
blanchet@37585
    76
val messages = Async_Manager.thread_messages das_Tool "ATP"
blanchet@35969
    77
blanchet@36281
    78
(** problems, results, provers, etc. **)
blanchet@35969
    79
blanchet@35969
    80
type params =
blanchet@35969
    81
  {debug: bool,
blanchet@35969
    82
   verbose: bool,
blanchet@36143
    83
   overlord: bool,
blanchet@35969
    84
   atps: string list,
blanchet@35969
    85
   full_types: bool,
blanchet@36235
    86
   explicit_apply: bool,
blanchet@35969
    87
   relevance_threshold: real,
blanchet@36922
    88
   relevance_convergence: real,
blanchet@36220
    89
   theory_relevant: bool option,
blanchet@36922
    90
   defs_relevant: bool,
blanchet@35969
    91
   isar_proof: bool,
blanchet@36924
    92
   isar_shrink_factor: int,
blanchet@35969
    93
   timeout: Time.time,
blanchet@35969
    94
   minimize_timeout: Time.time}
blanchet@35867
    95
blanchet@35867
    96
type problem =
blanchet@35969
    97
  {subgoal: int,
blanchet@35969
    98
   goal: Proof.context * (thm list * thm),
blanchet@35969
    99
   relevance_override: relevance_override,
blanchet@38084
   100
   axioms: (string * thm) list option}
blanchet@35867
   101
blanchet@35867
   102
type prover_result =
blanchet@36370
   103
  {outcome: failure option,
blanchet@35969
   104
   message: string,
blanchet@37926
   105
   pool: string Symtab.table,
blanchet@38015
   106
   used_thm_names: string list,
blanchet@35969
   107
   atp_run_time_in_msecs: int,
blanchet@36369
   108
   output: string,
blanchet@35969
   109
   proof: string,
blanchet@35969
   110
   internal_thm_names: string Vector.vector,
blanchet@38083
   111
   conjecture_shape: int list list}
blanchet@35867
   112
blanchet@38100
   113
type prover = params -> minimize_command -> problem -> prover_result
blanchet@35867
   114
blanchet@38023
   115
(* configuration attributes *)
blanchet@38023
   116
blanchet@38023
   117
val (dest_dir, dest_dir_setup) = Attrib.config_string "atp_dest_dir" (K "");
blanchet@38023
   118
  (*Empty string means create files in Isabelle's temporary files directory.*)
blanchet@38023
   119
blanchet@38023
   120
val (problem_prefix, problem_prefix_setup) =
blanchet@38023
   121
  Attrib.config_string "atp_problem_prefix" (K "prob");
blanchet@38023
   122
blanchet@38023
   123
val (measure_runtime, measure_runtime_setup) =
blanchet@38023
   124
  Attrib.config_bool "atp_measure_runtime" (K false);
wenzelm@28484
   125
blanchet@38023
   126
fun with_path cleanup after f path =
blanchet@38023
   127
  Exn.capture f path
blanchet@38023
   128
  |> tap (fn _ => cleanup path)
blanchet@38023
   129
  |> Exn.release
blanchet@38023
   130
  |> tap (after path)
blanchet@38023
   131
blanchet@38023
   132
(* Splits by the first possible of a list of delimiters. *)
blanchet@38023
   133
fun extract_proof delims output =
blanchet@38023
   134
  case pairself (find_first (fn s => String.isSubstring s output))
blanchet@38023
   135
                (ListPair.unzip delims) of
blanchet@38023
   136
    (SOME begin_delim, SOME end_delim) =>
blanchet@38023
   137
    (output |> first_field begin_delim |> the |> snd
blanchet@38023
   138
            |> first_field end_delim |> the |> fst
blanchet@38023
   139
            |> first_field "\n" |> the |> snd
blanchet@38023
   140
     handle Option.Option => "")
blanchet@38023
   141
  | _ => ""
wenzelm@28484
   142
blanchet@38023
   143
fun extract_proof_and_outcome complete res_code proof_delims known_failures
blanchet@38023
   144
                              output =
blanchet@38061
   145
  case known_failure_in_output output known_failures of
blanchet@38061
   146
    NONE => (case extract_proof proof_delims output of
blanchet@38061
   147
             "" => ("", SOME MalformedOutput)
blanchet@38023
   148
           | proof => if res_code = 0 then (proof, NONE)
blanchet@38023
   149
                      else ("", SOME UnknownError))
blanchet@38061
   150
  | SOME failure =>
blanchet@38023
   151
    ("", SOME (if failure = IncompleteUnprovable andalso complete then
blanchet@38023
   152
                 Unprovable
blanchet@38023
   153
               else
blanchet@38023
   154
                 failure))
wenzelm@28582
   155
wenzelm@28586
   156
blanchet@38023
   157
(* Clause preparation *)
blanchet@38023
   158
blanchet@38023
   159
datatype fol_formula =
blanchet@38023
   160
  FOLFormula of {formula_name: string,
blanchet@38023
   161
                 kind: kind,
blanchet@38023
   162
                 combformula: (name, combterm) formula,
blanchet@38023
   163
                 ctypes_sorts: typ list}
blanchet@38023
   164
blanchet@38023
   165
fun mk_anot phi = AConn (ANot, [phi])
blanchet@38023
   166
fun mk_aconn c phi1 phi2 = AConn (c, [phi1, phi2])
blanchet@38023
   167
fun mk_ahorn [] phi = phi
blanchet@38023
   168
  | mk_ahorn (phi :: phis) psi =
blanchet@38023
   169
    AConn (AImplies, [fold (mk_aconn AAnd) phis phi, psi])
blanchet@38023
   170
blanchet@38023
   171
(* ### FIXME: reintroduce
blanchet@38085
   172
fun make_formula_table xs =
blanchet@38023
   173
  fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
blanchet@38085
   174
(* Remove existing axioms from the conjecture, as this can
blanchet@38023
   175
   dramatically boost an ATP's performance (for some reason). *)
blanchet@38085
   176
fun subtract_cls axioms =
blanchet@38085
   177
  filter_out (Termtab.defined (make_formula_table axioms) o prop_of)
blanchet@38023
   178
*)
blanchet@38023
   179
blanchet@38023
   180
fun combformula_for_prop thy =
blanchet@38023
   181
  let
blanchet@38023
   182
    val do_term = combterm_from_term thy
blanchet@38023
   183
    fun do_quant bs q s T t' =
blanchet@38023
   184
      do_formula ((s, T) :: bs) t'
blanchet@38023
   185
      #>> (fn phi => AQuant (q, [`make_bound_var s], phi))
blanchet@38023
   186
    and do_conn bs c t1 t2 =
blanchet@38023
   187
      do_formula bs t1 ##>> do_formula bs t2
blanchet@38023
   188
      #>> (fn (phi1, phi2) => AConn (c, [phi1, phi2]))
blanchet@38023
   189
    and do_formula bs t =
blanchet@38023
   190
      case t of
blanchet@38023
   191
        @{const Not} $ t1 =>
blanchet@38023
   192
        do_formula bs t1 #>> (fn phi => AConn (ANot, [phi]))
blanchet@38023
   193
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@38023
   194
        do_quant bs AForall s T t'
blanchet@38023
   195
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@38023
   196
        do_quant bs AExists s T t'
blanchet@38023
   197
      | @{const "op &"} $ t1 $ t2 => do_conn bs AAnd t1 t2
blanchet@38023
   198
      | @{const "op |"} $ t1 $ t2 => do_conn bs AOr t1 t2
blanchet@38023
   199
      | @{const "op -->"} $ t1 $ t2 => do_conn bs AImplies t1 t2
blanchet@38023
   200
      | Const (@{const_name "op ="}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@38023
   201
        do_conn bs AIff t1 t2
blanchet@38023
   202
      | _ => (fn ts => do_term bs (Envir.eta_contract t)
blanchet@38034
   203
                       |>> AAtom ||> union (op =) ts)
blanchet@38023
   204
  in do_formula [] end
blanchet@38023
   205
blanchet@38023
   206
(* Converts an elim-rule into an equivalent theorem that does not have the
blanchet@38023
   207
   predicate variable. Leaves other theorems unchanged. We simply instantiate
blanchet@38023
   208
   the conclusion variable to False. (Cf. "transform_elim_term" in
blanchet@38023
   209
   "ATP_Systems".) *)
blanchet@38023
   210
(* FIXME: test! *)
blanchet@38023
   211
fun transform_elim_term t =
blanchet@38023
   212
  case Logic.strip_imp_concl t of
blanchet@38023
   213
    @{const Trueprop} $ Var (z, @{typ bool}) =>
blanchet@38023
   214
    subst_Vars [(z, @{const True})] t
blanchet@38023
   215
  | Var (z, @{typ prop}) => subst_Vars [(z, @{prop True})] t
blanchet@38023
   216
  | _ => t
blanchet@38023
   217
blanchet@38023
   218
(* Removes the lambdas from an equation of the form "t = (%x. u)".
blanchet@38023
   219
   (Cf. "extensionalize_theorem" in "Clausifier".) *)
blanchet@38023
   220
fun extensionalize_term t =
blanchet@38023
   221
  let
blanchet@38023
   222
    fun aux j (Const (@{const_name "op ="}, Type (_, [Type (_, [_, T']), _]))
blanchet@38023
   223
               $ t2 $ Abs (s, var_T, t')) =
blanchet@38023
   224
        let val var_t = Var (("x", j), var_T) in
blanchet@38023
   225
          Const (@{const_name "op ="}, T' --> T' --> HOLogic.boolT)
blanchet@38023
   226
            $ betapply (t2, var_t) $ subst_bound (var_t, t')
blanchet@38023
   227
          |> aux (j + 1)
blanchet@38023
   228
        end
blanchet@38023
   229
      | aux _ t = t
blanchet@38023
   230
  in aux (maxidx_of_term t + 1) t end
blanchet@38023
   231
blanchet@38089
   232
fun presimplify_term thy =
blanchet@38091
   233
  Skip_Proof.make_thm thy
blanchet@38089
   234
  #> Meson.presimplify
blanchet@38089
   235
  #> prop_of
blanchet@38089
   236
blanchet@38098
   237
(* Freshness almost guaranteed! *)
blanchet@38098
   238
fun concealed_bound_name j = das_Tool ^ Int.toString j
blanchet@38023
   239
fun conceal_bounds Ts t =
blanchet@38023
   240
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@38023
   241
                    (length Ts - 1 downto 0 ~~ rev Ts), t)
blanchet@38023
   242
fun reveal_bounds Ts =
blanchet@38023
   243
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@38023
   244
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@38023
   245
blanchet@38023
   246
fun introduce_combinators_in_term ctxt kind t =
blanchet@38023
   247
  let
blanchet@38023
   248
    val thy = ProofContext.theory_of ctxt
blanchet@38023
   249
    fun aux Ts t =
blanchet@38023
   250
      case t of
blanchet@38023
   251
        @{const Not} $ t1 => @{const Not} $ aux Ts t1
blanchet@38023
   252
      | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@38023
   253
        t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38023
   254
      | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@38023
   255
        t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38023
   256
      | (t0 as @{const "op &"}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
blanchet@38023
   257
      | (t0 as @{const "op |"}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
blanchet@38023
   258
      | (t0 as @{const "op -->"}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
blanchet@38023
   259
      | (t0 as Const (@{const_name "op ="}, Type (_, [@{typ bool}, _])))
blanchet@38023
   260
          $ t1 $ t2 =>
blanchet@38023
   261
        t0 $ aux Ts t1 $ aux Ts t2
blanchet@38023
   262
      | _ => if not (exists_subterm (fn Abs _ => true | _ => false) t) then
blanchet@38023
   263
               t
blanchet@38023
   264
             else
blanchet@38023
   265
               let
blanchet@38023
   266
                 val t = t |> conceal_bounds Ts
blanchet@38023
   267
                           |> Envir.eta_contract
blanchet@38023
   268
                 val ([t], ctxt') = Variable.import_terms true [t] ctxt
blanchet@38023
   269
               in
blanchet@38023
   270
                 t |> cterm_of thy
blanchet@38023
   271
                   |> Clausifier.introduce_combinators_in_cterm
blanchet@38023
   272
                   |> singleton (Variable.export ctxt' ctxt)
blanchet@38023
   273
                   |> prop_of |> Logic.dest_equals |> snd
blanchet@38023
   274
                   |> reveal_bounds Ts
blanchet@38023
   275
               end
blanchet@38023
   276
  in t |> not (Meson.is_fol_term thy t) ? aux [] end
blanchet@38023
   277
  handle THM _ =>
blanchet@38023
   278
         (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@38023
   279
         case kind of
blanchet@38023
   280
           Axiom => HOLogic.true_const
blanchet@38023
   281
         | Conjecture => HOLogic.false_const
blanchet@38023
   282
blanchet@38098
   283
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@38098
   284
   same in Sledgehammer to prevent the discovery of unreplable proofs. *)
blanchet@38098
   285
fun freeze_term t =
blanchet@38098
   286
  let
blanchet@38098
   287
    fun aux (t $ u) = aux t $ aux u
blanchet@38098
   288
      | aux (Abs (s, T, t)) = Abs (s, T, aux t)
blanchet@38098
   289
      | aux (Var ((s, i), T)) =
blanchet@38098
   290
        Free (das_Tool ^ "_" ^ s ^ "_" ^ string_of_int i, T)
blanchet@38098
   291
      | aux t = t
blanchet@38098
   292
  in t |> exists_subterm is_Var t ? aux end
blanchet@38098
   293
blanchet@38085
   294
(* making axiom and conjecture formulas *)
blanchet@38089
   295
fun make_formula ctxt presimp (formula_name, kind, t) =
blanchet@38023
   296
  let
blanchet@38023
   297
    val thy = ProofContext.theory_of ctxt
blanchet@38023
   298
    val t = t |> transform_elim_term
blanchet@38023
   299
              |> Object_Logic.atomize_term thy
blanchet@38091
   300
    val t = t |> fastype_of t = HOLogic.boolT ? HOLogic.mk_Trueprop
blanchet@38023
   301
              |> extensionalize_term
blanchet@38089
   302
              |> presimp ? presimplify_term thy
blanchet@38091
   303
              |> perhaps (try (HOLogic.dest_Trueprop))
blanchet@38023
   304
              |> introduce_combinators_in_term ctxt kind
blanchet@38098
   305
              |> kind = Conjecture ? freeze_term
blanchet@38023
   306
    val (combformula, ctypes_sorts) = combformula_for_prop thy t []
blanchet@38023
   307
  in
blanchet@38023
   308
    FOLFormula {formula_name = formula_name, combformula = combformula,
blanchet@38023
   309
                kind = kind, ctypes_sorts = ctypes_sorts}
blanchet@38023
   310
  end
blanchet@38023
   311
blanchet@38089
   312
fun make_axiom ctxt presimp (name, th) =
blanchet@38089
   313
  (name, make_formula ctxt presimp (name, Axiom, prop_of th))
blanchet@38085
   314
fun make_conjectures ctxt ts =
blanchet@38089
   315
  map2 (fn j => fn t => make_formula ctxt true (Int.toString j, Conjecture, t))
blanchet@38023
   316
       (0 upto length ts - 1) ts
blanchet@38023
   317
blanchet@38085
   318
(** Helper facts **)
blanchet@38023
   319
blanchet@38023
   320
fun count_combterm (CombConst ((s, _), _, _)) =
blanchet@38023
   321
    Symtab.map_entry s (Integer.add 1)
blanchet@38023
   322
  | count_combterm (CombVar _) = I
blanchet@38023
   323
  | count_combterm (CombApp (t1, t2)) = fold count_combterm [t1, t2]
blanchet@38023
   324
fun count_combformula (AQuant (_, _, phi)) = count_combformula phi
blanchet@38023
   325
  | count_combformula (AConn (_, phis)) = fold count_combformula phis
blanchet@38034
   326
  | count_combformula (AAtom tm) = count_combterm tm
blanchet@38023
   327
fun count_fol_formula (FOLFormula {combformula, ...}) =
blanchet@38023
   328
  count_combformula combformula
blanchet@38023
   329
blanchet@38023
   330
val optional_helpers =
blanchet@38023
   331
  [(["c_COMBI", "c_COMBK"], @{thms COMBI_def COMBK_def}),
blanchet@38023
   332
   (["c_COMBB", "c_COMBC"], @{thms COMBB_def COMBC_def}),
blanchet@38023
   333
   (["c_COMBS"], @{thms COMBS_def})]
blanchet@38023
   334
val optional_typed_helpers =
blanchet@38023
   335
  [(["c_True", "c_False"], @{thms True_or_False}),
blanchet@38023
   336
   (["c_If"], @{thms if_True if_False True_or_False})]
blanchet@38023
   337
val mandatory_helpers = @{thms fequal_imp_equal equal_imp_fequal}
blanchet@38023
   338
blanchet@38023
   339
val init_counters =
blanchet@38023
   340
  Symtab.make (maps (maps (map (rpair 0) o fst))
blanchet@38023
   341
                    [optional_helpers, optional_typed_helpers])
blanchet@38023
   342
blanchet@38085
   343
fun get_helper_facts ctxt is_FO full_types conjectures axioms =
blanchet@38023
   344
  let
blanchet@38085
   345
    val ct = fold (fold count_fol_formula) [conjectures, axioms] init_counters
blanchet@38023
   346
    fun is_needed c = the (Symtab.lookup ct c) > 0
blanchet@38085
   347
  in
blanchet@38085
   348
    (optional_helpers
blanchet@38085
   349
     |> full_types ? append optional_typed_helpers
blanchet@38085
   350
     |> maps (fn (ss, ths) =>
blanchet@38085
   351
                 if exists is_needed ss then map (`Thm.get_name_hint) ths
blanchet@38085
   352
                 else [])) @
blanchet@38085
   353
    (if is_FO then [] else map (`Thm.get_name_hint) mandatory_helpers)
blanchet@38089
   354
    |> map (snd o make_axiom ctxt false)
blanchet@38085
   355
  end
blanchet@38023
   356
blanchet@38086
   357
fun meta_not t = @{const "==>"} $ t $ @{prop False}
blanchet@38023
   358
blanchet@38085
   359
fun prepare_formulas ctxt full_types hyp_ts concl_t axcls =
blanchet@38023
   360
  let
blanchet@38023
   361
    val thy = ProofContext.theory_of ctxt
blanchet@38023
   362
    val goal_t = Logic.list_implies (hyp_ts, concl_t)
blanchet@38023
   363
    val is_FO = Meson.is_fol_term thy goal_t
blanchet@38083
   364
    val axtms = map (prop_of o snd) axcls
blanchet@38023
   365
    val subs = tfree_classes_of_terms [goal_t]
blanchet@38023
   366
    val supers = tvar_classes_of_terms axtms
blanchet@38023
   367
    val tycons = type_consts_of_terms thy (goal_t :: axtms)
blanchet@38085
   368
    (* TFrees in the conjecture; TVars in the axioms *)
blanchet@38086
   369
    val conjectures = map meta_not hyp_ts @ [concl_t] |> make_conjectures ctxt
blanchet@38089
   370
    val (clnames, axioms) = ListPair.unzip (map (make_axiom ctxt true) axcls)
blanchet@38085
   371
    val helper_facts = get_helper_facts ctxt is_FO full_types conjectures axioms
blanchet@38023
   372
    val (supers', arity_clauses) = make_arity_clauses thy tycons supers
blanchet@38023
   373
    val class_rel_clauses = make_class_rel_clauses thy subs supers'
blanchet@38023
   374
  in
blanchet@38023
   375
    (Vector.fromList clnames,
blanchet@38085
   376
      (conjectures, axioms, helper_facts, class_rel_clauses, arity_clauses))
blanchet@38023
   377
  end
blanchet@38023
   378
blanchet@38023
   379
fun wrap_type ty t = ATerm ((type_wrapper_name, type_wrapper_name), [ty, t])
blanchet@38023
   380
blanchet@38023
   381
fun fo_term_for_combtyp (CombTVar name) = ATerm (name, [])
blanchet@38023
   382
  | fo_term_for_combtyp (CombTFree name) = ATerm (name, [])
blanchet@38023
   383
  | fo_term_for_combtyp (CombType (name, tys)) =
blanchet@38023
   384
    ATerm (name, map fo_term_for_combtyp tys)
blanchet@38023
   385
blanchet@38023
   386
fun fo_literal_for_type_literal (TyLitVar (class, name)) =
blanchet@38023
   387
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@38023
   388
  | fo_literal_for_type_literal (TyLitFree (class, name)) =
blanchet@38023
   389
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@38023
   390
blanchet@38034
   391
fun formula_for_fo_literal (pos, t) = AAtom t |> not pos ? mk_anot
blanchet@38023
   392
blanchet@38023
   393
fun fo_term_for_combterm full_types =
blanchet@38023
   394
  let
blanchet@38023
   395
    fun aux top_level u =
blanchet@38023
   396
      let
blanchet@38023
   397
        val (head, args) = strip_combterm_comb u
blanchet@38023
   398
        val (x, ty_args) =
blanchet@38023
   399
          case head of
blanchet@38087
   400
            CombConst (name as (s, s'), _, ty_args) =>
blanchet@38088
   401
            if s = "equal" then
blanchet@38088
   402
              (if top_level andalso length args = 2 then name
blanchet@38088
   403
               else ("c_fequal", @{const_name fequal}), [])
blanchet@38088
   404
            else if top_level then
blanchet@38088
   405
              case s of
blanchet@38088
   406
                "c_False" => (("$false", s'), [])
blanchet@38088
   407
              | "c_True" => (("$true", s'), [])
blanchet@38088
   408
              | _ => (name, if full_types then [] else ty_args)
blanchet@38023
   409
            else
blanchet@38023
   410
              (name, if full_types then [] else ty_args)
blanchet@38023
   411
          | CombVar (name, _) => (name, [])
blanchet@38023
   412
          | CombApp _ => raise Fail "impossible \"CombApp\""
blanchet@38023
   413
        val t = ATerm (x, map fo_term_for_combtyp ty_args @
blanchet@38023
   414
                          map (aux false) args)
blanchet@38023
   415
    in
blanchet@38023
   416
      if full_types then wrap_type (fo_term_for_combtyp (combtyp_of u)) t else t
blanchet@38023
   417
    end
blanchet@38023
   418
  in aux true end
blanchet@38023
   419
blanchet@38023
   420
fun formula_for_combformula full_types =
blanchet@38023
   421
  let
blanchet@38023
   422
    fun aux (AQuant (q, xs, phi)) = AQuant (q, xs, aux phi)
blanchet@38023
   423
      | aux (AConn (c, phis)) = AConn (c, map aux phis)
blanchet@38034
   424
      | aux (AAtom tm) = AAtom (fo_term_for_combterm full_types tm)
blanchet@38023
   425
  in aux end
blanchet@38023
   426
blanchet@38023
   427
fun formula_for_axiom full_types (FOLFormula {combformula, ctypes_sorts, ...}) =
blanchet@38023
   428
  mk_ahorn (map (formula_for_fo_literal o fo_literal_for_type_literal)
blanchet@38023
   429
                (type_literals_for_types ctypes_sorts))
blanchet@38023
   430
           (formula_for_combformula full_types combformula)
blanchet@38023
   431
blanchet@38023
   432
fun problem_line_for_axiom full_types
blanchet@38023
   433
        (formula as FOLFormula {formula_name, kind, ...}) =
blanchet@38023
   434
  Fof (axiom_prefix ^ ascii_of formula_name, kind,
blanchet@38023
   435
       formula_for_axiom full_types formula)
blanchet@38023
   436
blanchet@38023
   437
fun problem_line_for_class_rel_clause
blanchet@38023
   438
        (ClassRelClause {axiom_name, subclass, superclass, ...}) =
blanchet@38023
   439
  let val ty_arg = ATerm (("T", "T"), []) in
blanchet@38023
   440
    Fof (ascii_of axiom_name, Axiom,
blanchet@38034
   441
         AConn (AImplies, [AAtom (ATerm (subclass, [ty_arg])),
blanchet@38034
   442
                           AAtom (ATerm (superclass, [ty_arg]))]))
blanchet@38023
   443
  end
blanchet@38023
   444
blanchet@38023
   445
fun fo_literal_for_arity_literal (TConsLit (c, t, args)) =
blanchet@38023
   446
    (true, ATerm (c, [ATerm (t, map (fn arg => ATerm (arg, [])) args)]))
blanchet@38023
   447
  | fo_literal_for_arity_literal (TVarLit (c, sort)) =
blanchet@38023
   448
    (false, ATerm (c, [ATerm (sort, [])]))
blanchet@38023
   449
blanchet@38023
   450
fun problem_line_for_arity_clause
blanchet@38023
   451
        (ArityClause {axiom_name, conclLit, premLits, ...}) =
blanchet@38023
   452
  Fof (arity_clause_prefix ^ ascii_of axiom_name, Axiom,
blanchet@38023
   453
       mk_ahorn (map (formula_for_fo_literal o apfst not
blanchet@38023
   454
                      o fo_literal_for_arity_literal) premLits)
blanchet@38023
   455
                (formula_for_fo_literal
blanchet@38023
   456
                     (fo_literal_for_arity_literal conclLit)))
blanchet@38023
   457
blanchet@38023
   458
fun problem_line_for_conjecture full_types
blanchet@38023
   459
        (FOLFormula {formula_name, kind, combformula, ...}) =
blanchet@38023
   460
  Fof (conjecture_prefix ^ formula_name, kind,
blanchet@38023
   461
       formula_for_combformula full_types combformula)
blanchet@38023
   462
blanchet@38023
   463
fun free_type_literals_for_conjecture (FOLFormula {ctypes_sorts, ...}) =
blanchet@38023
   464
  map fo_literal_for_type_literal (type_literals_for_types ctypes_sorts)
blanchet@38023
   465
blanchet@38023
   466
fun problem_line_for_free_type lit =
blanchet@38023
   467
  Fof (tfrees_name, Conjecture, mk_anot (formula_for_fo_literal lit))
blanchet@38023
   468
fun problem_lines_for_free_types conjectures =
blanchet@38023
   469
  let
blanchet@38023
   470
    val litss = map free_type_literals_for_conjecture conjectures
blanchet@38023
   471
    val lits = fold (union (op =)) litss []
blanchet@38023
   472
  in map problem_line_for_free_type lits end
blanchet@38023
   473
blanchet@38023
   474
(** "hBOOL" and "hAPP" **)
blanchet@38023
   475
blanchet@38023
   476
type const_info = {min_arity: int, max_arity: int, sub_level: bool}
blanchet@38023
   477
blanchet@38023
   478
fun consider_term top_level (ATerm ((s, _), ts)) =
blanchet@38023
   479
  (if is_tptp_variable s then
blanchet@38023
   480
     I
blanchet@38023
   481
   else
blanchet@38023
   482
     let val n = length ts in
blanchet@38023
   483
       Symtab.map_default
blanchet@38023
   484
           (s, {min_arity = n, max_arity = 0, sub_level = false})
blanchet@38023
   485
           (fn {min_arity, max_arity, sub_level} =>
blanchet@38023
   486
               {min_arity = Int.min (n, min_arity),
blanchet@38023
   487
                max_arity = Int.max (n, max_arity),
blanchet@38023
   488
                sub_level = sub_level orelse not top_level})
blanchet@38023
   489
     end)
blanchet@38023
   490
  #> fold (consider_term (top_level andalso s = type_wrapper_name)) ts
blanchet@38023
   491
fun consider_formula (AQuant (_, _, phi)) = consider_formula phi
blanchet@38023
   492
  | consider_formula (AConn (_, phis)) = fold consider_formula phis
blanchet@38034
   493
  | consider_formula (AAtom tm) = consider_term true tm
blanchet@38023
   494
blanchet@38023
   495
fun consider_problem_line (Fof (_, _, phi)) = consider_formula phi
blanchet@38023
   496
fun consider_problem problem = fold (fold consider_problem_line o snd) problem
blanchet@38023
   497
blanchet@38023
   498
fun const_table_for_problem explicit_apply problem =
blanchet@38023
   499
  if explicit_apply then NONE
blanchet@38023
   500
  else SOME (Symtab.empty |> consider_problem problem)
blanchet@38023
   501
blanchet@38023
   502
val tc_fun = make_fixed_type_const @{type_name fun}
blanchet@38023
   503
blanchet@38023
   504
fun min_arity_of thy full_types NONE s =
blanchet@38023
   505
    (if s = "equal" orelse s = type_wrapper_name orelse
blanchet@38023
   506
        String.isPrefix type_const_prefix s orelse
blanchet@38023
   507
        String.isPrefix class_prefix s then
blanchet@38023
   508
       16383 (* large number *)
blanchet@38023
   509
     else if full_types then
blanchet@38023
   510
       0
blanchet@38023
   511
     else case strip_prefix_and_undo_ascii const_prefix s of
blanchet@38023
   512
       SOME s' => num_type_args thy (invert_const s')
blanchet@38023
   513
     | NONE => 0)
blanchet@38023
   514
  | min_arity_of _ _ (SOME the_const_tab) s =
blanchet@38023
   515
    case Symtab.lookup the_const_tab s of
blanchet@38023
   516
      SOME ({min_arity, ...} : const_info) => min_arity
blanchet@38023
   517
    | NONE => 0
blanchet@38023
   518
blanchet@38023
   519
fun full_type_of (ATerm ((s, _), [ty, _])) =
blanchet@38023
   520
    if s = type_wrapper_name then ty else raise Fail "expected type wrapper"
blanchet@38023
   521
  | full_type_of _ = raise Fail "expected type wrapper"
blanchet@38023
   522
blanchet@38023
   523
fun list_hAPP_rev _ t1 [] = t1
blanchet@38023
   524
  | list_hAPP_rev NONE t1 (t2 :: ts2) =
blanchet@38023
   525
    ATerm (`I "hAPP", [list_hAPP_rev NONE t1 ts2, t2])
blanchet@38023
   526
  | list_hAPP_rev (SOME ty) t1 (t2 :: ts2) =
blanchet@38023
   527
    let val ty' = ATerm (`make_fixed_type_const @{type_name fun},
blanchet@38023
   528
                         [full_type_of t2, ty]) in
blanchet@38023
   529
      ATerm (`I "hAPP", [wrap_type ty' (list_hAPP_rev (SOME ty') t1 ts2), t2])
blanchet@38023
   530
    end
blanchet@38023
   531
blanchet@38023
   532
fun repair_applications_in_term thy full_types const_tab =
blanchet@38023
   533
  let
blanchet@38023
   534
    fun aux opt_ty (ATerm (name as (s, _), ts)) =
blanchet@38023
   535
      if s = type_wrapper_name then
blanchet@38023
   536
        case ts of
blanchet@38023
   537
          [t1, t2] => ATerm (name, [aux NONE t1, aux (SOME t1) t2])
blanchet@38023
   538
        | _ => raise Fail "malformed type wrapper"
blanchet@38023
   539
      else
blanchet@38023
   540
        let
blanchet@38023
   541
          val ts = map (aux NONE) ts
blanchet@38023
   542
          val (ts1, ts2) = chop (min_arity_of thy full_types const_tab s) ts
blanchet@38023
   543
        in list_hAPP_rev opt_ty (ATerm (name, ts1)) (rev ts2) end
blanchet@38023
   544
  in aux NONE end
blanchet@38023
   545
blanchet@38023
   546
fun boolify t = ATerm (`I "hBOOL", [t])
blanchet@38023
   547
blanchet@38023
   548
(* True if the constant ever appears outside of the top-level position in
blanchet@38023
   549
   literals, or if it appears with different arities (e.g., because of different
blanchet@38023
   550
   type instantiations). If false, the constant always receives all of its
blanchet@38023
   551
   arguments and is used as a predicate. *)
blanchet@38023
   552
fun is_predicate NONE s =
blanchet@38023
   553
    s = "equal" orelse String.isPrefix type_const_prefix s orelse
blanchet@38023
   554
    String.isPrefix class_prefix s
blanchet@38023
   555
  | is_predicate (SOME the_const_tab) s =
blanchet@38023
   556
    case Symtab.lookup the_const_tab s of
blanchet@38023
   557
      SOME {min_arity, max_arity, sub_level} =>
blanchet@38023
   558
      not sub_level andalso min_arity = max_arity
blanchet@38023
   559
    | NONE => false
blanchet@38023
   560
blanchet@38023
   561
fun repair_predicates_in_term const_tab (t as ATerm ((s, _), ts)) =
blanchet@38023
   562
  if s = type_wrapper_name then
blanchet@38023
   563
    case ts of
blanchet@38023
   564
      [_, t' as ATerm ((s', _), _)] =>
blanchet@38023
   565
      if is_predicate const_tab s' then t' else boolify t
blanchet@38023
   566
    | _ => raise Fail "malformed type wrapper"
blanchet@38023
   567
  else
blanchet@38023
   568
    t |> not (is_predicate const_tab s) ? boolify
blanchet@38023
   569
blanchet@38023
   570
fun close_universally phi =
blanchet@38023
   571
  let
blanchet@38023
   572
    fun term_vars bounds (ATerm (name as (s, _), tms)) =
blanchet@38023
   573
        (is_tptp_variable s andalso not (member (op =) bounds name))
blanchet@38023
   574
          ? insert (op =) name
blanchet@38023
   575
        #> fold (term_vars bounds) tms
blanchet@38023
   576
    fun formula_vars bounds (AQuant (q, xs, phi)) =
blanchet@38023
   577
        formula_vars (xs @ bounds) phi
blanchet@38023
   578
      | formula_vars bounds (AConn (_, phis)) = fold (formula_vars bounds) phis
blanchet@38034
   579
      | formula_vars bounds (AAtom tm) = term_vars bounds tm
blanchet@38023
   580
  in
blanchet@38023
   581
    case formula_vars [] phi [] of [] => phi | xs => AQuant (AForall, xs, phi)
blanchet@38023
   582
  end
blanchet@38023
   583
blanchet@38023
   584
fun repair_formula thy explicit_forall full_types const_tab =
blanchet@38023
   585
  let
blanchet@38023
   586
    fun aux (AQuant (q, xs, phi)) = AQuant (q, xs, aux phi)
blanchet@38023
   587
      | aux (AConn (c, phis)) = AConn (c, map aux phis)
blanchet@38034
   588
      | aux (AAtom tm) =
blanchet@38034
   589
        AAtom (tm |> repair_applications_in_term thy full_types const_tab
blanchet@38023
   590
                  |> repair_predicates_in_term const_tab)
blanchet@38023
   591
  in aux #> explicit_forall ? close_universally end
blanchet@38023
   592
blanchet@38023
   593
fun repair_problem_line thy explicit_forall full_types const_tab
blanchet@38023
   594
                        (Fof (ident, kind, phi)) =
blanchet@38023
   595
  Fof (ident, kind, repair_formula thy explicit_forall full_types const_tab phi)
blanchet@38023
   596
fun repair_problem_with_const_table thy =
blanchet@38023
   597
  map o apsnd o map ooo repair_problem_line thy
blanchet@38023
   598
blanchet@38023
   599
fun repair_problem thy explicit_forall full_types explicit_apply problem =
blanchet@38023
   600
  repair_problem_with_const_table thy explicit_forall full_types
blanchet@38023
   601
      (const_table_for_problem explicit_apply problem) problem
blanchet@38023
   602
blanchet@38023
   603
fun write_tptp_file thy readable_names explicit_forall full_types explicit_apply
blanchet@38085
   604
                    file (conjectures, axioms, helper_facts, class_rel_clauses,
blanchet@38085
   605
                          arity_clauses) =
blanchet@38023
   606
  let
blanchet@38084
   607
    val axiom_lines = map (problem_line_for_axiom full_types) axioms
blanchet@38023
   608
    val class_rel_lines =
blanchet@38023
   609
      map problem_line_for_class_rel_clause class_rel_clauses
blanchet@38023
   610
    val arity_lines = map problem_line_for_arity_clause arity_clauses
blanchet@38085
   611
    val helper_lines = map (problem_line_for_axiom full_types) helper_facts
blanchet@38023
   612
    val conjecture_lines =
blanchet@38023
   613
      map (problem_line_for_conjecture full_types) conjectures
blanchet@38023
   614
    val tfree_lines = problem_lines_for_free_types conjectures
blanchet@38023
   615
    (* Reordering these might or might not confuse the proof reconstruction
blanchet@38023
   616
       code or the SPASS Flotter hack. *)
blanchet@38023
   617
    val problem =
blanchet@38023
   618
      [("Relevant facts", axiom_lines),
blanchet@38023
   619
       ("Class relationships", class_rel_lines),
blanchet@38023
   620
       ("Arity declarations", arity_lines),
blanchet@38023
   621
       ("Helper facts", helper_lines),
blanchet@38023
   622
       ("Conjectures", conjecture_lines),
blanchet@38023
   623
       ("Type variables", tfree_lines)]
blanchet@38023
   624
      |> repair_problem thy explicit_forall full_types explicit_apply
blanchet@38023
   625
    val (problem, pool) = nice_tptp_problem readable_names problem
blanchet@38023
   626
    val conjecture_offset =
blanchet@38023
   627
      length axiom_lines + length class_rel_lines + length arity_lines
blanchet@38023
   628
      + length helper_lines
blanchet@38023
   629
    val _ = File.write_list file (strings_for_tptp_problem problem)
blanchet@38023
   630
  in
blanchet@38023
   631
    (case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
blanchet@38023
   632
     conjecture_offset)
blanchet@38023
   633
  end
blanchet@38023
   634
blanchet@38023
   635
fun extract_clause_sequence output =
blanchet@38023
   636
  let
blanchet@38023
   637
    val tokens_of = String.tokens (not o Char.isAlphaNum)
blanchet@38023
   638
    fun extract_num ("clause" :: (ss as _ :: _)) =
blanchet@38023
   639
    Int.fromString (List.last ss)
blanchet@38023
   640
      | extract_num _ = NONE
blanchet@38023
   641
  in output |> split_lines |> map_filter (extract_num o tokens_of) end
blanchet@38023
   642
blanchet@38023
   643
val set_ClauseFormulaRelationN = "set_ClauseFormulaRelation"
blanchet@38023
   644
blanchet@38023
   645
val parse_clause_formula_pair =
blanchet@38023
   646
  $$ "(" |-- scan_integer --| $$ "," -- Symbol.scan_id --| $$ ")"
blanchet@38023
   647
  --| Scan.option ($$ ",")
blanchet@38023
   648
val parse_clause_formula_relation =
blanchet@38023
   649
  Scan.this_string set_ClauseFormulaRelationN |-- $$ "("
blanchet@38023
   650
  |-- Scan.repeat parse_clause_formula_pair
blanchet@38023
   651
val extract_clause_formula_relation =
blanchet@38023
   652
  Substring.full
blanchet@38023
   653
  #> Substring.position set_ClauseFormulaRelationN
blanchet@38023
   654
  #> snd #> Substring.string #> strip_spaces #> explode
blanchet@38023
   655
  #> parse_clause_formula_relation #> fst
blanchet@38023
   656
blanchet@38023
   657
fun repair_conjecture_shape_and_theorem_names output conjecture_shape
blanchet@38023
   658
                                              thm_names =
blanchet@38023
   659
  if String.isSubstring set_ClauseFormulaRelationN output then
blanchet@38023
   660
    (* This is a hack required for keeping track of axioms after they have been
blanchet@38023
   661
       clausified by SPASS's Flotter tool. The "SPASS_TPTP" script is also part
blanchet@38023
   662
       of this hack. *)
blanchet@38023
   663
    let
blanchet@38040
   664
      val j0 = hd (hd conjecture_shape)
blanchet@38023
   665
      val seq = extract_clause_sequence output
blanchet@38023
   666
      val name_map = extract_clause_formula_relation output
blanchet@38023
   667
      fun renumber_conjecture j =
blanchet@38023
   668
        AList.find (op =) name_map (conjecture_prefix ^ Int.toString (j - j0))
blanchet@38040
   669
        |> map (fn s => find_index (curry (op =) s) seq + 1)
blanchet@38023
   670
    in
blanchet@38040
   671
      (conjecture_shape |> map (maps renumber_conjecture),
blanchet@38023
   672
       seq |> map (the o AList.lookup (op =) name_map)
blanchet@38023
   673
           |> map (fn s => case try (unprefix axiom_prefix) s of
blanchet@38023
   674
                             SOME s' => undo_ascii_of s'
blanchet@38023
   675
                           | NONE => "")
blanchet@38023
   676
           |> Vector.fromList)
blanchet@38023
   677
    end
blanchet@38023
   678
  else
blanchet@38023
   679
    (conjecture_shape, thm_names)
blanchet@38023
   680
blanchet@38023
   681
blanchet@38023
   682
(* generic TPTP-based provers *)
blanchet@38023
   683
blanchet@38023
   684
fun prover_fun name
blanchet@38092
   685
        {exec, required_execs, arguments, proof_delims, known_failures,
blanchet@38092
   686
         max_new_relevant_facts_per_iter, prefers_theory_relevant,
blanchet@38092
   687
         explicit_forall}
blanchet@38023
   688
        ({debug, overlord, full_types, explicit_apply, relevance_threshold,
blanchet@38023
   689
          relevance_convergence, theory_relevant, defs_relevant, isar_proof,
blanchet@38100
   690
          isar_shrink_factor, timeout, ...} : params)
blanchet@38100
   691
        minimize_command
blanchet@38084
   692
        ({subgoal, goal, relevance_override, axioms} : problem) =
blanchet@38023
   693
  let
blanchet@38023
   694
    val (ctxt, (_, th)) = goal;
blanchet@38023
   695
    val thy = ProofContext.theory_of ctxt
blanchet@38023
   696
    (* ### FIXME: (1) preprocessing for "if" etc. *)
blanchet@38023
   697
    val (params, hyp_ts, concl_t) = strip_subgoal th subgoal
blanchet@38084
   698
    val the_axioms =
blanchet@38084
   699
      case axioms of
blanchet@38083
   700
        SOME axioms => axioms
blanchet@38023
   701
      | NONE => relevant_facts full_types relevance_threshold
blanchet@38023
   702
                    relevance_convergence defs_relevant
blanchet@38023
   703
                    max_new_relevant_facts_per_iter
blanchet@38023
   704
                    (the_default prefers_theory_relevant theory_relevant)
blanchet@38023
   705
                    relevance_override goal hyp_ts concl_t
blanchet@38085
   706
    val (internal_thm_names, formulas) =
blanchet@38085
   707
      prepare_formulas ctxt full_types hyp_ts concl_t the_axioms
blanchet@38023
   708
blanchet@38023
   709
    (* path to unique problem file *)
blanchet@38023
   710
    val the_dest_dir = if overlord then getenv "ISABELLE_HOME_USER"
blanchet@38023
   711
                       else Config.get ctxt dest_dir;
blanchet@38023
   712
    val the_problem_prefix = Config.get ctxt problem_prefix;
blanchet@38023
   713
    fun prob_pathname nr =
blanchet@38023
   714
      let
blanchet@38023
   715
        val probfile =
blanchet@38023
   716
          Path.basic ((if overlord then "prob_" ^ name
blanchet@38023
   717
                       else the_problem_prefix ^ serial_string ())
blanchet@38023
   718
                      ^ "_" ^ string_of_int nr)
blanchet@38023
   719
      in
blanchet@38023
   720
        if the_dest_dir = "" then File.tmp_path probfile
blanchet@38023
   721
        else if File.exists (Path.explode the_dest_dir)
blanchet@38023
   722
        then Path.append (Path.explode the_dest_dir) probfile
blanchet@38023
   723
        else error ("No such directory: " ^ the_dest_dir ^ ".")
blanchet@38023
   724
      end;
blanchet@38023
   725
blanchet@38092
   726
    val command = Path.explode (getenv (fst exec) ^ "/" ^ snd exec)
blanchet@38023
   727
    (* write out problem file and call prover *)
blanchet@38023
   728
    fun command_line complete probfile =
blanchet@38023
   729
      let
blanchet@38023
   730
        val core = File.shell_path command ^ " " ^ arguments complete timeout ^
blanchet@38023
   731
                   " " ^ File.shell_path probfile
blanchet@38023
   732
      in
blanchet@38023
   733
        (if Config.get ctxt measure_runtime then
blanchet@38023
   734
           "TIMEFORMAT='%3U'; { time " ^ core ^ " ; }"
blanchet@38023
   735
         else
blanchet@38023
   736
           "exec " ^ core) ^ " 2>&1"
blanchet@38023
   737
      end
blanchet@38023
   738
    fun split_time s =
blanchet@38023
   739
      let
blanchet@38023
   740
        val split = String.tokens (fn c => str c = "\n");
blanchet@38023
   741
        val (output, t) = s |> split |> split_last |> apfst cat_lines;
blanchet@38023
   742
        fun as_num f = f >> (fst o read_int);
blanchet@38023
   743
        val num = as_num (Scan.many1 Symbol.is_ascii_digit);
blanchet@38023
   744
        val digit = Scan.one Symbol.is_ascii_digit;
blanchet@38023
   745
        val num3 = as_num (digit ::: digit ::: (digit >> single));
blanchet@38023
   746
        val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b);
blanchet@38023
   747
        val as_time = the_default 0 o Scan.read Symbol.stopper time o explode;
blanchet@38023
   748
      in (output, as_time t) end;
blanchet@38023
   749
    fun run_on probfile =
blanchet@38092
   750
      case filter (curry (op =) "" o getenv o fst) (exec :: required_execs) of
blanchet@38032
   751
        (home_var, _) :: _ =>
blanchet@38023
   752
        error ("The environment variable " ^ quote home_var ^ " is not set.")
blanchet@38032
   753
      | [] =>
blanchet@38032
   754
        if File.exists command then
blanchet@38032
   755
          let
blanchet@38032
   756
            fun do_run complete =
blanchet@38032
   757
              let
blanchet@38032
   758
                val command = command_line complete probfile
blanchet@38032
   759
                val ((output, msecs), res_code) =
blanchet@38032
   760
                  bash_output command
blanchet@38032
   761
                  |>> (if overlord then
blanchet@38032
   762
                         prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n")
blanchet@38032
   763
                       else
blanchet@38032
   764
                         I)
blanchet@38032
   765
                  |>> (if Config.get ctxt measure_runtime then split_time
blanchet@38032
   766
                       else rpair 0)
blanchet@38032
   767
                val (proof, outcome) =
blanchet@38032
   768
                  extract_proof_and_outcome complete res_code proof_delims
blanchet@38032
   769
                                            known_failures output
blanchet@38032
   770
              in (output, msecs, proof, outcome) end
blanchet@38032
   771
            val readable_names = debug andalso overlord
blanchet@38032
   772
            val (pool, conjecture_offset) =
blanchet@38032
   773
              write_tptp_file thy readable_names explicit_forall full_types
blanchet@38085
   774
                              explicit_apply probfile formulas
blanchet@38032
   775
            val conjecture_shape =
blanchet@38032
   776
              conjecture_offset + 1 upto conjecture_offset + length hyp_ts + 1
blanchet@38040
   777
              |> map single
blanchet@38032
   778
            val result =
blanchet@38032
   779
              do_run false
blanchet@38032
   780
              |> (fn (_, msecs0, _, SOME _) =>
blanchet@38032
   781
                     do_run true
blanchet@38032
   782
                     |> (fn (output, msecs, proof, outcome) =>
blanchet@38032
   783
                            (output, msecs0 + msecs, proof, outcome))
blanchet@38032
   784
                   | result => result)
blanchet@38032
   785
          in ((pool, conjecture_shape), result) end
blanchet@38032
   786
        else
blanchet@38032
   787
          error ("Bad executable: " ^ Path.implode command ^ ".")
blanchet@38023
   788
blanchet@38023
   789
    (* If the problem file has not been exported, remove it; otherwise, export
blanchet@38023
   790
       the proof file too. *)
blanchet@38023
   791
    fun cleanup probfile =
blanchet@38023
   792
      if the_dest_dir = "" then try File.rm probfile else NONE
blanchet@38023
   793
    fun export probfile (_, (output, _, _, _)) =
blanchet@38023
   794
      if the_dest_dir = "" then
blanchet@38023
   795
        ()
blanchet@38023
   796
      else
blanchet@38023
   797
        File.write (Path.explode (Path.implode probfile ^ "_proof")) output
blanchet@38023
   798
blanchet@38023
   799
    val ((pool, conjecture_shape), (output, msecs, proof, outcome)) =
blanchet@38023
   800
      with_path cleanup export run_on (prob_pathname subgoal)
blanchet@38023
   801
    val (conjecture_shape, internal_thm_names) =
blanchet@38023
   802
      repair_conjecture_shape_and_theorem_names output conjecture_shape
blanchet@38023
   803
                                                internal_thm_names
blanchet@38023
   804
blanchet@38023
   805
    val (message, used_thm_names) =
blanchet@38023
   806
      case outcome of
blanchet@38023
   807
        NONE =>
blanchet@38023
   808
        proof_text isar_proof
blanchet@38023
   809
            (pool, debug, isar_shrink_factor, ctxt, conjecture_shape)
blanchet@38023
   810
            (full_types, minimize_command, proof, internal_thm_names, th,
blanchet@38023
   811
             subgoal)
blanchet@38023
   812
      | SOME failure => (string_for_failure failure ^ "\n", [])
blanchet@38023
   813
  in
blanchet@38023
   814
    {outcome = outcome, message = message, pool = pool,
blanchet@38023
   815
     used_thm_names = used_thm_names, atp_run_time_in_msecs = msecs,
blanchet@38023
   816
     output = output, proof = proof, internal_thm_names = internal_thm_names,
blanchet@38083
   817
     conjecture_shape = conjecture_shape}
blanchet@38023
   818
  end
blanchet@38023
   819
blanchet@38023
   820
fun get_prover_fun thy name = prover_fun name (get_prover thy name)
blanchet@38023
   821
blanchet@37584
   822
fun start_prover_thread (params as {verbose, full_types, timeout, ...}) i n
blanchet@37584
   823
                        relevance_override minimize_command proof_state name =
blanchet@36379
   824
  let
blanchet@38023
   825
    val thy = Proof.theory_of proof_state
blanchet@37584
   826
    val birth_time = Time.now ()
blanchet@37584
   827
    val death_time = Time.+ (birth_time, timeout)
blanchet@38023
   828
    val prover = get_prover_fun thy name
blanchet@36379
   829
    val {context = ctxt, facts, goal} = Proof.goal proof_state;
blanchet@36379
   830
    val desc =
blanchet@36379
   831
      "ATP " ^ quote name ^ " for subgoal " ^ string_of_int i ^ ":\n" ^
blanchet@36392
   832
      Syntax.string_of_term ctxt (Thm.term_of (Thm.cprem_of goal i));
blanchet@37584
   833
  in
blanchet@37585
   834
    Async_Manager.launch das_Tool verbose birth_time death_time desc
blanchet@37584
   835
        (fn () =>
blanchet@37584
   836
            let
blanchet@37584
   837
              val problem =
blanchet@37584
   838
                {subgoal = i, goal = (ctxt, (facts, goal)),
blanchet@38084
   839
                 relevance_override = relevance_override, axioms = NONE}
blanchet@37584
   840
            in
blanchet@38100
   841
              prover params (minimize_command name) problem |> #message
blanchet@37994
   842
              handle ERROR message => "Error: " ^ message ^ "\n"
blanchet@37584
   843
            end)
blanchet@37584
   844
  end
wenzelm@28582
   845
blanchet@38044
   846
fun run_sledgehammer {atps = [], ...} _ _ _ _ = error "No ATP is set."
blanchet@38044
   847
  | run_sledgehammer (params as {atps, ...}) i relevance_override
blanchet@38044
   848
                     minimize_command state =
blanchet@38044
   849
    case subgoal_count state of
blanchet@38044
   850
      0 => priority "No subgoal!"
blanchet@38044
   851
    | n =>
blanchet@38044
   852
      let
blanchet@38044
   853
        val _ = kill_atps ()
blanchet@38044
   854
        val _ = priority "Sledgehammering..."
blanchet@38044
   855
        val _ = app (start_prover_thread params i n relevance_override
blanchet@38044
   856
                                         minimize_command state) atps
blanchet@38044
   857
      in () end
blanchet@38044
   858
blanchet@38023
   859
val setup =
blanchet@38023
   860
  dest_dir_setup
blanchet@38023
   861
  #> problem_prefix_setup
blanchet@38023
   862
  #> measure_runtime_setup
blanchet@38023
   863
wenzelm@28582
   864
end;