src/Pure/System/session.scala
author wenzelm
Sat, 13 Nov 2010 22:33:07 +0100
changeset 40779 e38e80686ce5
parent 40748 cc06f5528bb1
child 40812 36d4f2757f4f
permissions -rw-r--r--
somewhat adhoc replacement for 'thus' and 'hence';
complete words as short as 2 characters, e.g. "Un";
     1 /*  Title:      Pure/System/session.scala
     2     Author:     Makarius
     3     Options:    :folding=explicit:collapseFolds=1:
     4 
     5 Isabelle session, potentially with running prover.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import scala.actors.TIMEOUT
    12 import scala.actors.Actor
    13 import scala.actors.Actor._
    14 
    15 
    16 object Session
    17 {
    18   /* events */
    19 
    20   case object Global_Settings
    21   case object Perspective
    22   case object Assignment
    23   case class Commands_Changed(set: Set[Command])
    24 
    25   sealed abstract class Phase
    26   case object Inactive extends Phase
    27   case object Startup extends Phase  // transient
    28   case object Failed extends Phase
    29   case object Ready extends Phase
    30   case object Shutdown extends Phase  // transient
    31 }
    32 
    33 
    34 class Session(system: Isabelle_System)
    35 {
    36   /* real time parameters */  // FIXME properties or settings (!?)
    37 
    38   // user input (e.g. text edits, cursor movement)
    39   val input_delay = 300
    40 
    41   // prover output (markup, common messages)
    42   val output_delay = 100
    43 
    44   // GUI layout updates
    45   val update_delay = 500
    46 
    47 
    48   /* pervasive event buses */
    49 
    50   val phase_changed = new Event_Bus[Session.Phase]
    51   val global_settings = new Event_Bus[Session.Global_Settings.type]
    52   val raw_messages = new Event_Bus[Isabelle_Process.Result]
    53   val commands_changed = new Event_Bus[Session.Commands_Changed]
    54   val perspective = new Event_Bus[Session.Perspective.type]
    55   val assignments = new Event_Bus[Session.Assignment.type]
    56 
    57 
    58   /* unique ids */
    59 
    60   private var id_count: Document.ID = 0
    61   def new_id(): Document.ID = synchronized {
    62     require(id_count > java.lang.Long.MIN_VALUE)
    63     id_count -= 1
    64     id_count
    65   }
    66 
    67 
    68 
    69   /** buffered command changes (delay_first discipline) **/
    70 
    71   private case object Stop
    72 
    73   private val (_, command_change_buffer) =
    74     Simple_Thread.actor("command_change_buffer", daemon = true)
    75   //{{{
    76   {
    77     import scala.compat.Platform.currentTime
    78 
    79     var changed: Set[Command] = Set()
    80     var flush_time: Option[Long] = None
    81 
    82     def flush_timeout: Long =
    83       flush_time match {
    84         case None => 5000L
    85         case Some(time) => (time - currentTime) max 0
    86       }
    87 
    88     def flush()
    89     {
    90       if (!changed.isEmpty) commands_changed.event(Session.Commands_Changed(changed))
    91       changed = Set()
    92       flush_time = None
    93     }
    94 
    95     def invoke()
    96     {
    97       val now = currentTime
    98       flush_time match {
    99         case None => flush_time = Some(now + output_delay)
   100         case Some(time) => if (now >= time) flush()
   101       }
   102     }
   103 
   104     var finished = false
   105     while (!finished) {
   106       receiveWithin(flush_timeout) {
   107         case command: Command => changed += command; invoke()
   108         case TIMEOUT => flush()
   109         case Stop => finished = true; reply(())
   110         case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
   111       }
   112     }
   113   }
   114   //}}}
   115 
   116 
   117 
   118   /** main protocol actor **/
   119 
   120   @volatile private var syntax = new Outer_Syntax(system.symbols)
   121   def current_syntax(): Outer_Syntax = syntax
   122 
   123   @volatile private var reverse_syslog = List[XML.Elem]()
   124   def syslog(): String = reverse_syslog.reverse.map(msg => XML.content(msg).mkString).mkString("\n")
   125 
   126   @volatile private var _phase: Session.Phase = Session.Inactive
   127   def phase = _phase
   128   private def phase_=(new_phase: Session.Phase)
   129   {
   130     _phase = new_phase
   131     phase_changed.event(new_phase)
   132   }
   133 
   134   private val global_state = new Volatile(Document.State.init)
   135   def current_state(): Document.State = global_state.peek()
   136 
   137   private case object Interrupt_Prover
   138   private case class Edit_Version(edits: List[Document.Edit_Text])
   139   private case class Start(timeout: Int, args: List[String])
   140 
   141   private val (_, session_actor) = Simple_Thread.actor("session_actor", daemon = true)
   142   {
   143     var prover: Isabelle_Process with Isar_Document = null
   144 
   145 
   146     /* document changes */
   147 
   148     def handle_change(change: Document.Change)
   149     //{{{
   150     {
   151       val previous = change.previous.get_finished
   152       val (node_edits, version) = change.result.get_finished
   153 
   154       var former_assignment = global_state.peek().the_assignment(previous).get_finished
   155       for {
   156         (name, Some(cmd_edits)) <- node_edits
   157         (prev, None) <- cmd_edits
   158         removed <- previous.nodes(name).commands.get_after(prev)
   159       } former_assignment -= removed
   160 
   161       val id_edits =
   162         node_edits map {
   163           case (name, None) => (name, None)
   164           case (name, Some(cmd_edits)) =>
   165             val ids =
   166               cmd_edits map {
   167                 case (c1, c2) =>
   168                   val id1 = c1.map(_.id)
   169                   val id2 =
   170                     c2 match {
   171                       case None => None
   172                       case Some(command) =>
   173                         if (global_state.peek().lookup_command(command.id).isEmpty) {
   174                           global_state.change(_.define_command(command))
   175                           prover.define_command(command.id, system.symbols.encode(command.source))
   176                         }
   177                         Some(command.id)
   178                     }
   179                   (id1, id2)
   180               }
   181             (name -> Some(ids))
   182         }
   183       global_state.change(_.define_version(version, former_assignment))
   184       prover.edit_version(previous.id, version.id, id_edits)
   185     }
   186     //}}}
   187 
   188 
   189     /* prover results */
   190 
   191     def bad_result(result: Isabelle_Process.Result)
   192     {
   193       System.err.println("Ignoring prover result: " + result.message.toString)
   194     }
   195 
   196     def handle_result(result: Isabelle_Process.Result)
   197     //{{{
   198     {
   199       raw_messages.event(result)
   200 
   201       result.properties match {
   202         case Position.Id(state_id) =>
   203           try {
   204             val st = global_state.change_yield(_.accumulate(state_id, result.message))
   205             command_change_buffer ! st.command
   206           }
   207           catch { case _: Document.State.Fail => bad_result(result) }
   208         case _ =>
   209           if (result.is_syslog) {
   210             reverse_syslog ::= result.message
   211             if (result.is_ready) {
   212               // FIXME move to ML side
   213               syntax += ("hence", Keyword.PRF_ASM_GOAL, "then have")
   214               syntax += ("thus", Keyword.PRF_ASM_GOAL, "then show")
   215               phase = Session.Ready
   216             }
   217             else if (result.is_exit && phase == Session.Startup) phase = Session.Failed
   218             else if (result.is_exit) phase = Session.Inactive
   219           }
   220           else if (result.is_stdout) { }
   221           else if (result.is_status) {
   222             result.body match {
   223               case List(Isar_Document.Assign(id, edits)) =>
   224                 try {
   225                   val cmds: List[Command] = global_state.change_yield(_.assign(id, edits))
   226                   for (cmd <- cmds) command_change_buffer ! cmd
   227                   assignments.event(Session.Assignment)
   228                 }
   229                 catch { case _: Document.State.Fail => bad_result(result) }
   230               case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
   231               case List(Keyword.Keyword_Decl(name)) => syntax += name
   232               case _ => bad_result(result)
   233             }
   234           }
   235           else bad_result(result)
   236         }
   237     }
   238     //}}}
   239 
   240 
   241     /* main loop */
   242 
   243     var finished = false
   244     while (!finished) {
   245       receive {
   246         case Interrupt_Prover =>
   247           if (prover != null) prover.interrupt
   248 
   249         case Edit_Version(edits) if prover != null =>
   250           val previous = global_state.peek().history.tip.version
   251           val result = Future.fork { Thy_Syntax.text_edits(Session.this, previous.join, edits) }
   252           val change = global_state.change_yield(_.extend_history(previous, edits, result))
   253 
   254           val this_actor = self
   255           change.version.map(_ => {
   256             assignments.await { global_state.peek().is_assigned(previous.get_finished) }
   257             this_actor ! change })
   258 
   259           reply(())
   260 
   261         case change: Document.Change if prover != null => handle_change(change)
   262 
   263         case result: Isabelle_Process.Result => handle_result(result)
   264 
   265         case Start(timeout, args) if prover == null =>
   266           if (phase == Session.Inactive || phase == Session.Failed) {
   267             phase = Session.Startup
   268             prover = new Isabelle_Process(system, timeout, self, args:_*) with Isar_Document
   269           }
   270 
   271         case Stop =>
   272           if (phase == Session.Ready) {
   273             global_state.change(_ => Document.State.init)  // FIXME event bus!?
   274             phase = Session.Shutdown
   275             prover.terminate
   276             phase = Session.Inactive
   277           }
   278           finished = true
   279           reply(())
   280 
   281         case bad if prover != null =>
   282           System.err.println("session_actor: ignoring bad message " + bad)
   283       }
   284     }
   285   }
   286 
   287 
   288 
   289   /** main methods **/
   290 
   291   def start(timeout: Int, args: List[String]) { session_actor ! Start(timeout, args) }
   292 
   293   def stop() { command_change_buffer !? Stop; session_actor !? Stop }
   294 
   295   def interrupt() { session_actor ! Interrupt_Prover }
   296 
   297   def edit_version(edits: List[Document.Edit_Text]) { session_actor !? Edit_Version(edits) }
   298 
   299   def snapshot(name: String, pending_edits: List[Text.Edit]): Document.Snapshot =
   300     global_state.peek().snapshot(name, pending_edits)
   301 }