src/Pure/System/isabelle_process.ML
author wenzelm
Wed Jan 16 16:26:36 2013 +0100 (2013-01-16 ago)
changeset 50911 ee7fe4230642
parent 50715 8cfd585b9162
child 51044 890f502f0e89
permissions -rw-r--r--
more explicit treatment of (optional) exception properties, notably for "serial" -- avoid conflict with startPosition = offset;
     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.parse_id (Position.thread_data ()) of
    78     NONE => ()
    79   | SOME id =>
    80       let
    81         val (n, ok) =
    82           Synchronized.change_result command_tracing_messages (fn tab =>
    83             let
    84               val n = the_default 0 (Inttab.lookup tab id) + 1;
    85               val ok = n <= ! tracing_messages;
    86             in ((n, ok), Inttab.update (id, n) tab) end);
    87       in
    88         if ok then ()
    89         else
    90           let
    91             val (text, promise) = Active.dialog_text ();
    92             val _ =
    93               writeln ("Tracing paused.  " ^ text "Stop" ^ ", or continue with next " ^
    94                 text "10" ^ ", " ^ text "100" ^ ", " ^ text "1000" ^ " messages?")
    95             val m = Markup.parse_int (Future.join promise)
    96               handle Fail _ => error "Stopped";
    97           in
    98             Synchronized.change command_tracing_messages
    99               (Inttab.map_default (id, 0) (fn k => k - m))
   100           end
   101       end);
   102 
   103 
   104 (* message channels *)
   105 
   106 local
   107 
   108 fun chunk s = [string_of_int (size s), "\n", s];
   109 
   110 fun message do_flush mbox name raw_props body =
   111   let
   112     val robust_props = map (pairself YXML.embed_controls) raw_props;
   113     val header = YXML.string_of (XML.Elem ((name, robust_props), []));
   114   in Mailbox.send mbox (chunk header @ chunk body, do_flush) end;
   115 
   116 fun standard_message mbox opt_serial name body =
   117   if body = "" then ()
   118   else
   119     message false mbox name
   120       ((case opt_serial of SOME i => cons (Markup.serialN, Markup.print_int i) | _ => I)
   121         (Position.properties_of (Position.thread_data ()))) body;
   122 
   123 fun message_output mbox channel =
   124   let
   125     fun flush () = ignore (try System_Channel.flush channel);
   126     fun loop receive =
   127       (case receive mbox of
   128         SOME (msg, do_flush) =>
   129          (List.app (fn s => System_Channel.output channel s) msg;
   130           if do_flush then flush () else ();
   131           loop (Mailbox.receive_timeout (seconds 0.02)))
   132       | NONE => (flush (); loop (SOME o Mailbox.receive)));
   133   in fn () => loop (SOME o Mailbox.receive) end;
   134 
   135 in
   136 
   137 fun init_channels channel =
   138   let
   139     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdOut, IO.LINE_BUF);
   140     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdErr, IO.LINE_BUF);
   141 
   142     val mbox = Mailbox.create () : (string list * bool) Mailbox.T;
   143     val _ = Simple_Thread.fork false (message_output mbox channel);
   144   in
   145     Output.Private_Hooks.status_fn := standard_message mbox NONE Markup.statusN;
   146     Output.Private_Hooks.report_fn := standard_message mbox NONE Markup.reportN;
   147     Output.Private_Hooks.result_fn :=
   148       (fn (i, s) => standard_message mbox (SOME i) Markup.resultN s);
   149     Output.Private_Hooks.writeln_fn :=
   150       (fn s => standard_message mbox (SOME (serial ())) Markup.writelnN s);
   151     Output.Private_Hooks.tracing_fn :=
   152       (fn s => (update_tracing (); standard_message mbox (SOME (serial ())) Markup.tracingN s));
   153     Output.Private_Hooks.warning_fn :=
   154       (fn s => standard_message mbox (SOME (serial ())) Markup.warningN s);
   155     Output.Private_Hooks.error_fn :=
   156       (fn (i, s) => standard_message mbox (SOME i) Markup.errorN s);
   157     Output.Private_Hooks.protocol_message_fn := message true mbox Markup.protocolN;
   158     Output.Private_Hooks.urgent_message_fn := ! Output.Private_Hooks.writeln_fn;
   159     Output.Private_Hooks.prompt_fn := ignore;
   160     message true mbox Markup.initN [] (Session.welcome ())
   161   end;
   162 
   163 end;
   164 
   165 
   166 (* protocol loop -- uninterruptible *)
   167 
   168 val crashes = Synchronized.var "Isabelle_Process.crashes" ([]: exn list);
   169 
   170 local
   171 
   172 fun recover crash =
   173   (Synchronized.change crashes (cons crash);
   174     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   175 
   176 fun read_chunk channel len =
   177   let
   178     val n =
   179       (case Int.fromString len of
   180         SOME n => n
   181       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   182     val chunk = System_Channel.inputN channel n;
   183     val m = size chunk;
   184   in
   185     if m = n then chunk
   186     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   187   end;
   188 
   189 fun read_command channel =
   190   (case System_Channel.input_line channel of
   191     NONE => raise Runtime.TERMINATE
   192   | SOME line => map (read_chunk channel) (space_explode "," line));
   193 
   194 in
   195 
   196 fun loop channel =
   197   let val continue =
   198     (case read_command channel of
   199       [] => (Output.error_msg "Isabelle process: no input"; true)
   200     | name :: args => (run_command name args; true))
   201     handle Runtime.TERMINATE => false
   202       | exn => (Output.error_msg (ML_Compiler.exn_message exn) handle crash => recover crash; true);
   203   in if continue then loop channel else () end;
   204 
   205 end;
   206 
   207 
   208 (* init *)
   209 
   210 val default_modes1 =
   211   [Syntax_Trans.no_bracketsN, Syntax_Trans.no_type_bracketsN, Graph_Display.active_graphN];
   212 val default_modes2 = [Symbol.xsymbolsN, isabelle_processN, Pretty.symbolicN];
   213 
   214 fun init rendezvous = ignore (Simple_Thread.fork false (fn () =>
   215   let
   216     val _ = OS.Process.sleep (seconds 0.5);  (*yield to raw ML toplevel*)
   217     val _ = Output.physical_stderr Symbol.STX;
   218 
   219     val _ = Printer.show_markup_default := true;
   220     val _ = quick_and_dirty := false;
   221     val _ = Context.set_thread_data NONE;
   222     val _ =
   223       Unsynchronized.change print_mode
   224         (fn mode => (mode @ default_modes1) |> fold (update op =) default_modes2);
   225 
   226     val channel = rendezvous ();
   227     val _ = init_channels channel;
   228   in loop channel end));
   229 
   230 fun init_fifos fifo1 fifo2 = init (fn () => System_Channel.fifo_rendezvous fifo1 fifo2);
   231 fun init_socket name = init (fn () => System_Channel.socket_rendezvous name);
   232 
   233 
   234 (* options *)
   235 
   236 val _ =
   237   protocol_command "Isabelle_Process.options"
   238     (fn [options_yxml] =>
   239       let val options = Options.decode (YXML.parse_body options_yxml) in
   240         Future.ML_statistics := true;
   241         Multithreading.trace := Options.int options "threads_trace";
   242         Multithreading.max_threads := Options.int options "threads";
   243         if Multithreading.max_threads_value () < 2
   244         then Multithreading.max_threads := 2 else ();
   245         Goal.parallel_proofs := (if Options.int options "parallel_proofs" > 0 then 4 else 0);
   246         Goal.parallel_proofs_threshold := Options.int options "parallel_proofs_threshold";
   247         tracing_messages := Options.int options "editor_tracing_messages"
   248       end);
   249 
   250 end;
   251