src/HOL/Tools/SMT2/smt2_solver.ML
author blanchet
Tue Jun 03 10:13:44 2014 +0200 (2014-06-03)
changeset 57163 7fc7de3b387e
parent 57159 24cbdebba35a
child 57164 eb5f27ec3987
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@57163
    11
blanchet@57163
    12
  type parsed_proof =
blanchet@57163
    13
    {outcome: SMT2_Failure.failure option,
blanchet@57163
    14
     fact_ids: (int * ((string * ATP_Problem_Generate.stature) * thm)) list,
blanchet@57163
    15
     atp_proof: unit -> (term, string) ATP_Proof.atp_step list}
blanchet@57163
    16
blanchet@57163
    17
  type solver_config =
blanchet@57163
    18
    {name: string,
blanchet@57163
    19
     class: Proof.context -> SMT2_Util.class,
blanchet@57163
    20
     avail: unit -> bool,
blanchet@57163
    21
     command: unit -> string list,
blanchet@57163
    22
     options: Proof.context -> string list,
blanchet@57163
    23
     default_max_relevant: int,
blanchet@57163
    24
     can_filter: bool,
blanchet@57163
    25
     outcome: string -> string list -> outcome * string list,
blanchet@57163
    26
     parse_proof: (Proof.context -> SMT2_Translate.replay_data -> string list ->
blanchet@57163
    27
       (int * (int * thm)) list * Z3_New_Proof.z3_step list) option,
blanchet@57163
    28
     replay: (Proof.context -> SMT2_Translate.replay_data -> string list -> thm) option}
blanchet@56078
    29
blanchet@56078
    30
  (*registry*)
blanchet@56078
    31
  val add_solver: solver_config -> theory -> theory
blanchet@56078
    32
  val default_max_relevant: Proof.context -> string -> int
blanchet@56078
    33
blanchet@56078
    34
  (*filter*)
blanchet@57163
    35
  val smt2_filter: Proof.context -> thm ->
blanchet@57163
    36
    ((string * ATP_Problem_Generate.stature) * (int option * thm)) list -> int -> Time.time ->
blanchet@57163
    37
    parsed_proof
blanchet@56078
    38
blanchet@56078
    39
  (*tactic*)
blanchet@56078
    40
  val smt2_tac: Proof.context -> thm list -> int -> tactic
blanchet@56078
    41
  val smt2_tac': Proof.context -> thm list -> int -> tactic
blanchet@56078
    42
end
blanchet@56078
    43
blanchet@56078
    44
structure SMT2_Solver: SMT2_SOLVER =
blanchet@56078
    45
struct
blanchet@56078
    46
blanchet@56078
    47
blanchet@56078
    48
(* interface to external solvers *)
blanchet@56078
    49
blanchet@56078
    50
local
blanchet@56078
    51
blanchet@56132
    52
fun make_command command options problem_path proof_path =
blanchet@56132
    53
  "(exec 2>&1;" :: map File.shell_quote (command () @ options) @
blanchet@56132
    54
  [File.shell_path problem_path, ")", ">", File.shell_path proof_path]
blanchet@56132
    55
  |> space_implode " "
blanchet@56078
    56
blanchet@56132
    57
fun with_trace ctxt msg f x =
blanchet@56078
    58
  let val _ = SMT2_Config.trace_msg ctxt (fn () => msg) ()
blanchet@56078
    59
  in f x end
blanchet@56078
    60
blanchet@56078
    61
fun run ctxt name mk_cmd input =
blanchet@56078
    62
  (case SMT2_Config.certificates_of ctxt of
blanchet@56078
    63
    NONE =>
blanchet@56078
    64
      if not (SMT2_Config.is_available ctxt name) then
blanchet@56131
    65
        error ("The SMT solver " ^ quote name ^ " is not installed")
blanchet@56078
    66
      else if Config.get ctxt SMT2_Config.debug_files = "" then
blanchet@56132
    67
        with_trace ctxt ("Invoking SMT solver " ^ quote name ^ " ...") (Cache_IO.run mk_cmd) input
blanchet@56078
    68
      else
blanchet@56078
    69
        let
blanchet@56078
    70
          val base_path = Path.explode (Config.get ctxt SMT2_Config.debug_files)
blanchet@56078
    71
          val in_path = Path.ext "smt2_in" base_path
blanchet@56078
    72
          val out_path = Path.ext "smt2_out" base_path
blanchet@56078
    73
        in Cache_IO.raw_run mk_cmd input in_path out_path end
blanchet@56078
    74
  | SOME certs =>
blanchet@56078
    75
      (case Cache_IO.lookup certs input of
blanchet@56078
    76
        (NONE, key) =>
blanchet@56078
    77
          if Config.get ctxt SMT2_Config.read_only_certificates then
blanchet@56078
    78
            error ("Bad certificate cache: missing certificate")
blanchet@56078
    79
          else
blanchet@56078
    80
            Cache_IO.run_and_cache certs key mk_cmd input
blanchet@56078
    81
      | (SOME output, _) =>
blanchet@56132
    82
          with_trace ctxt ("Using cached certificate from " ^
blanchet@56132
    83
            File.shell_path (Cache_IO.cache_path_of certs) ^ " ...") 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@56132
    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@56132
   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@56112
   126
    val comments = [space_implode " " options]
blanchet@56078
   127
blanchet@56132
   128
    val (str, replay_data as {context = ctxt', ...}) =
blanchet@56078
   129
      ithms
blanchet@56078
   130
      |> tap (trace_assms ctxt)
blanchet@56078
   131
      |> SMT2_Translate.translate ctxt comments
blanchet@56078
   132
      ||> tap trace_replay_data
blanchet@56132
   133
  in (run_solver ctxt' name (make_command command options) str, replay_data) end
blanchet@56078
   134
blanchet@56078
   135
end
blanchet@56078
   136
blanchet@56078
   137
blanchet@56078
   138
(* configuration *)
blanchet@56078
   139
blanchet@56078
   140
datatype outcome = Unsat | Sat | Unknown
blanchet@56078
   141
blanchet@57163
   142
type parsed_proof =
blanchet@57163
   143
  {outcome: SMT2_Failure.failure option,
blanchet@57163
   144
   fact_ids: (int * ((string * ATP_Problem_Generate.stature) * thm)) list,
blanchet@57163
   145
   atp_proof: unit -> (term, string) ATP_Proof.atp_step list}
blanchet@57163
   146
blanchet@57163
   147
type solver_config =
blanchet@57163
   148
  {name: string,
blanchet@57163
   149
   class: Proof.context -> SMT2_Util.class,
blanchet@57163
   150
   avail: unit -> bool,
blanchet@57163
   151
   command: unit -> string list,
blanchet@57163
   152
   options: Proof.context -> string list,
blanchet@57163
   153
   default_max_relevant: int,
blanchet@57163
   154
   can_filter: bool,
blanchet@57163
   155
   outcome: string -> string list -> outcome * string list,
blanchet@57163
   156
   parse_proof: (Proof.context -> SMT2_Translate.replay_data -> string list ->
blanchet@57163
   157
     (int * (int * thm)) list * Z3_New_Proof.z3_step list) option,
blanchet@57163
   158
   replay: (Proof.context -> SMT2_Translate.replay_data -> string list -> thm) option}
blanchet@56078
   159
blanchet@56078
   160
blanchet@56106
   161
(* check well-sortedness *)
blanchet@56106
   162
blanchet@56106
   163
val has_topsort = Term.exists_type (Term.exists_subtype (fn
blanchet@56106
   164
    TFree (_, []) => true
blanchet@56106
   165
  | TVar (_, []) => true
blanchet@56106
   166
  | _ => false))
blanchet@56106
   167
blanchet@56106
   168
(* top sorts cause problems with atomization *)
blanchet@56106
   169
fun check_topsort ctxt thm =
blanchet@56106
   170
  if has_topsort (Thm.prop_of thm) then (SMT2_Normalize.drop_fact_warning ctxt thm; TrueI) else thm
blanchet@56106
   171
blanchet@56106
   172
blanchet@56078
   173
(* registry *)
blanchet@56078
   174
blanchet@56078
   175
type solver_info = {
blanchet@56078
   176
  command: unit -> string list,
blanchet@56078
   177
  default_max_relevant: int,
blanchet@56125
   178
  can_filter: bool,
blanchet@57157
   179
  parse_proof: Proof.context -> SMT2_Translate.replay_data -> string list ->
blanchet@57157
   180
    (int * (int * thm)) list * Z3_New_Proof.z3_step list,
blanchet@57157
   181
  replay: Proof.context -> SMT2_Translate.replay_data -> string list -> thm}
blanchet@56078
   182
blanchet@56078
   183
structure Solvers = Generic_Data
blanchet@56078
   184
(
blanchet@56078
   185
  type T = solver_info Symtab.table
blanchet@56078
   186
  val empty = Symtab.empty
blanchet@56078
   187
  val extend = I
blanchet@56078
   188
  fun merge data = Symtab.merge (K true) data
blanchet@56078
   189
)
blanchet@56078
   190
blanchet@56078
   191
local
blanchet@57157
   192
  fun parse_proof outcome parse_proof0 outer_ctxt replay_data output =
blanchet@57157
   193
    (case outcome output of
blanchet@57157
   194
      (Unsat, ls) =>
blanchet@57157
   195
        (case parse_proof0 of SOME pp => pp outer_ctxt replay_data ls | NONE => ([], []))
blanchet@57158
   196
    | (result, _) => raise SMT2_Failure.SMT (SMT2_Failure.Counterexample (result = Sat)))
blanchet@57157
   197
blanchet@57157
   198
  fun replay outcome replay0 oracle outer_ctxt
blanchet@56132
   199
      (replay_data as {context = ctxt, ...} : SMT2_Translate.replay_data) output =
blanchet@56078
   200
    (case outcome output of
blanchet@56078
   201
      (Unsat, ls) =>
blanchet@57157
   202
        if not (Config.get ctxt SMT2_Config.oracle) andalso is_some replay0
blanchet@57157
   203
        then the replay0 outer_ctxt replay_data ls
blanchet@57157
   204
        else oracle ()
blanchet@57158
   205
    | (result, _) => raise SMT2_Failure.SMT (SMT2_Failure.Counterexample (result = Sat)))
blanchet@56078
   206
blanchet@57157
   207
  val cfalse = Thm.cterm_of @{theory} @{prop False}
blanchet@56078
   208
in
blanchet@56078
   209
blanchet@56125
   210
fun add_solver ({name, class, avail, command, options, default_max_relevant, can_filter,
blanchet@57157
   211
    outcome, parse_proof = parse_proof0, replay = replay0} : solver_config) =
blanchet@56078
   212
  let
blanchet@57157
   213
    fun solver oracle = {
blanchet@56078
   214
      command = command,
blanchet@56078
   215
      default_max_relevant = default_max_relevant,
blanchet@56125
   216
      can_filter = can_filter,
blanchet@57157
   217
      parse_proof = parse_proof (outcome name) parse_proof0,
blanchet@57157
   218
      replay = replay (outcome name) replay0 oracle}
blanchet@56078
   219
blanchet@56132
   220
    val info = {name = name, class = class, avail = avail, options = options}
blanchet@56078
   221
  in
blanchet@57157
   222
    Thm.add_oracle (Binding.name name, K cfalse) #-> (fn (_, oracle) =>
blanchet@57157
   223
    Context.theory_map (Solvers.map (Symtab.update_new (name, solver oracle)))) #>
blanchet@56078
   224
    Context.theory_map (SMT2_Config.add_solver info)
blanchet@56078
   225
  end
blanchet@56078
   226
blanchet@56078
   227
end
blanchet@56078
   228
blanchet@56125
   229
fun get_info ctxt name = the (Symtab.lookup (Solvers.get (Context.Proof ctxt)) name)
blanchet@56078
   230
blanchet@56078
   231
fun name_and_info_of ctxt =
blanchet@56132
   232
  let val name = SMT2_Config.solver_of ctxt
blanchet@56078
   233
  in (name, get_info ctxt name) end
blanchet@56078
   234
blanchet@57163
   235
val default_max_relevant = #default_max_relevant oo get_info
blanchet@57163
   236
val can_filter = #can_filter o snd o name_and_info_of
blanchet@57157
   237
blanchet@57157
   238
fun apply_solver_and_replay ctxt wthms0 =
blanchet@57157
   239
  let
blanchet@57157
   240
    val wthms = map (apsnd (check_topsort ctxt)) wthms0
blanchet@57157
   241
    val (name, {command, replay, ...}) = name_and_info_of ctxt
blanchet@57157
   242
    val (output, replay_data) = invoke name command (SMT2_Normalize.normalize ctxt wthms) ctxt
blanchet@57157
   243
  in replay ctxt replay_data output end
blanchet@56078
   244
blanchet@56078
   245
blanchet@56078
   246
(* filter *)
blanchet@56078
   247
blanchet@56106
   248
val no_id = ~1
blanchet@56078
   249
blanchet@57163
   250
fun smt2_filter ctxt0 goal xwfacts i time_limit =
blanchet@56078
   251
  let
blanchet@57163
   252
    val ctxt = ctxt0 |> Config.put SMT2_Config.timeout (Time.toReal time_limit)
blanchet@56078
   253
blanchet@56132
   254
    val ({context = ctxt, prems, concl, ...}, _) = Subgoal.focus ctxt i goal
blanchet@56106
   255
    fun negate ct = Thm.dest_comb ct ||> Thm.apply @{cterm Not} |-> Thm.apply
blanchet@56078
   256
    val cprop =
blanchet@56082
   257
      (case try negate (Thm.rhs_of (SMT2_Normalize.atomize_conv ctxt concl)) of
blanchet@56078
   258
        SOME ct => ct
blanchet@56094
   259
      | NONE => raise SMT2_Failure.SMT (SMT2_Failure.Other_Failure "goal is not a HOL term"))
blanchet@56082
   260
blanchet@56106
   261
    val wconjecture = (NONE, Thm.assume cprop)
blanchet@56106
   262
    val wprems = map (pair NONE) prems
blanchet@56106
   263
    val wfacts = map snd xwfacts
blanchet@56106
   264
    val wthms = wconjecture :: wprems @ wfacts
blanchet@56106
   265
    val iwthms = map_index I wthms
blanchet@56082
   266
blanchet@56106
   267
    val conjecture_i = 0
blanchet@56981
   268
    val prems_i = 1
blanchet@56981
   269
    val facts_i = prems_i + length wprems
blanchet@57163
   270
blanchet@57163
   271
    val wthms' = map (apsnd (check_topsort ctxt)) wthms
blanchet@57163
   272
    val (name, {command, parse_proof, ...}) = name_and_info_of ctxt
blanchet@57163
   273
    val (output, replay_data as {rewrite_rules, ...}) =
blanchet@57163
   274
      invoke name command (SMT2_Normalize.normalize ctxt wthms') ctxt
blanchet@56078
   275
  in
blanchet@57163
   276
    parse_proof ctxt replay_data output
blanchet@57163
   277
    |> (fn (iidths0, z3_proof) =>
blanchet@56981
   278
      let
blanchet@56981
   279
        val iidths = if can_filter ctxt then iidths0 else map (apsnd (apfst (K no_id))) iwthms
blanchet@57159
   280
blanchet@56981
   281
        fun id_of_index i = the_default no_id (Option.map fst (AList.lookup (op =) iidths i))
blanchet@57159
   282
blanchet@57159
   283
        val conjecture_id = id_of_index conjecture_i
blanchet@57159
   284
        val prem_ids = map id_of_index (prems_i upto facts_i - 1)
blanchet@57159
   285
        val helper_ids = map_filter (try (fn (~1, idth) => idth)) iidths
blanchet@57159
   286
        val fact_ids = map_filter (fn (i, (id, _)) =>
blanchet@57159
   287
          try (apsnd (apsnd snd o nth xwfacts)) (id, i - facts_i)) iidths
blanchet@57159
   288
        val fact_helper_ts =
blanchet@57159
   289
          map (fn (_, th) => (ATP_Util.short_thm_name ctxt th, prop_of th)) helper_ids @
blanchet@57159
   290
          map (fn (_, ((s, _), th)) => (s, prop_of th)) fact_ids
blanchet@57159
   291
        val fact_helper_ids =
blanchet@57163
   292
          map (apsnd (ATP_Util.short_thm_name ctxt)) helper_ids @ map (apsnd (fst o fst)) fact_ids
blanchet@56104
   293
      in
blanchet@57159
   294
        {outcome = NONE, fact_ids = fact_ids,
blanchet@57159
   295
         atp_proof = fn () => Z3_New_Isar.atp_proof_of_z3_proof ctxt rewrite_rules
blanchet@57159
   296
           (map Thm.prop_of prems) (Thm.term_of concl) fact_helper_ts prem_ids conjecture_id
blanchet@57159
   297
           fact_helper_ids z3_proof}
blanchet@56104
   298
      end)
blanchet@56078
   299
  end
blanchet@57159
   300
  handle SMT2_Failure.SMT fail => {outcome = SOME fail, fact_ids = [], atp_proof = K []}
blanchet@56078
   301
blanchet@56078
   302
blanchet@56078
   303
(* SMT tactic *)
blanchet@56078
   304
blanchet@56078
   305
local
blanchet@56078
   306
  fun str_of ctxt fail =
blanchet@57158
   307
    "Solver " ^ SMT2_Config.solver_of ctxt ^ ": " ^ SMT2_Failure.string_of_failure fail
blanchet@56078
   308
blanchet@57157
   309
  fun safe_solve ctxt wfacts = SOME (apply_solver_and_replay ctxt wfacts)
blanchet@56078
   310
    handle
blanchet@56078
   311
      SMT2_Failure.SMT (fail as SMT2_Failure.Counterexample _) =>
blanchet@56078
   312
        (SMT2_Config.verbose_msg ctxt (str_of ctxt) fail; NONE)
blanchet@56078
   313
    | SMT2_Failure.SMT (fail as SMT2_Failure.Time_Out) =>
blanchet@56078
   314
        error ("SMT: Solver " ^ quote (SMT2_Config.solver_of ctxt) ^ ": " ^
blanchet@57158
   315
          SMT2_Failure.string_of_failure fail ^ " (setting the " ^
blanchet@56078
   316
          "configuration option " ^ quote (Config.name_of SMT2_Config.timeout) ^ " might help)")
blanchet@56078
   317
    | SMT2_Failure.SMT fail => error (str_of ctxt fail)
blanchet@56078
   318
blanchet@56078
   319
  fun resolve (SOME thm) = rtac thm 1
blanchet@56078
   320
    | resolve NONE = no_tac
blanchet@56078
   321
blanchet@56078
   322
  fun tac prove ctxt rules =
blanchet@56078
   323
    CONVERSION (SMT2_Normalize.atomize_conv ctxt)
blanchet@56078
   324
    THEN' rtac @{thm ccontr}
blanchet@56106
   325
    THEN' SUBPROOF (fn {context = ctxt, prems, ...} =>
blanchet@56106
   326
      resolve (prove ctxt (map (pair NONE) (rules @ prems)))) ctxt
blanchet@56078
   327
in
blanchet@56078
   328
blanchet@56078
   329
val smt2_tac = tac safe_solve
blanchet@57157
   330
val smt2_tac' = tac (SOME oo apply_solver_and_replay)
blanchet@56078
   331
blanchet@56078
   332
end
blanchet@56078
   333
blanchet@56078
   334
end