src/Pure/System/session.scala
author wenzelm
Sat Aug 14 22:45:23 2010 +0200 (2010-08-14)
changeset 38414 49f1f657adc2
parent 38413 224efb14f258
child 38415 f3220ef79d51
permissions -rw-r--r--
more basic Markup.parse_int/print_int (using signed_string_of_int) (ML);
added convenient Markup.Int/Long objects (Scala);
simplified "assign" message format -- explicit version id;
misc tuning and simplification;
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@38360
    22
  case class Commands_Changed(set: Set[Command])
wenzelm@34791
    23
}
wenzelm@34791
    24
wenzelm@34777
    25
wenzelm@34851
    26
class Session(system: Isabelle_System)
wenzelm@34777
    27
{
wenzelm@37849
    28
  /* real time parameters */  // FIXME properties or settings (!?)
wenzelm@37849
    29
wenzelm@37849
    30
  // user input (e.g. text edits, cursor movement)
wenzelm@37849
    31
  val input_delay = 300
wenzelm@37849
    32
wenzelm@37849
    33
  // prover output (markup, common messages)
wenzelm@37849
    34
  val output_delay = 100
wenzelm@37849
    35
wenzelm@37849
    36
  // GUI layout updates
wenzelm@37849
    37
  val update_delay = 500
wenzelm@37849
    38
wenzelm@37849
    39
wenzelm@34809
    40
  /* pervasive event buses */
wenzelm@34809
    41
wenzelm@34809
    42
  val global_settings = new Event_Bus[Session.Global_Settings.type]
wenzelm@34809
    43
  val raw_results = new Event_Bus[Isabelle_Process.Result]
wenzelm@37065
    44
  val raw_output = new Event_Bus[Isabelle_Process.Result]
wenzelm@38360
    45
  val commands_changed = new Event_Bus[Session.Commands_Changed]
wenzelm@37849
    46
  val perspective = new Event_Bus[Session.Perspective.type]
wenzelm@34809
    47
wenzelm@34809
    48
wenzelm@34778
    49
  /* unique ids */
wenzelm@34778
    50
wenzelm@38363
    51
  private var id_count: Document.ID = 0
wenzelm@38363
    52
  def create_id(): Document.ID = synchronized {
wenzelm@38355
    53
    require(id_count > java.lang.Long.MIN_VALUE)
wenzelm@38355
    54
    id_count -= 1
wenzelm@38355
    55
    id_count
wenzelm@38355
    56
  }
wenzelm@34778
    57
wenzelm@34778
    58
wenzelm@34826
    59
wenzelm@34826
    60
  /** main actor **/
wenzelm@34809
    61
wenzelm@34851
    62
  @volatile private var syntax = new Outer_Syntax(system.symbols)
wenzelm@34819
    63
  def current_syntax: Outer_Syntax = syntax
wenzelm@34809
    64
wenzelm@38370
    65
  @volatile private var global_state = Document.State.init
wenzelm@38370
    66
  private def change_state(f: Document.State => Document.State) { global_state = f(global_state) }
wenzelm@38370
    67
  def current_state(): Document.State = global_state
wenzelm@34816
    68
wenzelm@38221
    69
  private case class Started(timeout: Int, args: List[String])
wenzelm@34777
    70
  private case object Stop
wenzelm@34777
    71
wenzelm@37129
    72
  private lazy val session_actor = actor {
wenzelm@34809
    73
wenzelm@34809
    74
    var prover: Isabelle_Process with Isar_Document = null
wenzelm@34809
    75
wenzelm@34809
    76
wenzelm@34809
    77
    /* document changes */
wenzelm@34809
    78
wenzelm@38227
    79
    def handle_change(change: Document.Change)
wenzelm@38221
    80
    //{{{
wenzelm@34809
    81
    {
wenzelm@38366
    82
      require(change.is_finished)
wenzelm@34809
    83
wenzelm@38370
    84
      val old_doc = change.prev.join
wenzelm@38150
    85
      val (node_edits, doc) = change.result.join
wenzelm@38366
    86
wenzelm@38370
    87
      var former_assignment = current_state().the_assignment(old_doc).join
wenzelm@38370
    88
      for {
wenzelm@38370
    89
        (name, Some(cmd_edits)) <- node_edits
wenzelm@38370
    90
        (prev, None) <- cmd_edits
wenzelm@38370
    91
        removed <- old_doc.nodes(name).commands.get_after(prev)
wenzelm@38370
    92
      } former_assignment -= removed
wenzelm@38370
    93
wenzelm@38150
    94
      val id_edits =
wenzelm@38150
    95
        node_edits map {
wenzelm@38150
    96
          case (name, None) => (name, None)
wenzelm@38150
    97
          case (name, Some(cmd_edits)) =>
wenzelm@38370
    98
            val ids =
wenzelm@38150
    99
              cmd_edits map {
wenzelm@38150
   100
                case (c1, c2) =>
wenzelm@38150
   101
                  val id1 = c1.map(_.id)
wenzelm@38150
   102
                  val id2 =
wenzelm@38150
   103
                    c2 match {
wenzelm@38150
   104
                      case None => None
wenzelm@38150
   105
                      case Some(command) =>
wenzelm@38370
   106
                        if (current_state().lookup_command(command.id).isEmpty) {
wenzelm@38370
   107
                          change_state(_.define_command(command))
wenzelm@38150
   108
                          prover.define_command(command.id, system.symbols.encode(command.source))
wenzelm@38150
   109
                        }
wenzelm@38150
   110
                        Some(command.id)
wenzelm@38150
   111
                    }
wenzelm@38150
   112
                  (id1, id2)
wenzelm@38150
   113
              }
wenzelm@38370
   114
            (name -> Some(ids))
wenzelm@38150
   115
        }
wenzelm@38370
   116
      change_state(_.define_document(doc, former_assignment))
wenzelm@38370
   117
      prover.edit_document(old_doc.id, doc.id, id_edits)
wenzelm@34809
   118
    }
wenzelm@38221
   119
    //}}}
wenzelm@34809
   120
wenzelm@34809
   121
wenzelm@34809
   122
    /* prover results */
wenzelm@34809
   123
wenzelm@34836
   124
    def bad_result(result: Isabelle_Process.Result)
wenzelm@34836
   125
    {
wenzelm@37041
   126
      System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@34836
   127
    }
wenzelm@34836
   128
wenzelm@34809
   129
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   130
    //{{{
wenzelm@34809
   131
    {
wenzelm@34809
   132
      raw_results.event(result)
wenzelm@34799
   133
wenzelm@38370
   134
      Position.get_id(result.properties) match {
wenzelm@38414
   135
        case Some(state_id) =>
wenzelm@38370
   136
          try {
wenzelm@38414
   137
            val (st, state) = global_state.accumulate(state_id, result.message)
wenzelm@38370
   138
            global_state = state
wenzelm@38414
   139
            indicate_command_change(st.command)
wenzelm@38370
   140
          }
wenzelm@38414
   141
          catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   142
        case None =>
wenzelm@38370
   143
          if (result.is_status) {
wenzelm@38370
   144
            result.body match {
wenzelm@38414
   145
              case List(Isar_Document.Assign(doc_id, edits)) =>
wenzelm@38414
   146
                try { change_state(_.assign(doc_id, edits)) }
wenzelm@38414
   147
                catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   148
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   149
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@38370
   150
              case _ => if (!result.is_ready) bad_result(result)
wenzelm@38370
   151
            }
wenzelm@38370
   152
          }
wenzelm@38370
   153
          else if (result.kind == Markup.EXIT) prover = null
wenzelm@38370
   154
          else if (result.is_raw) raw_output.event(result)
wenzelm@38370
   155
          else if (!result.is_system) bad_result(result)  // FIXME syslog for system messages (!?)
wenzelm@34809
   156
        }
wenzelm@34809
   157
    }
wenzelm@38221
   158
    //}}}
wenzelm@34809
   159
wenzelm@34820
   160
wenzelm@34820
   161
    /* prover startup */
wenzelm@34820
   162
wenzelm@34820
   163
    def startup_error(): String =
wenzelm@34820
   164
    {
wenzelm@34820
   165
      val buf = new StringBuilder
wenzelm@34820
   166
      while (
wenzelm@34820
   167
        receiveWithin(0) {
wenzelm@34820
   168
          case result: Isabelle_Process.Result =>
wenzelm@34820
   169
            if (result.is_raw) {
wenzelm@34820
   170
              for (text <- XML.content(result.message))
wenzelm@34820
   171
                buf.append(text)
wenzelm@34820
   172
            }
wenzelm@34820
   173
            true
wenzelm@34820
   174
          case TIMEOUT => false
wenzelm@34820
   175
        }) {}
wenzelm@34820
   176
      buf.toString
wenzelm@34820
   177
    }
wenzelm@34820
   178
wenzelm@34820
   179
    def prover_startup(timeout: Int): Option[String] =
wenzelm@34820
   180
    {
wenzelm@34820
   181
      receiveWithin(timeout) {
wenzelm@34820
   182
        case result: Isabelle_Process.Result
wenzelm@37689
   183
          if result.kind == Markup.INIT =>
wenzelm@34820
   184
          while (receive {
wenzelm@34820
   185
            case result: Isabelle_Process.Result =>
wenzelm@34820
   186
              handle_result(result); !result.is_ready
wenzelm@34820
   187
            }) {}
wenzelm@34820
   188
          None
wenzelm@34820
   189
wenzelm@34820
   190
        case result: Isabelle_Process.Result
wenzelm@37689
   191
          if result.kind == Markup.EXIT =>
wenzelm@34820
   192
          Some(startup_error())
wenzelm@34820
   193
wenzelm@34820
   194
        case TIMEOUT =>  // FIXME clarify
wenzelm@34820
   195
          prover.kill; Some(startup_error())
wenzelm@34820
   196
      }
wenzelm@34820
   197
    }
wenzelm@34809
   198
wenzelm@34809
   199
wenzelm@34809
   200
    /* main loop */
wenzelm@34809
   201
wenzelm@34820
   202
    val xml_cache = new XML.Cache(131071)
wenzelm@34820
   203
wenzelm@34777
   204
    loop {
wenzelm@34777
   205
      react {
wenzelm@38221
   206
        case Started(timeout, args) =>
wenzelm@34777
   207
          if (prover == null) {
wenzelm@34851
   208
            prover = new Isabelle_Process(system, self, args:_*) with Isar_Document
wenzelm@34820
   209
            val origin = sender
wenzelm@34820
   210
            val opt_err = prover_startup(timeout)
wenzelm@34820
   211
            if (opt_err.isDefined) prover = null
wenzelm@34820
   212
            origin ! opt_err
wenzelm@34820
   213
          }
wenzelm@34820
   214
          else reply(None)
wenzelm@34820
   215
wenzelm@34820
   216
        case Stop =>  // FIXME clarify; synchronous
wenzelm@34820
   217
          if (prover != null) {
wenzelm@34820
   218
            prover.kill
wenzelm@34820
   219
            prover = null
wenzelm@34777
   220
          }
wenzelm@34777
   221
wenzelm@38227
   222
        case change: Document.Change if prover != null =>
wenzelm@34777
   223
          handle_change(change)
wenzelm@34777
   224
wenzelm@34777
   225
        case result: Isabelle_Process.Result =>
wenzelm@34795
   226
          handle_result(result.cache(xml_cache))
wenzelm@34777
   227
wenzelm@36782
   228
        case TIMEOUT =>  // FIXME clarify!
wenzelm@36782
   229
wenzelm@34820
   230
        case bad if prover != null =>
wenzelm@34777
   231
          System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   232
      }
wenzelm@34777
   233
    }
wenzelm@34777
   234
  }
wenzelm@34777
   235
wenzelm@34809
   236
wenzelm@37129
   237
wenzelm@38226
   238
  /** buffered command changes (delay_first discipline) **/
wenzelm@37129
   239
wenzelm@38221
   240
  private lazy val command_change_buffer = actor
wenzelm@38221
   241
  //{{{
wenzelm@38221
   242
  {
wenzelm@37129
   243
    import scala.compat.Platform.currentTime
wenzelm@37129
   244
wenzelm@37129
   245
    var changed: Set[Command] = Set()
wenzelm@37129
   246
    var flush_time: Option[Long] = None
wenzelm@37129
   247
wenzelm@37129
   248
    def flush_timeout: Long =
wenzelm@37129
   249
      flush_time match {
wenzelm@37129
   250
        case None => 5000L
wenzelm@37129
   251
        case Some(time) => (time - currentTime) max 0
wenzelm@37129
   252
      }
wenzelm@37129
   253
wenzelm@37129
   254
    def flush()
wenzelm@37129
   255
    {
wenzelm@38360
   256
      if (!changed.isEmpty) commands_changed.event(Session.Commands_Changed(changed))
wenzelm@37129
   257
      changed = Set()
wenzelm@37129
   258
      flush_time = None
wenzelm@37129
   259
    }
wenzelm@37129
   260
wenzelm@37129
   261
    def invoke()
wenzelm@37129
   262
    {
wenzelm@37129
   263
      val now = currentTime
wenzelm@37129
   264
      flush_time match {
wenzelm@37849
   265
        case None => flush_time = Some(now + output_delay)
wenzelm@37129
   266
        case Some(time) => if (now >= time) flush()
wenzelm@37129
   267
      }
wenzelm@37129
   268
    }
wenzelm@37129
   269
wenzelm@37129
   270
    loop {
wenzelm@37129
   271
      reactWithin(flush_timeout) {
wenzelm@37129
   272
        case command: Command => changed += command; invoke()
wenzelm@37129
   273
        case TIMEOUT => flush()
wenzelm@37129
   274
        case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
wenzelm@37129
   275
      }
wenzelm@37129
   276
    }
wenzelm@37129
   277
  }
wenzelm@38221
   278
  //}}}
wenzelm@37129
   279
wenzelm@37129
   280
  def indicate_command_change(command: Command)
wenzelm@37129
   281
  {
wenzelm@37129
   282
    command_change_buffer ! command
wenzelm@37129
   283
  }
wenzelm@37129
   284
wenzelm@37129
   285
wenzelm@38226
   286
wenzelm@38226
   287
  /** editor history **/
wenzelm@38226
   288
wenzelm@38226
   289
  private case class Edit_Document(edits: List[Document.Node_Text_Edit])
wenzelm@38226
   290
wenzelm@38226
   291
  private val editor_history = new Actor
wenzelm@38226
   292
  {
wenzelm@38366
   293
    @volatile private var history = List(Document.Change.init)
wenzelm@38365
   294
wenzelm@38365
   295
    def snapshot(name: String, pending_edits: List[Text_Edit]): Document.Snapshot =
wenzelm@38365
   296
    {
wenzelm@38370
   297
      val state_snapshot = current_state()
wenzelm@38366
   298
      val history_snapshot = history
wenzelm@38366
   299
wenzelm@38370
   300
      val found_stable = history_snapshot.find(change =>
wenzelm@38370
   301
        change.is_finished && state_snapshot.is_assigned(change.document.join))
wenzelm@38370
   302
      require(found_stable.isDefined)
wenzelm@38370
   303
      val stable = found_stable.get
wenzelm@38366
   304
      val latest = history_snapshot.head
wenzelm@38365
   305
wenzelm@38365
   306
      val edits =
wenzelm@38366
   307
        (pending_edits /: history_snapshot.takeWhile(_ != stable))((edits, change) =>
wenzelm@38365
   308
            (for ((a, eds) <- change.edits if a == name) yield eds).flatten ::: edits)
wenzelm@38365
   309
      lazy val reverse_edits = edits.reverse
wenzelm@38365
   310
wenzelm@38365
   311
      new Document.Snapshot {
wenzelm@38366
   312
        val document = stable.document.join
wenzelm@38365
   313
        val node = document.nodes(name)
wenzelm@38366
   314
        val is_outdated = !(pending_edits.isEmpty && latest == stable)
wenzelm@38365
   315
        def convert(offset: Int): Int = (offset /: edits)((i, edit) => edit.convert(i))
wenzelm@38365
   316
        def revert(offset: Int): Int = (offset /: reverse_edits)((i, edit) => edit.revert(i))
wenzelm@38370
   317
        def lookup_command(id: Document.Command_ID): Option[Command] =
wenzelm@38370
   318
          state_snapshot.lookup_command(id)
wenzelm@38370
   319
        def state(command: Command): Command.State =
wenzelm@38370
   320
          state_snapshot.command_state(document, command)
wenzelm@38365
   321
      }
wenzelm@38365
   322
    }
wenzelm@38226
   323
wenzelm@38226
   324
    def act
wenzelm@38226
   325
    {
wenzelm@38226
   326
      loop {
wenzelm@38226
   327
        react {
wenzelm@38226
   328
          case Edit_Document(edits) =>
wenzelm@38366
   329
            val history_snapshot = history
wenzelm@38366
   330
            require(!history_snapshot.isEmpty)
wenzelm@38366
   331
wenzelm@38366
   332
            val prev = history_snapshot.head.document
wenzelm@38226
   333
            val result: isabelle.Future[(List[Document.Edit[Command]], Document)] =
wenzelm@38226
   334
              isabelle.Future.fork {
wenzelm@38366
   335
                val old_doc = prev.join
wenzelm@38370
   336
                val former_assignment = current_state().the_assignment(old_doc).join  // FIXME async!?
wenzelm@38374
   337
                Thy_Syntax.text_edits(Session.this, old_doc, edits)
wenzelm@38226
   338
              }
wenzelm@38366
   339
            val new_change = new Document.Change(prev, edits, result)
wenzelm@38366
   340
            history ::= new_change
wenzelm@38366
   341
            new_change.document.map(_ => session_actor ! new_change)
wenzelm@38260
   342
            reply(())
wenzelm@38226
   343
wenzelm@38226
   344
          case bad => System.err.println("editor_model: ignoring bad message " + bad)
wenzelm@38226
   345
        }
wenzelm@38226
   346
      }
wenzelm@38226
   347
    }
wenzelm@38226
   348
  }
wenzelm@38226
   349
  editor_history.start
wenzelm@38226
   350
wenzelm@38226
   351
wenzelm@38226
   352
wenzelm@38226
   353
  /** main methods **/
wenzelm@34809
   354
wenzelm@38221
   355
  def started(timeout: Int, args: List[String]): Option[String] =
wenzelm@38221
   356
    (session_actor !? Started(timeout, args)).asInstanceOf[Option[String]]
wenzelm@34820
   357
wenzelm@34777
   358
  def stop() { session_actor ! Stop }
wenzelm@38221
   359
wenzelm@38359
   360
  def snapshot(name: String, pending_edits: List[Text_Edit]): Document.Snapshot =
wenzelm@38365
   361
    editor_history.snapshot(name, pending_edits)
wenzelm@38260
   362
wenzelm@38260
   363
  def edit_document(edits: List[Document.Node_Text_Edit]) { editor_history !? Edit_Document(edits) }
wenzelm@34777
   364
}