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