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