src/Pure/PIDE/session.scala
author wenzelm
Sun May 13 16:37:36 2018 +0200 (13 months ago)
changeset 68169 395432e7516e
parent 68168 a9b49430f061
child 68293 2bc4e5d9cca6
permissions -rw-r--r--
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@65206
    71
  {
wenzelm@65206
    72
    def print: String =
wenzelm@65206
    73
      this match {
wenzelm@65317
    74
        case Terminated(result) => if (result.ok) "finished" else "failed"
wenzelm@65206
    75
        case _ => Word.lowercase(this.toString)
wenzelm@65206
    76
      }
wenzelm@65206
    77
  }
wenzelm@65208
    78
  case object Inactive extends Phase  // stable
wenzelm@39701
    79
  case object Startup extends Phase  // transient
wenzelm@65208
    80
  case object Ready extends Phase  // metastable
wenzelm@39701
    81
  case object Shutdown extends Phase  // transient
wenzelm@65317
    82
  case class Terminated(result: Process_Result) extends Phase  // stable
wenzelm@43716
    83
  //}}}
wenzelm@52111
    84
wenzelm@52111
    85
wenzelm@56775
    86
  /* syslog */
wenzelm@56775
    87
wenzelm@56775
    88
  private[Session] class Syslog(limit: Int)
wenzelm@56775
    89
  {
wenzelm@56775
    90
    private var queue = Queue.empty[XML.Elem]
wenzelm@56775
    91
    private var length = 0
wenzelm@56775
    92
wenzelm@56775
    93
    def += (msg: XML.Elem): Unit = synchronized {
wenzelm@56775
    94
      queue = queue.enqueue(msg)
wenzelm@56775
    95
      length += 1
wenzelm@56775
    96
      if (length > limit) queue = queue.dequeue._2
wenzelm@56775
    97
    }
wenzelm@56775
    98
wenzelm@56775
    99
    def content: String = synchronized {
wenzelm@56775
   100
      cat_lines(queue.iterator.map(XML.content)) +
wenzelm@56775
   101
      (if (length > limit) "\n(A total of " + length + " messages...)" else "")
wenzelm@56775
   102
    }
wenzelm@56775
   103
  }
wenzelm@56775
   104
wenzelm@56775
   105
wenzelm@52111
   106
  /* protocol handlers */
wenzelm@52111
   107
wenzelm@52111
   108
  abstract class Protocol_Handler
wenzelm@52111
   109
  {
wenzelm@65219
   110
    def init(session: Session): Unit = {}
wenzelm@65219
   111
    def exit(): Unit = {}
wenzelm@65219
   112
    val functions: List[(String, Prover.Protocol_Output => Boolean)]
wenzelm@52111
   113
  }
wenzelm@34791
   114
}
wenzelm@34791
   115
wenzelm@34777
   116
wenzelm@65264
   117
class Session(session_options: => Options, val resources: Resources) extends Document.Session
wenzelm@34777
   118
{
wenzelm@65214
   119
  session =>
wenzelm@65214
   120
wenzelm@68169
   121
  val xml_cache: XML.Cache = XML.make_cache()
wenzelm@68168
   122
  val xz_cache: XZ.Cache = XZ.make_cache()
wenzelm@65218
   123
wenzelm@65214
   124
wenzelm@47653
   125
  /* global flags */
wenzelm@47653
   126
wenzelm@47653
   127
  @volatile var timing: Boolean = false
wenzelm@47653
   128
  @volatile var verbose: Boolean = false
wenzelm@47653
   129
wenzelm@47653
   130
wenzelm@65264
   131
  /* dynamic session options */
wenzelm@49288
   132
wenzelm@65264
   133
  def output_delay: Time = session_options.seconds("editor_output_delay")
wenzelm@66379
   134
  def consolidate_delay: Time = session_options.seconds("editor_consolidate_delay")
wenzelm@65264
   135
  def prune_delay: Time = session_options.seconds("editor_prune_delay")
wenzelm@65264
   136
  def prune_size: Int = session_options.int("editor_prune_size")
wenzelm@65264
   137
  def syslog_limit: Int = session_options.int("editor_syslog_limit")
wenzelm@65264
   138
  def reparse_limit: Int = session_options.int("editor_reparse_limit")
wenzelm@37849
   139
wenzelm@37849
   140
wenzelm@66094
   141
  /* dispatcher */
wenzelm@56715
   142
wenzelm@56715
   143
  private val dispatcher =
wenzelm@56715
   144
    Consumer_Thread.fork[() => Unit]("Session.dispatcher", daemon = true) { case e => e(); true }
wenzelm@34809
   145
wenzelm@66094
   146
  def assert_dispatcher[A](body: => A): A =
wenzelm@66094
   147
  {
wenzelm@66094
   148
    assert(dispatcher.check_thread)
wenzelm@66094
   149
    body
wenzelm@66094
   150
  }
wenzelm@66094
   151
wenzelm@66094
   152
  def require_dispatcher[A](body: => A): A =
wenzelm@66094
   153
  {
wenzelm@66094
   154
    require(dispatcher.check_thread)
wenzelm@66094
   155
    body
wenzelm@66094
   156
  }
wenzelm@66094
   157
wenzelm@66094
   158
  def send_dispatcher(body: => Unit): Unit =
wenzelm@66094
   159
  {
wenzelm@66094
   160
    if (dispatcher.check_thread) body
wenzelm@66094
   161
    else dispatcher.send(() => body)
wenzelm@66094
   162
  }
wenzelm@66094
   163
wenzelm@66094
   164
  def send_wait_dispatcher(body: => Unit): Unit =
wenzelm@66094
   165
  {
wenzelm@66094
   166
    if (dispatcher.check_thread) body
wenzelm@66094
   167
    else dispatcher.send_wait(() => body)
wenzelm@66094
   168
  }
wenzelm@66094
   169
wenzelm@66094
   170
wenzelm@66094
   171
  /* outlets */
wenzelm@66094
   172
wenzelm@56715
   173
  val statistics = new Session.Outlet[Session.Statistics](dispatcher)
wenzelm@56715
   174
  val global_options = new Session.Outlet[Session.Global_Options](dispatcher)
wenzelm@56715
   175
  val caret_focus = new Session.Outlet[Session.Caret_Focus.type](dispatcher)
wenzelm@56715
   176
  val raw_edits = new Session.Outlet[Session.Raw_Edits](dispatcher)
wenzelm@56715
   177
  val commands_changed = new Session.Outlet[Session.Commands_Changed](dispatcher)
wenzelm@56715
   178
  val phase_changed = new Session.Outlet[Session.Phase](dispatcher)
wenzelm@56715
   179
  val syslog_messages = new Session.Outlet[Prover.Output](dispatcher)
wenzelm@56715
   180
  val raw_output_messages = new Session.Outlet[Prover.Output](dispatcher)
wenzelm@56715
   181
  val trace_events = new Session.Outlet[Simplifier_Trace.Event.type](dispatcher)
wenzelm@60900
   182
  val debugger_updates = new Session.Outlet[Debugger.Update.type](dispatcher)
wenzelm@34809
   183
wenzelm@60749
   184
  val all_messages = new Session.Outlet[Prover.Message](dispatcher)  // potential bottle-neck!
wenzelm@34809
   185
wenzelm@56706
   186
wenzelm@56799
   187
  /** main protocol manager **/
wenzelm@45635
   188
wenzelm@56799
   189
  /* internal messages */
wenzelm@45635
   190
wenzelm@62556
   191
  private case class Start(start_prover: Prover.Receiver => Prover)
wenzelm@56799
   192
  private case object Stop
wenzelm@56799
   193
  private case class Cancel_Exec(exec_id: Document_ID.Exec)
wenzelm@56799
   194
  private case class Protocol_Command(name: String, args: List[String])
wenzelm@56799
   195
  private case class Update_Options(options: Options)
wenzelm@66379
   196
  private case object Consolidate_Execution
wenzelm@56799
   197
  private case object Prune_History
wenzelm@45635
   198
wenzelm@38841
   199
wenzelm@65208
   200
  /* phase */
wenzelm@65208
   201
wenzelm@65208
   202
  private def post_phase(new_phase: Session.Phase): Session.Phase =
wenzelm@65208
   203
  {
wenzelm@65208
   204
    phase_changed.post(new_phase)
wenzelm@65208
   205
    new_phase
wenzelm@65208
   206
  }
wenzelm@65208
   207
  private val _phase = Synchronized[Session.Phase](Session.Inactive)
wenzelm@65208
   208
  private def phase_=(new_phase: Session.Phase): Unit = _phase.change(_ => post_phase(new_phase))
wenzelm@65208
   209
wenzelm@65208
   210
  def phase = _phase.value
wenzelm@65208
   211
  def is_ready: Boolean = phase == Session.Ready
wenzelm@65208
   212
wenzelm@65208
   213
wenzelm@43651
   214
  /* global state */
wenzelm@43644
   215
wenzelm@56775
   216
  private val syslog = new Session.Syslog(syslog_limit)
wenzelm@56775
   217
  def syslog_content(): String = syslog.content
wenzelm@39626
   218
wenzelm@56690
   219
  private val global_state = Synchronized(Document.State.init)
wenzelm@56687
   220
  def current_state(): Document.State = global_state.value
wenzelm@46944
   221
wenzelm@63584
   222
  def recent_syntax(name: Document.Node.Name): Outer_Syntax =
wenzelm@60934
   223
    global_state.value.recent_finished.version.get_finished.nodes(name).syntax getOrElse
wenzelm@66720
   224
    resources.session_base.overall_syntax
wenzelm@34816
   225
wenzelm@43651
   226
wenzelm@56799
   227
  /* pipelined change parsing */
wenzelm@56799
   228
wenzelm@56799
   229
  private case class Text_Edits(
wenzelm@56799
   230
    previous: Future[Document.Version],
wenzelm@56799
   231
    doc_blobs: Document.Blobs,
wenzelm@56799
   232
    text_edits: List[Document.Edit_Text],
wenzelm@56799
   233
    version_result: Promise[Document.Version])
wenzelm@43651
   234
wenzelm@56799
   235
  private val change_parser = Consumer_Thread.fork[Text_Edits]("change_parser", daemon = true)
wenzelm@56799
   236
  {
wenzelm@56799
   237
    case Text_Edits(previous, doc_blobs, text_edits, version_result) =>
wenzelm@56799
   238
      val prev = previous.get_finished
wenzelm@56799
   239
      val change =
wenzelm@56799
   240
        Timing.timeit("parse_change", timing) {
wenzelm@56799
   241
          resources.parse_change(reparse_limit, prev, doc_blobs, text_edits)
wenzelm@56799
   242
        }
wenzelm@56799
   243
      version_result.fulfill(change.version)
wenzelm@56799
   244
      manager.send(change)
wenzelm@56799
   245
      true
wenzelm@56799
   246
  }
wenzelm@41534
   247
wenzelm@56706
   248
wenzelm@56719
   249
  /* buffered changes */
wenzelm@56719
   250
wenzelm@56719
   251
  private object change_buffer
wenzelm@56719
   252
  {
wenzelm@56719
   253
    private var assignment: Boolean = false
wenzelm@56719
   254
    private var nodes: Set[Document.Node.Name] = Set.empty
wenzelm@56719
   255
    private var commands: Set[Command] = Set.empty
wenzelm@56719
   256
wenzelm@56719
   257
    def flush(): Unit = synchronized {
wenzelm@59319
   258
      if (assignment || nodes.nonEmpty || commands.nonEmpty)
wenzelm@56719
   259
        commands_changed.post(Session.Commands_Changed(assignment, nodes, commands))
wenzelm@56719
   260
      assignment = false
wenzelm@56719
   261
      nodes = Set.empty
wenzelm@56719
   262
      commands = Set.empty
wenzelm@56719
   263
    }
wenzelm@61556
   264
    private val delay_flush = Standard_Thread.delay_first(output_delay) { flush() }
wenzelm@56719
   265
wenzelm@56719
   266
    def invoke(assign: Boolean, cmds: List[Command]): Unit = synchronized {
wenzelm@56719
   267
      assignment |= assign
wenzelm@56719
   268
      for (command <- cmds) {
wenzelm@56719
   269
        nodes += command.node_name
wenzelm@64803
   270
        command.blobs_names.foreach(nodes += _)
wenzelm@56719
   271
        commands += command
wenzelm@56719
   272
      }
wenzelm@56771
   273
      delay_flush.invoke()
wenzelm@56719
   274
    }
wenzelm@56719
   275
wenzelm@56719
   276
    def shutdown()
wenzelm@56719
   277
    {
wenzelm@56771
   278
      delay_flush.revoke()
wenzelm@56719
   279
      flush()
wenzelm@56719
   280
    }
wenzelm@56719
   281
  }
wenzelm@56719
   282
wenzelm@56719
   283
wenzelm@56706
   284
  /* postponed changes */
wenzelm@44733
   285
wenzelm@56706
   286
  private object postponed_changes
wenzelm@56706
   287
  {
wenzelm@56706
   288
    private var postponed: List[Session.Change] = Nil
wenzelm@56706
   289
wenzelm@56706
   290
    def store(change: Session.Change): Unit = synchronized { postponed ::= change }
wenzelm@56705
   291
wenzelm@57976
   292
    def flush(state: Document.State): List[Session.Change] = synchronized {
wenzelm@56706
   293
      val (assigned, unassigned) = postponed.partition(change => state.is_assigned(change.previous))
wenzelm@56706
   294
      postponed = unassigned
wenzelm@57976
   295
      assigned.reverse
wenzelm@56706
   296
    }
wenzelm@56706
   297
  }
wenzelm@44733
   298
wenzelm@56706
   299
wenzelm@56793
   300
  /* prover process */
wenzelm@56793
   301
wenzelm@56793
   302
  private object prover
wenzelm@56793
   303
  {
wenzelm@61590
   304
    private val variable = Synchronized[Option[Prover]](None)
wenzelm@56793
   305
wenzelm@56793
   306
    def defined: Boolean = variable.value.isDefined
wenzelm@56793
   307
    def get: Prover = variable.value.get
wenzelm@56793
   308
    def set(p: Prover) { variable.change(_ => Some(p)) }
wenzelm@56793
   309
    def reset { variable.change(_ => None) }
wenzelm@56793
   310
    def await_reset() { variable.guarded_access({ case None => Some((), None) case _ => None }) }
wenzelm@56793
   311
  }
wenzelm@56793
   312
wenzelm@56793
   313
wenzelm@59366
   314
  /* protocol handlers */
wenzelm@59366
   315
wenzelm@65215
   316
  private val protocol_handlers = Protocol_Handlers.init(session)
wenzelm@59366
   317
wenzelm@59366
   318
  def get_protocol_handler(name: String): Option[Session.Protocol_Handler] =
wenzelm@65214
   319
    protocol_handlers.get(name)
wenzelm@59366
   320
wenzelm@65315
   321
  def init_protocol_handler(handler: Session.Protocol_Handler): Unit =
wenzelm@65315
   322
    protocol_handlers.init(handler)
wenzelm@65214
   323
wenzelm@65315
   324
  def init_protocol_handler(name: String): Unit =
wenzelm@65315
   325
    protocol_handlers.init(name)
wenzelm@59366
   326
wenzelm@59366
   327
wenzelm@65222
   328
  /* debugger */
wenzelm@65222
   329
wenzelm@65222
   330
  private val debugger_handler = new Debugger.Handler(this)
wenzelm@65315
   331
  init_protocol_handler(debugger_handler)
wenzelm@65222
   332
wenzelm@65222
   333
  def debugger: Debugger = debugger_handler.debugger
wenzelm@65222
   334
wenzelm@65222
   335
wenzelm@56706
   336
  /* manager thread */
wenzelm@44733
   337
wenzelm@62115
   338
  private val delay_prune =
wenzelm@62115
   339
    Standard_Thread.delay_first(prune_delay) { manager.send(Prune_History) }
wenzelm@56771
   340
wenzelm@56706
   341
  private val manager: Consumer_Thread[Any] =
wenzelm@56706
   342
  {
wenzelm@52649
   343
    /* raw edits */
wenzelm@52649
   344
wenzelm@54521
   345
    def handle_raw_edits(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@52649
   346
    //{{{
wenzelm@52649
   347
    {
wenzelm@56793
   348
      require(prover.defined)
wenzelm@56712
   349
wenzelm@52649
   350
      prover.get.discontinue_execution()
wenzelm@52649
   351
wenzelm@56687
   352
      val previous = global_state.value.history.tip.version
wenzelm@52649
   353
      val version = Future.promise[Document.Version]
wenzelm@56711
   354
      global_state.change(_.continue_history(previous, edits, version))
wenzelm@52649
   355
wenzelm@56715
   356
      raw_edits.post(Session.Raw_Edits(doc_blobs, edits))
wenzelm@56704
   357
      change_parser.send(Text_Edits(previous, doc_blobs, edits, version))
wenzelm@52649
   358
    }
wenzelm@52649
   359
    //}}}
wenzelm@52649
   360
wenzelm@52649
   361
wenzelm@43716
   362
    /* resulting changes */
wenzelm@34809
   363
wenzelm@56315
   364
    def handle_change(change: Session.Change)
wenzelm@38221
   365
    //{{{
wenzelm@34809
   366
    {
wenzelm@56793
   367
      require(prover.defined)
wenzelm@56712
   368
wenzelm@44383
   369
      def id_command(command: Command)
wenzelm@43720
   370
      {
wenzelm@54519
   371
        for {
wenzelm@57842
   372
          (name, digest) <- command.blobs_defined
wenzelm@56687
   373
          if !global_state.value.defined_blob(digest)
wenzelm@54519
   374
        } {
wenzelm@57842
   375
          change.version.nodes(name).get_blob match {
wenzelm@54519
   376
            case Some(blob) =>
wenzelm@56687
   377
              global_state.change(_.define_blob(digest))
wenzelm@56335
   378
              prover.get.define_blob(digest, blob.bytes)
wenzelm@55783
   379
            case None =>
wenzelm@57842
   380
              Output.error_message("Missing blob " + quote(name.toString))
wenzelm@54519
   381
          }
wenzelm@54519
   382
        }
wenzelm@54519
   383
wenzelm@56687
   384
        if (!global_state.value.defined_command(command.id)) {
wenzelm@56687
   385
          global_state.change(_.define_command(command))
wenzelm@44644
   386
          prover.get.define_command(command)
wenzelm@43720
   387
        }
wenzelm@43720
   388
      }
wenzelm@56315
   389
      change.doc_edits foreach {
wenzelm@44383
   390
        case (_, edit) =>
wenzelm@44383
   391
          edit foreach { case (c1, c2) => c1 foreach id_command; c2 foreach id_command }
wenzelm@44383
   392
      }
wenzelm@43722
   393
wenzelm@56687
   394
      val assignment = global_state.value.the_assignment(change.previous).check_finished
wenzelm@56687
   395
      global_state.change(_.define_version(change.version, assignment))
wenzelm@56315
   396
      prover.get.update(change.previous.id, change.version.id, change.doc_edits)
wenzelm@56316
   397
      resources.commit(change)
wenzelm@34809
   398
    }
wenzelm@38221
   399
    //}}}
wenzelm@34809
   400
wenzelm@34809
   401
wenzelm@46772
   402
    /* prover output */
wenzelm@34809
   403
wenzelm@56385
   404
    def handle_output(output: Prover.Output)
wenzelm@38221
   405
    //{{{
wenzelm@34809
   406
    {
wenzelm@68103
   407
      def bad_output()
wenzelm@68103
   408
      {
wenzelm@68103
   409
        if (verbose)
wenzelm@68103
   410
          Output.warning("Ignoring bad prover output: " + output.message.toString)
wenzelm@68103
   411
      }
wenzelm@68103
   412
wenzelm@68103
   413
      def change_command(f: Document.State => (Command.State, Document.State))
wenzelm@68103
   414
      {
wenzelm@68103
   415
        try {
wenzelm@68103
   416
          val st = global_state.change_result(f)
wenzelm@68103
   417
          change_buffer.invoke(false, List(st.command))
wenzelm@68103
   418
        }
wenzelm@68103
   419
        catch { case _: Document.State.Fail => bad_output() }
wenzelm@68103
   420
      }
wenzelm@51662
   421
wenzelm@54442
   422
      output match {
wenzelm@56385
   423
        case msg: Prover.Protocol_Output =>
wenzelm@65214
   424
          val handled = protocol_handlers.invoke(msg)
wenzelm@54442
   425
          if (!handled) {
wenzelm@54442
   426
            msg.properties match {
wenzelm@56793
   427
              case Markup.Protocol_Handler(name) if prover.defined =>
wenzelm@65315
   428
                init_protocol_handler(name)
wenzelm@54442
   429
wenzelm@56793
   430
              case Protocol.Command_Timing(state_id, timing) if prover.defined =>
wenzelm@54442
   431
                val message = XML.elem(Markup.STATUS, List(XML.Elem(Markup.Timing(timing), Nil)))
wenzelm@68103
   432
                change_command(_.accumulate(state_id, xml_cache.elem(message), xml_cache))
wenzelm@46122
   433
wenzelm@66873
   434
              case Protocol.Theory_Timing(_, _) =>
wenzelm@66873
   435
                // FIXME
wenzelm@66873
   436
wenzelm@68101
   437
              case Markup.Export(args)
wenzelm@68101
   438
              if args.id.isDefined && Value.Long.unapply(args.id.get).isDefined =>
wenzelm@68103
   439
                val id = Value.Long.unapply(args.id.get).get
wenzelm@68168
   440
                val export = Export.make_entry("", args, msg.bytes, cache = xz_cache)
wenzelm@68168
   441
                change_command(_.add_export(id, (args.serial, export)))
wenzelm@68088
   442
wenzelm@54442
   443
              case Markup.Assign_Update =>
wenzelm@54442
   444
                msg.text match {
wenzelm@54442
   445
                  case Protocol.Assign_Update(id, update) =>
wenzelm@54442
   446
                    try {
wenzelm@56687
   447
                      val cmds = global_state.change_result(_.assign(id, update))
wenzelm@56719
   448
                      change_buffer.invoke(true, cmds)
wenzelm@57976
   449
                      manager.send(Session.Change_Flush)
wenzelm@54442
   450
                    }
wenzelm@68103
   451
                    catch { case _: Document.State.Fail => bad_output() }
wenzelm@68103
   452
                  case _ => bad_output()
wenzelm@54442
   453
                }
wenzelm@56771
   454
                delay_prune.invoke()
wenzelm@46122
   455
wenzelm@54442
   456
              case Markup.Removed_Versions =>
wenzelm@54442
   457
                msg.text match {
wenzelm@54442
   458
                  case Protocol.Removed(removed) =>
wenzelm@54442
   459
                    try {
wenzelm@56687
   460
                      global_state.change(_.removed_versions(removed))
wenzelm@57976
   461
                      manager.send(Session.Change_Flush)
wenzelm@54442
   462
                    }
wenzelm@68103
   463
                    catch { case _: Document.State.Fail => bad_output() }
wenzelm@68103
   464
                  case _ => bad_output()
wenzelm@54442
   465
                }
wenzelm@54442
   466
wenzelm@54442
   467
              case Markup.ML_Statistics(props) =>
wenzelm@56715
   468
                statistics.post(Session.Statistics(props))
wenzelm@54442
   469
wenzelm@54442
   470
              case Markup.Task_Statistics(props) =>
wenzelm@54442
   471
                // FIXME
wenzelm@52111
   472
wenzelm@68103
   473
              case _ => bad_output()
wenzelm@54442
   474
            }
wenzelm@54442
   475
          }
wenzelm@54442
   476
        case _ =>
wenzelm@54442
   477
          output.properties match {
wenzelm@54442
   478
            case Position.Id(state_id) =>
wenzelm@68103
   479
              change_command(_.accumulate(state_id, output.message, xml_cache))
wenzelm@56210
   480
wenzelm@54442
   481
            case _ if output.is_init =>
wenzelm@65264
   482
              prover.get.options(session_options)
wenzelm@65470
   483
              prover.get.session_base(resources)
wenzelm@54442
   484
              phase = Session.Ready
wenzelm@65223
   485
              debugger.ready()
wenzelm@56210
   486
wenzelm@65317
   487
            case Markup.Process_Result(result) if output.is_exit =>
wenzelm@65317
   488
              phase = Session.Terminated(result)
wenzelm@56793
   489
              prover.reset
wenzelm@56210
   490
wenzelm@61376
   491
            case _ =>
wenzelm@61376
   492
              raw_output_messages.post(output)
wenzelm@44661
   493
          }
wenzelm@52111
   494
        }
wenzelm@34809
   495
    }
wenzelm@38221
   496
    //}}}
wenzelm@34809
   497
wenzelm@34820
   498
wenzelm@56706
   499
    /* main thread */
wenzelm@56706
   500
wenzelm@56710
   501
    Consumer_Thread.fork[Any]("Session.manager", daemon = true)
wenzelm@56709
   502
    {
wenzelm@56709
   503
      case arg: Any =>
wenzelm@56709
   504
        //{{{
wenzelm@56709
   505
        arg match {
wenzelm@56733
   506
          case output: Prover.Output =>
wenzelm@56775
   507
            if (output.is_stdout || output.is_stderr)
wenzelm@56775
   508
              raw_output_messages.post(output)
wenzelm@56733
   509
            else handle_output(output)
wenzelm@56775
   510
wenzelm@56733
   511
            if (output.is_syslog) {
wenzelm@56775
   512
              syslog += output.message
wenzelm@56733
   513
              syslog_messages.post(output)
wenzelm@56733
   514
            }
wenzelm@56775
   515
wenzelm@56733
   516
            all_messages.post(output)
wenzelm@56733
   517
wenzelm@56733
   518
          case input: Prover.Input =>
wenzelm@56733
   519
            all_messages.post(input)
wenzelm@56733
   520
wenzelm@62556
   521
          case Start(start_prover) if !prover.defined =>
wenzelm@65207
   522
            prover.set(start_prover(manager.send(_)))
wenzelm@56706
   523
wenzelm@56709
   524
          case Stop =>
wenzelm@65208
   525
            delay_prune.revoke()
wenzelm@65208
   526
            if (prover.defined) {
wenzelm@65219
   527
              protocol_handlers.exit()
wenzelm@56772
   528
              global_state.change(_ => Document.State.init)
wenzelm@56709
   529
              prover.get.terminate
wenzelm@56709
   530
            }
wenzelm@56706
   531
wenzelm@66379
   532
          case Consolidate_Execution =>
wenzelm@66379
   533
            if (prover.defined) prover.get.consolidate_execution()
wenzelm@66379
   534
wenzelm@56771
   535
          case Prune_History =>
wenzelm@56793
   536
            if (prover.defined) {
wenzelm@57976
   537
              val old_versions = global_state.change_result(_.remove_versions(prune_size))
wenzelm@59319
   538
              if (old_versions.nonEmpty) prover.get.remove_versions(old_versions)
wenzelm@56771
   539
            }
wenzelm@56771
   540
wenzelm@56709
   541
          case Update_Options(options) =>
wenzelm@56793
   542
            if (prover.defined && is_ready) {
wenzelm@56709
   543
              prover.get.options(options)
wenzelm@56709
   544
              handle_raw_edits(Document.Blobs.empty, Nil)
wenzelm@56709
   545
            }
wenzelm@56715
   546
            global_options.post(Session.Global_Options(options))
wenzelm@34809
   547
wenzelm@56793
   548
          case Cancel_Exec(exec_id) if prover.defined =>
wenzelm@56709
   549
            prover.get.cancel_exec(exec_id)
wenzelm@56706
   550
wenzelm@56793
   551
          case Session.Raw_Edits(doc_blobs, edits) if prover.defined =>
wenzelm@56709
   552
            handle_raw_edits(doc_blobs, edits)
wenzelm@56709
   553
wenzelm@56793
   554
          case Session.Dialog_Result(id, serial, result) if prover.defined =>
wenzelm@56709
   555
            prover.get.dialog_result(serial, result)
wenzelm@56709
   556
            handle_output(new Prover.Output(Protocol.Dialog_Result(id, serial, result)))
wenzelm@56706
   557
wenzelm@56793
   558
          case Protocol_Command(name, args) if prover.defined =>
wenzelm@56709
   559
            prover.get.protocol_command(name, args:_*)
wenzelm@56706
   560
wenzelm@56793
   561
          case change: Session.Change if prover.defined =>
wenzelm@57976
   562
            val state = global_state.value
wenzelm@57976
   563
            if (!state.removing_versions && state.is_assigned(change.previous))
wenzelm@56709
   564
              handle_change(change)
wenzelm@56709
   565
            else postponed_changes.store(change)
wenzelm@57651
   566
wenzelm@57976
   567
          case Session.Change_Flush if prover.defined =>
wenzelm@57976
   568
            val state = global_state.value
wenzelm@57976
   569
            if (!state.removing_versions)
wenzelm@57976
   570
              postponed_changes.flush(state).foreach(handle_change(_))
wenzelm@57976
   571
wenzelm@57651
   572
          case bad =>
wenzelm@57651
   573
            if (verbose) Output.warning("Ignoring bad message: " + bad.toString)
wenzelm@56706
   574
        }
wenzelm@56709
   575
        true
wenzelm@56709
   576
        //}}}
wenzelm@56709
   577
    }
wenzelm@34777
   578
  }
wenzelm@34777
   579
wenzelm@66379
   580
  private val consolidator: Thread =
wenzelm@66379
   581
    Standard_Thread.fork("Session.consolidator", daemon = true) {
wenzelm@66379
   582
      try {
wenzelm@66379
   583
        while (true) {
wenzelm@66379
   584
          Thread.sleep(consolidate_delay.ms)
wenzelm@66379
   585
wenzelm@66379
   586
          val state = global_state.value
wenzelm@66379
   587
          state.stable_tip_version match {
wenzelm@66379
   588
            case None =>
wenzelm@66379
   589
            case Some(version) =>
wenzelm@66379
   590
              val consolidated =
wenzelm@66379
   591
                version.nodes.iterator.forall(
wenzelm@66379
   592
                  { case (name, _) =>
wenzelm@66379
   593
                      resources.session_base.loaded_theory(name) ||
wenzelm@66379
   594
                      state.node_consolidated(version, name) })
wenzelm@66379
   595
              if (!consolidated) manager.send(Consolidate_Execution)
wenzelm@66379
   596
          }
wenzelm@66379
   597
        }
wenzelm@66379
   598
      }
wenzelm@66379
   599
      catch { case Exn.Interrupt() => }
wenzelm@66379
   600
    }
wenzelm@66379
   601
wenzelm@34809
   602
wenzelm@56799
   603
  /* main operations */
wenzelm@56799
   604
wenzelm@56799
   605
  def snapshot(name: Document.Node.Name = Document.Node.Name.empty,
wenzelm@56799
   606
      pending_edits: List[Text.Edit] = Nil): Document.Snapshot =
wenzelm@56799
   607
    global_state.value.snapshot(name, pending_edits)
wenzelm@34809
   608
wenzelm@62556
   609
  def start(start_prover: Prover.Receiver => Prover)
wenzelm@65207
   610
  {
wenzelm@65207
   611
    _phase.change(
wenzelm@65207
   612
      {
wenzelm@65207
   613
        case Session.Inactive =>
wenzelm@65207
   614
          manager.send(Start(start_prover))
wenzelm@65208
   615
          post_phase(Session.Startup)
wenzelm@65207
   616
        case phase => error("Cannot start prover in phase " + quote(phase.print))
wenzelm@65207
   617
      })
wenzelm@65207
   618
  }
wenzelm@45076
   619
wenzelm@65311
   620
  def send_stop()
wenzelm@50117
   621
  {
wenzelm@65208
   622
    val was_ready =
wenzelm@65208
   623
      _phase.guarded_access(phase =>
wenzelm@65208
   624
        phase match {
wenzelm@65208
   625
          case Session.Startup | Session.Shutdown => None
wenzelm@65208
   626
          case Session.Terminated(_) => Some((false, phase))
wenzelm@65317
   627
          case Session.Inactive => Some((false, post_phase(Session.Terminated(Process_Result(0)))))
wenzelm@65208
   628
          case Session.Ready => Some((true, post_phase(Session.Shutdown)))
wenzelm@65208
   629
        })
wenzelm@65311
   630
    if (was_ready) manager.send(Stop)
wenzelm@65311
   631
  }
wenzelm@65311
   632
wenzelm@65317
   633
  def stop(): Process_Result =
wenzelm@65311
   634
  {
wenzelm@65311
   635
    send_stop()
wenzelm@56793
   636
    prover.await_reset()
wenzelm@65208
   637
wenzelm@56704
   638
    change_parser.shutdown()
wenzelm@56706
   639
    change_buffer.shutdown()
wenzelm@66379
   640
    consolidator.interrupt
wenzelm@66379
   641
    consolidator.join
wenzelm@56706
   642
    manager.shutdown()
wenzelm@56715
   643
    dispatcher.shutdown()
wenzelm@65209
   644
wenzelm@65209
   645
    phase match {
wenzelm@65317
   646
      case Session.Terminated(result) => result
wenzelm@65209
   647
      case phase => error("Bad session phase after shutdown: " + quote(phase.print))
wenzelm@65209
   648
    }
wenzelm@50117
   649
  }
wenzelm@38841
   650
wenzelm@53054
   651
  def protocol_command(name: String, args: String*)
wenzelm@56706
   652
  { manager.send(Protocol_Command(name, args.toList)) }
wenzelm@53054
   653
wenzelm@56706
   654
  def cancel_exec(exec_id: Document_ID.Exec)
wenzelm@56706
   655
  { manager.send(Cancel_Exec(exec_id)) }
wenzelm@52931
   656
wenzelm@54521
   657
  def update(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@59319
   658
  { if (edits.nonEmpty) manager.send_wait(Session.Raw_Edits(doc_blobs, edits)) }
wenzelm@50498
   659
wenzelm@52084
   660
  def update_options(options: Options)
wenzelm@56706
   661
  { manager.send_wait(Update_Options(options)) }
wenzelm@52084
   662
wenzelm@52531
   663
  def dialog_result(id: Document_ID.Generic, serial: Long, result: String)
wenzelm@56706
   664
  { manager.send(Session.Dialog_Result(id, serial, result)) }
wenzelm@34777
   665
}