src/Pure/System/session.scala
author wenzelm
Mon Jul 04 16:27:11 2011 +0200 (2011-07-04)
changeset 43651 511df47bcadc
parent 43649 a912f0b02359
child 43652 dcd0b667f73d
permissions -rw-r--r--
some support for theory files within Isabelle/Scala session;
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@43645
    43
class Session(val system: Isabelle_System, 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@34778
    67
  /* unique ids */
wenzelm@34778
    68
wenzelm@38363
    69
  private var id_count: Document.ID = 0
wenzelm@38419
    70
  def new_id(): Document.ID = synchronized {
wenzelm@38355
    71
    require(id_count > java.lang.Long.MIN_VALUE)
wenzelm@38355
    72
    id_count -= 1
wenzelm@38355
    73
    id_count
wenzelm@38355
    74
  }
wenzelm@34778
    75
wenzelm@34778
    76
wenzelm@34826
    77
wenzelm@38841
    78
  /** buffered command changes (delay_first discipline) **/
wenzelm@38841
    79
wenzelm@38841
    80
  private case object Stop
wenzelm@38841
    81
wenzelm@39572
    82
  private val (_, command_change_buffer) =
wenzelm@39572
    83
    Simple_Thread.actor("command_change_buffer", daemon = true)
wenzelm@38841
    84
  //{{{
wenzelm@38841
    85
  {
wenzelm@38841
    86
    var changed: Set[Command] = Set()
wenzelm@38841
    87
    var flush_time: Option[Long] = None
wenzelm@38841
    88
wenzelm@38841
    89
    def flush_timeout: Long =
wenzelm@38841
    90
      flush_time match {
wenzelm@38841
    91
        case None => 5000L
wenzelm@40848
    92
        case Some(time) => (time - System.currentTimeMillis()) max 0
wenzelm@38841
    93
      }
wenzelm@38841
    94
wenzelm@38841
    95
    def flush()
wenzelm@38841
    96
    {
wenzelm@38841
    97
      if (!changed.isEmpty) commands_changed.event(Session.Commands_Changed(changed))
wenzelm@38841
    98
      changed = Set()
wenzelm@38841
    99
      flush_time = None
wenzelm@38841
   100
    }
wenzelm@38841
   101
wenzelm@38841
   102
    def invoke()
wenzelm@38841
   103
    {
wenzelm@40848
   104
      val now = System.currentTimeMillis()
wenzelm@38841
   105
      flush_time match {
wenzelm@40848
   106
        case None => flush_time = Some(now + output_delay.ms)
wenzelm@38841
   107
        case Some(time) => if (now >= time) flush()
wenzelm@38841
   108
      }
wenzelm@38841
   109
    }
wenzelm@38841
   110
wenzelm@38841
   111
    var finished = false
wenzelm@38841
   112
    while (!finished) {
wenzelm@38841
   113
      receiveWithin(flush_timeout) {
wenzelm@38841
   114
        case command: Command => changed += command; invoke()
wenzelm@38841
   115
        case TIMEOUT => flush()
wenzelm@39630
   116
        case Stop => finished = true; reply(())
wenzelm@38841
   117
        case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
wenzelm@38841
   118
      }
wenzelm@38841
   119
    }
wenzelm@38841
   120
  }
wenzelm@38841
   121
  //}}}
wenzelm@38841
   122
wenzelm@38841
   123
wenzelm@38841
   124
wenzelm@38841
   125
  /** main protocol actor **/
wenzelm@34809
   126
wenzelm@43651
   127
  /* global state */
wenzelm@43644
   128
wenzelm@34851
   129
  @volatile private var syntax = new Outer_Syntax(system.symbols)
wenzelm@38569
   130
  def current_syntax(): Outer_Syntax = syntax
wenzelm@34809
   131
wenzelm@39626
   132
  @volatile private var reverse_syslog = List[XML.Elem]()
wenzelm@39629
   133
  def syslog(): String = reverse_syslog.reverse.map(msg => XML.content(msg).mkString).mkString("\n")
wenzelm@39626
   134
wenzelm@39630
   135
  @volatile private var _phase: Session.Phase = Session.Inactive
wenzelm@39630
   136
  def phase = _phase
wenzelm@39633
   137
  private def phase_=(new_phase: Session.Phase)
wenzelm@39630
   138
  {
wenzelm@39630
   139
    _phase = new_phase
wenzelm@39701
   140
    phase_changed.event(new_phase)
wenzelm@39630
   141
  }
wenzelm@43553
   142
  def is_ready: Boolean = phase == Session.Ready
wenzelm@39630
   143
wenzelm@38841
   144
  private val global_state = new Volatile(Document.State.init)
wenzelm@38841
   145
  def current_state(): Document.State = global_state.peek()
wenzelm@34816
   146
wenzelm@43651
   147
wenzelm@43651
   148
  /* theory files */
wenzelm@43651
   149
wenzelm@43651
   150
  val thy_header = new Thy_Header(system.symbols)
wenzelm@43651
   151
wenzelm@43651
   152
  val thy_load = new Thy_Load
wenzelm@43651
   153
  {
wenzelm@43651
   154
    override def check_thy(dir: Path, name: String): (String, Thy_Header.Header) =
wenzelm@43651
   155
    {
wenzelm@43651
   156
      val file = system.platform_file(dir + Thy_Header.thy_path(name))
wenzelm@43651
   157
      if (!file.exists || !file.isFile) error("No such file: " + Library.quote(file.toString))
wenzelm@43651
   158
      val text = Standard_System.read_file(file)
wenzelm@43651
   159
      val header = thy_header.read(text)
wenzelm@43651
   160
      (text, header)
wenzelm@43651
   161
    }
wenzelm@43651
   162
  }
wenzelm@43651
   163
wenzelm@43651
   164
  val thy_info = new Thy_Info(thy_load)
wenzelm@43651
   165
wenzelm@43651
   166
wenzelm@43651
   167
  /* actor messages */
wenzelm@43651
   168
wenzelm@39593
   169
  private case object Interrupt_Prover
wenzelm@43648
   170
  private case class Edit_Node(thy_name: String,
wenzelm@43648
   171
    header: Exn.Result[Thy_Header.Header], edits: List[Text.Edit])
wenzelm@43648
   172
  private case class Init_Node(thy_name: String,
wenzelm@43648
   173
    header: Exn.Result[Thy_Header.Header], text: String)
wenzelm@40848
   174
  private case class Start(timeout: Time, args: List[String])
wenzelm@34777
   175
wenzelm@41534
   176
  var verbose: Boolean = false
wenzelm@41534
   177
wenzelm@39572
   178
  private val (_, session_actor) = Simple_Thread.actor("session_actor", daemon = true)
wenzelm@38639
   179
  {
wenzelm@43648
   180
    val this_actor = self
wenzelm@43649
   181
    var prover: Option[Isabelle_Process with Isar_Document] = None
wenzelm@34809
   182
wenzelm@34809
   183
wenzelm@34809
   184
    /* document changes */
wenzelm@34809
   185
wenzelm@38227
   186
    def handle_change(change: Document.Change)
wenzelm@38221
   187
    //{{{
wenzelm@34809
   188
    {
wenzelm@38848
   189
      val previous = change.previous.get_finished
wenzelm@39698
   190
      val (node_edits, version) = change.result.get_finished
wenzelm@38366
   191
wenzelm@38848
   192
      var former_assignment = global_state.peek().the_assignment(previous).get_finished
wenzelm@38370
   193
      for {
wenzelm@38370
   194
        (name, Some(cmd_edits)) <- node_edits
wenzelm@38370
   195
        (prev, None) <- cmd_edits
wenzelm@38417
   196
        removed <- previous.nodes(name).commands.get_after(prev)
wenzelm@38370
   197
      } former_assignment -= removed
wenzelm@38370
   198
wenzelm@38150
   199
      val id_edits =
wenzelm@38150
   200
        node_edits map {
wenzelm@38150
   201
          case (name, None) => (name, None)
wenzelm@38150
   202
          case (name, Some(cmd_edits)) =>
wenzelm@38370
   203
            val ids =
wenzelm@38150
   204
              cmd_edits map {
wenzelm@38150
   205
                case (c1, c2) =>
wenzelm@38150
   206
                  val id1 = c1.map(_.id)
wenzelm@38150
   207
                  val id2 =
wenzelm@38150
   208
                    c2 match {
wenzelm@38150
   209
                      case None => None
wenzelm@38150
   210
                      case Some(command) =>
wenzelm@38841
   211
                        if (global_state.peek().lookup_command(command.id).isEmpty) {
wenzelm@38841
   212
                          global_state.change(_.define_command(command))
wenzelm@43649
   213
                          prover.get.
wenzelm@43649
   214
                            define_command(command.id, system.symbols.encode(command.source))
wenzelm@38150
   215
                        }
wenzelm@38150
   216
                        Some(command.id)
wenzelm@38150
   217
                    }
wenzelm@38150
   218
                  (id1, id2)
wenzelm@38150
   219
              }
wenzelm@38370
   220
            (name -> Some(ids))
wenzelm@38150
   221
        }
wenzelm@39698
   222
      global_state.change(_.define_version(version, former_assignment))
wenzelm@43649
   223
      prover.get.edit_version(previous.id, version.id, id_edits)
wenzelm@34809
   224
    }
wenzelm@38221
   225
    //}}}
wenzelm@34809
   226
wenzelm@34809
   227
wenzelm@34809
   228
    /* prover results */
wenzelm@34809
   229
wenzelm@34836
   230
    def bad_result(result: Isabelle_Process.Result)
wenzelm@34836
   231
    {
wenzelm@41534
   232
      if (verbose)
wenzelm@41534
   233
        System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@34836
   234
    }
wenzelm@34836
   235
wenzelm@34809
   236
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   237
    //{{{
wenzelm@34809
   238
    {
wenzelm@38722
   239
      result.properties match {
wenzelm@38722
   240
        case Position.Id(state_id) =>
wenzelm@38370
   241
          try {
wenzelm@38841
   242
            val st = global_state.change_yield(_.accumulate(state_id, result.message))
wenzelm@38841
   243
            command_change_buffer ! st.command
wenzelm@38370
   244
          }
wenzelm@38414
   245
          catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38722
   246
        case _ =>
wenzelm@39630
   247
          if (result.is_syslog) {
wenzelm@39630
   248
            reverse_syslog ::= result.message
wenzelm@40533
   249
            if (result.is_ready) {
wenzelm@40533
   250
              // FIXME move to ML side
wenzelm@40533
   251
              syntax += ("hence", Keyword.PRF_ASM_GOAL, "then have")
wenzelm@40533
   252
              syntax += ("thus", Keyword.PRF_ASM_GOAL, "then show")
wenzelm@40533
   253
              phase = Session.Ready
wenzelm@40533
   254
            }
wenzelm@39701
   255
            else if (result.is_exit && phase == Session.Startup) phase = Session.Failed
wenzelm@39696
   256
            else if (result.is_exit) phase = Session.Inactive
wenzelm@39630
   257
          }
wenzelm@39626
   258
          else if (result.is_stdout) { }
wenzelm@39625
   259
          else if (result.is_status) {
wenzelm@38370
   260
            result.body match {
wenzelm@38417
   261
              case List(Isar_Document.Assign(id, edits)) =>
wenzelm@38849
   262
                try {
wenzelm@38882
   263
                  val cmds: List[Command] = global_state.change_yield(_.assign(id, edits))
wenzelm@38882
   264
                  for (cmd <- cmds) command_change_buffer ! cmd
wenzelm@38849
   265
                  assignments.event(Session.Assignment)
wenzelm@38849
   266
                }
wenzelm@38414
   267
                catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   268
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   269
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@39625
   270
              case _ => bad_result(result)
wenzelm@38370
   271
            }
wenzelm@38370
   272
          }
wenzelm@39625
   273
          else bad_result(result)
wenzelm@34809
   274
        }
wenzelm@40566
   275
wenzelm@40566
   276
      raw_messages.event(result)
wenzelm@34809
   277
    }
wenzelm@38221
   278
    //}}}
wenzelm@34809
   279
wenzelm@34820
   280
wenzelm@43648
   281
    def edit_version(edits: List[Document.Edit_Text])
wenzelm@43648
   282
    //{{{
wenzelm@43648
   283
    {
wenzelm@43648
   284
      val previous = global_state.peek().history.tip.version
wenzelm@43648
   285
      val syntax = current_syntax()
wenzelm@43648
   286
      val result = Future.fork { Thy_Syntax.text_edits(syntax, new_id _, previous.join, edits) }
wenzelm@43648
   287
      val change = global_state.change_yield(_.extend_history(previous, edits, result))
wenzelm@43648
   288
wenzelm@43648
   289
      change.version.map(_ => {
wenzelm@43648
   290
        assignments.await { global_state.peek().is_assigned(previous.get_finished) }
wenzelm@43648
   291
        this_actor ! change })
wenzelm@43648
   292
    }
wenzelm@43648
   293
    //}}}
wenzelm@43648
   294
wenzelm@43648
   295
wenzelm@39630
   296
    /* main loop */
wenzelm@34809
   297
wenzelm@38639
   298
    var finished = false
wenzelm@38639
   299
    while (!finished) {
wenzelm@38639
   300
      receive {
wenzelm@39593
   301
        case Interrupt_Prover =>
wenzelm@43649
   302
          prover.map(_.interrupt)
wenzelm@39593
   303
wenzelm@43649
   304
        case Edit_Node(thy_name, header, text_edits) if prover.isDefined =>
wenzelm@43648
   305
          edit_version(List((thy_name, Some(text_edits))))
wenzelm@38841
   306
          reply(())
wenzelm@38841
   307
wenzelm@43649
   308
        case Init_Node(thy_name, header, text) if prover.isDefined =>
wenzelm@43648
   309
          // FIXME compare with existing node
wenzelm@43648
   310
          edit_version(List(
wenzelm@43648
   311
            (thy_name, None),
wenzelm@43648
   312
            (thy_name, Some(List(Text.Edit.insert(0, text))))))
wenzelm@43648
   313
          reply(())
wenzelm@43648
   314
wenzelm@43649
   315
        case change: Document.Change if prover.isDefined =>
wenzelm@43648
   316
          handle_change(change)
wenzelm@39630
   317
wenzelm@39630
   318
        case result: Isabelle_Process.Result => handle_result(result)
wenzelm@38841
   319
wenzelm@43649
   320
        case Start(timeout, args) if prover.isEmpty =>
wenzelm@39701
   321
          if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@39701
   322
            phase = Session.Startup
wenzelm@43649
   323
            prover =
wenzelm@43649
   324
              Some(new Isabelle_Process(system, timeout, this_actor, args:_*) with Isar_Document)
wenzelm@39701
   325
          }
wenzelm@38841
   326
wenzelm@39701
   327
        case Stop =>
wenzelm@39701
   328
          if (phase == Session.Ready) {
wenzelm@39701
   329
            global_state.change(_ => Document.State.init)  // FIXME event bus!?
wenzelm@39701
   330
            phase = Session.Shutdown
wenzelm@43649
   331
            prover.get.terminate
wenzelm@39701
   332
            phase = Session.Inactive
wenzelm@39701
   333
          }
wenzelm@39630
   334
          finished = true
wenzelm@39630
   335
          reply(())
wenzelm@38850
   336
wenzelm@43649
   337
        case bad if prover.isDefined =>
wenzelm@34777
   338
          System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   339
      }
wenzelm@34777
   340
    }
wenzelm@34777
   341
  }
wenzelm@34777
   342
wenzelm@34809
   343
wenzelm@37129
   344
wenzelm@38226
   345
  /** main methods **/
wenzelm@34809
   346
wenzelm@40848
   347
  def start(timeout: Time, args: List[String]) { session_actor ! Start(timeout, args) }
wenzelm@34820
   348
wenzelm@39630
   349
  def stop() { command_change_buffer !? Stop; session_actor !? Stop }
wenzelm@38841
   350
wenzelm@39593
   351
  def interrupt() { session_actor ! Interrupt_Prover }
wenzelm@39593
   352
wenzelm@43648
   353
  def edit_node(thy_name: String, header: Exn.Result[Thy_Header.Header], edits: List[Text.Edit])
wenzelm@43648
   354
  {
wenzelm@43648
   355
    session_actor !? Edit_Node(thy_name, header, edits)
wenzelm@43648
   356
  }
wenzelm@43648
   357
wenzelm@43648
   358
  def init_node(thy_name: String, header: Exn.Result[Thy_Header.Header], text: String)
wenzelm@43648
   359
  {
wenzelm@43648
   360
    session_actor !? Init_Node(thy_name, header, text)
wenzelm@43648
   361
  }
wenzelm@38221
   362
wenzelm@38841
   363
  def snapshot(name: String, pending_edits: List[Text.Edit]): Document.Snapshot =
wenzelm@38841
   364
    global_state.peek().snapshot(name, pending_edits)
wenzelm@34777
   365
}