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