src/HOL/Tools/SMT2/smt2_solver.ML
author blanchet
Fri Mar 14 11:52:03 2014 +0100 (2014-03-14)
changeset 56131 836b47c6531d
parent 56128 c106ac2ff76d
child 56132 64eeda68e693
permissions -rw-r--r--
tuning
blanchet@56078
     1
(*  Title:      HOL/Tools/SMT2/smt2_solver.ML
blanchet@56078
     2
    Author:     Sascha Boehme, TU Muenchen
blanchet@56078
     3
blanchet@56078
     4
SMT solvers registry and SMT tactic.
blanchet@56078
     5
*)
blanchet@56078
     6
blanchet@56078
     7
signature SMT2_SOLVER =
blanchet@56078
     8
sig
blanchet@56078
     9
  (*configuration*)
blanchet@56078
    10
  datatype outcome = Unsat | Sat | Unknown
blanchet@56078
    11
  type solver_config = {
blanchet@56078
    12
    name: string,
blanchet@56090
    13
    class: Proof.context -> SMT2_Util.class,
blanchet@56078
    14
    avail: unit -> bool,
blanchet@56078
    15
    command: unit -> string list,
blanchet@56078
    16
    options: Proof.context -> string list,
blanchet@56078
    17
    default_max_relevant: int,
blanchet@56125
    18
    can_filter: bool,
blanchet@56078
    19
    outcome: string -> string list -> outcome * string list,
blanchet@56078
    20
    cex_parser: (Proof.context -> SMT2_Translate.replay_data -> string list ->
blanchet@56078
    21
      term list * term list) option,
blanchet@56083
    22
    replay: (Proof.context -> SMT2_Translate.replay_data -> string list ->
blanchet@56125
    23
      ((int * (int * thm)) list * Z3_New_Proof.z3_step list) * thm) option}
blanchet@56078
    24
blanchet@56078
    25
  (*registry*)
blanchet@56078
    26
  val add_solver: solver_config -> theory -> theory
blanchet@56078
    27
  val solver_name_of: Proof.context -> string
blanchet@56078
    28
  val available_solvers_of: Proof.context -> string list
blanchet@56078
    29
  val default_max_relevant: Proof.context -> string -> int
blanchet@56078
    30
blanchet@56078
    31
  (*filter*)
blanchet@56104
    32
  val smt2_filter: Proof.context -> thm -> ('a * (int option * thm)) list -> int -> Time.time ->
blanchet@56128
    33
    {outcome: SMT2_Failure.failure option, rewrite_rules: thm list, conjecture_id: int,
blanchet@56128
    34
     helper_ids: (int * thm) list, fact_ids: (int * ('a * thm)) list,
blanchet@56128
    35
     z3_proof: Z3_New_Proof.z3_step list}
blanchet@56078
    36
blanchet@56078
    37
  (*tactic*)
blanchet@56078
    38
  val smt2_tac: Proof.context -> thm list -> int -> tactic
blanchet@56078
    39
  val smt2_tac': Proof.context -> thm list -> int -> tactic
blanchet@56078
    40
end
blanchet@56078
    41
blanchet@56078
    42
structure SMT2_Solver: SMT2_SOLVER =
blanchet@56078
    43
struct
blanchet@56078
    44
blanchet@56078
    45
blanchet@56078
    46
(* interface to external solvers *)
blanchet@56078
    47
blanchet@56078
    48
local
blanchet@56078
    49
blanchet@56078
    50
fun make_cmd command options problem_path proof_path = space_implode " " (
blanchet@56078
    51
  "(exec 2>&1;" :: map File.shell_quote (command @ options) @
blanchet@56078
    52
  [File.shell_path problem_path, ")", ">", File.shell_path proof_path])
blanchet@56078
    53
blanchet@56078
    54
fun trace_and ctxt msg f x =
blanchet@56078
    55
  let val _ = SMT2_Config.trace_msg ctxt (fn () => msg) ()
blanchet@56078
    56
  in f x end
blanchet@56078
    57
blanchet@56078
    58
fun run ctxt name mk_cmd input =
blanchet@56078
    59
  (case SMT2_Config.certificates_of ctxt of
blanchet@56078
    60
    NONE =>
blanchet@56078
    61
      if not (SMT2_Config.is_available ctxt name) then
blanchet@56131
    62
        error ("The SMT solver " ^ quote name ^ " is not installed")
blanchet@56078
    63
      else if Config.get ctxt SMT2_Config.debug_files = "" then
blanchet@56131
    64
        trace_and ctxt ("Invoking SMT solver " ^ quote name ^ " ...") (Cache_IO.run mk_cmd) input
blanchet@56078
    65
      else
blanchet@56078
    66
        let
blanchet@56078
    67
          val base_path = Path.explode (Config.get ctxt SMT2_Config.debug_files)
blanchet@56078
    68
          val in_path = Path.ext "smt2_in" base_path
blanchet@56078
    69
          val out_path = Path.ext "smt2_out" base_path
blanchet@56078
    70
        in Cache_IO.raw_run mk_cmd input in_path out_path end
blanchet@56078
    71
  | SOME certs =>
blanchet@56078
    72
      (case Cache_IO.lookup certs input of
blanchet@56078
    73
        (NONE, key) =>
blanchet@56078
    74
          if Config.get ctxt SMT2_Config.read_only_certificates then
blanchet@56078
    75
            error ("Bad certificate cache: missing certificate")
blanchet@56078
    76
          else
blanchet@56078
    77
            Cache_IO.run_and_cache certs key mk_cmd input
blanchet@56078
    78
      | (SOME output, _) =>
blanchet@56078
    79
          trace_and ctxt ("Using cached certificate from " ^
blanchet@56078
    80
            File.shell_path (Cache_IO.cache_path_of certs) ^ " ...")
blanchet@56078
    81
            I output))
blanchet@56078
    82
blanchet@56087
    83
(* Z3 returns 1 if "get-model" or "get-model" fails *)
blanchet@56087
    84
val normal_return_codes = [0, 1]
blanchet@56087
    85
blanchet@56078
    86
fun run_solver ctxt name mk_cmd input =
blanchet@56078
    87
  let
blanchet@56087
    88
    fun pretty tag ls = Pretty.string_of (Pretty.big_list tag (map Pretty.str ls))
blanchet@56078
    89
blanchet@56078
    90
    val _ = SMT2_Config.trace_msg ctxt (pretty "Problem:" o split_lines) input
blanchet@56078
    91
blanchet@56078
    92
    val {redirected_output=res, output=err, return_code} =
blanchet@56078
    93
      SMT2_Config.with_timeout ctxt (run ctxt name mk_cmd) input
blanchet@56078
    94
    val _ = SMT2_Config.trace_msg ctxt (pretty "Solver:") err
blanchet@56078
    95
blanchet@56078
    96
    val output = fst (take_suffix (equal "") res)
blanchet@56078
    97
    val _ = SMT2_Config.trace_msg ctxt (pretty "Result:") output
blanchet@56078
    98
blanchet@56087
    99
    val _ = member (op =) normal_return_codes return_code orelse
blanchet@56078
   100
      raise SMT2_Failure.SMT (SMT2_Failure.Abnormal_Termination return_code)
blanchet@56078
   101
  in output end
blanchet@56078
   102
blanchet@56078
   103
fun trace_assms ctxt =
blanchet@56078
   104
  SMT2_Config.trace_msg ctxt (Pretty.string_of o
blanchet@56078
   105
    Pretty.big_list "Assertions:" o map (Display.pretty_thm ctxt o snd))
blanchet@56078
   106
blanchet@56078
   107
fun trace_replay_data ({context=ctxt, typs, terms, ...} : SMT2_Translate.replay_data) =
blanchet@56078
   108
  let
blanchet@56078
   109
    fun pretty_eq n p = Pretty.block [Pretty.str n, Pretty.str " = ", p]
blanchet@56078
   110
    fun p_typ (n, T) = pretty_eq n (Syntax.pretty_typ ctxt T)
blanchet@56078
   111
    fun p_term (n, t) = pretty_eq n (Syntax.pretty_term ctxt t)
blanchet@56078
   112
  in
blanchet@56078
   113
    SMT2_Config.trace_msg ctxt (fn () =>
blanchet@56078
   114
      Pretty.string_of (Pretty.big_list "Names:" [
blanchet@56078
   115
        Pretty.big_list "sorts:" (map p_typ (Symtab.dest typs)),
blanchet@56078
   116
        Pretty.big_list "functions:" (map p_term (Symtab.dest terms))])) ()
blanchet@56078
   117
  end
blanchet@56078
   118
blanchet@56078
   119
in
blanchet@56078
   120
blanchet@56078
   121
fun invoke name command ithms ctxt =
blanchet@56078
   122
  let
blanchet@56078
   123
    val options = SMT2_Config.solver_options_of ctxt
blanchet@56078
   124
    val cmd = command ()
blanchet@56112
   125
    val comments = [space_implode " " options]
blanchet@56078
   126
blanchet@56078
   127
    val (str, replay_data as {context=ctxt', ...}) =
blanchet@56078
   128
      ithms
blanchet@56078
   129
      |> tap (trace_assms ctxt)
blanchet@56078
   130
      |> SMT2_Translate.translate ctxt comments
blanchet@56078
   131
      ||> tap trace_replay_data
blanchet@56078
   132
  in (run_solver ctxt' name (make_cmd cmd options) str, replay_data) end
blanchet@56078
   133
blanchet@56078
   134
end
blanchet@56078
   135
blanchet@56078
   136
blanchet@56078
   137
(* configuration *)
blanchet@56078
   138
blanchet@56078
   139
datatype outcome = Unsat | Sat | Unknown
blanchet@56078
   140
blanchet@56078
   141
type solver_config = {
blanchet@56078
   142
  name: string,
blanchet@56090
   143
  class: Proof.context -> SMT2_Util.class,
blanchet@56078
   144
  avail: unit -> bool,
blanchet@56078
   145
  command: unit -> string list,
blanchet@56078
   146
  options: Proof.context -> string list,
blanchet@56078
   147
  default_max_relevant: int,
blanchet@56125
   148
  can_filter: bool,
blanchet@56078
   149
  outcome: string -> string list -> outcome * string list,
blanchet@56078
   150
  cex_parser: (Proof.context -> SMT2_Translate.replay_data -> string list ->
blanchet@56078
   151
    term list * term list) option,
blanchet@56083
   152
  replay: (Proof.context -> SMT2_Translate.replay_data -> string list ->
blanchet@56125
   153
    ((int * (int * thm)) list * Z3_New_Proof.z3_step list) * thm) option}
blanchet@56078
   154
blanchet@56078
   155
blanchet@56106
   156
(* check well-sortedness *)
blanchet@56106
   157
blanchet@56106
   158
val has_topsort = Term.exists_type (Term.exists_subtype (fn
blanchet@56106
   159
    TFree (_, []) => true
blanchet@56106
   160
  | TVar (_, []) => true
blanchet@56106
   161
  | _ => false))
blanchet@56106
   162
blanchet@56106
   163
(* top sorts cause problems with atomization *)
blanchet@56106
   164
fun check_topsort ctxt thm =
blanchet@56106
   165
  if has_topsort (Thm.prop_of thm) then (SMT2_Normalize.drop_fact_warning ctxt thm; TrueI) else thm
blanchet@56106
   166
blanchet@56106
   167
blanchet@56078
   168
(* registry *)
blanchet@56078
   169
blanchet@56078
   170
type solver_info = {
blanchet@56078
   171
  command: unit -> string list,
blanchet@56078
   172
  default_max_relevant: int,
blanchet@56125
   173
  can_filter: bool,
blanchet@56125
   174
  finish: Proof.context -> SMT2_Translate.replay_data -> string list ->
blanchet@56125
   175
    ((int * (int * thm)) list * Z3_New_Proof.z3_step list) * thm}
blanchet@56078
   176
blanchet@56078
   177
structure Solvers = Generic_Data
blanchet@56078
   178
(
blanchet@56078
   179
  type T = solver_info Symtab.table
blanchet@56078
   180
  val empty = Symtab.empty
blanchet@56078
   181
  val extend = I
blanchet@56078
   182
  fun merge data = Symtab.merge (K true) data
blanchet@56078
   183
)
blanchet@56078
   184
blanchet@56078
   185
local
blanchet@56078
   186
  fun finish outcome cex_parser replay ocl outer_ctxt
blanchet@56125
   187
      (replay_data as {context=ctxt, ...} : SMT2_Translate.replay_data) output =
blanchet@56078
   188
    (case outcome output of
blanchet@56078
   189
      (Unsat, ls) =>
blanchet@56078
   190
        if not (Config.get ctxt SMT2_Config.oracle) andalso is_some replay
blanchet@56078
   191
        then the replay outer_ctxt replay_data ls
blanchet@56083
   192
        else (([], []), ocl ())
blanchet@56078
   193
    | (result, ls) =>
blanchet@56078
   194
        let
blanchet@56078
   195
          val (ts, us) =
blanchet@56078
   196
            (case cex_parser of SOME f => f ctxt replay_data ls | _ => ([], []))
blanchet@56083
   197
        in
blanchet@56078
   198
          raise SMT2_Failure.SMT (SMT2_Failure.Counterexample {
blanchet@56078
   199
            is_real_cex = (result = Sat),
blanchet@56078
   200
            free_constraints = ts,
blanchet@56078
   201
            const_defs = us})
blanchet@56078
   202
        end)
blanchet@56078
   203
blanchet@56078
   204
  val cfalse = Thm.cterm_of @{theory} (@{const Trueprop} $ @{const False})
blanchet@56078
   205
in
blanchet@56078
   206
blanchet@56125
   207
fun add_solver ({name, class, avail, command, options, default_max_relevant, can_filter,
blanchet@56125
   208
    outcome, cex_parser, replay} : solver_config) =
blanchet@56078
   209
  let
blanchet@56078
   210
    fun solver ocl = {
blanchet@56078
   211
      command = command,
blanchet@56078
   212
      default_max_relevant = default_max_relevant,
blanchet@56125
   213
      can_filter = can_filter,
blanchet@56125
   214
      finish = finish (outcome name) cex_parser replay ocl}
blanchet@56078
   215
blanchet@56078
   216
    val info = {name=name, class=class, avail=avail, options=options}
blanchet@56078
   217
  in
blanchet@56125
   218
    Thm.add_oracle (Binding.name name, K cfalse) #-> (fn (_, ocl) =>
blanchet@56078
   219
    Context.theory_map (Solvers.map (Symtab.update_new (name, solver ocl)))) #>
blanchet@56078
   220
    Context.theory_map (SMT2_Config.add_solver info)
blanchet@56078
   221
  end
blanchet@56078
   222
blanchet@56078
   223
end
blanchet@56078
   224
blanchet@56125
   225
fun get_info ctxt name = the (Symtab.lookup (Solvers.get (Context.Proof ctxt)) name)
blanchet@56078
   226
blanchet@56078
   227
val solver_name_of = SMT2_Config.solver_of
blanchet@56078
   228
blanchet@56078
   229
val available_solvers_of = SMT2_Config.available_solvers_of
blanchet@56078
   230
blanchet@56078
   231
fun name_and_info_of ctxt =
blanchet@56078
   232
  let val name = solver_name_of ctxt
blanchet@56078
   233
  in (name, get_info ctxt name) end
blanchet@56078
   234
blanchet@56106
   235
fun apply_solver ctxt wthms0 =
blanchet@56082
   236
  let
blanchet@56106
   237
    val wthms = map (apsnd (check_topsort ctxt)) wthms0
blanchet@56125
   238
    val (name, {command, finish, ...}) = name_and_info_of ctxt
blanchet@56125
   239
    val (output, replay_data) = invoke name command (SMT2_Normalize.normalize ctxt wthms) ctxt
blanchet@56128
   240
  in (finish ctxt replay_data output, replay_data) end
blanchet@56078
   241
blanchet@56078
   242
val default_max_relevant = #default_max_relevant oo get_info
blanchet@56125
   243
val can_filter = #can_filter o snd o name_and_info_of 
blanchet@56078
   244
blanchet@56078
   245
blanchet@56078
   246
(* filter *)
blanchet@56078
   247
blanchet@56106
   248
val no_id = ~1
blanchet@56078
   249
blanchet@56104
   250
fun smt2_filter ctxt goal xwfacts i time_limit =
blanchet@56078
   251
  let
blanchet@56078
   252
    val ctxt =
blanchet@56078
   253
      ctxt
blanchet@56078
   254
      |> Config.put SMT2_Config.oracle false
blanchet@56078
   255
      |> Config.put SMT2_Config.filter_only_facts true
blanchet@56082
   256
      |> Config.put SMT2_Config.timeout (Time.toReal time_limit)
blanchet@56078
   257
blanchet@56082
   258
    val ({context=ctxt, prems, concl, ...}, _) = Subgoal.focus ctxt i goal
blanchet@56106
   259
    fun negate ct = Thm.dest_comb ct ||> Thm.apply @{cterm Not} |-> Thm.apply
blanchet@56078
   260
    val cprop =
blanchet@56082
   261
      (case try negate (Thm.rhs_of (SMT2_Normalize.atomize_conv ctxt concl)) of
blanchet@56078
   262
        SOME ct => ct
blanchet@56094
   263
      | NONE => raise SMT2_Failure.SMT (SMT2_Failure.Other_Failure "goal is not a HOL term"))
blanchet@56082
   264
blanchet@56106
   265
    val wconjecture = (NONE, Thm.assume cprop)
blanchet@56106
   266
    val wprems = map (pair NONE) prems
blanchet@56106
   267
    val wfacts = map snd xwfacts
blanchet@56106
   268
    val wthms = wconjecture :: wprems @ wfacts
blanchet@56106
   269
    val iwthms = map_index I wthms
blanchet@56082
   270
blanchet@56106
   271
    val conjecture_i = 0
blanchet@56106
   272
    val facts_i = 1 + length wprems
blanchet@56078
   273
  in
blanchet@56106
   274
    wthms
blanchet@56082
   275
    |> apply_solver ctxt
blanchet@56128
   276
    |> (fn (((iidths0, z3_proof), _), {rewrite_rules, ...}) =>
blanchet@56128
   277
      let val iidths = if can_filter ctxt then iidths0 else map (apsnd (apfst (K no_id))) iwthms
blanchet@56104
   278
      in
blanchet@56128
   279
        {outcome = NONE,
blanchet@56128
   280
         rewrite_rules = rewrite_rules,
blanchet@56104
   281
         conjecture_id =
blanchet@56106
   282
           the_default no_id (Option.map fst (AList.lookup (op =) iidths conjecture_i)),
blanchet@56106
   283
         helper_ids = map_filter (try (fn (~1, idth) => idth)) iidths,
blanchet@56106
   284
         fact_ids = map_filter (fn (i, (id, _)) =>
blanchet@56106
   285
           try (apsnd (apsnd snd o nth xwfacts)) (id, i - facts_i)) iidths,
blanchet@56104
   286
         z3_proof = z3_proof}
blanchet@56104
   287
      end)
blanchet@56078
   288
  end
blanchet@56128
   289
  handle SMT2_Failure.SMT fail => {outcome = SOME fail, rewrite_rules = [], conjecture_id = no_id,
blanchet@56128
   290
    helper_ids = [], fact_ids = [], z3_proof = []}
blanchet@56078
   291
blanchet@56078
   292
blanchet@56078
   293
(* SMT tactic *)
blanchet@56078
   294
blanchet@56078
   295
local
blanchet@56106
   296
  fun trace_assumptions ctxt wfacts iidths =
blanchet@56106
   297
    let val used = map_filter (try (snd o nth wfacts) o fst) iidths in
blanchet@56104
   298
      if Config.get ctxt SMT2_Config.trace_used_facts andalso length wfacts > 0 then
blanchet@56078
   299
        tracing (Pretty.string_of (Pretty.big_list "SMT used facts:"
blanchet@56106
   300
          (map (Display.pretty_thm ctxt) used)))
blanchet@56078
   301
      else ()
blanchet@56078
   302
    end
blanchet@56078
   303
blanchet@56106
   304
  fun solve ctxt wfacts =
blanchet@56106
   305
    wfacts
blanchet@56078
   306
    |> apply_solver ctxt
blanchet@56128
   307
    |> fst
blanchet@56106
   308
    |>> apfst (trace_assumptions ctxt wfacts)
blanchet@56078
   309
    |> snd
blanchet@56078
   310
blanchet@56078
   311
  fun str_of ctxt fail =
blanchet@56078
   312
    SMT2_Failure.string_of_failure ctxt fail
blanchet@56078
   313
    |> prefix ("Solver " ^ SMT2_Config.solver_of ctxt ^ ": ")
blanchet@56078
   314
blanchet@56106
   315
  fun safe_solve ctxt wfacts = SOME (solve ctxt wfacts)
blanchet@56078
   316
    handle
blanchet@56078
   317
      SMT2_Failure.SMT (fail as SMT2_Failure.Counterexample _) =>
blanchet@56078
   318
        (SMT2_Config.verbose_msg ctxt (str_of ctxt) fail; NONE)
blanchet@56078
   319
    | SMT2_Failure.SMT (fail as SMT2_Failure.Time_Out) =>
blanchet@56078
   320
        error ("SMT: Solver " ^ quote (SMT2_Config.solver_of ctxt) ^ ": " ^
blanchet@56078
   321
          SMT2_Failure.string_of_failure ctxt fail ^ " (setting the " ^
blanchet@56078
   322
          "configuration option " ^ quote (Config.name_of SMT2_Config.timeout) ^ " might help)")
blanchet@56078
   323
    | SMT2_Failure.SMT fail => error (str_of ctxt fail)
blanchet@56078
   324
blanchet@56078
   325
  fun resolve (SOME thm) = rtac thm 1
blanchet@56078
   326
    | resolve NONE = no_tac
blanchet@56078
   327
blanchet@56078
   328
  fun tac prove ctxt rules =
blanchet@56078
   329
    CONVERSION (SMT2_Normalize.atomize_conv ctxt)
blanchet@56078
   330
    THEN' rtac @{thm ccontr}
blanchet@56106
   331
    THEN' SUBPROOF (fn {context = ctxt, prems, ...} =>
blanchet@56106
   332
      resolve (prove ctxt (map (pair NONE) (rules @ prems)))) ctxt
blanchet@56078
   333
in
blanchet@56078
   334
blanchet@56078
   335
val smt2_tac = tac safe_solve
blanchet@56078
   336
val smt2_tac' = tac (SOME oo solve)
blanchet@56078
   337
blanchet@56078
   338
end
blanchet@56078
   339
blanchet@56078
   340
end