src/Pure/PIDE/session.scala
author wenzelm
Sat May 05 22:33:35 2018 +0200 (18 months ago ago)
changeset 68090 0763d4eb3ebc
parent 67825 f9c071cc958b
child 68104 0699a0bacc50
permissions -rw-r--r--
protocol message for export of theory resources;
     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, xml_cache))
   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.Export(_) =>
   439                 // FIXME
   440 
   441               case Markup.Assign_Update =>
   442                 msg.text match {
   443                   case Protocol.Assign_Update(id, update) =>
   444                     try {
   445                       val cmds = global_state.change_result(_.assign(id, update))
   446                       change_buffer.invoke(true, cmds)
   447                       manager.send(Session.Change_Flush)
   448                     }
   449                     catch { case _: Document.State.Fail => bad_output() }
   450                   case _ => bad_output()
   451                 }
   452                 delay_prune.invoke()
   453 
   454               case Markup.Removed_Versions =>
   455                 msg.text match {
   456                   case Protocol.Removed(removed) =>
   457                     try {
   458                       global_state.change(_.removed_versions(removed))
   459                       manager.send(Session.Change_Flush)
   460                     }
   461                     catch { case _: Document.State.Fail => bad_output() }
   462                   case _ => bad_output()
   463                 }
   464 
   465               case Markup.ML_Statistics(props) =>
   466                 statistics.post(Session.Statistics(props))
   467 
   468               case Markup.Task_Statistics(props) =>
   469                 // FIXME
   470 
   471               case _ => bad_output()
   472             }
   473           }
   474         case _ =>
   475           output.properties match {
   476             case Position.Id(state_id) =>
   477               accumulate(state_id, output.message)
   478 
   479             case _ if output.is_init =>
   480               prover.get.options(session_options)
   481               prover.get.session_base(resources)
   482               phase = Session.Ready
   483               debugger.ready()
   484 
   485             case Markup.Process_Result(result) if output.is_exit =>
   486               phase = Session.Terminated(result)
   487               prover.reset
   488 
   489             case _ =>
   490               raw_output_messages.post(output)
   491           }
   492         }
   493     }
   494     //}}}
   495 
   496 
   497     /* main thread */
   498 
   499     Consumer_Thread.fork[Any]("Session.manager", daemon = true)
   500     {
   501       case arg: Any =>
   502         //{{{
   503         arg match {
   504           case output: Prover.Output =>
   505             if (output.is_stdout || output.is_stderr)
   506               raw_output_messages.post(output)
   507             else handle_output(output)
   508 
   509             if (output.is_syslog) {
   510               syslog += output.message
   511               syslog_messages.post(output)
   512             }
   513 
   514             all_messages.post(output)
   515 
   516           case input: Prover.Input =>
   517             all_messages.post(input)
   518 
   519           case Start(start_prover) if !prover.defined =>
   520             prover.set(start_prover(manager.send(_)))
   521 
   522           case Stop =>
   523             delay_prune.revoke()
   524             if (prover.defined) {
   525               protocol_handlers.exit()
   526               global_state.change(_ => Document.State.init)
   527               prover.get.terminate
   528             }
   529 
   530           case Consolidate_Execution =>
   531             if (prover.defined) prover.get.consolidate_execution()
   532 
   533           case Prune_History =>
   534             if (prover.defined) {
   535               val old_versions = global_state.change_result(_.remove_versions(prune_size))
   536               if (old_versions.nonEmpty) prover.get.remove_versions(old_versions)
   537             }
   538 
   539           case Update_Options(options) =>
   540             if (prover.defined && is_ready) {
   541               prover.get.options(options)
   542               handle_raw_edits(Document.Blobs.empty, Nil)
   543             }
   544             global_options.post(Session.Global_Options(options))
   545 
   546           case Cancel_Exec(exec_id) if prover.defined =>
   547             prover.get.cancel_exec(exec_id)
   548 
   549           case Session.Raw_Edits(doc_blobs, edits) if prover.defined =>
   550             handle_raw_edits(doc_blobs, edits)
   551 
   552           case Session.Dialog_Result(id, serial, result) if prover.defined =>
   553             prover.get.dialog_result(serial, result)
   554             handle_output(new Prover.Output(Protocol.Dialog_Result(id, serial, result)))
   555 
   556           case Protocol_Command(name, args) if prover.defined =>
   557             prover.get.protocol_command(name, args:_*)
   558 
   559           case change: Session.Change if prover.defined =>
   560             val state = global_state.value
   561             if (!state.removing_versions && state.is_assigned(change.previous))
   562               handle_change(change)
   563             else postponed_changes.store(change)
   564 
   565           case Session.Change_Flush if prover.defined =>
   566             val state = global_state.value
   567             if (!state.removing_versions)
   568               postponed_changes.flush(state).foreach(handle_change(_))
   569 
   570           case bad =>
   571             if (verbose) Output.warning("Ignoring bad message: " + bad.toString)
   572         }
   573         true
   574         //}}}
   575     }
   576   }
   577 
   578   private val consolidator: Thread =
   579     Standard_Thread.fork("Session.consolidator", daemon = true) {
   580       try {
   581         while (true) {
   582           Thread.sleep(consolidate_delay.ms)
   583 
   584           val state = global_state.value
   585           state.stable_tip_version match {
   586             case None =>
   587             case Some(version) =>
   588               val consolidated =
   589                 version.nodes.iterator.forall(
   590                   { case (name, _) =>
   591                       resources.session_base.loaded_theory(name) ||
   592                       state.node_consolidated(version, name) })
   593               if (!consolidated) manager.send(Consolidate_Execution)
   594           }
   595         }
   596       }
   597       catch { case Exn.Interrupt() => }
   598     }
   599 
   600 
   601   /* main operations */
   602 
   603   def snapshot(name: Document.Node.Name = Document.Node.Name.empty,
   604       pending_edits: List[Text.Edit] = Nil): Document.Snapshot =
   605     global_state.value.snapshot(name, pending_edits)
   606 
   607   def start(start_prover: Prover.Receiver => Prover)
   608   {
   609     _phase.change(
   610       {
   611         case Session.Inactive =>
   612           manager.send(Start(start_prover))
   613           post_phase(Session.Startup)
   614         case phase => error("Cannot start prover in phase " + quote(phase.print))
   615       })
   616   }
   617 
   618   def send_stop()
   619   {
   620     val was_ready =
   621       _phase.guarded_access(phase =>
   622         phase match {
   623           case Session.Startup | Session.Shutdown => None
   624           case Session.Terminated(_) => Some((false, phase))
   625           case Session.Inactive => Some((false, post_phase(Session.Terminated(Process_Result(0)))))
   626           case Session.Ready => Some((true, post_phase(Session.Shutdown)))
   627         })
   628     if (was_ready) manager.send(Stop)
   629   }
   630 
   631   def stop(): Process_Result =
   632   {
   633     send_stop()
   634     prover.await_reset()
   635 
   636     change_parser.shutdown()
   637     change_buffer.shutdown()
   638     consolidator.interrupt
   639     consolidator.join
   640     manager.shutdown()
   641     dispatcher.shutdown()
   642 
   643     phase match {
   644       case Session.Terminated(result) => result
   645       case phase => error("Bad session phase after shutdown: " + quote(phase.print))
   646     }
   647   }
   648 
   649   def protocol_command(name: String, args: String*)
   650   { manager.send(Protocol_Command(name, args.toList)) }
   651 
   652   def cancel_exec(exec_id: Document_ID.Exec)
   653   { manager.send(Cancel_Exec(exec_id)) }
   654 
   655   def update(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
   656   { if (edits.nonEmpty) manager.send_wait(Session.Raw_Edits(doc_blobs, edits)) }
   657 
   658   def update_options(options: Options)
   659   { manager.send_wait(Update_Options(options)) }
   660 
   661   def dialog_result(id: Document_ID.Generic, serial: Long, result: String)
   662   { manager.send(Session.Dialog_Result(id, serial, result)) }
   663 }