src/Pure/System/isabelle_process.ML
author wenzelm
Thu, 05 Jan 2012 13:24:29 +0100
changeset 46990 0d7172a7672c
parent 46537 d83797ef0d2d
child 46992 30a69cd8a9a0
permissions -rw-r--r--
tuned signature -- emphasize special nature of protocol commands;
     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   ... message INIT(pid): channels ready
    14   ... message STATUS(keywords)
    15   ... message READY: main loop ready
    16 *)
    17 
    18 signature ISABELLE_PROCESS =
    19 sig
    20   val is_active: unit -> bool
    21   val protocol_command: string -> (string list -> 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: " ^ name ^ "\n" ^ ML_Compiler.exn_message exn)));
    61 
    62 end;
    63 
    64 
    65 (* message channels *)
    66 
    67 local
    68 
    69 fun chunk s = [string_of_int (size s), "\n", s];
    70 
    71 fun message do_flush mbox ch raw_props body =
    72   let
    73     val robust_props = map (pairself YXML.embed_controls) raw_props;
    74     val header = YXML.string_of (XML.Elem ((ch, robust_props), []));
    75   in Mailbox.send mbox (chunk header @ chunk body, do_flush) end;
    76 
    77 fun standard_message mbox opt_serial ch body =
    78   if body = "" then ()
    79   else
    80     message false mbox ch
    81       ((case opt_serial of SOME i => cons (Isabelle_Markup.serialN, string_of_int i) | _ => I)
    82         (Position.properties_of (Position.thread_data ()))) body;
    83 
    84 fun message_output mbox channel =
    85   let
    86     fun flush () = ignore (try System_Channel.flush channel);
    87     fun loop receive =
    88       (case receive mbox of
    89         SOME (msg, do_flush) =>
    90          (List.app (fn s => System_Channel.output channel s) msg;
    91           if do_flush then flush () else ();
    92           loop (Mailbox.receive_timeout (seconds 0.02)))
    93       | NONE => (flush (); loop (SOME o Mailbox.receive)));
    94   in fn () => loop (SOME o Mailbox.receive) end;
    95 
    96 in
    97 
    98 fun setup_channels channel =
    99   let
   100     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdOut, IO.LINE_BUF);
   101     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdErr, IO.LINE_BUF);
   102 
   103     val mbox = Mailbox.create () : (string list * bool) Mailbox.T;
   104     val _ = Simple_Thread.fork false (message_output mbox channel);
   105   in
   106     Output.Private_Hooks.status_fn := standard_message mbox NONE "B";
   107     Output.Private_Hooks.report_fn := standard_message mbox NONE "C";
   108     Output.Private_Hooks.writeln_fn := (fn s => standard_message mbox (SOME (serial ())) "D" s);
   109     Output.Private_Hooks.tracing_fn := (fn s => standard_message mbox (SOME (serial ())) "E" s);
   110     Output.Private_Hooks.warning_fn := (fn s => standard_message mbox (SOME (serial ())) "F" s);
   111     Output.Private_Hooks.error_fn := (fn (i, s) => standard_message mbox (SOME i) "G" s);
   112     Output.Private_Hooks.raw_message_fn := message true mbox "H";
   113     Output.Private_Hooks.urgent_message_fn := ! Output.Private_Hooks.writeln_fn;
   114     Output.Private_Hooks.prompt_fn := ignore;
   115     message true mbox "A" [] (Session.welcome ())
   116   end;
   117 
   118 end;
   119 
   120 
   121 (* protocol loop -- uninterruptible *)
   122 
   123 val crashes = Synchronized.var "Isabelle_Process.crashes" ([]: exn list);
   124 
   125 local
   126 
   127 fun recover crash =
   128   (Synchronized.change crashes (cons crash);
   129     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   130 
   131 fun read_chunk channel len =
   132   let
   133     val n =
   134       (case Int.fromString len of
   135         SOME n => n
   136       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   137     val chunk = System_Channel.inputN channel n;
   138     val m = size chunk;
   139   in
   140     if m = n then chunk
   141     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   142   end;
   143 
   144 fun read_command channel =
   145   (case System_Channel.input_line channel of
   146     NONE => raise Runtime.TERMINATE
   147   | SOME line => map (read_chunk channel) (space_explode "," line));
   148 
   149 in
   150 
   151 fun loop channel =
   152   let val continue =
   153     (case read_command channel of
   154       [] => (Output.error_msg "Isabelle process: no input"; true)
   155     | name :: args => (run_command name args; true))
   156     handle Runtime.TERMINATE => false
   157       | exn => (Output.error_msg (ML_Compiler.exn_message exn) handle crash => recover crash; true);
   158   in if continue then loop channel else () end;
   159 
   160 end;
   161 
   162 
   163 (* init *)
   164 
   165 fun init rendezvous = ignore (Simple_Thread.fork false (fn () =>
   166   let
   167     val _ = OS.Process.sleep (seconds 0.5);  (*yield to raw ML toplevel*)
   168     val _ = Output.physical_stdout Symbol.STX;
   169 
   170     val _ = quick_and_dirty := true;
   171     val _ = Goal.parallel_proofs := 0;
   172     val _ =
   173       if Multithreading.max_threads_value () < 2
   174       then Multithreading.max_threads := 2 else ();
   175     val _ = Context.set_thread_data NONE;
   176     val _ =
   177       Unsynchronized.change print_mode
   178         (fn mode =>
   179           (mode @ [Syntax_Trans.no_bracketsN, Syntax_Trans.no_type_bracketsN])
   180           |> fold (update op =)
   181             [Symbol.xsymbolsN, isabelle_processN, Keyword.keyword_statusN, Pretty.symbolicN]);
   182 
   183     val channel = rendezvous ();
   184     val _ = setup_channels channel;
   185 
   186     val _ = Keyword.status ();
   187     val _ = Thy_Info.status ();
   188     val _ = Output.status (Markup.markup Isabelle_Markup.ready "process ready");
   189   in loop channel end));
   190 
   191 fun init_fifos fifo1 fifo2 = init (fn () => System_Channel.fifo_rendezvous fifo1 fifo2);
   192 fun init_socket name = init (fn () => System_Channel.socket_rendezvous name);
   193 
   194 end;
   195