src/Pure/System/session.scala
author wenzelm
Sat Jul 09 16:53:19 2011 +0200 (2011-07-09)
changeset 43716 1d64662c1bfd
parent 43697 77ce24aa1770
child 43717 c3ddb5537a2f
permissions -rw-r--r--
tuned source structure;
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@43716
    61
  val raw_messages = new Event_Bus[Isabelle_Process.Result]
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@38841
   136
  def current_state(): Document.State = global_state.peek()
wenzelm@34816
   137
wenzelm@43716
   138
  def snapshot(name: String, pending_edits: List[Text.Edit]): Document.Snapshot =
wenzelm@43716
   139
    current_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@41534
   168
wenzelm@39572
   169
  private val (_, session_actor) = Simple_Thread.actor("session_actor", daemon = true)
wenzelm@38639
   170
  {
wenzelm@43648
   171
    val this_actor = self
wenzelm@43649
   172
    var prover: Option[Isabelle_Process with Isar_Document] = None
wenzelm@34809
   173
wenzelm@34809
   174
wenzelm@43716
   175
    /* incoming edits */
wenzelm@43716
   176
wenzelm@43716
   177
    def handle_edits(headers: List[Document.Node.Header], edits: List[Document.Edit_Text])
wenzelm@43716
   178
    //{{{
wenzelm@43716
   179
    {
wenzelm@43716
   180
      val syntax = current_syntax()
wenzelm@43716
   181
      val previous = current_state().history.tip.version
wenzelm@43716
   182
      val result = Future.fork { Thy_Syntax.text_edits(syntax, previous.join, edits) }
wenzelm@43716
   183
      val change = global_state.change_yield(_.extend_history(previous, edits, result))
wenzelm@43716
   184
wenzelm@43716
   185
      change.version.map(_ => {
wenzelm@43716
   186
        assignments.await { current_state().is_assigned(previous.get_finished) }
wenzelm@43716
   187
        this_actor ! change })
wenzelm@43716
   188
    }
wenzelm@43716
   189
    //}}}
wenzelm@43716
   190
wenzelm@43716
   191
wenzelm@43716
   192
    /* resulting changes */
wenzelm@34809
   193
wenzelm@38227
   194
    def handle_change(change: Document.Change)
wenzelm@38221
   195
    //{{{
wenzelm@34809
   196
    {
wenzelm@38848
   197
      val previous = change.previous.get_finished
wenzelm@39698
   198
      val (node_edits, version) = change.result.get_finished
wenzelm@38366
   199
wenzelm@43716
   200
      var former_assignment = current_state().the_assignment(previous).get_finished
wenzelm@38370
   201
      for {
wenzelm@38370
   202
        (name, Some(cmd_edits)) <- node_edits
wenzelm@38370
   203
        (prev, None) <- cmd_edits
wenzelm@38417
   204
        removed <- previous.nodes(name).commands.get_after(prev)
wenzelm@38370
   205
      } former_assignment -= removed
wenzelm@38370
   206
wenzelm@38150
   207
      val id_edits =
wenzelm@38150
   208
        node_edits map {
wenzelm@38150
   209
          case (name, None) => (name, None)
wenzelm@38150
   210
          case (name, Some(cmd_edits)) =>
wenzelm@38370
   211
            val ids =
wenzelm@38150
   212
              cmd_edits map {
wenzelm@38150
   213
                case (c1, c2) =>
wenzelm@38150
   214
                  val id1 = c1.map(_.id)
wenzelm@38150
   215
                  val id2 =
wenzelm@38150
   216
                    c2 match {
wenzelm@38150
   217
                      case None => None
wenzelm@38150
   218
                      case Some(command) =>
wenzelm@43716
   219
                        if (current_state().lookup_command(command.id).isEmpty) {
wenzelm@38841
   220
                          global_state.change(_.define_command(command))
wenzelm@43695
   221
                          prover.get.define_command(command.id, Symbol.encode(command.source))
wenzelm@38150
   222
                        }
wenzelm@38150
   223
                        Some(command.id)
wenzelm@38150
   224
                    }
wenzelm@38150
   225
                  (id1, id2)
wenzelm@38150
   226
              }
wenzelm@38370
   227
            (name -> Some(ids))
wenzelm@38150
   228
        }
wenzelm@39698
   229
      global_state.change(_.define_version(version, former_assignment))
wenzelm@43649
   230
      prover.get.edit_version(previous.id, version.id, id_edits)
wenzelm@34809
   231
    }
wenzelm@38221
   232
    //}}}
wenzelm@34809
   233
wenzelm@34809
   234
wenzelm@34809
   235
    /* prover results */
wenzelm@34809
   236
wenzelm@34809
   237
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   238
    //{{{
wenzelm@34809
   239
    {
wenzelm@43716
   240
      def bad_result(result: Isabelle_Process.Result)
wenzelm@43716
   241
      {
wenzelm@43716
   242
        if (verbose)
wenzelm@43716
   243
          System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@43716
   244
      }
wenzelm@43716
   245
wenzelm@38722
   246
      result.properties match {
wenzelm@38722
   247
        case Position.Id(state_id) =>
wenzelm@38370
   248
          try {
wenzelm@38841
   249
            val st = global_state.change_yield(_.accumulate(state_id, result.message))
wenzelm@38841
   250
            command_change_buffer ! st.command
wenzelm@38370
   251
          }
wenzelm@38414
   252
          catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38722
   253
        case _ =>
wenzelm@39630
   254
          if (result.is_syslog) {
wenzelm@39630
   255
            reverse_syslog ::= result.message
wenzelm@40533
   256
            if (result.is_ready) {
wenzelm@43716
   257
              // FIXME move to ML side (!?)
wenzelm@40533
   258
              syntax += ("hence", Keyword.PRF_ASM_GOAL, "then have")
wenzelm@40533
   259
              syntax += ("thus", Keyword.PRF_ASM_GOAL, "then show")
wenzelm@40533
   260
              phase = Session.Ready
wenzelm@40533
   261
            }
wenzelm@39701
   262
            else if (result.is_exit && phase == Session.Startup) phase = Session.Failed
wenzelm@39696
   263
            else if (result.is_exit) phase = Session.Inactive
wenzelm@39630
   264
          }
wenzelm@39626
   265
          else if (result.is_stdout) { }
wenzelm@39625
   266
          else if (result.is_status) {
wenzelm@38370
   267
            result.body match {
wenzelm@38417
   268
              case List(Isar_Document.Assign(id, edits)) =>
wenzelm@38849
   269
                try {
wenzelm@38882
   270
                  val cmds: List[Command] = global_state.change_yield(_.assign(id, edits))
wenzelm@38882
   271
                  for (cmd <- cmds) command_change_buffer ! cmd
wenzelm@38849
   272
                  assignments.event(Session.Assignment)
wenzelm@38849
   273
                }
wenzelm@38414
   274
                catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   275
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   276
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@43673
   277
              case List(Thy_Info.Loaded_Theory(name)) => loaded_theories += name
wenzelm@39625
   278
              case _ => bad_result(result)
wenzelm@38370
   279
            }
wenzelm@38370
   280
          }
wenzelm@39625
   281
          else bad_result(result)
wenzelm@34809
   282
        }
wenzelm@40566
   283
wenzelm@40566
   284
      raw_messages.event(result)
wenzelm@34809
   285
    }
wenzelm@38221
   286
    //}}}
wenzelm@34809
   287
wenzelm@34820
   288
wenzelm@39630
   289
    /* main loop */
wenzelm@34809
   290
wenzelm@43716
   291
    //{{{
wenzelm@38639
   292
    var finished = false
wenzelm@38639
   293
    while (!finished) {
wenzelm@38639
   294
      receive {
wenzelm@43649
   295
        case Start(timeout, args) if prover.isEmpty =>
wenzelm@39701
   296
          if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@39701
   297
            phase = Session.Startup
wenzelm@43661
   298
            prover = Some(new Isabelle_Process(timeout, this_actor, args:_*) with Isar_Document)
wenzelm@39701
   299
          }
wenzelm@38841
   300
wenzelm@39701
   301
        case Stop =>
wenzelm@39701
   302
          if (phase == Session.Ready) {
wenzelm@39701
   303
            global_state.change(_ => Document.State.init)  // FIXME event bus!?
wenzelm@39701
   304
            phase = Session.Shutdown
wenzelm@43649
   305
            prover.get.terminate
wenzelm@39701
   306
            phase = Session.Inactive
wenzelm@39701
   307
          }
wenzelm@39630
   308
          finished = true
wenzelm@39630
   309
          reply(())
wenzelm@38850
   310
wenzelm@43716
   311
        case Interrupt =>
wenzelm@43716
   312
          prover.map(_.interrupt)
wenzelm@43716
   313
wenzelm@43716
   314
        case Edit_Node(name, header, text_edits) if prover.isDefined =>
wenzelm@43716
   315
          val node_name = (header.master_dir + Path.basic(name)).implode  // FIXME
wenzelm@43716
   316
          handle_edits(List(header), List((node_name, Some(text_edits))))
wenzelm@43716
   317
          reply(())
wenzelm@43716
   318
wenzelm@43716
   319
        case Init_Node(name, header, text) if prover.isDefined =>
wenzelm@43716
   320
          // FIXME compare with existing node
wenzelm@43716
   321
          val node_name = (header.master_dir + Path.basic(name)).implode  // FIXME
wenzelm@43716
   322
          handle_edits(List(header),
wenzelm@43716
   323
            List(
wenzelm@43716
   324
              (node_name, None),
wenzelm@43716
   325
              (node_name, Some(List(Text.Edit.insert(0, text))))))
wenzelm@43716
   326
          reply(())
wenzelm@43716
   327
wenzelm@43716
   328
        case change: Document.Change if prover.isDefined =>
wenzelm@43716
   329
          handle_change(change)
wenzelm@43716
   330
wenzelm@43716
   331
        case result: Isabelle_Process.Result =>
wenzelm@43716
   332
          handle_result(result)
wenzelm@43716
   333
wenzelm@43649
   334
        case bad if prover.isDefined =>
wenzelm@34777
   335
          System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   336
      }
wenzelm@34777
   337
    }
wenzelm@43716
   338
    //}}}
wenzelm@34777
   339
  }
wenzelm@34777
   340
wenzelm@34809
   341
wenzelm@43716
   342
  /* actions */
wenzelm@34809
   343
wenzelm@40848
   344
  def start(timeout: Time, args: List[String]) { session_actor ! Start(timeout, args) }
wenzelm@34820
   345
wenzelm@39630
   346
  def stop() { command_change_buffer !? Stop; session_actor !? Stop }
wenzelm@38841
   347
wenzelm@43716
   348
  def interrupt() { session_actor ! Interrupt }
wenzelm@43648
   349
wenzelm@43697
   350
  def init_node(name: String, header: Document.Node.Header, text: String)
wenzelm@43716
   351
  { session_actor !? Init_Node(name, header, text) }
wenzelm@38221
   352
wenzelm@43716
   353
  def edit_node(name: String, header: Document.Node.Header, edits: List[Text.Edit])
wenzelm@43716
   354
  { session_actor !? Edit_Node(name, header, edits) }
wenzelm@34777
   355
}