src/Pure/Thy/thy_resources.scala
author wenzelm
Sat Mar 24 21:14:49 2018 +0100 (14 months ago)
changeset 67946 e1e57c288e45
parent 67945 984c3dc46cc0
child 67948 83902fff6243
permissions -rw-r--r--
session tmp_dir is default master_dir;
wenzelm@67054
     1
/*  Title:      Pure/Thy/thy_resources.scala
wenzelm@67054
     2
    Author:     Makarius
wenzelm@67054
     3
wenzelm@67892
     4
PIDE resources for theory files: load/unload theories via PIDE document updates.
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@67925
    12
wenzelm@67054
    13
object Thy_Resources
wenzelm@67054
    14
{
wenzelm@67061
    15
  /* PIDE session */
wenzelm@67061
    16
wenzelm@67061
    17
  def start_session(
wenzelm@67061
    18
    options: Options,
wenzelm@67061
    19
    session_name: String,
wenzelm@67061
    20
    session_dirs: List[Path] = Nil,
wenzelm@67062
    21
    session_base: Option[Sessions.Base] = None,
wenzelm@67869
    22
    print_mode: List[String] = Nil,
wenzelm@67869
    23
    progress: Progress = No_Progress,
wenzelm@67061
    24
    log: Logger = No_Logger): Session =
wenzelm@67061
    25
  {
wenzelm@67062
    26
    val base =
wenzelm@67062
    27
      session_base getOrElse
wenzelm@67852
    28
      Sessions.base_info(options, session_name, progress = progress, dirs = session_dirs).check_base
wenzelm@67062
    29
    val resources = new Thy_Resources(base, log = log)
wenzelm@67945
    30
    val session = new Session(session_name, options, resources)
wenzelm@67061
    31
wenzelm@67061
    32
    val session_error = Future.promise[String]
wenzelm@67061
    33
    var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@67061
    34
    session_phase =
wenzelm@67061
    35
      Session.Consumer(getClass.getName) {
wenzelm@67061
    36
        case Session.Ready =>
wenzelm@67061
    37
          session.phase_changed -= session_phase
wenzelm@67061
    38
          session_error.fulfill("")
wenzelm@67061
    39
        case Session.Terminated(result) if !result.ok =>
wenzelm@67061
    40
          session.phase_changed -= session_phase
wenzelm@67869
    41
          session_error.fulfill("Session start failed: return code " + result.rc)
wenzelm@67061
    42
        case _ =>
wenzelm@67061
    43
      }
wenzelm@67061
    44
    session.phase_changed += session_phase
wenzelm@67061
    45
wenzelm@67877
    46
    progress.echo("Starting " + session_name + " ...")
wenzelm@67061
    47
    Isabelle_Process.start(session, options,
wenzelm@67869
    48
      logic = session_name, dirs = session_dirs, modes = print_mode)
wenzelm@67061
    49
wenzelm@67061
    50
    session_error.join match {
wenzelm@67061
    51
      case "" => session
wenzelm@67061
    52
      case msg => session.stop(); error(msg)
wenzelm@67061
    53
    }
wenzelm@67061
    54
  }
wenzelm@67061
    55
wenzelm@67879
    56
  sealed case class Theories_Result(
wenzelm@67883
    57
    val state: Document.State,
wenzelm@67889
    58
    val version: Document.Version,
wenzelm@67889
    59
    val nodes: List[(Document.Node.Name, Protocol.Node_Status)])
wenzelm@67879
    60
  {
wenzelm@67883
    61
    def ok: Boolean = nodes.forall({ case (_, st) => st.ok })
wenzelm@67897
    62
wenzelm@67897
    63
    def messages(node_name: Document.Node.Name): List[(XML.Tree, Position.T)] =
wenzelm@67897
    64
    {
wenzelm@67897
    65
      val node = version.nodes(node_name)
wenzelm@67897
    66
      (for {
wenzelm@67897
    67
        (command, start) <-
wenzelm@67897
    68
          Document.Node.Commands.starts_pos(node.commands.iterator, Token.Pos.file(node_name.node))
wenzelm@67897
    69
        pos = command.span.keyword_pos(start).position(command.span.name)
wenzelm@67897
    70
        (_, tree) <- state.command_results(version, command).iterator
wenzelm@67897
    71
       } yield (tree, pos)).toList
wenzelm@67897
    72
    }
wenzelm@67879
    73
  }
wenzelm@67879
    74
wenzelm@67063
    75
  class Session private[Thy_Resources](
wenzelm@67945
    76
    session_name: String,
wenzelm@67064
    77
    session_options: Options,
wenzelm@67064
    78
    override val resources: Thy_Resources) extends isabelle.Session(session_options, resources)
wenzelm@67063
    79
  {
wenzelm@67063
    80
    session =>
wenzelm@67063
    81
wenzelm@67925
    82
    val tmp_dir: JFile = Isabelle_System.tmp_dir("server_session")
wenzelm@67946
    83
    val tmp_dir_name: String = File.path(tmp_dir).implode
wenzelm@67925
    84
wenzelm@67945
    85
    override def toString: String = session_name
wenzelm@67945
    86
wenzelm@67925
    87
    override def stop(): Process_Result =
wenzelm@67925
    88
    {
wenzelm@67925
    89
      try { super.stop() }
wenzelm@67925
    90
      finally { Isabelle_System.rm_tree(tmp_dir) }
wenzelm@67925
    91
    }
wenzelm@67925
    92
wenzelm@67936
    93
wenzelm@67936
    94
    /* theories */
wenzelm@67936
    95
wenzelm@67064
    96
    def use_theories(
wenzelm@67940
    97
      theories: List[String],
wenzelm@67064
    98
      qualifier: String = Sessions.DRAFT,
wenzelm@67881
    99
      master_dir: String = "",
wenzelm@67885
   100
      id: UUID = UUID(),
wenzelm@67881
   101
      progress: Progress = No_Progress): Theories_Result =
wenzelm@67064
   102
    {
wenzelm@67887
   103
      val dep_theories =
wenzelm@67884
   104
        resources.load_theories(session, id, theories, qualifier = qualifier,
wenzelm@67946
   105
          master_dir = proper_string(master_dir) getOrElse tmp_dir_name, progress = progress)
wenzelm@67064
   106
wenzelm@67879
   107
      val result = Future.promise[Theories_Result]
wenzelm@67064
   108
wenzelm@67064
   109
      def check_state
wenzelm@67064
   110
      {
wenzelm@67064
   111
        val state = session.current_state()
wenzelm@67064
   112
        state.stable_tip_version match {
wenzelm@67887
   113
          case Some(version) if dep_theories.forall(state.node_consolidated(version, _)) =>
wenzelm@67889
   114
            val nodes =
wenzelm@67889
   115
              for (name <- dep_theories)
wenzelm@67889
   116
              yield (name -> Protocol.node_status(state, version, name, version.nodes(name)))
wenzelm@67889
   117
            try { result.fulfill(Theories_Result(state, version, nodes)) }
wenzelm@67064
   118
            catch { case _: IllegalStateException => }
wenzelm@67064
   119
          case _ =>
wenzelm@67064
   120
        }
wenzelm@67064
   121
      }
wenzelm@67064
   122
wenzelm@67894
   123
      val check_progress =
wenzelm@67894
   124
        Event_Timer.request(Time.now(), repeat = Some(Time.seconds(0.5)))
wenzelm@67894
   125
          { if (progress.stopped) result.cancel else check_state }
wenzelm@67894
   126
wenzelm@67064
   127
      val consumer =
wenzelm@67064
   128
        Session.Consumer[Session.Commands_Changed](getClass.getName) {
wenzelm@67887
   129
          case changed => if (dep_theories.exists(changed.nodes)) check_state
wenzelm@67064
   130
        }
wenzelm@67064
   131
wenzelm@67892
   132
      try {
wenzelm@67892
   133
        session.commands_changed += consumer
wenzelm@67892
   134
        result.join_result
wenzelm@67894
   135
        check_progress.cancel
wenzelm@67892
   136
        session.commands_changed -= consumer
wenzelm@67892
   137
      }
wenzelm@67892
   138
      finally {
wenzelm@67892
   139
        resources.unload_theories(session, id, dep_theories)
wenzelm@67892
   140
      }
wenzelm@67884
   141
wenzelm@67879
   142
      result.join
wenzelm@67064
   143
    }
wenzelm@67936
   144
wenzelm@67939
   145
    def purge_theories(
wenzelm@67939
   146
        theories: List[String],
wenzelm@67939
   147
        qualifier: String = Sessions.DRAFT,
wenzelm@67939
   148
        master_dir: String = "",
wenzelm@67943
   149
        all: Boolean = false): (List[Document.Node.Name], List[Document.Node.Name]) =
wenzelm@67939
   150
      resources.purge_theories(session, theories = theories, qualifier = qualifier,
wenzelm@67946
   151
        master_dir = proper_string(master_dir) getOrElse tmp_dir_name, all = all)
wenzelm@67063
   152
  }
wenzelm@67063
   153
wenzelm@67061
   154
wenzelm@67054
   155
  /* internal state */
wenzelm@67054
   156
wenzelm@67884
   157
  sealed case class State(
wenzelm@67887
   158
    required: Multi_Map[Document.Node.Name, UUID] = Multi_Map.empty,
wenzelm@67887
   159
    theories: Map[Document.Node.Name, Theory] = Map.empty)
wenzelm@67884
   160
  {
wenzelm@67887
   161
    def is_required(name: Document.Node.Name): Boolean = required.isDefinedAt(name)
wenzelm@67887
   162
wenzelm@67887
   163
    def insert_required(id: UUID, names: List[Document.Node.Name]): State =
wenzelm@67887
   164
      copy(required = (required /: names)(_.insert(_, id)))
wenzelm@67887
   165
wenzelm@67887
   166
    def remove_required(id: UUID, names: List[Document.Node.Name]): State =
wenzelm@67887
   167
      copy(required = (required /: names)(_.remove(_, id)))
wenzelm@67887
   168
wenzelm@67887
   169
    def update_theories(update: List[(Document.Node.Name, Theory)]): State =
wenzelm@67887
   170
      copy(theories =
wenzelm@67887
   171
        (theories /: update)({ case (thys, (name, thy)) =>
wenzelm@67887
   172
          thys.get(name) match {
wenzelm@67887
   173
            case Some(thy1) if thy1 == thy => thys
wenzelm@67887
   174
            case _ => thys + (name -> thy)
wenzelm@67887
   175
          }
wenzelm@67887
   176
        }))
wenzelm@67936
   177
wenzelm@67936
   178
    def remove_theories(remove: List[Document.Node.Name]): State =
wenzelm@67936
   179
    {
wenzelm@67936
   180
      require(remove.forall(name => !is_required(name)))
wenzelm@67936
   181
      copy(theories = theories -- remove)
wenzelm@67936
   182
    }
wenzelm@67936
   183
wenzelm@67936
   184
    lazy val theories_graph: Graph[Document.Node.Name, Unit] =
wenzelm@67936
   185
    {
wenzelm@67936
   186
      val entries =
wenzelm@67936
   187
        for ((name, theory) <- theories.toList)
wenzelm@67936
   188
        yield ((name, ()), theory.node_header.imports.map(_._1).filter(theories.isDefinedAt(_)))
wenzelm@67936
   189
      Graph.make(entries, symmetric = true)(Document.Node.Name.Ordering)
wenzelm@67936
   190
    }
wenzelm@67884
   191
  }
wenzelm@67058
   192
wenzelm@67058
   193
  final class Theory private[Thy_Resources](
wenzelm@67058
   194
    val node_name: Document.Node.Name,
wenzelm@67058
   195
    val node_header: Document.Node.Header,
wenzelm@67884
   196
    val text: String,
wenzelm@67884
   197
    val node_required: Boolean)
wenzelm@67056
   198
  {
wenzelm@67058
   199
    override def toString: String = node_name.toString
wenzelm@67058
   200
wenzelm@67058
   201
    def node_perspective: Document.Node.Perspective_Text =
wenzelm@67884
   202
      Document.Node.Perspective(node_required, Text.Perspective.empty, Document.Node.Overlays.empty)
wenzelm@67058
   203
wenzelm@67936
   204
    def make_edits(text_edits: List[Text.Edit]): List[Document.Edit_Text] =
wenzelm@67936
   205
      List(node_name -> Document.Node.Deps(node_header),
wenzelm@67936
   206
        node_name -> Document.Node.Edits(text_edits),
wenzelm@67936
   207
        node_name -> node_perspective)
wenzelm@67936
   208
wenzelm@67058
   209
    def node_edits(old: Option[Theory]): List[Document.Edit_Text] =
wenzelm@67058
   210
    {
wenzelm@67884
   211
      val (text_edits, old_required) =
wenzelm@67884
   212
        if (old.isEmpty) (Text.Edit.inserts(0, text), false)
wenzelm@67884
   213
        else (Text.Edit.replace(0, old.get.text, text), old.get.node_required)
wenzelm@67058
   214
wenzelm@67884
   215
      if (text_edits.isEmpty && node_required == old_required) Nil
wenzelm@67936
   216
      else make_edits(text_edits)
wenzelm@67058
   217
    }
wenzelm@67884
   218
wenzelm@67936
   219
    def purge_edits: List[Document.Edit_Text] =
wenzelm@67936
   220
      make_edits(Text.Edit.removes(0, text))
wenzelm@67936
   221
wenzelm@67887
   222
    def required(required: Boolean): Theory =
wenzelm@67887
   223
      if (required == node_required) this
wenzelm@67887
   224
      else new Theory(node_name, node_header, text, required)
wenzelm@67056
   225
  }
wenzelm@67054
   226
}
wenzelm@67054
   227
wenzelm@67056
   228
class Thy_Resources(session_base: Sessions.Base, log: Logger = No_Logger)
wenzelm@67054
   229
  extends Resources(session_base, log = log)
wenzelm@67054
   230
{
wenzelm@67056
   231
  resources =>
wenzelm@67056
   232
wenzelm@67054
   233
  private val state = Synchronized(Thy_Resources.State())
wenzelm@67056
   234
wenzelm@67056
   235
  def load_theories(
wenzelm@67056
   236
    session: Session,
wenzelm@67885
   237
    id: UUID,
wenzelm@67940
   238
    theories: List[String],
wenzelm@67946
   239
    qualifier: String,
wenzelm@67946
   240
    master_dir: String,
wenzelm@67946
   241
    progress: Progress): List[Document.Node.Name] =
wenzelm@67056
   242
  {
wenzelm@67940
   243
    val import_names = theories.map(thy => import_name(qualifier, master_dir, thy) -> Position.none)
wenzelm@67881
   244
    val dependencies = resources.dependencies(import_names, progress = progress).check_errors
wenzelm@67887
   245
    val dep_theories = dependencies.theories
wenzelm@67888
   246
wenzelm@67888
   247
    val loaded_theories =
wenzelm@67888
   248
      for (node_name <- dep_theories)
wenzelm@67888
   249
      yield {
wenzelm@67888
   250
        val path = node_name.path
wenzelm@67888
   251
        if (!node_name.is_theory) error("Not a theory file: " + path)
wenzelm@67888
   252
wenzelm@67888
   253
        progress.expose_interrupt()
wenzelm@67888
   254
        val text = File.read(path)
wenzelm@67888
   255
        val node_header = resources.check_thy_reader(node_name, Scan.char_reader(text))
wenzelm@67888
   256
        new Thy_Resources.Theory(node_name, node_header, text, true)
wenzelm@67888
   257
      }
wenzelm@67056
   258
wenzelm@67893
   259
    state.change(st =>
wenzelm@67893
   260
      {
wenzelm@67893
   261
        val st1 = st.insert_required(id, dep_theories)
wenzelm@67893
   262
        val theory_edits =
wenzelm@67893
   263
          for (theory <- loaded_theories)
wenzelm@67893
   264
          yield {
wenzelm@67893
   265
            val node_name = theory.node_name
wenzelm@67893
   266
            val theory1 = theory.required(st1.is_required(node_name))
wenzelm@67893
   267
            val edits = theory1.node_edits(st1.theories.get(node_name))
wenzelm@67893
   268
            (edits, (node_name, theory1))
wenzelm@67893
   269
          }
wenzelm@67893
   270
        session.update(Document.Blobs.empty, theory_edits.flatMap(_._1))
wenzelm@67893
   271
        st1.update_theories(theory_edits.map(_._2))
wenzelm@67893
   272
      })
wenzelm@67056
   273
wenzelm@67887
   274
    dep_theories
wenzelm@67056
   275
  }
wenzelm@67884
   276
wenzelm@67887
   277
  def unload_theories(session: Session, id: UUID, dep_theories: List[Document.Node.Name])
wenzelm@67884
   278
  {
wenzelm@67893
   279
    state.change(st =>
wenzelm@67893
   280
      {
wenzelm@67893
   281
        val st1 = st.remove_required(id, dep_theories)
wenzelm@67893
   282
        val theory_edits =
wenzelm@67893
   283
          for {
wenzelm@67893
   284
            node_name <- dep_theories
wenzelm@67893
   285
            theory <- st1.theories.get(node_name)
wenzelm@67893
   286
          }
wenzelm@67893
   287
          yield {
wenzelm@67893
   288
            val theory1 = theory.required(st1.is_required(node_name))
wenzelm@67893
   289
            val edits = theory1.node_edits(Some(theory))
wenzelm@67893
   290
            (edits, (node_name, theory1))
wenzelm@67893
   291
          }
wenzelm@67893
   292
        session.update(Document.Blobs.empty, theory_edits.flatMap(_._1))
wenzelm@67893
   293
        st1.update_theories(theory_edits.map(_._2))
wenzelm@67893
   294
      })
wenzelm@67884
   295
  }
wenzelm@67936
   296
wenzelm@67939
   297
  def purge_theories(session: Session,
wenzelm@67939
   298
    theories: List[String],
wenzelm@67946
   299
    qualifier: String,
wenzelm@67946
   300
    master_dir: String,
wenzelm@67946
   301
    all: Boolean): (List[Document.Node.Name], List[Document.Node.Name]) =
wenzelm@67936
   302
  {
wenzelm@67939
   303
    val nodes = theories.map(import_name(qualifier, master_dir, _))
wenzelm@67939
   304
wenzelm@67936
   305
    state.change_result(st =>
wenzelm@67936
   306
      {
wenzelm@67936
   307
        val graph = st.theories_graph
wenzelm@67936
   308
        val all_nodes = graph.topological_order
wenzelm@67936
   309
wenzelm@67936
   310
        val purge =
wenzelm@67939
   311
          (if (all) all_nodes else nodes.filter(graph.defined(_))).
wenzelm@67936
   312
            filterNot(st.is_required(_)).toSet
wenzelm@67943
   313
wenzelm@67943
   314
        val retain = graph.all_preds(all_nodes.filterNot(purge)).toSet
wenzelm@67943
   315
        val (retained, purged) = all_nodes.partition(retain)
wenzelm@67936
   316
wenzelm@67936
   317
        val purge_edits = purged.flatMap(name => st.theories(name).purge_edits)
wenzelm@67936
   318
        session.update(Document.Blobs.empty, purge_edits)
wenzelm@67936
   319
wenzelm@67943
   320
        ((purged, retained), st.remove_theories(purged))
wenzelm@67936
   321
      })
wenzelm@67936
   322
  }
wenzelm@67054
   323
}