src/Pure/System/isabelle_process.ML
author wenzelm
Wed Jul 10 20:44:39 2013 +0200 (2013-07-10 ago)
changeset 52578 bd94e26e4388
parent 52560 9e6b59cd5560
child 52580 36aa39694ab4
permissions -rw-r--r--
retain main thread for protocol loop -- no access to raw ML toplevel;
     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 reset_tracing: unit -> unit
    21   val crashes: exn list Synchronized.var
    22   val init_fifos: string -> string -> unit
    23   val init_socket: string -> unit
    24 end;
    25 
    26 structure Isabelle_Process: ISABELLE_PROCESS =
    27 struct
    28 
    29 (* print mode *)
    30 
    31 val isabelle_processN = "isabelle_process";
    32 
    33 fun is_active () = Print_Mode.print_mode_active isabelle_processN;
    34 
    35 val _ = Output.add_mode isabelle_processN Output.default_output Output.default_escape;
    36 val _ = Markup.add_mode isabelle_processN YXML.output_markup;
    37 
    38 
    39 (* protocol commands *)
    40 
    41 local
    42 
    43 val commands =
    44   Synchronized.var "Isabelle_Process.commands" (Symtab.empty: (string list -> unit) Symtab.table);
    45 
    46 in
    47 
    48 fun protocol_command name cmd =
    49   Synchronized.change commands (fn cmds =>
    50    (if not (Symtab.defined cmds name) then ()
    51     else warning ("Redefining Isabelle process command " ^ quote name);
    52     Symtab.update (name, cmd) cmds));
    53 
    54 fun run_command name args =
    55   (case Symtab.lookup (Synchronized.value commands) name of
    56     NONE => error ("Undefined Isabelle process command " ^ quote name)
    57   | SOME cmd =>
    58       (Runtime.debugging cmd args handle exn =>
    59         error ("Isabelle process protocol failure: " ^ quote name ^ "\n" ^
    60           ML_Compiler.exn_message exn)));
    61 
    62 end;
    63 
    64 
    65 (* restricted tracing messages *)
    66 
    67 val tracing_messages =
    68   Synchronized.var "tracing_messages" (Inttab.empty: int Inttab.table);
    69 
    70 fun reset_tracing () =
    71   Synchronized.change tracing_messages (K Inttab.empty);
    72 
    73 fun update_tracing () =
    74   (case Position.parse_id (Position.thread_data ()) of
    75     NONE => ()
    76   | SOME id =>
    77       let
    78         val ok =
    79           Synchronized.change_result tracing_messages (fn tab =>
    80             let
    81               val n = the_default 0 (Inttab.lookup tab id) + 1;
    82               val ok = n <= Options.default_int "editor_tracing_messages";
    83             in (ok, Inttab.update (id, n) tab) end);
    84       in
    85         if ok then ()
    86         else
    87           let
    88             val (text, promise) = Active.dialog_text ();
    89             val _ =
    90               writeln ("Tracing paused.  " ^ text "Stop" ^ ", or continue with next " ^
    91                 text "100" ^ ", " ^ text "1000" ^ ", " ^ text "10000" ^ " messages?")
    92             val m = Markup.parse_int (Future.join promise)
    93               handle Fail _ => error "Stopped";
    94           in
    95             Synchronized.change tracing_messages
    96               (Inttab.map_default (id, 0) (fn k => k - m))
    97           end
    98       end);
    99 
   100 
   101 (* message channels *)
   102 
   103 local
   104 
   105 fun chunk s = [string_of_int (size s), "\n", s];
   106 
   107 fun message do_flush mbox name raw_props body =
   108   let
   109     val robust_props = map (pairself YXML.embed_controls) raw_props;
   110     val header = YXML.string_of (XML.Elem ((name, robust_props), []));
   111   in Mailbox.send mbox (chunk header @ chunk body, do_flush) end;
   112 
   113 fun standard_message mbox opt_serial name body =
   114   if body = "" then ()
   115   else
   116     message false mbox name
   117       ((case opt_serial of SOME i => cons (Markup.serialN, Markup.print_int i) | _ => I)
   118         (Position.properties_of (Position.thread_data ()))) body;
   119 
   120 fun message_output mbox channel =
   121   let
   122     fun flush () = ignore (try System_Channel.flush channel);
   123     fun loop receive =
   124       (case receive mbox of
   125         SOME (msg, do_flush) =>
   126          (List.app (fn s => System_Channel.output channel s) msg;
   127           if do_flush then flush () else ();
   128           loop (Mailbox.receive_timeout (seconds 0.02)))
   129       | NONE => (flush (); loop (SOME o Mailbox.receive)));
   130   in fn () => loop (SOME o Mailbox.receive) end;
   131 
   132 in
   133 
   134 fun init_channels channel =
   135   let
   136     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdOut, IO.LINE_BUF);
   137     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdErr, IO.LINE_BUF);
   138 
   139     val mbox = Mailbox.create () : (string list * bool) Mailbox.T;
   140     val _ = Simple_Thread.fork false (message_output mbox channel);
   141   in
   142     Output.Private_Hooks.status_fn := standard_message mbox NONE Markup.statusN;
   143     Output.Private_Hooks.report_fn := standard_message mbox NONE Markup.reportN;
   144     Output.Private_Hooks.result_fn :=
   145       (fn (i, s) => standard_message mbox (SOME i) Markup.resultN s);
   146     Output.Private_Hooks.writeln_fn :=
   147       (fn s => standard_message mbox (SOME (serial ())) Markup.writelnN s);
   148     Output.Private_Hooks.tracing_fn :=
   149       (fn s => (update_tracing (); standard_message mbox (SOME (serial ())) Markup.tracingN s));
   150     Output.Private_Hooks.warning_fn :=
   151       (fn s => standard_message mbox (SOME (serial ())) Markup.warningN s);
   152     Output.Private_Hooks.error_fn :=
   153       (fn (i, s) => standard_message mbox (SOME i) Markup.errorN s);
   154     Output.Private_Hooks.protocol_message_fn := message true mbox Markup.protocolN;
   155     Output.Private_Hooks.urgent_message_fn := ! Output.Private_Hooks.writeln_fn;
   156     Output.Private_Hooks.prompt_fn := ignore;
   157     message true mbox Markup.initN [] (Session.welcome ())
   158   end;
   159 
   160 end;
   161 
   162 
   163 (* protocol loop -- uninterruptible *)
   164 
   165 val crashes = Synchronized.var "Isabelle_Process.crashes" ([]: exn list);
   166 
   167 local
   168 
   169 fun recover crash =
   170   (Synchronized.change crashes (cons crash);
   171     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   172 
   173 fun read_chunk channel len =
   174   let
   175     val n =
   176       (case Int.fromString len of
   177         SOME n => n
   178       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   179     val chunk = System_Channel.inputN channel n;
   180     val m = size chunk;
   181   in
   182     if m = n then chunk
   183     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   184   end;
   185 
   186 fun read_command channel =
   187   (case System_Channel.input_line channel of
   188     NONE => raise Runtime.TERMINATE
   189   | SOME line => map (read_chunk channel) (space_explode "," line));
   190 
   191 fun worker_guest e =
   192   Future.worker_guest "Isabelle_Process.loop" (Future.new_group NONE) e ();
   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 => (worker_guest (fn () => 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 val init = uninterruptible (fn _ => fn rendezvous =>
   215   let
   216     val _ = Output.physical_stderr Symbol.STX;
   217 
   218     val _ = Printer.show_markup_default := true;
   219     val _ = Context.set_thread_data NONE;
   220     val _ =
   221       Unsynchronized.change print_mode
   222         (fn mode => (mode @ default_modes1) |> fold (update op =) default_modes2);
   223 
   224     val channel = rendezvous ();
   225     val _ = init_channels channel;
   226     val _ = Session.init_protocol_handlers ();
   227   in loop channel end);
   228 
   229 fun init_fifos fifo1 fifo2 = init (fn () => System_Channel.fifo_rendezvous fifo1 fifo2);
   230 fun init_socket name = init (fn () => System_Channel.socket_rendezvous name);
   231 
   232 
   233 (* options *)
   234 
   235 val _ =
   236   protocol_command "Isabelle_Process.options"
   237     (fn [options_yxml] =>
   238       let val options = Options.decode (YXML.parse_body options_yxml) in
   239         Options.set_default options;
   240         Future.ML_statistics := true;
   241         Multithreading.trace := Options.int options "threads_trace";
   242         Multithreading.max_threads := Options.int options "threads";
   243         Goal.skip_proofs := Options.bool options "editor_skip_proofs";
   244         Goal.parallel_proofs := (if Options.int options "parallel_proofs" > 0 then 3 else 0)
   245       end);
   246 
   247 end;
   248