src/Pure/System/isabelle_process.ML
author wenzelm
Wed, 28 Nov 2012 16:09:05 +0100
changeset 51269 935ac0ad7e83
parent 51216 c26369c9eda6
child 51270 d0ec1f0d1d7d
permissions -rw-r--r--
prefer tight Markup.print_int/parse_int for property values;
     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_limit: int Unsynchronized.ref;
    21   val reset_tracing_limits: 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 (* tracing limit *)
    67 
    68 val tracing_limit = Unsynchronized.ref 1000000;
    69 
    70 val tracing_limits = Synchronized.var "tracing_limits" (Inttab.empty: int Inttab.table);
    71 
    72 fun reset_tracing_limits () = Synchronized.change tracing_limits (K Inttab.empty);
    73 
    74 fun update_tracing_limits msg =
    75   (case Position.get_id (Position.thread_data ()) of
    76     NONE => ()
    77   | SOME id =>
    78       Synchronized.change tracing_limits (fn tab =>
    79         let
    80           val i = Markup.parse_int id;
    81           val n = the_default 0 (Inttab.lookup tab i) + size msg;
    82           val _ = if n > ! tracing_limit then raise Output.TRACING_LIMIT n else ();
    83         in Inttab.update (i, n) tab end));
    84 
    85 
    86 (* message channels *)
    87 
    88 local
    89 
    90 fun chunk s = [string_of_int (size s), "\n", s];
    91 
    92 fun message do_flush mbox name raw_props body =
    93   let
    94     val robust_props = map (pairself YXML.embed_controls) raw_props;
    95     val header = YXML.string_of (XML.Elem ((name, robust_props), []));
    96   in Mailbox.send mbox (chunk header @ chunk body, do_flush) end;
    97 
    98 fun standard_message mbox opt_serial name body =
    99   if body = "" then ()
   100   else
   101     message false mbox name
   102       ((case opt_serial of SOME i => cons (Markup.serialN, Markup.print_int i) | _ => I)
   103         (Position.properties_of (Position.thread_data ()))) body;
   104 
   105 fun message_output mbox channel =
   106   let
   107     fun flush () = ignore (try System_Channel.flush channel);
   108     fun loop receive =
   109       (case receive mbox of
   110         SOME (msg, do_flush) =>
   111          (List.app (fn s => System_Channel.output channel s) msg;
   112           if do_flush then flush () else ();
   113           loop (Mailbox.receive_timeout (seconds 0.02)))
   114       | NONE => (flush (); loop (SOME o Mailbox.receive)));
   115   in fn () => loop (SOME o Mailbox.receive) end;
   116 
   117 in
   118 
   119 fun init_channels channel =
   120   let
   121     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdOut, IO.LINE_BUF);
   122     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdErr, IO.LINE_BUF);
   123 
   124     val mbox = Mailbox.create () : (string list * bool) Mailbox.T;
   125     val _ = Simple_Thread.fork false (message_output mbox channel);
   126   in
   127     Output.Private_Hooks.status_fn := standard_message mbox NONE Markup.statusN;
   128     Output.Private_Hooks.report_fn := standard_message mbox NONE Markup.reportN;
   129     Output.Private_Hooks.writeln_fn :=
   130       (fn s => standard_message mbox (SOME (serial ())) Markup.writelnN s);
   131     Output.Private_Hooks.tracing_fn :=
   132       (fn s => (update_tracing_limits s; standard_message mbox (SOME (serial ())) Markup.tracingN s));
   133     Output.Private_Hooks.warning_fn :=
   134       (fn s => standard_message mbox (SOME (serial ())) Markup.warningN s);
   135     Output.Private_Hooks.error_fn :=
   136       (fn (i, s) => standard_message mbox (SOME i) Markup.errorN s);
   137     Output.Private_Hooks.protocol_message_fn := message true mbox Markup.protocolN;
   138     Output.Private_Hooks.urgent_message_fn := ! Output.Private_Hooks.writeln_fn;
   139     Output.Private_Hooks.prompt_fn := ignore;
   140     message true mbox Markup.initN [] (Session.welcome ())
   141   end;
   142 
   143 end;
   144 
   145 
   146 (* protocol loop -- uninterruptible *)
   147 
   148 val crashes = Synchronized.var "Isabelle_Process.crashes" ([]: exn list);
   149 
   150 local
   151 
   152 fun recover crash =
   153   (Synchronized.change crashes (cons crash);
   154     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   155 
   156 fun read_chunk channel len =
   157   let
   158     val n =
   159       (case Int.fromString len of
   160         SOME n => n
   161       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   162     val chunk = System_Channel.inputN channel n;
   163     val m = size chunk;
   164   in
   165     if m = n then chunk
   166     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   167   end;
   168 
   169 fun read_command channel =
   170   (case System_Channel.input_line channel of
   171     NONE => raise Runtime.TERMINATE
   172   | SOME line => map (read_chunk channel) (space_explode "," line));
   173 
   174 in
   175 
   176 fun loop channel =
   177   let val continue =
   178     (case read_command channel of
   179       [] => (Output.error_msg "Isabelle process: no input"; true)
   180     | name :: args => (run_command name args; true))
   181     handle Runtime.TERMINATE => false
   182       | exn => (Output.error_msg (ML_Compiler.exn_message exn) handle crash => recover crash; true);
   183   in if continue then loop channel else () end;
   184 
   185 end;
   186 
   187 
   188 (* init *)
   189 
   190 val default_modes1 = [Syntax_Trans.no_bracketsN, Syntax_Trans.no_type_bracketsN];
   191 val default_modes2 =
   192   [Symbol.xsymbolsN, isabelle_processN, Pretty.symbolicN, Graph_Display.graphview_reportN];
   193 
   194 fun init rendezvous = ignore (Simple_Thread.fork false (fn () =>
   195   let
   196     val _ = OS.Process.sleep (seconds 0.5);  (*yield to raw ML toplevel*)
   197     val _ = Output.physical_stderr Symbol.STX;
   198 
   199     val _ = Printer.show_markup_default := true;
   200     val _ = quick_and_dirty := false;
   201     val _ = Context.set_thread_data NONE;
   202     val _ =
   203       Unsynchronized.change print_mode
   204         (fn mode => (mode @ default_modes1) |> fold (update op =) default_modes2);
   205 
   206     val channel = rendezvous ();
   207     val _ = init_channels channel;
   208   in loop channel end));
   209 
   210 fun init_fifos fifo1 fifo2 = init (fn () => System_Channel.fifo_rendezvous fifo1 fifo2);
   211 fun init_socket name = init (fn () => System_Channel.socket_rendezvous name);
   212 
   213 
   214 (* options *)
   215 
   216 val _ =
   217   protocol_command "Isabelle_Process.options"
   218     (fn [options_yxml] =>
   219       let val options = Options.decode (YXML.parse_body options_yxml) in
   220         Multithreading.trace := Options.int options "threads_trace";
   221         Multithreading.max_threads := Options.int options "threads";
   222         if Multithreading.max_threads_value () < 2
   223         then Multithreading.max_threads := 2 else ();
   224         Goal.parallel_proofs := (if Options.int options "parallel_proofs" > 0 then 4 else 0);
   225         Goal.parallel_proofs_threshold := Options.int options "parallel_proofs_threshold";
   226         tracing_limit := Options.int options "editor_tracing_limit"
   227       end);
   228 
   229 end;
   230