src/Pure/System/isabelle_process.ML
author wenzelm
Thu Sep 22 20:33:08 2011 +0200 (2011-09-22 ago)
changeset 45029 63144ea111f7
parent 45028 d608dd8cd409
child 45057 86c9b73158a8
permissions -rw-r--r--
abstract System_Channel in ML (cf. Scala version);
back to TextIO for fifo, which is more stable in Poly/ML 5.4.x;
explicit block buffering -- BinIO might be subject to old Poly/ML defaults;
     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.
     6 
     7 Startup phases:
     8   . raw Posix process startup with uncontrolled output on stdout/stderr
     9   . stdout \002: ML running
    10   .. stdin/stdout/stderr freely available (raw ML loop)
    11   .. protocol thread initialization
    12   ... rendezvous on system channel
    13   ... out_fifo INIT(pid): channels ready
    14   ... out_fifo STATUS(keywords)
    15   ... out_fifo READY: main loop ready
    16 *)
    17 
    18 signature ISABELLE_PROCESS =
    19 sig
    20   val is_active: unit -> bool
    21   val add_command: string -> (string list -> unit) -> unit
    22   val command: string -> string list -> unit
    23   val crashes: exn list Synchronized.var
    24   val init_fifos: string -> string -> unit
    25   val init_socket: string -> unit
    26 end;
    27 
    28 structure Isabelle_Process: ISABELLE_PROCESS =
    29 struct
    30 
    31 (* print mode *)
    32 
    33 val isabelle_processN = "isabelle_process";
    34 
    35 fun is_active () = Print_Mode.print_mode_active isabelle_processN;
    36 
    37 val _ = Output.add_mode isabelle_processN Output.default_output Output.default_escape;
    38 val _ = Markup.add_mode isabelle_processN YXML.output_markup;
    39 
    40 
    41 (* commands *)
    42 
    43 local
    44 
    45 val commands =
    46   Synchronized.var "Isabelle_Process.commands" (Symtab.empty: (string list -> unit) Symtab.table);
    47 
    48 in
    49 
    50 fun add_command name cmd =
    51   Synchronized.change commands (fn cmds =>
    52    (if not (Symtab.defined cmds name) then ()
    53     else warning ("Redefining Isabelle process command " ^ quote name);
    54     Symtab.update (name, cmd) cmds));
    55 
    56 fun command name args =
    57   (case Symtab.lookup (Synchronized.value commands) name of
    58     NONE => error ("Undefined Isabelle process command " ^ quote name)
    59   | SOME cmd => cmd args);
    60 
    61 end;
    62 
    63 
    64 (* message channels *)
    65 
    66 local
    67 
    68 fun chunk s = [string_of_int (size s), "\n", s];
    69 
    70 fun message do_flush mbox ch raw_props body =
    71   let
    72     val robust_props = map (pairself YXML.embed_controls) raw_props;
    73     val header = YXML.string_of (XML.Elem ((ch, robust_props), []));
    74   in Mailbox.send mbox (chunk header @ chunk body, do_flush) end;
    75 
    76 fun standard_message mbox opt_serial ch body =
    77   if body = "" then ()
    78   else
    79     message false mbox ch
    80       ((case opt_serial of SOME i => cons (Markup.serialN, string_of_int i) | _ => I)
    81         (Position.properties_of (Position.thread_data ()))) body;
    82 
    83 fun message_output mbox channel =
    84   let
    85     fun flush () = ignore (try System_Channel.flush channel);
    86     fun loop receive =
    87       (case receive mbox of
    88         SOME (msg, do_flush) =>
    89          (List.app (fn s => System_Channel.output channel s) msg;
    90           if do_flush then flush () else ();
    91           loop (Mailbox.receive_timeout (seconds 0.02)))
    92       | NONE => (flush (); loop (SOME o Mailbox.receive)));
    93   in fn () => loop (SOME o Mailbox.receive) end;
    94 
    95 in
    96 
    97 fun setup_channels channel =
    98   let
    99     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdOut, IO.LINE_BUF);
   100     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdErr, IO.LINE_BUF);
   101 
   102     val mbox = Mailbox.create () : (string list * bool) Mailbox.T;
   103     val _ = Simple_Thread.fork false (message_output mbox channel);
   104   in
   105     Output.Private_Hooks.status_fn := standard_message mbox NONE "B";
   106     Output.Private_Hooks.report_fn := standard_message mbox NONE "C";
   107     Output.Private_Hooks.writeln_fn := (fn s => standard_message mbox (SOME (serial ())) "D" s);
   108     Output.Private_Hooks.tracing_fn := (fn s => standard_message mbox (SOME (serial ())) "E" s);
   109     Output.Private_Hooks.warning_fn := (fn s => standard_message mbox (SOME (serial ())) "F" s);
   110     Output.Private_Hooks.error_fn := (fn (i, s) => standard_message mbox (SOME i) "G" s);
   111     Output.Private_Hooks.raw_message_fn := message true mbox "H";
   112     Output.Private_Hooks.urgent_message_fn := ! Output.Private_Hooks.writeln_fn;
   113     Output.Private_Hooks.prompt_fn := ignore;
   114     message true mbox "A" [] (Session.welcome ())
   115   end;
   116 
   117 end;
   118 
   119 
   120 (* protocol loop -- uninterruptible *)
   121 
   122 val crashes = Synchronized.var "Isabelle_Process.crashes" ([]: exn list);
   123 
   124 local
   125 
   126 fun recover crash =
   127   (Synchronized.change crashes (cons crash);
   128     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   129 
   130 fun read_chunk channel len =
   131   let
   132     val n =
   133       (case Int.fromString len of
   134         SOME n => n
   135       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   136     val chunk = System_Channel.inputN channel n;
   137     val m = size chunk;
   138   in
   139     if m = n then chunk
   140     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   141   end;
   142 
   143 fun read_command channel =
   144   (case System_Channel.input_line channel of
   145     NONE => raise Runtime.TERMINATE
   146   | SOME line => map (read_chunk channel) (space_explode "," line));
   147 
   148 fun run_command name args =
   149   Runtime.debugging (command name) args
   150     handle exn =>
   151       error ("Isabelle process command failure: " ^ name ^ "\n" ^ ML_Compiler.exn_message exn);
   152 
   153 in
   154 
   155 fun loop channel =
   156   let val continue =
   157     (case read_command channel of
   158       [] => (Output.error_msg "Isabelle process: no input"; true)
   159     | name :: args => (run_command name args; true))
   160     handle Runtime.TERMINATE => false
   161       | exn => (Output.error_msg (ML_Compiler.exn_message exn) handle crash => recover crash; true);
   162   in if continue then loop channel else () end;
   163 
   164 end;
   165 
   166 
   167 (* init *)
   168 
   169 fun init rendezvous = ignore (Simple_Thread.fork false (fn () =>
   170   let
   171     val _ = OS.Process.sleep (seconds 0.5);  (*yield to raw ML toplevel*)
   172     val _ = Output.physical_stdout Symbol.STX;
   173 
   174     val _ = quick_and_dirty := true;
   175     val _ = Goal.parallel_proofs := 0;
   176     val _ =
   177       if Multithreading.max_threads_value () < 2
   178       then Multithreading.max_threads := 2 else ();
   179     val _ = Context.set_thread_data NONE;
   180     val _ =
   181       Unsynchronized.change print_mode
   182         (fold (update op =)
   183           [Symbol.xsymbolsN, isabelle_processN, Keyword.keyword_statusN, Pretty.symbolicN]);
   184 
   185     val channel = rendezvous ();
   186     val _ = setup_channels channel;
   187 
   188     val _ = Keyword.status ();
   189     val _ = Thy_Info.status ();
   190     val _ = Output.status (Markup.markup Markup.ready "process ready");
   191   in loop channel end));
   192 
   193 fun init_fifos fifo1 fifo2 = init (fn () => System_Channel.fifo_rendezvous fifo1 fifo2);
   194 fun init_socket name = init (fn () => System_Channel.socket_rendezvous name);
   195 
   196 end;
   197