src/Pure/System/session.scala
author wenzelm
Thu Jul 07 13:48:30 2011 +0200 (2011-07-07)
changeset 43695 5130dfe1b7be
parent 43673 29eb1cd29961
child 43697 77ce24aa1770
permissions -rw-r--r--
simplified Symbol based on lazy Symbol.Interpretation -- reduced odd "functorial style";
tuned implicit build/init messages;
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@43673
   118
  @volatile 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@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@43673
   143
    override def is_loaded(name: String): Boolean =
wenzelm@43673
   144
      loaded_theories.contains(name)
wenzelm@43673
   145
wenzelm@43651
   146
    override def check_thy(dir: Path, name: String): (String, Thy_Header.Header) =
wenzelm@43651
   147
    {
wenzelm@43661
   148
      val file = Isabelle_System.platform_file(dir + Thy_Header.thy_path(name))
wenzelm@43652
   149
      if (!file.exists || !file.isFile) error("No such file: " + quote(file.toString))
wenzelm@43651
   150
      val text = Standard_System.read_file(file)
wenzelm@43661
   151
      val header = Thy_Header.read(text)
wenzelm@43651
   152
      (text, header)
wenzelm@43651
   153
    }
wenzelm@43651
   154
  }
wenzelm@43651
   155
wenzelm@43651
   156
  val thy_info = new Thy_Info(thy_load)
wenzelm@43651
   157
wenzelm@43651
   158
wenzelm@43651
   159
  /* actor messages */
wenzelm@43651
   160
wenzelm@39593
   161
  private case object Interrupt_Prover
wenzelm@43648
   162
  private case class Edit_Node(thy_name: String,
wenzelm@43648
   163
    header: Exn.Result[Thy_Header.Header], edits: List[Text.Edit])
wenzelm@43648
   164
  private case class Init_Node(thy_name: String,
wenzelm@43648
   165
    header: Exn.Result[Thy_Header.Header], text: String)
wenzelm@40848
   166
  private case class Start(timeout: Time, args: List[String])
wenzelm@34777
   167
wenzelm@41534
   168
  var verbose: Boolean = false
wenzelm@41534
   169
wenzelm@39572
   170
  private val (_, session_actor) = Simple_Thread.actor("session_actor", daemon = true)
wenzelm@38639
   171
  {
wenzelm@43648
   172
    val this_actor = self
wenzelm@43649
   173
    var prover: Option[Isabelle_Process with Isar_Document] = None
wenzelm@34809
   174
wenzelm@34809
   175
wenzelm@34809
   176
    /* document changes */
wenzelm@34809
   177
wenzelm@38227
   178
    def handle_change(change: Document.Change)
wenzelm@38221
   179
    //{{{
wenzelm@34809
   180
    {
wenzelm@38848
   181
      val previous = change.previous.get_finished
wenzelm@39698
   182
      val (node_edits, version) = change.result.get_finished
wenzelm@38366
   183
wenzelm@38848
   184
      var former_assignment = global_state.peek().the_assignment(previous).get_finished
wenzelm@38370
   185
      for {
wenzelm@38370
   186
        (name, Some(cmd_edits)) <- node_edits
wenzelm@38370
   187
        (prev, None) <- cmd_edits
wenzelm@38417
   188
        removed <- previous.nodes(name).commands.get_after(prev)
wenzelm@38370
   189
      } former_assignment -= removed
wenzelm@38370
   190
wenzelm@38150
   191
      val id_edits =
wenzelm@38150
   192
        node_edits map {
wenzelm@38150
   193
          case (name, None) => (name, None)
wenzelm@38150
   194
          case (name, Some(cmd_edits)) =>
wenzelm@38370
   195
            val ids =
wenzelm@38150
   196
              cmd_edits map {
wenzelm@38150
   197
                case (c1, c2) =>
wenzelm@38150
   198
                  val id1 = c1.map(_.id)
wenzelm@38150
   199
                  val id2 =
wenzelm@38150
   200
                    c2 match {
wenzelm@38150
   201
                      case None => None
wenzelm@38150
   202
                      case Some(command) =>
wenzelm@38841
   203
                        if (global_state.peek().lookup_command(command.id).isEmpty) {
wenzelm@38841
   204
                          global_state.change(_.define_command(command))
wenzelm@43695
   205
                          prover.get.define_command(command.id, Symbol.encode(command.source))
wenzelm@38150
   206
                        }
wenzelm@38150
   207
                        Some(command.id)
wenzelm@38150
   208
                    }
wenzelm@38150
   209
                  (id1, id2)
wenzelm@38150
   210
              }
wenzelm@38370
   211
            (name -> Some(ids))
wenzelm@38150
   212
        }
wenzelm@39698
   213
      global_state.change(_.define_version(version, former_assignment))
wenzelm@43649
   214
      prover.get.edit_version(previous.id, version.id, id_edits)
wenzelm@34809
   215
    }
wenzelm@38221
   216
    //}}}
wenzelm@34809
   217
wenzelm@34809
   218
wenzelm@34809
   219
    /* prover results */
wenzelm@34809
   220
wenzelm@34836
   221
    def bad_result(result: Isabelle_Process.Result)
wenzelm@34836
   222
    {
wenzelm@41534
   223
      if (verbose)
wenzelm@41534
   224
        System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@34836
   225
    }
wenzelm@34836
   226
wenzelm@34809
   227
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   228
    //{{{
wenzelm@34809
   229
    {
wenzelm@38722
   230
      result.properties match {
wenzelm@38722
   231
        case Position.Id(state_id) =>
wenzelm@38370
   232
          try {
wenzelm@38841
   233
            val st = global_state.change_yield(_.accumulate(state_id, result.message))
wenzelm@38841
   234
            command_change_buffer ! st.command
wenzelm@38370
   235
          }
wenzelm@38414
   236
          catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38722
   237
        case _ =>
wenzelm@39630
   238
          if (result.is_syslog) {
wenzelm@39630
   239
            reverse_syslog ::= result.message
wenzelm@40533
   240
            if (result.is_ready) {
wenzelm@40533
   241
              // FIXME move to ML side
wenzelm@40533
   242
              syntax += ("hence", Keyword.PRF_ASM_GOAL, "then have")
wenzelm@40533
   243
              syntax += ("thus", Keyword.PRF_ASM_GOAL, "then show")
wenzelm@40533
   244
              phase = Session.Ready
wenzelm@40533
   245
            }
wenzelm@39701
   246
            else if (result.is_exit && phase == Session.Startup) phase = Session.Failed
wenzelm@39696
   247
            else if (result.is_exit) phase = Session.Inactive
wenzelm@39630
   248
          }
wenzelm@39626
   249
          else if (result.is_stdout) { }
wenzelm@39625
   250
          else if (result.is_status) {
wenzelm@38370
   251
            result.body match {
wenzelm@38417
   252
              case List(Isar_Document.Assign(id, edits)) =>
wenzelm@38849
   253
                try {
wenzelm@38882
   254
                  val cmds: List[Command] = global_state.change_yield(_.assign(id, edits))
wenzelm@38882
   255
                  for (cmd <- cmds) command_change_buffer ! cmd
wenzelm@38849
   256
                  assignments.event(Session.Assignment)
wenzelm@38849
   257
                }
wenzelm@38414
   258
                catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   259
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   260
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@43673
   261
              case List(Thy_Info.Loaded_Theory(name)) => loaded_theories += name
wenzelm@39625
   262
              case _ => bad_result(result)
wenzelm@38370
   263
            }
wenzelm@38370
   264
          }
wenzelm@39625
   265
          else bad_result(result)
wenzelm@34809
   266
        }
wenzelm@40566
   267
wenzelm@40566
   268
      raw_messages.event(result)
wenzelm@34809
   269
    }
wenzelm@38221
   270
    //}}}
wenzelm@34809
   271
wenzelm@34820
   272
wenzelm@43648
   273
    def edit_version(edits: List[Document.Edit_Text])
wenzelm@43648
   274
    //{{{
wenzelm@43648
   275
    {
wenzelm@43648
   276
      val previous = global_state.peek().history.tip.version
wenzelm@43648
   277
      val syntax = current_syntax()
wenzelm@43662
   278
      val result = Future.fork { Thy_Syntax.text_edits(syntax, previous.join, edits) }
wenzelm@43648
   279
      val change = global_state.change_yield(_.extend_history(previous, edits, result))
wenzelm@43648
   280
wenzelm@43648
   281
      change.version.map(_ => {
wenzelm@43648
   282
        assignments.await { global_state.peek().is_assigned(previous.get_finished) }
wenzelm@43648
   283
        this_actor ! change })
wenzelm@43648
   284
    }
wenzelm@43648
   285
    //}}}
wenzelm@43648
   286
wenzelm@43648
   287
wenzelm@39630
   288
    /* main loop */
wenzelm@34809
   289
wenzelm@38639
   290
    var finished = false
wenzelm@38639
   291
    while (!finished) {
wenzelm@38639
   292
      receive {
wenzelm@39593
   293
        case Interrupt_Prover =>
wenzelm@43649
   294
          prover.map(_.interrupt)
wenzelm@39593
   295
wenzelm@43649
   296
        case Edit_Node(thy_name, header, text_edits) if prover.isDefined =>
wenzelm@43648
   297
          edit_version(List((thy_name, Some(text_edits))))
wenzelm@38841
   298
          reply(())
wenzelm@38841
   299
wenzelm@43649
   300
        case Init_Node(thy_name, header, text) if prover.isDefined =>
wenzelm@43648
   301
          // FIXME compare with existing node
wenzelm@43648
   302
          edit_version(List(
wenzelm@43648
   303
            (thy_name, None),
wenzelm@43648
   304
            (thy_name, Some(List(Text.Edit.insert(0, text))))))
wenzelm@43648
   305
          reply(())
wenzelm@43648
   306
wenzelm@43649
   307
        case change: Document.Change if prover.isDefined =>
wenzelm@43648
   308
          handle_change(change)
wenzelm@39630
   309
wenzelm@39630
   310
        case result: Isabelle_Process.Result => handle_result(result)
wenzelm@38841
   311
wenzelm@43649
   312
        case Start(timeout, args) if prover.isEmpty =>
wenzelm@39701
   313
          if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@39701
   314
            phase = Session.Startup
wenzelm@43661
   315
            prover = Some(new Isabelle_Process(timeout, this_actor, args:_*) with Isar_Document)
wenzelm@39701
   316
          }
wenzelm@38841
   317
wenzelm@39701
   318
        case Stop =>
wenzelm@39701
   319
          if (phase == Session.Ready) {
wenzelm@39701
   320
            global_state.change(_ => Document.State.init)  // FIXME event bus!?
wenzelm@39701
   321
            phase = Session.Shutdown
wenzelm@43649
   322
            prover.get.terminate
wenzelm@39701
   323
            phase = Session.Inactive
wenzelm@39701
   324
          }
wenzelm@39630
   325
          finished = true
wenzelm@39630
   326
          reply(())
wenzelm@38850
   327
wenzelm@43649
   328
        case bad if prover.isDefined =>
wenzelm@34777
   329
          System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   330
      }
wenzelm@34777
   331
    }
wenzelm@34777
   332
  }
wenzelm@34777
   333
wenzelm@34809
   334
wenzelm@37129
   335
wenzelm@38226
   336
  /** main methods **/
wenzelm@34809
   337
wenzelm@40848
   338
  def start(timeout: Time, args: List[String]) { session_actor ! Start(timeout, args) }
wenzelm@34820
   339
wenzelm@39630
   340
  def stop() { command_change_buffer !? Stop; session_actor !? Stop }
wenzelm@38841
   341
wenzelm@39593
   342
  def interrupt() { session_actor ! Interrupt_Prover }
wenzelm@39593
   343
wenzelm@43648
   344
  def edit_node(thy_name: String, header: Exn.Result[Thy_Header.Header], edits: List[Text.Edit])
wenzelm@43648
   345
  {
wenzelm@43648
   346
    session_actor !? Edit_Node(thy_name, header, edits)
wenzelm@43648
   347
  }
wenzelm@43648
   348
wenzelm@43648
   349
  def init_node(thy_name: String, header: Exn.Result[Thy_Header.Header], text: String)
wenzelm@43648
   350
  {
wenzelm@43648
   351
    session_actor !? Init_Node(thy_name, header, text)
wenzelm@43648
   352
  }
wenzelm@38221
   353
wenzelm@38841
   354
  def snapshot(name: String, pending_edits: List[Text.Edit]): Document.Snapshot =
wenzelm@38841
   355
    global_state.peek().snapshot(name, pending_edits)
wenzelm@34777
   356
}