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