src/HOL/Tools/ATP_Manager/atp_manager.ML
author wenzelm
Wed Oct 28 22:18:00 2009 +0100 (2009-10-28)
changeset 33292 affe60b3d864
parent 33220 11a1af478dac
child 33312 6ca8a7984fd9
permissions -rw-r--r--
renamed raw Proof.get_goal to Proof.raw_goal;
     1 (*  Title:      HOL/Tools/ATP_Manager/atp_manager.ML
     2     Author:     Fabian Immler, TU Muenchen
     3     Author:     Makarius
     4 
     5 Central manager component for ATP threads.
     6 *)
     7 
     8 signature ATP_MANAGER =
     9 sig
    10   val atps: string Unsynchronized.ref
    11   val get_atps: unit -> string list
    12   val timeout: int Unsynchronized.ref
    13   val full_types: bool Unsynchronized.ref
    14   val kill: unit -> unit
    15   val info: unit -> unit
    16   val messages: int option -> unit
    17   val add_prover: string * ATP_Wrapper.prover -> theory -> theory
    18   val get_prover: theory -> string -> ATP_Wrapper.prover option
    19   val print_provers: theory -> unit
    20   val sledgehammer: string list -> Proof.state -> unit
    21 end;
    22 
    23 structure ATP_Manager: ATP_MANAGER =
    24 struct
    25 
    26 (** preferences **)
    27 
    28 val message_store_limit = 20;
    29 val message_display_limit = 5;
    30 
    31 val atps = Unsynchronized.ref "e spass remote_vampire";
    32 fun get_atps () = String.tokens (Symbol.is_ascii_blank o String.str) (! atps);
    33 
    34 val timeout = Unsynchronized.ref 60;
    35 val full_types = Unsynchronized.ref false;
    36 
    37 val _ =
    38   ProofGeneralPgip.add_preference Preferences.category_proof
    39     (Preferences.string_pref atps
    40       "ATP: provers" "Default automatic provers (separated by whitespace)");
    41 
    42 val _ =
    43   ProofGeneralPgip.add_preference Preferences.category_proof
    44     (Preferences.int_pref timeout
    45       "ATP: timeout" "ATPs will be interrupted after this time (in seconds)");
    46 
    47 val _ =
    48   ProofGeneralPgip.add_preference Preferences.category_proof
    49     (Preferences.bool_pref full_types
    50       "ATP: full types" "ATPs will use full type information");
    51 
    52 
    53 
    54 (** thread management **)
    55 
    56 (* data structures over threads *)
    57 
    58 structure Thread_Heap = Heap
    59 (
    60   type elem = Time.time * Thread.thread;
    61   fun ord ((a, _), (b, _)) = Time.compare (a, b);
    62 );
    63 
    64 fun lookup_thread xs = AList.lookup Thread.equal xs;
    65 fun delete_thread xs = AList.delete Thread.equal xs;
    66 fun update_thread xs = AList.update Thread.equal xs;
    67 
    68 
    69 (* state of thread manager *)
    70 
    71 type state =
    72  {manager: Thread.thread option,
    73   timeout_heap: Thread_Heap.T,
    74   active: (Thread.thread * (Time.time * Time.time * string)) list,
    75   cancelling: (Thread.thread * (Time.time * string)) list,
    76   messages: string list,
    77   store: string list};
    78 
    79 fun make_state manager timeout_heap active cancelling messages store : state =
    80   {manager = manager, timeout_heap = timeout_heap, active = active,
    81     cancelling = cancelling, messages = messages, store = store};
    82 
    83 val global_state = Synchronized.var "atp_manager"
    84   (make_state NONE Thread_Heap.empty [] [] [] []);
    85 
    86 
    87 (* unregister ATP thread *)
    88 
    89 fun unregister (success, message) thread = Synchronized.change global_state
    90   (fn state as {manager, timeout_heap, active, cancelling, messages, store} =>
    91     (case lookup_thread active thread of
    92       SOME (birth_time, _, description) =>
    93         let
    94           val active' = delete_thread thread active;
    95           val cancelling' = (thread, (Time.now (), description)) :: cancelling;
    96           val message' = description ^ "\n" ^ message;
    97           val messages' = message' :: messages;
    98           val store' = message' ::
    99             (if length store <= message_store_limit then store
   100              else #1 (chop message_store_limit store));
   101         in make_state manager timeout_heap active' cancelling' messages' store' end
   102     | NONE => state));
   103 
   104 
   105 (* main manager thread -- only one may exist *)
   106 
   107 val min_wait_time = Time.fromMilliseconds 300;
   108 val max_wait_time = Time.fromSeconds 10;
   109 
   110 fun print_new_messages () =
   111   let val msgs = Synchronized.change_result global_state
   112     (fn {manager, timeout_heap, active, cancelling, messages, store} =>
   113       (messages, make_state manager timeout_heap active cancelling [] store))
   114   in
   115     if null msgs then ()
   116     else priority ("Sledgehammer: " ^ space_implode "\n\n" msgs)
   117   end;
   118 
   119 fun check_thread_manager () = Synchronized.change global_state
   120   (fn state as {manager, timeout_heap, active, cancelling, messages, store} =>
   121     if (case manager of SOME thread => Thread.isActive thread | NONE => false) then state
   122     else let val manager = SOME (SimpleThread.fork false (fn () =>
   123       let
   124         fun time_limit timeout_heap =
   125           (case try Thread_Heap.min timeout_heap of
   126             NONE => Time.+ (Time.now (), max_wait_time)
   127           | SOME (time, _) => time);
   128 
   129         (*action: find threads whose timeout is reached, and interrupt cancelling threads*)
   130         fun action {manager, timeout_heap, active, cancelling, messages, store} =
   131           let val (timeout_threads, timeout_heap') =
   132             Thread_Heap.upto (Time.now (), Thread.self ()) timeout_heap;
   133           in
   134             if null timeout_threads andalso null cancelling
   135             then NONE
   136             else
   137               let
   138                 val _ = List.app (SimpleThread.interrupt o #1) cancelling;
   139                 val cancelling' = filter (Thread.isActive o #1) cancelling;
   140                 val state' = make_state manager timeout_heap' active cancelling' messages store;
   141               in SOME (map #2 timeout_threads, state') end
   142           end;
   143       in
   144         while Synchronized.change_result global_state
   145           (fn state as {timeout_heap, active, cancelling, messages, store, ...} =>
   146             if null active andalso null cancelling andalso null messages
   147             then (false, make_state NONE timeout_heap active cancelling messages store)
   148             else (true, state))
   149         do
   150           (Synchronized.timed_access global_state (SOME o time_limit o #timeout_heap) action
   151             |> these
   152             |> List.app (unregister (false, "Interrupted (reached timeout)"));
   153             print_new_messages ();
   154             (*give threads some time to respond to interrupt*)
   155             OS.Process.sleep min_wait_time)
   156       end))
   157     in make_state manager timeout_heap active cancelling messages store end);
   158 
   159 
   160 (* register ATP thread *)
   161 
   162 fun register birth_time death_time (thread, desc) =
   163  (Synchronized.change global_state
   164     (fn {manager, timeout_heap, active, cancelling, messages, store} =>
   165       let
   166         val timeout_heap' = Thread_Heap.insert (death_time, thread) timeout_heap;
   167         val active' = update_thread (thread, (birth_time, death_time, desc)) active;
   168         val state' = make_state manager timeout_heap' active' cancelling messages store;
   169       in state' end);
   170   check_thread_manager ());
   171 
   172 
   173 
   174 (** user commands **)
   175 
   176 (* kill *)
   177 
   178 fun kill () = Synchronized.change global_state
   179   (fn {manager, timeout_heap, active, cancelling, messages, store} =>
   180     let
   181       val killing = map (fn (th, (_, _, desc)) => (th, (Time.now (), desc))) active;
   182       val state' = make_state manager timeout_heap [] (killing @ cancelling) messages store;
   183     in state' end);
   184 
   185 
   186 (* info *)
   187 
   188 fun seconds time = string_of_int (Time.toSeconds time) ^ "s";
   189 
   190 fun info () =
   191   let
   192     val {active, cancelling, ...} = Synchronized.value global_state;
   193 
   194     val now = Time.now ();
   195     fun running_info (_, (birth_time, death_time, desc)) =
   196       "Running: " ^ seconds (Time.- (now, birth_time)) ^ " -- " ^
   197         seconds (Time.- (death_time, now)) ^ " to live:\n" ^ desc;
   198     fun cancelling_info (_, (deadth_time, desc)) =
   199       "Trying to interrupt thread since " ^ seconds (Time.- (now, deadth_time)) ^ ":\n" ^ desc;
   200 
   201     val running =
   202       if null active then "No ATPs running."
   203       else space_implode "\n\n" ("Running ATPs:" :: map running_info active);
   204     val interrupting =
   205       if null cancelling then ""
   206       else
   207         space_implode "\n\n"
   208           ("Trying to interrupt the following ATPs:" :: map cancelling_info cancelling);
   209 
   210   in writeln (running ^ "\n" ^ interrupting) end;
   211 
   212 fun messages opt_limit =
   213   let
   214     val limit = the_default message_display_limit opt_limit;
   215     val {store, ...} = Synchronized.value global_state;
   216     val header =
   217       "Recent ATP messages" ^
   218         (if length store <= limit then ":" else " (" ^ string_of_int limit ^ " displayed):");
   219   in writeln (space_implode "\n\n" (header :: #1 (chop limit store))) end;
   220 
   221 
   222 
   223 (** The Sledgehammer **)
   224 
   225 (* named provers *)
   226 
   227 fun err_dup_prover name = error ("Duplicate prover: " ^ quote name);
   228 
   229 structure Provers = TheoryDataFun
   230 (
   231   type T = (ATP_Wrapper.prover * stamp) Symtab.table;
   232   val empty = Symtab.empty;
   233   val copy = I;
   234   val extend = I;
   235   fun merge _ tabs : T = Symtab.merge (eq_snd op =) tabs
   236     handle Symtab.DUP dup => err_dup_prover dup;
   237 );
   238 
   239 fun add_prover (name, prover) thy =
   240   Provers.map (Symtab.update_new (name, (prover, stamp ()))) thy
   241     handle Symtab.DUP dup => err_dup_prover dup;
   242 
   243 fun get_prover thy name =
   244   Option.map #1 (Symtab.lookup (Provers.get thy) name);
   245 
   246 fun print_provers thy = Pretty.writeln
   247   (Pretty.strs ("external provers:" :: sort_strings (Symtab.keys (Provers.get thy))));
   248 
   249 
   250 (* start prover thread *)
   251 
   252 fun start_prover name birth_time death_time i proof_state =
   253   (case get_prover (Proof.theory_of proof_state) name of
   254     NONE => warning ("Unknown external prover: " ^ quote name)
   255   | SOME prover =>
   256       let
   257         val {context = ctxt, facts, goal} = Proof.raw_goal proof_state; (* FIXME Proof.goal *)
   258         val desc =
   259           "external prover " ^ quote name ^ " for subgoal " ^ string_of_int i ^ ":\n" ^
   260             Syntax.string_of_term ctxt (Thm.term_of (Thm.cprem_of goal i));
   261 
   262         val _ = SimpleThread.fork true (fn () =>
   263           let
   264             val _ = register birth_time death_time (Thread.self (), desc);
   265             val problem = ATP_Wrapper.problem_of_goal (! full_types) i (ctxt, (facts, goal));
   266             val result =
   267               let val {success, message, ...} = prover (! timeout) problem;
   268               in (success, message) end
   269               handle ResHolClause.TOO_TRIVIAL =>   (* FIXME !? *)
   270                   (true, "Empty clause: Try this command: " ^
   271                     Markup.markup Markup.sendback "apply metis")
   272                 | ERROR msg => (false, "Error: " ^ msg);
   273             val _ = unregister result (Thread.self ());
   274           in () end)
   275       in () end);
   276 
   277 
   278 (* sledghammer for first subgoal *)
   279 
   280 fun sledgehammer names proof_state =
   281   let
   282     val provers = if null names then get_atps () else names;
   283     val birth_time = Time.now ();
   284     val death_time = Time.+ (birth_time, Time.fromSeconds (! timeout));
   285     val _ = kill ();   (*RACE wrt. other invocations of sledgehammer*)
   286     val _ = List.app (fn name => start_prover name birth_time death_time 1 proof_state) provers;
   287   in () end;
   288 
   289 
   290 
   291 (** Isar command syntax **)
   292 
   293 local structure K = OuterKeyword and P = OuterParse in
   294 
   295 val _ =
   296   OuterSyntax.improper_command "atp_kill" "kill all managed provers" K.diag
   297     (Scan.succeed (Toplevel.no_timing o Toplevel.imperative kill));
   298 
   299 val _ =
   300   OuterSyntax.improper_command "atp_info" "print information about managed provers" K.diag
   301     (Scan.succeed (Toplevel.no_timing o Toplevel.imperative info));
   302 
   303 val _ =
   304   OuterSyntax.improper_command "atp_messages" "print recent messages issued by managed provers" K.diag
   305     (Scan.option (P.$$$ "(" |-- P.nat --| P.$$$ ")") >>
   306       (fn limit => Toplevel.no_timing o Toplevel.imperative (fn () => messages limit)));
   307 
   308 val _ =
   309   OuterSyntax.improper_command "print_atps" "print external provers" K.diag
   310     (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_theory o
   311       Toplevel.keep (print_provers o Toplevel.theory_of)));
   312 
   313 val _ =
   314   OuterSyntax.command "sledgehammer" "call all automatic theorem provers" K.diag
   315     (Scan.repeat P.xname >> (fn names => Toplevel.no_timing o Toplevel.unknown_proof o
   316       Toplevel.keep (sledgehammer names o Toplevel.proof_of)));
   317 
   318 end;
   319 
   320 end;
   321