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