src/Pure/System/isabelle_process.ML
author wenzelm
Thu Dec 13 19:53:55 2012 +0100 (2012-12-13 ago)
changeset 50505 33c92722cc3d
parent 50503 50f141b34bb7
child 50698 49621c755075
permissions -rw-r--r--
smarter handling of tracing messages: prover process pauses and enters user dialog;
     1 (*  Title:      Pure/System/isabelle_process.ML
     2     Author:     Makarius
     3 
     4 Isabelle process wrapper, based on private fifos for maximum
     5 robustness and performance, or local socket for maximum portability.
     6 
     7 Startup phases:
     8   - raw Posix process startup with uncontrolled output on stdout/stderr
     9   - stderr \002: ML running
    10   - stdin/stdout/stderr freely available (raw ML loop)
    11   - protocol thread initialization
    12   - rendezvous on system channel
    13   - message INIT: channels ready
    14 *)
    15 
    16 signature ISABELLE_PROCESS =
    17 sig
    18   val is_active: unit -> bool
    19   val protocol_command: string -> (string list -> unit) -> unit
    20   val tracing_messages: int Unsynchronized.ref;
    21   val reset_tracing: unit -> unit
    22   val crashes: exn list Synchronized.var
    23   val init_fifos: string -> string -> unit
    24   val init_socket: string -> unit
    25 end;
    26 
    27 structure Isabelle_Process: ISABELLE_PROCESS =
    28 struct
    29 
    30 (* print mode *)
    31 
    32 val isabelle_processN = "isabelle_process";
    33 
    34 fun is_active () = Print_Mode.print_mode_active isabelle_processN;
    35 
    36 val _ = Output.add_mode isabelle_processN Output.default_output Output.default_escape;
    37 val _ = Markup.add_mode isabelle_processN YXML.output_markup;
    38 
    39 
    40 (* protocol commands *)
    41 
    42 local
    43 
    44 val commands =
    45   Synchronized.var "Isabelle_Process.commands" (Symtab.empty: (string list -> unit) Symtab.table);
    46 
    47 in
    48 
    49 fun protocol_command name cmd =
    50   Synchronized.change commands (fn cmds =>
    51    (if not (Symtab.defined cmds name) then ()
    52     else warning ("Redefining Isabelle process command " ^ quote name);
    53     Symtab.update (name, cmd) cmds));
    54 
    55 fun run_command name args =
    56   (case Symtab.lookup (Synchronized.value commands) name of
    57     NONE => error ("Undefined Isabelle process command " ^ quote name)
    58   | SOME cmd =>
    59       (Runtime.debugging cmd args handle exn =>
    60         error ("Isabelle process protocol failure: " ^ quote name ^ "\n" ^
    61           ML_Compiler.exn_message exn)));
    62 
    63 end;
    64 
    65 
    66 (* restricted tracing messages *)
    67 
    68 val tracing_messages = Unsynchronized.ref 100;
    69 
    70 val command_tracing_messages =
    71   Synchronized.var "command_tracing_messages" (Inttab.empty: int Inttab.table);
    72 
    73 fun reset_tracing () =
    74   Synchronized.change command_tracing_messages (K Inttab.empty);
    75 
    76 fun update_tracing () =
    77   (case Position.get_id (Position.thread_data ()) of
    78     NONE => ()
    79   | SOME id =>
    80       let
    81         val i = Markup.parse_int id;
    82         val (n, ok) =
    83           Synchronized.change_result command_tracing_messages (fn tab =>
    84             let
    85               val n = the_default 0 (Inttab.lookup tab i) + 1;
    86               val ok = n <= ! tracing_messages;
    87             in ((n, ok), Inttab.update (i, n) tab) end);
    88       in
    89         if ok then ()
    90         else
    91           let
    92             val (text, promise) = Active.dialog_text ();
    93             val _ =
    94               writeln ("Tracing paused.  " ^ text "Stop" ^ ", or continue with next " ^
    95                 text "10" ^ ", " ^ text "100" ^ ", " ^ text "1000" ^ " messages?")
    96             val m = Markup.parse_int (Future.join promise)
    97               handle Fail _ => error "Stopped";
    98           in
    99             Synchronized.change command_tracing_messages
   100               (Inttab.map_default (i, 0) (fn k => k - m))
   101           end
   102       end);
   103 
   104 
   105 (* message channels *)
   106 
   107 local
   108 
   109 fun chunk s = [string_of_int (size s), "\n", s];
   110 
   111 fun message do_flush mbox name raw_props body =
   112   let
   113     val robust_props = map (pairself YXML.embed_controls) raw_props;
   114     val header = YXML.string_of (XML.Elem ((name, robust_props), []));
   115   in Mailbox.send mbox (chunk header @ chunk body, do_flush) end;
   116 
   117 fun standard_message mbox opt_serial name body =
   118   if body = "" then ()
   119   else
   120     message false mbox name
   121       ((case opt_serial of SOME i => cons (Markup.serialN, Markup.print_int i) | _ => I)
   122         (Position.properties_of (Position.thread_data ()))) body;
   123 
   124 fun message_output mbox channel =
   125   let
   126     fun flush () = ignore (try System_Channel.flush channel);
   127     fun loop receive =
   128       (case receive mbox of
   129         SOME (msg, do_flush) =>
   130          (List.app (fn s => System_Channel.output channel s) msg;
   131           if do_flush then flush () else ();
   132           loop (Mailbox.receive_timeout (seconds 0.02)))
   133       | NONE => (flush (); loop (SOME o Mailbox.receive)));
   134   in fn () => loop (SOME o Mailbox.receive) end;
   135 
   136 in
   137 
   138 fun init_channels channel =
   139   let
   140     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdOut, IO.LINE_BUF);
   141     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdErr, IO.LINE_BUF);
   142 
   143     val mbox = Mailbox.create () : (string list * bool) Mailbox.T;
   144     val _ = Simple_Thread.fork false (message_output mbox channel);
   145   in
   146     Output.Private_Hooks.status_fn := standard_message mbox NONE Markup.statusN;
   147     Output.Private_Hooks.report_fn := standard_message mbox NONE Markup.reportN;
   148     Output.Private_Hooks.result_fn :=
   149       (fn (i, s) => standard_message mbox (SOME i) Markup.resultN s);
   150     Output.Private_Hooks.writeln_fn :=
   151       (fn s => standard_message mbox (SOME (serial ())) Markup.writelnN s);
   152     Output.Private_Hooks.tracing_fn :=
   153       (fn s => (update_tracing (); standard_message mbox (SOME (serial ())) Markup.tracingN s));
   154     Output.Private_Hooks.warning_fn :=
   155       (fn s => standard_message mbox (SOME (serial ())) Markup.warningN s);
   156     Output.Private_Hooks.error_fn :=
   157       (fn (i, s) => standard_message mbox (SOME i) Markup.errorN s);
   158     Output.Private_Hooks.protocol_message_fn := message true mbox Markup.protocolN;
   159     Output.Private_Hooks.urgent_message_fn := ! Output.Private_Hooks.writeln_fn;
   160     Output.Private_Hooks.prompt_fn := ignore;
   161     message true mbox Markup.initN [] (Session.welcome ())
   162   end;
   163 
   164 end;
   165 
   166 
   167 (* protocol loop -- uninterruptible *)
   168 
   169 val crashes = Synchronized.var "Isabelle_Process.crashes" ([]: exn list);
   170 
   171 local
   172 
   173 fun recover crash =
   174   (Synchronized.change crashes (cons crash);
   175     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   176 
   177 fun read_chunk channel len =
   178   let
   179     val n =
   180       (case Int.fromString len of
   181         SOME n => n
   182       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   183     val chunk = System_Channel.inputN channel n;
   184     val m = size chunk;
   185   in
   186     if m = n then chunk
   187     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   188   end;
   189 
   190 fun read_command channel =
   191   (case System_Channel.input_line channel of
   192     NONE => raise Runtime.TERMINATE
   193   | SOME line => map (read_chunk channel) (space_explode "," line));
   194 
   195 in
   196 
   197 fun loop channel =
   198   let val continue =
   199     (case read_command channel of
   200       [] => (Output.error_msg "Isabelle process: no input"; true)
   201     | name :: args => (run_command name args; true))
   202     handle Runtime.TERMINATE => false
   203       | exn => (Output.error_msg (ML_Compiler.exn_message exn) handle crash => recover crash; true);
   204   in if continue then loop channel else () end;
   205 
   206 end;
   207 
   208 
   209 (* init *)
   210 
   211 val default_modes1 = [Syntax_Trans.no_bracketsN, Syntax_Trans.no_type_bracketsN];
   212 val default_modes2 =
   213   [Symbol.xsymbolsN, isabelle_processN, Pretty.symbolicN, Graph_Display.graphview_reportN];
   214 
   215 fun init rendezvous = ignore (Simple_Thread.fork false (fn () =>
   216   let
   217     val _ = OS.Process.sleep (seconds 0.5);  (*yield to raw ML toplevel*)
   218     val _ = Output.physical_stderr Symbol.STX;
   219 
   220     val _ = Printer.show_markup_default := true;
   221     val _ = quick_and_dirty := false;
   222     val _ = Context.set_thread_data NONE;
   223     val _ =
   224       Unsynchronized.change print_mode
   225         (fn mode => (mode @ default_modes1) |> fold (update op =) default_modes2);
   226 
   227     val channel = rendezvous ();
   228     val _ = init_channels channel;
   229   in loop channel end));
   230 
   231 fun init_fifos fifo1 fifo2 = init (fn () => System_Channel.fifo_rendezvous fifo1 fifo2);
   232 fun init_socket name = init (fn () => System_Channel.socket_rendezvous name);
   233 
   234 
   235 (* options *)
   236 
   237 val _ =
   238   protocol_command "Isabelle_Process.options"
   239     (fn [options_yxml] =>
   240       let val options = Options.decode (YXML.parse_body options_yxml) in
   241         Future.ML_statistics := Options.bool options "ML_statistics";
   242         Multithreading.trace := Options.int options "threads_trace";
   243         Multithreading.max_threads := Options.int options "threads";
   244         if Multithreading.max_threads_value () < 2
   245         then Multithreading.max_threads := 2 else ();
   246         Goal.parallel_proofs := (if Options.int options "parallel_proofs" > 0 then 4 else 0);
   247         Goal.parallel_proofs_threshold := Options.int options "parallel_proofs_threshold";
   248         tracing_messages := Options.int options "editor_tracing_messages"
   249       end);
   250 
   251 end;
   252