src/Pure/System/session.scala
author wenzelm
Thu May 27 12:35:40 2010 +0200 (2010-05-27)
changeset 37132 10ef4da1c314
parent 37129 4c83696b340e
child 37689 628eabe2213a
permissions -rw-r--r--
indicate prospective properties;
     1 /*  Title:      Pure/System/session.scala
     2     Author:     Makarius
     3 
     4 Isabelle session, potentially with running prover.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import scala.actors.TIMEOUT
    11 import scala.actors.Actor._
    12 
    13 
    14 object Session
    15 {
    16   /* events */
    17 
    18   case object Global_Settings
    19 
    20 
    21   /* managed entities */
    22 
    23   type Entity_ID = String
    24 
    25   trait Entity
    26   {
    27     val id: Entity_ID
    28     def consume(message: XML.Tree, forward: Command => Unit): Unit
    29   }
    30 }
    31 
    32 
    33 class Session(system: Isabelle_System)
    34 {
    35   /* pervasive event buses */
    36 
    37   val global_settings = new Event_Bus[Session.Global_Settings.type]
    38   val raw_results = new Event_Bus[Isabelle_Process.Result]
    39   val raw_output = new Event_Bus[Isabelle_Process.Result]
    40   val commands_changed = new Event_Bus[Command_Set]
    41 
    42 
    43   /* unique ids */
    44 
    45   private var id_count: BigInt = 0
    46   def create_id(): Session.Entity_ID = synchronized { id_count += 1; "j" + id_count }
    47 
    48 
    49 
    50   /** main actor **/
    51 
    52   @volatile private var syntax = new Outer_Syntax(system.symbols)
    53   def current_syntax: Outer_Syntax = syntax
    54 
    55   @volatile private var entities = Map[Session.Entity_ID, Session.Entity]()
    56   def lookup_entity(id: Session.Entity_ID): Option[Session.Entity] = entities.get(id)
    57   def lookup_command(id: Session.Entity_ID): Option[Command] =
    58     lookup_entity(id) match {
    59       case Some(cmd: Command) => Some(cmd)
    60       case _ => None
    61     }
    62 
    63   private case class Start(timeout: Int, args: List[String])
    64   private case object Stop
    65   private case class Begin_Document(path: String)
    66 
    67   private lazy val session_actor = actor {
    68 
    69     var prover: Isabelle_Process with Isar_Document = null
    70 
    71     def register(entity: Session.Entity) { entities += (entity.id -> entity) }
    72 
    73     var documents = Map[Isar_Document.Document_ID, Document]()
    74     def register_document(doc: Document) { documents += (doc.id -> doc) }
    75 
    76 
    77     /* document changes */
    78 
    79     def handle_change(change: Change)
    80     {
    81       require(change.parent.isDefined)
    82 
    83       val (changes, doc) = change.result.join
    84       val id_changes = changes map {
    85         case (c1, c2) =>
    86           (c1.map(_.id).getOrElse(""),
    87            c2 match {
    88               case None => None
    89               case Some(command) =>
    90                 if (!lookup_command(command.id).isDefined) {
    91                   register(command)
    92                   prover.define_command(command.id, system.symbols.encode(command.source))
    93                 }
    94                 Some(command.id)
    95             })
    96       }
    97       register_document(doc)
    98       prover.edit_document(change.parent.get.id, doc.id, id_changes)
    99     }
   100 
   101 
   102     /* prover results */
   103 
   104     def bad_result(result: Isabelle_Process.Result)
   105     {
   106       System.err.println("Ignoring prover result: " + result.message.toString)
   107     }
   108 
   109     def handle_result(result: Isabelle_Process.Result)
   110     {
   111       raw_results.event(result)
   112 
   113       val target_id: Option[Session.Entity_ID] = Position.get_id(result.props)
   114       val target: Option[Session.Entity] =
   115         target_id match {
   116           case None => None
   117           case Some(id) => lookup_entity(id)
   118         }
   119       if (target.isDefined) target.get.consume(result.message, indicate_command_change)
   120       else if (result.kind == Isabelle_Process.Kind.STATUS) {
   121         // global status message
   122         result.body match {
   123 
   124           // document state assignment
   125           case List(Isar_Document.Assign(edits)) if target_id.isDefined =>
   126             documents.get(target_id.get) match {
   127               case Some(doc) =>
   128                 val states =
   129                   for {
   130                     Isar_Document.Edit(cmd_id, state_id) <- edits
   131                     cmd <- lookup_command(cmd_id)
   132                   } yield {
   133                     val st = cmd.assign_state(state_id)
   134                     register(st)
   135                     (cmd, st)
   136                   }
   137                 doc.assign_states(states)
   138               case None => bad_result(result)
   139             }
   140 
   141           // keyword declarations
   142           case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
   143           case List(Keyword.Keyword_Decl(name)) => syntax += name
   144 
   145           case _ => if (!result.is_ready) bad_result(result)
   146         }
   147       }
   148       else if (result.kind == Isabelle_Process.Kind.EXIT)
   149         prover = null
   150       else if (result.is_raw)
   151         raw_output.event(result)
   152       else if (!result.is_system)   // FIXME syslog (!?)
   153         bad_result(result)
   154     }
   155 
   156 
   157     /* prover startup */
   158 
   159     def startup_error(): String =
   160     {
   161       val buf = new StringBuilder
   162       while (
   163         receiveWithin(0) {
   164           case result: Isabelle_Process.Result =>
   165             if (result.is_raw) {
   166               for (text <- XML.content(result.message))
   167                 buf.append(text)
   168             }
   169             true
   170           case TIMEOUT => false
   171         }) {}
   172       buf.toString
   173     }
   174 
   175     def prover_startup(timeout: Int): Option[String] =
   176     {
   177       receiveWithin(timeout) {
   178         case result: Isabelle_Process.Result
   179           if result.kind == Isabelle_Process.Kind.INIT =>
   180           while (receive {
   181             case result: Isabelle_Process.Result =>
   182               handle_result(result); !result.is_ready
   183             }) {}
   184           None
   185 
   186         case result: Isabelle_Process.Result
   187           if result.kind == Isabelle_Process.Kind.EXIT =>
   188           Some(startup_error())
   189 
   190         case TIMEOUT =>  // FIXME clarify
   191           prover.kill; Some(startup_error())
   192       }
   193     }
   194 
   195 
   196     /* main loop */
   197 
   198     val xml_cache = new XML.Cache(131071)
   199 
   200     loop {
   201       react {
   202         case Start(timeout, args) =>
   203           if (prover == null) {
   204             prover = new Isabelle_Process(system, self, args:_*) with Isar_Document
   205             val origin = sender
   206             val opt_err = prover_startup(timeout)
   207             if (opt_err.isDefined) prover = null
   208             origin ! opt_err
   209           }
   210           else reply(None)
   211 
   212         case Stop =>  // FIXME clarify; synchronous
   213           if (prover != null) {
   214             prover.kill
   215             prover = null
   216           }
   217 
   218         case Begin_Document(path: String) if prover != null =>
   219           val id = create_id()
   220           val doc = Document.empty(id)
   221           register_document(doc)
   222           prover.begin_document(id, path)
   223           reply(doc)
   224 
   225         case change: Change if prover != null =>
   226           handle_change(change)
   227 
   228         case result: Isabelle_Process.Result =>
   229           handle_result(result.cache(xml_cache))
   230 
   231         case TIMEOUT =>  // FIXME clarify!
   232 
   233         case bad if prover != null =>
   234           System.err.println("session_actor: ignoring bad message " + bad)
   235       }
   236     }
   237   }
   238 
   239 
   240 
   241   /** buffered command changes -- delay_first discipline **/
   242 
   243   private lazy val command_change_buffer = actor {
   244     import scala.compat.Platform.currentTime
   245 
   246     var changed: Set[Command] = Set()
   247     var flush_time: Option[Long] = None
   248 
   249     def flush_timeout: Long =
   250       flush_time match {
   251         case None => 5000L
   252         case Some(time) => (time - currentTime) max 0
   253       }
   254 
   255     def flush()
   256     {
   257       if (!changed.isEmpty) commands_changed.event(Command_Set(changed))
   258       changed = Set()
   259       flush_time = None
   260     }
   261 
   262     def invoke()
   263     {
   264       val now = currentTime
   265       flush_time match {
   266         case None => flush_time = Some(now + 100)   // FIXME output_delay property
   267         case Some(time) => if (now >= time) flush()
   268       }
   269     }
   270 
   271     loop {
   272       reactWithin(flush_timeout) {
   273         case command: Command => changed += command; invoke()
   274         case TIMEOUT => flush()
   275         case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
   276       }
   277     }
   278   }
   279 
   280   def indicate_command_change(command: Command)
   281   {
   282     command_change_buffer ! command
   283   }
   284 
   285 
   286   /* main methods */
   287 
   288   def start(timeout: Int, args: List[String]): Option[String] =
   289     (session_actor !? Start(timeout, args)).asInstanceOf[Option[String]]
   290 
   291   def stop() { session_actor ! Stop }
   292   def input(change: Change) { session_actor ! change }
   293 
   294   def begin_document(path: String): Document =
   295     (session_actor !? Begin_Document(path)).asInstanceOf[Document]
   296 }