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