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