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