src/Pure/PIDE/session.scala
author wenzelm
Sat May 03 22:47:43 2014 +0200 (2014-05-03 ago)
changeset 56843 b2bfcd8cda80
parent 56799 00b13fb87b3a
child 56864 0446c7ac2e32
permissions -rw-r--r--
support for path completion based on file-system content;
     1 /*  Title:      Pure/PIDE/session.scala
     2     Author:     Makarius
     3     Options:    :folding=explicit:collapseFolds=1:
     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.empty[Consumer[A]])
    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     doc_blobs: Document.Blobs,
    51     syntax_changed: Boolean,
    52     deps_changed: Boolean,
    53     doc_edits: List[Document.Edit_Command],
    54     version: Document.Version)
    55 
    56 
    57   /* events */
    58 
    59   //{{{
    60   case class Statistics(props: Properties.T)
    61   case class Global_Options(options: Options)
    62   case object Caret_Focus
    63   case class Raw_Edits(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
    64   case class Dialog_Result(id: Document_ID.Generic, serial: Long, result: String)
    65   case class Commands_Changed(
    66     assignment: Boolean, nodes: Set[Document.Node.Name], commands: Set[Command])
    67 
    68   sealed abstract class Phase
    69   case object Inactive extends Phase
    70   case object Startup extends Phase  // transient
    71   case object Failed extends Phase
    72   case object Ready extends Phase
    73   case object Shutdown extends Phase  // transient
    74   //}}}
    75 
    76 
    77   /* syslog */
    78 
    79   private[Session] class Syslog(limit: Int)
    80   {
    81     private var queue = Queue.empty[XML.Elem]
    82     private var length = 0
    83 
    84     def += (msg: XML.Elem): Unit = synchronized {
    85       queue = queue.enqueue(msg)
    86       length += 1
    87       if (length > limit) queue = queue.dequeue._2
    88     }
    89 
    90     def content: String = synchronized {
    91       cat_lines(queue.iterator.map(XML.content)) +
    92       (if (length > limit) "\n(A total of " + length + " messages...)" else "")
    93     }
    94   }
    95 
    96 
    97   /* protocol handlers */
    98 
    99   abstract class Protocol_Handler
   100   {
   101     def stop(prover: Prover): Unit = {}
   102     val functions: Map[String, (Prover, Prover.Protocol_Output) => Boolean]
   103   }
   104 
   105   class Protocol_Handlers(
   106     handlers: Map[String, Session.Protocol_Handler] = Map.empty,
   107     functions: Map[String, Prover.Protocol_Output => Boolean] = Map.empty)
   108   {
   109     def get(name: String): Option[Protocol_Handler] = handlers.get(name)
   110 
   111     def add(prover: Prover, name: String): Protocol_Handlers =
   112     {
   113       val (handlers1, functions1) =
   114         handlers.get(name) match {
   115           case Some(old_handler) =>
   116             Output.warning("Redefining protocol handler: " + name)
   117             old_handler.stop(prover)
   118             (handlers - name, functions -- old_handler.functions.keys)
   119           case None => (handlers, functions)
   120         }
   121 
   122       val (handlers2, functions2) =
   123         try {
   124           val new_handler = Class.forName(name).newInstance.asInstanceOf[Protocol_Handler]
   125           val new_functions =
   126             for ((a, f) <- new_handler.functions.toList) yield
   127               (a, (msg: Prover.Protocol_Output) => f(prover, msg))
   128 
   129           val dups = for ((a, _) <- new_functions if functions1.isDefinedAt(a)) yield a
   130           if (!dups.isEmpty) error("Duplicate protocol functions: " + commas_quote(dups))
   131 
   132           (handlers1 + (name -> new_handler), functions1 ++ new_functions)
   133         }
   134         catch {
   135           case exn: Throwable =>
   136             Output.error_message(
   137               "Failed to initialize protocol handler: " + quote(name) + "\n" + Exn.message(exn))
   138             (handlers1, functions1)
   139         }
   140 
   141       new Protocol_Handlers(handlers2, functions2)
   142     }
   143 
   144     def invoke(msg: Prover.Protocol_Output): Boolean =
   145       msg.properties match {
   146         case Markup.Function(a) if functions.isDefinedAt(a) =>
   147           try { functions(a)(msg) }
   148           catch {
   149             case exn: Throwable =>
   150               Output.error_message(
   151                 "Failed invocation of protocol function: " + quote(a) + "\n" + Exn.message(exn))
   152             false
   153           }
   154         case _ => false
   155       }
   156 
   157     def stop(prover: Prover): Protocol_Handlers =
   158     {
   159       for ((_, handler) <- handlers) handler.stop(prover)
   160       new Protocol_Handlers()
   161     }
   162   }
   163 }
   164 
   165 
   166 class Session(val resources: Resources)
   167 {
   168   /* global flags */
   169 
   170   @volatile var timing: Boolean = false
   171   @volatile var verbose: Boolean = false
   172 
   173 
   174   /* tuning parameters */
   175 
   176   def output_delay: Time = Time.seconds(0.1)  // prover output (markup, common messages)
   177   def message_delay: Time = Time.seconds(0.1)  // prover input/output messages
   178   def prune_delay: Time = Time.seconds(60.0)  // prune history -- delete old versions
   179   def prune_size: Int = 0  // size of retained history
   180   def syslog_limit: Int = 100
   181   def reparse_limit: Int = 0
   182 
   183 
   184   /* outlets */
   185 
   186   private val dispatcher =
   187     Consumer_Thread.fork[() => Unit]("Session.dispatcher", daemon = true) { case e => e(); true }
   188 
   189   val statistics = new Session.Outlet[Session.Statistics](dispatcher)
   190   val global_options = new Session.Outlet[Session.Global_Options](dispatcher)
   191   val caret_focus = new Session.Outlet[Session.Caret_Focus.type](dispatcher)
   192   val raw_edits = new Session.Outlet[Session.Raw_Edits](dispatcher)
   193   val commands_changed = new Session.Outlet[Session.Commands_Changed](dispatcher)
   194   val phase_changed = new Session.Outlet[Session.Phase](dispatcher)
   195   val syslog_messages = new Session.Outlet[Prover.Output](dispatcher)
   196   val raw_output_messages = new Session.Outlet[Prover.Output](dispatcher)
   197   val all_messages = new Session.Outlet[Prover.Message](dispatcher)  // potential bottle-neck
   198   val trace_events = new Session.Outlet[Simplifier_Trace.Event.type](dispatcher)
   199 
   200 
   201 
   202   /** main protocol manager **/
   203 
   204   /* internal messages */
   205 
   206   private case class Start(name: String, args: List[String])
   207   private case object Stop
   208   private case class Cancel_Exec(exec_id: Document_ID.Exec)
   209   private case class Protocol_Command(name: String, args: List[String])
   210   private case class Update_Options(options: Options)
   211   private case object Prune_History
   212 
   213 
   214   /* global state */
   215 
   216   private val syslog = new Session.Syslog(syslog_limit)
   217   def syslog_content(): String = syslog.content
   218 
   219   @volatile private var _phase: Session.Phase = Session.Inactive
   220   private def phase_=(new_phase: Session.Phase)
   221   {
   222     _phase = new_phase
   223     phase_changed.post(new_phase)
   224   }
   225   def phase = _phase
   226   def is_ready: Boolean = phase == Session.Ready
   227 
   228   private val global_state = Synchronized(Document.State.init)
   229   def current_state(): Document.State = global_state.value
   230 
   231   def recent_syntax(): Prover.Syntax =
   232   {
   233     val version = current_state().recent_finished.version.get_finished
   234     version.syntax getOrElse resources.base_syntax
   235   }
   236 
   237 
   238   /* protocol handlers */
   239 
   240   @volatile private var _protocol_handlers = new Session.Protocol_Handlers()
   241 
   242   def protocol_handler(name: String): Option[Session.Protocol_Handler] =
   243     _protocol_handlers.get(name)
   244 
   245 
   246   /* theory files */
   247 
   248   def header_edit(name: Document.Node.Name, header: Document.Node.Header): Document.Edit_Text =
   249   {
   250     val header1 =
   251       if (resources.loaded_theories(name.theory))
   252         header.error("Cannot update finished theory " + quote(name.theory))
   253       else header
   254     (name, Document.Node.Deps(header1))
   255   }
   256 
   257 
   258   /* pipelined change parsing */
   259 
   260   private case class Text_Edits(
   261     previous: Future[Document.Version],
   262     doc_blobs: Document.Blobs,
   263     text_edits: List[Document.Edit_Text],
   264     version_result: Promise[Document.Version])
   265 
   266   private val change_parser = Consumer_Thread.fork[Text_Edits]("change_parser", daemon = true)
   267   {
   268     case Text_Edits(previous, doc_blobs, text_edits, version_result) =>
   269       val prev = previous.get_finished
   270       val change =
   271         Timing.timeit("parse_change", timing) {
   272           resources.parse_change(reparse_limit, prev, doc_blobs, text_edits)
   273         }
   274       version_result.fulfill(change.version)
   275       manager.send(change)
   276       true
   277   }
   278 
   279 
   280   /* buffered changes */
   281 
   282   private object change_buffer
   283   {
   284     private var assignment: Boolean = false
   285     private var nodes: Set[Document.Node.Name] = Set.empty
   286     private var commands: Set[Command] = Set.empty
   287 
   288     def flush(): Unit = synchronized {
   289       if (assignment || !nodes.isEmpty || !commands.isEmpty)
   290         commands_changed.post(Session.Commands_Changed(assignment, nodes, commands))
   291       assignment = false
   292       nodes = Set.empty
   293       commands = Set.empty
   294     }
   295     private val delay_flush = Simple_Thread.delay_first(output_delay) { flush() }
   296 
   297     def invoke(assign: Boolean, cmds: List[Command]): Unit = synchronized {
   298       assignment |= assign
   299       for (command <- cmds) {
   300         nodes += command.node_name
   301         commands += command
   302       }
   303       delay_flush.invoke()
   304     }
   305 
   306     def shutdown()
   307     {
   308       delay_flush.revoke()
   309       flush()
   310     }
   311   }
   312 
   313 
   314   /* postponed changes */
   315 
   316   private object postponed_changes
   317   {
   318     private var postponed: List[Session.Change] = Nil
   319 
   320     def store(change: Session.Change): Unit = synchronized { postponed ::= change }
   321 
   322     def flush(): Unit = synchronized {
   323       val state = global_state.value
   324       val (assigned, unassigned) = postponed.partition(change => state.is_assigned(change.previous))
   325       postponed = unassigned
   326       assigned.reverseIterator.foreach(change => manager.send(change))
   327     }
   328   }
   329 
   330 
   331   /* prover process */
   332 
   333   private object prover
   334   {
   335     private val variable = Synchronized(None: Option[Prover])
   336 
   337     def defined: Boolean = variable.value.isDefined
   338     def get: Prover = variable.value.get
   339     def set(p: Prover) { variable.change(_ => Some(p)) }
   340     def reset { variable.change(_ => None) }
   341     def await_reset() { variable.guarded_access({ case None => Some((), None) case _ => None }) }
   342   }
   343 
   344 
   345   /* manager thread */
   346 
   347   private val delay_prune = Simple_Thread.delay_first(prune_delay) { manager.send(Prune_History) }
   348 
   349   private val manager: Consumer_Thread[Any] =
   350   {
   351     /* raw edits */
   352 
   353     def handle_raw_edits(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
   354     //{{{
   355     {
   356       require(prover.defined)
   357 
   358       prover.get.discontinue_execution()
   359 
   360       val previous = global_state.value.history.tip.version
   361       val version = Future.promise[Document.Version]
   362       global_state.change(_.continue_history(previous, edits, version))
   363 
   364       raw_edits.post(Session.Raw_Edits(doc_blobs, edits))
   365       change_parser.send(Text_Edits(previous, doc_blobs, edits, version))
   366     }
   367     //}}}
   368 
   369 
   370     /* resulting changes */
   371 
   372     def handle_change(change: Session.Change)
   373     //{{{
   374     {
   375       require(prover.defined)
   376 
   377       def id_command(command: Command)
   378       {
   379         for {
   380           digest <- command.blobs_digests
   381           if !global_state.value.defined_blob(digest)
   382         } {
   383           change.doc_blobs.get(digest) match {
   384             case Some(blob) =>
   385               global_state.change(_.define_blob(digest))
   386               prover.get.define_blob(digest, blob.bytes)
   387             case None =>
   388               Output.error_message("Missing blob for SHA1 digest " + digest)
   389           }
   390         }
   391 
   392         if (!global_state.value.defined_command(command.id)) {
   393           global_state.change(_.define_command(command))
   394           prover.get.define_command(command)
   395         }
   396       }
   397       change.doc_edits foreach {
   398         case (_, edit) =>
   399           edit foreach { case (c1, c2) => c1 foreach id_command; c2 foreach id_command }
   400       }
   401 
   402       val assignment = global_state.value.the_assignment(change.previous).check_finished
   403       global_state.change(_.define_version(change.version, assignment))
   404       prover.get.update(change.previous.id, change.version.id, change.doc_edits)
   405       resources.commit(change)
   406     }
   407     //}}}
   408 
   409 
   410     /* prover output */
   411 
   412     def handle_output(output: Prover.Output)
   413     //{{{
   414     {
   415       def bad_output()
   416       {
   417         if (verbose)
   418           Output.warning("Ignoring bad prover output: " + output.message.toString)
   419       }
   420 
   421       def accumulate(state_id: Document_ID.Generic, message: XML.Elem)
   422       {
   423         try {
   424           val st = global_state.change_result(_.accumulate(state_id, message))
   425           change_buffer.invoke(false, List(st.command))
   426         }
   427         catch {
   428           case _: Document.State.Fail => bad_output()
   429         }
   430       }
   431 
   432       output match {
   433         case msg: Prover.Protocol_Output =>
   434           val handled = _protocol_handlers.invoke(msg)
   435           if (!handled) {
   436             msg.properties match {
   437               case Markup.Protocol_Handler(name) if prover.defined =>
   438                 _protocol_handlers = _protocol_handlers.add(prover.get, name)
   439 
   440               case Protocol.Command_Timing(state_id, timing) if prover.defined =>
   441                 val message = XML.elem(Markup.STATUS, List(XML.Elem(Markup.Timing(timing), Nil)))
   442                 accumulate(state_id, prover.get.xml_cache.elem(message))
   443 
   444               case Markup.Assign_Update =>
   445                 msg.text match {
   446                   case Protocol.Assign_Update(id, update) =>
   447                     try {
   448                       val cmds = global_state.change_result(_.assign(id, update))
   449                       change_buffer.invoke(true, cmds)
   450                     }
   451                     catch { case _: Document.State.Fail => bad_output() }
   452                     postponed_changes.flush()
   453                   case _ => bad_output()
   454                 }
   455                 delay_prune.invoke()
   456 
   457               case Markup.Removed_Versions =>
   458                 msg.text match {
   459                   case Protocol.Removed(removed) =>
   460                     try {
   461                       global_state.change(_.removed_versions(removed))
   462                     }
   463                     catch { case _: Document.State.Fail => bad_output() }
   464                   case _ => bad_output()
   465                 }
   466 
   467               case Markup.ML_Statistics(props) =>
   468                 statistics.post(Session.Statistics(props))
   469 
   470               case Markup.Task_Statistics(props) =>
   471                 // FIXME
   472 
   473               case _ => bad_output()
   474             }
   475           }
   476         case _ =>
   477           output.properties match {
   478             case Position.Id(state_id) =>
   479               accumulate(state_id, output.message)
   480 
   481             case _ if output.is_init =>
   482               phase = Session.Ready
   483 
   484             case Markup.Return_Code(rc) if output.is_exit =>
   485               if (rc == 0) phase = Session.Inactive
   486               else phase = Session.Failed
   487               prover.reset
   488 
   489             case _ => raw_output_messages.post(output)
   490           }
   491         }
   492     }
   493     //}}}
   494 
   495 
   496     /* main thread */
   497 
   498     Consumer_Thread.fork[Any]("Session.manager", daemon = true)
   499     {
   500       case arg: Any =>
   501         //{{{
   502         arg match {
   503           case output: Prover.Output =>
   504             if (output.is_stdout || output.is_stderr)
   505               raw_output_messages.post(output)
   506             else handle_output(output)
   507 
   508             if (output.is_syslog) {
   509               syslog += output.message
   510               syslog_messages.post(output)
   511             }
   512 
   513             all_messages.post(output)
   514 
   515           case input: Prover.Input =>
   516             all_messages.post(input)
   517 
   518           case Start(name, args) if !prover.defined =>
   519             if (phase == Session.Inactive || phase == Session.Failed) {
   520               phase = Session.Startup
   521               prover.set(resources.start_prover(manager.send(_), name, args))
   522             }
   523 
   524           case Stop =>
   525             if (prover.defined && is_ready) {
   526               _protocol_handlers = _protocol_handlers.stop(prover.get)
   527               global_state.change(_ => Document.State.init)
   528               phase = Session.Shutdown
   529               prover.get.terminate
   530             }
   531 
   532           case Prune_History =>
   533             if (prover.defined) {
   534               val old_versions = global_state.change_result(_.prune_history(prune_size))
   535               if (!old_versions.isEmpty) prover.get.remove_versions(old_versions)
   536             }
   537 
   538           case Update_Options(options) =>
   539             if (prover.defined && is_ready) {
   540               prover.get.options(options)
   541               handle_raw_edits(Document.Blobs.empty, Nil)
   542             }
   543             global_options.post(Session.Global_Options(options))
   544 
   545           case Cancel_Exec(exec_id) if prover.defined =>
   546             prover.get.cancel_exec(exec_id)
   547 
   548           case Session.Raw_Edits(doc_blobs, edits) if prover.defined =>
   549             handle_raw_edits(doc_blobs, edits)
   550 
   551           case Session.Dialog_Result(id, serial, result) if prover.defined =>
   552             prover.get.dialog_result(serial, result)
   553             handle_output(new Prover.Output(Protocol.Dialog_Result(id, serial, result)))
   554 
   555           case Protocol_Command(name, args) if prover.defined =>
   556             prover.get.protocol_command(name, args:_*)
   557 
   558           case change: Session.Change if prover.defined =>
   559             if (global_state.value.is_assigned(change.previous))
   560               handle_change(change)
   561             else postponed_changes.store(change)
   562         }
   563         true
   564         //}}}
   565     }
   566   }
   567 
   568 
   569   /* main operations */
   570 
   571   def snapshot(name: Document.Node.Name = Document.Node.Name.empty,
   572       pending_edits: List[Text.Edit] = Nil): Document.Snapshot =
   573     global_state.value.snapshot(name, pending_edits)
   574 
   575   def start(name: String, args: List[String])
   576   { manager.send(Start(name, args)) }
   577 
   578   def stop()
   579   {
   580     manager.send_wait(Stop)
   581     prover.await_reset()
   582     change_parser.shutdown()
   583     change_buffer.shutdown()
   584     delay_prune.revoke()
   585     manager.shutdown()
   586     dispatcher.shutdown()
   587   }
   588 
   589   def protocol_command(name: String, args: String*)
   590   { manager.send(Protocol_Command(name, args.toList)) }
   591 
   592   def cancel_exec(exec_id: Document_ID.Exec)
   593   { manager.send(Cancel_Exec(exec_id)) }
   594 
   595   def update(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
   596   { if (!edits.isEmpty) manager.send_wait(Session.Raw_Edits(doc_blobs, edits)) }
   597 
   598   def update_options(options: Options)
   599   { manager.send_wait(Update_Options(options)) }
   600 
   601   def dialog_result(id: Document_ID.Generic, serial: Long, result: String)
   602   { manager.send(Session.Dialog_Result(id, serial, result)) }
   603 }