src/Pure/System/isabelle_process.ML
author wenzelm
Wed Jul 10 23:25:28 2013 +0200 (2013-07-10 ago)
changeset 52584 5cad4a5f5615
parent 52583 0a7240d88e09
child 52655 3b2b1ef13979
permissions -rw-r--r--
more abstract message channel;
     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 protocol 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 protocol command " ^ quote name)
    57   | SOME cmd =>
    58       (Runtime.debugging cmd args handle exn =>
    59         error ("Isabelle protocol command 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 msg_channel 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     val msg = chunk header @ chunk body;
   112   in Message_Channel.send msg_channel msg do_flush end;
   113 
   114 in
   115 
   116 fun init_channels channel =
   117   let
   118     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdOut, IO.LINE_BUF);
   119     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdErr, IO.LINE_BUF);
   120 
   121     val msg_channel = Message_Channel.make channel;
   122 
   123     fun standard_message opt_serial name body =
   124       if body = "" then ()
   125       else
   126         message false msg_channel name
   127           ((case opt_serial of SOME i => cons (Markup.serialN, Markup.print_int i) | _ => I)
   128             (Position.properties_of (Position.thread_data ()))) body;
   129   in
   130     Output.Private_Hooks.status_fn := standard_message NONE Markup.statusN;
   131     Output.Private_Hooks.report_fn := standard_message NONE Markup.reportN;
   132     Output.Private_Hooks.result_fn := (fn (i, s) => standard_message (SOME i) Markup.resultN s);
   133     Output.Private_Hooks.writeln_fn :=
   134       (fn s => standard_message (SOME (serial ())) Markup.writelnN s);
   135     Output.Private_Hooks.tracing_fn :=
   136       (fn s => (update_tracing (); standard_message (SOME (serial ())) Markup.tracingN s));
   137     Output.Private_Hooks.warning_fn :=
   138       (fn s => standard_message (SOME (serial ())) Markup.warningN s);
   139     Output.Private_Hooks.error_fn :=
   140       (fn (i, s) => standard_message (SOME i) Markup.errorN s);
   141     Output.Private_Hooks.protocol_message_fn := message true msg_channel Markup.protocolN;
   142     Output.Private_Hooks.urgent_message_fn := ! Output.Private_Hooks.writeln_fn;
   143     Output.Private_Hooks.prompt_fn := ignore;
   144     message true msg_channel Markup.initN [] (Session.welcome ());
   145     msg_channel
   146   end;
   147 
   148 end;
   149 
   150 
   151 (* protocol loop -- uninterruptible *)
   152 
   153 val crashes = Synchronized.var "Isabelle_Process.crashes" ([]: exn list);
   154 
   155 local
   156 
   157 fun recover crash =
   158   (Synchronized.change crashes (cons crash);
   159     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   160 
   161 fun read_chunk channel len =
   162   let
   163     val n =
   164       (case Int.fromString len of
   165         SOME n => n
   166       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   167     val chunk = System_Channel.inputN channel n;
   168     val m = size chunk;
   169   in
   170     if m = n then chunk
   171     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   172   end;
   173 
   174 fun read_command channel =
   175   (case System_Channel.input_line channel of
   176     NONE => raise Runtime.TERMINATE
   177   | SOME line => map (read_chunk channel) (space_explode "," line));
   178 
   179 fun worker_guest e =
   180   Future.worker_guest "Isabelle_Process.loop" (Future.new_group NONE) e ();
   181 
   182 in
   183 
   184 fun loop channel =
   185   let val continue =
   186     (case read_command channel of
   187       [] => (Output.error_msg "Isabelle process: no input"; true)
   188     | name :: args => (worker_guest (fn () => run_command name args); true))
   189     handle Runtime.TERMINATE => false
   190       | exn => (Output.error_msg (ML_Compiler.exn_message exn) handle crash => recover crash; true);
   191   in if continue then loop channel else () end;
   192 
   193 end;
   194 
   195 
   196 (* init *)
   197 
   198 val default_modes1 =
   199   [Syntax_Trans.no_bracketsN, Syntax_Trans.no_type_bracketsN, Graph_Display.active_graphN];
   200 val default_modes2 = [Symbol.xsymbolsN, isabelle_processN, Pretty.symbolicN];
   201 
   202 val init = uninterruptible (fn _ => fn rendezvous =>
   203   let
   204     val _ = Output.physical_stderr Symbol.STX;
   205 
   206     val _ = Printer.show_markup_default := true;
   207     val _ = Context.set_thread_data NONE;
   208     val _ =
   209       Unsynchronized.change print_mode
   210         (fn mode => (mode @ default_modes1) |> fold (update op =) default_modes2);
   211 
   212     val channel = rendezvous ();
   213     val msg_channel = init_channels channel;
   214     val _ = Session.init_protocol_handlers ();
   215     val _ = loop channel;
   216   in Message_Channel.shutdown msg_channel end);
   217 
   218 fun init_fifos fifo1 fifo2 = init (fn () => System_Channel.fifo_rendezvous fifo1 fifo2);
   219 fun init_socket name = init (fn () => System_Channel.socket_rendezvous name);
   220 
   221 
   222 (* options *)
   223 
   224 val _ =
   225   protocol_command "Isabelle_Process.options"
   226     (fn [options_yxml] =>
   227       let val options = Options.decode (YXML.parse_body options_yxml) in
   228         Options.set_default options;
   229         Future.ML_statistics := true;
   230         Multithreading.trace := Options.int options "threads_trace";
   231         Multithreading.max_threads := Options.int options "threads";
   232         Goal.skip_proofs := Options.bool options "editor_skip_proofs";
   233         Goal.parallel_proofs := (if Options.int options "parallel_proofs" > 0 then 3 else 0)
   234       end);
   235 
   236 end;
   237