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