src/Pure/System/session.scala
author wenzelm
Fri Sep 02 21:48:27 2011 +0200 (2011-09-02 ago)
changeset 44661 383c9d758a56
parent 44644 317e4962dd0f
child 44676 7de87f1ae965
permissions -rw-r--r--
raw message function "assign_execs" avoids full overhead of decoding and caching message body;
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@44615
    25
  case class Commands_Changed(nodes: Set[Document.Node.Name], 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@44615
    66
    var changed_nodes: Set[Document.Node.Name] = 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@44615
   137
  def snapshot(name: Document.Node.Name, 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@44615
   143
  def header_edit(name: Document.Node.Name, header: Document.Node_Header): Document.Edit_Text =
wenzelm@44442
   144
  {
wenzelm@44442
   145
    def norm_import(s: String): String =
wenzelm@44442
   146
    {
wenzelm@44442
   147
      val thy_name = Thy_Header.base_name(s)
wenzelm@44442
   148
      if (thy_load.is_loaded(thy_name)) thy_name
wenzelm@44616
   149
      else thy_load.append(name.dir, Thy_Header.thy_path(Path.explode(s)))
wenzelm@44442
   150
    }
wenzelm@44616
   151
    def norm_use(s: String): String = thy_load.append(name.dir, Path.explode(s))
wenzelm@44442
   152
wenzelm@44442
   153
    val header1: Document.Node_Header =
wenzelm@44442
   154
      header match {
wenzelm@44442
   155
        case Exn.Res(Thy_Header(thy_name, _, _))
wenzelm@44442
   156
        if (thy_load.is_loaded(thy_name)) =>
wenzelm@44442
   157
          Exn.Exn(ERROR("Attempt to update loaded theory " + quote(thy_name)))
wenzelm@44442
   158
        case _ => Document.Node.norm_header(norm_import, norm_use, header)
wenzelm@44442
   159
      }
wenzelm@44442
   160
    (name, Document.Node.Header(header1))
wenzelm@44442
   161
  }
wenzelm@44442
   162
wenzelm@43651
   163
wenzelm@43651
   164
  /* actor messages */
wenzelm@43651
   165
wenzelm@43716
   166
  private case class Start(timeout: Time, args: List[String])
wenzelm@43716
   167
  private case object Interrupt
wenzelm@44615
   168
  private case class Init_Node(name: Document.Node.Name,
wenzelm@44385
   169
    header: Document.Node_Header, perspective: Text.Perspective, text: String)
wenzelm@44615
   170
  private case class Edit_Node(name: Document.Node.Name,
wenzelm@44385
   171
    header: Document.Node_Header, perspective: Text.Perspective, edits: List[Text.Edit])
wenzelm@43722
   172
  private case class Change_Node(
wenzelm@44615
   173
    name: Document.Node.Name,
wenzelm@43722
   174
    doc_edits: List[Document.Edit_Command],
wenzelm@43722
   175
    previous: Document.Version,
wenzelm@43722
   176
    version: Document.Version)
wenzelm@41534
   177
wenzelm@39572
   178
  private val (_, session_actor) = Simple_Thread.actor("session_actor", daemon = true)
wenzelm@38639
   179
  {
wenzelm@43648
   180
    val this_actor = self
wenzelm@43649
   181
    var prover: Option[Isabelle_Process with Isar_Document] = None
wenzelm@34809
   182
wenzelm@34809
   183
wenzelm@44436
   184
    /* perspective */
wenzelm@44436
   185
wenzelm@44615
   186
    def update_perspective(name: Document.Node.Name, text_perspective: Text.Perspective)
wenzelm@44436
   187
    {
wenzelm@44475
   188
      val previous = global_state().tip_version
wenzelm@44436
   189
      val (perspective, version) = Thy_Syntax.edit_perspective(previous, name, text_perspective)
wenzelm@44436
   190
wenzelm@44436
   191
      val text_edits: List[Document.Edit_Text] =
wenzelm@44436
   192
        List((name, Document.Node.Perspective(text_perspective)))
wenzelm@44436
   193
      val change =
wenzelm@44436
   194
        global_state.change_yield(
wenzelm@44446
   195
          _.continue_history(Future.value(previous), text_edits, Future.value(version)))
wenzelm@44436
   196
wenzelm@44477
   197
      val assignment = global_state().the_assignment(previous).check_finished
wenzelm@44479
   198
      global_state.change(_.define_version(version, assignment))
wenzelm@44476
   199
      global_state.change_yield(_.assign(version.id, Document.no_assign))
wenzelm@44436
   200
wenzelm@44436
   201
      prover.get.update_perspective(previous.id, version.id, name, perspective)
wenzelm@44436
   202
    }
wenzelm@44436
   203
wenzelm@44436
   204
wenzelm@43716
   205
    /* incoming edits */
wenzelm@43716
   206
wenzelm@44615
   207
    def handle_edits(name: Document.Node.Name,
wenzelm@44384
   208
        header: Document.Node_Header, edits: List[Document.Node.Edit[Text.Edit, Text.Perspective]])
wenzelm@43716
   209
    //{{{
wenzelm@43716
   210
    {
wenzelm@43716
   211
      val syntax = current_syntax()
wenzelm@43719
   212
      val previous = global_state().history.tip.version
wenzelm@44185
   213
wenzelm@44612
   214
      prover.get.cancel_execution()
wenzelm@44612
   215
wenzelm@44615
   216
      val text_edits = header_edit(name, header) :: edits.map(edit => (name, edit))
wenzelm@44185
   217
      val result = Future.fork { Thy_Syntax.text_edits(syntax, previous.join, text_edits) }
wenzelm@43722
   218
      val change =
wenzelm@44446
   219
        global_state.change_yield(_.continue_history(previous, text_edits, result.map(_._2)))
wenzelm@43716
   220
wenzelm@43722
   221
      result.map {
wenzelm@44157
   222
        case (doc_edits, _) =>
wenzelm@43722
   223
          assignments.await { global_state().is_assigned(previous.get_finished) }
wenzelm@44157
   224
          this_actor ! Change_Node(name, doc_edits, previous.join, change.version.join)
wenzelm@43722
   225
      }
wenzelm@43716
   226
    }
wenzelm@43716
   227
    //}}}
wenzelm@43716
   228
wenzelm@43716
   229
wenzelm@44436
   230
    /* exec state assignment */
wenzelm@44436
   231
wenzelm@44476
   232
    def handle_assign(id: Document.Version_ID, assign: Document.Assign)
wenzelm@44436
   233
    //{{{
wenzelm@44436
   234
    {
wenzelm@44476
   235
      val cmds = global_state.change_yield(_.assign(id, assign))
wenzelm@44436
   236
      for (cmd <- cmds) command_change_buffer ! cmd
wenzelm@44436
   237
      assignments.event(Session.Assignment)
wenzelm@44436
   238
    }
wenzelm@44436
   239
    //}}}
wenzelm@44436
   240
wenzelm@44436
   241
wenzelm@43716
   242
    /* resulting changes */
wenzelm@34809
   243
wenzelm@43722
   244
    def handle_change(change: Change_Node)
wenzelm@38221
   245
    //{{{
wenzelm@34809
   246
    {
wenzelm@43722
   247
      val previous = change.previous
wenzelm@43722
   248
      val version = change.version
wenzelm@43722
   249
      val name = change.name
wenzelm@43722
   250
      val doc_edits = change.doc_edits
wenzelm@38366
   251
wenzelm@44383
   252
      def id_command(command: Command)
wenzelm@43720
   253
      {
wenzelm@44582
   254
        if (!global_state().defined_command(command.id)) {
wenzelm@43720
   255
          global_state.change(_.define_command(command))
wenzelm@44644
   256
          prover.get.define_command(command)
wenzelm@43720
   257
        }
wenzelm@43720
   258
      }
wenzelm@44383
   259
      doc_edits foreach {
wenzelm@44383
   260
        case (_, edit) =>
wenzelm@44383
   261
          edit foreach { case (c1, c2) => c1 foreach id_command; c2 foreach id_command }
wenzelm@44383
   262
      }
wenzelm@43722
   263
wenzelm@44479
   264
      val assignment = global_state().the_assignment(previous).check_finished
wenzelm@44479
   265
      global_state.change(_.define_version(version, assignment))
wenzelm@44481
   266
      prover.get.update(previous.id, version.id, doc_edits)
wenzelm@34809
   267
    }
wenzelm@38221
   268
    //}}}
wenzelm@34809
   269
wenzelm@34809
   270
wenzelm@34809
   271
    /* prover results */
wenzelm@34809
   272
wenzelm@34809
   273
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   274
    //{{{
wenzelm@34809
   275
    {
wenzelm@43716
   276
      def bad_result(result: Isabelle_Process.Result)
wenzelm@43716
   277
      {
wenzelm@43716
   278
        if (verbose)
wenzelm@43716
   279
          System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@43716
   280
      }
wenzelm@43716
   281
wenzelm@38722
   282
      result.properties match {
wenzelm@43748
   283
        case Position.Id(state_id) if !result.is_raw =>
wenzelm@38370
   284
          try {
wenzelm@38841
   285
            val st = global_state.change_yield(_.accumulate(state_id, result.message))
wenzelm@38841
   286
            command_change_buffer ! st.command
wenzelm@38370
   287
          }
wenzelm@43748
   288
          catch {
wenzelm@43748
   289
            case _: Document.State.Fail => bad_result(result)
wenzelm@43748
   290
          }
wenzelm@44661
   291
        case Markup.Assign_Execs if result.is_raw =>
wenzelm@44661
   292
          XML.content(result.body).mkString match {
wenzelm@44661
   293
            case Isar_Document.Assign(id, assign) =>
wenzelm@44661
   294
              try { handle_assign(id, assign) }
wenzelm@44661
   295
              catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@44661
   296
            case _ => bad_result(result)
wenzelm@44661
   297
          }
wenzelm@43748
   298
        case Markup.Invoke_Scala(name, id) if result.is_raw =>
wenzelm@43748
   299
          Future.fork {
wenzelm@43748
   300
            val arg = XML.content(result.body).mkString
wenzelm@43748
   301
            val (tag, res) = Invoke_Scala.method(name, arg)
wenzelm@43748
   302
            prover.get.invoke_scala(id, tag, res)
wenzelm@43748
   303
          }
wenzelm@44298
   304
        case Markup.Cancel_Scala(id) =>
wenzelm@44298
   305
          System.err.println("cancel_scala " + id)  // FIXME cancel JVM task
wenzelm@38722
   306
        case _ =>
wenzelm@39630
   307
          if (result.is_syslog) {
wenzelm@39630
   308
            reverse_syslog ::= result.message
wenzelm@40533
   309
            if (result.is_ready) {
wenzelm@43716
   310
              // FIXME move to ML side (!?)
wenzelm@40533
   311
              syntax += ("hence", Keyword.PRF_ASM_GOAL, "then have")
wenzelm@40533
   312
              syntax += ("thus", Keyword.PRF_ASM_GOAL, "then show")
wenzelm@40533
   313
              phase = Session.Ready
wenzelm@40533
   314
            }
wenzelm@39701
   315
            else if (result.is_exit && phase == Session.Startup) phase = Session.Failed
wenzelm@39696
   316
            else if (result.is_exit) phase = Session.Inactive
wenzelm@39630
   317
          }
wenzelm@39626
   318
          else if (result.is_stdout) { }
wenzelm@39625
   319
          else if (result.is_status) {
wenzelm@38370
   320
            result.body match {
wenzelm@38370
   321
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   322
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@44574
   323
              case List(Thy_Info.Loaded_Theory(name)) => thy_load.register_thy(name)
wenzelm@39625
   324
              case _ => bad_result(result)
wenzelm@38370
   325
            }
wenzelm@38370
   326
          }
wenzelm@39625
   327
          else bad_result(result)
wenzelm@43748
   328
      }
wenzelm@34809
   329
    }
wenzelm@38221
   330
    //}}}
wenzelm@34809
   331
wenzelm@34820
   332
wenzelm@39630
   333
    /* main loop */
wenzelm@34809
   334
wenzelm@43716
   335
    //{{{
wenzelm@38639
   336
    var finished = false
wenzelm@38639
   337
    while (!finished) {
wenzelm@38639
   338
      receive {
wenzelm@43649
   339
        case Start(timeout, args) if prover.isEmpty =>
wenzelm@39701
   340
          if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@39701
   341
            phase = Session.Startup
wenzelm@43661
   342
            prover = Some(new Isabelle_Process(timeout, this_actor, args:_*) with Isar_Document)
wenzelm@39701
   343
          }
wenzelm@38841
   344
wenzelm@39701
   345
        case Stop =>
wenzelm@39701
   346
          if (phase == Session.Ready) {
wenzelm@39701
   347
            global_state.change(_ => Document.State.init)  // FIXME event bus!?
wenzelm@39701
   348
            phase = Session.Shutdown
wenzelm@43649
   349
            prover.get.terminate
wenzelm@43717
   350
            prover = None
wenzelm@39701
   351
            phase = Session.Inactive
wenzelm@39701
   352
          }
wenzelm@39630
   353
          finished = true
wenzelm@39630
   354
          reply(())
wenzelm@38850
   355
wenzelm@43717
   356
        case Interrupt if prover.isDefined =>
wenzelm@43717
   357
          prover.get.interrupt
wenzelm@43716
   358
wenzelm@44615
   359
        case Init_Node(name, header, perspective, text) if prover.isDefined =>
wenzelm@43716
   360
          // FIXME compare with existing node
wenzelm@44615
   361
          handle_edits(name, header,
wenzelm@44385
   362
            List(Document.Node.Clear(),
wenzelm@44385
   363
              Document.Node.Edits(List(Text.Edit.insert(0, text))),
wenzelm@44385
   364
              Document.Node.Perspective(perspective)))
wenzelm@43716
   365
          reply(())
wenzelm@43716
   366
wenzelm@44615
   367
        case Edit_Node(name, header, perspective, text_edits) if prover.isDefined =>
wenzelm@44484
   368
          if (text_edits.isEmpty && global_state().tip_stable &&
wenzelm@44484
   369
              perspective.range.stop <= global_state().last_exec_offset(name))
wenzelm@44484
   370
            update_perspective(name, perspective)
wenzelm@44484
   371
          else
wenzelm@44615
   372
            handle_edits(name, header,
wenzelm@44436
   373
              List(Document.Node.Edits(text_edits), Document.Node.Perspective(perspective)))
wenzelm@43718
   374
          reply(())
wenzelm@43718
   375
wenzelm@43722
   376
        case change: Change_Node if prover.isDefined =>
wenzelm@43722
   377
          handle_change(change)
wenzelm@43716
   378
wenzelm@43721
   379
        case input: Isabelle_Process.Input =>
wenzelm@43721
   380
          raw_messages.event(input)
wenzelm@43721
   381
wenzelm@43716
   382
        case result: Isabelle_Process.Result =>
wenzelm@43716
   383
          handle_result(result)
wenzelm@43721
   384
          raw_messages.event(result)
wenzelm@43716
   385
wenzelm@43717
   386
        case bad => System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   387
      }
wenzelm@34777
   388
    }
wenzelm@43716
   389
    //}}}
wenzelm@34777
   390
  }
wenzelm@34777
   391
wenzelm@34809
   392
wenzelm@43716
   393
  /* actions */
wenzelm@34809
   394
wenzelm@40848
   395
  def start(timeout: Time, args: List[String]) { session_actor ! Start(timeout, args) }
wenzelm@34820
   396
wenzelm@39630
   397
  def stop() { command_change_buffer !? Stop; session_actor !? Stop }
wenzelm@38841
   398
wenzelm@43716
   399
  def interrupt() { session_actor ! Interrupt }
wenzelm@43648
   400
wenzelm@44615
   401
  def init_node(name: Document.Node.Name,
wenzelm@44385
   402
    header: Document.Node_Header, perspective: Text.Perspective, text: String)
wenzelm@44615
   403
  { session_actor !? Init_Node(name, header, perspective, text) }
wenzelm@38221
   404
wenzelm@44615
   405
  def edit_node(name: Document.Node.Name,
wenzelm@44615
   406
    header: Document.Node_Header, perspective: Text.Perspective, edits: List[Text.Edit])
wenzelm@44615
   407
  { session_actor !? Edit_Node(name, header, perspective, edits) }
wenzelm@34777
   408
}