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