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