src/Pure/PIDE/session.scala
author wenzelm
Tue Mar 08 14:44:11 2016 +0100 (2016-03-08)
changeset 62556 c115e69f457f
parent 62545 8ebffdaf2ce2
child 63584 68751fe1c036
permissions -rw-r--r--
more abstract Session.start, without prover command-line;
Isabelle_Process.apply is directly based on ML_Process;
clarified Isabelle_Process.main command-line;
tuned signature;
wenzelm@56210
     1
/*  Title:      Pure/PIDE/session.scala
wenzelm@36676
     2
    Author:     Makarius
wenzelm@57923
     3
    Options:    :folding=explicit:
wenzelm@36676
     4
wenzelm@56210
     5
PIDE editor session, potentially with running prover process.
wenzelm@36676
     6
*/
wenzelm@34777
     7
wenzelm@34871
     8
package isabelle
wenzelm@34777
     9
wenzelm@44733
    10
wenzelm@46771
    11
import scala.collection.immutable.Queue
wenzelm@34777
    12
wenzelm@34815
    13
wenzelm@34791
    14
object Session
wenzelm@34791
    15
{
wenzelm@56715
    16
  /* outlets */
wenzelm@56715
    17
wenzelm@56715
    18
  object Consumer
wenzelm@56715
    19
  {
wenzelm@56715
    20
    def apply[A](name: String)(consume: A => Unit): Consumer[A] =
wenzelm@56715
    21
      new Consumer[A](name, consume)
wenzelm@56715
    22
  }
wenzelm@56715
    23
  final class Consumer[-A] private(val name: String, val consume: A => Unit)
wenzelm@56715
    24
wenzelm@56715
    25
  class Outlet[A](dispatcher: Consumer_Thread[() => Unit])
wenzelm@56715
    26
  {
wenzelm@61590
    27
    private val consumers = Synchronized[List[Consumer[A]]](Nil)
wenzelm@56715
    28
wenzelm@56715
    29
    def += (c: Consumer[A]) { consumers.change(Library.update(c)) }
wenzelm@56715
    30
    def -= (c: Consumer[A]) { consumers.change(Library.remove(c)) }
wenzelm@56715
    31
wenzelm@56715
    32
    def post(a: A)
wenzelm@56715
    33
    {
wenzelm@56715
    34
      for (c <- consumers.value.iterator) {
wenzelm@56715
    35
        dispatcher.send(() =>
wenzelm@56715
    36
          try { c.consume(a) }
wenzelm@56715
    37
          catch {
wenzelm@56715
    38
            case exn: Throwable =>
wenzelm@56782
    39
              Output.error_message("Consumer failed: " + quote(c.name) + "\n" + Exn.message(exn))
wenzelm@56715
    40
          })
wenzelm@56715
    41
      }
wenzelm@56715
    42
    }
wenzelm@56715
    43
  }
wenzelm@56715
    44
wenzelm@56715
    45
wenzelm@56315
    46
  /* change */
wenzelm@56315
    47
wenzelm@56315
    48
  sealed case class Change(
wenzelm@56315
    49
    previous: Document.Version,
wenzelm@59077
    50
    syntax_changed: List[Document.Node.Name],
wenzelm@56316
    51
    deps_changed: Boolean,
wenzelm@56315
    52
    doc_edits: List[Document.Edit_Command],
wenzelm@56315
    53
    version: Document.Version)
wenzelm@56315
    54
wenzelm@57976
    55
  case object Change_Flush
wenzelm@57976
    56
wenzelm@56315
    57
wenzelm@34813
    58
  /* events */
wenzelm@34813
    59
wenzelm@43716
    60
  //{{{
wenzelm@50697
    61
  case class Statistics(props: Properties.T)
wenzelm@50117
    62
  case class Global_Options(options: Options)
wenzelm@44805
    63
  case object Caret_Focus
wenzelm@54521
    64
  case class Raw_Edits(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@52531
    65
  case class Dialog_Result(id: Document_ID.Generic, serial: Long, result: String)
wenzelm@59364
    66
  case class Build_Theories(id: String, master_dir: Path, theories: List[(Options, List[Path])])
wenzelm@47027
    67
  case class Commands_Changed(
wenzelm@47027
    68
    assignment: Boolean, nodes: Set[Document.Node.Name], commands: Set[Command])
wenzelm@39630
    69
wenzelm@39630
    70
  sealed abstract class Phase
wenzelm@39630
    71
  case object Inactive extends Phase
wenzelm@39701
    72
  case object Startup extends Phase  // transient
wenzelm@39701
    73
  case object Failed extends Phase
wenzelm@39630
    74
  case object Ready extends Phase
wenzelm@39701
    75
  case object Shutdown extends Phase  // transient
wenzelm@43716
    76
  //}}}
wenzelm@52111
    77
wenzelm@52111
    78
wenzelm@56775
    79
  /* syslog */
wenzelm@56775
    80
wenzelm@56775
    81
  private[Session] class Syslog(limit: Int)
wenzelm@56775
    82
  {
wenzelm@56775
    83
    private var queue = Queue.empty[XML.Elem]
wenzelm@56775
    84
    private var length = 0
wenzelm@56775
    85
wenzelm@56775
    86
    def += (msg: XML.Elem): Unit = synchronized {
wenzelm@56775
    87
      queue = queue.enqueue(msg)
wenzelm@56775
    88
      length += 1
wenzelm@56775
    89
      if (length > limit) queue = queue.dequeue._2
wenzelm@56775
    90
    }
wenzelm@56775
    91
wenzelm@56775
    92
    def content: String = synchronized {
wenzelm@56775
    93
      cat_lines(queue.iterator.map(XML.content)) +
wenzelm@56775
    94
      (if (length > limit) "\n(A total of " + length + " messages...)" else "")
wenzelm@56775
    95
    }
wenzelm@56775
    96
  }
wenzelm@56775
    97
wenzelm@56775
    98
wenzelm@52111
    99
  /* protocol handlers */
wenzelm@52111
   100
wenzelm@52111
   101
  abstract class Protocol_Handler
wenzelm@52111
   102
  {
wenzelm@56864
   103
    def start(prover: Prover): Unit = {}
wenzelm@52111
   104
    def stop(prover: Prover): Unit = {}
wenzelm@56385
   105
    val functions: Map[String, (Prover, Prover.Protocol_Output) => Boolean]
wenzelm@52111
   106
  }
wenzelm@52111
   107
wenzelm@59367
   108
  def bad_protocol_handler(exn: Throwable, name: String): Unit =
wenzelm@59367
   109
    Output.error_message(
wenzelm@59367
   110
      "Failed to initialize protocol handler: " + quote(name) + "\n" + Exn.message(exn))
wenzelm@59367
   111
wenzelm@59366
   112
  private class Protocol_Handlers(
wenzelm@52111
   113
    handlers: Map[String, Session.Protocol_Handler] = Map.empty,
wenzelm@56385
   114
    functions: Map[String, Prover.Protocol_Output => Boolean] = Map.empty)
wenzelm@52111
   115
  {
wenzelm@53054
   116
    def get(name: String): Option[Protocol_Handler] = handlers.get(name)
wenzelm@53054
   117
wenzelm@59367
   118
    def add(prover: Prover, handler: Protocol_Handler): Protocol_Handlers =
wenzelm@52111
   119
    {
wenzelm@59367
   120
      val name = handler.getClass.getName
wenzelm@59367
   121
wenzelm@52111
   122
      val (handlers1, functions1) =
wenzelm@52111
   123
        handlers.get(name) match {
wenzelm@52111
   124
          case Some(old_handler) =>
wenzelm@56782
   125
            Output.warning("Redefining protocol handler: " + name)
wenzelm@52111
   126
            old_handler.stop(prover)
wenzelm@52111
   127
            (handlers - name, functions -- old_handler.functions.keys)
wenzelm@52111
   128
          case None => (handlers, functions)
wenzelm@52111
   129
        }
wenzelm@52111
   130
wenzelm@52111
   131
      val (handlers2, functions2) =
wenzelm@52111
   132
        try {
wenzelm@59367
   133
          handler.start(prover)
wenzelm@56864
   134
wenzelm@52111
   135
          val new_functions =
wenzelm@59367
   136
            for ((a, f) <- handler.functions.toList) yield
wenzelm@56385
   137
              (a, (msg: Prover.Protocol_Output) => f(prover, msg))
wenzelm@52111
   138
wenzelm@52111
   139
          val dups = for ((a, _) <- new_functions if functions1.isDefinedAt(a)) yield a
wenzelm@59319
   140
          if (dups.nonEmpty) error("Duplicate protocol functions: " + commas_quote(dups))
wenzelm@52111
   141
wenzelm@59367
   142
          (handlers1 + (name -> handler), functions1 ++ new_functions)
wenzelm@52111
   143
        }
wenzelm@52111
   144
        catch {
wenzelm@52111
   145
          case exn: Throwable =>
wenzelm@59367
   146
            Session.bad_protocol_handler(exn, name)
wenzelm@52111
   147
            (handlers1, functions1)
wenzelm@52111
   148
        }
wenzelm@52111
   149
wenzelm@52111
   150
      new Protocol_Handlers(handlers2, functions2)
wenzelm@52111
   151
    }
wenzelm@52111
   152
wenzelm@56385
   153
    def invoke(msg: Prover.Protocol_Output): Boolean =
wenzelm@54442
   154
      msg.properties match {
wenzelm@52111
   155
        case Markup.Function(a) if functions.isDefinedAt(a) =>
wenzelm@54442
   156
          try { functions(a)(msg) }
wenzelm@52111
   157
          catch {
wenzelm@52111
   158
            case exn: Throwable =>
wenzelm@56782
   159
              Output.error_message(
wenzelm@56782
   160
                "Failed invocation of protocol function: " + quote(a) + "\n" + Exn.message(exn))
wenzelm@52111
   161
            false
wenzelm@52111
   162
          }
wenzelm@52111
   163
        case _ => false
wenzelm@52111
   164
      }
wenzelm@52113
   165
wenzelm@52113
   166
    def stop(prover: Prover): Protocol_Handlers =
wenzelm@52113
   167
    {
wenzelm@52113
   168
      for ((_, handler) <- handlers) handler.stop(prover)
wenzelm@52113
   169
      new Protocol_Handlers()
wenzelm@52113
   170
    }
wenzelm@52111
   171
  }
wenzelm@34791
   172
}
wenzelm@34791
   173
wenzelm@34777
   174
wenzelm@56208
   175
class Session(val resources: Resources)
wenzelm@34777
   176
{
wenzelm@47653
   177
  /* global flags */
wenzelm@47653
   178
wenzelm@47653
   179
  @volatile var timing: Boolean = false
wenzelm@47653
   180
  @volatile var verbose: Boolean = false
wenzelm@47653
   181
wenzelm@47653
   182
wenzelm@49288
   183
  /* tuning parameters */
wenzelm@49288
   184
wenzelm@49288
   185
  def output_delay: Time = Time.seconds(0.1)  // prover output (markup, common messages)
wenzelm@62115
   186
  def prune_delay: Time = Time.seconds(15.0)  // prune history (delete old versions)
wenzelm@49293
   187
  def prune_size: Int = 0  // size of retained history
wenzelm@49293
   188
  def syslog_limit: Int = 100
wenzelm@49524
   189
  def reparse_limit: Int = 0
wenzelm@37849
   190
wenzelm@37849
   191
wenzelm@56715
   192
  /* outlets */
wenzelm@56715
   193
wenzelm@56715
   194
  private val dispatcher =
wenzelm@56715
   195
    Consumer_Thread.fork[() => Unit]("Session.dispatcher", daemon = true) { case e => e(); true }
wenzelm@34809
   196
wenzelm@56715
   197
  val statistics = new Session.Outlet[Session.Statistics](dispatcher)
wenzelm@56715
   198
  val global_options = new Session.Outlet[Session.Global_Options](dispatcher)
wenzelm@56715
   199
  val caret_focus = new Session.Outlet[Session.Caret_Focus.type](dispatcher)
wenzelm@56715
   200
  val raw_edits = new Session.Outlet[Session.Raw_Edits](dispatcher)
wenzelm@56715
   201
  val commands_changed = new Session.Outlet[Session.Commands_Changed](dispatcher)
wenzelm@56715
   202
  val phase_changed = new Session.Outlet[Session.Phase](dispatcher)
wenzelm@56715
   203
  val syslog_messages = new Session.Outlet[Prover.Output](dispatcher)
wenzelm@56715
   204
  val raw_output_messages = new Session.Outlet[Prover.Output](dispatcher)
wenzelm@56715
   205
  val trace_events = new Session.Outlet[Simplifier_Trace.Event.type](dispatcher)
wenzelm@60900
   206
  val debugger_updates = new Session.Outlet[Debugger.Update.type](dispatcher)
wenzelm@34809
   207
wenzelm@60749
   208
  val all_messages = new Session.Outlet[Prover.Message](dispatcher)  // potential bottle-neck!
wenzelm@34809
   209
wenzelm@56706
   210
wenzelm@56799
   211
  /** main protocol manager **/
wenzelm@45635
   212
wenzelm@56799
   213
  /* internal messages */
wenzelm@45635
   214
wenzelm@62556
   215
  private case class Start(start_prover: Prover.Receiver => Prover)
wenzelm@56799
   216
  private case object Stop
wenzelm@56799
   217
  private case class Cancel_Exec(exec_id: Document_ID.Exec)
wenzelm@56799
   218
  private case class Protocol_Command(name: String, args: List[String])
wenzelm@56799
   219
  private case class Update_Options(options: Options)
wenzelm@56799
   220
  private case object Prune_History
wenzelm@45635
   221
wenzelm@38841
   222
wenzelm@43651
   223
  /* global state */
wenzelm@43644
   224
wenzelm@56775
   225
  private val syslog = new Session.Syslog(syslog_limit)
wenzelm@56775
   226
  def syslog_content(): String = syslog.content
wenzelm@39626
   227
wenzelm@39630
   228
  @volatile private var _phase: Session.Phase = Session.Inactive
wenzelm@39633
   229
  private def phase_=(new_phase: Session.Phase)
wenzelm@39630
   230
  {
wenzelm@39630
   231
    _phase = new_phase
wenzelm@56715
   232
    phase_changed.post(new_phase)
wenzelm@39630
   233
  }
wenzelm@43716
   234
  def phase = _phase
wenzelm@43553
   235
  def is_ready: Boolean = phase == Session.Ready
wenzelm@39630
   236
wenzelm@56690
   237
  private val global_state = Synchronized(Document.State.init)
wenzelm@56687
   238
  def current_state(): Document.State = global_state.value
wenzelm@46944
   239
wenzelm@59077
   240
  def recent_syntax(name: Document.Node.Name): Prover.Syntax =
wenzelm@60934
   241
    global_state.value.recent_finished.version.get_finished.nodes(name).syntax getOrElse
wenzelm@59077
   242
    resources.base_syntax
wenzelm@34816
   243
wenzelm@43651
   244
wenzelm@43651
   245
  /* theory files */
wenzelm@43651
   246
wenzelm@48707
   247
  def header_edit(name: Document.Node.Name, header: Document.Node.Header): Document.Edit_Text =
wenzelm@44442
   248
  {
wenzelm@48707
   249
    val header1 =
wenzelm@56208
   250
      if (resources.loaded_theories(name.theory))
wenzelm@54559
   251
        header.error("Cannot update finished theory " + quote(name.theory))
wenzelm@48707
   252
      else header
wenzelm@48707
   253
    (name, Document.Node.Deps(header1))
wenzelm@44442
   254
  }
wenzelm@44442
   255
wenzelm@43651
   256
wenzelm@56799
   257
  /* pipelined change parsing */
wenzelm@56799
   258
wenzelm@56799
   259
  private case class Text_Edits(
wenzelm@56799
   260
    previous: Future[Document.Version],
wenzelm@56799
   261
    doc_blobs: Document.Blobs,
wenzelm@56799
   262
    text_edits: List[Document.Edit_Text],
wenzelm@56799
   263
    version_result: Promise[Document.Version])
wenzelm@43651
   264
wenzelm@56799
   265
  private val change_parser = Consumer_Thread.fork[Text_Edits]("change_parser", daemon = true)
wenzelm@56799
   266
  {
wenzelm@56799
   267
    case Text_Edits(previous, doc_blobs, text_edits, version_result) =>
wenzelm@56799
   268
      val prev = previous.get_finished
wenzelm@56799
   269
      val change =
wenzelm@56799
   270
        Timing.timeit("parse_change", timing) {
wenzelm@56799
   271
          resources.parse_change(reparse_limit, prev, doc_blobs, text_edits)
wenzelm@56799
   272
        }
wenzelm@56799
   273
      version_result.fulfill(change.version)
wenzelm@56799
   274
      manager.send(change)
wenzelm@56799
   275
      true
wenzelm@56799
   276
  }
wenzelm@41534
   277
wenzelm@56706
   278
wenzelm@56719
   279
  /* buffered changes */
wenzelm@56719
   280
wenzelm@56719
   281
  private object change_buffer
wenzelm@56719
   282
  {
wenzelm@56719
   283
    private var assignment: Boolean = false
wenzelm@56719
   284
    private var nodes: Set[Document.Node.Name] = Set.empty
wenzelm@56719
   285
    private var commands: Set[Command] = Set.empty
wenzelm@56719
   286
wenzelm@56719
   287
    def flush(): Unit = synchronized {
wenzelm@59319
   288
      if (assignment || nodes.nonEmpty || commands.nonEmpty)
wenzelm@56719
   289
        commands_changed.post(Session.Commands_Changed(assignment, nodes, commands))
wenzelm@56719
   290
      assignment = false
wenzelm@56719
   291
      nodes = Set.empty
wenzelm@56719
   292
      commands = Set.empty
wenzelm@56719
   293
    }
wenzelm@61556
   294
    private val delay_flush = Standard_Thread.delay_first(output_delay) { flush() }
wenzelm@56719
   295
wenzelm@56719
   296
    def invoke(assign: Boolean, cmds: List[Command]): Unit = synchronized {
wenzelm@56719
   297
      assignment |= assign
wenzelm@56719
   298
      for (command <- cmds) {
wenzelm@56719
   299
        nodes += command.node_name
wenzelm@56719
   300
        commands += command
wenzelm@56719
   301
      }
wenzelm@56771
   302
      delay_flush.invoke()
wenzelm@56719
   303
    }
wenzelm@56719
   304
wenzelm@56719
   305
    def shutdown()
wenzelm@56719
   306
    {
wenzelm@56771
   307
      delay_flush.revoke()
wenzelm@56719
   308
      flush()
wenzelm@56719
   309
    }
wenzelm@56719
   310
  }
wenzelm@56719
   311
wenzelm@56719
   312
wenzelm@56706
   313
  /* postponed changes */
wenzelm@44733
   314
wenzelm@56706
   315
  private object postponed_changes
wenzelm@56706
   316
  {
wenzelm@56706
   317
    private var postponed: List[Session.Change] = Nil
wenzelm@56706
   318
wenzelm@56706
   319
    def store(change: Session.Change): Unit = synchronized { postponed ::= change }
wenzelm@56705
   320
wenzelm@57976
   321
    def flush(state: Document.State): List[Session.Change] = synchronized {
wenzelm@56706
   322
      val (assigned, unassigned) = postponed.partition(change => state.is_assigned(change.previous))
wenzelm@56706
   323
      postponed = unassigned
wenzelm@57976
   324
      assigned.reverse
wenzelm@56706
   325
    }
wenzelm@56706
   326
  }
wenzelm@44733
   327
wenzelm@56706
   328
wenzelm@56793
   329
  /* prover process */
wenzelm@56793
   330
wenzelm@56793
   331
  private object prover
wenzelm@56793
   332
  {
wenzelm@61590
   333
    private val variable = Synchronized[Option[Prover]](None)
wenzelm@56793
   334
wenzelm@56793
   335
    def defined: Boolean = variable.value.isDefined
wenzelm@56793
   336
    def get: Prover = variable.value.get
wenzelm@56793
   337
    def set(p: Prover) { variable.change(_ => Some(p)) }
wenzelm@56793
   338
    def reset { variable.change(_ => None) }
wenzelm@56793
   339
    def await_reset() { variable.guarded_access({ case None => Some((), None) case _ => None }) }
wenzelm@56793
   340
  }
wenzelm@56793
   341
wenzelm@56793
   342
wenzelm@59366
   343
  /* protocol handlers */
wenzelm@59366
   344
wenzelm@59366
   345
  private val _protocol_handlers = Synchronized(new Session.Protocol_Handlers)
wenzelm@59366
   346
wenzelm@59366
   347
  def get_protocol_handler(name: String): Option[Session.Protocol_Handler] =
wenzelm@59366
   348
    _protocol_handlers.value.get(name)
wenzelm@59366
   349
wenzelm@59367
   350
  def add_protocol_handler(handler: Session.Protocol_Handler): Unit =
wenzelm@59367
   351
    _protocol_handlers.change(_.add(prover.get, handler))
wenzelm@59366
   352
wenzelm@59366
   353
wenzelm@56706
   354
  /* manager thread */
wenzelm@44733
   355
wenzelm@62115
   356
  private val delay_prune =
wenzelm@62115
   357
    Standard_Thread.delay_first(prune_delay) { manager.send(Prune_History) }
wenzelm@56771
   358
wenzelm@56706
   359
  private val manager: Consumer_Thread[Any] =
wenzelm@56706
   360
  {
wenzelm@52649
   361
    /* raw edits */
wenzelm@52649
   362
wenzelm@54521
   363
    def handle_raw_edits(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@52649
   364
    //{{{
wenzelm@52649
   365
    {
wenzelm@56793
   366
      require(prover.defined)
wenzelm@56712
   367
wenzelm@52649
   368
      prover.get.discontinue_execution()
wenzelm@52649
   369
wenzelm@56687
   370
      val previous = global_state.value.history.tip.version
wenzelm@52649
   371
      val version = Future.promise[Document.Version]
wenzelm@56711
   372
      global_state.change(_.continue_history(previous, edits, version))
wenzelm@52649
   373
wenzelm@56715
   374
      raw_edits.post(Session.Raw_Edits(doc_blobs, edits))
wenzelm@56704
   375
      change_parser.send(Text_Edits(previous, doc_blobs, edits, version))
wenzelm@52649
   376
    }
wenzelm@52649
   377
    //}}}
wenzelm@52649
   378
wenzelm@52649
   379
wenzelm@43716
   380
    /* resulting changes */
wenzelm@34809
   381
wenzelm@56315
   382
    def handle_change(change: Session.Change)
wenzelm@38221
   383
    //{{{
wenzelm@34809
   384
    {
wenzelm@56793
   385
      require(prover.defined)
wenzelm@56712
   386
wenzelm@44383
   387
      def id_command(command: Command)
wenzelm@43720
   388
      {
wenzelm@54519
   389
        for {
wenzelm@57842
   390
          (name, digest) <- command.blobs_defined
wenzelm@56687
   391
          if !global_state.value.defined_blob(digest)
wenzelm@54519
   392
        } {
wenzelm@57842
   393
          change.version.nodes(name).get_blob match {
wenzelm@54519
   394
            case Some(blob) =>
wenzelm@56687
   395
              global_state.change(_.define_blob(digest))
wenzelm@56335
   396
              prover.get.define_blob(digest, blob.bytes)
wenzelm@55783
   397
            case None =>
wenzelm@57842
   398
              Output.error_message("Missing blob " + quote(name.toString))
wenzelm@54519
   399
          }
wenzelm@54519
   400
        }
wenzelm@54519
   401
wenzelm@56687
   402
        if (!global_state.value.defined_command(command.id)) {
wenzelm@56687
   403
          global_state.change(_.define_command(command))
wenzelm@44644
   404
          prover.get.define_command(command)
wenzelm@43720
   405
        }
wenzelm@43720
   406
      }
wenzelm@56315
   407
      change.doc_edits foreach {
wenzelm@44383
   408
        case (_, edit) =>
wenzelm@44383
   409
          edit foreach { case (c1, c2) => c1 foreach id_command; c2 foreach id_command }
wenzelm@44383
   410
      }
wenzelm@43722
   411
wenzelm@56687
   412
      val assignment = global_state.value.the_assignment(change.previous).check_finished
wenzelm@56687
   413
      global_state.change(_.define_version(change.version, assignment))
wenzelm@56315
   414
      prover.get.update(change.previous.id, change.version.id, change.doc_edits)
wenzelm@56316
   415
      resources.commit(change)
wenzelm@34809
   416
    }
wenzelm@38221
   417
    //}}}
wenzelm@34809
   418
wenzelm@34809
   419
wenzelm@46772
   420
    /* prover output */
wenzelm@34809
   421
wenzelm@56385
   422
    def handle_output(output: Prover.Output)
wenzelm@38221
   423
    //{{{
wenzelm@34809
   424
    {
wenzelm@51662
   425
      def bad_output()
wenzelm@43716
   426
      {
wenzelm@43716
   427
        if (verbose)
wenzelm@56782
   428
          Output.warning("Ignoring bad prover output: " + output.message.toString)
wenzelm@43716
   429
      }
wenzelm@43716
   430
wenzelm@52531
   431
      def accumulate(state_id: Document_ID.Generic, message: XML.Elem)
wenzelm@51662
   432
      {
wenzelm@51662
   433
        try {
wenzelm@56687
   434
          val st = global_state.change_result(_.accumulate(state_id, message))
wenzelm@56719
   435
          change_buffer.invoke(false, List(st.command))
wenzelm@51662
   436
        }
wenzelm@51662
   437
        catch {
wenzelm@51662
   438
          case _: Document.State.Fail => bad_output()
wenzelm@51662
   439
        }
wenzelm@51662
   440
      }
wenzelm@51662
   441
wenzelm@54442
   442
      output match {
wenzelm@56385
   443
        case msg: Prover.Protocol_Output =>
wenzelm@59366
   444
          val handled = _protocol_handlers.value.invoke(msg)
wenzelm@54442
   445
          if (!handled) {
wenzelm@54442
   446
            msg.properties match {
wenzelm@56793
   447
              case Markup.Protocol_Handler(name) if prover.defined =>
wenzelm@59367
   448
                try {
wenzelm@59367
   449
                  val handler =
wenzelm@59367
   450
                    Class.forName(name).newInstance.asInstanceOf[Session.Protocol_Handler]
wenzelm@59367
   451
                  add_protocol_handler(handler)
wenzelm@59367
   452
                }
wenzelm@59367
   453
                catch { case exn: Throwable => Session.bad_protocol_handler(exn, name) }
wenzelm@54442
   454
wenzelm@56793
   455
              case Protocol.Command_Timing(state_id, timing) if prover.defined =>
wenzelm@54442
   456
                val message = XML.elem(Markup.STATUS, List(XML.Elem(Markup.Timing(timing), Nil)))
wenzelm@54442
   457
                accumulate(state_id, prover.get.xml_cache.elem(message))
wenzelm@46122
   458
wenzelm@54442
   459
              case Markup.Assign_Update =>
wenzelm@54442
   460
                msg.text match {
wenzelm@54442
   461
                  case Protocol.Assign_Update(id, update) =>
wenzelm@54442
   462
                    try {
wenzelm@56687
   463
                      val cmds = global_state.change_result(_.assign(id, update))
wenzelm@56719
   464
                      change_buffer.invoke(true, cmds)
wenzelm@57976
   465
                      manager.send(Session.Change_Flush)
wenzelm@54442
   466
                    }
wenzelm@54442
   467
                    catch { case _: Document.State.Fail => bad_output() }
wenzelm@54442
   468
                  case _ => bad_output()
wenzelm@54442
   469
                }
wenzelm@56771
   470
                delay_prune.invoke()
wenzelm@46122
   471
wenzelm@54442
   472
              case Markup.Removed_Versions =>
wenzelm@54442
   473
                msg.text match {
wenzelm@54442
   474
                  case Protocol.Removed(removed) =>
wenzelm@54442
   475
                    try {
wenzelm@56687
   476
                      global_state.change(_.removed_versions(removed))
wenzelm@57976
   477
                      manager.send(Session.Change_Flush)
wenzelm@54442
   478
                    }
wenzelm@54442
   479
                    catch { case _: Document.State.Fail => bad_output() }
wenzelm@54442
   480
                  case _ => bad_output()
wenzelm@54442
   481
                }
wenzelm@54442
   482
wenzelm@54442
   483
              case Markup.ML_Statistics(props) =>
wenzelm@56715
   484
                statistics.post(Session.Statistics(props))
wenzelm@54442
   485
wenzelm@54442
   486
              case Markup.Task_Statistics(props) =>
wenzelm@54442
   487
                // FIXME
wenzelm@52111
   488
wenzelm@54442
   489
              case _ => bad_output()
wenzelm@54442
   490
            }
wenzelm@54442
   491
          }
wenzelm@54442
   492
        case _ =>
wenzelm@54442
   493
          output.properties match {
wenzelm@54442
   494
            case Position.Id(state_id) =>
wenzelm@54442
   495
              accumulate(state_id, output.message)
wenzelm@56210
   496
wenzelm@54442
   497
            case _ if output.is_init =>
wenzelm@54442
   498
              phase = Session.Ready
wenzelm@56210
   499
wenzelm@54442
   500
            case Markup.Return_Code(rc) if output.is_exit =>
wenzelm@54442
   501
              if (rc == 0) phase = Session.Inactive
wenzelm@54442
   502
              else phase = Session.Failed
wenzelm@56793
   503
              prover.reset
wenzelm@56210
   504
wenzelm@61376
   505
            case _ =>
wenzelm@61376
   506
              raw_output_messages.post(output)
wenzelm@44661
   507
          }
wenzelm@52111
   508
        }
wenzelm@34809
   509
    }
wenzelm@38221
   510
    //}}}
wenzelm@34809
   511
wenzelm@34820
   512
wenzelm@56706
   513
    /* main thread */
wenzelm@56706
   514
wenzelm@56710
   515
    Consumer_Thread.fork[Any]("Session.manager", daemon = true)
wenzelm@56709
   516
    {
wenzelm@56709
   517
      case arg: Any =>
wenzelm@56709
   518
        //{{{
wenzelm@56709
   519
        arg match {
wenzelm@56733
   520
          case output: Prover.Output =>
wenzelm@56775
   521
            if (output.is_stdout || output.is_stderr)
wenzelm@56775
   522
              raw_output_messages.post(output)
wenzelm@56733
   523
            else handle_output(output)
wenzelm@56775
   524
wenzelm@56733
   525
            if (output.is_syslog) {
wenzelm@56775
   526
              syslog += output.message
wenzelm@56733
   527
              syslog_messages.post(output)
wenzelm@56733
   528
            }
wenzelm@56775
   529
wenzelm@56733
   530
            all_messages.post(output)
wenzelm@56733
   531
wenzelm@56733
   532
          case input: Prover.Input =>
wenzelm@56733
   533
            all_messages.post(input)
wenzelm@56733
   534
wenzelm@62556
   535
          case Start(start_prover) if !prover.defined =>
wenzelm@56709
   536
            if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@56709
   537
              phase = Session.Startup
wenzelm@62556
   538
              prover.set(start_prover(manager.send(_)))
wenzelm@56709
   539
            }
wenzelm@56706
   540
wenzelm@56709
   541
          case Stop =>
wenzelm@56793
   542
            if (prover.defined && is_ready) {
wenzelm@59366
   543
              _protocol_handlers.change(_.stop(prover.get))
wenzelm@56772
   544
              global_state.change(_ => Document.State.init)
wenzelm@56709
   545
              phase = Session.Shutdown
wenzelm@56709
   546
              prover.get.terminate
wenzelm@56709
   547
            }
wenzelm@56706
   548
wenzelm@56771
   549
          case Prune_History =>
wenzelm@56793
   550
            if (prover.defined) {
wenzelm@57976
   551
              val old_versions = global_state.change_result(_.remove_versions(prune_size))
wenzelm@59319
   552
              if (old_versions.nonEmpty) prover.get.remove_versions(old_versions)
wenzelm@56771
   553
            }
wenzelm@56771
   554
wenzelm@56709
   555
          case Update_Options(options) =>
wenzelm@56793
   556
            if (prover.defined && is_ready) {
wenzelm@56709
   557
              prover.get.options(options)
wenzelm@56709
   558
              handle_raw_edits(Document.Blobs.empty, Nil)
wenzelm@56709
   559
            }
wenzelm@56715
   560
            global_options.post(Session.Global_Options(options))
wenzelm@34809
   561
wenzelm@56793
   562
          case Cancel_Exec(exec_id) if prover.defined =>
wenzelm@56709
   563
            prover.get.cancel_exec(exec_id)
wenzelm@56706
   564
wenzelm@56793
   565
          case Session.Raw_Edits(doc_blobs, edits) if prover.defined =>
wenzelm@56709
   566
            handle_raw_edits(doc_blobs, edits)
wenzelm@56709
   567
wenzelm@56793
   568
          case Session.Dialog_Result(id, serial, result) if prover.defined =>
wenzelm@56709
   569
            prover.get.dialog_result(serial, result)
wenzelm@56709
   570
            handle_output(new Prover.Output(Protocol.Dialog_Result(id, serial, result)))
wenzelm@56706
   571
wenzelm@59364
   572
          case Session.Build_Theories(id, master_dir, theories) if prover.defined =>
wenzelm@59364
   573
            prover.get.build_theories(id, master_dir, theories)
wenzelm@59362
   574
wenzelm@56793
   575
          case Protocol_Command(name, args) if prover.defined =>
wenzelm@56709
   576
            prover.get.protocol_command(name, args:_*)
wenzelm@56706
   577
wenzelm@56793
   578
          case change: Session.Change if prover.defined =>
wenzelm@57976
   579
            val state = global_state.value
wenzelm@57976
   580
            if (!state.removing_versions && state.is_assigned(change.previous))
wenzelm@56709
   581
              handle_change(change)
wenzelm@56709
   582
            else postponed_changes.store(change)
wenzelm@57651
   583
wenzelm@57976
   584
          case Session.Change_Flush if prover.defined =>
wenzelm@57976
   585
            val state = global_state.value
wenzelm@57976
   586
            if (!state.removing_versions)
wenzelm@57976
   587
              postponed_changes.flush(state).foreach(handle_change(_))
wenzelm@57976
   588
wenzelm@57651
   589
          case bad =>
wenzelm@57651
   590
            if (verbose) Output.warning("Ignoring bad message: " + bad.toString)
wenzelm@56706
   591
        }
wenzelm@56709
   592
        true
wenzelm@56709
   593
        //}}}
wenzelm@56709
   594
    }
wenzelm@34777
   595
  }
wenzelm@34777
   596
wenzelm@34809
   597
wenzelm@56799
   598
  /* main operations */
wenzelm@56799
   599
wenzelm@56799
   600
  def snapshot(name: Document.Node.Name = Document.Node.Name.empty,
wenzelm@56799
   601
      pending_edits: List[Text.Edit] = Nil): Document.Snapshot =
wenzelm@56799
   602
    global_state.value.snapshot(name, pending_edits)
wenzelm@34809
   603
wenzelm@62556
   604
  def start(start_prover: Prover.Receiver => Prover)
wenzelm@62556
   605
  { manager.send(Start(start_prover)) }
wenzelm@45076
   606
wenzelm@50117
   607
  def stop()
wenzelm@50117
   608
  {
wenzelm@62050
   609
    delay_prune.revoke()
wenzelm@56709
   610
    manager.send_wait(Stop)
wenzelm@56793
   611
    prover.await_reset()
wenzelm@56704
   612
    change_parser.shutdown()
wenzelm@56706
   613
    change_buffer.shutdown()
wenzelm@56706
   614
    manager.shutdown()
wenzelm@56715
   615
    dispatcher.shutdown()
wenzelm@50117
   616
  }
wenzelm@38841
   617
wenzelm@53054
   618
  def protocol_command(name: String, args: String*)
wenzelm@56706
   619
  { manager.send(Protocol_Command(name, args.toList)) }
wenzelm@53054
   620
wenzelm@56706
   621
  def cancel_exec(exec_id: Document_ID.Exec)
wenzelm@56706
   622
  { manager.send(Cancel_Exec(exec_id)) }
wenzelm@52931
   623
wenzelm@54521
   624
  def update(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@59319
   625
  { if (edits.nonEmpty) manager.send_wait(Session.Raw_Edits(doc_blobs, edits)) }
wenzelm@50498
   626
wenzelm@52084
   627
  def update_options(options: Options)
wenzelm@56706
   628
  { manager.send_wait(Update_Options(options)) }
wenzelm@52084
   629
wenzelm@52531
   630
  def dialog_result(id: Document_ID.Generic, serial: Long, result: String)
wenzelm@56706
   631
  { manager.send(Session.Dialog_Result(id, serial, result)) }
wenzelm@59362
   632
wenzelm@59364
   633
  def build_theories(id: String, master_dir: Path, theories: List[(Options, List[Path])])
wenzelm@59364
   634
  { manager.send(Session.Build_Theories(id, master_dir, theories)) }
wenzelm@34777
   635
}