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