src/Pure/System/session.scala
author wenzelm
Sun Jul 10 00:21:19 2011 +0200 (2011-07-10)
changeset 43722 9b5dadb0c28d
parent 43721 fad8634cee62
child 43746 a41f618c641d
permissions -rw-r--r--
propagate header changes to prover process;
simplified Document case classes;
Document.State.assignments: indexed by Version_ID;
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@43716
    19
  /* file store */
wenzelm@43645
    20
wenzelm@43645
    21
  abstract class File_Store
wenzelm@43645
    22
  {
wenzelm@43645
    23
    def read(path: Path): String
wenzelm@43645
    24
  }
wenzelm@43645
    25
wenzelm@43645
    26
wenzelm@34813
    27
  /* events */
wenzelm@34813
    28
wenzelm@43716
    29
  //{{{
wenzelm@34791
    30
  case object Global_Settings
wenzelm@37849
    31
  case object Perspective
wenzelm@38849
    32
  case object Assignment
wenzelm@38360
    33
  case class Commands_Changed(set: Set[Command])
wenzelm@39630
    34
wenzelm@39630
    35
  sealed abstract class Phase
wenzelm@39630
    36
  case object Inactive extends Phase
wenzelm@39701
    37
  case object Startup extends Phase  // transient
wenzelm@39701
    38
  case object Failed extends Phase
wenzelm@39630
    39
  case object Ready extends Phase
wenzelm@39701
    40
  case object Shutdown extends Phase  // transient
wenzelm@43716
    41
  //}}}
wenzelm@34791
    42
}
wenzelm@34791
    43
wenzelm@34777
    44
wenzelm@43661
    45
class Session(val file_store: Session.File_Store)
wenzelm@34777
    46
{
wenzelm@37849
    47
  /* real time parameters */  // FIXME properties or settings (!?)
wenzelm@37849
    48
wenzelm@43716
    49
  val input_delay = Time.seconds(0.3)  // user input (e.g. text edits, cursor movement)
wenzelm@43716
    50
  val output_delay = Time.seconds(0.1)  // prover output (markup, common messages)
wenzelm@43716
    51
  val update_delay = Time.seconds(0.5)  // GUI layout updates
wenzelm@37849
    52
wenzelm@37849
    53
wenzelm@34809
    54
  /* pervasive event buses */
wenzelm@34809
    55
wenzelm@34809
    56
  val global_settings = new Event_Bus[Session.Global_Settings.type]
wenzelm@37849
    57
  val perspective = new Event_Bus[Session.Perspective.type]
wenzelm@38849
    58
  val assignments = new Event_Bus[Session.Assignment.type]
wenzelm@43716
    59
  val commands_changed = new Event_Bus[Session.Commands_Changed]
wenzelm@43716
    60
  val phase_changed = new Event_Bus[Session.Phase]
wenzelm@43721
    61
  val raw_messages = new Event_Bus[Isabelle_Process.Message]
wenzelm@43716
    62
wenzelm@34809
    63
wenzelm@34809
    64
wenzelm@38841
    65
  /** buffered command changes (delay_first discipline) **/
wenzelm@38841
    66
wenzelm@43716
    67
  //{{{
wenzelm@38841
    68
  private case object Stop
wenzelm@38841
    69
wenzelm@39572
    70
  private val (_, command_change_buffer) =
wenzelm@39572
    71
    Simple_Thread.actor("command_change_buffer", daemon = true)
wenzelm@38841
    72
  {
wenzelm@38841
    73
    var changed: Set[Command] = Set()
wenzelm@38841
    74
    var flush_time: Option[Long] = None
wenzelm@38841
    75
wenzelm@38841
    76
    def flush_timeout: Long =
wenzelm@38841
    77
      flush_time match {
wenzelm@38841
    78
        case None => 5000L
wenzelm@40848
    79
        case Some(time) => (time - System.currentTimeMillis()) max 0
wenzelm@38841
    80
      }
wenzelm@38841
    81
wenzelm@38841
    82
    def flush()
wenzelm@38841
    83
    {
wenzelm@38841
    84
      if (!changed.isEmpty) commands_changed.event(Session.Commands_Changed(changed))
wenzelm@38841
    85
      changed = Set()
wenzelm@38841
    86
      flush_time = None
wenzelm@38841
    87
    }
wenzelm@38841
    88
wenzelm@38841
    89
    def invoke()
wenzelm@38841
    90
    {
wenzelm@40848
    91
      val now = System.currentTimeMillis()
wenzelm@38841
    92
      flush_time match {
wenzelm@40848
    93
        case None => flush_time = Some(now + output_delay.ms)
wenzelm@38841
    94
        case Some(time) => if (now >= time) flush()
wenzelm@38841
    95
      }
wenzelm@38841
    96
    }
wenzelm@38841
    97
wenzelm@38841
    98
    var finished = false
wenzelm@38841
    99
    while (!finished) {
wenzelm@38841
   100
      receiveWithin(flush_timeout) {
wenzelm@38841
   101
        case command: Command => changed += command; invoke()
wenzelm@38841
   102
        case TIMEOUT => flush()
wenzelm@39630
   103
        case Stop => finished = true; reply(())
wenzelm@38841
   104
        case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
wenzelm@38841
   105
      }
wenzelm@38841
   106
    }
wenzelm@38841
   107
  }
wenzelm@38841
   108
  //}}}
wenzelm@38841
   109
wenzelm@38841
   110
wenzelm@38841
   111
wenzelm@38841
   112
  /** main protocol actor **/
wenzelm@34809
   113
wenzelm@43651
   114
  /* global state */
wenzelm@43644
   115
wenzelm@43716
   116
  @volatile var verbose: Boolean = false
wenzelm@43716
   117
wenzelm@43716
   118
  @volatile private var loaded_theories: Set[String] = Set()
wenzelm@43673
   119
wenzelm@43695
   120
  @volatile private var syntax = new Outer_Syntax
wenzelm@38569
   121
  def current_syntax(): Outer_Syntax = syntax
wenzelm@34809
   122
wenzelm@39626
   123
  @volatile private var reverse_syslog = List[XML.Elem]()
wenzelm@39629
   124
  def syslog(): String = reverse_syslog.reverse.map(msg => XML.content(msg).mkString).mkString("\n")
wenzelm@39626
   125
wenzelm@39630
   126
  @volatile private var _phase: Session.Phase = Session.Inactive
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@43716
   132
  def phase = _phase
wenzelm@43553
   133
  def is_ready: Boolean = phase == Session.Ready
wenzelm@39630
   134
wenzelm@38841
   135
  private val global_state = new Volatile(Document.State.init)
wenzelm@43719
   136
  def current_state(): Document.State = global_state()
wenzelm@34816
   137
wenzelm@43716
   138
  def snapshot(name: String, pending_edits: List[Text.Edit]): Document.Snapshot =
wenzelm@43719
   139
    global_state().snapshot(name, pending_edits)
wenzelm@43716
   140
wenzelm@43651
   141
wenzelm@43651
   142
  /* theory files */
wenzelm@43651
   143
wenzelm@43651
   144
  val thy_load = new Thy_Load
wenzelm@43651
   145
  {
wenzelm@43673
   146
    override def is_loaded(name: String): Boolean =
wenzelm@43673
   147
      loaded_theories.contains(name)
wenzelm@43673
   148
wenzelm@43651
   149
    override def check_thy(dir: Path, name: String): (String, Thy_Header.Header) =
wenzelm@43651
   150
    {
wenzelm@43661
   151
      val file = Isabelle_System.platform_file(dir + Thy_Header.thy_path(name))
wenzelm@43652
   152
      if (!file.exists || !file.isFile) error("No such file: " + quote(file.toString))
wenzelm@43651
   153
      val text = Standard_System.read_file(file)
wenzelm@43661
   154
      val header = Thy_Header.read(text)
wenzelm@43651
   155
      (text, header)
wenzelm@43651
   156
    }
wenzelm@43651
   157
  }
wenzelm@43651
   158
wenzelm@43651
   159
  val thy_info = new Thy_Info(thy_load)
wenzelm@43651
   160
wenzelm@43651
   161
wenzelm@43651
   162
  /* actor messages */
wenzelm@43651
   163
wenzelm@43716
   164
  private case class Start(timeout: Time, args: List[String])
wenzelm@43716
   165
  private case object Interrupt
wenzelm@43697
   166
  private case class Init_Node(name: String, header: Document.Node.Header, text: String)
wenzelm@43716
   167
  private case class Edit_Node(name: String, header: Document.Node.Header, edits: List[Text.Edit])
wenzelm@43722
   168
  private case class Change_Node(
wenzelm@43722
   169
    name: String,
wenzelm@43722
   170
    doc_edits: List[Document.Edit_Command],
wenzelm@43722
   171
    header_edits: List[(String, Thy_Header.Header)],
wenzelm@43722
   172
    previous: Document.Version,
wenzelm@43722
   173
    version: Document.Version)
wenzelm@41534
   174
wenzelm@39572
   175
  private val (_, session_actor) = Simple_Thread.actor("session_actor", daemon = true)
wenzelm@38639
   176
  {
wenzelm@43648
   177
    val this_actor = self
wenzelm@43649
   178
    var prover: Option[Isabelle_Process with Isar_Document] = None
wenzelm@34809
   179
wenzelm@34809
   180
wenzelm@43716
   181
    /* incoming edits */
wenzelm@43716
   182
wenzelm@43718
   183
    def handle_edits(name: String,
wenzelm@43718
   184
        header: Document.Node.Header, edits: List[Option[List[Text.Edit]]])
wenzelm@43716
   185
    //{{{
wenzelm@43716
   186
    {
wenzelm@43716
   187
      val syntax = current_syntax()
wenzelm@43719
   188
      val previous = global_state().history.tip.version
wenzelm@43718
   189
      val doc_edits = edits.map(edit => (name, edit))
wenzelm@43722
   190
      val result = Future.fork {
wenzelm@43722
   191
        Thy_Syntax.text_edits(syntax, previous.join, doc_edits, List((name, header)))
wenzelm@43722
   192
      }
wenzelm@43722
   193
      val change =
wenzelm@43722
   194
        global_state.change_yield(_.extend_history(previous, doc_edits, result.map(_._3)))
wenzelm@43716
   195
wenzelm@43722
   196
      result.map {
wenzelm@43722
   197
        case (doc_edits, header_edits, _) =>
wenzelm@43722
   198
          assignments.await { global_state().is_assigned(previous.get_finished) }
wenzelm@43722
   199
          this_actor !
wenzelm@43722
   200
            Change_Node(name, doc_edits, header_edits, previous.join, change.version.join)
wenzelm@43722
   201
      }
wenzelm@43716
   202
    }
wenzelm@43716
   203
    //}}}
wenzelm@43716
   204
wenzelm@43716
   205
wenzelm@43716
   206
    /* resulting changes */
wenzelm@34809
   207
wenzelm@43722
   208
    def handle_change(change: Change_Node)
wenzelm@38221
   209
    //{{{
wenzelm@34809
   210
    {
wenzelm@43722
   211
      val previous = change.previous
wenzelm@43722
   212
      val version = change.version
wenzelm@43722
   213
      val name = change.name
wenzelm@43722
   214
      val doc_edits = change.doc_edits
wenzelm@43722
   215
      val header_edits = change.header_edits
wenzelm@38366
   216
wenzelm@43719
   217
      var former_assignment = global_state().the_assignment(previous).get_finished
wenzelm@38370
   218
      for {
wenzelm@43722
   219
        (name, Some(cmd_edits)) <- doc_edits
wenzelm@38370
   220
        (prev, None) <- cmd_edits
wenzelm@38417
   221
        removed <- previous.nodes(name).commands.get_after(prev)
wenzelm@38370
   222
      } former_assignment -= removed
wenzelm@38370
   223
wenzelm@43720
   224
      def id_command(command: Command): Document.Command_ID =
wenzelm@43720
   225
      {
wenzelm@43720
   226
        if (global_state().lookup_command(command.id).isEmpty) {
wenzelm@43720
   227
          global_state.change(_.define_command(command))
wenzelm@43720
   228
          prover.get.define_command(command.id, Symbol.encode(command.source))
wenzelm@43720
   229
        }
wenzelm@43720
   230
        command.id
wenzelm@43720
   231
      }
wenzelm@38150
   232
      val id_edits =
wenzelm@43722
   233
        doc_edits map {
wenzelm@43720
   234
          case (name, edits) =>
wenzelm@38370
   235
            val ids =
wenzelm@43720
   236
              edits.map(_.map { case (c1, c2) => (c1.map(id_command), c2.map(id_command)) })
wenzelm@43720
   237
            (name, ids)
wenzelm@38150
   238
        }
wenzelm@43722
   239
wenzelm@39698
   240
      global_state.change(_.define_version(version, former_assignment))
wenzelm@43722
   241
      prover.get.edit_version(previous.id, version.id, id_edits, header_edits)
wenzelm@34809
   242
    }
wenzelm@38221
   243
    //}}}
wenzelm@34809
   244
wenzelm@34809
   245
wenzelm@34809
   246
    /* prover results */
wenzelm@34809
   247
wenzelm@34809
   248
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   249
    //{{{
wenzelm@34809
   250
    {
wenzelm@43716
   251
      def bad_result(result: Isabelle_Process.Result)
wenzelm@43716
   252
      {
wenzelm@43716
   253
        if (verbose)
wenzelm@43716
   254
          System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@43716
   255
      }
wenzelm@43716
   256
wenzelm@38722
   257
      result.properties match {
wenzelm@38722
   258
        case Position.Id(state_id) =>
wenzelm@38370
   259
          try {
wenzelm@38841
   260
            val st = global_state.change_yield(_.accumulate(state_id, result.message))
wenzelm@38841
   261
            command_change_buffer ! st.command
wenzelm@38370
   262
          }
wenzelm@38414
   263
          catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38722
   264
        case _ =>
wenzelm@39630
   265
          if (result.is_syslog) {
wenzelm@39630
   266
            reverse_syslog ::= result.message
wenzelm@40533
   267
            if (result.is_ready) {
wenzelm@43716
   268
              // FIXME move to ML side (!?)
wenzelm@40533
   269
              syntax += ("hence", Keyword.PRF_ASM_GOAL, "then have")
wenzelm@40533
   270
              syntax += ("thus", Keyword.PRF_ASM_GOAL, "then show")
wenzelm@40533
   271
              phase = Session.Ready
wenzelm@40533
   272
            }
wenzelm@39701
   273
            else if (result.is_exit && phase == Session.Startup) phase = Session.Failed
wenzelm@39696
   274
            else if (result.is_exit) phase = Session.Inactive
wenzelm@39630
   275
          }
wenzelm@39626
   276
          else if (result.is_stdout) { }
wenzelm@39625
   277
          else if (result.is_status) {
wenzelm@38370
   278
            result.body match {
wenzelm@38417
   279
              case List(Isar_Document.Assign(id, edits)) =>
wenzelm@38849
   280
                try {
wenzelm@38882
   281
                  val cmds: List[Command] = global_state.change_yield(_.assign(id, edits))
wenzelm@38882
   282
                  for (cmd <- cmds) command_change_buffer ! cmd
wenzelm@38849
   283
                  assignments.event(Session.Assignment)
wenzelm@38849
   284
                }
wenzelm@38414
   285
                catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   286
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   287
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@43673
   288
              case List(Thy_Info.Loaded_Theory(name)) => loaded_theories += name
wenzelm@39625
   289
              case _ => bad_result(result)
wenzelm@38370
   290
            }
wenzelm@38370
   291
          }
wenzelm@39625
   292
          else bad_result(result)
wenzelm@34809
   293
        }
wenzelm@34809
   294
    }
wenzelm@38221
   295
    //}}}
wenzelm@34809
   296
wenzelm@34820
   297
wenzelm@39630
   298
    /* main loop */
wenzelm@34809
   299
wenzelm@43716
   300
    //{{{
wenzelm@38639
   301
    var finished = false
wenzelm@38639
   302
    while (!finished) {
wenzelm@38639
   303
      receive {
wenzelm@43649
   304
        case Start(timeout, args) if prover.isEmpty =>
wenzelm@39701
   305
          if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@39701
   306
            phase = Session.Startup
wenzelm@43661
   307
            prover = Some(new Isabelle_Process(timeout, this_actor, args:_*) with Isar_Document)
wenzelm@39701
   308
          }
wenzelm@38841
   309
wenzelm@39701
   310
        case Stop =>
wenzelm@39701
   311
          if (phase == Session.Ready) {
wenzelm@39701
   312
            global_state.change(_ => Document.State.init)  // FIXME event bus!?
wenzelm@39701
   313
            phase = Session.Shutdown
wenzelm@43649
   314
            prover.get.terminate
wenzelm@43717
   315
            prover = None
wenzelm@39701
   316
            phase = Session.Inactive
wenzelm@39701
   317
          }
wenzelm@39630
   318
          finished = true
wenzelm@39630
   319
          reply(())
wenzelm@38850
   320
wenzelm@43717
   321
        case Interrupt if prover.isDefined =>
wenzelm@43717
   322
          prover.get.interrupt
wenzelm@43716
   323
wenzelm@43716
   324
        case Init_Node(name, header, text) if prover.isDefined =>
wenzelm@43716
   325
          // FIXME compare with existing node
wenzelm@43718
   326
          handle_edits(name, header, List(None, Some(List(Text.Edit.insert(0, text)))))
wenzelm@43716
   327
          reply(())
wenzelm@43716
   328
wenzelm@43718
   329
        case Edit_Node(name, header, text_edits) if prover.isDefined =>
wenzelm@43718
   330
          handle_edits(name, header, List(Some(text_edits)))
wenzelm@43718
   331
          reply(())
wenzelm@43718
   332
wenzelm@43722
   333
        case change: Change_Node if prover.isDefined =>
wenzelm@43722
   334
          handle_change(change)
wenzelm@43716
   335
wenzelm@43721
   336
        case input: Isabelle_Process.Input =>
wenzelm@43721
   337
          raw_messages.event(input)
wenzelm@43721
   338
wenzelm@43716
   339
        case result: Isabelle_Process.Result =>
wenzelm@43716
   340
          handle_result(result)
wenzelm@43721
   341
          raw_messages.event(result)
wenzelm@43716
   342
wenzelm@43717
   343
        case bad => System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   344
      }
wenzelm@34777
   345
    }
wenzelm@43716
   346
    //}}}
wenzelm@34777
   347
  }
wenzelm@34777
   348
wenzelm@34809
   349
wenzelm@43716
   350
  /* actions */
wenzelm@34809
   351
wenzelm@40848
   352
  def start(timeout: Time, args: List[String]) { session_actor ! Start(timeout, args) }
wenzelm@34820
   353
wenzelm@39630
   354
  def stop() { command_change_buffer !? Stop; session_actor !? Stop }
wenzelm@38841
   355
wenzelm@43716
   356
  def interrupt() { session_actor ! Interrupt }
wenzelm@43648
   357
wenzelm@43697
   358
  def init_node(name: String, header: Document.Node.Header, text: String)
wenzelm@43716
   359
  { session_actor !? Init_Node(name, header, text) }
wenzelm@38221
   360
wenzelm@43716
   361
  def edit_node(name: String, header: Document.Node.Header, edits: List[Text.Edit])
wenzelm@43716
   362
  { session_actor !? Edit_Node(name, header, edits) }
wenzelm@34777
   363
}