src/HOL/Tools/Sledgehammer/sledgehammer_commands.ML
author blanchet
Mon Jun 02 17:34:26 2014 +0200 (2014-06-02 ago)
changeset 57158 f028d93798e6
parent 57154 f0eff6393a32
child 57208 5bf2a5c498c2
permissions -rw-r--r--
simplified counterexample handling
     1 (*  Title:      HOL/Tools/Sledgehammer/sledgehammer_commands.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3 
     4 Adds "sledgehammer" and related commands to Isabelle/Isar's outer syntax.
     5 *)
     6 
     7 signature SLEDGEHAMMER_COMMANDS =
     8 sig
     9   type params = Sledgehammer_Prover.params
    10 
    11   val provers : string Unsynchronized.ref
    12   val default_params : theory -> (string * string) list -> params
    13 end;
    14 
    15 structure Sledgehammer_Commands : SLEDGEHAMMER_COMMANDS =
    16 struct
    17 
    18 open ATP_Util
    19 open ATP_Systems
    20 open ATP_Problem_Generate
    21 open ATP_Proof
    22 open ATP_Proof_Reconstruct
    23 open Sledgehammer_Util
    24 open Sledgehammer_Fact
    25 open Sledgehammer_Prover
    26 open Sledgehammer_Prover_SMT
    27 open Sledgehammer_Prover_Minimize
    28 open Sledgehammer_MaSh
    29 open Sledgehammer
    30 
    31 (* val cvc3N = "cvc3" *)
    32 val yicesN = "yices"
    33 val z3_newN = "z3_new"
    34 
    35 val runN = "run"
    36 val minN = "min"
    37 val messagesN = "messages"
    38 val supported_proversN = "supported_provers"
    39 val kill_allN = "kill_all"
    40 val running_proversN = "running_provers"
    41 val running_learnersN = "running_learners"
    42 val refresh_tptpN = "refresh_tptp"
    43 
    44 val _ =
    45   ProofGeneral.preference_option ProofGeneral.category_tracing
    46     NONE
    47     @{system_option auto_sledgehammer}
    48     "auto-sledgehammer"
    49     "Run Sledgehammer automatically"
    50 
    51 (** Sledgehammer commands **)
    52 
    53 fun add_fact_override ns : fact_override = {add = ns, del = [], only = false}
    54 fun del_fact_override ns : fact_override = {add = [], del = ns, only = false}
    55 fun only_fact_override ns : fact_override = {add = ns, del = [], only = true}
    56 fun merge_fact_override_pairwise (r1 : fact_override) (r2 : fact_override) =
    57   {add = #add r1 @ #add r2, del = #del r1 @ #del r2,
    58    only = #only r1 andalso #only r2}
    59 fun merge_fact_overrides rs =
    60   fold merge_fact_override_pairwise rs (only_fact_override [])
    61 
    62 (*** parameters ***)
    63 
    64 val provers = Unsynchronized.ref ""
    65 
    66 val _ =
    67   ProofGeneral.preference_string ProofGeneral.category_proof
    68     NONE
    69     provers
    70     "Sledgehammer: Provers"
    71     "Default automatic provers (separated by whitespace)"
    72 
    73 val _ =
    74   ProofGeneral.preference_option ProofGeneral.category_proof
    75     NONE
    76     @{system_option sledgehammer_timeout}
    77     "Sledgehammer: Time Limit"
    78     "ATPs will be interrupted after this time (in seconds)"
    79 
    80 type raw_param = string * string list
    81 
    82 val default_default_params =
    83   [("debug", "false"),
    84    ("verbose", "false"),
    85    ("overlord", "false"),
    86    ("spy", "false"),
    87    ("blocking", "false"),
    88    ("type_enc", "smart"),
    89    ("strict", "false"),
    90    ("lam_trans", "smart"),
    91    ("uncurried_aliases", "smart"),
    92    ("learn", "true"),
    93    ("fact_filter", "smart"),
    94    ("max_facts", "smart"),
    95    ("fact_thresholds", "0.45 0.85"),
    96    ("max_mono_iters", "smart"),
    97    ("max_new_mono_instances", "smart"),
    98    ("isar_proofs", "smart"),
    99    ("compress_isar", "10"),
   100    ("try0_isar", "true"),
   101    ("smt_proofs", "smart"),
   102    ("slice", "true"),
   103    ("minimize", "smart"),
   104    ("preplay_timeout", "2")]
   105 
   106 val alias_params =
   107   [("prover", ("provers", [])), (* undocumented *)
   108    ("dont_preplay", ("preplay_timeout", ["0"])),
   109    ("dont_compress_isar", ("compress_isar", ["0"])),
   110    ("isar_proof", ("isar_proofs", [])) (* legacy *)]
   111 val negated_alias_params =
   112   [("no_debug", "debug"),
   113    ("quiet", "verbose"),
   114    ("no_overlord", "overlord"),
   115    ("dont_spy", "spy"),
   116    ("non_blocking", "blocking"),
   117    ("non_strict", "strict"),
   118    ("no_uncurried_aliases", "uncurried_aliases"),
   119    ("dont_learn", "learn"),
   120    ("no_isar_proofs", "isar_proofs"),
   121    ("dont_slice", "slice"),
   122    ("dont_minimize", "minimize"),
   123    ("dont_try0_isar", "try0_isar"),
   124    ("no_smt_proofs", "smt_proofs")]
   125 
   126 val params_not_for_minimize =
   127   ["provers", "blocking", "fact_filter", "max_facts", "fact_thresholds", "slice", "minimize"];
   128 
   129 val property_dependent_params = ["provers", "timeout"]
   130 
   131 fun is_known_raw_param s =
   132   AList.defined (op =) default_default_params s orelse
   133   AList.defined (op =) alias_params s orelse
   134   AList.defined (op =) negated_alias_params s orelse
   135   member (op =) property_dependent_params s orelse s = "expect"
   136 
   137 fun is_prover_list ctxt s =
   138   (case space_explode " " s of
   139     ss as _ :: _ => forall (is_prover_supported ctxt) ss
   140   | _ => false)
   141 
   142 fun unalias_raw_param (name, value) =
   143   (case AList.lookup (op =) alias_params name of
   144     SOME (name', []) => (name', value)
   145   | SOME (param' as (name', _)) =>
   146     if value <> ["false"] then
   147       param'
   148     else
   149       error ("Parameter " ^ quote name ^ " cannot be set to \"false\" \
   150              \(cf. " ^ quote name' ^ ").")
   151   | NONE =>
   152     (case AList.lookup (op =) negated_alias_params name of
   153       SOME name' => (name',
   154         (case value of
   155           ["false"] => ["true"]
   156         | ["true"] => ["false"]
   157         | [] => ["false"]
   158         | _ => value))
   159     | NONE => (name, value)))
   160 
   161 val any_type_enc = type_enc_of_string Strict "erased"
   162 
   163 (* "provers =", "type_enc =", "lam_trans =", "fact_filter =", and "max_facts ="
   164    can be omitted. For the last four, this is a secret feature. *)
   165 fun normalize_raw_param ctxt =
   166   unalias_raw_param
   167   #> (fn (name, value) =>
   168          if is_known_raw_param name then
   169            (name, value)
   170          else if null value then
   171            if is_prover_list ctxt name then
   172              ("provers", [name])
   173            else if can (type_enc_of_string Strict) name then
   174              ("type_enc", [name])
   175            else if can (trans_lams_of_string ctxt any_type_enc) name then
   176              ("lam_trans", [name])
   177            else if member (op =) fact_filters name then
   178              ("fact_filter", [name])
   179            else if is_some (Int.fromString name) then
   180              ("max_facts", [name])
   181            else
   182              error ("Unknown parameter: " ^ quote name ^ ".")
   183          else
   184            error ("Unknown parameter: " ^ quote name ^ "."))
   185 
   186 (* Ensures that type encodings such as "mono_native?" and "poly_guards!!" are
   187    read correctly. *)
   188 val implode_param = strip_spaces_except_between_idents o space_implode " "
   189 
   190 (* FIXME: use "Generic_Data" *)
   191 structure Data = Theory_Data
   192 (
   193   type T = raw_param list
   194   val empty = default_default_params |> map (apsnd single)
   195   val extend = I
   196   fun merge data : T = AList.merge (op =) (K true) data
   197 )
   198 
   199 fun remotify_prover_if_supported_and_not_already_remote ctxt name =
   200   if String.isPrefix remote_prefix name then
   201     SOME name
   202   else
   203     let val remote_name = remote_prefix ^ name in
   204       if is_prover_supported ctxt remote_name then SOME remote_name else NONE
   205     end
   206 
   207 fun remotify_prover_if_not_installed ctxt name =
   208   if is_prover_supported ctxt name andalso is_prover_installed ctxt name then
   209     SOME name
   210   else
   211     remotify_prover_if_supported_and_not_already_remote ctxt name
   212 
   213 (* The first ATP of the list is used by Auto Sledgehammer. Because of the low
   214    timeout, it makes sense to put E first. *)
   215 fun default_provers_param_value mode ctxt =
   216   [eN, spassN, z3_newN, e_sineN, vampireN, yicesN]
   217   |> map_filter (remotify_prover_if_not_installed ctxt)
   218   (* In "try" mode, leave at least one thread to another slow tool (e.g. Nitpick) *)
   219   |> take (Multithreading.max_threads_value () - (if mode = Try then 1 else 0))
   220   |> implode_param
   221 
   222 fun set_default_raw_param param thy =
   223   let val ctxt = Proof_Context.init_global thy in
   224     thy |> Data.map (AList.update (op =) (normalize_raw_param ctxt param))
   225   end
   226 
   227 fun default_raw_params mode thy =
   228   let val ctxt = Proof_Context.init_global thy in
   229     Data.get thy
   230     |> fold (AList.default (op =))
   231          [("provers", [(case !provers of "" => default_provers_param_value mode ctxt | s => s)]),
   232           ("timeout",
   233            let val timeout = Options.default_int @{system_option sledgehammer_timeout} in
   234              [if timeout <= 0 then "none" else string_of_int timeout]
   235            end)]
   236   end
   237 
   238 fun extract_params mode default_params override_params =
   239   let
   240     val raw_params = rev override_params @ rev default_params
   241     val lookup = Option.map implode_param o AList.lookup (op =) raw_params
   242     val lookup_string = the_default "" o lookup
   243     fun general_lookup_bool option default_value name =
   244       (case lookup name of
   245         SOME s => parse_bool_option option name s
   246       | NONE => default_value)
   247     val lookup_bool = the o general_lookup_bool false (SOME false)
   248     fun lookup_time name =
   249       (case lookup name of
   250         SOME s => parse_time name s
   251       | NONE => Time.zeroTime)
   252     fun lookup_int name =
   253       (case lookup name of
   254         NONE => 0
   255       | SOME s =>
   256         (case Int.fromString s of
   257           SOME n => n
   258         | NONE => error ("Parameter " ^ quote name ^ " must be assigned an integer value.")))
   259     fun lookup_real name =
   260       (case lookup name of
   261         NONE => 0.0
   262       | SOME s =>
   263         (case Real.fromString s of
   264           SOME n => n
   265         | NONE => error ("Parameter " ^ quote name ^ " must be assigned a real value.")))
   266     fun lookup_real_pair name =
   267       (case lookup name of
   268         NONE => (0.0, 0.0)
   269       | SOME s =>
   270         (case s |> space_explode " " |> map Real.fromString of
   271           [SOME r1, SOME r2] => (r1, r2)
   272         | _ => error ("Parameter " ^ quote name ^ " must be assigned a pair of floating-point \
   273                  \values (e.g., \"0.6 0.95\")")))
   274     fun lookup_option lookup' name =
   275       (case lookup name of
   276         SOME "smart" => NONE
   277       | _ => SOME (lookup' name))
   278     val debug = mode <> Auto_Try andalso lookup_bool "debug"
   279     val verbose = debug orelse (mode <> Auto_Try andalso lookup_bool "verbose")
   280     val overlord = lookup_bool "overlord"
   281     val spy = getenv "SLEDGEHAMMER_SPY" = "yes" orelse lookup_bool "spy"
   282     val blocking =
   283       Isabelle_Process.is_active () orelse mode <> Normal orelse debug orelse lookup_bool "blocking"
   284     val provers = lookup_string "provers" |> space_explode " "
   285                   |> mode = Auto_Try ? single o hd
   286     val type_enc =
   287       if mode = Auto_Try then
   288         NONE
   289       else
   290         (case lookup_string "type_enc" of
   291           "smart" => NONE
   292         | s => (type_enc_of_string Strict s; SOME s))
   293     val strict = mode = Auto_Try orelse lookup_bool "strict"
   294     val lam_trans = lookup_option lookup_string "lam_trans"
   295     val uncurried_aliases = lookup_option lookup_bool "uncurried_aliases"
   296     val learn = lookup_bool "learn"
   297     val fact_filter =
   298       lookup_option lookup_string "fact_filter"
   299       |> mode = Auto_Try ? (fn NONE => SOME mepoN | sf => sf)
   300     val max_facts = lookup_option lookup_int "max_facts"
   301     val fact_thresholds = lookup_real_pair "fact_thresholds"
   302     val max_mono_iters = lookup_option lookup_int "max_mono_iters"
   303     val max_new_mono_instances =
   304       lookup_option lookup_int "max_new_mono_instances"
   305     val isar_proofs = lookup_option lookup_bool "isar_proofs"
   306     val compress_isar = Real.max (1.0, lookup_real "compress_isar")
   307     val try0_isar = lookup_bool "try0_isar"
   308     val smt_proofs = lookup_option lookup_bool "smt_proofs"
   309     val slice = mode <> Auto_Try andalso lookup_bool "slice"
   310     val minimize = if mode = Auto_Try then NONE else lookup_option lookup_bool "minimize"
   311     val timeout = lookup_time "timeout"
   312     val preplay_timeout = if mode = Auto_Try then Time.zeroTime else lookup_time "preplay_timeout"
   313     val expect = lookup_string "expect"
   314   in
   315     {debug = debug, verbose = verbose, overlord = overlord, spy = spy, blocking = blocking,
   316      provers = provers, type_enc = type_enc, strict = strict, lam_trans = lam_trans,
   317      uncurried_aliases = uncurried_aliases, learn = learn, fact_filter = fact_filter,
   318      max_facts = max_facts, fact_thresholds = fact_thresholds, max_mono_iters = max_mono_iters,
   319      max_new_mono_instances = max_new_mono_instances, isar_proofs = isar_proofs,
   320      compress_isar = compress_isar, try0_isar = try0_isar, smt_proofs = smt_proofs, slice = slice,
   321      minimize = minimize, timeout = timeout, preplay_timeout = preplay_timeout, expect = expect}
   322   end
   323 
   324 fun get_params mode = extract_params mode o default_raw_params mode
   325 fun default_params thy = get_params Normal thy o map (apsnd single)
   326 
   327 (* Sledgehammer the given subgoal *)
   328 
   329 val default_minimize_prover = metisN
   330 
   331 fun is_raw_param_relevant_for_minimize (name, _) =
   332   not (member (op =) params_not_for_minimize name)
   333 fun string_of_raw_param (key, values) =
   334   key ^ (case implode_param values of "" => "" | value => " = " ^ value)
   335 fun nice_string_of_raw_param (p as (key, ["false"])) =
   336     (case AList.find (op =) negated_alias_params key of
   337        [neg] => neg
   338      | _ => string_of_raw_param p)
   339   | nice_string_of_raw_param p = string_of_raw_param p
   340 
   341 fun minimize_command override_params i more_override_params prover_name
   342                      fact_names =
   343   let
   344     val params =
   345       (override_params
   346        |> filter_out (AList.defined (op =) more_override_params o fst)) @
   347       more_override_params
   348       |> filter is_raw_param_relevant_for_minimize
   349       |> map nice_string_of_raw_param
   350       |> (if prover_name = default_minimize_prover then I else cons prover_name)
   351       |> space_implode ", "
   352   in
   353     sledgehammerN ^ " " ^ minN ^
   354     (if params = "" then "" else enclose " [" "]" params) ^
   355     " (" ^ space_implode " " fact_names ^ ")" ^
   356     (if i = 1 then "" else " " ^ string_of_int i)
   357   end
   358 
   359 val default_learn_prover_timeout = 2.0
   360 
   361 fun hammer_away override_params subcommand opt_i fact_override state0 =
   362   let
   363     val state =
   364       Proof.map_contexts (Try0.silence_methods false #> Config.put SMT2_Config.verbose false) state0
   365     val thy = Proof.theory_of state
   366     val ctxt = Proof.context_of state
   367 
   368     val override_params = override_params |> map (normalize_raw_param ctxt)
   369     val _ = Isabelle_System.mkdir (Path.explode (getenv "ISABELLE_TMP"))
   370   in
   371     if subcommand = runN then
   372       let val i = the_default 1 opt_i in
   373         run_sledgehammer (get_params Normal thy override_params) Normal NONE i fact_override
   374           (minimize_command override_params i) state
   375         |> K ()
   376       end
   377     else if subcommand = minN then
   378       let
   379         val ctxt = ctxt |> Config.put instantiate_inducts false
   380         val i = the_default 1 opt_i
   381         val params =
   382           get_params Minimize thy (("provers", [default_minimize_prover]) :: override_params)
   383         val goal = prop_of (#goal (Proof.goal state))
   384         val facts = nearly_all_facts ctxt false fact_override Symtab.empty
   385                                      Termtab.empty [] [] goal
   386         val learn = mash_learn_proof ctxt params goal facts
   387       in run_minimize params learn i (#add fact_override) state end
   388     else if subcommand = messagesN then
   389       messages opt_i
   390     else if subcommand = supported_proversN then
   391       supported_provers ctxt
   392     else if subcommand = kill_allN then
   393       (kill_provers ();
   394        kill_learners ctxt (get_params Normal thy override_params))
   395     else if subcommand = running_proversN then
   396       running_provers ()
   397     else if subcommand = unlearnN then
   398       mash_unlearn ctxt (get_params Normal thy override_params)
   399     else if subcommand = learn_isarN orelse subcommand = learn_proverN orelse
   400             subcommand = relearn_isarN orelse subcommand = relearn_proverN then
   401       (if subcommand = relearn_isarN orelse subcommand = relearn_proverN then
   402          mash_unlearn ctxt (get_params Normal thy override_params)
   403        else
   404          ();
   405        mash_learn ctxt
   406            (* TODO: Use MaSh mode instead and have the special defaults hardcoded in "get_params" *)
   407            (get_params Normal thy
   408                 ([("timeout", [string_of_real default_learn_prover_timeout]),
   409                   ("slice", ["false"])] @
   410                  override_params @
   411                  [("minimize", ["true"]),
   412                   ("preplay_timeout", ["0"])]))
   413            fact_override (#facts (Proof.goal state))
   414            (subcommand = learn_proverN orelse subcommand = relearn_proverN))
   415     else if subcommand = running_learnersN then
   416       running_learners ()
   417     else if subcommand = refresh_tptpN then
   418       refresh_systems_on_tptp ()
   419     else
   420       error ("Unknown subcommand: " ^ quote subcommand ^ ".")
   421   end
   422 
   423 fun sledgehammer_trans (((subcommand, params), fact_override), opt_i) =
   424   Toplevel.unknown_proof o
   425   Toplevel.keep (hammer_away params subcommand opt_i fact_override
   426                  o Toplevel.proof_of)
   427 
   428 fun string_of_raw_param (name, value) = name ^ " = " ^ implode_param value
   429 
   430 fun sledgehammer_params_trans params =
   431   Toplevel.theory
   432     (fold set_default_raw_param params
   433      #> tap (fn thy =>
   434           writeln ("Default parameters for Sledgehammer:\n" ^
   435             (case rev (default_raw_params Normal thy) of
   436               [] => "none"
   437             | params => params |> map string_of_raw_param |> sort_strings |> cat_lines))))
   438 
   439 val parse_query_bang = @{keyword "?"} || @{keyword "!"} || @{keyword "!!"}
   440 val parse_key =
   441   Scan.repeat1 (Parse.typ_group || parse_query_bang) >> implode_param
   442 val parse_value =
   443   Scan.repeat1 (Parse.xname || Parse.float_number || parse_query_bang)
   444 val parse_param = parse_key -- Scan.optional (@{keyword "="} |-- parse_value) []
   445 val parse_params = Scan.optional (Args.bracks (Parse.list parse_param)) []
   446 val parse_fact_refs =
   447   Scan.repeat1 (Scan.unless (Parse.name -- Args.colon) Parse_Spec.xthm)
   448 val parse_fact_override_chunk =
   449   (Args.add |-- Args.colon |-- parse_fact_refs >> add_fact_override)
   450   || (Args.del |-- Args.colon |-- parse_fact_refs >> del_fact_override)
   451   || (parse_fact_refs >> only_fact_override)
   452 val parse_fact_override =
   453   Scan.optional (Args.parens (Scan.repeat parse_fact_override_chunk
   454                               >> merge_fact_overrides))
   455                 no_fact_override
   456 
   457 val _ =
   458   Outer_Syntax.improper_command @{command_spec "sledgehammer"}
   459     "search for first-order proof using automatic theorem provers"
   460     ((Scan.optional Parse.short_ident runN -- parse_params
   461       -- parse_fact_override -- Scan.option Parse.nat) #>> sledgehammer_trans)
   462 val _ =
   463   Outer_Syntax.command @{command_spec "sledgehammer_params"}
   464     "set and display the default parameters for Sledgehammer"
   465     (parse_params #>> sledgehammer_params_trans)
   466 
   467 fun try_sledgehammer auto state =
   468   let
   469     val thy = Proof.theory_of state
   470     val mode = if auto then Auto_Try else Try
   471     val i = 1
   472   in
   473     run_sledgehammer (get_params mode thy []) mode NONE i no_fact_override (minimize_command [] i)
   474       state
   475   end
   476 
   477 val _ = Try.tool_setup (sledgehammerN, (40, @{system_option auto_sledgehammer}, try_sledgehammer))
   478 
   479 val _ =
   480   Query_Operation.register sledgehammerN (fn {state = st, args, output_result} =>
   481     (case try Toplevel.proof_of st of
   482       SOME state =>
   483         let
   484           val thy = Proof.theory_of state
   485           val ctxt = Proof.context_of state
   486           val [provers_arg, isar_proofs_arg] = args
   487 
   488           val override_params =
   489             ((if provers_arg = "" then [] else [("provers", space_explode " " provers_arg)]) @
   490               [("isar_proofs", [isar_proofs_arg]),
   491                ("blocking", ["true"]),
   492                ("minimize", ["true"]),
   493                ("debug", ["false"]),
   494                ("verbose", ["false"]),
   495                ("overlord", ["false"])])
   496             |> map (normalize_raw_param ctxt)
   497 
   498           val _ = run_sledgehammer (get_params Normal thy override_params) Normal
   499             (SOME output_result) 1 no_fact_override (minimize_command override_params 1) state
   500         in () end
   501     | NONE => error "Unknown proof context"))
   502 
   503 end;