src/Pure/System/isabelle_process.scala
author wenzelm
Fri May 07 22:00:23 2010 +0200 (2010-05-07 ago)
changeset 36735 42b7f881f5fc
parent 34215 f0322b595146
child 37038 1ce1b19f78f4
permissions -rw-r--r--
output symbolic pretty printing markup and format in the front end;
wenzelm@30173
     1
/*  Title:      Pure/System/isabelle_process.ML
wenzelm@27949
     2
    Author:     Makarius
wenzelm@27963
     3
    Options:    :folding=explicit:collapseFolds=1:
wenzelm@27949
     4
wenzelm@27949
     5
Isabelle process management -- always reactive due to multi-threaded I/O.
wenzelm@27949
     6
*/
wenzelm@27949
     7
wenzelm@27949
     8
package isabelle
wenzelm@27949
     9
wenzelm@27955
    10
import java.util.concurrent.LinkedBlockingQueue
wenzelm@28045
    11
import java.io.{BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter,
wenzelm@28056
    12
  InputStream, OutputStream, IOException}
wenzelm@27949
    13
wenzelm@32474
    14
import scala.actors.Actor
wenzelm@32474
    15
import Actor._
wenzelm@27949
    16
wenzelm@27973
    17
wenzelm@32474
    18
object Isabelle_Process
wenzelm@32474
    19
{
wenzelm@27949
    20
  /* results */
wenzelm@27949
    21
wenzelm@27949
    22
  object Kind extends Enumeration {
wenzelm@28344
    23
    //{{{ values and codes
wenzelm@28344
    24
    // internal system notification
wenzelm@28344
    25
    val SYSTEM = Value("SYSTEM")
wenzelm@27949
    26
    // Posix channels/events
wenzelm@27949
    27
    val STDIN = Value("STDIN")
wenzelm@27949
    28
    val STDOUT = Value("STDOUT")
wenzelm@27949
    29
    val SIGNAL = Value("SIGNAL")
wenzelm@27949
    30
    val EXIT = Value("EXIT")
wenzelm@27949
    31
    // Isabelle messages
wenzelm@28344
    32
    val INIT = Value("INIT")
wenzelm@28344
    33
    val STATUS = Value("STATUS")
wenzelm@27949
    34
    val WRITELN = Value("WRITELN")
wenzelm@27949
    35
    val PRIORITY = Value("PRIORITY")
wenzelm@27949
    36
    val TRACING = Value("TRACING")
wenzelm@27949
    37
    val WARNING = Value("WARNING")
wenzelm@27949
    38
    val ERROR = Value("ERROR")
wenzelm@27949
    39
    val DEBUG = Value("DEBUG")
wenzelm@28344
    40
    // messages codes
wenzelm@28344
    41
    val code = Map(
wenzelm@28344
    42
      ('A' : Int) -> Kind.INIT,
wenzelm@28344
    43
      ('B' : Int) -> Kind.STATUS,
wenzelm@28344
    44
      ('C' : Int) -> Kind.WRITELN,
wenzelm@28344
    45
      ('D' : Int) -> Kind.PRIORITY,
wenzelm@28344
    46
      ('E' : Int) -> Kind.TRACING,
wenzelm@28344
    47
      ('F' : Int) -> Kind.WARNING,
wenzelm@28344
    48
      ('G' : Int) -> Kind.ERROR,
wenzelm@28344
    49
      ('H' : Int) -> Kind.DEBUG,
wenzelm@28344
    50
      ('0' : Int) -> Kind.SYSTEM,
wenzelm@28344
    51
      ('1' : Int) -> Kind.STDIN,
wenzelm@28344
    52
      ('2' : Int) -> Kind.STDOUT,
wenzelm@28344
    53
      ('3' : Int) -> Kind.SIGNAL,
wenzelm@28344
    54
      ('4' : Int) -> Kind.EXIT)
wenzelm@29522
    55
    // message markup
wenzelm@29522
    56
    val markup = Map(
wenzelm@29522
    57
      Kind.INIT -> Markup.INIT,
wenzelm@29522
    58
      Kind.STATUS -> Markup.STATUS,
wenzelm@29522
    59
      Kind.WRITELN -> Markup.WRITELN,
wenzelm@29522
    60
      Kind.PRIORITY -> Markup.PRIORITY,
wenzelm@29522
    61
      Kind.TRACING -> Markup.TRACING,
wenzelm@29522
    62
      Kind.WARNING -> Markup.WARNING,
wenzelm@29522
    63
      Kind.ERROR -> Markup.ERROR,
wenzelm@29522
    64
      Kind.DEBUG -> Markup.DEBUG,
wenzelm@29522
    65
      Kind.SYSTEM -> Markup.SYSTEM,
wenzelm@29522
    66
      Kind.STDIN -> Markup.STDIN,
wenzelm@29522
    67
      Kind.STDOUT -> Markup.STDOUT,
wenzelm@29522
    68
      Kind.SIGNAL -> Markup.SIGNAL,
wenzelm@29522
    69
      Kind.EXIT -> Markup.EXIT)
wenzelm@27949
    70
    //}}}
wenzelm@27949
    71
    def is_raw(kind: Value) =
wenzelm@28045
    72
      kind == STDOUT
wenzelm@27990
    73
    def is_control(kind: Value) =
wenzelm@28344
    74
      kind == SYSTEM ||
wenzelm@27990
    75
      kind == SIGNAL ||
wenzelm@28344
    76
      kind == EXIT
wenzelm@27949
    77
    def is_system(kind: Value) =
wenzelm@28344
    78
      kind == SYSTEM ||
wenzelm@27949
    79
      kind == STDIN ||
wenzelm@27949
    80
      kind == SIGNAL ||
wenzelm@27949
    81
      kind == EXIT ||
wenzelm@28498
    82
      kind == STATUS
wenzelm@27949
    83
  }
wenzelm@27949
    84
wenzelm@34100
    85
  class Result(val kind: Kind.Value, val props: List[(String, String)], val body: List[XML.Tree])
wenzelm@34100
    86
  {
wenzelm@34100
    87
    def message = XML.Elem(Markup.MESSAGE, (Markup.CLASS, Kind.markup(kind)) :: props, body)
wenzelm@34100
    88
wenzelm@34100
    89
    override def toString: String =
wenzelm@34100
    90
    {
wenzelm@29522
    91
      val res =
wenzelm@34100
    92
        if (kind == Kind.STATUS) body.map(_.toString).mkString
wenzelm@36735
    93
        else Pretty.string_of(body)
wenzelm@29572
    94
      if (props.isEmpty)
wenzelm@29572
    95
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    96
      else
wenzelm@29572
    97
        kind.toString + " " +
wenzelm@29572
    98
          (for ((x, y) <- props) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    99
    }
wenzelm@29192
   100
    def is_raw = Kind.is_raw(kind)
wenzelm@29192
   101
    def is_control = Kind.is_control(kind)
wenzelm@29192
   102
    def is_system = Kind.is_system(kind)
wenzelm@34109
   103
wenzelm@34215
   104
    def is_ready = kind == Kind.STATUS && body == List(XML.Elem(Markup.READY, Nil, Nil))
wenzelm@34215
   105
wenzelm@34117
   106
    def cache(c: XML.Cache): Result =
wenzelm@34117
   107
      new Result(kind, c.cache_props(props), c.cache_trees(body))
wenzelm@27973
   108
  }
wenzelm@27973
   109
}
wenzelm@27973
   110
wenzelm@27973
   111
wenzelm@34100
   112
class Isabelle_Process(system: Isabelle_System, receiver: Actor, args: String*)
wenzelm@29192
   113
{
wenzelm@31797
   114
  import Isabelle_Process._
wenzelm@29194
   115
wenzelm@27973
   116
wenzelm@29192
   117
  /* demo constructor */
wenzelm@27973
   118
wenzelm@29192
   119
  def this(args: String*) =
wenzelm@32474
   120
    this(new Isabelle_System,
wenzelm@34213
   121
      actor { loop { react { case res => Console.println(res) } } }, args: _*)
wenzelm@29174
   122
wenzelm@29174
   123
wenzelm@27973
   124
  /* process information */
wenzelm@27973
   125
wenzelm@29648
   126
  @volatile private var proc: Process = null
wenzelm@29648
   127
  @volatile private var closing = false
wenzelm@29648
   128
  @volatile private var pid: String = null
wenzelm@27973
   129
wenzelm@27973
   130
wenzelm@27973
   131
  /* results */
wenzelm@27949
   132
wenzelm@34100
   133
  private def put_result(kind: Kind.Value, props: List[(String, String)], body: List[XML.Tree])
wenzelm@29572
   134
  {
wenzelm@29572
   135
    if (kind == Kind.INIT) {
wenzelm@34214
   136
      for ((Markup.PID, p) <- props) pid = p
wenzelm@27963
   137
    }
wenzelm@34100
   138
    receiver ! new Result(kind, props, body)
wenzelm@34100
   139
  }
wenzelm@34100
   140
wenzelm@34100
   141
  private def put_result(kind: Kind.Value, text: String)
wenzelm@34100
   142
  {
wenzelm@34100
   143
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   144
  }
wenzelm@27992
   145
wenzelm@27973
   146
wenzelm@27973
   147
  /* signals */
wenzelm@27973
   148
wenzelm@27973
   149
  def interrupt() = synchronized {
wenzelm@27993
   150
    if (proc == null) error("Cannot interrupt Isabelle: no process")
wenzelm@34100
   151
    if (pid == null) put_result(Kind.SYSTEM, "Cannot interrupt: unknown pid")
wenzelm@27973
   152
    else {
wenzelm@27973
   153
      try {
wenzelm@34100
   154
        if (system.execute(true, "kill", "-INT", pid).waitFor == 0)
wenzelm@34100
   155
          put_result(Kind.SIGNAL, "INT")
wenzelm@27990
   156
        else
wenzelm@34100
   157
          put_result(Kind.SYSTEM, "Cannot interrupt: kill command failed")
wenzelm@27973
   158
      }
wenzelm@27993
   159
      catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   160
    }
wenzelm@27973
   161
  }
wenzelm@27973
   162
wenzelm@27973
   163
  def kill() = synchronized {
wenzelm@27993
   164
    if (proc == 0) error("Cannot kill Isabelle: no process")
wenzelm@27973
   165
    else {
wenzelm@27973
   166
      try_close()
wenzelm@27990
   167
      Thread.sleep(500)
wenzelm@34100
   168
      put_result(Kind.SIGNAL, "KILL")
wenzelm@27973
   169
      proc.destroy
wenzelm@27973
   170
      proc = null
wenzelm@27990
   171
      pid = null
wenzelm@27973
   172
    }
wenzelm@27973
   173
  }
wenzelm@27973
   174
wenzelm@27949
   175
wenzelm@27949
   176
  /* output being piped into the process */
wenzelm@27949
   177
wenzelm@27990
   178
  private val output = new LinkedBlockingQueue[String]
wenzelm@27949
   179
wenzelm@28045
   180
  private def output_raw(text: String) = synchronized {
wenzelm@27993
   181
    if (proc == null) error("Cannot output to Isabelle: no process")
wenzelm@27993
   182
    if (closing) error("Cannot output to Isabelle: already closing")
wenzelm@27955
   183
    output.put(text)
wenzelm@27949
   184
  }
wenzelm@27949
   185
wenzelm@28303
   186
  def output_sync(text: String) =
wenzelm@28045
   187
    output_raw(" \\<^sync>\n; " + text + " \\<^sync>;\n")
wenzelm@27949
   188
wenzelm@27963
   189
wenzelm@27963
   190
  def command(text: String) =
wenzelm@32448
   191
    output_sync("Isabelle.command " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   192
wenzelm@29572
   193
  def command(props: List[(String, String)], text: String) =
wenzelm@32448
   194
    output_sync("Isabelle.command " + Isabelle_Syntax.encode_properties(props) + " " +
wenzelm@32448
   195
      Isabelle_Syntax.encode_string(text))
wenzelm@27949
   196
wenzelm@27963
   197
  def ML(text: String) =
wenzelm@32448
   198
    output_sync("ML_val " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   199
wenzelm@27949
   200
  def close() = synchronized {    // FIXME watchdog/timeout
wenzelm@27949
   201
    output_raw("\u0000")
wenzelm@27949
   202
    closing = true
wenzelm@27949
   203
  }
wenzelm@27949
   204
wenzelm@27949
   205
  def try_close() = synchronized {
wenzelm@27949
   206
    if (proc != null && !closing) {
wenzelm@27949
   207
      try { close() }
wenzelm@27993
   208
      catch { case _: RuntimeException => }
wenzelm@27949
   209
    }
wenzelm@27949
   210
  }
wenzelm@27949
   211
wenzelm@27949
   212
wenzelm@27949
   213
  /* stdin */
wenzelm@27949
   214
wenzelm@34213
   215
  private class Stdin_Thread(out_stream: OutputStream) extends Thread("isabelle: stdin") {
wenzelm@27949
   216
    override def run() = {
wenzelm@34201
   217
      val writer = new BufferedWriter(new OutputStreamWriter(out_stream, Standard_System.charset))
wenzelm@27949
   218
      var finished = false
wenzelm@27949
   219
      while (!finished) {
wenzelm@27949
   220
        try {
wenzelm@27949
   221
          //{{{
wenzelm@27955
   222
          val s = output.take
wenzelm@27949
   223
          if (s == "\u0000") {
wenzelm@27949
   224
            writer.close
wenzelm@27949
   225
            finished = true
wenzelm@27949
   226
          }
wenzelm@27949
   227
          else {
wenzelm@34100
   228
            put_result(Kind.STDIN, s)
wenzelm@27949
   229
            writer.write(s)
wenzelm@27949
   230
            writer.flush
wenzelm@27949
   231
          }
wenzelm@27949
   232
          //}}}
wenzelm@27949
   233
        }
wenzelm@27949
   234
        catch {
wenzelm@34100
   235
          case e: IOException => put_result(Kind.SYSTEM, "Stdin thread: " + e.getMessage)
wenzelm@27949
   236
        }
wenzelm@27949
   237
      }
wenzelm@34100
   238
      put_result(Kind.SYSTEM, "Stdin thread terminated")
wenzelm@27949
   239
    }
wenzelm@27949
   240
  }
wenzelm@27949
   241
wenzelm@27949
   242
wenzelm@27949
   243
  /* stdout */
wenzelm@27949
   244
wenzelm@34213
   245
  private class Stdout_Thread(in_stream: InputStream) extends Thread("isabelle: stdout") {
wenzelm@27949
   246
    override def run() = {
wenzelm@34201
   247
      val reader = new BufferedReader(new InputStreamReader(in_stream, Standard_System.charset))
wenzelm@28045
   248
      var result = new StringBuilder(100)
wenzelm@27949
   249
wenzelm@27949
   250
      var finished = false
wenzelm@27949
   251
      while (!finished) {
wenzelm@27949
   252
        try {
wenzelm@28045
   253
          //{{{
wenzelm@28045
   254
          var c = -1
wenzelm@28045
   255
          var done = false
wenzelm@28045
   256
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   257
            c = reader.read
wenzelm@28045
   258
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   259
            else done = true
wenzelm@28045
   260
          }
wenzelm@28045
   261
          if (result.length > 0) {
wenzelm@34100
   262
            put_result(Kind.STDOUT, result.toString)
wenzelm@28045
   263
            result.length = 0
wenzelm@27949
   264
          }
wenzelm@27949
   265
          else {
wenzelm@28045
   266
            reader.close
wenzelm@28045
   267
            finished = true
wenzelm@28045
   268
            try_close()
wenzelm@27949
   269
          }
wenzelm@28045
   270
          //}}}
wenzelm@27963
   271
        }
wenzelm@27963
   272
        catch {
wenzelm@34100
   273
          case e: IOException => put_result(Kind.SYSTEM, "Stdout thread: " + e.getMessage)
wenzelm@27949
   274
        }
wenzelm@27949
   275
      }
wenzelm@34100
   276
      put_result(Kind.SYSTEM, "Stdout thread terminated")
wenzelm@27949
   277
    }
wenzelm@27949
   278
  }
wenzelm@27949
   279
wenzelm@27949
   280
wenzelm@28045
   281
  /* messages */
wenzelm@27949
   282
wenzelm@34213
   283
  private class Message_Thread(fifo: String) extends Thread("isabelle: messages")
wenzelm@34100
   284
  {
wenzelm@34100
   285
    private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@34100
   286
    override def run()
wenzelm@34100
   287
    {
wenzelm@34100
   288
      val stream = system.fifo_stream(fifo)
wenzelm@34100
   289
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   290
      var c = -1
wenzelm@27949
   291
wenzelm@34100
   292
      def read_chunk(): List[XML.Tree] =
wenzelm@34100
   293
      {
wenzelm@34100
   294
        //{{{
wenzelm@34100
   295
        // chunk size
wenzelm@34100
   296
        var n = 0
wenzelm@34100
   297
        c = stream.read
wenzelm@34100
   298
        while (48 <= c && c <= 57) {
wenzelm@34100
   299
          n = 10 * n + (c - 48)
wenzelm@34100
   300
          c = stream.read
wenzelm@34100
   301
        }
wenzelm@34100
   302
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   303
wenzelm@34100
   304
        // chunk content
wenzelm@34100
   305
        val buf =
wenzelm@34100
   306
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   307
          else new Array[Byte](n)
wenzelm@34100
   308
wenzelm@34100
   309
        var i = 0
wenzelm@34100
   310
        var m = 0
wenzelm@34100
   311
        do {
wenzelm@34100
   312
          m = stream.read(buf, i, n - i)
wenzelm@34100
   313
          i += m
wenzelm@34100
   314
        } while (m > 0 && n > i)
wenzelm@34100
   315
wenzelm@34100
   316
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   317
wenzelm@34100
   318
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   319
        //}}}
wenzelm@34100
   320
      }
wenzelm@34100
   321
wenzelm@34100
   322
      do {
wenzelm@27949
   323
        try {
wenzelm@34100
   324
          //{{{
wenzelm@34100
   325
          c = stream.read
wenzelm@34100
   326
          var non_sync = 0
wenzelm@34100
   327
          while (c >= 0 && c != 2) {
wenzelm@34100
   328
            non_sync += 1
wenzelm@34100
   329
            c = stream.read
wenzelm@28063
   330
          }
wenzelm@34100
   331
          if (non_sync > 0)
wenzelm@34100
   332
            throw new Protocol_Error("lost synchronization -- skipping " + non_sync + " bytes")
wenzelm@34100
   333
          if (c == 2) {
wenzelm@34100
   334
            val header = read_chunk()
wenzelm@34100
   335
            val body = read_chunk()
wenzelm@34100
   336
            header match {
wenzelm@34100
   337
              case List(XML.Elem(name, props, Nil))
wenzelm@34100
   338
                  if name.size == 1 && Kind.code.isDefinedAt(name(0)) =>
wenzelm@34100
   339
                put_result(Kind.code(name(0)), props, body)
wenzelm@34100
   340
              case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   341
            }
wenzelm@27949
   342
          }
wenzelm@34100
   343
          //}}}
wenzelm@27963
   344
        }
wenzelm@28063
   345
        catch {
wenzelm@34100
   346
          case e: IOException =>
wenzelm@34100
   347
            put_result(Kind.SYSTEM, "Cannot read message:\n" + e.getMessage)
wenzelm@34100
   348
          case e: Protocol_Error =>
wenzelm@34100
   349
            put_result(Kind.SYSTEM, "Malformed message:\n" + e.getMessage)
wenzelm@28063
   350
        }
wenzelm@34100
   351
      } while (c != -1)
wenzelm@34100
   352
      stream.close
wenzelm@34100
   353
      try_close()
wenzelm@34100
   354
wenzelm@34100
   355
      put_result(Kind.SYSTEM, "Message thread terminated")
wenzelm@27949
   356
    }
wenzelm@27949
   357
  }
wenzelm@27949
   358
wenzelm@27949
   359
wenzelm@29192
   360
wenzelm@27949
   361
  /** main **/
wenzelm@27949
   362
wenzelm@27949
   363
  {
wenzelm@29192
   364
    /* messages */
wenzelm@28045
   365
wenzelm@34100
   366
    val message_fifo = system.mk_fifo()
wenzelm@34100
   367
    def rm_fifo() = system.rm_fifo(message_fifo)
wenzelm@28045
   368
wenzelm@34213
   369
    val message_thread = new Message_Thread(message_fifo)
wenzelm@28063
   370
    message_thread.start
wenzelm@28045
   371
wenzelm@28045
   372
wenzelm@27973
   373
    /* exec process */
wenzelm@27963
   374
wenzelm@27973
   375
    try {
wenzelm@34100
   376
      val cmdline = List(system.getenv_strict("ISABELLE_PROCESS"), "-W", message_fifo) ++ args
wenzelm@34100
   377
      proc = system.execute(true, cmdline: _*)
wenzelm@27949
   378
    }
wenzelm@27993
   379
    catch {
wenzelm@28063
   380
      case e: IOException =>
wenzelm@28063
   381
        rm_fifo()
wenzelm@28063
   382
        error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@27993
   383
    }
wenzelm@27949
   384
wenzelm@27949
   385
wenzelm@28045
   386
    /* stdin/stdout */
wenzelm@28045
   387
wenzelm@34213
   388
    new Stdin_Thread(proc.getOutputStream).start
wenzelm@34213
   389
    new Stdout_Thread(proc.getInputStream).start
wenzelm@28045
   390
wenzelm@28045
   391
wenzelm@28045
   392
    /* exit */
wenzelm@27949
   393
wenzelm@28063
   394
    new Thread("isabelle: exit") {
wenzelm@28045
   395
      override def run() = {
wenzelm@28045
   396
        val rc = proc.waitFor()
wenzelm@28045
   397
        Thread.sleep(300)
wenzelm@34100
   398
        put_result(Kind.SYSTEM, "Exit thread terminated")
wenzelm@34100
   399
        put_result(Kind.EXIT, rc.toString)
wenzelm@28063
   400
        rm_fifo()
wenzelm@28045
   401
      }
wenzelm@28063
   402
    }.start
wenzelm@27949
   403
  }
wenzelm@27949
   404
}