src/Pure/Thy/sessions.scala
author wenzelm
Wed Jan 16 17:55:26 2019 +0100 (10 months ago)
changeset 69671 2486792eaf61
parent 69560 195371990820
child 69762 58fb0d779583
permissions -rw-r--r--
support pruning of export names;
wenzelm@62631
     1
/*  Title:      Pure/Thy/sessions.scala
wenzelm@62631
     2
    Author:     Makarius
wenzelm@62631
     3
wenzelm@65430
     4
Cumulative session information.
wenzelm@62631
     5
*/
wenzelm@62631
     6
wenzelm@62631
     7
package isabelle
wenzelm@62631
     8
wenzelm@65461
     9
import java.io.{File => JFile}
wenzelm@62704
    10
import java.nio.ByteBuffer
wenzelm@62704
    11
import java.nio.channels.FileChannel
wenzelm@62704
    12
import java.nio.file.StandardOpenOption
wenzelm@62631
    13
wenzelm@62631
    14
import scala.collection.SortedSet
wenzelm@62631
    15
import scala.collection.mutable
wenzelm@62631
    16
wenzelm@62631
    17
wenzelm@62631
    18
object Sessions
wenzelm@62631
    19
{
wenzelm@67284
    20
  /* session and theory names */
wenzelm@62883
    21
wenzelm@67215
    22
  val root_name: String = "ROOT"
wenzelm@67215
    23
  val theory_name: String = "Pure.Sessions"
wenzelm@67215
    24
wenzelm@65445
    25
  val DRAFT = "Draft"
wenzelm@65445
    26
wenzelm@65360
    27
  def is_pure(name: String): Boolean = name == Thy_Header.PURE
wenzelm@64856
    28
wenzelm@67284
    29
wenzelm@67284
    30
  def exclude_session(name: String): Boolean = name == "" || name == DRAFT
wenzelm@67284
    31
wenzelm@67286
    32
  def exclude_theory(name: String): Boolean =
wenzelm@67290
    33
    name == root_name || name == "README" || name == "index" || name == "bib"
wenzelm@67284
    34
wenzelm@67284
    35
wenzelm@67284
    36
  /* base info and source dependencies */
wenzelm@67284
    37
wenzelm@65495
    38
  object Known
wenzelm@64856
    39
  {
wenzelm@65495
    40
    val empty: Known = Known()
wenzelm@65360
    41
wenzelm@66701
    42
    def make(local_dir: Path, bases: List[Base],
wenzelm@67493
    43
      sessions: List[(String, Position.T)] = Nil,
wenzelm@68306
    44
      theories: List[Document.Node.Entry] = Nil,
wenzelm@66701
    45
      loaded_files: List[(String, List[Path])] = Nil): Known =
wenzelm@65427
    46
    {
wenzelm@65463
    47
      def bases_iterator(local: Boolean) =
wenzelm@65463
    48
        for {
wenzelm@65463
    49
          base <- bases.iterator
wenzelm@68306
    50
          (_, entry) <- (if (local) base.known.theories_local else base.known.theories).iterator
wenzelm@68306
    51
        } yield entry
wenzelm@65463
    52
wenzelm@65463
    53
      def local_theories_iterator =
wenzelm@65463
    54
      {
wenzelm@65833
    55
        val local_path = local_dir.canonical_file.toPath
wenzelm@68306
    56
        theories.iterator.filter(entry =>
wenzelm@68306
    57
          entry.name.path.canonical_file.toPath.startsWith(local_path))
wenzelm@65463
    58
      }
wenzelm@65427
    59
wenzelm@67219
    60
      val known_sessions =
wenzelm@67493
    61
        (sessions.toMap /: bases)({ case (known, base) => known ++ base.known.sessions })
wenzelm@67219
    62
wenzelm@65461
    63
      val known_theories =
wenzelm@68306
    64
        (Map.empty[String, Document.Node.Entry] /: (bases_iterator(false) ++ theories.iterator))({
wenzelm@68306
    65
          case (known, entry) =>
wenzelm@68306
    66
            known.get(entry.name.theory) match {
wenzelm@68306
    67
              case Some(entry1) if entry.name != entry1.name =>
wenzelm@68306
    68
                error("Duplicate theory " + quote(entry.name.node) + " vs. " +
wenzelm@68306
    69
                  quote(entry1.name.node))
wenzelm@68306
    70
              case _ => known + (entry.name.theory -> entry)
wenzelm@65461
    71
            }
wenzelm@65461
    72
          })
wenzelm@65463
    73
      val known_theories_local =
wenzelm@68306
    74
        (Map.empty[String, Document.Node.Entry] /:
wenzelm@65463
    75
            (bases_iterator(true) ++ local_theories_iterator))({
wenzelm@68306
    76
          case (known, entry) => known + (entry.name.theory -> entry)
wenzelm@65463
    77
        })
wenzelm@65461
    78
      val known_files =
wenzelm@65463
    79
        (Map.empty[JFile, List[Document.Node.Name]] /:
wenzelm@65463
    80
            (bases_iterator(true) ++ bases_iterator(false) ++ theories.iterator))({
wenzelm@68306
    81
          case (known, entry) =>
wenzelm@68306
    82
            val name = entry.name
wenzelm@66716
    83
            val file = name.path.canonical_file
wenzelm@65463
    84
            val theories1 = known.getOrElse(file, Nil)
wenzelm@65463
    85
            if (theories1.exists(name1 => name.node == name1.node && name.theory == name1.theory))
wenzelm@65461
    86
              known
wenzelm@65463
    87
            else known + (file -> (name :: theories1))
wenzelm@65427
    88
        })
wenzelm@66701
    89
wenzelm@66701
    90
      val known_loaded_files =
wenzelm@66701
    91
        (loaded_files.toMap /: bases.map(base => base.known.loaded_files))(_ ++ _)
wenzelm@66701
    92
wenzelm@67219
    93
      Known(
wenzelm@67219
    94
        known_sessions,
wenzelm@68306
    95
        known_theories,
wenzelm@68306
    96
        known_theories_local,
wenzelm@66701
    97
        known_files.iterator.map(p => (p._1, p._2.reverse)).toMap,
wenzelm@66701
    98
        known_loaded_files)
wenzelm@65427
    99
    }
wenzelm@64856
   100
  }
wenzelm@64856
   101
wenzelm@65495
   102
  sealed case class Known(
wenzelm@67493
   103
    sessions: Map[String, Position.T] = Map.empty,
wenzelm@68306
   104
    theories: Map[String, Document.Node.Entry] = Map.empty,
wenzelm@68306
   105
    theories_local: Map[String, Document.Node.Entry] = Map.empty,
wenzelm@66701
   106
    files: Map[JFile, List[Document.Node.Name]] = Map.empty,
wenzelm@66701
   107
    loaded_files: Map[String, List[Path]] = Map.empty)
wenzelm@65355
   108
  {
wenzelm@65495
   109
    def platform_path: Known =
wenzelm@65499
   110
      copy(theories = for ((a, b) <- theories) yield (a, b.map(File.platform_path(_))),
wenzelm@65499
   111
        theories_local = for ((a, b) <- theories_local) yield (a, b.map(File.platform_path(_))),
wenzelm@65499
   112
        files = for ((a, b) <- files) yield (a, b.map(c => c.map(File.platform_path(_)))))
wenzelm@65524
   113
wenzelm@66668
   114
    def standard_path: Known =
wenzelm@66668
   115
      copy(theories = for ((a, b) <- theories) yield (a, b.map(File.standard_path(_))),
wenzelm@66668
   116
        theories_local = for ((a, b) <- theories_local) yield (a, b.map(File.standard_path(_))),
wenzelm@66668
   117
        files = for ((a, b) <- files) yield (a, b.map(c => c.map(File.standard_path(_)))))
wenzelm@66668
   118
wenzelm@68306
   119
    def theory_names: List[Document.Node.Name] = theories.iterator.map(p => p._2.name).toList
wenzelm@68306
   120
wenzelm@68306
   121
    lazy val theory_graph: Graph[Document.Node.Name, Unit] =
wenzelm@68306
   122
    {
wenzelm@68307
   123
      val entries =
wenzelm@68307
   124
        for ((_, entry) <- theories.toList)
wenzelm@68307
   125
        yield ((entry.name, ()), entry.header.imports.map(imp => theories(imp._1.theory).name))
wenzelm@68307
   126
      Graph.make(entries, symmetric = true)(Document.Node.Name.Ordering)
wenzelm@68306
   127
    }
wenzelm@68306
   128
wenzelm@66195
   129
    def get_file(file: JFile, bootstrap: Boolean = false): Option[Document.Node.Name] =
wenzelm@66195
   130
    {
wenzelm@66234
   131
      val res = files.getOrElse(File.canonical(file), Nil).headOption
wenzelm@66195
   132
      if (bootstrap) res.map(_.map_theory(Thy_Header.bootstrap_name(_))) else res
wenzelm@66195
   133
    }
wenzelm@65495
   134
  }
wenzelm@65495
   135
wenzelm@65495
   136
  object Base
wenzelm@65495
   137
  {
wenzelm@65495
   138
    def bootstrap(global_theories: Map[String, String]): Base =
wenzelm@65495
   139
      Base(
wenzelm@65495
   140
        global_theories = global_theories,
wenzelm@66720
   141
        overall_syntax = Thy_Header.bootstrap_syntax)
wenzelm@65495
   142
  }
wenzelm@65495
   143
wenzelm@65495
   144
  sealed case class Base(
wenzelm@66571
   145
    pos: Position.T = Position.none,
wenzelm@67471
   146
    doc_names: List[String] = Nil,
wenzelm@65495
   147
    global_theories: Map[String, String] = Map.empty,
wenzelm@66717
   148
    loaded_theories: Graph[String, Outer_Syntax] = Graph.string,
wenzelm@69008
   149
    used_theories: List[(Options, Document.Node.Name)] = Nil,
wenzelm@65495
   150
    known: Known = Known.empty,
wenzelm@66720
   151
    overall_syntax: Outer_Syntax = Outer_Syntax.empty,
wenzelm@66744
   152
    imported_sources: List[(Path, SHA1.Digest)] = Nil,
wenzelm@65495
   153
    sources: List[(Path, SHA1.Digest)] = Nil,
wenzelm@66822
   154
    session_graph_display: Graph_Display.Graph = Graph_Display.empty_graph,
wenzelm@66694
   155
    errors: List[String] = Nil,
wenzelm@66694
   156
    imports: Option[Base] = None)
wenzelm@65495
   157
  {
wenzelm@69102
   158
    override def toString: String =
wenzelm@69102
   159
      "Sessions.Base(loaded_theories = " + loaded_theories.size +
wenzelm@69102
   160
        ", used_theories = " + used_theories.length + ")"
wenzelm@69102
   161
wenzelm@65495
   162
    def platform_path: Base = copy(known = known.platform_path)
wenzelm@66668
   163
    def standard_path: Base = copy(known = known.standard_path)
wenzelm@65463
   164
wenzelm@66967
   165
    def theory_qualifier(name: String): String =
wenzelm@66967
   166
      global_theories.getOrElse(name, Long_Name.qualifier(name))
wenzelm@66967
   167
    def theory_qualifier(name: Document.Node.Name): String = theory_qualifier(name.theory)
wenzelm@66966
   168
wenzelm@66717
   169
    def loaded_theory(name: String): Boolean = loaded_theories.defined(name)
wenzelm@66712
   170
    def loaded_theory(name: Document.Node.Name): Boolean = loaded_theory(name.theory)
wenzelm@65432
   171
wenzelm@66717
   172
    def loaded_theory_syntax(name: String): Option[Outer_Syntax] =
wenzelm@66717
   173
      if (loaded_theory(name)) Some(loaded_theories.get_node(name)) else None
wenzelm@66717
   174
    def loaded_theory_syntax(name: Document.Node.Name): Option[Outer_Syntax] =
wenzelm@66717
   175
      loaded_theory_syntax(name.theory)
wenzelm@66717
   176
wenzelm@66770
   177
    def node_syntax(nodes: Document.Nodes, name: Document.Node.Name): Outer_Syntax =
wenzelm@66770
   178
      nodes(name).syntax orElse loaded_theory_syntax(name) getOrElse overall_syntax
wenzelm@66721
   179
wenzelm@65498
   180
    def known_theory(name: String): Option[Document.Node.Name] =
wenzelm@68306
   181
      known.theories.get(name).map(_.name)
wenzelm@65498
   182
wenzelm@65432
   183
    def dest_known_theories: List[(String, String)] =
wenzelm@68306
   184
      for ((theory, entry) <- known.theories.toList)
wenzelm@68306
   185
        yield (theory, entry.name.node)
wenzelm@66694
   186
wenzelm@66694
   187
    def get_imports: Base = imports getOrElse Base.bootstrap(global_theories)
wenzelm@65355
   188
  }
wenzelm@64856
   189
wenzelm@68204
   190
  sealed case class Deps(
wenzelm@68204
   191
    sessions_structure: Structure, session_bases: Map[String, Base], all_known: Known)
wenzelm@65251
   192
  {
wenzelm@69102
   193
    override def toString: String = "Sessions.Deps(" + sessions_structure + ")"
wenzelm@69102
   194
wenzelm@65463
   195
    def is_empty: Boolean = session_bases.isEmpty
wenzelm@65463
   196
    def apply(name: String): Base = session_bases(name)
wenzelm@66988
   197
    def get(name: String): Option[Base] = session_bases.get(name)
wenzelm@66744
   198
wenzelm@66744
   199
    def imported_sources(name: String): List[SHA1.Digest] =
wenzelm@66744
   200
      session_bases(name).imported_sources.map(_._2)
wenzelm@66744
   201
wenzelm@69026
   202
    def used_theories_condition(default_options: Options, warning: String => Unit = _ => ())
wenzelm@69025
   203
      : List[(Options, Document.Node.Name)] =
wenzelm@69025
   204
    {
wenzelm@69026
   205
      val default_skip_proofs = default_options.bool("skip_proofs")
wenzelm@69008
   206
      for {
wenzelm@69008
   207
        session_name <- sessions_structure.build_topological_order
wenzelm@69008
   208
        (options, name) <- session_bases(session_name).used_theories
wenzelm@69008
   209
        if {
wenzelm@69026
   210
          def warn(msg: String): Unit = warning("Skipping theory " + name + "  (" + msg + ")")
wenzelm@69026
   211
wenzelm@69008
   212
          val conditions =
wenzelm@69008
   213
            space_explode(',', options.string("condition")).
wenzelm@69008
   214
              filter(cond => Isabelle_System.getenv(cond) == "")
wenzelm@69026
   215
          if (conditions.nonEmpty) {
wenzelm@69080
   216
            warn("undefined " + conditions.mkString(", "))
wenzelm@69008
   217
            false
wenzelm@69008
   218
          }
wenzelm@69026
   219
          else if (default_skip_proofs && !options.bool("skip_proofs")) {
wenzelm@69026
   220
            warn("option skip_proofs")
wenzelm@69026
   221
            false
wenzelm@69026
   222
          }
wenzelm@69026
   223
          else true
wenzelm@69008
   224
        }
wenzelm@69025
   225
      } yield (options, name)
wenzelm@69025
   226
    }
wenzelm@69008
   227
wenzelm@66744
   228
    def sources(name: String): List[SHA1.Digest] =
wenzelm@66744
   229
      session_bases(name).sources.map(_._2)
wenzelm@66571
   230
wenzelm@66571
   231
    def errors: List[String] =
wenzelm@66571
   232
      (for {
wenzelm@66571
   233
        (name, base) <- session_bases.iterator
wenzelm@66571
   234
        if base.errors.nonEmpty
wenzelm@66571
   235
      } yield cat_lines(base.errors) +
wenzelm@66571
   236
          "\nThe error(s) above occurred in session " + quote(name) + Position.here(base.pos)
wenzelm@66571
   237
      ).toList
wenzelm@66571
   238
wenzelm@66571
   239
    def check_errors: Deps =
wenzelm@66571
   240
      errors match {
wenzelm@66571
   241
        case Nil => this
wenzelm@66571
   242
        case errs => error(cat_lines(errs))
wenzelm@66571
   243
      }
wenzelm@65251
   244
  }
wenzelm@64856
   245
wenzelm@67052
   246
  def deps(sessions_structure: Structure,
wenzelm@66962
   247
      global_theories: Map[String, String],
wenzelm@65251
   248
      progress: Progress = No_Progress,
wenzelm@65251
   249
      inlined_files: Boolean = false,
wenzelm@65251
   250
      verbose: Boolean = false,
wenzelm@65251
   251
      list_files: Boolean = false,
wenzelm@66962
   252
      check_keywords: Set[String] = Set.empty): Deps =
wenzelm@65372
   253
  {
wenzelm@66743
   254
    var cache_sources = Map.empty[JFile, SHA1.Digest]
wenzelm@66743
   255
    def check_sources(paths: List[Path]): List[(Path, SHA1.Digest)] =
wenzelm@66743
   256
    {
wenzelm@66743
   257
      for {
wenzelm@66743
   258
        path <- paths
wenzelm@66743
   259
        file = path.file
wenzelm@66743
   260
        if cache_sources.isDefinedAt(file) || file.isFile
wenzelm@66743
   261
      }
wenzelm@66743
   262
      yield {
wenzelm@66743
   263
        cache_sources.get(file) match {
wenzelm@66743
   264
          case Some(digest) => (path, digest)
wenzelm@66743
   265
          case None =>
wenzelm@66743
   266
            val digest = SHA1.digest(file)
wenzelm@66743
   267
            cache_sources = cache_sources + (file -> digest)
wenzelm@66743
   268
            (path, digest)
wenzelm@66743
   269
        }
wenzelm@66743
   270
      }
wenzelm@66743
   271
    }
wenzelm@66743
   272
wenzelm@67471
   273
    val doc_names = Doc.doc_names()
wenzelm@67471
   274
wenzelm@65463
   275
    val session_bases =
wenzelm@67024
   276
      (Map.empty[String, Base] /: sessions_structure.imports_topological_order)({
wenzelm@67023
   277
        case (session_bases, session_name) =>
wenzelm@67880
   278
          progress.expose_interrupt()
wenzelm@65251
   279
wenzelm@67024
   280
          val info = sessions_structure(session_name)
wenzelm@65463
   281
          try {
wenzelm@65496
   282
            val parent_base: Sessions.Base =
wenzelm@65463
   283
              info.parent match {
wenzelm@65475
   284
                case None => Base.bootstrap(global_theories)
wenzelm@65463
   285
                case Some(parent) => session_bases(parent)
wenzelm@65463
   286
              }
wenzelm@65496
   287
            val imports_base: Sessions.Base =
wenzelm@65496
   288
              parent_base.copy(known =
wenzelm@66701
   289
                Known.make(info.dir, parent_base :: info.imports.map(session_bases(_))))
wenzelm@65496
   290
wenzelm@65532
   291
            val resources = new Resources(imports_base)
wenzelm@65251
   292
wenzelm@65463
   293
            if (verbose || list_files) {
wenzelm@65463
   294
              val groups =
wenzelm@65463
   295
                if (info.groups.isEmpty) ""
wenzelm@65463
   296
                else info.groups.mkString(" (", " ", ")")
wenzelm@65519
   297
              progress.echo("Session " + info.chapter + "/" + info.name + groups)
wenzelm@65463
   298
            }
wenzelm@65251
   299
wenzelm@69008
   300
            val dependencies = resources.session_dependencies(info)
wenzelm@65251
   301
wenzelm@67053
   302
            val overall_syntax = dependencies.overall_syntax
wenzelm@65251
   303
wenzelm@67059
   304
            val theory_files = dependencies.theories.map(_.path)
wenzelm@65463
   305
            val loaded_files =
wenzelm@69560
   306
              if (inlined_files) dependencies.loaded_files(Sessions.is_pure(info.name))
wenzelm@65463
   307
              else Nil
wenzelm@65251
   308
wenzelm@66742
   309
            val session_files =
wenzelm@66701
   310
              (theory_files ::: loaded_files.flatMap(_._2) :::
wenzelm@65463
   311
                info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
wenzelm@65463
   312
wenzelm@67053
   313
            val imported_files = if (inlined_files) dependencies.imported_files else Nil
wenzelm@66743
   314
wenzelm@65463
   315
            if (list_files)
wenzelm@66742
   316
              progress.echo(cat_lines(session_files.map(_.implode).sorted.map("  " + _)))
wenzelm@65463
   317
wenzelm@66719
   318
            if (check_keywords.nonEmpty) {
wenzelm@66719
   319
              Check_Keywords.check_keywords(
wenzelm@66720
   320
                progress, overall_syntax.keywords, check_keywords, theory_files)
wenzelm@66719
   321
            }
wenzelm@65251
   322
wenzelm@66822
   323
            val session_graph_display: Graph_Display.Graph =
wenzelm@65507
   324
            {
wenzelm@65507
   325
              def session_node(name: String): Graph_Display.Node =
wenzelm@65507
   326
                Graph_Display.Node("[" + name + "]", "session." + name)
wenzelm@65507
   327
wenzelm@65507
   328
              def node(name: Document.Node.Name): Graph_Display.Node =
wenzelm@65507
   329
              {
wenzelm@66966
   330
                val qualifier = imports_base.theory_qualifier(name)
wenzelm@66780
   331
                if (qualifier == info.name)
wenzelm@65507
   332
                  Graph_Display.Node(name.theory_base_name, "theory." + name.theory)
wenzelm@65528
   333
                else session_node(qualifier)
wenzelm@65507
   334
              }
wenzelm@65507
   335
wenzelm@65507
   336
              val imports_subgraph =
wenzelm@67024
   337
                sessions_structure.imports_graph.
wenzelm@67024
   338
                  restrict(sessions_structure.imports_graph.all_preds(info.deps).toSet)
wenzelm@65507
   339
wenzelm@65507
   340
              val graph0 =
wenzelm@65507
   341
                (Graph_Display.empty_graph /: imports_subgraph.topological_order)(
wenzelm@65507
   342
                  { case (g, session) =>
wenzelm@65507
   343
                      val a = session_node(session)
wenzelm@65507
   344
                      val bs = imports_subgraph.imm_preds(session).toList.map(session_node(_))
wenzelm@65507
   345
                      ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
wenzelm@65507
   346
wenzelm@67053
   347
              (graph0 /: dependencies.entries)(
wenzelm@66714
   348
                { case (g, entry) =>
wenzelm@66714
   349
                    val a = node(entry.name)
wenzelm@65507
   350
                    val bs =
wenzelm@66714
   351
                      entry.header.imports.map({ case (name, _) => node(name) }).
wenzelm@65507
   352
                        filterNot(_ == a)
wenzelm@65507
   353
                    ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
wenzelm@65507
   354
            }
wenzelm@65507
   355
wenzelm@66701
   356
            val known =
wenzelm@66701
   357
              Known.make(info.dir, List(imports_base),
wenzelm@67493
   358
                sessions = List(info.name -> info.pos),
wenzelm@68306
   359
                theories = dependencies.entries,
wenzelm@66701
   360
                loaded_files = loaded_files)
wenzelm@66701
   361
wenzelm@66743
   362
            val sources_errors =
wenzelm@66743
   363
              for (p <- session_files if !p.is_file) yield "No such file: " + p
wenzelm@66604
   364
wenzelm@67297
   365
            val bibtex_errors =
wenzelm@67297
   366
              try { info.bibtex_entries; Nil }
wenzelm@67297
   367
              catch { case ERROR(msg) => List(msg) }
wenzelm@67297
   368
wenzelm@65463
   369
            val base =
wenzelm@66571
   370
              Base(
wenzelm@66571
   371
                pos = info.pos,
wenzelm@67471
   372
                doc_names = doc_names,
wenzelm@65540
   373
                global_theories = global_theories,
wenzelm@67053
   374
                loaded_theories = dependencies.loaded_theories,
wenzelm@69008
   375
                used_theories = dependencies.adjunct_theories,
wenzelm@66701
   376
                known = known,
wenzelm@66720
   377
                overall_syntax = overall_syntax,
wenzelm@66744
   378
                imported_sources = check_sources(imported_files),
wenzelm@66743
   379
                sources = check_sources(session_files),
wenzelm@66822
   380
                session_graph_display = session_graph_display,
wenzelm@67297
   381
                errors = dependencies.errors ::: sources_errors ::: bibtex_errors,
wenzelm@66694
   382
                imports = Some(imports_base))
wenzelm@65251
   383
wenzelm@65519
   384
            session_bases + (info.name -> base)
wenzelm@65463
   385
          }
wenzelm@65463
   386
          catch {
wenzelm@65463
   387
            case ERROR(msg) =>
wenzelm@65463
   388
              cat_error(msg, "The error(s) above occurred in session " +
wenzelm@65519
   389
                quote(info.name) + Position.here(info.pos))
wenzelm@65463
   390
          }
wenzelm@65463
   391
      })
wenzelm@65251
   392
wenzelm@68307
   393
    val all_known =
wenzelm@68307
   394
      Known.make(Path.current, sessions_structure.imports_topological_order.map(session_bases(_)))
wenzelm@68307
   395
wenzelm@68307
   396
    Deps(sessions_structure, session_bases, all_known)
wenzelm@65372
   397
  }
wenzelm@65251
   398
wenzelm@66963
   399
wenzelm@66963
   400
  /* base info */
wenzelm@66963
   401
wenzelm@66974
   402
  sealed case class Base_Info(
wenzelm@67869
   403
    options: Options,
wenzelm@67869
   404
    dirs: List[Path],
wenzelm@66974
   405
    session: String,
wenzelm@67052
   406
    sessions_structure: Structure,
wenzelm@66975
   407
    errors: List[String],
wenzelm@66974
   408
    base: Base,
wenzelm@66974
   409
    infos: List[Info])
wenzelm@66974
   410
  {
wenzelm@66974
   411
    def check_base: Base = if (errors.isEmpty) base else error(cat_lines(errors))
wenzelm@66974
   412
  }
wenzelm@66974
   413
wenzelm@67846
   414
  def base_info(options: Options,
wenzelm@67846
   415
    session: String,
wenzelm@67852
   416
    progress: Progress = No_Progress,
wenzelm@65428
   417
    dirs: List[Path] = Nil,
wenzelm@67922
   418
    include_sessions: List[String] = Nil,
wenzelm@68370
   419
    session_ancestor: Option[String] = None,
wenzelm@68370
   420
    session_requirements: Boolean = false,
wenzelm@68370
   421
    session_focus: Boolean = false,
wenzelm@68370
   422
    all_known: Boolean = false): Base_Info =
wenzelm@65251
   423
  {
wenzelm@67026
   424
    val full_sessions = load_structure(options, dirs = dirs)
wenzelm@65428
   425
    val global_theories = full_sessions.global_theories
wenzelm@65372
   426
wenzelm@66990
   427
    val selected_sessions =
wenzelm@68370
   428
      full_sessions.selection(Selection(sessions = session :: session_ancestor.toList))
wenzelm@66974
   429
    val info = selected_sessions(session)
wenzelm@68370
   430
    val ancestor = session_ancestor orElse info.parent
wenzelm@66963
   431
wenzelm@66974
   432
    val (session1, infos1) =
wenzelm@68370
   433
      if (session_requirements && ancestor.isDefined) {
wenzelm@67852
   434
        val deps = Sessions.deps(selected_sessions, global_theories, progress = progress)
wenzelm@66974
   435
        val base = deps(session)
wenzelm@66968
   436
wenzelm@66988
   437
        val ancestor_loaded =
wenzelm@66988
   438
          deps.get(ancestor.get) match {
wenzelm@66990
   439
            case Some(ancestor_base)
wenzelm@66990
   440
            if !selected_sessions.imports_requirements(List(ancestor.get)).contains(session) =>
wenzelm@66990
   441
              ancestor_base.loaded_theories.defined(_)
wenzelm@66990
   442
            case _ =>
wenzelm@66988
   443
              error("Bad ancestor " + quote(ancestor.get) + " for session " + quote(session))
wenzelm@66988
   444
          }
wenzelm@66974
   445
wenzelm@66974
   446
        val required_theories =
wenzelm@66968
   447
          for {
wenzelm@66968
   448
            thy <- base.loaded_theories.keys
wenzelm@66988
   449
            if !ancestor_loaded(thy) && base.theory_qualifier(thy) != session
wenzelm@66968
   450
          }
wenzelm@66974
   451
          yield thy
wenzelm@66968
   452
wenzelm@66988
   453
        if (required_theories.isEmpty) (ancestor.get, Nil)
wenzelm@66968
   454
        else {
wenzelm@68370
   455
          val other_name = info.name + "_requirements(" + ancestor.get + ")"
wenzelm@66974
   456
          (other_name,
wenzelm@66968
   457
            List(
wenzelm@66968
   458
              make_info(info.options,
wenzelm@66968
   459
                dir_selected = false,
wenzelm@66968
   460
                dir = info.dir,
wenzelm@66968
   461
                chapter = info.chapter,
wenzelm@66968
   462
                Session_Entry(
wenzelm@66968
   463
                  pos = info.pos,
wenzelm@66968
   464
                  name = other_name,
wenzelm@66968
   465
                  groups = info.groups,
wenzelm@66968
   466
                  path = ".",
wenzelm@66988
   467
                  parent = ancestor,
wenzelm@66974
   468
                  description = "Required theory imports from other sessions",
wenzelm@66968
   469
                  options = Nil,
wenzelm@66991
   470
                  imports = info.deps,
wenzelm@66974
   471
                  theories = List((Nil, required_theories.map(thy => ((thy, Position.none), false)))),
wenzelm@68292
   472
                  document_files = Nil,
wenzelm@68292
   473
                  export_files = Nil))))
wenzelm@66968
   474
        }
wenzelm@66968
   475
      }
wenzelm@66974
   476
      else (session, Nil)
wenzelm@66968
   477
wenzelm@66974
   478
    val full_sessions1 =
wenzelm@66974
   479
      if (infos1.isEmpty) full_sessions
wenzelm@67026
   480
      else load_structure(options, dirs = dirs, infos = infos1)
wenzelm@66987
   481
wenzelm@66987
   482
    val selected_sessions1 =
wenzelm@67922
   483
    {
wenzelm@68483
   484
      val sel_sessions1 = session1 :: session :: include_sessions
wenzelm@67922
   485
      val select_sessions1 =
wenzelm@68542
   486
        if (session_focus) {
wenzelm@68542
   487
          full_sessions1.check_sessions(sel_sessions1)
wenzelm@68542
   488
          full_sessions1.imports_descendants(sel_sessions1)
wenzelm@68542
   489
        }
wenzelm@68542
   490
        else sel_sessions1
wenzelm@67025
   491
      full_sessions1.selection(Selection(sessions = select_sessions1))
wenzelm@67922
   492
    }
wenzelm@66964
   493
wenzelm@66974
   494
    val sessions1 = if (all_known) full_sessions1 else selected_sessions1
wenzelm@67852
   495
    val deps1 = Sessions.deps(sessions1, global_theories, progress = progress)
wenzelm@67922
   496
    val base1 = deps1(session1).copy(known = deps1.all_known)
wenzelm@66964
   497
wenzelm@68204
   498
    Base_Info(options, dirs, session1, deps1.sessions_structure, deps1.errors, base1, infos1)
wenzelm@65251
   499
  }
wenzelm@65251
   500
wenzelm@65251
   501
wenzelm@65415
   502
  /* cumulative session info */
wenzelm@62631
   503
wenzelm@62631
   504
  sealed case class Info(
wenzelm@65519
   505
    name: String,
wenzelm@62631
   506
    chapter: String,
wenzelm@66829
   507
    dir_selected: Boolean,
wenzelm@62631
   508
    pos: Position.T,
wenzelm@62631
   509
    groups: List[String],
wenzelm@62631
   510
    dir: Path,
wenzelm@62631
   511
    parent: Option[String],
wenzelm@62631
   512
    description: String,
wenzelm@62631
   513
    options: Options,
wenzelm@65420
   514
    imports: List[String],
wenzelm@65517
   515
    theories: List[(Options, List[(String, Position.T)])],
wenzelm@65374
   516
    global_theories: List[String],
wenzelm@62631
   517
    document_files: List[(Path, Path)],
wenzelm@69671
   518
    export_files: List[(Path, Int, List[String])],
wenzelm@62631
   519
    meta_digest: SHA1.Digest)
wenzelm@62631
   520
  {
wenzelm@66828
   521
    def deps: List[String] = parent.toList ::: imports
wenzelm@66828
   522
wenzelm@62631
   523
    def timeout: Time = Time.seconds(options.real("timeout") * options.real("timeout_scale"))
wenzelm@67297
   524
wenzelm@67297
   525
    def bibtex_entries: List[Text.Info[String]] =
wenzelm@67297
   526
      (for {
wenzelm@67297
   527
        (document_dir, file) <- document_files.iterator
wenzelm@69366
   528
        if Bibtex.is_bibtex(file.file_name)
wenzelm@67297
   529
        info <- Bibtex.entries(File.read(dir + document_dir + file)).iterator
wenzelm@67297
   530
      } yield info).toList
wenzelm@62631
   531
  }
wenzelm@62631
   532
wenzelm@66967
   533
  def make_info(options: Options, dir_selected: Boolean, dir: Path, chapter: String,
wenzelm@66967
   534
    entry: Session_Entry): Info =
wenzelm@66967
   535
  {
wenzelm@66967
   536
    try {
wenzelm@66967
   537
      val name = entry.name
wenzelm@66967
   538
wenzelm@67284
   539
      if (exclude_session(name)) error("Bad session name")
wenzelm@66967
   540
      if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
wenzelm@66967
   541
      if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
wenzelm@66967
   542
wenzelm@66967
   543
      val session_options = options ++ entry.options
wenzelm@66967
   544
wenzelm@66967
   545
      val theories =
wenzelm@67216
   546
        entry.theories.map({ case (opts, thys) =>
wenzelm@67216
   547
          (session_options ++ opts,
wenzelm@67216
   548
            thys.map({ case ((thy, pos), _) =>
wenzelm@67284
   549
              if (exclude_theory(thy))
wenzelm@67216
   550
                error("Bad theory name " + quote(thy) + Position.here(pos))
wenzelm@67216
   551
              else (thy, pos) })) })
wenzelm@66967
   552
wenzelm@66967
   553
      val global_theories =
wenzelm@66967
   554
        for { (_, thys) <- entry.theories; ((thy, pos), global) <- thys if global }
wenzelm@66967
   555
        yield {
wenzelm@69366
   556
          val thy_name = Path.explode(thy).file_name
wenzelm@66967
   557
          if (Long_Name.is_qualified(thy_name))
wenzelm@66967
   558
            error("Bad qualified name for global theory " +
wenzelm@66967
   559
              quote(thy_name) + Position.here(pos))
wenzelm@66967
   560
          else thy_name
wenzelm@66967
   561
        }
wenzelm@66967
   562
wenzelm@66967
   563
      val conditions =
wenzelm@66967
   564
        theories.flatMap(thys => space_explode(',', thys._1.string("condition"))).distinct.sorted.
wenzelm@66967
   565
          map(x => (x, Isabelle_System.getenv(x) != ""))
wenzelm@66967
   566
wenzelm@66967
   567
      val document_files =
wenzelm@66967
   568
        entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
wenzelm@66967
   569
wenzelm@68292
   570
      val export_files =
wenzelm@69671
   571
        entry.export_files.map({ case (dir, prune, pats) => (Path.explode(dir), prune, pats) })
wenzelm@68292
   572
wenzelm@66967
   573
      val meta_digest =
wenzelm@66967
   574
        SHA1.digest((name, chapter, entry.parent, entry.options, entry.imports,
wenzelm@68292
   575
          entry.theories_no_position, conditions, entry.document_files, entry.export_files).toString)
wenzelm@66967
   576
wenzelm@66967
   577
      Info(name, chapter, dir_selected, entry.pos, entry.groups,
wenzelm@66967
   578
        dir + Path.explode(entry.path), entry.parent, entry.description, session_options,
wenzelm@68292
   579
        entry.imports, theories, global_theories, document_files, export_files, meta_digest)
wenzelm@66967
   580
    }
wenzelm@66967
   581
    catch {
wenzelm@66967
   582
      case ERROR(msg) =>
wenzelm@66967
   583
        error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@66967
   584
          quote(entry.name) + Position.here(entry.pos))
wenzelm@66967
   585
    }
wenzelm@66967
   586
  }
wenzelm@66967
   587
wenzelm@65419
   588
  object Selection
wenzelm@65419
   589
  {
wenzelm@65422
   590
    val empty: Selection = Selection()
wenzelm@65525
   591
    val all: Selection = Selection(all_sessions = true)
wenzelm@65419
   592
  }
wenzelm@65419
   593
wenzelm@65419
   594
  sealed case class Selection(
wenzelm@65419
   595
    requirements: Boolean = false,
wenzelm@65419
   596
    all_sessions: Boolean = false,
wenzelm@66737
   597
    base_sessions: List[String] = Nil,
wenzelm@65419
   598
    exclude_session_groups: List[String] = Nil,
wenzelm@65419
   599
    exclude_sessions: List[String] = Nil,
wenzelm@65419
   600
    session_groups: List[String] = Nil,
wenzelm@65419
   601
    sessions: List[String] = Nil)
wenzelm@65419
   602
  {
wenzelm@66736
   603
    def ++ (other: Selection): Selection =
wenzelm@65422
   604
      Selection(
wenzelm@65422
   605
        requirements = requirements || other.requirements,
wenzelm@65422
   606
        all_sessions = all_sessions || other.all_sessions,
wenzelm@66737
   607
        base_sessions = Library.merge(base_sessions, other.base_sessions),
wenzelm@66736
   608
        exclude_session_groups = Library.merge(exclude_session_groups, other.exclude_session_groups),
wenzelm@66736
   609
        exclude_sessions = Library.merge(exclude_sessions, other.exclude_sessions),
wenzelm@66736
   610
        session_groups = Library.merge(session_groups, other.session_groups),
wenzelm@66736
   611
        sessions = Library.merge(sessions, other.sessions))
wenzelm@65419
   612
  }
wenzelm@65419
   613
wenzelm@67052
   614
  def make(infos: List[Info]): Structure =
wenzelm@62631
   615
  {
wenzelm@65420
   616
    def add_edges(graph: Graph[String, Info], kind: String, edges: Info => Traversable[String])
wenzelm@65420
   617
      : Graph[String, Info] =
wenzelm@65420
   618
    {
wenzelm@65420
   619
      def add_edge(pos: Position.T, name: String, g: Graph[String, Info], parent: String) =
wenzelm@65420
   620
      {
wenzelm@65420
   621
        if (!g.defined(parent))
wenzelm@65420
   622
          error("Bad " + kind + " session " + quote(parent) + " for " +
wenzelm@65420
   623
            quote(name) + Position.here(pos))
wenzelm@65420
   624
wenzelm@65420
   625
        try { g.add_edge_acyclic(parent, name) }
wenzelm@65420
   626
        catch {
wenzelm@65420
   627
          case exn: Graph.Cycles[_] =>
wenzelm@65420
   628
            error(cat_lines(exn.cycles.map(cycle =>
wenzelm@65420
   629
              "Cyclic session dependency of " +
wenzelm@65420
   630
                cycle.map(c => quote(c.toString)).mkString(" via "))) + Position.here(pos))
wenzelm@65420
   631
        }
wenzelm@65420
   632
      }
wenzelm@65420
   633
      (graph /: graph.iterator) {
wenzelm@65420
   634
        case (g, (name, (info, _))) => (g /: edges(info))(add_edge(info.pos, name, _, _))
wenzelm@65420
   635
      }
wenzelm@65420
   636
    }
wenzelm@65420
   637
wenzelm@65420
   638
    val graph0 =
wenzelm@65415
   639
      (Graph.string[Info] /: infos) {
wenzelm@66960
   640
        case (graph, info) =>
wenzelm@66960
   641
          if (graph.defined(info.name))
wenzelm@66960
   642
            error("Duplicate session " + quote(info.name) + Position.here(info.pos) +
wenzelm@66960
   643
              Position.here(graph.get_node(info.name).pos))
wenzelm@66960
   644
          else graph.new_node(info.name, info)
wenzelm@65415
   645
      }
wenzelm@65420
   646
    val graph1 = add_edges(graph0, "parent", _.parent)
wenzelm@65420
   647
    val graph2 = add_edges(graph1, "imports", _.imports)
wenzelm@62631
   648
wenzelm@67052
   649
    new Structure(graph1, graph2)
wenzelm@62631
   650
  }
wenzelm@62631
   651
wenzelm@67052
   652
  final class Structure private[Sessions](
wenzelm@65420
   653
      val build_graph: Graph[String, Info],
wenzelm@65420
   654
      val imports_graph: Graph[String, Info])
wenzelm@62631
   655
  {
wenzelm@69524
   656
    sessions_structure =>
wenzelm@69524
   657
wenzelm@66823
   658
    def build_graph_display: Graph_Display.Graph = Graph_Display.make_graph(build_graph)
wenzelm@66823
   659
    def imports_graph_display: Graph_Display.Graph = Graph_Display.make_graph(imports_graph)
wenzelm@66823
   660
wenzelm@67025
   661
    def defined(name: String): Boolean = imports_graph.defined(name)
wenzelm@65420
   662
    def apply(name: String): Info = imports_graph.get_node(name)
wenzelm@67025
   663
    def get(name: String): Option[Info] = if (defined(name)) Some(apply(name)) else None
wenzelm@62631
   664
wenzelm@65457
   665
    def global_theories: Map[String, String] =
wenzelm@65490
   666
      (Thy_Header.bootstrap_global_theories.toMap /:
wenzelm@65424
   667
        (for {
wenzelm@65519
   668
          (_, (info, _)) <- imports_graph.iterator
wenzelm@65519
   669
          thy <- info.global_theories.iterator }
wenzelm@65519
   670
         yield (thy, info)))({
wenzelm@65519
   671
            case (global, (thy, info)) =>
wenzelm@66780
   672
              val qualifier = info.name
wenzelm@65457
   673
              global.get(thy) match {
wenzelm@65457
   674
                case Some(qualifier1) if qualifier != qualifier1 =>
wenzelm@65457
   675
                  error("Duplicate global theory " + quote(thy) + Position.here(info.pos))
wenzelm@65457
   676
                case _ => global + (thy -> qualifier)
wenzelm@65457
   677
              }
wenzelm@65457
   678
          })
wenzelm@65372
   679
wenzelm@68542
   680
    def check_sessions(names: List[String])
wenzelm@68542
   681
    {
wenzelm@68542
   682
      val bad_sessions = SortedSet(names.filterNot(defined(_)): _*).toList
wenzelm@68542
   683
      if (bad_sessions.nonEmpty)
wenzelm@68542
   684
        error("Undefined session(s): " + commas_quote(bad_sessions))
wenzelm@68542
   685
    }
wenzelm@68542
   686
wenzelm@68733
   687
    def check_sessions(sel: Selection): Unit =
wenzelm@68733
   688
      check_sessions(sel.base_sessions ::: sel.exclude_sessions ::: sel.sessions)
wenzelm@68733
   689
wenzelm@68732
   690
    private def selected(graph: Graph[String, Info], sel: Selection): List[String] =
wenzelm@68732
   691
    {
wenzelm@68733
   692
      check_sessions(sel)
wenzelm@68733
   693
wenzelm@68732
   694
      val select_group = sel.session_groups.toSet
wenzelm@68734
   695
      val select_session = sel.sessions.toSet ++ imports_graph.all_succs(sel.base_sessions)
wenzelm@68732
   696
wenzelm@68732
   697
      val selected0 =
wenzelm@68732
   698
        if (sel.all_sessions) graph.keys
wenzelm@68732
   699
        else {
wenzelm@68732
   700
          (for {
wenzelm@68732
   701
            (name, (info, _)) <- graph.iterator
wenzelm@68732
   702
            if info.dir_selected || select_session(name) ||
wenzelm@68732
   703
              graph.get_node(name).groups.exists(select_group)
wenzelm@68732
   704
          } yield name).toList
wenzelm@68732
   705
        }
wenzelm@68732
   706
wenzelm@68732
   707
      if (sel.requirements) (graph.all_preds(selected0).toSet -- selected0).toList
wenzelm@68732
   708
      else selected0
wenzelm@68732
   709
    }
wenzelm@68732
   710
wenzelm@67052
   711
    def selection(sel: Selection): Structure =
wenzelm@62631
   712
    {
wenzelm@68733
   713
      check_sessions(sel)
wenzelm@67025
   714
wenzelm@68732
   715
      val excluded =
wenzelm@68732
   716
      {
wenzelm@68732
   717
        val exclude_group = sel.exclude_session_groups.toSet
wenzelm@68732
   718
        val exclude_group_sessions =
wenzelm@68732
   719
          (for {
wenzelm@68734
   720
            (name, (info, _)) <- imports_graph.iterator
wenzelm@68734
   721
            if imports_graph.get_node(name).groups.exists(exclude_group)
wenzelm@68732
   722
          } yield name).toList
wenzelm@68734
   723
        imports_graph.all_succs(exclude_group_sessions ::: sel.exclude_sessions).toSet
wenzelm@68732
   724
      }
wenzelm@67027
   725
wenzelm@67025
   726
      def restrict(graph: Graph[String, Info]): Graph[String, Info] =
wenzelm@67025
   727
      {
wenzelm@68732
   728
        val sessions = graph.all_preds(selected(graph, sel)).filterNot(excluded)
wenzelm@67029
   729
        graph.restrict(graph.all_preds(sessions).toSet)
wenzelm@67025
   730
      }
wenzelm@67025
   731
wenzelm@67052
   732
      new Structure(restrict(build_graph), restrict(imports_graph))
wenzelm@62631
   733
    }
wenzelm@62631
   734
wenzelm@69524
   735
    def selection_deps(
wenzelm@69524
   736
      options: Options,
wenzelm@69524
   737
      selection: Selection,
wenzelm@68304
   738
      progress: Progress = No_Progress,
wenzelm@69524
   739
      uniform_session: Boolean = false,
wenzelm@69524
   740
      loading_sessions: Boolean = false,
wenzelm@68304
   741
      inlined_files: Boolean = false,
wenzelm@68304
   742
      verbose: Boolean = false): Deps =
wenzelm@68304
   743
    {
wenzelm@69524
   744
      val selection1 =
wenzelm@69524
   745
        if (uniform_session) {
wenzelm@69524
   746
          val sessions_structure1 = sessions_structure.selection(selection)
wenzelm@69524
   747
wenzelm@69524
   748
          val default_record_proofs = options.int("record_proofs")
wenzelm@69524
   749
          val sessions_record_proofs =
wenzelm@69524
   750
            for {
wenzelm@69524
   751
              name <- sessions_structure1.build_topological_order
wenzelm@69524
   752
              info <- sessions_structure1.get(name)
wenzelm@69524
   753
              if info.options.int("record_proofs") > default_record_proofs
wenzelm@69524
   754
            } yield name
wenzelm@69524
   755
wenzelm@69524
   756
          val excluded =
wenzelm@69524
   757
            for (name <- sessions_structure1.build_descendants(sessions_record_proofs))
wenzelm@69524
   758
            yield {
wenzelm@69524
   759
              progress.echo_warning("Skipping session " + name + "  (option record_proofs)")
wenzelm@69524
   760
              name
wenzelm@69524
   761
            }
wenzelm@69524
   762
wenzelm@69524
   763
          selection.copy(exclude_sessions = excluded ::: selection.exclude_sessions)
wenzelm@69524
   764
        }
wenzelm@69524
   765
        else selection
wenzelm@69524
   766
wenzelm@69524
   767
      val deps =
wenzelm@69524
   768
        Sessions.deps(sessions_structure.selection(selection1), global_theories,
wenzelm@69524
   769
          progress = progress, inlined_files = inlined_files, verbose = verbose)
wenzelm@69524
   770
wenzelm@69524
   771
      if (loading_sessions) {
wenzelm@69524
   772
        val selection_size = deps.sessions_structure.build_graph.size
wenzelm@69524
   773
        if (selection_size > 1) progress.echo("Loading " + selection_size + " sessions ...")
wenzelm@69524
   774
      }
wenzelm@69524
   775
wenzelm@69524
   776
      deps
wenzelm@68304
   777
    }
wenzelm@68304
   778
wenzelm@68732
   779
    def build_selection(sel: Selection): List[String] = selected(build_graph, sel)
wenzelm@67029
   780
    def build_descendants(ss: List[String]): List[String] = build_graph.all_succs(ss)
wenzelm@67029
   781
    def build_requirements(ss: List[String]): List[String] = build_graph.all_preds(ss).reverse
wenzelm@67029
   782
    def build_topological_order: List[String] = build_graph.topological_order
wenzelm@62631
   783
wenzelm@68732
   784
    def imports_selection(sel: Selection): List[String] = selected(imports_graph, sel)
wenzelm@67029
   785
    def imports_descendants(ss: List[String]): List[String] = imports_graph.all_succs(ss)
wenzelm@67029
   786
    def imports_requirements(ss: List[String]): List[String] = imports_graph.all_preds(ss).reverse
wenzelm@67029
   787
    def imports_topological_order: List[String] = imports_graph.topological_order
wenzelm@65420
   788
wenzelm@65420
   789
    override def toString: String =
wenzelm@67052
   790
      imports_graph.keys_iterator.mkString("Sessions.Structure(", ", ", ")")
wenzelm@62631
   791
  }
wenzelm@62631
   792
wenzelm@62631
   793
wenzelm@62631
   794
  /* parser */
wenzelm@62631
   795
wenzelm@62864
   796
  val ROOT = Path.explode("ROOT")
wenzelm@62864
   797
  val ROOTS = Path.explode("ROOTS")
wenzelm@62864
   798
wenzelm@62631
   799
  private val CHAPTER = "chapter"
wenzelm@62631
   800
  private val SESSION = "session"
wenzelm@62631
   801
  private val IN = "in"
wenzelm@62631
   802
  private val DESCRIPTION = "description"
wenzelm@62631
   803
  private val OPTIONS = "options"
wenzelm@65420
   804
  private val SESSIONS = "sessions"
wenzelm@62631
   805
  private val THEORIES = "theories"
wenzelm@65374
   806
  private val GLOBAL = "global"
wenzelm@62631
   807
  private val DOCUMENT_FILES = "document_files"
wenzelm@68292
   808
  private val EXPORT_FILES = "export_files"
wenzelm@62631
   809
wenzelm@67004
   810
  val root_syntax =
wenzelm@67004
   811
    Outer_Syntax.empty + "(" + ")" + "+" + "," + "=" + "[" + "]" + GLOBAL + IN +
wenzelm@63443
   812
      (CHAPTER, Keyword.THY_DECL) +
wenzelm@63443
   813
      (SESSION, Keyword.THY_DECL) +
wenzelm@63443
   814
      (DESCRIPTION, Keyword.QUASI_COMMAND) +
wenzelm@63443
   815
      (OPTIONS, Keyword.QUASI_COMMAND) +
wenzelm@65420
   816
      (SESSIONS, Keyword.QUASI_COMMAND) +
wenzelm@63443
   817
      (THEORIES, Keyword.QUASI_COMMAND) +
wenzelm@68292
   818
      (DOCUMENT_FILES, Keyword.QUASI_COMMAND) +
wenzelm@68292
   819
      (EXPORT_FILES, Keyword.QUASI_COMMAND)
wenzelm@62631
   820
wenzelm@66818
   821
  abstract class Entry
wenzelm@66818
   822
  sealed case class Chapter(name: String) extends Entry
wenzelm@66818
   823
  sealed case class Session_Entry(
wenzelm@66818
   824
    pos: Position.T,
wenzelm@66818
   825
    name: String,
wenzelm@66818
   826
    groups: List[String],
wenzelm@66818
   827
    path: String,
wenzelm@66818
   828
    parent: Option[String],
wenzelm@66818
   829
    description: String,
wenzelm@66818
   830
    options: List[Options.Spec],
wenzelm@66818
   831
    imports: List[String],
wenzelm@66818
   832
    theories: List[(List[Options.Spec], List[((String, Position.T), Boolean)])],
wenzelm@68292
   833
    document_files: List[(String, String)],
wenzelm@69671
   834
    export_files: List[(String, Int, List[String])]) extends Entry
wenzelm@66818
   835
  {
wenzelm@66818
   836
    def theories_no_position: List[(List[Options.Spec], List[(String, Boolean)])] =
wenzelm@66818
   837
      theories.map({ case (a, b) => (a, b.map({ case ((c, _), d) => (c, d) })) })
wenzelm@66818
   838
  }
wenzelm@66818
   839
wenzelm@68841
   840
  private object Parser extends Options.Parser
wenzelm@62631
   841
  {
wenzelm@62631
   842
    private val chapter: Parser[Chapter] =
wenzelm@62631
   843
    {
wenzelm@62631
   844
      val chapter_name = atom("chapter name", _.is_name)
wenzelm@62631
   845
wenzelm@62631
   846
      command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
wenzelm@62631
   847
    }
wenzelm@62631
   848
wenzelm@62631
   849
    private val session_entry: Parser[Session_Entry] =
wenzelm@62631
   850
    {
wenzelm@62631
   851
      val option =
wenzelm@67210
   852
        option_name ~ opt($$$("=") ~! option_value ^^ { case _ ~ x => x }) ^^
wenzelm@67210
   853
          { case x ~ y => (x, y) }
wenzelm@62631
   854
      val options = $$$("[") ~> rep1sep(option, $$$(",")) <~ $$$("]")
wenzelm@62631
   855
wenzelm@65374
   856
      val global =
wenzelm@65374
   857
        ($$$("(") ~! $$$(GLOBAL) ~ $$$(")")) ^^ { case _ => true } | success(false)
wenzelm@65374
   858
wenzelm@65374
   859
      val theory_entry =
wenzelm@65517
   860
        position(theory_name) ~ global ^^ { case x ~ y => (x, y) }
wenzelm@65374
   861
wenzelm@62631
   862
      val theories =
wenzelm@65374
   863
        $$$(THEORIES) ~!
wenzelm@66970
   864
          ((options | success(Nil)) ~ rep1(theory_entry)) ^^
wenzelm@65374
   865
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@62631
   866
wenzelm@68292
   867
      val in_path = $$$("(") ~! ($$$(IN) ~ path ~ $$$(")")) ^^ { case _ ~ (_ ~ x ~ _) => x }
wenzelm@68292
   868
wenzelm@62631
   869
      val document_files =
wenzelm@62631
   870
        $$$(DOCUMENT_FILES) ~!
wenzelm@68292
   871
          ((in_path | success("document")) ~ rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
wenzelm@68292
   872
wenzelm@69671
   873
      val prune = $$$("[") ~! (nat ~ $$$("]")) ^^ { case _ ~ (x ~ _) => x } | success(0)
wenzelm@69671
   874
wenzelm@68292
   875
      val export_files =
wenzelm@69671
   876
        $$$(EXPORT_FILES) ~! ((in_path | success("export")) ~ prune ~ rep1(embedded)) ^^
wenzelm@69671
   877
          { case _ ~ (x ~ y ~ z) => (x, y, z) }
wenzelm@62631
   878
wenzelm@62631
   879
      command(SESSION) ~!
wenzelm@62631
   880
        (position(session_name) ~
wenzelm@62631
   881
          (($$$("(") ~! (rep1(name) <~ $$$(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   882
          (($$$(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
wenzelm@62631
   883
          ($$$("=") ~!
wenzelm@62631
   884
            (opt(session_name ~! $$$("+") ^^ { case x ~ _ => x }) ~
wenzelm@62631
   885
              (($$$(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
wenzelm@62631
   886
              (($$$(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@66970
   887
              (($$$(SESSIONS) ~! rep1(session_name)  ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@66970
   888
              rep(theories) ~
wenzelm@68292
   889
              (rep(document_files) ^^ (x => x.flatten)) ~
wenzelm@68292
   890
              (rep(export_files))))) ^^
wenzelm@68292
   891
        { case _ ~ ((a, pos) ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i ~ j))) =>
wenzelm@68292
   892
            Session_Entry(pos, a, b, c, d, e, f, g, h, i, j) }
wenzelm@62631
   893
    }
wenzelm@62631
   894
wenzelm@66819
   895
    def parse_root(path: Path): List[Entry] =
wenzelm@62631
   896
    {
wenzelm@66764
   897
      val toks = Token.explode(root_syntax.keywords, File.read(path))
wenzelm@66764
   898
      val start = Token.Pos.file(path.implode)
wenzelm@62631
   899
wenzelm@66764
   900
      parse_all(rep(chapter | session_entry), Token.reader(toks, start)) match {
wenzelm@66818
   901
        case Success(result, _) => result
wenzelm@66764
   902
        case bad => error(bad.toString)
wenzelm@62631
   903
      }
wenzelm@62631
   904
    }
wenzelm@62631
   905
  }
wenzelm@62631
   906
wenzelm@66819
   907
  def parse_root(path: Path): List[Entry] = Parser.parse_root(path)
wenzelm@66819
   908
wenzelm@66819
   909
  def parse_root_entries(path: Path): List[Session_Entry] =
wenzelm@66819
   910
    for (entry <- Parser.parse_root(path) if entry.isInstanceOf[Session_Entry])
wenzelm@66819
   911
    yield entry.asInstanceOf[Session_Entry]
wenzelm@66818
   912
wenzelm@66960
   913
  def read_root(options: Options, select: Boolean, path: Path): List[Info] =
wenzelm@66818
   914
  {
wenzelm@66818
   915
    var entry_chapter = "Unsorted"
wenzelm@66960
   916
    val infos = new mutable.ListBuffer[Info]
wenzelm@66819
   917
    parse_root(path).foreach {
wenzelm@66818
   918
      case Chapter(name) => entry_chapter = name
wenzelm@66967
   919
      case entry: Session_Entry =>
wenzelm@66967
   920
        infos += make_info(options, select, path.dir, entry_chapter, entry)
wenzelm@66818
   921
    }
wenzelm@66818
   922
    infos.toList
wenzelm@66818
   923
  }
wenzelm@66818
   924
wenzelm@66818
   925
  def parse_roots(roots: Path): List[String] =
wenzelm@66818
   926
  {
wenzelm@66818
   927
    for {
wenzelm@66818
   928
      line <- split_lines(File.read(roots))
wenzelm@66818
   929
      if !(line == "" || line.startsWith("#"))
wenzelm@66818
   930
    } yield line
wenzelm@66818
   931
  }
wenzelm@66818
   932
wenzelm@62631
   933
wenzelm@62635
   934
  /* load sessions from certain directories */
wenzelm@62631
   935
wenzelm@62631
   936
  private def is_session_dir(dir: Path): Boolean =
wenzelm@62631
   937
    (dir + ROOT).is_file || (dir + ROOTS).is_file
wenzelm@62631
   938
wenzelm@62631
   939
  private def check_session_dir(dir: Path): Path =
wenzelm@65468
   940
    if (is_session_dir(dir)) File.pwd() + dir.expand
wenzelm@62631
   941
    else error("Bad session root directory: " + dir.toString)
wenzelm@62631
   942
wenzelm@65561
   943
  def directories(dirs: List[Path], select_dirs: List[Path]): List[(Boolean, Path)] =
wenzelm@65561
   944
  {
wenzelm@65561
   945
    val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
wenzelm@68746
   946
    for { (select, dir) <- (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _)) }
wenzelm@68746
   947
    yield (select, dir.canonical)
wenzelm@65561
   948
  }
wenzelm@65561
   949
wenzelm@67026
   950
  def load_structure(options: Options,
wenzelm@66968
   951
    dirs: List[Path] = Nil,
wenzelm@66968
   952
    select_dirs: List[Path] = Nil,
wenzelm@67052
   953
    infos: List[Info] = Nil): Structure =
wenzelm@62631
   954
  {
wenzelm@66764
   955
    def load_dir(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@62635
   956
      load_root(select, dir) ::: load_roots(select, dir)
wenzelm@62631
   957
wenzelm@66764
   958
    def load_root(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@66764
   959
    {
wenzelm@66764
   960
      val root = dir + ROOT
wenzelm@66764
   961
      if (root.is_file) List((select, root)) else Nil
wenzelm@66764
   962
    }
wenzelm@62631
   963
wenzelm@66764
   964
    def load_roots(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@62631
   965
    {
wenzelm@62631
   966
      val roots = dir + ROOTS
wenzelm@62631
   967
      if (roots.is_file) {
wenzelm@62631
   968
        for {
wenzelm@66818
   969
          entry <- parse_roots(roots)
wenzelm@62631
   970
          dir1 =
wenzelm@66818
   971
            try { check_session_dir(dir + Path.explode(entry)) }
wenzelm@62631
   972
            catch {
wenzelm@62631
   973
              case ERROR(msg) =>
wenzelm@62631
   974
                error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
wenzelm@62631
   975
            }
wenzelm@66764
   976
          res <- load_dir(select, dir1)
wenzelm@66764
   977
        } yield res
wenzelm@62631
   978
      }
wenzelm@62631
   979
      else Nil
wenzelm@62631
   980
    }
wenzelm@62631
   981
wenzelm@66764
   982
    val roots =
wenzelm@62631
   983
      for {
wenzelm@65561
   984
        (select, dir) <- directories(dirs, select_dirs)
wenzelm@66764
   985
        res <- load_dir(select, check_session_dir(dir))
wenzelm@66764
   986
      } yield res
wenzelm@66764
   987
wenzelm@66764
   988
    val unique_roots =
wenzelm@66764
   989
      ((Map.empty[JFile, (Boolean, Path)] /: roots) { case (m, (select, path)) =>
wenzelm@66764
   990
        val file = path.canonical_file
wenzelm@66764
   991
        m.get(file) match {
wenzelm@66764
   992
          case None => m + (file -> (select, path))
wenzelm@66764
   993
          case Some((select1, path1)) => m + (file -> (select1 || select, path1))
wenzelm@66764
   994
        }
wenzelm@66764
   995
      }).toList.map(_._2)
wenzelm@66764
   996
wenzelm@66968
   997
    make(unique_roots.flatMap(p => read_root(options, p._1, p._2)) ::: infos)
wenzelm@62631
   998
  }
wenzelm@62632
   999
wenzelm@62632
  1000
wenzelm@62637
  1001
wenzelm@62704
  1002
  /** heap file with SHA1 digest **/
wenzelm@62704
  1003
wenzelm@62704
  1004
  private val sha1_prefix = "SHA1:"
wenzelm@62704
  1005
wenzelm@62704
  1006
  def read_heap_digest(heap: Path): Option[String] =
wenzelm@62704
  1007
  {
wenzelm@62704
  1008
    if (heap.is_file) {
wenzelm@69393
  1009
      using(FileChannel.open(heap.file.toPath, StandardOpenOption.READ))(file =>
wenzelm@69393
  1010
      {
wenzelm@62704
  1011
        val len = file.size
wenzelm@62704
  1012
        val n = sha1_prefix.length + SHA1.digest_length
wenzelm@62704
  1013
        if (len >= n) {
wenzelm@62704
  1014
          file.position(len - n)
wenzelm@62704
  1015
wenzelm@62704
  1016
          val buf = ByteBuffer.allocate(n)
wenzelm@62704
  1017
          var i = 0
wenzelm@62704
  1018
          var m = 0
wenzelm@62704
  1019
          do {
wenzelm@62704
  1020
            m = file.read(buf)
wenzelm@62704
  1021
            if (m != -1) i += m
wenzelm@62704
  1022
          }
wenzelm@62704
  1023
          while (m != -1 && n > i)
wenzelm@62704
  1024
wenzelm@62704
  1025
          if (i == n) {
wenzelm@62704
  1026
            val prefix = new String(buf.array(), 0, sha1_prefix.length, UTF8.charset)
wenzelm@62704
  1027
            val s = new String(buf.array(), sha1_prefix.length, SHA1.digest_length, UTF8.charset)
wenzelm@62704
  1028
            if (prefix == sha1_prefix) Some(s) else None
wenzelm@62704
  1029
          }
wenzelm@62704
  1030
          else None
wenzelm@62704
  1031
        }
wenzelm@62704
  1032
        else None
wenzelm@69393
  1033
      })
wenzelm@62704
  1034
    }
wenzelm@62704
  1035
    else None
wenzelm@62704
  1036
  }
wenzelm@62704
  1037
wenzelm@62704
  1038
  def write_heap_digest(heap: Path): String =
wenzelm@62704
  1039
    read_heap_digest(heap) match {
wenzelm@62704
  1040
      case None =>
wenzelm@62704
  1041
        val s = SHA1.digest(heap).rep
wenzelm@62704
  1042
        File.append(heap, sha1_prefix + s)
wenzelm@62704
  1043
        s
wenzelm@62704
  1044
      case Some(s) => s
wenzelm@62704
  1045
    }
wenzelm@62704
  1046
wenzelm@62704
  1047
wenzelm@62704
  1048
wenzelm@62637
  1049
  /** persistent store **/
wenzelm@62632
  1050
wenzelm@65296
  1051
  object Session_Info
wenzelm@65296
  1052
  {
wenzelm@66857
  1053
    val session_name = SQL.Column.string("session_name").make_primary_key
wenzelm@65326
  1054
wenzelm@65296
  1055
    // Build_Log.Session_Info
wenzelm@65296
  1056
    val session_timing = SQL.Column.bytes("session_timing")
wenzelm@65296
  1057
    val command_timings = SQL.Column.bytes("command_timings")
wenzelm@66873
  1058
    val theory_timings = SQL.Column.bytes("theory_timings")
wenzelm@65296
  1059
    val ml_statistics = SQL.Column.bytes("ml_statistics")
wenzelm@65296
  1060
    val task_statistics = SQL.Column.bytes("task_statistics")
wenzelm@65934
  1061
    val errors = SQL.Column.bytes("errors")
wenzelm@65296
  1062
    val build_log_columns =
wenzelm@66873
  1063
      List(session_name, session_timing, command_timings, theory_timings,
wenzelm@66873
  1064
        ml_statistics, task_statistics, errors)
wenzelm@65296
  1065
wenzelm@65296
  1066
    // Build.Session_Info
wenzelm@65296
  1067
    val sources = SQL.Column.string("sources")
wenzelm@65296
  1068
    val input_heaps = SQL.Column.string("input_heaps")
wenzelm@65296
  1069
    val output_heap = SQL.Column.string("output_heap")
wenzelm@65296
  1070
    val return_code = SQL.Column.int("return_code")
wenzelm@66746
  1071
    val build_columns = List(sources, input_heaps, output_heap, return_code)
wenzelm@65296
  1072
wenzelm@65296
  1073
    val table = SQL.Table("isabelle_session_info", build_log_columns ::: build_columns)
wenzelm@65296
  1074
  }
wenzelm@65296
  1075
wenzelm@68209
  1076
  def store(options: Options, system_mode: Boolean = false): Store =
wenzelm@68209
  1077
    new Store(options, system_mode)
wenzelm@62632
  1078
wenzelm@68209
  1079
  class Store private[Sessions](val options: Options, val system_mode: Boolean)
wenzelm@62632
  1080
  {
wenzelm@68219
  1081
    override def toString: String = "Store(output_dir = " + output_dir.expand + ")"
wenzelm@68219
  1082
wenzelm@68219
  1083
wenzelm@68219
  1084
    /* directories */
wenzelm@68219
  1085
wenzelm@68523
  1086
    val system_output_dir: Path = Path.explode("$ISABELLE_HEAPS_SYSTEM/$ML_IDENTIFIER")
wenzelm@68523
  1087
    val user_output_dir: Path = Path.explode("$ISABELLE_HEAPS/$ML_IDENTIFIER")
wenzelm@68219
  1088
wenzelm@68221
  1089
    val output_dir: Path =
wenzelm@68219
  1090
      if (system_mode) system_output_dir else user_output_dir
wenzelm@68219
  1091
wenzelm@68221
  1092
    val input_dirs: List[Path] =
wenzelm@68219
  1093
      if (system_mode) List(system_output_dir)
wenzelm@68219
  1094
      else List(user_output_dir, system_output_dir)
wenzelm@62632
  1095
wenzelm@62632
  1096
    val browser_info: Path =
wenzelm@68523
  1097
      if (system_mode) Path.explode("$ISABELLE_BROWSER_INFO_SYSTEM")
wenzelm@62632
  1098
      else Path.explode("$ISABELLE_BROWSER_INFO")
wenzelm@62632
  1099
wenzelm@62637
  1100
wenzelm@68221
  1101
    /* file names */
wenzelm@65298
  1102
wenzelm@68221
  1103
    def heap(name: String): Path = Path.basic(name)
wenzelm@68221
  1104
    def database(name: String): Path = Path.basic("log") + Path.basic(name).ext("db")
wenzelm@68221
  1105
    def log(name: String): Path = Path.basic("log") + Path.basic(name)
wenzelm@68221
  1106
    def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@62637
  1107
wenzelm@68221
  1108
    def output_heap(name: String): Path = output_dir + heap(name)
wenzelm@68221
  1109
    def output_database(name: String): Path = output_dir + database(name)
wenzelm@68086
  1110
    def output_log(name: String): Path = output_dir + log(name)
wenzelm@68086
  1111
    def output_log_gz(name: String): Path = output_dir + log_gz(name)
wenzelm@68086
  1112
wenzelm@68221
  1113
    def prepare_output_dir() { Isabelle_System.mkdirs(output_dir + Path.basic("log")) }
wenzelm@68220
  1114
wenzelm@62637
  1115
wenzelm@68221
  1116
    /* heap */
wenzelm@62637
  1117
wenzelm@68212
  1118
    def find_heap(name: String): Option[Path] =
wenzelm@68221
  1119
      input_dirs.map(_ + heap(name)).find(_.is_file)
wenzelm@68212
  1120
wenzelm@68212
  1121
    def find_heap_digest(name: String): Option[String] =
wenzelm@68212
  1122
      find_heap(name).flatMap(read_heap_digest(_))
wenzelm@62632
  1123
wenzelm@68221
  1124
    def the_heap(name: String): Path =
wenzelm@68221
  1125
      find_heap(name) getOrElse
wenzelm@68221
  1126
        error("Missing heap image for session " + quote(name) + " -- expected in:\n" +
wenzelm@68221
  1127
          cat_lines(input_dirs.map(dir => "  " + dir.expand.implode)))
wenzelm@68221
  1128
wenzelm@68221
  1129
wenzelm@68221
  1130
    /* database */
wenzelm@68221
  1131
wenzelm@68221
  1132
    private def database_server: Boolean = options.bool("build_database_server")
wenzelm@65281
  1133
wenzelm@68221
  1134
    def access_database(name: String, output: Boolean = false): Option[SQL.Database] =
wenzelm@68221
  1135
    {
wenzelm@68221
  1136
      if (database_server) {
wenzelm@68221
  1137
        val db =
wenzelm@68221
  1138
          PostgreSQL.open_database(
wenzelm@68221
  1139
            user = options.string("build_database_user"),
wenzelm@68221
  1140
            password = options.string("build_database_password"),
wenzelm@68221
  1141
            database = options.string("build_database_name"),
wenzelm@68221
  1142
            host = options.string("build_database_host"),
wenzelm@68221
  1143
            port = options.int("build_database_port"),
wenzelm@68221
  1144
            ssh =
wenzelm@69074
  1145
              options.proper_string("build_database_ssh_host").map(ssh_host =>
wenzelm@68221
  1146
                SSH.open_session(options,
wenzelm@68221
  1147
                  host = ssh_host,
wenzelm@68221
  1148
                  user = options.string("build_database_ssh_user"),
wenzelm@68221
  1149
                  port = options.int("build_database_ssh_port"))),
wenzelm@68221
  1150
            ssh_close = true)
wenzelm@68221
  1151
        if (output || has_session_info(db, name)) Some(db) else { db.close; None }
wenzelm@68221
  1152
      }
wenzelm@68221
  1153
      else if (output) Some(SQLite.open_database(output_database(name)))
wenzelm@68221
  1154
      else input_dirs.map(_ + database(name)).find(_.is_file).map(SQLite.open_database(_))
wenzelm@68221
  1155
    }
wenzelm@68212
  1156
wenzelm@68221
  1157
    def open_database(name: String, output: Boolean = false): SQL.Database =
wenzelm@68221
  1158
      access_database(name, output = output) getOrElse
wenzelm@68221
  1159
        error("Missing build database for session " + quote(name))
wenzelm@68205
  1160
wenzelm@68221
  1161
    def clean_output(name: String): (Boolean, Boolean) =
wenzelm@68221
  1162
    {
wenzelm@68221
  1163
      val relevant_db =
wenzelm@68221
  1164
        database_server &&
wenzelm@68221
  1165
        {
wenzelm@68221
  1166
          access_database(name) match {
wenzelm@68221
  1167
            case Some(db) =>
wenzelm@68221
  1168
              try {
wenzelm@68221
  1169
                db.transaction {
wenzelm@68221
  1170
                  val relevant_db = has_session_info(db, name)
wenzelm@68221
  1171
                  init_session_info(db, name)
wenzelm@68221
  1172
                  relevant_db
wenzelm@68221
  1173
                }
wenzelm@68221
  1174
              } finally { db.close }
wenzelm@68221
  1175
            case None => false
wenzelm@68221
  1176
          }
wenzelm@68221
  1177
        }
wenzelm@68212
  1178
wenzelm@68221
  1179
      val del =
wenzelm@68221
  1180
        for {
wenzelm@68221
  1181
          dir <- (if (system_mode) List(user_output_dir, system_output_dir) else List(user_output_dir))
wenzelm@68221
  1182
          file <- List(heap(name), database(name), log(name), log_gz(name))
wenzelm@68221
  1183
          path = dir + file if path.is_file
wenzelm@68221
  1184
        } yield path.file.delete
wenzelm@68221
  1185
wenzelm@68221
  1186
      val relevant = relevant_db || del.nonEmpty
wenzelm@68221
  1187
      val ok = del.forall(b => b)
wenzelm@68221
  1188
      (relevant, ok)
wenzelm@68221
  1189
    }
wenzelm@65287
  1190
wenzelm@65287
  1191
wenzelm@68218
  1192
    /* SQL database content */
wenzelm@68218
  1193
wenzelm@68294
  1194
    val xml_cache: XML.Cache = XML.make_cache()
wenzelm@68294
  1195
    val xz_cache: XZ.Cache = XZ.make_cache()
wenzelm@68218
  1196
wenzelm@68218
  1197
    def read_bytes(db: SQL.Database, name: String, column: SQL.Column): Bytes =
wenzelm@68218
  1198
      db.using_statement(Session_Info.table.select(List(column),
wenzelm@68218
  1199
        Session_Info.session_name.where_equal(name)))(stmt =>
wenzelm@68218
  1200
      {
wenzelm@68218
  1201
        val res = stmt.execute_query()
wenzelm@68218
  1202
        if (!res.next()) Bytes.empty else res.bytes(column)
wenzelm@68218
  1203
      })
wenzelm@68218
  1204
wenzelm@68218
  1205
    def read_properties(db: SQL.Database, name: String, column: SQL.Column): List[Properties.T] =
wenzelm@68218
  1206
      Properties.uncompress(
wenzelm@68218
  1207
        read_bytes(db, name, column), cache = xz_cache, xml_cache = Some(xml_cache))
wenzelm@68218
  1208
wenzelm@68218
  1209
wenzelm@65296
  1210
    /* session info */
wenzelm@65281
  1211
wenzelm@68086
  1212
    def init_session_info(db: SQL.Database, name: String)
wenzelm@68086
  1213
    {
wenzelm@68086
  1214
      db.transaction {
wenzelm@68086
  1215
        db.create_table(Session_Info.table)
wenzelm@68086
  1216
        db.using_statement(
wenzelm@68086
  1217
          Session_Info.table.delete(Session_Info.session_name.where_equal(name)))(_.execute)
wenzelm@68221
  1218
wenzelm@68221
  1219
        db.create_table(Export.Data.table)
wenzelm@68221
  1220
        db.using_statement(
wenzelm@68221
  1221
          Export.Data.table.delete(Export.Data.session_name.where_equal(name)))(_.execute)
wenzelm@68221
  1222
      }
wenzelm@68221
  1223
    }
wenzelm@68221
  1224
wenzelm@68221
  1225
    def has_session_info(db: SQL.Database, name: String): Boolean =
wenzelm@68221
  1226
    {
wenzelm@68221
  1227
      db.transaction {
wenzelm@68221
  1228
        db.tables.contains(Session_Info.table.name) &&
wenzelm@68221
  1229
        {
wenzelm@68221
  1230
          db.using_statement(
wenzelm@68221
  1231
            Session_Info.table.select(List(Session_Info.session_name),
wenzelm@68221
  1232
              Session_Info.session_name.where_equal(name)))(stmt => stmt.execute_query().next())
wenzelm@68221
  1233
        }
wenzelm@68086
  1234
      }
wenzelm@68086
  1235
    }
wenzelm@68086
  1236
wenzelm@65296
  1237
    def write_session_info(
wenzelm@65318
  1238
      db: SQL.Database,
wenzelm@65320
  1239
      name: String,
wenzelm@65318
  1240
      build_log: Build_Log.Session_Info,
wenzelm@65318
  1241
      build: Build.Session_Info)
wenzelm@65281
  1242
    {
wenzelm@65281
  1243
      db.transaction {
wenzelm@65698
  1244
        db.using_statement(Session_Info.table.insert())(stmt =>
wenzelm@65281
  1245
        {
wenzelm@65748
  1246
          stmt.string(1) = name
wenzelm@65857
  1247
          stmt.bytes(2) = Properties.encode(build_log.session_timing)
wenzelm@68018
  1248
          stmt.bytes(3) = Properties.compress(build_log.command_timings, cache = xz_cache)
wenzelm@68018
  1249
          stmt.bytes(4) = Properties.compress(build_log.theory_timings, cache = xz_cache)
wenzelm@68018
  1250
          stmt.bytes(5) = Properties.compress(build_log.ml_statistics, cache = xz_cache)
wenzelm@68018
  1251
          stmt.bytes(6) = Properties.compress(build_log.task_statistics, cache = xz_cache)
wenzelm@68018
  1252
          stmt.bytes(7) = Build_Log.compress_errors(build_log.errors, cache = xz_cache)
wenzelm@66873
  1253
          stmt.string(8) = build.sources
wenzelm@66873
  1254
          stmt.string(9) = cat_lines(build.input_heaps)
wenzelm@66873
  1255
          stmt.string(10) = build.output_heap getOrElse ""
wenzelm@66873
  1256
          stmt.int(11) = build.return_code
wenzelm@65281
  1257
          stmt.execute()
wenzelm@65281
  1258
        })
wenzelm@65281
  1259
      }
wenzelm@65281
  1260
    }
wenzelm@65281
  1261
wenzelm@65320
  1262
    def read_session_timing(db: SQL.Database, name: String): Properties.T =
wenzelm@65857
  1263
      Properties.decode(read_bytes(db, name, Session_Info.session_timing), Some(xml_cache))
wenzelm@65286
  1264
wenzelm@65320
  1265
    def read_command_timings(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1266
      read_properties(db, name, Session_Info.command_timings)
wenzelm@65286
  1267
wenzelm@66873
  1268
    def read_theory_timings(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@66873
  1269
      read_properties(db, name, Session_Info.theory_timings)
wenzelm@66873
  1270
wenzelm@65320
  1271
    def read_ml_statistics(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1272
      read_properties(db, name, Session_Info.ml_statistics)
wenzelm@65286
  1273
wenzelm@65320
  1274
    def read_task_statistics(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1275
      read_properties(db, name, Session_Info.task_statistics)
wenzelm@65286
  1276
wenzelm@65937
  1277
    def read_errors(db: SQL.Database, name: String): List[String] =
wenzelm@68018
  1278
      Build_Log.uncompress_errors(read_bytes(db, name, Session_Info.errors), cache = xz_cache)
wenzelm@65937
  1279
wenzelm@65320
  1280
    def read_build(db: SQL.Database, name: String): Option[Build.Session_Info] =
wenzelm@66744
  1281
    {
wenzelm@66957
  1282
      if (db.tables.contains(Session_Info.table.name)) {
wenzelm@66957
  1283
        db.using_statement(Session_Info.table.select(Session_Info.build_columns,
wenzelm@66957
  1284
          Session_Info.session_name.where_equal(name)))(stmt =>
wenzelm@66957
  1285
        {
wenzelm@66957
  1286
          val res = stmt.execute_query()
wenzelm@66957
  1287
          if (!res.next()) None
wenzelm@66957
  1288
          else {
wenzelm@66957
  1289
            Some(
wenzelm@66957
  1290
              Build.Session_Info(
wenzelm@66957
  1291
                res.string(Session_Info.sources),
wenzelm@66957
  1292
                split_lines(res.string(Session_Info.input_heaps)),
wenzelm@66957
  1293
                res.string(Session_Info.output_heap) match { case "" => None case s => Some(s) },
wenzelm@66957
  1294
                res.int(Session_Info.return_code)))
wenzelm@66957
  1295
          }
wenzelm@66957
  1296
        })
wenzelm@66957
  1297
      }
wenzelm@66957
  1298
      else None
wenzelm@66744
  1299
    }
wenzelm@65281
  1300
  }
wenzelm@62631
  1301
}