src/Pure/Thy/sessions.scala
author wenzelm
Tue Jan 23 19:25:39 2018 +0100 (21 months ago ago)
changeset 67493 c4e9e0c50487
parent 67472 bddfa23a4ea9
child 67846 bdf6933f7ac9
permissions -rw-r--r--
treat sessions as entities with defining position;
tuned signature;
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@66705
    42
    def make(local_dir: Path, bases: List[Base],
wenzelm@67493
    43
      sessions: List[(String, Position.T)] = Nil,
wenzelm@66705
    44
      theories: List[Document.Node.Name] = Nil,
wenzelm@66705
    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@65499
    50
          (_, name) <- (if (local) base.known.theories_local else base.known.theories).iterator
wenzelm@65463
    51
        } yield name
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@66716
    56
        theories.iterator.filter(name => name.path.canonical_file.toPath.startsWith(local_path))
wenzelm@65463
    57
      }
wenzelm@65427
    58
wenzelm@67219
    59
      val known_sessions =
wenzelm@67493
    60
        (sessions.toMap /: bases)({ case (known, base) => known ++ base.known.sessions })
wenzelm@67219
    61
wenzelm@65461
    62
      val known_theories =
wenzelm@65463
    63
        (Map.empty[String, Document.Node.Name] /: (bases_iterator(false) ++ theories.iterator))({
wenzelm@65461
    64
          case (known, name) =>
wenzelm@65461
    65
            known.get(name.theory) match {
wenzelm@65461
    66
              case Some(name1) if name != name1 =>
wenzelm@65461
    67
                error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
wenzelm@65461
    68
              case _ => known + (name.theory -> name)
wenzelm@65461
    69
            }
wenzelm@65461
    70
          })
wenzelm@65463
    71
      val known_theories_local =
wenzelm@65463
    72
        (Map.empty[String, Document.Node.Name] /:
wenzelm@65463
    73
            (bases_iterator(true) ++ local_theories_iterator))({
wenzelm@65463
    74
          case (known, name) => known + (name.theory -> name)
wenzelm@65463
    75
        })
wenzelm@65461
    76
      val known_files =
wenzelm@65463
    77
        (Map.empty[JFile, List[Document.Node.Name]] /:
wenzelm@65463
    78
            (bases_iterator(true) ++ bases_iterator(false) ++ theories.iterator))({
wenzelm@65461
    79
          case (known, name) =>
wenzelm@66716
    80
            val file = name.path.canonical_file
wenzelm@65463
    81
            val theories1 = known.getOrElse(file, Nil)
wenzelm@65463
    82
            if (theories1.exists(name1 => name.node == name1.node && name.theory == name1.theory))
wenzelm@65461
    83
              known
wenzelm@65463
    84
            else known + (file -> (name :: theories1))
wenzelm@65427
    85
        })
wenzelm@66705
    86
wenzelm@66705
    87
      val known_loaded_files =
wenzelm@66705
    88
        (loaded_files.toMap /: bases.map(base => base.known.loaded_files))(_ ++ _)
wenzelm@66705
    89
wenzelm@67219
    90
      Known(
wenzelm@67219
    91
        known_sessions,
wenzelm@67219
    92
        known_theories, known_theories_local,
wenzelm@66705
    93
        known_files.iterator.map(p => (p._1, p._2.reverse)).toMap,
wenzelm@66705
    94
        known_loaded_files)
wenzelm@65427
    95
    }
wenzelm@64856
    96
  }
wenzelm@64856
    97
wenzelm@65495
    98
  sealed case class Known(
wenzelm@67493
    99
    sessions: Map[String, Position.T] = Map.empty,
wenzelm@65499
   100
    theories: Map[String, Document.Node.Name] = Map.empty,
wenzelm@65499
   101
    theories_local: Map[String, Document.Node.Name] = Map.empty,
wenzelm@66705
   102
    files: Map[JFile, List[Document.Node.Name]] = Map.empty,
wenzelm@66705
   103
    loaded_files: Map[String, List[Path]] = Map.empty)
wenzelm@65355
   104
  {
wenzelm@65495
   105
    def platform_path: Known =
wenzelm@65499
   106
      copy(theories = for ((a, b) <- theories) yield (a, b.map(File.platform_path(_))),
wenzelm@65499
   107
        theories_local = for ((a, b) <- theories_local) yield (a, b.map(File.platform_path(_))),
wenzelm@65499
   108
        files = for ((a, b) <- files) yield (a, b.map(c => c.map(File.platform_path(_)))))
wenzelm@65524
   109
wenzelm@66670
   110
    def standard_path: Known =
wenzelm@66670
   111
      copy(theories = for ((a, b) <- theories) yield (a, b.map(File.standard_path(_))),
wenzelm@66670
   112
        theories_local = for ((a, b) <- theories_local) yield (a, b.map(File.standard_path(_))),
wenzelm@66670
   113
        files = for ((a, b) <- files) yield (a, b.map(c => c.map(File.standard_path(_)))))
wenzelm@66670
   114
wenzelm@66195
   115
    def get_file(file: JFile, bootstrap: Boolean = false): Option[Document.Node.Name] =
wenzelm@66195
   116
    {
wenzelm@66234
   117
      val res = files.getOrElse(File.canonical(file), Nil).headOption
wenzelm@66195
   118
      if (bootstrap) res.map(_.map_theory(Thy_Header.bootstrap_name(_))) else res
wenzelm@66195
   119
    }
wenzelm@65495
   120
  }
wenzelm@65495
   121
wenzelm@65495
   122
  object Base
wenzelm@65495
   123
  {
wenzelm@65495
   124
    def bootstrap(global_theories: Map[String, String]): Base =
wenzelm@65495
   125
      Base(
wenzelm@65495
   126
        global_theories = global_theories,
wenzelm@66720
   127
        overall_syntax = Thy_Header.bootstrap_syntax)
wenzelm@65495
   128
  }
wenzelm@65495
   129
wenzelm@65495
   130
  sealed case class Base(
wenzelm@66573
   131
    pos: Position.T = Position.none,
wenzelm@67472
   132
    doc_names: List[String] = Nil,
wenzelm@65495
   133
    global_theories: Map[String, String] = Map.empty,
wenzelm@66717
   134
    loaded_theories: Graph[String, Outer_Syntax] = Graph.string,
wenzelm@65495
   135
    known: Known = Known.empty,
wenzelm@66720
   136
    overall_syntax: Outer_Syntax = Outer_Syntax.empty,
wenzelm@66744
   137
    imported_sources: List[(Path, SHA1.Digest)] = Nil,
wenzelm@65495
   138
    sources: List[(Path, SHA1.Digest)] = Nil,
wenzelm@66822
   139
    session_graph_display: Graph_Display.Graph = Graph_Display.empty_graph,
wenzelm@66698
   140
    errors: List[String] = Nil,
wenzelm@66698
   141
    imports: Option[Base] = None)
wenzelm@65495
   142
  {
wenzelm@65495
   143
    def platform_path: Base = copy(known = known.platform_path)
wenzelm@66670
   144
    def standard_path: Base = copy(known = known.standard_path)
wenzelm@65463
   145
wenzelm@66967
   146
    def theory_qualifier(name: String): String =
wenzelm@66967
   147
      global_theories.getOrElse(name, Long_Name.qualifier(name))
wenzelm@66967
   148
    def theory_qualifier(name: Document.Node.Name): String = theory_qualifier(name.theory)
wenzelm@66966
   149
wenzelm@66717
   150
    def loaded_theory(name: String): Boolean = loaded_theories.defined(name)
wenzelm@66712
   151
    def loaded_theory(name: Document.Node.Name): Boolean = loaded_theory(name.theory)
wenzelm@65432
   152
wenzelm@66717
   153
    def loaded_theory_syntax(name: String): Option[Outer_Syntax] =
wenzelm@66717
   154
      if (loaded_theory(name)) Some(loaded_theories.get_node(name)) else None
wenzelm@66717
   155
    def loaded_theory_syntax(name: Document.Node.Name): Option[Outer_Syntax] =
wenzelm@66717
   156
      loaded_theory_syntax(name.theory)
wenzelm@66717
   157
wenzelm@66770
   158
    def node_syntax(nodes: Document.Nodes, name: Document.Node.Name): Outer_Syntax =
wenzelm@66770
   159
      nodes(name).syntax orElse loaded_theory_syntax(name) getOrElse overall_syntax
wenzelm@66721
   160
wenzelm@65498
   161
    def known_theory(name: String): Option[Document.Node.Name] =
wenzelm@65499
   162
      known.theories.get(name)
wenzelm@65498
   163
wenzelm@65432
   164
    def dest_known_theories: List[(String, String)] =
wenzelm@65499
   165
      for ((theory, node_name) <- known.theories.toList)
wenzelm@65432
   166
        yield (theory, node_name.node)
wenzelm@66698
   167
wenzelm@66698
   168
    def get_imports: Base = imports getOrElse Base.bootstrap(global_theories)
wenzelm@65355
   169
  }
wenzelm@64856
   170
wenzelm@65495
   171
  sealed case class Deps(session_bases: Map[String, Base], all_known: Known)
wenzelm@65251
   172
  {
wenzelm@65463
   173
    def is_empty: Boolean = session_bases.isEmpty
wenzelm@65463
   174
    def apply(name: String): Base = session_bases(name)
wenzelm@66988
   175
    def get(name: String): Option[Base] = session_bases.get(name)
wenzelm@66744
   176
wenzelm@66744
   177
    def imported_sources(name: String): List[SHA1.Digest] =
wenzelm@66744
   178
      session_bases(name).imported_sources.map(_._2)
wenzelm@66744
   179
wenzelm@66744
   180
    def sources(name: String): List[SHA1.Digest] =
wenzelm@66744
   181
      session_bases(name).sources.map(_._2)
wenzelm@66573
   182
wenzelm@66573
   183
    def errors: List[String] =
wenzelm@66573
   184
      (for {
wenzelm@66573
   185
        (name, base) <- session_bases.iterator
wenzelm@66573
   186
        if base.errors.nonEmpty
wenzelm@66573
   187
      } yield cat_lines(base.errors) +
wenzelm@66573
   188
          "\nThe error(s) above occurred in session " + quote(name) + Position.here(base.pos)
wenzelm@66573
   189
      ).toList
wenzelm@66573
   190
wenzelm@66573
   191
    def check_errors: Deps =
wenzelm@66573
   192
      errors match {
wenzelm@66573
   193
        case Nil => this
wenzelm@66573
   194
        case errs => error(cat_lines(errs))
wenzelm@66573
   195
      }
wenzelm@65251
   196
  }
wenzelm@64856
   197
wenzelm@67052
   198
  def deps(sessions_structure: Structure,
wenzelm@66962
   199
      global_theories: Map[String, String],
wenzelm@65251
   200
      progress: Progress = No_Progress,
wenzelm@65251
   201
      inlined_files: Boolean = false,
wenzelm@65251
   202
      verbose: Boolean = false,
wenzelm@65251
   203
      list_files: Boolean = false,
wenzelm@66962
   204
      check_keywords: Set[String] = Set.empty): Deps =
wenzelm@65375
   205
  {
wenzelm@66743
   206
    var cache_sources = Map.empty[JFile, SHA1.Digest]
wenzelm@66743
   207
    def check_sources(paths: List[Path]): List[(Path, SHA1.Digest)] =
wenzelm@66743
   208
    {
wenzelm@66743
   209
      for {
wenzelm@66743
   210
        path <- paths
wenzelm@66743
   211
        file = path.file
wenzelm@66743
   212
        if cache_sources.isDefinedAt(file) || file.isFile
wenzelm@66743
   213
      }
wenzelm@66743
   214
      yield {
wenzelm@66743
   215
        cache_sources.get(file) match {
wenzelm@66743
   216
          case Some(digest) => (path, digest)
wenzelm@66743
   217
          case None =>
wenzelm@66743
   218
            val digest = SHA1.digest(file)
wenzelm@66743
   219
            cache_sources = cache_sources + (file -> digest)
wenzelm@66743
   220
            (path, digest)
wenzelm@66743
   221
        }
wenzelm@66743
   222
      }
wenzelm@66743
   223
    }
wenzelm@66743
   224
wenzelm@67472
   225
    val doc_names = Doc.doc_names()
wenzelm@67472
   226
wenzelm@65463
   227
    val session_bases =
wenzelm@67024
   228
      (Map.empty[String, Base] /: sessions_structure.imports_topological_order)({
wenzelm@67023
   229
        case (session_bases, session_name) =>
wenzelm@65463
   230
          if (progress.stopped) throw Exn.Interrupt()
wenzelm@65251
   231
wenzelm@67024
   232
          val info = sessions_structure(session_name)
wenzelm@65463
   233
          try {
wenzelm@65496
   234
            val parent_base: Sessions.Base =
wenzelm@65463
   235
              info.parent match {
wenzelm@65475
   236
                case None => Base.bootstrap(global_theories)
wenzelm@65463
   237
                case Some(parent) => session_bases(parent)
wenzelm@65463
   238
              }
wenzelm@65496
   239
            val imports_base: Sessions.Base =
wenzelm@65496
   240
              parent_base.copy(known =
wenzelm@66705
   241
                Known.make(info.dir, parent_base :: info.imports.map(session_bases(_))))
wenzelm@65496
   242
wenzelm@65532
   243
            val resources = new Resources(imports_base)
wenzelm@65251
   244
wenzelm@65463
   245
            if (verbose || list_files) {
wenzelm@65463
   246
              val groups =
wenzelm@65463
   247
                if (info.groups.isEmpty) ""
wenzelm@65463
   248
                else info.groups.mkString(" (", " ", ")")
wenzelm@65519
   249
              progress.echo("Session " + info.chapter + "/" + info.name + groups)
wenzelm@65463
   250
            }
wenzelm@65251
   251
wenzelm@67053
   252
            val dependencies =
wenzelm@66959
   253
              resources.dependencies(
wenzelm@66742
   254
                for { (_, thys) <- info.theories; (thy, pos) <- thys }
wenzelm@66780
   255
                yield (resources.import_name(info.name, info.dir.implode, thy), pos))
wenzelm@65251
   256
wenzelm@67053
   257
            val overall_syntax = dependencies.overall_syntax
wenzelm@65251
   258
wenzelm@67059
   259
            val theory_files = dependencies.theories.map(_.path)
wenzelm@65463
   260
            val loaded_files =
wenzelm@65463
   261
              if (inlined_files) {
wenzelm@66705
   262
                if (Sessions.is_pure(info.name)) {
wenzelm@67097
   263
                  val pure_files = resources.pure_files(overall_syntax, info.dir)
wenzelm@67097
   264
                  dependencies.loaded_files.map({ case (name, files) =>
wenzelm@67097
   265
                    (name, if (name == Thy_Header.PURE) pure_files ::: files else files) })
wenzelm@66705
   266
                }
wenzelm@67053
   267
                else dependencies.loaded_files
wenzelm@65463
   268
              }
wenzelm@65463
   269
              else Nil
wenzelm@65251
   270
wenzelm@66742
   271
            val session_files =
wenzelm@66705
   272
              (theory_files ::: loaded_files.flatMap(_._2) :::
wenzelm@65463
   273
                info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
wenzelm@65463
   274
wenzelm@67053
   275
            val imported_files = if (inlined_files) dependencies.imported_files else Nil
wenzelm@66743
   276
wenzelm@65463
   277
            if (list_files)
wenzelm@66742
   278
              progress.echo(cat_lines(session_files.map(_.implode).sorted.map("  " + _)))
wenzelm@65463
   279
wenzelm@66719
   280
            if (check_keywords.nonEmpty) {
wenzelm@66719
   281
              Check_Keywords.check_keywords(
wenzelm@66720
   282
                progress, overall_syntax.keywords, check_keywords, theory_files)
wenzelm@66719
   283
            }
wenzelm@65251
   284
wenzelm@66822
   285
            val session_graph_display: Graph_Display.Graph =
wenzelm@65507
   286
            {
wenzelm@65507
   287
              def session_node(name: String): Graph_Display.Node =
wenzelm@65507
   288
                Graph_Display.Node("[" + name + "]", "session." + name)
wenzelm@65507
   289
wenzelm@65507
   290
              def node(name: Document.Node.Name): Graph_Display.Node =
wenzelm@65507
   291
              {
wenzelm@66966
   292
                val qualifier = imports_base.theory_qualifier(name)
wenzelm@66780
   293
                if (qualifier == info.name)
wenzelm@65507
   294
                  Graph_Display.Node(name.theory_base_name, "theory." + name.theory)
wenzelm@65528
   295
                else session_node(qualifier)
wenzelm@65507
   296
              }
wenzelm@65507
   297
wenzelm@65507
   298
              val imports_subgraph =
wenzelm@67024
   299
                sessions_structure.imports_graph.
wenzelm@67024
   300
                  restrict(sessions_structure.imports_graph.all_preds(info.deps).toSet)
wenzelm@65507
   301
wenzelm@65507
   302
              val graph0 =
wenzelm@65507
   303
                (Graph_Display.empty_graph /: imports_subgraph.topological_order)(
wenzelm@65507
   304
                  { case (g, session) =>
wenzelm@65507
   305
                      val a = session_node(session)
wenzelm@65507
   306
                      val bs = imports_subgraph.imm_preds(session).toList.map(session_node(_))
wenzelm@65507
   307
                      ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
wenzelm@65507
   308
wenzelm@67053
   309
              (graph0 /: dependencies.entries)(
wenzelm@66714
   310
                { case (g, entry) =>
wenzelm@66714
   311
                    val a = node(entry.name)
wenzelm@65507
   312
                    val bs =
wenzelm@66714
   313
                      entry.header.imports.map({ case (name, _) => node(name) }).
wenzelm@65507
   314
                        filterNot(_ == a)
wenzelm@65507
   315
                    ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
wenzelm@65507
   316
            }
wenzelm@65507
   317
wenzelm@66705
   318
            val known =
wenzelm@66705
   319
              Known.make(info.dir, List(imports_base),
wenzelm@67493
   320
                sessions = List(info.name -> info.pos),
wenzelm@67059
   321
                theories = dependencies.theories,
wenzelm@66705
   322
                loaded_files = loaded_files)
wenzelm@66705
   323
wenzelm@66743
   324
            val sources_errors =
wenzelm@66743
   325
              for (p <- session_files if !p.is_file) yield "No such file: " + p
wenzelm@66606
   326
wenzelm@67297
   327
            val bibtex_errors =
wenzelm@67297
   328
              try { info.bibtex_entries; Nil }
wenzelm@67297
   329
              catch { case ERROR(msg) => List(msg) }
wenzelm@67297
   330
wenzelm@65463
   331
            val base =
wenzelm@66573
   332
              Base(
wenzelm@66573
   333
                pos = info.pos,
wenzelm@67472
   334
                doc_names = doc_names,
wenzelm@65540
   335
                global_theories = global_theories,
wenzelm@67053
   336
                loaded_theories = dependencies.loaded_theories,
wenzelm@66705
   337
                known = known,
wenzelm@66720
   338
                overall_syntax = overall_syntax,
wenzelm@66744
   339
                imported_sources = check_sources(imported_files),
wenzelm@66743
   340
                sources = check_sources(session_files),
wenzelm@66822
   341
                session_graph_display = session_graph_display,
wenzelm@67297
   342
                errors = dependencies.errors ::: sources_errors ::: bibtex_errors,
wenzelm@66698
   343
                imports = Some(imports_base))
wenzelm@65251
   344
wenzelm@65519
   345
            session_bases + (info.name -> base)
wenzelm@65463
   346
          }
wenzelm@65463
   347
          catch {
wenzelm@65463
   348
            case ERROR(msg) =>
wenzelm@65463
   349
              cat_error(msg, "The error(s) above occurred in session " +
wenzelm@65519
   350
                quote(info.name) + Position.here(info.pos))
wenzelm@65463
   351
          }
wenzelm@65463
   352
      })
wenzelm@65251
   353
wenzelm@66705
   354
    Deps(session_bases, Known.make(Path.current, session_bases.toList.map(_._2)))
wenzelm@65375
   355
  }
wenzelm@65251
   356
wenzelm@66963
   357
wenzelm@66963
   358
  /* base info */
wenzelm@66963
   359
wenzelm@66974
   360
  sealed case class Base_Info(
wenzelm@66974
   361
    session: String,
wenzelm@67052
   362
    sessions_structure: Structure,
wenzelm@66975
   363
    errors: List[String],
wenzelm@66974
   364
    base: Base,
wenzelm@66974
   365
    infos: List[Info])
wenzelm@66974
   366
  {
wenzelm@66974
   367
    def check_base: Base = if (errors.isEmpty) base else error(cat_lines(errors))
wenzelm@66974
   368
  }
wenzelm@66974
   369
wenzelm@66976
   370
  def base_info(options: Options, session: String,
wenzelm@65428
   371
    dirs: List[Path] = Nil,
wenzelm@66988
   372
    ancestor_session: Option[String] = None,
wenzelm@66968
   373
    all_known: Boolean = false,
wenzelm@66987
   374
    focus_session: Boolean = false,
wenzelm@66968
   375
    required_session: Boolean = false): Base_Info =
wenzelm@65251
   376
  {
wenzelm@67026
   377
    val full_sessions = load_structure(options, dirs = dirs)
wenzelm@65428
   378
    val global_theories = full_sessions.global_theories
wenzelm@65375
   379
wenzelm@66990
   380
    val selected_sessions =
wenzelm@67025
   381
      full_sessions.selection(Selection(sessions = session :: ancestor_session.toList))
wenzelm@66974
   382
    val info = selected_sessions(session)
wenzelm@66988
   383
    val ancestor = ancestor_session orElse info.parent
wenzelm@66963
   384
wenzelm@66974
   385
    val (session1, infos1) =
wenzelm@66988
   386
      if (required_session && ancestor.isDefined) {
wenzelm@66974
   387
        val deps = Sessions.deps(selected_sessions, global_theories)
wenzelm@66974
   388
        val base = deps(session)
wenzelm@66968
   389
wenzelm@66988
   390
        val ancestor_loaded =
wenzelm@66988
   391
          deps.get(ancestor.get) match {
wenzelm@66990
   392
            case Some(ancestor_base)
wenzelm@66990
   393
            if !selected_sessions.imports_requirements(List(ancestor.get)).contains(session) =>
wenzelm@66990
   394
              ancestor_base.loaded_theories.defined(_)
wenzelm@66990
   395
            case _ =>
wenzelm@66988
   396
              error("Bad ancestor " + quote(ancestor.get) + " for session " + quote(session))
wenzelm@66988
   397
          }
wenzelm@66974
   398
wenzelm@66974
   399
        val required_theories =
wenzelm@66968
   400
          for {
wenzelm@66968
   401
            thy <- base.loaded_theories.keys
wenzelm@66988
   402
            if !ancestor_loaded(thy) && base.theory_qualifier(thy) != session
wenzelm@66968
   403
          }
wenzelm@66974
   404
          yield thy
wenzelm@66968
   405
wenzelm@66988
   406
        if (required_theories.isEmpty) (ancestor.get, Nil)
wenzelm@66968
   407
        else {
wenzelm@66988
   408
          val other_name = info.name + "_base(" + ancestor.get + ")"
wenzelm@66974
   409
          (other_name,
wenzelm@66968
   410
            List(
wenzelm@66968
   411
              make_info(info.options,
wenzelm@66968
   412
                dir_selected = false,
wenzelm@66968
   413
                dir = info.dir,
wenzelm@66968
   414
                chapter = info.chapter,
wenzelm@66968
   415
                Session_Entry(
wenzelm@66968
   416
                  pos = info.pos,
wenzelm@66968
   417
                  name = other_name,
wenzelm@66968
   418
                  groups = info.groups,
wenzelm@66968
   419
                  path = ".",
wenzelm@66988
   420
                  parent = ancestor,
wenzelm@66974
   421
                  description = "Required theory imports from other sessions",
wenzelm@66968
   422
                  options = Nil,
wenzelm@66991
   423
                  imports = info.deps,
wenzelm@66974
   424
                  theories = List((Nil, required_theories.map(thy => ((thy, Position.none), false)))),
wenzelm@66974
   425
                  document_files = Nil))))
wenzelm@66968
   426
        }
wenzelm@66968
   427
      }
wenzelm@66974
   428
      else (session, Nil)
wenzelm@66968
   429
wenzelm@66974
   430
    val full_sessions1 =
wenzelm@66974
   431
      if (infos1.isEmpty) full_sessions
wenzelm@67026
   432
      else load_structure(options, dirs = dirs, infos = infos1)
wenzelm@66987
   433
wenzelm@66987
   434
    val select_sessions1 =
wenzelm@66987
   435
      if (focus_session) full_sessions1.imports_descendants(List(session1))
wenzelm@66987
   436
      else List(session1)
wenzelm@66987
   437
    val selected_sessions1 =
wenzelm@67025
   438
      full_sessions1.selection(Selection(sessions = select_sessions1))
wenzelm@66964
   439
wenzelm@66974
   440
    val sessions1 = if (all_known) full_sessions1 else selected_sessions1
wenzelm@66974
   441
    val deps1 = Sessions.deps(sessions1, global_theories)
wenzelm@66974
   442
    val base1 = if (all_known) deps1(session1).copy(known = deps1.all_known) else deps1(session1)
wenzelm@66964
   443
wenzelm@66975
   444
    Base_Info(session1, sessions1, deps1.errors, base1, infos1)
wenzelm@65251
   445
  }
wenzelm@65251
   446
wenzelm@65251
   447
wenzelm@65415
   448
  /* cumulative session info */
wenzelm@62631
   449
wenzelm@62631
   450
  sealed case class Info(
wenzelm@65519
   451
    name: String,
wenzelm@62631
   452
    chapter: String,
wenzelm@66829
   453
    dir_selected: Boolean,
wenzelm@62631
   454
    pos: Position.T,
wenzelm@62631
   455
    groups: List[String],
wenzelm@62631
   456
    dir: Path,
wenzelm@62631
   457
    parent: Option[String],
wenzelm@62631
   458
    description: String,
wenzelm@62631
   459
    options: Options,
wenzelm@65420
   460
    imports: List[String],
wenzelm@65517
   461
    theories: List[(Options, List[(String, Position.T)])],
wenzelm@65377
   462
    global_theories: List[String],
wenzelm@62631
   463
    document_files: List[(Path, Path)],
wenzelm@62631
   464
    meta_digest: SHA1.Digest)
wenzelm@62631
   465
  {
wenzelm@66828
   466
    def deps: List[String] = parent.toList ::: imports
wenzelm@66828
   467
wenzelm@62631
   468
    def timeout: Time = Time.seconds(options.real("timeout") * options.real("timeout_scale"))
wenzelm@67297
   469
wenzelm@67297
   470
    def bibtex_entries: List[Text.Info[String]] =
wenzelm@67297
   471
      (for {
wenzelm@67297
   472
        (document_dir, file) <- document_files.iterator
wenzelm@67297
   473
        if Bibtex.is_bibtex(file.base_name)
wenzelm@67297
   474
        info <- Bibtex.entries(File.read(dir + document_dir + file)).iterator
wenzelm@67297
   475
      } yield info).toList
wenzelm@62631
   476
  }
wenzelm@62631
   477
wenzelm@66967
   478
  def make_info(options: Options, dir_selected: Boolean, dir: Path, chapter: String,
wenzelm@66967
   479
    entry: Session_Entry): Info =
wenzelm@66967
   480
  {
wenzelm@66967
   481
    try {
wenzelm@66967
   482
      val name = entry.name
wenzelm@66967
   483
wenzelm@67284
   484
      if (exclude_session(name)) error("Bad session name")
wenzelm@66967
   485
      if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
wenzelm@66967
   486
      if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
wenzelm@66967
   487
wenzelm@66967
   488
      val session_options = options ++ entry.options
wenzelm@66967
   489
wenzelm@66967
   490
      val theories =
wenzelm@67216
   491
        entry.theories.map({ case (opts, thys) =>
wenzelm@67216
   492
          (session_options ++ opts,
wenzelm@67216
   493
            thys.map({ case ((thy, pos), _) =>
wenzelm@67284
   494
              if (exclude_theory(thy))
wenzelm@67216
   495
                error("Bad theory name " + quote(thy) + Position.here(pos))
wenzelm@67216
   496
              else (thy, pos) })) })
wenzelm@66967
   497
wenzelm@66967
   498
      val global_theories =
wenzelm@66967
   499
        for { (_, thys) <- entry.theories; ((thy, pos), global) <- thys if global }
wenzelm@66967
   500
        yield {
wenzelm@66967
   501
          val thy_name = Path.explode(thy).expand.base_name
wenzelm@66967
   502
          if (Long_Name.is_qualified(thy_name))
wenzelm@66967
   503
            error("Bad qualified name for global theory " +
wenzelm@66967
   504
              quote(thy_name) + Position.here(pos))
wenzelm@66967
   505
          else thy_name
wenzelm@66967
   506
        }
wenzelm@66967
   507
wenzelm@66967
   508
      val conditions =
wenzelm@66967
   509
        theories.flatMap(thys => space_explode(',', thys._1.string("condition"))).distinct.sorted.
wenzelm@66967
   510
          map(x => (x, Isabelle_System.getenv(x) != ""))
wenzelm@66967
   511
wenzelm@66967
   512
      val document_files =
wenzelm@66967
   513
        entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
wenzelm@66967
   514
wenzelm@66967
   515
      val meta_digest =
wenzelm@66967
   516
        SHA1.digest((name, chapter, entry.parent, entry.options, entry.imports,
wenzelm@66967
   517
          entry.theories_no_position, conditions, entry.document_files).toString)
wenzelm@66967
   518
wenzelm@66967
   519
      Info(name, chapter, dir_selected, entry.pos, entry.groups,
wenzelm@66967
   520
        dir + Path.explode(entry.path), entry.parent, entry.description, session_options,
wenzelm@66967
   521
        entry.imports, theories, global_theories, document_files, meta_digest)
wenzelm@66967
   522
    }
wenzelm@66967
   523
    catch {
wenzelm@66967
   524
      case ERROR(msg) =>
wenzelm@66967
   525
        error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@66967
   526
          quote(entry.name) + Position.here(entry.pos))
wenzelm@66967
   527
    }
wenzelm@66967
   528
  }
wenzelm@66967
   529
wenzelm@65419
   530
  object Selection
wenzelm@65419
   531
  {
wenzelm@65422
   532
    val empty: Selection = Selection()
wenzelm@65525
   533
    val all: Selection = Selection(all_sessions = true)
wenzelm@65419
   534
  }
wenzelm@65419
   535
wenzelm@65419
   536
  sealed case class Selection(
wenzelm@65419
   537
    requirements: Boolean = false,
wenzelm@65419
   538
    all_sessions: Boolean = false,
wenzelm@66737
   539
    base_sessions: List[String] = Nil,
wenzelm@65419
   540
    exclude_session_groups: List[String] = Nil,
wenzelm@65419
   541
    exclude_sessions: List[String] = Nil,
wenzelm@65419
   542
    session_groups: List[String] = Nil,
wenzelm@65419
   543
    sessions: List[String] = Nil)
wenzelm@65419
   544
  {
wenzelm@66736
   545
    def ++ (other: Selection): Selection =
wenzelm@65422
   546
      Selection(
wenzelm@65422
   547
        requirements = requirements || other.requirements,
wenzelm@65422
   548
        all_sessions = all_sessions || other.all_sessions,
wenzelm@66737
   549
        base_sessions = Library.merge(base_sessions, other.base_sessions),
wenzelm@66736
   550
        exclude_session_groups = Library.merge(exclude_session_groups, other.exclude_session_groups),
wenzelm@66736
   551
        exclude_sessions = Library.merge(exclude_sessions, other.exclude_sessions),
wenzelm@66736
   552
        session_groups = Library.merge(session_groups, other.session_groups),
wenzelm@66736
   553
        sessions = Library.merge(sessions, other.sessions))
wenzelm@67029
   554
wenzelm@67029
   555
    def selected(graph: Graph[String, Info]): List[String] =
wenzelm@67029
   556
    {
wenzelm@67029
   557
      val select_group = session_groups.toSet
wenzelm@67029
   558
      val select_session = sessions.toSet ++ graph.all_succs(base_sessions)
wenzelm@67029
   559
wenzelm@67029
   560
      val selected0 =
wenzelm@67029
   561
        if (all_sessions) graph.keys
wenzelm@67029
   562
        else {
wenzelm@67029
   563
          (for {
wenzelm@67029
   564
            (name, (info, _)) <- graph.iterator
wenzelm@67029
   565
            if info.dir_selected || select_session(name) ||
wenzelm@67029
   566
              graph.get_node(name).groups.exists(select_group)
wenzelm@67029
   567
          } yield name).toList
wenzelm@67029
   568
        }
wenzelm@67029
   569
wenzelm@67029
   570
      if (requirements) (graph.all_preds(selected0).toSet -- selected0).toList
wenzelm@67029
   571
      else selected0
wenzelm@67029
   572
    }
wenzelm@67029
   573
wenzelm@67029
   574
    def excluded(graph: Graph[String, Info]): List[String] =
wenzelm@67029
   575
    {
wenzelm@67029
   576
      val exclude_group = exclude_session_groups.toSet
wenzelm@67029
   577
      val exclude_group_sessions =
wenzelm@67029
   578
        (for {
wenzelm@67029
   579
          (name, (info, _)) <- graph.iterator
wenzelm@67029
   580
          if graph.get_node(name).groups.exists(exclude_group)
wenzelm@67029
   581
        } yield name).toList
wenzelm@67029
   582
      graph.all_succs(exclude_group_sessions ::: exclude_sessions)
wenzelm@67029
   583
    }
wenzelm@65419
   584
  }
wenzelm@65419
   585
wenzelm@67052
   586
  def make(infos: List[Info]): Structure =
wenzelm@62631
   587
  {
wenzelm@65420
   588
    def add_edges(graph: Graph[String, Info], kind: String, edges: Info => Traversable[String])
wenzelm@65420
   589
      : Graph[String, Info] =
wenzelm@65420
   590
    {
wenzelm@65420
   591
      def add_edge(pos: Position.T, name: String, g: Graph[String, Info], parent: String) =
wenzelm@65420
   592
      {
wenzelm@65420
   593
        if (!g.defined(parent))
wenzelm@65420
   594
          error("Bad " + kind + " session " + quote(parent) + " for " +
wenzelm@65420
   595
            quote(name) + Position.here(pos))
wenzelm@65420
   596
wenzelm@65420
   597
        try { g.add_edge_acyclic(parent, name) }
wenzelm@65420
   598
        catch {
wenzelm@65420
   599
          case exn: Graph.Cycles[_] =>
wenzelm@65420
   600
            error(cat_lines(exn.cycles.map(cycle =>
wenzelm@65420
   601
              "Cyclic session dependency of " +
wenzelm@65420
   602
                cycle.map(c => quote(c.toString)).mkString(" via "))) + Position.here(pos))
wenzelm@65420
   603
        }
wenzelm@65420
   604
      }
wenzelm@65420
   605
      (graph /: graph.iterator) {
wenzelm@65420
   606
        case (g, (name, (info, _))) => (g /: edges(info))(add_edge(info.pos, name, _, _))
wenzelm@65420
   607
      }
wenzelm@65420
   608
    }
wenzelm@65420
   609
wenzelm@65420
   610
    val graph0 =
wenzelm@65415
   611
      (Graph.string[Info] /: infos) {
wenzelm@66960
   612
        case (graph, info) =>
wenzelm@66960
   613
          if (graph.defined(info.name))
wenzelm@66960
   614
            error("Duplicate session " + quote(info.name) + Position.here(info.pos) +
wenzelm@66960
   615
              Position.here(graph.get_node(info.name).pos))
wenzelm@66960
   616
          else graph.new_node(info.name, info)
wenzelm@65415
   617
      }
wenzelm@65420
   618
    val graph1 = add_edges(graph0, "parent", _.parent)
wenzelm@65420
   619
    val graph2 = add_edges(graph1, "imports", _.imports)
wenzelm@62631
   620
wenzelm@67052
   621
    new Structure(graph1, graph2)
wenzelm@62631
   622
  }
wenzelm@62631
   623
wenzelm@67052
   624
  final class Structure private[Sessions](
wenzelm@65420
   625
      val build_graph: Graph[String, Info],
wenzelm@65420
   626
      val imports_graph: Graph[String, Info])
wenzelm@62631
   627
  {
wenzelm@66823
   628
    def build_graph_display: Graph_Display.Graph = Graph_Display.make_graph(build_graph)
wenzelm@66823
   629
    def imports_graph_display: Graph_Display.Graph = Graph_Display.make_graph(imports_graph)
wenzelm@66823
   630
wenzelm@67025
   631
    def defined(name: String): Boolean = imports_graph.defined(name)
wenzelm@65420
   632
    def apply(name: String): Info = imports_graph.get_node(name)
wenzelm@67025
   633
    def get(name: String): Option[Info] = if (defined(name)) Some(apply(name)) else None
wenzelm@62631
   634
wenzelm@65457
   635
    def global_theories: Map[String, String] =
wenzelm@65490
   636
      (Thy_Header.bootstrap_global_theories.toMap /:
wenzelm@65424
   637
        (for {
wenzelm@65519
   638
          (_, (info, _)) <- imports_graph.iterator
wenzelm@65519
   639
          thy <- info.global_theories.iterator }
wenzelm@65519
   640
         yield (thy, info)))({
wenzelm@65519
   641
            case (global, (thy, info)) =>
wenzelm@66780
   642
              val qualifier = info.name
wenzelm@65457
   643
              global.get(thy) match {
wenzelm@65457
   644
                case Some(qualifier1) if qualifier != qualifier1 =>
wenzelm@65457
   645
                  error("Duplicate global theory " + quote(thy) + Position.here(info.pos))
wenzelm@65457
   646
                case _ => global + (thy -> qualifier)
wenzelm@65457
   647
              }
wenzelm@65457
   648
          })
wenzelm@65375
   649
wenzelm@67052
   650
    def selection(sel: Selection): Structure =
wenzelm@62631
   651
    {
wenzelm@67025
   652
      val bad_sessions =
wenzelm@67025
   653
        SortedSet((sel.base_sessions ::: sel.exclude_sessions ::: sel.sessions).
wenzelm@67025
   654
          filterNot(defined(_)): _*).toList
wenzelm@67025
   655
      if (bad_sessions.nonEmpty)
wenzelm@67025
   656
        error("Undefined session(s): " + commas_quote(bad_sessions))
wenzelm@67025
   657
wenzelm@67029
   658
      val excluded = sel.excluded(build_graph).toSet
wenzelm@67027
   659
wenzelm@67025
   660
      def restrict(graph: Graph[String, Info]): Graph[String, Info] =
wenzelm@67025
   661
      {
wenzelm@67029
   662
        val sessions = graph.all_preds(sel.selected(graph)).filterNot(excluded)
wenzelm@67029
   663
        graph.restrict(graph.all_preds(sessions).toSet)
wenzelm@67025
   664
      }
wenzelm@67025
   665
wenzelm@67052
   666
      new Structure(restrict(build_graph), restrict(imports_graph))
wenzelm@62631
   667
    }
wenzelm@62631
   668
wenzelm@67029
   669
    def build_selection(sel: Selection): List[String] = sel.selected(build_graph)
wenzelm@67029
   670
    def build_descendants(ss: List[String]): List[String] = build_graph.all_succs(ss)
wenzelm@67029
   671
    def build_requirements(ss: List[String]): List[String] = build_graph.all_preds(ss).reverse
wenzelm@67029
   672
    def build_topological_order: List[String] = build_graph.topological_order
wenzelm@62631
   673
wenzelm@67029
   674
    def imports_selection(sel: Selection): List[String] = sel.selected(imports_graph)
wenzelm@67029
   675
    def imports_descendants(ss: List[String]): List[String] = imports_graph.all_succs(ss)
wenzelm@67029
   676
    def imports_requirements(ss: List[String]): List[String] = imports_graph.all_preds(ss).reverse
wenzelm@67029
   677
    def imports_topological_order: List[String] = imports_graph.topological_order
wenzelm@65420
   678
wenzelm@65420
   679
    override def toString: String =
wenzelm@67052
   680
      imports_graph.keys_iterator.mkString("Sessions.Structure(", ", ", ")")
wenzelm@62631
   681
  }
wenzelm@62631
   682
wenzelm@62631
   683
wenzelm@62631
   684
  /* parser */
wenzelm@62631
   685
wenzelm@62864
   686
  val ROOT = Path.explode("ROOT")
wenzelm@62864
   687
  val ROOTS = Path.explode("ROOTS")
wenzelm@62864
   688
wenzelm@62631
   689
  private val CHAPTER = "chapter"
wenzelm@62631
   690
  private val SESSION = "session"
wenzelm@62631
   691
  private val IN = "in"
wenzelm@62631
   692
  private val DESCRIPTION = "description"
wenzelm@62631
   693
  private val OPTIONS = "options"
wenzelm@65420
   694
  private val SESSIONS = "sessions"
wenzelm@62631
   695
  private val THEORIES = "theories"
wenzelm@65377
   696
  private val GLOBAL = "global"
wenzelm@62631
   697
  private val DOCUMENT_FILES = "document_files"
wenzelm@62631
   698
wenzelm@67004
   699
  val root_syntax =
wenzelm@67004
   700
    Outer_Syntax.empty + "(" + ")" + "+" + "," + "=" + "[" + "]" + GLOBAL + IN +
wenzelm@63443
   701
      (CHAPTER, Keyword.THY_DECL) +
wenzelm@63443
   702
      (SESSION, Keyword.THY_DECL) +
wenzelm@63443
   703
      (DESCRIPTION, Keyword.QUASI_COMMAND) +
wenzelm@63443
   704
      (OPTIONS, Keyword.QUASI_COMMAND) +
wenzelm@65420
   705
      (SESSIONS, Keyword.QUASI_COMMAND) +
wenzelm@63443
   706
      (THEORIES, Keyword.QUASI_COMMAND) +
wenzelm@63443
   707
      (DOCUMENT_FILES, Keyword.QUASI_COMMAND)
wenzelm@62631
   708
wenzelm@66818
   709
  abstract class Entry
wenzelm@66818
   710
  sealed case class Chapter(name: String) extends Entry
wenzelm@66818
   711
  sealed case class Session_Entry(
wenzelm@66818
   712
    pos: Position.T,
wenzelm@66818
   713
    name: String,
wenzelm@66818
   714
    groups: List[String],
wenzelm@66818
   715
    path: String,
wenzelm@66818
   716
    parent: Option[String],
wenzelm@66818
   717
    description: String,
wenzelm@66818
   718
    options: List[Options.Spec],
wenzelm@66818
   719
    imports: List[String],
wenzelm@66818
   720
    theories: List[(List[Options.Spec], List[((String, Position.T), Boolean)])],
wenzelm@66818
   721
    document_files: List[(String, String)]) extends Entry
wenzelm@66818
   722
  {
wenzelm@66818
   723
    def theories_no_position: List[(List[Options.Spec], List[(String, Boolean)])] =
wenzelm@66818
   724
      theories.map({ case (a, b) => (a, b.map({ case ((c, _), d) => (c, d) })) })
wenzelm@66818
   725
  }
wenzelm@66818
   726
wenzelm@62968
   727
  private object Parser extends Parse.Parser with Options.Parser
wenzelm@62631
   728
  {
wenzelm@62631
   729
    private val chapter: Parser[Chapter] =
wenzelm@62631
   730
    {
wenzelm@62631
   731
      val chapter_name = atom("chapter name", _.is_name)
wenzelm@62631
   732
wenzelm@62631
   733
      command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
wenzelm@62631
   734
    }
wenzelm@62631
   735
wenzelm@62631
   736
    private val session_entry: Parser[Session_Entry] =
wenzelm@62631
   737
    {
wenzelm@62631
   738
      val option =
wenzelm@67210
   739
        option_name ~ opt($$$("=") ~! option_value ^^ { case _ ~ x => x }) ^^
wenzelm@67210
   740
          { case x ~ y => (x, y) }
wenzelm@62631
   741
      val options = $$$("[") ~> rep1sep(option, $$$(",")) <~ $$$("]")
wenzelm@62631
   742
wenzelm@65377
   743
      val global =
wenzelm@65377
   744
        ($$$("(") ~! $$$(GLOBAL) ~ $$$(")")) ^^ { case _ => true } | success(false)
wenzelm@65377
   745
wenzelm@65377
   746
      val theory_entry =
wenzelm@65517
   747
        position(theory_name) ~ global ^^ { case x ~ y => (x, y) }
wenzelm@65377
   748
wenzelm@62631
   749
      val theories =
wenzelm@65377
   750
        $$$(THEORIES) ~!
wenzelm@66970
   751
          ((options | success(Nil)) ~ rep1(theory_entry)) ^^
wenzelm@65377
   752
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@62631
   753
wenzelm@62631
   754
      val document_files =
wenzelm@62631
   755
        $$$(DOCUMENT_FILES) ~!
wenzelm@67210
   756
          (($$$("(") ~! ($$$(IN) ~ path ~ $$$(")")) ^^
wenzelm@67210
   757
              { case _ ~ (_ ~ x ~ _) => x } | success("document")) ~
wenzelm@62631
   758
            rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
wenzelm@62631
   759
wenzelm@62631
   760
      command(SESSION) ~!
wenzelm@62631
   761
        (position(session_name) ~
wenzelm@62631
   762
          (($$$("(") ~! (rep1(name) <~ $$$(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   763
          (($$$(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
wenzelm@62631
   764
          ($$$("=") ~!
wenzelm@62631
   765
            (opt(session_name ~! $$$("+") ^^ { case x ~ _ => x }) ~
wenzelm@62631
   766
              (($$$(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
wenzelm@62631
   767
              (($$$(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@66970
   768
              (($$$(SESSIONS) ~! rep1(session_name)  ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@66970
   769
              rep(theories) ~
wenzelm@62631
   770
              (rep(document_files) ^^ (x => x.flatten))))) ^^
wenzelm@66759
   771
        { case _ ~ ((a, pos) ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i))) =>
wenzelm@66759
   772
            Session_Entry(pos, a, b, c, d, e, f, g, h, i) }
wenzelm@62631
   773
    }
wenzelm@62631
   774
wenzelm@66819
   775
    def parse_root(path: Path): List[Entry] =
wenzelm@62631
   776
    {
wenzelm@66764
   777
      val toks = Token.explode(root_syntax.keywords, File.read(path))
wenzelm@66764
   778
      val start = Token.Pos.file(path.implode)
wenzelm@62631
   779
wenzelm@66764
   780
      parse_all(rep(chapter | session_entry), Token.reader(toks, start)) match {
wenzelm@66818
   781
        case Success(result, _) => result
wenzelm@66764
   782
        case bad => error(bad.toString)
wenzelm@62631
   783
      }
wenzelm@62631
   784
    }
wenzelm@62631
   785
  }
wenzelm@62631
   786
wenzelm@66819
   787
  def parse_root(path: Path): List[Entry] = Parser.parse_root(path)
wenzelm@66819
   788
wenzelm@66819
   789
  def parse_root_entries(path: Path): List[Session_Entry] =
wenzelm@66819
   790
    for (entry <- Parser.parse_root(path) if entry.isInstanceOf[Session_Entry])
wenzelm@66819
   791
    yield entry.asInstanceOf[Session_Entry]
wenzelm@66818
   792
wenzelm@66960
   793
  def read_root(options: Options, select: Boolean, path: Path): List[Info] =
wenzelm@66818
   794
  {
wenzelm@66818
   795
    var entry_chapter = "Unsorted"
wenzelm@66960
   796
    val infos = new mutable.ListBuffer[Info]
wenzelm@66819
   797
    parse_root(path).foreach {
wenzelm@66818
   798
      case Chapter(name) => entry_chapter = name
wenzelm@66967
   799
      case entry: Session_Entry =>
wenzelm@66967
   800
        infos += make_info(options, select, path.dir, entry_chapter, entry)
wenzelm@66818
   801
    }
wenzelm@66818
   802
    infos.toList
wenzelm@66818
   803
  }
wenzelm@66818
   804
wenzelm@66818
   805
  def parse_roots(roots: Path): List[String] =
wenzelm@66818
   806
  {
wenzelm@66818
   807
    for {
wenzelm@66818
   808
      line <- split_lines(File.read(roots))
wenzelm@66818
   809
      if !(line == "" || line.startsWith("#"))
wenzelm@66818
   810
    } yield line
wenzelm@66818
   811
  }
wenzelm@66818
   812
wenzelm@62631
   813
wenzelm@62635
   814
  /* load sessions from certain directories */
wenzelm@62631
   815
wenzelm@62631
   816
  private def is_session_dir(dir: Path): Boolean =
wenzelm@62631
   817
    (dir + ROOT).is_file || (dir + ROOTS).is_file
wenzelm@62631
   818
wenzelm@62631
   819
  private def check_session_dir(dir: Path): Path =
wenzelm@65468
   820
    if (is_session_dir(dir)) File.pwd() + dir.expand
wenzelm@62631
   821
    else error("Bad session root directory: " + dir.toString)
wenzelm@62631
   822
wenzelm@65561
   823
  def directories(dirs: List[Path], select_dirs: List[Path]): List[(Boolean, Path)] =
wenzelm@65561
   824
  {
wenzelm@65561
   825
    val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
wenzelm@65561
   826
    (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _))
wenzelm@65561
   827
  }
wenzelm@65561
   828
wenzelm@67026
   829
  def load_structure(options: Options,
wenzelm@66968
   830
    dirs: List[Path] = Nil,
wenzelm@66968
   831
    select_dirs: List[Path] = Nil,
wenzelm@67052
   832
    infos: List[Info] = Nil): Structure =
wenzelm@62631
   833
  {
wenzelm@66764
   834
    def load_dir(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@62635
   835
      load_root(select, dir) ::: load_roots(select, dir)
wenzelm@62631
   836
wenzelm@66764
   837
    def load_root(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@66764
   838
    {
wenzelm@66764
   839
      val root = dir + ROOT
wenzelm@66764
   840
      if (root.is_file) List((select, root)) else Nil
wenzelm@66764
   841
    }
wenzelm@62631
   842
wenzelm@66764
   843
    def load_roots(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@62631
   844
    {
wenzelm@62631
   845
      val roots = dir + ROOTS
wenzelm@62631
   846
      if (roots.is_file) {
wenzelm@62631
   847
        for {
wenzelm@66818
   848
          entry <- parse_roots(roots)
wenzelm@62631
   849
          dir1 =
wenzelm@66818
   850
            try { check_session_dir(dir + Path.explode(entry)) }
wenzelm@62631
   851
            catch {
wenzelm@62631
   852
              case ERROR(msg) =>
wenzelm@62631
   853
                error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
wenzelm@62631
   854
            }
wenzelm@66764
   855
          res <- load_dir(select, dir1)
wenzelm@66764
   856
        } yield res
wenzelm@62631
   857
      }
wenzelm@62631
   858
      else Nil
wenzelm@62631
   859
    }
wenzelm@62631
   860
wenzelm@66764
   861
    val roots =
wenzelm@62631
   862
      for {
wenzelm@65561
   863
        (select, dir) <- directories(dirs, select_dirs)
wenzelm@66764
   864
        res <- load_dir(select, check_session_dir(dir))
wenzelm@66764
   865
      } yield res
wenzelm@66764
   866
wenzelm@66764
   867
    val unique_roots =
wenzelm@66764
   868
      ((Map.empty[JFile, (Boolean, Path)] /: roots) { case (m, (select, path)) =>
wenzelm@66764
   869
        val file = path.canonical_file
wenzelm@66764
   870
        m.get(file) match {
wenzelm@66764
   871
          case None => m + (file -> (select, path))
wenzelm@66764
   872
          case Some((select1, path1)) => m + (file -> (select1 || select, path1))
wenzelm@66764
   873
        }
wenzelm@66764
   874
      }).toList.map(_._2)
wenzelm@66764
   875
wenzelm@66968
   876
    make(unique_roots.flatMap(p => read_root(options, p._1, p._2)) ::: infos)
wenzelm@62631
   877
  }
wenzelm@62632
   878
wenzelm@62632
   879
wenzelm@62637
   880
wenzelm@62704
   881
  /** heap file with SHA1 digest **/
wenzelm@62704
   882
wenzelm@62704
   883
  private val sha1_prefix = "SHA1:"
wenzelm@62704
   884
wenzelm@62704
   885
  def read_heap_digest(heap: Path): Option[String] =
wenzelm@62704
   886
  {
wenzelm@62704
   887
    if (heap.is_file) {
wenzelm@62704
   888
      val file = FileChannel.open(heap.file.toPath, StandardOpenOption.READ)
wenzelm@62704
   889
      try {
wenzelm@62704
   890
        val len = file.size
wenzelm@62704
   891
        val n = sha1_prefix.length + SHA1.digest_length
wenzelm@62704
   892
        if (len >= n) {
wenzelm@62704
   893
          file.position(len - n)
wenzelm@62704
   894
wenzelm@62704
   895
          val buf = ByteBuffer.allocate(n)
wenzelm@62704
   896
          var i = 0
wenzelm@62704
   897
          var m = 0
wenzelm@62704
   898
          do {
wenzelm@62704
   899
            m = file.read(buf)
wenzelm@62704
   900
            if (m != -1) i += m
wenzelm@62704
   901
          }
wenzelm@62704
   902
          while (m != -1 && n > i)
wenzelm@62704
   903
wenzelm@62704
   904
          if (i == n) {
wenzelm@62704
   905
            val prefix = new String(buf.array(), 0, sha1_prefix.length, UTF8.charset)
wenzelm@62704
   906
            val s = new String(buf.array(), sha1_prefix.length, SHA1.digest_length, UTF8.charset)
wenzelm@62704
   907
            if (prefix == sha1_prefix) Some(s) else None
wenzelm@62704
   908
          }
wenzelm@62704
   909
          else None
wenzelm@62704
   910
        }
wenzelm@62704
   911
        else None
wenzelm@62704
   912
      }
wenzelm@62704
   913
      finally { file.close }
wenzelm@62704
   914
    }
wenzelm@62704
   915
    else None
wenzelm@62704
   916
  }
wenzelm@62704
   917
wenzelm@62704
   918
  def write_heap_digest(heap: Path): String =
wenzelm@62704
   919
    read_heap_digest(heap) match {
wenzelm@62704
   920
      case None =>
wenzelm@62704
   921
        val s = SHA1.digest(heap).rep
wenzelm@62704
   922
        File.append(heap, sha1_prefix + s)
wenzelm@62704
   923
        s
wenzelm@62704
   924
      case Some(s) => s
wenzelm@62704
   925
    }
wenzelm@62704
   926
wenzelm@62704
   927
wenzelm@62704
   928
wenzelm@62637
   929
  /** persistent store **/
wenzelm@62632
   930
wenzelm@65296
   931
  object Session_Info
wenzelm@65296
   932
  {
wenzelm@66857
   933
    val session_name = SQL.Column.string("session_name").make_primary_key
wenzelm@65326
   934
wenzelm@65296
   935
    // Build_Log.Session_Info
wenzelm@65296
   936
    val session_timing = SQL.Column.bytes("session_timing")
wenzelm@65296
   937
    val command_timings = SQL.Column.bytes("command_timings")
wenzelm@66873
   938
    val theory_timings = SQL.Column.bytes("theory_timings")
wenzelm@65296
   939
    val ml_statistics = SQL.Column.bytes("ml_statistics")
wenzelm@65296
   940
    val task_statistics = SQL.Column.bytes("task_statistics")
wenzelm@65934
   941
    val errors = SQL.Column.bytes("errors")
wenzelm@65296
   942
    val build_log_columns =
wenzelm@66873
   943
      List(session_name, session_timing, command_timings, theory_timings,
wenzelm@66873
   944
        ml_statistics, task_statistics, errors)
wenzelm@65296
   945
wenzelm@65296
   946
    // Build.Session_Info
wenzelm@65296
   947
    val sources = SQL.Column.string("sources")
wenzelm@65296
   948
    val input_heaps = SQL.Column.string("input_heaps")
wenzelm@65296
   949
    val output_heap = SQL.Column.string("output_heap")
wenzelm@65296
   950
    val return_code = SQL.Column.int("return_code")
wenzelm@66746
   951
    val build_columns = List(sources, input_heaps, output_heap, return_code)
wenzelm@65296
   952
wenzelm@65296
   953
    val table = SQL.Table("isabelle_session_info", build_log_columns ::: build_columns)
wenzelm@65296
   954
  }
wenzelm@65296
   955
wenzelm@62632
   956
  def store(system_mode: Boolean = false): Store = new Store(system_mode)
wenzelm@62632
   957
wenzelm@65857
   958
  class Store private[Sessions](system_mode: Boolean)
wenzelm@62632
   959
  {
wenzelm@65278
   960
    /* file names */
wenzelm@65278
   961
wenzelm@65281
   962
    def database(name: String): Path = Path.basic("log") + Path.basic(name).ext("db")
wenzelm@65278
   963
    def log(name: String): Path = Path.basic("log") + Path.basic(name)
wenzelm@65278
   964
    def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@65278
   965
wenzelm@65278
   966
wenzelm@65286
   967
    /* SQL database content */
wenzelm@65283
   968
wenzelm@65857
   969
    val xml_cache = new XML.Cache()
wenzelm@65857
   970
wenzelm@65320
   971
    def read_bytes(db: SQL.Database, name: String, column: SQL.Column): Bytes =
wenzelm@65698
   972
      db.using_statement(Session_Info.table.select(List(column),
wenzelm@65699
   973
        Session_Info.session_name.where_equal(name)))(stmt =>
wenzelm@65291
   974
      {
wenzelm@65740
   975
        val res = stmt.execute_query()
wenzelm@65740
   976
        if (!res.next()) Bytes.empty else res.bytes(column)
wenzelm@65291
   977
      })
wenzelm@65285
   978
wenzelm@65320
   979
    def read_properties(db: SQL.Database, name: String, column: SQL.Column): List[Properties.T] =
wenzelm@65857
   980
      Properties.uncompress(read_bytes(db, name, column), Some(xml_cache))
wenzelm@65286
   981
wenzelm@65283
   982
wenzelm@62637
   983
    /* output */
wenzelm@62632
   984
wenzelm@62632
   985
    val browser_info: Path =
wenzelm@62632
   986
      if (system_mode) Path.explode("~~/browser_info")
wenzelm@62632
   987
      else Path.explode("$ISABELLE_BROWSER_INFO")
wenzelm@62632
   988
wenzelm@62637
   989
    val output_dir: Path =
wenzelm@62637
   990
      if (system_mode) Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@62637
   991
      else Path.explode("$ISABELLE_OUTPUT")
wenzelm@62637
   992
wenzelm@65298
   993
    override def toString: String = "Store(output_dir = " + output_dir.expand + ")"
wenzelm@65298
   994
wenzelm@62637
   995
    def prepare_output() { Isabelle_System.mkdirs(output_dir + Path.basic("log")) }
wenzelm@62637
   996
wenzelm@62637
   997
wenzelm@62637
   998
    /* input */
wenzelm@62637
   999
wenzelm@62637
  1000
    private val input_dirs =
wenzelm@62632
  1001
      if (system_mode) List(output_dir)
wenzelm@62633
  1002
      else {
wenzelm@62633
  1003
        val ml_ident = Path.explode("$ML_IDENTIFIER").expand
wenzelm@62633
  1004
        output_dir :: Path.split(Isabelle_System.getenv_strict("ISABELLE_PATH")).map(_ + ml_ident)
wenzelm@62633
  1005
      }
wenzelm@62632
  1006
wenzelm@65291
  1007
    def find_database_heap(name: String): Option[(Path, Option[String])] =
wenzelm@65291
  1008
      input_dirs.find(dir => (dir + database(name)).is_file).map(dir =>
wenzelm@65291
  1009
        (dir + database(name), read_heap_digest(dir + Path.basic(name))))
wenzelm@62632
  1010
wenzelm@65281
  1011
    def find_database(name: String): Option[Path] =
wenzelm@65281
  1012
      input_dirs.map(_ + database(name)).find(_.is_file)
wenzelm@65281
  1013
wenzelm@62637
  1014
    def heap(name: String): Path =
wenzelm@65288
  1015
      input_dirs.map(_ + Path.basic(name)).find(_.is_file) getOrElse
wenzelm@62637
  1016
        error("Unknown logic " + quote(name) + " -- no heap file found in:\n" +
wenzelm@62769
  1017
          cat_lines(input_dirs.map(dir => "  " + dir.expand.implode)))
wenzelm@65287
  1018
wenzelm@65287
  1019
wenzelm@65296
  1020
    /* session info */
wenzelm@65281
  1021
wenzelm@65296
  1022
    def write_session_info(
wenzelm@65318
  1023
      db: SQL.Database,
wenzelm@65320
  1024
      name: String,
wenzelm@65318
  1025
      build_log: Build_Log.Session_Info,
wenzelm@65318
  1026
      build: Build.Session_Info)
wenzelm@65281
  1027
    {
wenzelm@65281
  1028
      db.transaction {
wenzelm@65296
  1029
        db.create_table(Session_Info.table)
wenzelm@65698
  1030
        db.using_statement(
wenzelm@65699
  1031
          Session_Info.table.delete(Session_Info.session_name.where_equal(name)))(_.execute)
wenzelm@65698
  1032
        db.using_statement(Session_Info.table.insert())(stmt =>
wenzelm@65281
  1033
        {
wenzelm@65748
  1034
          stmt.string(1) = name
wenzelm@65857
  1035
          stmt.bytes(2) = Properties.encode(build_log.session_timing)
wenzelm@65857
  1036
          stmt.bytes(3) = Properties.compress(build_log.command_timings)
wenzelm@66873
  1037
          stmt.bytes(4) = Properties.compress(build_log.theory_timings)
wenzelm@66873
  1038
          stmt.bytes(5) = Properties.compress(build_log.ml_statistics)
wenzelm@66873
  1039
          stmt.bytes(6) = Properties.compress(build_log.task_statistics)
wenzelm@66873
  1040
          stmt.bytes(7) = Build_Log.compress_errors(build_log.errors)
wenzelm@66873
  1041
          stmt.string(8) = build.sources
wenzelm@66873
  1042
          stmt.string(9) = cat_lines(build.input_heaps)
wenzelm@66873
  1043
          stmt.string(10) = build.output_heap getOrElse ""
wenzelm@66873
  1044
          stmt.int(11) = build.return_code
wenzelm@65281
  1045
          stmt.execute()
wenzelm@65281
  1046
        })
wenzelm@65281
  1047
      }
wenzelm@65281
  1048
    }
wenzelm@65281
  1049
wenzelm@65320
  1050
    def read_session_timing(db: SQL.Database, name: String): Properties.T =
wenzelm@65857
  1051
      Properties.decode(read_bytes(db, name, Session_Info.session_timing), Some(xml_cache))
wenzelm@65286
  1052
wenzelm@65320
  1053
    def read_command_timings(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1054
      read_properties(db, name, Session_Info.command_timings)
wenzelm@65286
  1055
wenzelm@66873
  1056
    def read_theory_timings(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@66873
  1057
      read_properties(db, name, Session_Info.theory_timings)
wenzelm@66873
  1058
wenzelm@65320
  1059
    def read_ml_statistics(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1060
      read_properties(db, name, Session_Info.ml_statistics)
wenzelm@65286
  1061
wenzelm@65320
  1062
    def read_task_statistics(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1063
      read_properties(db, name, Session_Info.task_statistics)
wenzelm@65286
  1064
wenzelm@65937
  1065
    def read_errors(db: SQL.Database, name: String): List[String] =
wenzelm@65937
  1066
      Build_Log.uncompress_errors(read_bytes(db, name, Session_Info.errors))
wenzelm@65937
  1067
wenzelm@65320
  1068
    def read_build(db: SQL.Database, name: String): Option[Build.Session_Info] =
wenzelm@66744
  1069
    {
wenzelm@66957
  1070
      if (db.tables.contains(Session_Info.table.name)) {
wenzelm@66957
  1071
        db.using_statement(Session_Info.table.select(Session_Info.build_columns,
wenzelm@66957
  1072
          Session_Info.session_name.where_equal(name)))(stmt =>
wenzelm@66957
  1073
        {
wenzelm@66957
  1074
          val res = stmt.execute_query()
wenzelm@66957
  1075
          if (!res.next()) None
wenzelm@66957
  1076
          else {
wenzelm@66957
  1077
            Some(
wenzelm@66957
  1078
              Build.Session_Info(
wenzelm@66957
  1079
                res.string(Session_Info.sources),
wenzelm@66957
  1080
                split_lines(res.string(Session_Info.input_heaps)),
wenzelm@66957
  1081
                res.string(Session_Info.output_heap) match { case "" => None case s => Some(s) },
wenzelm@66957
  1082
                res.int(Session_Info.return_code)))
wenzelm@66957
  1083
          }
wenzelm@66957
  1084
        })
wenzelm@66957
  1085
      }
wenzelm@66957
  1086
      else None
wenzelm@66744
  1087
    }
wenzelm@65281
  1088
  }
wenzelm@62631
  1089
}