src/Pure/System/session.scala
author wenzelm
Wed Aug 31 20:47:33 2011 +0200 (2011-08-31 ago)
changeset 44612 990ac978854c
parent 44608 76c2e3ddc183
child 44615 a4ff8a787202
permissions -rw-r--r--
explicit cancel_execution before queueing new edits -- potential performance improvement for machines with few cores;
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@43651
     5
Main Isabelle/Scala session, potentially with running prover process.
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@43716
    21
  //{{{
wenzelm@34791
    22
  case object Global_Settings
wenzelm@37849
    23
  case object Perspective
wenzelm@38849
    24
  case object Assignment
wenzelm@44608
    25
  case class Commands_Changed(nodes: Set[String], commands: Set[Command])
wenzelm@39630
    26
wenzelm@39630
    27
  sealed abstract class Phase
wenzelm@39630
    28
  case object Inactive extends Phase
wenzelm@39701
    29
  case object Startup extends Phase  // transient
wenzelm@39701
    30
  case object Failed extends Phase
wenzelm@39630
    31
  case object Ready extends Phase
wenzelm@39701
    32
  case object Shutdown extends Phase  // transient
wenzelm@43716
    33
  //}}}
wenzelm@34791
    34
}
wenzelm@34791
    35
wenzelm@34777
    36
wenzelm@44574
    37
class Session(thy_load: Thy_Load)
wenzelm@34777
    38
{
wenzelm@37849
    39
  /* real time parameters */  // FIXME properties or settings (!?)
wenzelm@37849
    40
wenzelm@43716
    41
  val input_delay = Time.seconds(0.3)  // user input (e.g. text edits, cursor movement)
wenzelm@43716
    42
  val output_delay = Time.seconds(0.1)  // prover output (markup, common messages)
wenzelm@43716
    43
  val update_delay = Time.seconds(0.5)  // GUI layout updates
wenzelm@44573
    44
  val load_delay = Time.seconds(0.5)  // file load operations (new buffers etc.)
wenzelm@37849
    45
wenzelm@37849
    46
wenzelm@34809
    47
  /* pervasive event buses */
wenzelm@34809
    48
wenzelm@34809
    49
  val global_settings = new Event_Bus[Session.Global_Settings.type]
wenzelm@37849
    50
  val perspective = new Event_Bus[Session.Perspective.type]
wenzelm@38849
    51
  val assignments = new Event_Bus[Session.Assignment.type]
wenzelm@43716
    52
  val commands_changed = new Event_Bus[Session.Commands_Changed]
wenzelm@43716
    53
  val phase_changed = new Event_Bus[Session.Phase]
wenzelm@43721
    54
  val raw_messages = new Event_Bus[Isabelle_Process.Message]
wenzelm@43716
    55
wenzelm@34809
    56
wenzelm@34809
    57
wenzelm@38841
    58
  /** buffered command changes (delay_first discipline) **/
wenzelm@38841
    59
wenzelm@43716
    60
  //{{{
wenzelm@38841
    61
  private case object Stop
wenzelm@38841
    62
wenzelm@39572
    63
  private val (_, command_change_buffer) =
wenzelm@39572
    64
    Simple_Thread.actor("command_change_buffer", daemon = true)
wenzelm@38841
    65
  {
wenzelm@44608
    66
    var changed_nodes: Set[String] = Set.empty
wenzelm@44608
    67
    var changed_commands: Set[Command] = Set.empty
wenzelm@44608
    68
    def changed: Boolean = !changed_nodes.isEmpty || !changed_commands.isEmpty
wenzelm@44608
    69
wenzelm@38841
    70
    var flush_time: Option[Long] = None
wenzelm@38841
    71
wenzelm@38841
    72
    def flush_timeout: Long =
wenzelm@38841
    73
      flush_time match {
wenzelm@38841
    74
        case None => 5000L
wenzelm@40848
    75
        case Some(time) => (time - System.currentTimeMillis()) max 0
wenzelm@38841
    76
      }
wenzelm@38841
    77
wenzelm@38841
    78
    def flush()
wenzelm@38841
    79
    {
wenzelm@44608
    80
      if (changed)
wenzelm@44608
    81
        commands_changed.event(Session.Commands_Changed(changed_nodes, changed_commands))
wenzelm@44608
    82
      changed_nodes = Set.empty
wenzelm@44608
    83
      changed_commands = Set.empty
wenzelm@38841
    84
      flush_time = None
wenzelm@38841
    85
    }
wenzelm@38841
    86
wenzelm@38841
    87
    def invoke()
wenzelm@38841
    88
    {
wenzelm@40848
    89
      val now = System.currentTimeMillis()
wenzelm@38841
    90
      flush_time match {
wenzelm@40848
    91
        case None => flush_time = Some(now + output_delay.ms)
wenzelm@38841
    92
        case Some(time) => if (now >= time) flush()
wenzelm@38841
    93
      }
wenzelm@38841
    94
    }
wenzelm@38841
    95
wenzelm@38841
    96
    var finished = false
wenzelm@38841
    97
    while (!finished) {
wenzelm@38841
    98
      receiveWithin(flush_timeout) {
wenzelm@44608
    99
        case command: Command =>
wenzelm@44608
   100
          changed_nodes += command.node_name
wenzelm@44608
   101
          changed_commands += command
wenzelm@44608
   102
          invoke()
wenzelm@38841
   103
        case TIMEOUT => flush()
wenzelm@39630
   104
        case Stop => finished = true; reply(())
wenzelm@38841
   105
        case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
wenzelm@38841
   106
      }
wenzelm@38841
   107
    }
wenzelm@38841
   108
  }
wenzelm@38841
   109
  //}}}
wenzelm@38841
   110
wenzelm@38841
   111
wenzelm@38841
   112
wenzelm@38841
   113
  /** main protocol actor **/
wenzelm@34809
   114
wenzelm@43651
   115
  /* global state */
wenzelm@43644
   116
wenzelm@43716
   117
  @volatile var verbose: Boolean = false
wenzelm@43716
   118
wenzelm@43695
   119
  @volatile private var syntax = new Outer_Syntax
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@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@43716
   131
  def phase = _phase
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@43719
   135
  def current_state(): Document.State = global_state()
wenzelm@34816
   136
wenzelm@43716
   137
  def snapshot(name: String, pending_edits: List[Text.Edit]): Document.Snapshot =
wenzelm@43719
   138
    global_state().snapshot(name, pending_edits)
wenzelm@43716
   139
wenzelm@43651
   140
wenzelm@43651
   141
  /* theory files */
wenzelm@43651
   142
wenzelm@44442
   143
  def header_edit(name: String, master_dir: String,
wenzelm@44442
   144
    header: Document.Node_Header): Document.Edit_Text =
wenzelm@44442
   145
  {
wenzelm@44442
   146
    def norm_import(s: String): String =
wenzelm@44442
   147
    {
wenzelm@44442
   148
      val thy_name = Thy_Header.base_name(s)
wenzelm@44442
   149
      if (thy_load.is_loaded(thy_name)) thy_name
wenzelm@44574
   150
      else thy_load.append(master_dir, Thy_Header.thy_path(Path.explode(s)))
wenzelm@44442
   151
    }
wenzelm@44442
   152
    def norm_use(s: String): String =
wenzelm@44574
   153
      thy_load.append(master_dir, Path.explode(s))
wenzelm@44442
   154
wenzelm@44442
   155
    val header1: Document.Node_Header =
wenzelm@44442
   156
      header match {
wenzelm@44442
   157
        case Exn.Res(Thy_Header(thy_name, _, _))
wenzelm@44442
   158
        if (thy_load.is_loaded(thy_name)) =>
wenzelm@44442
   159
          Exn.Exn(ERROR("Attempt to update loaded theory " + quote(thy_name)))
wenzelm@44442
   160
        case _ => Document.Node.norm_header(norm_import, norm_use, header)
wenzelm@44442
   161
      }
wenzelm@44442
   162
    (name, Document.Node.Header(header1))
wenzelm@44442
   163
  }
wenzelm@44442
   164
wenzelm@43651
   165
wenzelm@43651
   166
  /* actor messages */
wenzelm@43651
   167
wenzelm@43716
   168
  private case class Start(timeout: Time, args: List[String])
wenzelm@43716
   169
  private case object Interrupt
wenzelm@44385
   170
  private case class Init_Node(name: String, master_dir: String,
wenzelm@44385
   171
    header: Document.Node_Header, perspective: Text.Perspective, text: String)
wenzelm@44385
   172
  private case class Edit_Node(name: String, master_dir: String,
wenzelm@44385
   173
    header: Document.Node_Header, perspective: Text.Perspective, edits: List[Text.Edit])
wenzelm@43722
   174
  private case class Change_Node(
wenzelm@43722
   175
    name: String,
wenzelm@43722
   176
    doc_edits: List[Document.Edit_Command],
wenzelm@43722
   177
    previous: Document.Version,
wenzelm@43722
   178
    version: Document.Version)
wenzelm@41534
   179
wenzelm@39572
   180
  private val (_, session_actor) = Simple_Thread.actor("session_actor", daemon = true)
wenzelm@38639
   181
  {
wenzelm@43648
   182
    val this_actor = self
wenzelm@43649
   183
    var prover: Option[Isabelle_Process with Isar_Document] = None
wenzelm@34809
   184
wenzelm@34809
   185
wenzelm@44436
   186
    /* perspective */
wenzelm@44436
   187
wenzelm@44436
   188
    def update_perspective(name: String, text_perspective: Text.Perspective)
wenzelm@44436
   189
    {
wenzelm@44475
   190
      val previous = global_state().tip_version
wenzelm@44436
   191
      val (perspective, version) = Thy_Syntax.edit_perspective(previous, name, text_perspective)
wenzelm@44436
   192
wenzelm@44436
   193
      val text_edits: List[Document.Edit_Text] =
wenzelm@44436
   194
        List((name, Document.Node.Perspective(text_perspective)))
wenzelm@44436
   195
      val change =
wenzelm@44436
   196
        global_state.change_yield(
wenzelm@44446
   197
          _.continue_history(Future.value(previous), text_edits, Future.value(version)))
wenzelm@44436
   198
wenzelm@44477
   199
      val assignment = global_state().the_assignment(previous).check_finished
wenzelm@44479
   200
      global_state.change(_.define_version(version, assignment))
wenzelm@44476
   201
      global_state.change_yield(_.assign(version.id, Document.no_assign))
wenzelm@44436
   202
wenzelm@44436
   203
      prover.get.update_perspective(previous.id, version.id, name, perspective)
wenzelm@44436
   204
    }
wenzelm@44436
   205
wenzelm@44436
   206
wenzelm@43716
   207
    /* incoming edits */
wenzelm@43716
   208
wenzelm@44182
   209
    def handle_edits(name: String, master_dir: String,
wenzelm@44384
   210
        header: Document.Node_Header, edits: List[Document.Node.Edit[Text.Edit, Text.Perspective]])
wenzelm@43716
   211
    //{{{
wenzelm@43716
   212
    {
wenzelm@43716
   213
      val syntax = current_syntax()
wenzelm@43719
   214
      val previous = global_state().history.tip.version
wenzelm@44185
   215
wenzelm@44612
   216
      prover.get.cancel_execution()
wenzelm@44612
   217
wenzelm@44442
   218
      val text_edits = header_edit(name, master_dir, header) :: edits.map(edit => (name, edit))
wenzelm@44185
   219
      val result = Future.fork { Thy_Syntax.text_edits(syntax, previous.join, text_edits) }
wenzelm@43722
   220
      val change =
wenzelm@44446
   221
        global_state.change_yield(_.continue_history(previous, text_edits, result.map(_._2)))
wenzelm@43716
   222
wenzelm@43722
   223
      result.map {
wenzelm@44157
   224
        case (doc_edits, _) =>
wenzelm@43722
   225
          assignments.await { global_state().is_assigned(previous.get_finished) }
wenzelm@44157
   226
          this_actor ! Change_Node(name, doc_edits, previous.join, change.version.join)
wenzelm@43722
   227
      }
wenzelm@43716
   228
    }
wenzelm@43716
   229
    //}}}
wenzelm@43716
   230
wenzelm@43716
   231
wenzelm@44436
   232
    /* exec state assignment */
wenzelm@44436
   233
wenzelm@44476
   234
    def handle_assign(id: Document.Version_ID, assign: Document.Assign)
wenzelm@44436
   235
    //{{{
wenzelm@44436
   236
    {
wenzelm@44476
   237
      val cmds = global_state.change_yield(_.assign(id, assign))
wenzelm@44436
   238
      for (cmd <- cmds) command_change_buffer ! cmd
wenzelm@44436
   239
      assignments.event(Session.Assignment)
wenzelm@44436
   240
    }
wenzelm@44436
   241
    //}}}
wenzelm@44436
   242
wenzelm@44436
   243
wenzelm@43716
   244
    /* resulting changes */
wenzelm@34809
   245
wenzelm@43722
   246
    def handle_change(change: Change_Node)
wenzelm@38221
   247
    //{{{
wenzelm@34809
   248
    {
wenzelm@43722
   249
      val previous = change.previous
wenzelm@43722
   250
      val version = change.version
wenzelm@43722
   251
      val name = change.name
wenzelm@43722
   252
      val doc_edits = change.doc_edits
wenzelm@38366
   253
wenzelm@44383
   254
      def id_command(command: Command)
wenzelm@43720
   255
      {
wenzelm@44582
   256
        if (!global_state().defined_command(command.id)) {
wenzelm@43720
   257
          global_state.change(_.define_command(command))
wenzelm@43720
   258
          prover.get.define_command(command.id, Symbol.encode(command.source))
wenzelm@43720
   259
        }
wenzelm@43720
   260
      }
wenzelm@44383
   261
      doc_edits foreach {
wenzelm@44383
   262
        case (_, edit) =>
wenzelm@44383
   263
          edit foreach { case (c1, c2) => c1 foreach id_command; c2 foreach id_command }
wenzelm@44383
   264
      }
wenzelm@43722
   265
wenzelm@44479
   266
      val assignment = global_state().the_assignment(previous).check_finished
wenzelm@44479
   267
      global_state.change(_.define_version(version, assignment))
wenzelm@44481
   268
      prover.get.update(previous.id, version.id, doc_edits)
wenzelm@34809
   269
    }
wenzelm@38221
   270
    //}}}
wenzelm@34809
   271
wenzelm@34809
   272
wenzelm@34809
   273
    /* prover results */
wenzelm@34809
   274
wenzelm@34809
   275
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   276
    //{{{
wenzelm@34809
   277
    {
wenzelm@43716
   278
      def bad_result(result: Isabelle_Process.Result)
wenzelm@43716
   279
      {
wenzelm@43716
   280
        if (verbose)
wenzelm@43716
   281
          System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@43716
   282
      }
wenzelm@43716
   283
wenzelm@38722
   284
      result.properties match {
wenzelm@43748
   285
        case Position.Id(state_id) if !result.is_raw =>
wenzelm@38370
   286
          try {
wenzelm@38841
   287
            val st = global_state.change_yield(_.accumulate(state_id, result.message))
wenzelm@38841
   288
            command_change_buffer ! st.command
wenzelm@38370
   289
          }
wenzelm@43748
   290
          catch {
wenzelm@43748
   291
            case _: Document.State.Fail => bad_result(result)
wenzelm@43748
   292
          }
wenzelm@43748
   293
        case Markup.Invoke_Scala(name, id) if result.is_raw =>
wenzelm@43748
   294
          Future.fork {
wenzelm@43748
   295
            val arg = XML.content(result.body).mkString
wenzelm@43748
   296
            val (tag, res) = Invoke_Scala.method(name, arg)
wenzelm@43748
   297
            prover.get.invoke_scala(id, tag, res)
wenzelm@43748
   298
          }
wenzelm@44298
   299
        case Markup.Cancel_Scala(id) =>
wenzelm@44298
   300
          System.err.println("cancel_scala " + id)  // FIXME cancel JVM task
wenzelm@38722
   301
        case _ =>
wenzelm@39630
   302
          if (result.is_syslog) {
wenzelm@39630
   303
            reverse_syslog ::= result.message
wenzelm@40533
   304
            if (result.is_ready) {
wenzelm@43716
   305
              // FIXME move to ML side (!?)
wenzelm@40533
   306
              syntax += ("hence", Keyword.PRF_ASM_GOAL, "then have")
wenzelm@40533
   307
              syntax += ("thus", Keyword.PRF_ASM_GOAL, "then show")
wenzelm@40533
   308
              phase = Session.Ready
wenzelm@40533
   309
            }
wenzelm@39701
   310
            else if (result.is_exit && phase == Session.Startup) phase = Session.Failed
wenzelm@39696
   311
            else if (result.is_exit) phase = Session.Inactive
wenzelm@39630
   312
          }
wenzelm@39626
   313
          else if (result.is_stdout) { }
wenzelm@39625
   314
          else if (result.is_status) {
wenzelm@38370
   315
            result.body match {
wenzelm@44476
   316
              case List(Isar_Document.Assign(id, assign)) =>
wenzelm@44476
   317
                try { handle_assign(id, assign) }
wenzelm@38414
   318
                catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   319
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   320
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@44574
   321
              case List(Thy_Info.Loaded_Theory(name)) => thy_load.register_thy(name)
wenzelm@39625
   322
              case _ => bad_result(result)
wenzelm@38370
   323
            }
wenzelm@38370
   324
          }
wenzelm@39625
   325
          else bad_result(result)
wenzelm@43748
   326
      }
wenzelm@34809
   327
    }
wenzelm@38221
   328
    //}}}
wenzelm@34809
   329
wenzelm@34820
   330
wenzelm@39630
   331
    /* main loop */
wenzelm@34809
   332
wenzelm@43716
   333
    //{{{
wenzelm@38639
   334
    var finished = false
wenzelm@38639
   335
    while (!finished) {
wenzelm@38639
   336
      receive {
wenzelm@43649
   337
        case Start(timeout, args) if prover.isEmpty =>
wenzelm@39701
   338
          if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@39701
   339
            phase = Session.Startup
wenzelm@43661
   340
            prover = Some(new Isabelle_Process(timeout, this_actor, args:_*) with Isar_Document)
wenzelm@39701
   341
          }
wenzelm@38841
   342
wenzelm@39701
   343
        case Stop =>
wenzelm@39701
   344
          if (phase == Session.Ready) {
wenzelm@39701
   345
            global_state.change(_ => Document.State.init)  // FIXME event bus!?
wenzelm@39701
   346
            phase = Session.Shutdown
wenzelm@43649
   347
            prover.get.terminate
wenzelm@43717
   348
            prover = None
wenzelm@39701
   349
            phase = Session.Inactive
wenzelm@39701
   350
          }
wenzelm@39630
   351
          finished = true
wenzelm@39630
   352
          reply(())
wenzelm@38850
   353
wenzelm@43717
   354
        case Interrupt if prover.isDefined =>
wenzelm@43717
   355
          prover.get.interrupt
wenzelm@43716
   356
wenzelm@44385
   357
        case Init_Node(name, master_dir, header, perspective, text) if prover.isDefined =>
wenzelm@43716
   358
          // FIXME compare with existing node
wenzelm@44182
   359
          handle_edits(name, master_dir, header,
wenzelm@44385
   360
            List(Document.Node.Clear(),
wenzelm@44385
   361
              Document.Node.Edits(List(Text.Edit.insert(0, text))),
wenzelm@44385
   362
              Document.Node.Perspective(perspective)))
wenzelm@43716
   363
          reply(())
wenzelm@43716
   364
wenzelm@44385
   365
        case Edit_Node(name, master_dir, header, perspective, text_edits) if prover.isDefined =>
wenzelm@44484
   366
          if (text_edits.isEmpty && global_state().tip_stable &&
wenzelm@44484
   367
              perspective.range.stop <= global_state().last_exec_offset(name))
wenzelm@44484
   368
            update_perspective(name, perspective)
wenzelm@44484
   369
          else
wenzelm@44436
   370
            handle_edits(name, master_dir, header,
wenzelm@44436
   371
              List(Document.Node.Edits(text_edits), Document.Node.Perspective(perspective)))
wenzelm@43718
   372
          reply(())
wenzelm@43718
   373
wenzelm@43722
   374
        case change: Change_Node if prover.isDefined =>
wenzelm@43722
   375
          handle_change(change)
wenzelm@43716
   376
wenzelm@43721
   377
        case input: Isabelle_Process.Input =>
wenzelm@43721
   378
          raw_messages.event(input)
wenzelm@43721
   379
wenzelm@43716
   380
        case result: Isabelle_Process.Result =>
wenzelm@43716
   381
          handle_result(result)
wenzelm@43721
   382
          raw_messages.event(result)
wenzelm@43716
   383
wenzelm@43717
   384
        case bad => System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   385
      }
wenzelm@34777
   386
    }
wenzelm@43716
   387
    //}}}
wenzelm@34777
   388
  }
wenzelm@34777
   389
wenzelm@34809
   390
wenzelm@43716
   391
  /* actions */
wenzelm@34809
   392
wenzelm@40848
   393
  def start(timeout: Time, args: List[String]) { session_actor ! Start(timeout, args) }
wenzelm@34820
   394
wenzelm@39630
   395
  def stop() { command_change_buffer !? Stop; session_actor !? Stop }
wenzelm@38841
   396
wenzelm@43716
   397
  def interrupt() { session_actor ! Interrupt }
wenzelm@43648
   398
wenzelm@44385
   399
  // FIXME simplify signature
wenzelm@44385
   400
  def init_node(name: String, master_dir: String,
wenzelm@44385
   401
    header: Document.Node_Header, perspective: Text.Perspective, text: String)
wenzelm@44385
   402
  { session_actor !? Init_Node(name, master_dir, header, perspective, text) }
wenzelm@38221
   403
wenzelm@44385
   404
  // FIXME simplify signature
wenzelm@44385
   405
  def edit_node(name: String, master_dir: String, header: Document.Node_Header,
wenzelm@44385
   406
    perspective: Text.Perspective, edits: List[Text.Edit])
wenzelm@44385
   407
  { session_actor !? Edit_Node(name, master_dir, header, perspective, edits) }
wenzelm@34777
   408
}