src/Pure/PIDE/prover.scala
author wenzelm
Tue Aug 12 18:54:53 2014 +0200 (2014-08-12)
changeset 57917 8ce97e5d545f
parent 57916 2c2c24dbf0a4
child 57923 cdae2467311d
permissions -rw-r--r--
tuned signature;
wenzelm@56385
     1
/*  Title:      Pure/PIDE/prover.scala
wenzelm@56385
     2
    Author:     Makarius
wenzelm@56385
     3
wenzelm@57916
     4
General prover operations and process wrapping.
wenzelm@56385
     5
*/
wenzelm@56385
     6
wenzelm@56385
     7
package isabelle
wenzelm@56385
     8
wenzelm@56385
     9
wenzelm@57916
    10
import java.io.{InputStream, OutputStream, BufferedReader, BufferedOutputStream, IOException}
wenzelm@57915
    11
wenzelm@57915
    12
wenzelm@56385
    13
object Prover
wenzelm@56385
    14
{
wenzelm@56393
    15
  /* syntax */
wenzelm@56393
    16
wenzelm@56393
    17
  trait Syntax
wenzelm@56393
    18
  {
wenzelm@56393
    19
    def add_keywords(keywords: Thy_Header.Keywords): Syntax
wenzelm@57906
    20
    def parse_spans(input: CharSequence): List[Command_Span.Span]
wenzelm@57901
    21
    def load_command(name: String): Option[List[String]]
wenzelm@56393
    22
    def load_commands_in(text: String): Boolean
wenzelm@56393
    23
  }
wenzelm@56393
    24
wenzelm@56393
    25
wenzelm@57915
    26
  /* underlying system process */
wenzelm@57915
    27
wenzelm@57915
    28
  trait System_Process
wenzelm@57915
    29
  {
wenzelm@57915
    30
    def stdout: BufferedReader
wenzelm@57915
    31
    def stderr: BufferedReader
wenzelm@57915
    32
    def terminate: Unit
wenzelm@57915
    33
    def join: Int
wenzelm@57915
    34
  }
wenzelm@57915
    35
wenzelm@57915
    36
wenzelm@56385
    37
  /* messages */
wenzelm@56385
    38
wenzelm@56385
    39
  sealed abstract class Message
wenzelm@56385
    40
wenzelm@56386
    41
  class Input(val name: String, val args: List[String]) extends Message
wenzelm@56385
    42
  {
wenzelm@56385
    43
    override def toString: String =
wenzelm@56385
    44
      XML.Elem(Markup(Markup.PROVER_COMMAND, List((Markup.NAME, name))),
wenzelm@56385
    45
        args.map(s =>
wenzelm@56385
    46
          List(XML.Text("\n"), XML.elem(Markup.PROVER_ARG, YXML.parse_body(s)))).flatten).toString
wenzelm@56385
    47
  }
wenzelm@56385
    48
wenzelm@56385
    49
  class Output(val message: XML.Elem) extends Message
wenzelm@56385
    50
  {
wenzelm@56385
    51
    def kind: String = message.markup.name
wenzelm@56385
    52
    def properties: Properties.T = message.markup.properties
wenzelm@56385
    53
    def body: XML.Body = message.body
wenzelm@56385
    54
wenzelm@56385
    55
    def is_init = kind == Markup.INIT
wenzelm@56385
    56
    def is_exit = kind == Markup.EXIT
wenzelm@56385
    57
    def is_stdout = kind == Markup.STDOUT
wenzelm@56385
    58
    def is_stderr = kind == Markup.STDERR
wenzelm@56385
    59
    def is_system = kind == Markup.SYSTEM
wenzelm@56385
    60
    def is_status = kind == Markup.STATUS
wenzelm@56385
    61
    def is_report = kind == Markup.REPORT
wenzelm@56385
    62
    def is_syslog = is_init || is_exit || is_system || is_stderr
wenzelm@56385
    63
wenzelm@56385
    64
    override def toString: String =
wenzelm@56385
    65
    {
wenzelm@56385
    66
      val res =
wenzelm@56385
    67
        if (is_status || is_report) message.body.map(_.toString).mkString
wenzelm@56385
    68
        else Pretty.string_of(message.body)
wenzelm@56385
    69
      if (properties.isEmpty)
wenzelm@56385
    70
        kind.toString + " [[" + res + "]]"
wenzelm@56385
    71
      else
wenzelm@56385
    72
        kind.toString + " " +
wenzelm@56385
    73
          (for ((x, y) <- properties) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@56385
    74
    }
wenzelm@56385
    75
  }
wenzelm@56385
    76
wenzelm@56385
    77
  class Protocol_Output(props: Properties.T, val bytes: Bytes)
wenzelm@56385
    78
    extends Output(XML.Elem(Markup(Markup.PROTOCOL, props), Nil))
wenzelm@56385
    79
  {
wenzelm@56385
    80
    lazy val text: String = bytes.toString
wenzelm@56385
    81
  }
wenzelm@56385
    82
}
wenzelm@56385
    83
wenzelm@56393
    84
wenzelm@57916
    85
abstract class Prover(
wenzelm@57916
    86
  receiver: Prover.Message => Unit,
wenzelm@57917
    87
  system_channel: System_Channel,
wenzelm@57916
    88
  system_process: Prover.System_Process) extends Protocol
wenzelm@56387
    89
{
wenzelm@57916
    90
  /* output */
wenzelm@57916
    91
wenzelm@57916
    92
  val xml_cache: XML.Cache = new XML.Cache()
wenzelm@57916
    93
wenzelm@57916
    94
  private def system_output(text: String)
wenzelm@57916
    95
  {
wenzelm@57916
    96
    receiver(new Prover.Output(XML.Elem(Markup(Markup.SYSTEM, Nil), List(XML.Text(text)))))
wenzelm@57916
    97
  }
wenzelm@57916
    98
wenzelm@57916
    99
  private def protocol_output(props: Properties.T, bytes: Bytes)
wenzelm@57916
   100
  {
wenzelm@57916
   101
    receiver(new Prover.Protocol_Output(props, bytes))
wenzelm@57916
   102
  }
wenzelm@57916
   103
wenzelm@57916
   104
  private def output(kind: String, props: Properties.T, body: XML.Body)
wenzelm@57916
   105
  {
wenzelm@57917
   106
    if (kind == Markup.INIT) system_channel.accepted()
wenzelm@56387
   107
wenzelm@57916
   108
    val main = XML.Elem(Markup(kind, props), Protocol.clean_message(body))
wenzelm@57916
   109
    val reports = Protocol.message_reports(props, body)
wenzelm@57916
   110
    for (msg <- main :: reports) receiver(new Prover.Output(xml_cache.elem(msg)))
wenzelm@57916
   111
  }
wenzelm@57916
   112
wenzelm@57916
   113
  private def exit_message(rc: Int)
wenzelm@57916
   114
  {
wenzelm@57916
   115
    output(Markup.EXIT, Markup.Return_Code(rc), List(XML.Text("Return code: " + rc.toString)))
wenzelm@57916
   116
  }
wenzelm@57916
   117
wenzelm@57916
   118
wenzelm@56387
   119
wenzelm@57916
   120
  /** process manager **/
wenzelm@57916
   121
wenzelm@57916
   122
  private val (_, process_result) =
wenzelm@57916
   123
    Simple_Thread.future("process_result") { system_process.join }
wenzelm@57916
   124
wenzelm@57916
   125
  private def terminate_process()
wenzelm@56387
   126
  {
wenzelm@57916
   127
    try { system_process.terminate }
wenzelm@57916
   128
    catch {
wenzelm@57916
   129
      case exn @ ERROR(_) => system_output("Failed to terminate prover process: " + exn.getMessage)
wenzelm@57916
   130
    }
wenzelm@56387
   131
  }
wenzelm@56387
   132
wenzelm@57916
   133
  private val process_manager = Simple_Thread.fork("process_manager")
wenzelm@57916
   134
  {
wenzelm@57916
   135
    val (startup_failed, startup_errors) =
wenzelm@57916
   136
    {
wenzelm@57916
   137
      var finished: Option[Boolean] = None
wenzelm@57916
   138
      val result = new StringBuilder(100)
wenzelm@57916
   139
      while (finished.isEmpty && (system_process.stderr.ready || !process_result.is_finished)) {
wenzelm@57916
   140
        while (finished.isEmpty && system_process.stderr.ready) {
wenzelm@57916
   141
          try {
wenzelm@57916
   142
            val c = system_process.stderr.read
wenzelm@57916
   143
            if (c == 2) finished = Some(true)
wenzelm@57916
   144
            else result += c.toChar
wenzelm@57916
   145
          }
wenzelm@57916
   146
          catch { case _: IOException => finished = Some(false) }
wenzelm@57916
   147
        }
wenzelm@57916
   148
        Thread.sleep(10)
wenzelm@57916
   149
      }
wenzelm@57916
   150
      (finished.isEmpty || !finished.get, result.toString.trim)
wenzelm@57916
   151
    }
wenzelm@57916
   152
    if (startup_errors != "") system_output(startup_errors)
wenzelm@57916
   153
wenzelm@57916
   154
    if (startup_failed) {
wenzelm@57916
   155
      terminate_process()
wenzelm@57916
   156
      process_result.join
wenzelm@57916
   157
      exit_message(127)
wenzelm@57916
   158
    }
wenzelm@57916
   159
    else {
wenzelm@57917
   160
      val (command_stream, message_stream) = system_channel.rendezvous()
wenzelm@57916
   161
wenzelm@57916
   162
      command_input_init(command_stream)
wenzelm@57916
   163
      val stdout = physical_output(false)
wenzelm@57916
   164
      val stderr = physical_output(true)
wenzelm@57916
   165
      val message = message_output(message_stream)
wenzelm@57916
   166
wenzelm@57916
   167
      val rc = process_result.join
wenzelm@57916
   168
      system_output("process terminated")
wenzelm@57916
   169
      command_input_close()
wenzelm@57916
   170
      for (thread <- List(stdout, stderr, message)) thread.join
wenzelm@57916
   171
      system_output("process_manager terminated")
wenzelm@57916
   172
      exit_message(rc)
wenzelm@57916
   173
    }
wenzelm@57917
   174
    system_channel.accepted()
wenzelm@57916
   175
  }
wenzelm@57916
   176
wenzelm@57916
   177
wenzelm@57916
   178
  /* management methods */
wenzelm@57916
   179
wenzelm@57916
   180
  def join() { process_manager.join() }
wenzelm@57916
   181
wenzelm@57916
   182
  def terminate()
wenzelm@57916
   183
  {
wenzelm@57916
   184
    command_input_close()
wenzelm@57916
   185
    system_output("Terminating prover process")
wenzelm@57916
   186
    terminate_process()
wenzelm@57916
   187
  }
wenzelm@57916
   188
wenzelm@57916
   189
wenzelm@57916
   190
wenzelm@57916
   191
  /** process streams **/
wenzelm@57916
   192
wenzelm@57916
   193
  /* command input */
wenzelm@57916
   194
wenzelm@57916
   195
  private var command_input: Option[Consumer_Thread[List[Bytes]]] = None
wenzelm@57916
   196
wenzelm@57916
   197
  private def command_input_close(): Unit = command_input.foreach(_.shutdown)
wenzelm@57916
   198
wenzelm@57916
   199
  private def command_input_init(raw_stream: OutputStream)
wenzelm@57916
   200
  {
wenzelm@57916
   201
    val name = "command_input"
wenzelm@57916
   202
    val stream = new BufferedOutputStream(raw_stream)
wenzelm@57916
   203
    command_input =
wenzelm@57916
   204
      Some(
wenzelm@57916
   205
        Consumer_Thread.fork(name)(
wenzelm@57916
   206
          consume =
wenzelm@57916
   207
            {
wenzelm@57916
   208
              case chunks =>
wenzelm@57916
   209
                try {
wenzelm@57916
   210
                  Bytes(chunks.map(_.length).mkString("", ",", "\n")).write(stream)
wenzelm@57916
   211
                  chunks.foreach(_.write(stream))
wenzelm@57916
   212
                  stream.flush
wenzelm@57916
   213
                  true
wenzelm@57916
   214
                }
wenzelm@57916
   215
                catch { case e: IOException => system_output(name + ": " + e.getMessage); false }
wenzelm@57916
   216
            },
wenzelm@57916
   217
          finish = { case () => stream.close; system_output(name + " terminated") }
wenzelm@57916
   218
        )
wenzelm@57916
   219
      )
wenzelm@57916
   220
  }
wenzelm@56387
   221
wenzelm@56387
   222
wenzelm@57916
   223
  /* physical output */
wenzelm@57916
   224
wenzelm@57916
   225
  private def physical_output(err: Boolean): Thread =
wenzelm@57916
   226
  {
wenzelm@57916
   227
    val (name, reader, markup) =
wenzelm@57916
   228
      if (err) ("standard_error", system_process.stderr, Markup.STDERR)
wenzelm@57916
   229
      else ("standard_output", system_process.stdout, Markup.STDOUT)
wenzelm@56387
   230
wenzelm@57916
   231
    Simple_Thread.fork(name) {
wenzelm@57916
   232
      try {
wenzelm@57916
   233
        var result = new StringBuilder(100)
wenzelm@57916
   234
        var finished = false
wenzelm@57916
   235
        while (!finished) {
wenzelm@57916
   236
          //{{{
wenzelm@57916
   237
          var c = -1
wenzelm@57916
   238
          var done = false
wenzelm@57916
   239
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@57916
   240
            c = reader.read
wenzelm@57916
   241
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@57916
   242
            else done = true
wenzelm@57916
   243
          }
wenzelm@57916
   244
          if (result.length > 0) {
wenzelm@57916
   245
            output(markup, Nil, List(XML.Text(decode(result.toString))))
wenzelm@57916
   246
            result.length = 0
wenzelm@57916
   247
          }
wenzelm@57916
   248
          else {
wenzelm@57916
   249
            reader.close
wenzelm@57916
   250
            finished = true
wenzelm@57916
   251
          }
wenzelm@57916
   252
          //}}}
wenzelm@57916
   253
        }
wenzelm@57916
   254
      }
wenzelm@57916
   255
      catch { case e: IOException => system_output(name + ": " + e.getMessage) }
wenzelm@57916
   256
      system_output(name + " terminated")
wenzelm@57916
   257
    }
wenzelm@57916
   258
  }
wenzelm@56387
   259
wenzelm@56387
   260
wenzelm@57916
   261
  /* message output */
wenzelm@57916
   262
wenzelm@57916
   263
  private def message_output(stream: InputStream): Thread =
wenzelm@57916
   264
  {
wenzelm@57916
   265
    class EOF extends Exception
wenzelm@57916
   266
    class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@57916
   267
wenzelm@57916
   268
    val name = "message_output"
wenzelm@57916
   269
    Simple_Thread.fork(name) {
wenzelm@57916
   270
      val default_buffer = new Array[Byte](65536)
wenzelm@57916
   271
      var c = -1
wenzelm@56387
   272
wenzelm@57916
   273
      def read_int(): Int =
wenzelm@57916
   274
      //{{{
wenzelm@57916
   275
      {
wenzelm@57916
   276
        var n = 0
wenzelm@57916
   277
        c = stream.read
wenzelm@57916
   278
        if (c == -1) throw new EOF
wenzelm@57916
   279
        while (48 <= c && c <= 57) {
wenzelm@57916
   280
          n = 10 * n + (c - 48)
wenzelm@57916
   281
          c = stream.read
wenzelm@57916
   282
        }
wenzelm@57916
   283
        if (c != 10)
wenzelm@57916
   284
          throw new Protocol_Error("malformed header: expected integer followed by newline")
wenzelm@57916
   285
        else n
wenzelm@57916
   286
      }
wenzelm@57916
   287
      //}}}
wenzelm@56387
   288
wenzelm@57916
   289
      def read_chunk_bytes(): (Array[Byte], Int) =
wenzelm@57916
   290
      //{{{
wenzelm@57916
   291
      {
wenzelm@57916
   292
        val n = read_int()
wenzelm@57916
   293
        val buf =
wenzelm@57916
   294
          if (n <= default_buffer.size) default_buffer
wenzelm@57916
   295
          else new Array[Byte](n)
wenzelm@57916
   296
wenzelm@57916
   297
        var i = 0
wenzelm@57916
   298
        var m = 0
wenzelm@57916
   299
        do {
wenzelm@57916
   300
          m = stream.read(buf, i, n - i)
wenzelm@57916
   301
          if (m != -1) i += m
wenzelm@57916
   302
        }
wenzelm@57916
   303
        while (m != -1 && n > i)
wenzelm@57916
   304
wenzelm@57916
   305
        if (i != n)
wenzelm@57916
   306
          throw new Protocol_Error("bad chunk (unexpected EOF after " + i + " of " + n + " bytes)")
wenzelm@57916
   307
wenzelm@57916
   308
        (buf, n)
wenzelm@57916
   309
      }
wenzelm@57916
   310
      //}}}
wenzelm@56387
   311
wenzelm@57916
   312
      def read_chunk(): XML.Body =
wenzelm@57916
   313
      {
wenzelm@57916
   314
        val (buf, n) = read_chunk_bytes()
wenzelm@57916
   315
        YXML.parse_body_failsafe(UTF8.decode_chars(decode, buf, 0, n))
wenzelm@57916
   316
      }
wenzelm@56387
   317
wenzelm@57916
   318
      try {
wenzelm@57916
   319
        do {
wenzelm@57916
   320
          try {
wenzelm@57916
   321
            val header = read_chunk()
wenzelm@57916
   322
            header match {
wenzelm@57916
   323
              case List(XML.Elem(Markup(name, props), Nil)) =>
wenzelm@57916
   324
                val kind = name.intern
wenzelm@57916
   325
                if (kind == Markup.PROTOCOL) {
wenzelm@57916
   326
                  val (buf, n) = read_chunk_bytes()
wenzelm@57916
   327
                  protocol_output(props, Bytes(buf, 0, n))
wenzelm@57916
   328
                }
wenzelm@57916
   329
                else {
wenzelm@57916
   330
                  val body = read_chunk()
wenzelm@57916
   331
                  output(kind, props, body)
wenzelm@57916
   332
                }
wenzelm@57916
   333
              case _ =>
wenzelm@57916
   334
                read_chunk()
wenzelm@57916
   335
                throw new Protocol_Error("bad header: " + header.toString)
wenzelm@57916
   336
            }
wenzelm@57916
   337
          }
wenzelm@57916
   338
          catch { case _: EOF => }
wenzelm@57916
   339
        }
wenzelm@57916
   340
        while (c != -1)
wenzelm@57916
   341
      }
wenzelm@57916
   342
      catch {
wenzelm@57916
   343
        case e: IOException => system_output("Cannot read message:\n" + e.getMessage)
wenzelm@57916
   344
        case e: Protocol_Error => system_output("Malformed message:\n" + e.getMessage)
wenzelm@57916
   345
      }
wenzelm@57916
   346
      stream.close
wenzelm@56387
   347
wenzelm@57916
   348
      system_output(name + " terminated")
wenzelm@57916
   349
    }
wenzelm@57916
   350
  }
wenzelm@57916
   351
wenzelm@57916
   352
wenzelm@57916
   353
wenzelm@57916
   354
  /** protocol commands **/
wenzelm@57916
   355
wenzelm@57916
   356
  def protocol_command_bytes(name: String, args: Bytes*): Unit =
wenzelm@57916
   357
    command_input match {
wenzelm@57916
   358
      case Some(thread) => thread.send(Bytes(name) :: args.toList)
wenzelm@57916
   359
      case None => error("Uninitialized command input thread")
wenzelm@57916
   360
    }
wenzelm@57916
   361
wenzelm@57916
   362
  def protocol_command(name: String, args: String*)
wenzelm@57916
   363
  {
wenzelm@57916
   364
    receiver(new Prover.Input(name, args.toList))
wenzelm@57916
   365
    protocol_command_bytes(name, args.map(Bytes(_)): _*)
wenzelm@57916
   366
  }
wenzelm@56387
   367
}
wenzelm@56387
   368