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