src/Pure/PIDE/headless.scala
author wenzelm
Tue Sep 18 11:05:14 2018 +0200 (11 months ago ago)
changeset 69012 c91d14ab065f
parent 68987 src/Pure/Thy/thy_resources.scala@22f02724e7d1
child 69013 bb4e4c253ebe
permissions -rw-r--r--
clarified modules;
wenzelm@69012
     1
/*  Title:      Pure/PIDE/headless.scala
wenzelm@67054
     2
    Author:     Makarius
wenzelm@67054
     3
wenzelm@69012
     4
Headless PIDE session and resources from file-system.
wenzelm@67054
     5
*/
wenzelm@67054
     6
wenzelm@67054
     7
package isabelle
wenzelm@67054
     8
wenzelm@67054
     9
wenzelm@67925
    10
import java.io.{File => JFile}
wenzelm@67925
    11
wenzelm@68936
    12
import scala.annotation.tailrec
wenzelm@68936
    13
wenzelm@67925
    14
wenzelm@69012
    15
object Headless
wenzelm@67054
    16
{
wenzelm@69012
    17
  /** session **/
wenzelm@67061
    18
wenzelm@67061
    19
  def start_session(
wenzelm@67061
    20
    options: Options,
wenzelm@67061
    21
    session_name: String,
wenzelm@67061
    22
    session_dirs: List[Path] = Nil,
wenzelm@67948
    23
    include_sessions: List[String] = Nil,
wenzelm@67062
    24
    session_base: Option[Sessions.Base] = None,
wenzelm@67869
    25
    print_mode: List[String] = Nil,
wenzelm@67869
    26
    progress: Progress = No_Progress,
wenzelm@67061
    27
    log: Logger = No_Logger): Session =
wenzelm@67061
    28
  {
wenzelm@67062
    29
    val base =
wenzelm@67062
    30
      session_base getOrElse
wenzelm@67948
    31
        Sessions.base_info(options, session_name, include_sessions = include_sessions,
wenzelm@67948
    32
          progress = progress, dirs = session_dirs).check_base
wenzelm@69012
    33
    val resources = new Resources(base, log = log)
wenzelm@67945
    34
    val session = new Session(session_name, options, resources)
wenzelm@67061
    35
wenzelm@67061
    36
    val session_error = Future.promise[String]
wenzelm@67061
    37
    var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@67061
    38
    session_phase =
wenzelm@67061
    39
      Session.Consumer(getClass.getName) {
wenzelm@67061
    40
        case Session.Ready =>
wenzelm@67061
    41
          session.phase_changed -= session_phase
wenzelm@67061
    42
          session_error.fulfill("")
wenzelm@67061
    43
        case Session.Terminated(result) if !result.ok =>
wenzelm@67061
    44
          session.phase_changed -= session_phase
wenzelm@67869
    45
          session_error.fulfill("Session start failed: return code " + result.rc)
wenzelm@67061
    46
        case _ =>
wenzelm@67061
    47
      }
wenzelm@67061
    48
    session.phase_changed += session_phase
wenzelm@67061
    49
wenzelm@68987
    50
    progress.echo("Starting session " + session_name + " ...")
wenzelm@67061
    51
    Isabelle_Process.start(session, options,
wenzelm@67869
    52
      logic = session_name, dirs = session_dirs, modes = print_mode)
wenzelm@67061
    53
wenzelm@67061
    54
    session_error.join match {
wenzelm@67061
    55
      case "" => session
wenzelm@67061
    56
      case msg => session.stop(); error(msg)
wenzelm@67061
    57
    }
wenzelm@67061
    58
  }
wenzelm@67061
    59
wenzelm@68916
    60
  private def stable_snapshot(
wenzelm@68916
    61
    state: Document.State, version: Document.Version, name: Document.Node.Name): Document.Snapshot =
wenzelm@68916
    62
  {
wenzelm@68916
    63
    val snapshot = state.snapshot(name)
wenzelm@68916
    64
    assert(version.id == snapshot.version.id)
wenzelm@68916
    65
    snapshot
wenzelm@68916
    66
  }
wenzelm@68916
    67
wenzelm@69012
    68
  class Theories_Result private[Headless](
wenzelm@67883
    69
    val state: Document.State,
wenzelm@67889
    70
    val version: Document.Version,
wenzelm@68925
    71
    val nodes: List[(Document.Node.Name, Document_Status.Node_Status)],
wenzelm@68925
    72
    val nodes_committed: List[(Document.Node.Name, Document_Status.Node_Status)])
wenzelm@67879
    73
  {
wenzelm@68925
    74
    def snapshot(name: Document.Node.Name): Document.Snapshot =
wenzelm@68925
    75
      stable_snapshot(state, version, name)
wenzelm@68925
    76
wenzelm@68925
    77
    def ok: Boolean =
wenzelm@68925
    78
      (nodes.iterator ++ nodes_committed.iterator).forall({ case (_, st) => st.ok })
wenzelm@67879
    79
  }
wenzelm@67879
    80
wenzelm@68943
    81
  val default_check_delay = Time.seconds(0.5)
wenzelm@68943
    82
  val default_nodes_status_delay = Time.seconds(-1.0)
wenzelm@68982
    83
  val default_commit_cleanup_delay = Time.seconds(60.0)
wenzelm@68947
    84
  val default_watchdog_timeout = Time.seconds(600.0)
wenzelm@68694
    85
wenzelm@68694
    86
wenzelm@69012
    87
  class Session private[Headless](
wenzelm@67945
    88
    session_name: String,
wenzelm@67064
    89
    session_options: Options,
wenzelm@69012
    90
    override val resources: Resources) extends isabelle.Session(session_options, resources)
wenzelm@67063
    91
  {
wenzelm@67063
    92
    session =>
wenzelm@67063
    93
wenzelm@68922
    94
wenzelm@68922
    95
    /* temporary directory */
wenzelm@68922
    96
wenzelm@67925
    97
    val tmp_dir: JFile = Isabelle_System.tmp_dir("server_session")
wenzelm@67946
    98
    val tmp_dir_name: String = File.path(tmp_dir).implode
wenzelm@67925
    99
wenzelm@68923
   100
    def master_directory(master_dir: String): String =
wenzelm@68923
   101
      proper_string(master_dir) getOrElse tmp_dir_name
wenzelm@68923
   102
wenzelm@67945
   103
    override def toString: String = session_name
wenzelm@67945
   104
wenzelm@67925
   105
    override def stop(): Process_Result =
wenzelm@67925
   106
    {
wenzelm@67925
   107
      try { super.stop() }
wenzelm@67925
   108
      finally { Isabelle_System.rm_tree(tmp_dir) }
wenzelm@67925
   109
    }
wenzelm@67925
   110
wenzelm@67936
   111
wenzelm@67936
   112
    /* theories */
wenzelm@67936
   113
wenzelm@68914
   114
    private sealed case class Use_Theories_State(
wenzelm@68914
   115
      last_update: Time = Time.now(),
wenzelm@68914
   116
      nodes_status: Document_Status.Nodes_Status = Document_Status.Nodes_Status.empty,
wenzelm@68925
   117
      already_committed: Map[Document.Node.Name, Document_Status.Node_Status] = Map.empty,
wenzelm@68916
   118
      result: Promise[Theories_Result] = Future.promise[Theories_Result])
wenzelm@68914
   119
    {
wenzelm@68914
   120
      def update(new_nodes_status: Document_Status.Nodes_Status): Use_Theories_State =
wenzelm@68914
   121
        copy(last_update = Time.now(), nodes_status = new_nodes_status)
wenzelm@68914
   122
wenzelm@68914
   123
      def watchdog(watchdog_timeout: Time): Boolean =
wenzelm@68914
   124
        watchdog_timeout > Time.zero && Time.now() - last_update > watchdog_timeout
wenzelm@68914
   125
wenzelm@68916
   126
      def cancel_result { result.cancel }
wenzelm@68936
   127
      def finished_result: Boolean = result.is_finished
wenzelm@68916
   128
      def await_result { result.join_result }
wenzelm@68916
   129
      def join_result: Theories_Result = result.join
wenzelm@68916
   130
      def check_result(
wenzelm@68916
   131
          state: Document.State,
wenzelm@68916
   132
          version: Document.Version,
wenzelm@68925
   133
          dep_theories: List[Document.Node.Name],
wenzelm@68916
   134
          beyond_limit: Boolean,
wenzelm@68916
   135
          watchdog_timeout: Time,
wenzelm@68916
   136
          commit: Option[(Document.Snapshot, Document_Status.Node_Status) => Unit])
wenzelm@68916
   137
        : Use_Theories_State =
wenzelm@68916
   138
      {
wenzelm@68916
   139
        val st1 =
wenzelm@68916
   140
          if (commit.isDefined) {
wenzelm@68949
   141
            val already_committed1 =
wenzelm@68949
   142
              (already_committed /: dep_theories)({ case (committed, name) =>
wenzelm@68949
   143
                def parents_committed: Boolean =
wenzelm@68949
   144
                  version.nodes(name).header.imports.forall({ case (parent, _) =>
wenzelm@68949
   145
                    Sessions.is_pure(parent.theory) || committed.isDefinedAt(parent)
wenzelm@68949
   146
                  })
wenzelm@68949
   147
                if (!committed.isDefinedAt(name) && parents_committed &&
wenzelm@68949
   148
                    state.node_consolidated(version, name))
wenzelm@68949
   149
                {
wenzelm@68949
   150
                  val snapshot = stable_snapshot(state, version, name)
wenzelm@68949
   151
                  val status = Document_Status.Node_Status.make(state, version, name)
wenzelm@68949
   152
                  commit.get.apply(snapshot, status)
wenzelm@68949
   153
                  committed + (name -> status)
wenzelm@68949
   154
                }
wenzelm@68949
   155
                else committed
wenzelm@68949
   156
              })
wenzelm@68949
   157
            copy(already_committed = already_committed1)
wenzelm@68916
   158
          }
wenzelm@68916
   159
          else this
wenzelm@68916
   160
wenzelm@68916
   161
        if (beyond_limit || watchdog(watchdog_timeout) ||
wenzelm@68925
   162
          dep_theories.forall(name =>
wenzelm@68925
   163
            already_committed.isDefinedAt(name) ||
wenzelm@68916
   164
            state.node_consolidated(version, name) ||
wenzelm@68916
   165
            nodes_status.quasi_consolidated(name)))
wenzelm@68916
   166
        {
wenzelm@68916
   167
          val nodes =
wenzelm@68925
   168
            for (name <- dep_theories)
wenzelm@68916
   169
            yield { (name -> Document_Status.Node_Status.make(state, version, name)) }
wenzelm@68925
   170
          val nodes_committed =
wenzelm@68925
   171
            for {
wenzelm@68925
   172
              name <- dep_theories
wenzelm@68925
   173
              status <- already_committed.get(name)
wenzelm@68925
   174
            } yield (name -> status)
wenzelm@68925
   175
wenzelm@68925
   176
          try { result.fulfill(new Theories_Result(state, version, nodes, nodes_committed)) }
wenzelm@68916
   177
          catch { case _: IllegalStateException => }
wenzelm@68916
   178
        }
wenzelm@68916
   179
wenzelm@68916
   180
        st1
wenzelm@68916
   181
      }
wenzelm@68914
   182
    }
wenzelm@68914
   183
wenzelm@67064
   184
    def use_theories(
wenzelm@67940
   185
      theories: List[String],
wenzelm@67064
   186
      qualifier: String = Sessions.DRAFT,
wenzelm@67881
   187
      master_dir: String = "",
wenzelm@68943
   188
      check_delay: Time = default_check_delay,
wenzelm@68694
   189
      check_limit: Int = 0,
wenzelm@68947
   190
      watchdog_timeout: Time = default_watchdog_timeout,
wenzelm@68943
   191
      nodes_status_delay: Time = default_nodes_status_delay,
wenzelm@67885
   192
      id: UUID = UUID(),
wenzelm@68916
   193
      // commit: must not block, must not fail
wenzelm@68916
   194
      commit: Option[(Document.Snapshot, Document_Status.Node_Status) => Unit] = None,
wenzelm@68982
   195
      commit_cleanup_delay: Time = default_commit_cleanup_delay,
wenzelm@67881
   196
      progress: Progress = No_Progress): Theories_Result =
wenzelm@67064
   197
    {
wenzelm@67887
   198
      val dep_theories =
wenzelm@68894
   199
      {
wenzelm@68894
   200
        val import_names =
wenzelm@68923
   201
          theories.map(thy =>
wenzelm@68923
   202
            resources.import_name(qualifier, master_directory(master_dir), thy) -> Position.none)
wenzelm@68894
   203
        resources.dependencies(import_names, progress = progress).check_errors.theories
wenzelm@68894
   204
      }
wenzelm@67064
   205
wenzelm@68914
   206
      val use_theories_state = Synchronized(Use_Theories_State())
wenzelm@67064
   207
wenzelm@68916
   208
      def check_result(beyond_limit: Boolean = false)
wenzelm@67064
   209
      {
wenzelm@67064
   210
        val state = session.current_state()
wenzelm@67064
   211
        state.stable_tip_version match {
wenzelm@68694
   212
          case Some(version) =>
wenzelm@68916
   213
            use_theories_state.change(
wenzelm@68916
   214
              _.check_result(state, version, dep_theories, beyond_limit, watchdog_timeout, commit))
wenzelm@68694
   215
          case None =>
wenzelm@67064
   216
        }
wenzelm@67064
   217
      }
wenzelm@67064
   218
wenzelm@67894
   219
      val check_progress =
wenzelm@68694
   220
      {
wenzelm@68694
   221
        var check_count = 0
wenzelm@68694
   222
        Event_Timer.request(Time.now(), repeat = Some(check_delay))
wenzelm@68694
   223
          {
wenzelm@68916
   224
            if (progress.stopped) use_theories_state.value.cancel_result
wenzelm@68694
   225
            else {
wenzelm@68694
   226
              check_count += 1
wenzelm@68916
   227
              check_result(check_limit > 0 && check_count > check_limit)
wenzelm@68694
   228
            }
wenzelm@68694
   229
          }
wenzelm@68694
   230
      }
wenzelm@67894
   231
wenzelm@68907
   232
      val consumer =
wenzelm@68907
   233
      {
wenzelm@68907
   234
        val delay_nodes_status =
wenzelm@68907
   235
          Standard_Thread.delay_first(nodes_status_delay max Time.zero) {
wenzelm@68914
   236
            progress.nodes_status(use_theories_state.value.nodes_status)
wenzelm@68907
   237
          }
wenzelm@68770
   238
wenzelm@68936
   239
        val delay_commit_clean =
wenzelm@68982
   240
          Standard_Thread.delay_first(commit_cleanup_delay max Time.zero) {
wenzelm@68936
   241
            val clean = use_theories_state.value.already_committed.keySet
wenzelm@68936
   242
            resources.clean_theories(session, id, clean)
wenzelm@68936
   243
          }
wenzelm@68936
   244
wenzelm@68952
   245
        val dep_theories_set = dep_theories.toSet
wenzelm@68952
   246
wenzelm@67064
   247
        Session.Consumer[Session.Commands_Changed](getClass.getName) {
wenzelm@68331
   248
          case changed =>
wenzelm@68770
   249
            if (changed.nodes.exists(dep_theories_set)) {
wenzelm@68770
   250
              val snapshot = session.snapshot()
wenzelm@68770
   251
              val state = snapshot.state
wenzelm@68770
   252
              val version = snapshot.version
wenzelm@68770
   253
wenzelm@68957
   254
              val theory_progress =
wenzelm@68914
   255
                use_theories_state.change_result(st =>
wenzelm@68904
   256
                  {
wenzelm@68883
   257
                    val domain =
wenzelm@68914
   258
                      if (st.nodes_status.is_empty) dep_theories_set
wenzelm@68883
   259
                      else changed.nodes.iterator.filter(dep_theories_set).toSet
wenzelm@68899
   260
wenzelm@68904
   261
                    val (nodes_status_changed, nodes_status1) =
wenzelm@68914
   262
                      st.nodes_status.update(resources.session_base, state, version,
wenzelm@68904
   263
                        domain = Some(domain), trim = changed.assignment)
wenzelm@68899
   264
wenzelm@68904
   265
                    if (nodes_status_delay >= Time.zero && nodes_status_changed) {
wenzelm@68883
   266
                      delay_nodes_status.invoke
wenzelm@68899
   267
                    }
wenzelm@68883
   268
wenzelm@68957
   269
                    val theory_progress =
wenzelm@68906
   270
                      (for {
wenzelm@68905
   271
                        (name, node_status) <- nodes_status1.present.iterator
wenzelm@68959
   272
                        if changed.nodes.contains(name) && !st.already_committed.isDefinedAt(name)
wenzelm@68962
   273
                        p1 = node_status.percentage
wenzelm@68962
   274
                        if p1 > 0 && Some(p1) != st.nodes_status.get(name).map(_.percentage)
wenzelm@68962
   275
                      } yield Progress.Theory(name.theory, percentage = Some(p1))).toList
wenzelm@68904
   276
wenzelm@68957
   277
                    (theory_progress, st.update(nodes_status1))
wenzelm@68904
   278
                  })
wenzelm@68331
   279
wenzelm@68957
   280
              theory_progress.foreach(progress.theory(_))
wenzelm@68904
   281
wenzelm@68916
   282
              check_result()
wenzelm@68936
   283
wenzelm@68982
   284
              if (commit.isDefined && commit_cleanup_delay > Time.zero) {
wenzelm@68936
   285
                if (use_theories_state.value.finished_result)
wenzelm@68936
   286
                  delay_commit_clean.revoke
wenzelm@68936
   287
                else delay_commit_clean.invoke
wenzelm@68936
   288
              }
wenzelm@68331
   289
            }
wenzelm@67064
   290
        }
wenzelm@68907
   291
      }
wenzelm@67064
   292
wenzelm@67892
   293
      try {
wenzelm@67892
   294
        session.commands_changed += consumer
wenzelm@68894
   295
        resources.load_theories(session, id, dep_theories, progress)
wenzelm@68916
   296
        use_theories_state.value.await_result
wenzelm@67894
   297
        check_progress.cancel
wenzelm@67892
   298
      }
wenzelm@67892
   299
      finally {
wenzelm@68908
   300
        session.commands_changed -= consumer
wenzelm@67892
   301
        resources.unload_theories(session, id, dep_theories)
wenzelm@67892
   302
      }
wenzelm@67884
   303
wenzelm@68916
   304
      use_theories_state.value.join_result
wenzelm@67064
   305
    }
wenzelm@67936
   306
wenzelm@67939
   307
    def purge_theories(
wenzelm@68915
   308
      theories: List[String],
wenzelm@68915
   309
      qualifier: String = Sessions.DRAFT,
wenzelm@68915
   310
      master_dir: String = "",
wenzelm@68915
   311
      all: Boolean = false): (List[Document.Node.Name], List[Document.Node.Name]) =
wenzelm@68915
   312
    {
wenzelm@68923
   313
      val nodes =
wenzelm@68923
   314
        if (all) None
wenzelm@68923
   315
        else Some(theories.map(resources.import_name(qualifier, master_directory(master_dir), _)))
wenzelm@68915
   316
      resources.purge_theories(session, nodes)
wenzelm@68915
   317
    }
wenzelm@67063
   318
  }
wenzelm@67063
   319
wenzelm@67061
   320
wenzelm@67054
   321
wenzelm@69012
   322
  /** resources **/
wenzelm@68922
   323
wenzelm@69012
   324
  object Resources
wenzelm@69012
   325
  {
wenzelm@69012
   326
    final class Theory private[Headless](
wenzelm@69012
   327
      val node_name: Document.Node.Name,
wenzelm@69012
   328
      val node_header: Document.Node.Header,
wenzelm@69012
   329
      val text: String,
wenzelm@69012
   330
      val node_required: Boolean)
wenzelm@68922
   331
    {
wenzelm@69012
   332
      override def toString: String = node_name.toString
wenzelm@68922
   333
wenzelm@69012
   334
      def node_perspective: Document.Node.Perspective_Text =
wenzelm@69012
   335
        Document.Node.Perspective(node_required, Text.Perspective.empty, Document.Node.Overlays.empty)
wenzelm@68922
   336
wenzelm@69012
   337
      def make_edits(text_edits: List[Text.Edit]): List[Document.Edit_Text] =
wenzelm@69012
   338
        List(node_name -> Document.Node.Deps(node_header),
wenzelm@69012
   339
          node_name -> Document.Node.Edits(text_edits),
wenzelm@69012
   340
          node_name -> node_perspective)
wenzelm@68922
   341
wenzelm@69012
   342
      def node_edits(old: Option[Theory]): List[Document.Edit_Text] =
wenzelm@69012
   343
      {
wenzelm@69012
   344
        val (text_edits, old_required) =
wenzelm@69012
   345
          if (old.isEmpty) (Text.Edit.inserts(0, text), false)
wenzelm@69012
   346
          else (Text.Edit.replace(0, old.get.text, text), old.get.node_required)
wenzelm@67887
   347
wenzelm@69012
   348
        if (text_edits.isEmpty && node_required == old_required) Nil
wenzelm@69012
   349
        else make_edits(text_edits)
wenzelm@69012
   350
      }
wenzelm@67887
   351
wenzelm@69012
   352
      def purge_edits: List[Document.Edit_Text] =
wenzelm@69012
   353
        make_edits(Text.Edit.removes(0, text))
wenzelm@67936
   354
wenzelm@69012
   355
      def required(required: Boolean): Theory =
wenzelm@69012
   356
        if (required == node_required) this
wenzelm@69012
   357
        else new Theory(node_name, node_header, text, required)
wenzelm@67936
   358
    }
wenzelm@67936
   359
wenzelm@69012
   360
    sealed case class State(
wenzelm@69012
   361
      required: Multi_Map[Document.Node.Name, UUID] = Multi_Map.empty,
wenzelm@69012
   362
      theories: Map[Document.Node.Name, Theory] = Map.empty)
wenzelm@68936
   363
    {
wenzelm@69012
   364
      lazy val theory_graph: Graph[Document.Node.Name, Unit] =
wenzelm@68936
   365
      {
wenzelm@69012
   366
        val entries =
wenzelm@69012
   367
          for ((name, theory) <- theories.toList)
wenzelm@69012
   368
          yield ((name, ()), theory.node_header.imports.map(_._1).filter(theories.isDefinedAt(_)))
wenzelm@69012
   369
        Graph.make(entries, symmetric = true)(Document.Node.Name.Ordering)
wenzelm@67888
   370
      }
wenzelm@67056
   371
wenzelm@69012
   372
      def is_required(name: Document.Node.Name): Boolean = required.isDefinedAt(name)
wenzelm@69012
   373
wenzelm@69012
   374
      def insert_required(id: UUID, names: List[Document.Node.Name]): State =
wenzelm@69012
   375
        copy(required = (required /: names)(_.insert(_, id)))
wenzelm@69012
   376
wenzelm@69012
   377
      def remove_required(id: UUID, names: List[Document.Node.Name]): State =
wenzelm@69012
   378
        copy(required = (required /: names)(_.remove(_, id)))
wenzelm@68958
   379
wenzelm@69012
   380
      def update_theories(update: List[(Document.Node.Name, Theory)]): State =
wenzelm@69012
   381
        copy(theories =
wenzelm@69012
   382
          (theories /: update)({ case (thys, (name, thy)) =>
wenzelm@69012
   383
            thys.get(name) match {
wenzelm@69012
   384
              case Some(thy1) if thy1 == thy => thys
wenzelm@69012
   385
              case _ => thys + (name -> thy)
wenzelm@69012
   386
            }
wenzelm@69012
   387
          }))
wenzelm@69012
   388
wenzelm@69012
   389
      def remove_theories(remove: List[Document.Node.Name]): State =
wenzelm@67893
   390
      {
wenzelm@69012
   391
        require(remove.forall(name => !is_required(name)))
wenzelm@69012
   392
        copy(theories = theories -- remove)
wenzelm@69012
   393
      }
wenzelm@69012
   394
wenzelm@69012
   395
      def unload_theories(session: Session, id: UUID, dep_theories: List[Document.Node.Name]): State =
wenzelm@69012
   396
      {
wenzelm@69012
   397
        val st1 = remove_required(id, dep_theories)
wenzelm@67893
   398
        val theory_edits =
wenzelm@69012
   399
          for {
wenzelm@69012
   400
            node_name <- dep_theories
wenzelm@69012
   401
            theory <- st1.theories.get(node_name)
wenzelm@69012
   402
          }
wenzelm@67893
   403
          yield {
wenzelm@67893
   404
            val theory1 = theory.required(st1.is_required(node_name))
wenzelm@69012
   405
            val edits = theory1.node_edits(Some(theory))
wenzelm@67893
   406
            (edits, (node_name, theory1))
wenzelm@67893
   407
          }
wenzelm@67893
   408
        session.update(Document.Blobs.empty, theory_edits.flatMap(_._1))
wenzelm@67893
   409
        st1.update_theories(theory_edits.map(_._2))
wenzelm@69012
   410
      }
wenzelm@69012
   411
wenzelm@69012
   412
      def purge_theories(session: Session, nodes: List[Document.Node.Name])
wenzelm@69012
   413
        : ((List[Document.Node.Name], List[Document.Node.Name]), State) =
wenzelm@69012
   414
      {
wenzelm@69012
   415
        val all_nodes = theory_graph.topological_order
wenzelm@69012
   416
        val purge = nodes.filterNot(is_required(_)).toSet
wenzelm@69012
   417
wenzelm@69012
   418
        val retain = theory_graph.all_preds(all_nodes.filterNot(purge)).toSet
wenzelm@69012
   419
        val (retained, purged) = all_nodes.partition(retain)
wenzelm@69012
   420
wenzelm@69012
   421
        val purge_edits = purged.flatMap(name => theories(name).purge_edits)
wenzelm@69012
   422
        session.update(Document.Blobs.empty, purge_edits)
wenzelm@69012
   423
wenzelm@69012
   424
        ((purged, retained), remove_theories(purged))
wenzelm@69012
   425
      }
wenzelm@67884
   426
wenzelm@69012
   427
      def frontier_theories(clean: Set[Document.Node.Name]): Set[Document.Node.Name] =
wenzelm@69012
   428
      {
wenzelm@69012
   429
        @tailrec def frontier(base: List[Document.Node.Name], front: Set[Document.Node.Name])
wenzelm@69012
   430
          : Set[Document.Node.Name] =
wenzelm@69012
   431
        {
wenzelm@69012
   432
          val add = base.filter(b => theory_graph.imm_succs(b).forall(front))
wenzelm@69012
   433
          if (add.isEmpty) front
wenzelm@69012
   434
          else {
wenzelm@69012
   435
            val pre_add = add.map(theory_graph.imm_preds)
wenzelm@69012
   436
            val base1 = (pre_add.head /: pre_add.tail)(_ ++ _).toList.filter(clean)
wenzelm@69012
   437
            frontier(base1, front ++ add)
wenzelm@69012
   438
          }
wenzelm@69012
   439
        }
wenzelm@69012
   440
        frontier(theory_graph.maximals.filter(clean), Set.empty)
wenzelm@69012
   441
      }
wenzelm@69012
   442
    }
wenzelm@68936
   443
  }
wenzelm@68936
   444
wenzelm@69012
   445
  class Resources(session_base: Sessions.Base, log: Logger = No_Logger)
wenzelm@69012
   446
    extends isabelle.Resources(session_base, log = log)
wenzelm@67884
   447
  {
wenzelm@69012
   448
    resources =>
wenzelm@69012
   449
wenzelm@69012
   450
    private val state = Synchronized(Resources.State())
wenzelm@69012
   451
wenzelm@69012
   452
    def load_theories(
wenzelm@69012
   453
      session: Session,
wenzelm@69012
   454
      id: UUID,
wenzelm@69012
   455
      dep_theories: List[Document.Node.Name],
wenzelm@69012
   456
      progress: Progress)
wenzelm@69012
   457
    {
wenzelm@69012
   458
      val loaded_theories =
wenzelm@69012
   459
        for (node_name <- dep_theories)
wenzelm@69012
   460
        yield {
wenzelm@69012
   461
          val path = node_name.path
wenzelm@69012
   462
          if (!node_name.is_theory) error("Not a theory file: " + path)
wenzelm@69012
   463
wenzelm@69012
   464
          progress.expose_interrupt()
wenzelm@69012
   465
          val text = File.read(path)
wenzelm@69012
   466
          val node_header = resources.check_thy_reader(node_name, Scan.char_reader(text))
wenzelm@69012
   467
          new Resources.Theory(node_name, node_header, text, true)
wenzelm@68936
   468
        }
wenzelm@69012
   469
wenzelm@69012
   470
      val loaded = loaded_theories.length
wenzelm@69012
   471
      if (loaded > 1) progress.echo("Loading " + loaded + " theories ...")
wenzelm@69012
   472
wenzelm@69012
   473
      state.change(st =>
wenzelm@69012
   474
        {
wenzelm@69012
   475
          val st1 = st.insert_required(id, dep_theories)
wenzelm@69012
   476
          val theory_edits =
wenzelm@69012
   477
            for (theory <- loaded_theories)
wenzelm@69012
   478
            yield {
wenzelm@69012
   479
              val node_name = theory.node_name
wenzelm@69012
   480
              val theory1 = theory.required(st1.is_required(node_name))
wenzelm@69012
   481
              val edits = theory1.node_edits(st1.theories.get(node_name))
wenzelm@69012
   482
              (edits, (node_name, theory1))
wenzelm@69012
   483
            }
wenzelm@69012
   484
          session.update(Document.Blobs.empty, theory_edits.flatMap(_._1))
wenzelm@69012
   485
          st1.update_theories(theory_edits.map(_._2))
wenzelm@69012
   486
        })
wenzelm@69012
   487
    }
wenzelm@67936
   488
wenzelm@69012
   489
    def unload_theories(session: Session, id: UUID, dep_theories: List[Document.Node.Name])
wenzelm@69012
   490
    {
wenzelm@69012
   491
      state.change(_.unload_theories(session, id, dep_theories))
wenzelm@69012
   492
    }
wenzelm@69012
   493
wenzelm@69012
   494
    def clean_theories(session: Session, id: UUID, clean: Set[Document.Node.Name])
wenzelm@69012
   495
    {
wenzelm@69012
   496
      state.change(st =>
wenzelm@69012
   497
        {
wenzelm@69012
   498
          val frontier = st.frontier_theories(clean).toList
wenzelm@69012
   499
          if (frontier.isEmpty) st
wenzelm@69012
   500
          else {
wenzelm@69012
   501
            val st1 = st.unload_theories(session, id, frontier)
wenzelm@69012
   502
            val (_, st2) = st1.purge_theories(session, frontier)
wenzelm@69012
   503
            st2
wenzelm@69012
   504
          }
wenzelm@69012
   505
        })
wenzelm@69012
   506
    }
wenzelm@69012
   507
wenzelm@69012
   508
    def purge_theories(session: Session, nodes: Option[List[Document.Node.Name]])
wenzelm@69012
   509
      : (List[Document.Node.Name], List[Document.Node.Name]) =
wenzelm@69012
   510
    {
wenzelm@69012
   511
      state.change_result(st => st.purge_theories(session, nodes getOrElse st.theory_graph.keys))
wenzelm@69012
   512
    }
wenzelm@67936
   513
  }
wenzelm@67054
   514
}