src/HOL/Tools/atp_manager.ML
author nipkow
Wed Jun 24 15:51:07 2009 +0200 (2009-06-24)
changeset 31791 c9a1caf218c8
parent 31752 19a5f1c8a844
child 31793 7c10b13d49fe
permissions -rw-r--r--
New ATP option: full types
     1 (*  Title:      HOL/Tools/atp_manager.ML
     2     Author:     Fabian Immler, TU Muenchen
     3 
     4 ATP threads are registered here.
     5 Threads with the same birth-time are seen as one group.
     6 All threads of a group are killed when one thread of it has been successful,
     7 or after a certain time,
     8 or when the maximum number of threads exceeds; then the oldest thread is killed.
     9 *)
    10 
    11 signature ATP_MANAGER =
    12 sig
    13   val get_atps: unit -> string
    14   val set_atps: string -> unit
    15   val get_max_atps: unit -> int
    16   val set_max_atps: int -> unit
    17   val get_timeout: unit -> int
    18   val set_timeout: int -> unit
    19   val get_full_types: unit -> bool
    20   val kill: unit -> unit
    21   val info: unit -> unit
    22   val messages: int option -> unit
    23   type prover = int -> (thm * (string * int)) list option ->
    24     (thm * (string * int)) list option -> string -> int ->
    25     Proof.context * (thm list * thm) ->
    26     bool * string * string * string vector * (thm * (string * int)) list
    27   val add_prover: string -> prover -> theory -> theory
    28   val print_provers: theory -> unit
    29   val get_prover: string -> theory -> prover option
    30   val sledgehammer: string list -> Proof.state -> unit
    31 end;
    32 
    33 structure AtpManager: ATP_MANAGER =
    34 struct
    35 
    36 (** preferences **)
    37 
    38 val message_store_limit = 20;
    39 val message_display_limit = 5;
    40 
    41 local
    42 
    43 val atps = ref "e remote_vampire";
    44 val max_atps = ref 5;   (* ~1 means infinite number of atps *)
    45 val timeout = ref 60;
    46 val full_types = ref false;
    47 
    48 in
    49 
    50 fun get_atps () = CRITICAL (fn () => ! atps);
    51 fun set_atps str = CRITICAL (fn () => atps := str);
    52 
    53 fun get_max_atps () = CRITICAL (fn () => ! max_atps);
    54 fun set_max_atps number = CRITICAL (fn () => max_atps := number);
    55 
    56 fun get_timeout () = CRITICAL (fn () => ! timeout);
    57 fun set_timeout time = CRITICAL (fn () => timeout := time);
    58 
    59 fun get_full_types () = CRITICAL (fn () => ! full_types);
    60 
    61 val _ =
    62   ProofGeneralPgip.add_preference Preferences.category_proof
    63     (Preferences.string_pref atps
    64       "ATP: provers" "Default automatic provers (separated by whitespace)");
    65 
    66 val _ =
    67   ProofGeneralPgip.add_preference Preferences.category_proof
    68     (Preferences.int_pref max_atps
    69       "ATP: maximum number" "How many provers may run in parallel");
    70 
    71 val _ =
    72   ProofGeneralPgip.add_preference Preferences.category_proof
    73     (Preferences.int_pref timeout
    74       "ATP: timeout" "ATPs will be interrupted after this time (in seconds)");
    75 
    76 val _ =
    77   ProofGeneralPgip.add_preference Preferences.category_proof
    78     (Preferences.bool_pref full_types
    79       "ATP: full types" "ATPs will use full type information");
    80 
    81 end;
    82 
    83 
    84 
    85 (** thread management **)
    86 
    87 (* data structures over threads *)
    88 
    89 structure ThreadHeap = HeapFun
    90 (
    91   type elem = Time.time * Thread.thread;
    92   fun ord ((a, _), (b, _)) = Time.compare (a, b);
    93 );
    94 
    95 fun lookup_thread xs = AList.lookup Thread.equal xs;
    96 fun delete_thread xs = AList.delete Thread.equal xs;
    97 fun update_thread xs = AList.update Thread.equal xs;
    98 
    99 
   100 (* state of thread manager *)
   101 
   102 datatype T = State of
   103  {managing_thread: Thread.thread option,
   104   timeout_heap: ThreadHeap.T,
   105   oldest_heap: ThreadHeap.T,
   106   active: (Thread.thread * (Time.time * Time.time * string)) list,
   107   cancelling: (Thread.thread * (Time.time * Time.time * string)) list,
   108   messages: string list,
   109   store: string list};
   110 
   111 fun make_state managing_thread timeout_heap oldest_heap active cancelling messages store =
   112   State {managing_thread = managing_thread, timeout_heap = timeout_heap, oldest_heap = oldest_heap,
   113     active = active, cancelling = cancelling, messages = messages, store = store};
   114 
   115 val state = Synchronized.var "atp_manager"
   116   (make_state NONE ThreadHeap.empty ThreadHeap.empty [] [] [] []);
   117 
   118 
   119 (* unregister thread *)
   120 
   121 fun unregister (success, message) thread = Synchronized.change state
   122   (fn state as State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
   123     (case lookup_thread active thread of
   124       SOME (birthtime, _, description) =>
   125         let
   126           val (group, active') =
   127             if success then List.partition (fn (_, (tb, _, _)) => tb = birthtime) active
   128             else List.partition (fn (th, _) => Thread.equal (th, thread)) active
   129 
   130           val now = Time.now ()
   131           val cancelling' =
   132             fold (fn (th, (tb, _, desc)) => update_thread (th, (tb, now, desc))) group cancelling
   133 
   134           val message' = description ^ "\n" ^ message ^
   135             (if length group <= 1 then ""
   136              else "\nInterrupted " ^ string_of_int (length group - 1) ^ " other group members")
   137           val store' = message' ::
   138             (if length store <= message_store_limit then store
   139              else #1 (chop message_store_limit store))
   140         in make_state
   141           managing_thread timeout_heap oldest_heap active' cancelling' (message' :: messages) store'
   142         end
   143     | NONE => state));
   144 
   145 
   146 (* kill excessive atp threads *)
   147 
   148 fun excessive_atps active =
   149   let val max = get_max_atps ()
   150   in length active > max andalso max > ~1 end;
   151 
   152 local
   153 
   154 fun kill_oldest () =
   155   let exception Unchanged in
   156     Synchronized.change_result state
   157       (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
   158         if ThreadHeap.is_empty oldest_heap orelse not (excessive_atps active)
   159         then raise Unchanged
   160         else
   161           let val ((_, oldest_thread), oldest_heap') = ThreadHeap.min_elem oldest_heap
   162           in (oldest_thread,
   163           make_state managing_thread timeout_heap oldest_heap' active cancelling messages store) end)
   164       |> unregister (false, "Interrupted (maximum number of ATPs exceeded)")
   165     handle Unchanged => ()
   166   end;
   167 
   168 in
   169 
   170 fun kill_excessive () =
   171   let val State {active, ...} = Synchronized.value state
   172   in if excessive_atps active then (kill_oldest (); kill_excessive ()) else () end;
   173 
   174 end;
   175 
   176 fun print_new_messages () =
   177   let val to_print = Synchronized.change_result state
   178     (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
   179       (messages, make_state managing_thread timeout_heap oldest_heap active cancelling [] store))
   180   in
   181     if null to_print then ()
   182     else priority ("Sledgehammer: " ^ space_implode "\n\n" to_print)
   183   end;
   184 
   185 
   186 (* start a watching thread -- only one may exist *)
   187 
   188 fun check_thread_manager () = Synchronized.change state
   189   (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
   190     if (case managing_thread of SOME thread => Thread.isActive thread | NONE => false)
   191     then make_state managing_thread timeout_heap oldest_heap active cancelling messages store
   192     else let val managing_thread = SOME (SimpleThread.fork false (fn () =>
   193       let
   194         val min_wait_time = Time.fromMilliseconds 300
   195         val max_wait_time = Time.fromSeconds 10
   196 
   197         (* wait for next thread to cancel, or maximum*)
   198         fun time_limit (State {timeout_heap, ...}) =
   199           (case try ThreadHeap.min timeout_heap of
   200             NONE => SOME (Time.+ (Time.now (), max_wait_time))
   201           | SOME (time, _) => SOME time)
   202 
   203         (* action: find threads whose timeout is reached, and interrupt cancelling threads *)
   204         fun action (State {managing_thread, timeout_heap, oldest_heap, active, cancelling,
   205                            messages, store}) =
   206           let val (timeout_threads, timeout_heap') =
   207             ThreadHeap.upto (Time.now (), Thread.self ()) timeout_heap
   208           in
   209             if null timeout_threads andalso null cancelling andalso not (excessive_atps active)
   210             then NONE
   211             else
   212               let
   213                 val _ = List.app (SimpleThread.interrupt o #1) cancelling
   214                 val cancelling' = filter (Thread.isActive o #1) cancelling
   215                 val state' = make_state
   216                   managing_thread timeout_heap' oldest_heap active cancelling' messages store
   217               in SOME (map #2 timeout_threads, state') end
   218           end
   219       in
   220         while Synchronized.change_result state
   221           (fn st as
   222             State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
   223             if (null active) andalso (null cancelling) andalso (null messages)
   224             then (false, make_state NONE timeout_heap oldest_heap active cancelling messages store)
   225             else (true, st))
   226         do
   227           (Synchronized.timed_access state time_limit action
   228             |> these
   229             |> List.app (unregister (false, "Interrupted (reached timeout)"));
   230             kill_excessive ();
   231             print_new_messages ();
   232             (*give threads time to respond to interrupt*)
   233             OS.Process.sleep min_wait_time)
   234       end))
   235     in make_state managing_thread timeout_heap oldest_heap active cancelling messages store end);
   236 
   237 
   238 (* thread is registered here by sledgehammer *)
   239 
   240 fun register birthtime deadtime (thread, desc) =
   241  (Synchronized.change state
   242     (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
   243       let
   244         val timeout_heap' = ThreadHeap.insert (deadtime, thread) timeout_heap
   245         val oldest_heap' = ThreadHeap.insert (birthtime, thread) oldest_heap
   246         val active' = update_thread (thread, (birthtime, deadtime, desc)) active
   247       in make_state managing_thread timeout_heap' oldest_heap' active' cancelling messages store end);
   248   check_thread_manager ());
   249 
   250 
   251 
   252 (** user commands **)
   253 
   254 (* kill: move all threads to cancelling *)
   255 
   256 fun kill () = Synchronized.change state
   257   (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
   258     let val formerly_active = map (fn (th, (tb, _, desc)) => (th, (tb, Time.now (), desc))) active
   259     in make_state
   260       managing_thread timeout_heap oldest_heap [] (formerly_active @ cancelling) messages store
   261     end);
   262 
   263 
   264 (* ATP info *)
   265 
   266 fun info () =
   267   let
   268     val State {active, cancelling, ...} = Synchronized.value state
   269 
   270     fun running_info (_, (birth_time, dead_time, desc)) = "Running: "
   271         ^ (string_of_int o Time.toSeconds) (Time.- (Time.now (), birth_time))
   272         ^ " s  --  "
   273         ^ (string_of_int o Time.toSeconds) (Time.- (dead_time, Time.now ()))
   274         ^ " s to live:\n" ^ desc
   275     fun cancelling_info (_, (_, dead_time, desc)) = "Trying to interrupt thread since "
   276         ^ (string_of_int o Time.toSeconds) (Time.- (Time.now (), dead_time))
   277         ^ " s:\n" ^ desc
   278 
   279     val running =
   280       if null active then "No ATPs running."
   281       else space_implode "\n\n" ("Running ATPs:" :: map running_info active)
   282     val interrupting =
   283       if null cancelling then ""
   284       else space_implode "\n\n"
   285         ("Trying to interrupt the following ATPs:" :: map cancelling_info cancelling)
   286 
   287   in writeln (running ^ "\n" ^ interrupting) end;
   288 
   289 fun messages opt_limit =
   290   let
   291     val limit = the_default message_display_limit opt_limit;
   292     val State {store = msgs, ...} = Synchronized.value state
   293     val header = "Recent ATP messages" ^
   294       (if length msgs <= limit then ":" else " (" ^ string_of_int limit ^ " displayed):");
   295   in writeln (space_implode "\n\n" (header :: #1 (chop limit msgs))) end;
   296 
   297 
   298 
   299 (** The Sledgehammer **)
   300 
   301 (* named provers *)
   302 
   303 type prover = int -> (thm * (string * int)) list option ->
   304   (thm * (string * int)) list option -> string -> int ->
   305   Proof.context * (thm list * thm) ->
   306   bool * string * string * string vector * (thm * (string * int)) list
   307 
   308 fun err_dup_prover name = error ("Duplicate prover: " ^ quote name);
   309 
   310 structure Provers = TheoryDataFun
   311 (
   312   type T = (prover * stamp) Symtab.table
   313   val empty = Symtab.empty
   314   val copy = I
   315   val extend = I
   316   fun merge _ tabs : T = Symtab.merge (eq_snd op =) tabs
   317     handle Symtab.DUP dup => err_dup_prover dup
   318 );
   319 
   320 fun add_prover name prover thy =
   321   Provers.map (Symtab.update_new (name, (prover, stamp ()))) thy
   322     handle Symtab.DUP dup => err_dup_prover dup;
   323 
   324 fun print_provers thy = Pretty.writeln
   325   (Pretty.strs ("external provers:" :: sort_strings (Symtab.keys (Provers.get thy))));
   326 
   327 fun get_prover name thy = case Symtab.lookup (Provers.get thy) name of
   328   NONE => NONE
   329 | SOME (prover, _) => SOME prover;
   330 
   331 (* start prover thread *)
   332 
   333 fun start_prover name birthtime deadtime i proof_state =
   334   (case get_prover name (Proof.theory_of proof_state) of
   335     NONE => warning ("Unknown external prover: " ^ quote name)
   336   | SOME prover =>
   337       let
   338         val (ctxt, (_, goal)) = Proof.get_goal proof_state
   339         val desc =
   340           "external prover " ^ quote name ^ " for subgoal " ^ string_of_int i ^ ":\n" ^
   341             Syntax.string_of_term ctxt (Thm.term_of (Thm.cprem_of goal i))
   342         val _ = SimpleThread.fork true (fn () =>
   343           let
   344             val _ = register birthtime deadtime (Thread.self (), desc)
   345             val result =
   346               let val (success, message, _, _, _) =
   347                 prover (get_timeout ()) NONE NONE name i (Proof.get_goal proof_state)
   348               in (success, message) end
   349               handle ResHolClause.TOO_TRIVIAL
   350                 => (true, "Empty clause: Try this command: " ^ Markup.markup Markup.sendback "apply metis")
   351               | ERROR msg
   352                 => (false, "Error: " ^ msg)
   353             val _ = unregister result (Thread.self ())
   354           in () end handle Interrupt => ())
   355       in () end);
   356 
   357 
   358 (* sledghammer for first subgoal *)
   359 
   360 fun sledgehammer names proof_state =
   361   let
   362     val provers =
   363       if null names then String.tokens (Symbol.is_ascii_blank o String.str) (get_atps ())
   364       else names
   365     val birthtime = Time.now ()
   366     val deadtime = Time.+ (birthtime, Time.fromSeconds (get_timeout ()))
   367   in List.app (fn name => start_prover name birthtime deadtime 1 proof_state) provers end;
   368 
   369 
   370 
   371 (** Isar command syntax **)
   372 
   373 local structure K = OuterKeyword and P = OuterParse in
   374 
   375 val _ =
   376   OuterSyntax.improper_command "atp_kill" "kill all managed provers" K.diag
   377     (Scan.succeed (Toplevel.no_timing o Toplevel.imperative kill));
   378 
   379 val _ =
   380   OuterSyntax.improper_command "atp_info" "print information about managed provers" K.diag
   381     (Scan.succeed (Toplevel.no_timing o Toplevel.imperative info));
   382 
   383 val _ =
   384   OuterSyntax.improper_command "atp_messages" "print recent messages issued by managed provers" K.diag
   385     (Scan.option (P.$$$ "(" |-- P.nat --| P.$$$ ")") >>
   386       (fn limit => Toplevel.no_timing o Toplevel.imperative (fn () => messages limit)));
   387 
   388 val _ =
   389   OuterSyntax.improper_command "print_atps" "print external provers" K.diag
   390     (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_theory o
   391       Toplevel.keep (print_provers o Toplevel.theory_of)));
   392 
   393 val _ =
   394   OuterSyntax.command "sledgehammer" "call all automatic theorem provers" K.diag
   395     (Scan.repeat P.xname >> (fn names => Toplevel.no_timing o Toplevel.unknown_proof o
   396       Toplevel.keep (sledgehammer names o Toplevel.proof_of)));
   397 
   398 end;
   399 
   400 end;
   401