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