src/Pure/Thy/sessions.scala
author wenzelm
Sun May 13 16:37:36 2018 +0200 (14 months ago)
changeset 68169 395432e7516e
parent 68086 9e1c670301b8
child 68204 a554da2811f2
permissions -rw-r--r--
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@66701
    42
    def make(local_dir: Path, bases: List[Base],
wenzelm@67493
    43
      sessions: List[(String, Position.T)] = Nil,
wenzelm@66701
    44
      theories: List[Document.Node.Name] = 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@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@66701
    86
wenzelm@66701
    87
      val known_loaded_files =
wenzelm@66701
    88
        (loaded_files.toMap /: bases.map(base => base.known.loaded_files))(_ ++ _)
wenzelm@66701
    89
wenzelm@67219
    90
      Known(
wenzelm@67219
    91
        known_sessions,
wenzelm@67219
    92
        known_theories, known_theories_local,
wenzelm@66701
    93
        known_files.iterator.map(p => (p._1, p._2.reverse)).toMap,
wenzelm@66701
    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@66701
   102
    files: Map[JFile, List[Document.Node.Name]] = Map.empty,
wenzelm@66701
   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@66668
   110
    def standard_path: Known =
wenzelm@66668
   111
      copy(theories = for ((a, b) <- theories) yield (a, b.map(File.standard_path(_))),
wenzelm@66668
   112
        theories_local = for ((a, b) <- theories_local) yield (a, b.map(File.standard_path(_))),
wenzelm@66668
   113
        files = for ((a, b) <- files) yield (a, b.map(c => c.map(File.standard_path(_)))))
wenzelm@66668
   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@66571
   131
    pos: Position.T = Position.none,
wenzelm@67471
   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@66694
   140
    errors: List[String] = Nil,
wenzelm@66694
   141
    imports: Option[Base] = None)
wenzelm@65495
   142
  {
wenzelm@65495
   143
    def platform_path: Base = copy(known = known.platform_path)
wenzelm@66668
   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@66694
   167
wenzelm@66694
   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@66571
   182
wenzelm@66571
   183
    def errors: List[String] =
wenzelm@66571
   184
      (for {
wenzelm@66571
   185
        (name, base) <- session_bases.iterator
wenzelm@66571
   186
        if base.errors.nonEmpty
wenzelm@66571
   187
      } yield cat_lines(base.errors) +
wenzelm@66571
   188
          "\nThe error(s) above occurred in session " + quote(name) + Position.here(base.pos)
wenzelm@66571
   189
      ).toList
wenzelm@66571
   190
wenzelm@66571
   191
    def check_errors: Deps =
wenzelm@66571
   192
      errors match {
wenzelm@66571
   193
        case Nil => this
wenzelm@66571
   194
        case errs => error(cat_lines(errs))
wenzelm@66571
   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@65372
   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@67471
   225
    val doc_names = Doc.doc_names()
wenzelm@67471
   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@67880
   230
          progress.expose_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@66701
   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@66701
   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@66701
   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@66701
   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@66701
   318
            val known =
wenzelm@66701
   319
              Known.make(info.dir, List(imports_base),
wenzelm@67493
   320
                sessions = List(info.name -> info.pos),
wenzelm@67059
   321
                theories = dependencies.theories,
wenzelm@66701
   322
                loaded_files = loaded_files)
wenzelm@66701
   323
wenzelm@66743
   324
            val sources_errors =
wenzelm@66743
   325
              for (p <- session_files if !p.is_file) yield "No such file: " + p
wenzelm@66604
   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@66571
   332
              Base(
wenzelm@66571
   333
                pos = info.pos,
wenzelm@67471
   334
                doc_names = doc_names,
wenzelm@65540
   335
                global_theories = global_theories,
wenzelm@67053
   336
                loaded_theories = dependencies.loaded_theories,
wenzelm@66701
   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@66694
   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@66701
   354
    Deps(session_bases, Known.make(Path.current, session_bases.toList.map(_._2)))
wenzelm@65372
   355
  }
wenzelm@65251
   356
wenzelm@66963
   357
wenzelm@66963
   358
  /* base info */
wenzelm@66963
   359
wenzelm@66974
   360
  sealed case class Base_Info(
wenzelm@67869
   361
    options: Options,
wenzelm@67869
   362
    dirs: List[Path],
wenzelm@66974
   363
    session: String,
wenzelm@67052
   364
    sessions_structure: Structure,
wenzelm@66975
   365
    errors: List[String],
wenzelm@66974
   366
    base: Base,
wenzelm@66974
   367
    infos: List[Info])
wenzelm@66974
   368
  {
wenzelm@66974
   369
    def check_base: Base = if (errors.isEmpty) base else error(cat_lines(errors))
wenzelm@66974
   370
  }
wenzelm@66974
   371
wenzelm@67846
   372
  def base_info(options: Options,
wenzelm@67846
   373
    session: String,
wenzelm@67852
   374
    progress: Progress = No_Progress,
wenzelm@65428
   375
    dirs: List[Path] = Nil,
wenzelm@67922
   376
    include_sessions: List[String] = Nil,
wenzelm@66988
   377
    ancestor_session: Option[String] = None,
wenzelm@66968
   378
    all_known: Boolean = false,
wenzelm@66987
   379
    focus_session: Boolean = false,
wenzelm@66968
   380
    required_session: Boolean = false): Base_Info =
wenzelm@65251
   381
  {
wenzelm@67026
   382
    val full_sessions = load_structure(options, dirs = dirs)
wenzelm@65428
   383
    val global_theories = full_sessions.global_theories
wenzelm@65372
   384
wenzelm@66990
   385
    val selected_sessions =
wenzelm@67025
   386
      full_sessions.selection(Selection(sessions = session :: ancestor_session.toList))
wenzelm@66974
   387
    val info = selected_sessions(session)
wenzelm@66988
   388
    val ancestor = ancestor_session orElse info.parent
wenzelm@66963
   389
wenzelm@66974
   390
    val (session1, infos1) =
wenzelm@66988
   391
      if (required_session && ancestor.isDefined) {
wenzelm@67852
   392
        val deps = Sessions.deps(selected_sessions, global_theories, progress = progress)
wenzelm@66974
   393
        val base = deps(session)
wenzelm@66968
   394
wenzelm@66988
   395
        val ancestor_loaded =
wenzelm@66988
   396
          deps.get(ancestor.get) match {
wenzelm@66990
   397
            case Some(ancestor_base)
wenzelm@66990
   398
            if !selected_sessions.imports_requirements(List(ancestor.get)).contains(session) =>
wenzelm@66990
   399
              ancestor_base.loaded_theories.defined(_)
wenzelm@66990
   400
            case _ =>
wenzelm@66988
   401
              error("Bad ancestor " + quote(ancestor.get) + " for session " + quote(session))
wenzelm@66988
   402
          }
wenzelm@66974
   403
wenzelm@66974
   404
        val required_theories =
wenzelm@66968
   405
          for {
wenzelm@66968
   406
            thy <- base.loaded_theories.keys
wenzelm@66988
   407
            if !ancestor_loaded(thy) && base.theory_qualifier(thy) != session
wenzelm@66968
   408
          }
wenzelm@66974
   409
          yield thy
wenzelm@66968
   410
wenzelm@66988
   411
        if (required_theories.isEmpty) (ancestor.get, Nil)
wenzelm@66968
   412
        else {
wenzelm@66988
   413
          val other_name = info.name + "_base(" + ancestor.get + ")"
wenzelm@66974
   414
          (other_name,
wenzelm@66968
   415
            List(
wenzelm@66968
   416
              make_info(info.options,
wenzelm@66968
   417
                dir_selected = false,
wenzelm@66968
   418
                dir = info.dir,
wenzelm@66968
   419
                chapter = info.chapter,
wenzelm@66968
   420
                Session_Entry(
wenzelm@66968
   421
                  pos = info.pos,
wenzelm@66968
   422
                  name = other_name,
wenzelm@66968
   423
                  groups = info.groups,
wenzelm@66968
   424
                  path = ".",
wenzelm@66988
   425
                  parent = ancestor,
wenzelm@66974
   426
                  description = "Required theory imports from other sessions",
wenzelm@66968
   427
                  options = Nil,
wenzelm@66991
   428
                  imports = info.deps,
wenzelm@66974
   429
                  theories = List((Nil, required_theories.map(thy => ((thy, Position.none), false)))),
wenzelm@66974
   430
                  document_files = Nil))))
wenzelm@66968
   431
        }
wenzelm@66968
   432
      }
wenzelm@66974
   433
      else (session, Nil)
wenzelm@66968
   434
wenzelm@66974
   435
    val full_sessions1 =
wenzelm@66974
   436
      if (infos1.isEmpty) full_sessions
wenzelm@67026
   437
      else load_structure(options, dirs = dirs, infos = infos1)
wenzelm@66987
   438
wenzelm@66987
   439
    val selected_sessions1 =
wenzelm@67922
   440
    {
wenzelm@67922
   441
      val sel_sessions1 = session1 :: include_sessions
wenzelm@67922
   442
      val select_sessions1 =
wenzelm@67922
   443
        if (focus_session) full_sessions1.imports_descendants(sel_sessions1) else sel_sessions1
wenzelm@67025
   444
      full_sessions1.selection(Selection(sessions = select_sessions1))
wenzelm@67922
   445
    }
wenzelm@66964
   446
wenzelm@66974
   447
    val sessions1 = if (all_known) full_sessions1 else selected_sessions1
wenzelm@67852
   448
    val deps1 = Sessions.deps(sessions1, global_theories, progress = progress)
wenzelm@67922
   449
    val base1 = deps1(session1).copy(known = deps1.all_known)
wenzelm@66964
   450
wenzelm@67869
   451
    Base_Info(options, dirs, session1, sessions1, deps1.errors, base1, infos1)
wenzelm@65251
   452
  }
wenzelm@65251
   453
wenzelm@65251
   454
wenzelm@65415
   455
  /* cumulative session info */
wenzelm@62631
   456
wenzelm@62631
   457
  sealed case class Info(
wenzelm@65519
   458
    name: String,
wenzelm@62631
   459
    chapter: String,
wenzelm@66829
   460
    dir_selected: Boolean,
wenzelm@62631
   461
    pos: Position.T,
wenzelm@62631
   462
    groups: List[String],
wenzelm@62631
   463
    dir: Path,
wenzelm@62631
   464
    parent: Option[String],
wenzelm@62631
   465
    description: String,
wenzelm@62631
   466
    options: Options,
wenzelm@65420
   467
    imports: List[String],
wenzelm@65517
   468
    theories: List[(Options, List[(String, Position.T)])],
wenzelm@65374
   469
    global_theories: List[String],
wenzelm@62631
   470
    document_files: List[(Path, Path)],
wenzelm@62631
   471
    meta_digest: SHA1.Digest)
wenzelm@62631
   472
  {
wenzelm@66828
   473
    def deps: List[String] = parent.toList ::: imports
wenzelm@66828
   474
wenzelm@62631
   475
    def timeout: Time = Time.seconds(options.real("timeout") * options.real("timeout_scale"))
wenzelm@67297
   476
wenzelm@67297
   477
    def bibtex_entries: List[Text.Info[String]] =
wenzelm@67297
   478
      (for {
wenzelm@67297
   479
        (document_dir, file) <- document_files.iterator
wenzelm@67297
   480
        if Bibtex.is_bibtex(file.base_name)
wenzelm@67297
   481
        info <- Bibtex.entries(File.read(dir + document_dir + file)).iterator
wenzelm@67297
   482
      } yield info).toList
wenzelm@62631
   483
  }
wenzelm@62631
   484
wenzelm@66967
   485
  def make_info(options: Options, dir_selected: Boolean, dir: Path, chapter: String,
wenzelm@66967
   486
    entry: Session_Entry): Info =
wenzelm@66967
   487
  {
wenzelm@66967
   488
    try {
wenzelm@66967
   489
      val name = entry.name
wenzelm@66967
   490
wenzelm@67284
   491
      if (exclude_session(name)) error("Bad session name")
wenzelm@66967
   492
      if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
wenzelm@66967
   493
      if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
wenzelm@66967
   494
wenzelm@66967
   495
      val session_options = options ++ entry.options
wenzelm@66967
   496
wenzelm@66967
   497
      val theories =
wenzelm@67216
   498
        entry.theories.map({ case (opts, thys) =>
wenzelm@67216
   499
          (session_options ++ opts,
wenzelm@67216
   500
            thys.map({ case ((thy, pos), _) =>
wenzelm@67284
   501
              if (exclude_theory(thy))
wenzelm@67216
   502
                error("Bad theory name " + quote(thy) + Position.here(pos))
wenzelm@67216
   503
              else (thy, pos) })) })
wenzelm@66967
   504
wenzelm@66967
   505
      val global_theories =
wenzelm@66967
   506
        for { (_, thys) <- entry.theories; ((thy, pos), global) <- thys if global }
wenzelm@66967
   507
        yield {
wenzelm@66967
   508
          val thy_name = Path.explode(thy).expand.base_name
wenzelm@66967
   509
          if (Long_Name.is_qualified(thy_name))
wenzelm@66967
   510
            error("Bad qualified name for global theory " +
wenzelm@66967
   511
              quote(thy_name) + Position.here(pos))
wenzelm@66967
   512
          else thy_name
wenzelm@66967
   513
        }
wenzelm@66967
   514
wenzelm@66967
   515
      val conditions =
wenzelm@66967
   516
        theories.flatMap(thys => space_explode(',', thys._1.string("condition"))).distinct.sorted.
wenzelm@66967
   517
          map(x => (x, Isabelle_System.getenv(x) != ""))
wenzelm@66967
   518
wenzelm@66967
   519
      val document_files =
wenzelm@66967
   520
        entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
wenzelm@66967
   521
wenzelm@66967
   522
      val meta_digest =
wenzelm@66967
   523
        SHA1.digest((name, chapter, entry.parent, entry.options, entry.imports,
wenzelm@66967
   524
          entry.theories_no_position, conditions, entry.document_files).toString)
wenzelm@66967
   525
wenzelm@66967
   526
      Info(name, chapter, dir_selected, entry.pos, entry.groups,
wenzelm@66967
   527
        dir + Path.explode(entry.path), entry.parent, entry.description, session_options,
wenzelm@66967
   528
        entry.imports, theories, global_theories, document_files, meta_digest)
wenzelm@66967
   529
    }
wenzelm@66967
   530
    catch {
wenzelm@66967
   531
      case ERROR(msg) =>
wenzelm@66967
   532
        error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@66967
   533
          quote(entry.name) + Position.here(entry.pos))
wenzelm@66967
   534
    }
wenzelm@66967
   535
  }
wenzelm@66967
   536
wenzelm@65419
   537
  object Selection
wenzelm@65419
   538
  {
wenzelm@65422
   539
    val empty: Selection = Selection()
wenzelm@65525
   540
    val all: Selection = Selection(all_sessions = true)
wenzelm@65419
   541
  }
wenzelm@65419
   542
wenzelm@65419
   543
  sealed case class Selection(
wenzelm@65419
   544
    requirements: Boolean = false,
wenzelm@65419
   545
    all_sessions: Boolean = false,
wenzelm@66737
   546
    base_sessions: List[String] = Nil,
wenzelm@65419
   547
    exclude_session_groups: List[String] = Nil,
wenzelm@65419
   548
    exclude_sessions: List[String] = Nil,
wenzelm@65419
   549
    session_groups: List[String] = Nil,
wenzelm@65419
   550
    sessions: List[String] = Nil)
wenzelm@65419
   551
  {
wenzelm@66736
   552
    def ++ (other: Selection): Selection =
wenzelm@65422
   553
      Selection(
wenzelm@65422
   554
        requirements = requirements || other.requirements,
wenzelm@65422
   555
        all_sessions = all_sessions || other.all_sessions,
wenzelm@66737
   556
        base_sessions = Library.merge(base_sessions, other.base_sessions),
wenzelm@66736
   557
        exclude_session_groups = Library.merge(exclude_session_groups, other.exclude_session_groups),
wenzelm@66736
   558
        exclude_sessions = Library.merge(exclude_sessions, other.exclude_sessions),
wenzelm@66736
   559
        session_groups = Library.merge(session_groups, other.session_groups),
wenzelm@66736
   560
        sessions = Library.merge(sessions, other.sessions))
wenzelm@67029
   561
wenzelm@67029
   562
    def selected(graph: Graph[String, Info]): List[String] =
wenzelm@67029
   563
    {
wenzelm@67029
   564
      val select_group = session_groups.toSet
wenzelm@67029
   565
      val select_session = sessions.toSet ++ graph.all_succs(base_sessions)
wenzelm@67029
   566
wenzelm@67029
   567
      val selected0 =
wenzelm@67029
   568
        if (all_sessions) graph.keys
wenzelm@67029
   569
        else {
wenzelm@67029
   570
          (for {
wenzelm@67029
   571
            (name, (info, _)) <- graph.iterator
wenzelm@67029
   572
            if info.dir_selected || select_session(name) ||
wenzelm@67029
   573
              graph.get_node(name).groups.exists(select_group)
wenzelm@67029
   574
          } yield name).toList
wenzelm@67029
   575
        }
wenzelm@67029
   576
wenzelm@67029
   577
      if (requirements) (graph.all_preds(selected0).toSet -- selected0).toList
wenzelm@67029
   578
      else selected0
wenzelm@67029
   579
    }
wenzelm@67029
   580
wenzelm@67029
   581
    def excluded(graph: Graph[String, Info]): List[String] =
wenzelm@67029
   582
    {
wenzelm@67029
   583
      val exclude_group = exclude_session_groups.toSet
wenzelm@67029
   584
      val exclude_group_sessions =
wenzelm@67029
   585
        (for {
wenzelm@67029
   586
          (name, (info, _)) <- graph.iterator
wenzelm@67029
   587
          if graph.get_node(name).groups.exists(exclude_group)
wenzelm@67029
   588
        } yield name).toList
wenzelm@67029
   589
      graph.all_succs(exclude_group_sessions ::: exclude_sessions)
wenzelm@67029
   590
    }
wenzelm@65419
   591
  }
wenzelm@65419
   592
wenzelm@67052
   593
  def make(infos: List[Info]): Structure =
wenzelm@62631
   594
  {
wenzelm@65420
   595
    def add_edges(graph: Graph[String, Info], kind: String, edges: Info => Traversable[String])
wenzelm@65420
   596
      : Graph[String, Info] =
wenzelm@65420
   597
    {
wenzelm@65420
   598
      def add_edge(pos: Position.T, name: String, g: Graph[String, Info], parent: String) =
wenzelm@65420
   599
      {
wenzelm@65420
   600
        if (!g.defined(parent))
wenzelm@65420
   601
          error("Bad " + kind + " session " + quote(parent) + " for " +
wenzelm@65420
   602
            quote(name) + Position.here(pos))
wenzelm@65420
   603
wenzelm@65420
   604
        try { g.add_edge_acyclic(parent, name) }
wenzelm@65420
   605
        catch {
wenzelm@65420
   606
          case exn: Graph.Cycles[_] =>
wenzelm@65420
   607
            error(cat_lines(exn.cycles.map(cycle =>
wenzelm@65420
   608
              "Cyclic session dependency of " +
wenzelm@65420
   609
                cycle.map(c => quote(c.toString)).mkString(" via "))) + Position.here(pos))
wenzelm@65420
   610
        }
wenzelm@65420
   611
      }
wenzelm@65420
   612
      (graph /: graph.iterator) {
wenzelm@65420
   613
        case (g, (name, (info, _))) => (g /: edges(info))(add_edge(info.pos, name, _, _))
wenzelm@65420
   614
      }
wenzelm@65420
   615
    }
wenzelm@65420
   616
wenzelm@65420
   617
    val graph0 =
wenzelm@65415
   618
      (Graph.string[Info] /: infos) {
wenzelm@66960
   619
        case (graph, info) =>
wenzelm@66960
   620
          if (graph.defined(info.name))
wenzelm@66960
   621
            error("Duplicate session " + quote(info.name) + Position.here(info.pos) +
wenzelm@66960
   622
              Position.here(graph.get_node(info.name).pos))
wenzelm@66960
   623
          else graph.new_node(info.name, info)
wenzelm@65415
   624
      }
wenzelm@65420
   625
    val graph1 = add_edges(graph0, "parent", _.parent)
wenzelm@65420
   626
    val graph2 = add_edges(graph1, "imports", _.imports)
wenzelm@62631
   627
wenzelm@67052
   628
    new Structure(graph1, graph2)
wenzelm@62631
   629
  }
wenzelm@62631
   630
wenzelm@67052
   631
  final class Structure private[Sessions](
wenzelm@65420
   632
      val build_graph: Graph[String, Info],
wenzelm@65420
   633
      val imports_graph: Graph[String, Info])
wenzelm@62631
   634
  {
wenzelm@66823
   635
    def build_graph_display: Graph_Display.Graph = Graph_Display.make_graph(build_graph)
wenzelm@66823
   636
    def imports_graph_display: Graph_Display.Graph = Graph_Display.make_graph(imports_graph)
wenzelm@66823
   637
wenzelm@67025
   638
    def defined(name: String): Boolean = imports_graph.defined(name)
wenzelm@65420
   639
    def apply(name: String): Info = imports_graph.get_node(name)
wenzelm@67025
   640
    def get(name: String): Option[Info] = if (defined(name)) Some(apply(name)) else None
wenzelm@62631
   641
wenzelm@65457
   642
    def global_theories: Map[String, String] =
wenzelm@65490
   643
      (Thy_Header.bootstrap_global_theories.toMap /:
wenzelm@65424
   644
        (for {
wenzelm@65519
   645
          (_, (info, _)) <- imports_graph.iterator
wenzelm@65519
   646
          thy <- info.global_theories.iterator }
wenzelm@65519
   647
         yield (thy, info)))({
wenzelm@65519
   648
            case (global, (thy, info)) =>
wenzelm@66780
   649
              val qualifier = info.name
wenzelm@65457
   650
              global.get(thy) match {
wenzelm@65457
   651
                case Some(qualifier1) if qualifier != qualifier1 =>
wenzelm@65457
   652
                  error("Duplicate global theory " + quote(thy) + Position.here(info.pos))
wenzelm@65457
   653
                case _ => global + (thy -> qualifier)
wenzelm@65457
   654
              }
wenzelm@65457
   655
          })
wenzelm@65372
   656
wenzelm@67052
   657
    def selection(sel: Selection): Structure =
wenzelm@62631
   658
    {
wenzelm@67025
   659
      val bad_sessions =
wenzelm@67025
   660
        SortedSet((sel.base_sessions ::: sel.exclude_sessions ::: sel.sessions).
wenzelm@67025
   661
          filterNot(defined(_)): _*).toList
wenzelm@67025
   662
      if (bad_sessions.nonEmpty)
wenzelm@67025
   663
        error("Undefined session(s): " + commas_quote(bad_sessions))
wenzelm@67025
   664
wenzelm@67029
   665
      val excluded = sel.excluded(build_graph).toSet
wenzelm@67027
   666
wenzelm@67025
   667
      def restrict(graph: Graph[String, Info]): Graph[String, Info] =
wenzelm@67025
   668
      {
wenzelm@67029
   669
        val sessions = graph.all_preds(sel.selected(graph)).filterNot(excluded)
wenzelm@67029
   670
        graph.restrict(graph.all_preds(sessions).toSet)
wenzelm@67025
   671
      }
wenzelm@67025
   672
wenzelm@67052
   673
      new Structure(restrict(build_graph), restrict(imports_graph))
wenzelm@62631
   674
    }
wenzelm@62631
   675
wenzelm@67029
   676
    def build_selection(sel: Selection): List[String] = sel.selected(build_graph)
wenzelm@67029
   677
    def build_descendants(ss: List[String]): List[String] = build_graph.all_succs(ss)
wenzelm@67029
   678
    def build_requirements(ss: List[String]): List[String] = build_graph.all_preds(ss).reverse
wenzelm@67029
   679
    def build_topological_order: List[String] = build_graph.topological_order
wenzelm@62631
   680
wenzelm@67029
   681
    def imports_selection(sel: Selection): List[String] = sel.selected(imports_graph)
wenzelm@67029
   682
    def imports_descendants(ss: List[String]): List[String] = imports_graph.all_succs(ss)
wenzelm@67029
   683
    def imports_requirements(ss: List[String]): List[String] = imports_graph.all_preds(ss).reverse
wenzelm@67029
   684
    def imports_topological_order: List[String] = imports_graph.topological_order
wenzelm@65420
   685
wenzelm@65420
   686
    override def toString: String =
wenzelm@67052
   687
      imports_graph.keys_iterator.mkString("Sessions.Structure(", ", ", ")")
wenzelm@62631
   688
  }
wenzelm@62631
   689
wenzelm@62631
   690
wenzelm@62631
   691
  /* parser */
wenzelm@62631
   692
wenzelm@62864
   693
  val ROOT = Path.explode("ROOT")
wenzelm@62864
   694
  val ROOTS = Path.explode("ROOTS")
wenzelm@62864
   695
wenzelm@62631
   696
  private val CHAPTER = "chapter"
wenzelm@62631
   697
  private val SESSION = "session"
wenzelm@62631
   698
  private val IN = "in"
wenzelm@62631
   699
  private val DESCRIPTION = "description"
wenzelm@62631
   700
  private val OPTIONS = "options"
wenzelm@65420
   701
  private val SESSIONS = "sessions"
wenzelm@62631
   702
  private val THEORIES = "theories"
wenzelm@65374
   703
  private val GLOBAL = "global"
wenzelm@62631
   704
  private val DOCUMENT_FILES = "document_files"
wenzelm@62631
   705
wenzelm@67004
   706
  val root_syntax =
wenzelm@67004
   707
    Outer_Syntax.empty + "(" + ")" + "+" + "," + "=" + "[" + "]" + GLOBAL + IN +
wenzelm@63443
   708
      (CHAPTER, Keyword.THY_DECL) +
wenzelm@63443
   709
      (SESSION, Keyword.THY_DECL) +
wenzelm@63443
   710
      (DESCRIPTION, Keyword.QUASI_COMMAND) +
wenzelm@63443
   711
      (OPTIONS, Keyword.QUASI_COMMAND) +
wenzelm@65420
   712
      (SESSIONS, Keyword.QUASI_COMMAND) +
wenzelm@63443
   713
      (THEORIES, Keyword.QUASI_COMMAND) +
wenzelm@63443
   714
      (DOCUMENT_FILES, Keyword.QUASI_COMMAND)
wenzelm@62631
   715
wenzelm@66818
   716
  abstract class Entry
wenzelm@66818
   717
  sealed case class Chapter(name: String) extends Entry
wenzelm@66818
   718
  sealed case class Session_Entry(
wenzelm@66818
   719
    pos: Position.T,
wenzelm@66818
   720
    name: String,
wenzelm@66818
   721
    groups: List[String],
wenzelm@66818
   722
    path: String,
wenzelm@66818
   723
    parent: Option[String],
wenzelm@66818
   724
    description: String,
wenzelm@66818
   725
    options: List[Options.Spec],
wenzelm@66818
   726
    imports: List[String],
wenzelm@66818
   727
    theories: List[(List[Options.Spec], List[((String, Position.T), Boolean)])],
wenzelm@66818
   728
    document_files: List[(String, String)]) extends Entry
wenzelm@66818
   729
  {
wenzelm@66818
   730
    def theories_no_position: List[(List[Options.Spec], List[(String, Boolean)])] =
wenzelm@66818
   731
      theories.map({ case (a, b) => (a, b.map({ case ((c, _), d) => (c, d) })) })
wenzelm@66818
   732
  }
wenzelm@66818
   733
wenzelm@62968
   734
  private object Parser extends Parse.Parser with Options.Parser
wenzelm@62631
   735
  {
wenzelm@62631
   736
    private val chapter: Parser[Chapter] =
wenzelm@62631
   737
    {
wenzelm@62631
   738
      val chapter_name = atom("chapter name", _.is_name)
wenzelm@62631
   739
wenzelm@62631
   740
      command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
wenzelm@62631
   741
    }
wenzelm@62631
   742
wenzelm@62631
   743
    private val session_entry: Parser[Session_Entry] =
wenzelm@62631
   744
    {
wenzelm@62631
   745
      val option =
wenzelm@67210
   746
        option_name ~ opt($$$("=") ~! option_value ^^ { case _ ~ x => x }) ^^
wenzelm@67210
   747
          { case x ~ y => (x, y) }
wenzelm@62631
   748
      val options = $$$("[") ~> rep1sep(option, $$$(",")) <~ $$$("]")
wenzelm@62631
   749
wenzelm@65374
   750
      val global =
wenzelm@65374
   751
        ($$$("(") ~! $$$(GLOBAL) ~ $$$(")")) ^^ { case _ => true } | success(false)
wenzelm@65374
   752
wenzelm@65374
   753
      val theory_entry =
wenzelm@65517
   754
        position(theory_name) ~ global ^^ { case x ~ y => (x, y) }
wenzelm@65374
   755
wenzelm@62631
   756
      val theories =
wenzelm@65374
   757
        $$$(THEORIES) ~!
wenzelm@66970
   758
          ((options | success(Nil)) ~ rep1(theory_entry)) ^^
wenzelm@65374
   759
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@62631
   760
wenzelm@62631
   761
      val document_files =
wenzelm@62631
   762
        $$$(DOCUMENT_FILES) ~!
wenzelm@67210
   763
          (($$$("(") ~! ($$$(IN) ~ path ~ $$$(")")) ^^
wenzelm@67210
   764
              { case _ ~ (_ ~ x ~ _) => x } | success("document")) ~
wenzelm@62631
   765
            rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
wenzelm@62631
   766
wenzelm@62631
   767
      command(SESSION) ~!
wenzelm@62631
   768
        (position(session_name) ~
wenzelm@62631
   769
          (($$$("(") ~! (rep1(name) <~ $$$(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   770
          (($$$(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
wenzelm@62631
   771
          ($$$("=") ~!
wenzelm@62631
   772
            (opt(session_name ~! $$$("+") ^^ { case x ~ _ => x }) ~
wenzelm@62631
   773
              (($$$(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
wenzelm@62631
   774
              (($$$(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@66970
   775
              (($$$(SESSIONS) ~! rep1(session_name)  ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@66970
   776
              rep(theories) ~
wenzelm@62631
   777
              (rep(document_files) ^^ (x => x.flatten))))) ^^
wenzelm@66759
   778
        { case _ ~ ((a, pos) ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i))) =>
wenzelm@66759
   779
            Session_Entry(pos, a, b, c, d, e, f, g, h, i) }
wenzelm@62631
   780
    }
wenzelm@62631
   781
wenzelm@66819
   782
    def parse_root(path: Path): List[Entry] =
wenzelm@62631
   783
    {
wenzelm@66764
   784
      val toks = Token.explode(root_syntax.keywords, File.read(path))
wenzelm@66764
   785
      val start = Token.Pos.file(path.implode)
wenzelm@62631
   786
wenzelm@66764
   787
      parse_all(rep(chapter | session_entry), Token.reader(toks, start)) match {
wenzelm@66818
   788
        case Success(result, _) => result
wenzelm@66764
   789
        case bad => error(bad.toString)
wenzelm@62631
   790
      }
wenzelm@62631
   791
    }
wenzelm@62631
   792
  }
wenzelm@62631
   793
wenzelm@66819
   794
  def parse_root(path: Path): List[Entry] = Parser.parse_root(path)
wenzelm@66819
   795
wenzelm@66819
   796
  def parse_root_entries(path: Path): List[Session_Entry] =
wenzelm@66819
   797
    for (entry <- Parser.parse_root(path) if entry.isInstanceOf[Session_Entry])
wenzelm@66819
   798
    yield entry.asInstanceOf[Session_Entry]
wenzelm@66818
   799
wenzelm@66960
   800
  def read_root(options: Options, select: Boolean, path: Path): List[Info] =
wenzelm@66818
   801
  {
wenzelm@66818
   802
    var entry_chapter = "Unsorted"
wenzelm@66960
   803
    val infos = new mutable.ListBuffer[Info]
wenzelm@66819
   804
    parse_root(path).foreach {
wenzelm@66818
   805
      case Chapter(name) => entry_chapter = name
wenzelm@66967
   806
      case entry: Session_Entry =>
wenzelm@66967
   807
        infos += make_info(options, select, path.dir, entry_chapter, entry)
wenzelm@66818
   808
    }
wenzelm@66818
   809
    infos.toList
wenzelm@66818
   810
  }
wenzelm@66818
   811
wenzelm@66818
   812
  def parse_roots(roots: Path): List[String] =
wenzelm@66818
   813
  {
wenzelm@66818
   814
    for {
wenzelm@66818
   815
      line <- split_lines(File.read(roots))
wenzelm@66818
   816
      if !(line == "" || line.startsWith("#"))
wenzelm@66818
   817
    } yield line
wenzelm@66818
   818
  }
wenzelm@66818
   819
wenzelm@62631
   820
wenzelm@62635
   821
  /* load sessions from certain directories */
wenzelm@62631
   822
wenzelm@62631
   823
  private def is_session_dir(dir: Path): Boolean =
wenzelm@62631
   824
    (dir + ROOT).is_file || (dir + ROOTS).is_file
wenzelm@62631
   825
wenzelm@62631
   826
  private def check_session_dir(dir: Path): Path =
wenzelm@65468
   827
    if (is_session_dir(dir)) File.pwd() + dir.expand
wenzelm@62631
   828
    else error("Bad session root directory: " + dir.toString)
wenzelm@62631
   829
wenzelm@65561
   830
  def directories(dirs: List[Path], select_dirs: List[Path]): List[(Boolean, Path)] =
wenzelm@65561
   831
  {
wenzelm@65561
   832
    val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
wenzelm@65561
   833
    (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _))
wenzelm@65561
   834
  }
wenzelm@65561
   835
wenzelm@67026
   836
  def load_structure(options: Options,
wenzelm@66968
   837
    dirs: List[Path] = Nil,
wenzelm@66968
   838
    select_dirs: List[Path] = Nil,
wenzelm@67052
   839
    infos: List[Info] = Nil): Structure =
wenzelm@62631
   840
  {
wenzelm@66764
   841
    def load_dir(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@62635
   842
      load_root(select, dir) ::: load_roots(select, dir)
wenzelm@62631
   843
wenzelm@66764
   844
    def load_root(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@66764
   845
    {
wenzelm@66764
   846
      val root = dir + ROOT
wenzelm@66764
   847
      if (root.is_file) List((select, root)) else Nil
wenzelm@66764
   848
    }
wenzelm@62631
   849
wenzelm@66764
   850
    def load_roots(select: Boolean, dir: Path): List[(Boolean, Path)] =
wenzelm@62631
   851
    {
wenzelm@62631
   852
      val roots = dir + ROOTS
wenzelm@62631
   853
      if (roots.is_file) {
wenzelm@62631
   854
        for {
wenzelm@66818
   855
          entry <- parse_roots(roots)
wenzelm@62631
   856
          dir1 =
wenzelm@66818
   857
            try { check_session_dir(dir + Path.explode(entry)) }
wenzelm@62631
   858
            catch {
wenzelm@62631
   859
              case ERROR(msg) =>
wenzelm@62631
   860
                error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
wenzelm@62631
   861
            }
wenzelm@66764
   862
          res <- load_dir(select, dir1)
wenzelm@66764
   863
        } yield res
wenzelm@62631
   864
      }
wenzelm@62631
   865
      else Nil
wenzelm@62631
   866
    }
wenzelm@62631
   867
wenzelm@66764
   868
    val roots =
wenzelm@62631
   869
      for {
wenzelm@65561
   870
        (select, dir) <- directories(dirs, select_dirs)
wenzelm@66764
   871
        res <- load_dir(select, check_session_dir(dir))
wenzelm@66764
   872
      } yield res
wenzelm@66764
   873
wenzelm@66764
   874
    val unique_roots =
wenzelm@66764
   875
      ((Map.empty[JFile, (Boolean, Path)] /: roots) { case (m, (select, path)) =>
wenzelm@66764
   876
        val file = path.canonical_file
wenzelm@66764
   877
        m.get(file) match {
wenzelm@66764
   878
          case None => m + (file -> (select, path))
wenzelm@66764
   879
          case Some((select1, path1)) => m + (file -> (select1 || select, path1))
wenzelm@66764
   880
        }
wenzelm@66764
   881
      }).toList.map(_._2)
wenzelm@66764
   882
wenzelm@66968
   883
    make(unique_roots.flatMap(p => read_root(options, p._1, p._2)) ::: infos)
wenzelm@62631
   884
  }
wenzelm@62632
   885
wenzelm@62632
   886
wenzelm@62637
   887
wenzelm@62704
   888
  /** heap file with SHA1 digest **/
wenzelm@62704
   889
wenzelm@62704
   890
  private val sha1_prefix = "SHA1:"
wenzelm@62704
   891
wenzelm@62704
   892
  def read_heap_digest(heap: Path): Option[String] =
wenzelm@62704
   893
  {
wenzelm@62704
   894
    if (heap.is_file) {
wenzelm@62704
   895
      val file = FileChannel.open(heap.file.toPath, StandardOpenOption.READ)
wenzelm@62704
   896
      try {
wenzelm@62704
   897
        val len = file.size
wenzelm@62704
   898
        val n = sha1_prefix.length + SHA1.digest_length
wenzelm@62704
   899
        if (len >= n) {
wenzelm@62704
   900
          file.position(len - n)
wenzelm@62704
   901
wenzelm@62704
   902
          val buf = ByteBuffer.allocate(n)
wenzelm@62704
   903
          var i = 0
wenzelm@62704
   904
          var m = 0
wenzelm@62704
   905
          do {
wenzelm@62704
   906
            m = file.read(buf)
wenzelm@62704
   907
            if (m != -1) i += m
wenzelm@62704
   908
          }
wenzelm@62704
   909
          while (m != -1 && n > i)
wenzelm@62704
   910
wenzelm@62704
   911
          if (i == n) {
wenzelm@62704
   912
            val prefix = new String(buf.array(), 0, sha1_prefix.length, UTF8.charset)
wenzelm@62704
   913
            val s = new String(buf.array(), sha1_prefix.length, SHA1.digest_length, UTF8.charset)
wenzelm@62704
   914
            if (prefix == sha1_prefix) Some(s) else None
wenzelm@62704
   915
          }
wenzelm@62704
   916
          else None
wenzelm@62704
   917
        }
wenzelm@62704
   918
        else None
wenzelm@62704
   919
      }
wenzelm@62704
   920
      finally { file.close }
wenzelm@62704
   921
    }
wenzelm@62704
   922
    else None
wenzelm@62704
   923
  }
wenzelm@62704
   924
wenzelm@62704
   925
  def write_heap_digest(heap: Path): String =
wenzelm@62704
   926
    read_heap_digest(heap) match {
wenzelm@62704
   927
      case None =>
wenzelm@62704
   928
        val s = SHA1.digest(heap).rep
wenzelm@62704
   929
        File.append(heap, sha1_prefix + s)
wenzelm@62704
   930
        s
wenzelm@62704
   931
      case Some(s) => s
wenzelm@62704
   932
    }
wenzelm@62704
   933
wenzelm@62704
   934
wenzelm@62704
   935
wenzelm@62637
   936
  /** persistent store **/
wenzelm@62632
   937
wenzelm@65296
   938
  object Session_Info
wenzelm@65296
   939
  {
wenzelm@66857
   940
    val session_name = SQL.Column.string("session_name").make_primary_key
wenzelm@65326
   941
wenzelm@65296
   942
    // Build_Log.Session_Info
wenzelm@65296
   943
    val session_timing = SQL.Column.bytes("session_timing")
wenzelm@65296
   944
    val command_timings = SQL.Column.bytes("command_timings")
wenzelm@66873
   945
    val theory_timings = SQL.Column.bytes("theory_timings")
wenzelm@65296
   946
    val ml_statistics = SQL.Column.bytes("ml_statistics")
wenzelm@65296
   947
    val task_statistics = SQL.Column.bytes("task_statistics")
wenzelm@65934
   948
    val errors = SQL.Column.bytes("errors")
wenzelm@65296
   949
    val build_log_columns =
wenzelm@66873
   950
      List(session_name, session_timing, command_timings, theory_timings,
wenzelm@66873
   951
        ml_statistics, task_statistics, errors)
wenzelm@65296
   952
wenzelm@65296
   953
    // Build.Session_Info
wenzelm@65296
   954
    val sources = SQL.Column.string("sources")
wenzelm@65296
   955
    val input_heaps = SQL.Column.string("input_heaps")
wenzelm@65296
   956
    val output_heap = SQL.Column.string("output_heap")
wenzelm@65296
   957
    val return_code = SQL.Column.int("return_code")
wenzelm@66746
   958
    val build_columns = List(sources, input_heaps, output_heap, return_code)
wenzelm@65296
   959
wenzelm@65296
   960
    val table = SQL.Table("isabelle_session_info", build_log_columns ::: build_columns)
wenzelm@65296
   961
  }
wenzelm@65296
   962
wenzelm@62632
   963
  def store(system_mode: Boolean = false): Store = new Store(system_mode)
wenzelm@62632
   964
wenzelm@65857
   965
  class Store private[Sessions](system_mode: Boolean)
wenzelm@62632
   966
  {
wenzelm@65278
   967
    /* file names */
wenzelm@65278
   968
wenzelm@65281
   969
    def database(name: String): Path = Path.basic("log") + Path.basic(name).ext("db")
wenzelm@65278
   970
    def log(name: String): Path = Path.basic("log") + Path.basic(name)
wenzelm@65278
   971
    def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@65278
   972
wenzelm@65278
   973
wenzelm@65286
   974
    /* SQL database content */
wenzelm@65283
   975
wenzelm@68169
   976
    val xml_cache = XML.make_cache()
wenzelm@68018
   977
    val xz_cache = XZ.make_cache()
wenzelm@65857
   978
wenzelm@65320
   979
    def read_bytes(db: SQL.Database, name: String, column: SQL.Column): Bytes =
wenzelm@65698
   980
      db.using_statement(Session_Info.table.select(List(column),
wenzelm@65699
   981
        Session_Info.session_name.where_equal(name)))(stmt =>
wenzelm@65291
   982
      {
wenzelm@65740
   983
        val res = stmt.execute_query()
wenzelm@65740
   984
        if (!res.next()) Bytes.empty else res.bytes(column)
wenzelm@65291
   985
      })
wenzelm@65285
   986
wenzelm@65320
   987
    def read_properties(db: SQL.Database, name: String, column: SQL.Column): List[Properties.T] =
wenzelm@68018
   988
      Properties.uncompress(
wenzelm@68018
   989
        read_bytes(db, name, column), cache = xz_cache, xml_cache = Some(xml_cache))
wenzelm@65286
   990
wenzelm@65283
   991
wenzelm@62637
   992
    /* output */
wenzelm@62632
   993
wenzelm@62632
   994
    val browser_info: Path =
wenzelm@62632
   995
      if (system_mode) Path.explode("~~/browser_info")
wenzelm@62632
   996
      else Path.explode("$ISABELLE_BROWSER_INFO")
wenzelm@62632
   997
wenzelm@62637
   998
    val output_dir: Path =
wenzelm@62637
   999
      if (system_mode) Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@62637
  1000
      else Path.explode("$ISABELLE_OUTPUT")
wenzelm@62637
  1001
wenzelm@65298
  1002
    override def toString: String = "Store(output_dir = " + output_dir.expand + ")"
wenzelm@65298
  1003
wenzelm@62637
  1004
    def prepare_output() { Isabelle_System.mkdirs(output_dir + Path.basic("log")) }
wenzelm@62637
  1005
wenzelm@68086
  1006
    def output_database(name: String): Path = output_dir + database(name)
wenzelm@68086
  1007
    def output_log(name: String): Path = output_dir + log(name)
wenzelm@68086
  1008
    def output_log_gz(name: String): Path = output_dir + log_gz(name)
wenzelm@68086
  1009
wenzelm@62637
  1010
wenzelm@62637
  1011
    /* input */
wenzelm@62637
  1012
wenzelm@62637
  1013
    private val input_dirs =
wenzelm@62632
  1014
      if (system_mode) List(output_dir)
wenzelm@62633
  1015
      else {
wenzelm@62633
  1016
        val ml_ident = Path.explode("$ML_IDENTIFIER").expand
wenzelm@62633
  1017
        output_dir :: Path.split(Isabelle_System.getenv_strict("ISABELLE_PATH")).map(_ + ml_ident)
wenzelm@62633
  1018
      }
wenzelm@62632
  1019
wenzelm@65291
  1020
    def find_database_heap(name: String): Option[(Path, Option[String])] =
wenzelm@65291
  1021
      input_dirs.find(dir => (dir + database(name)).is_file).map(dir =>
wenzelm@65291
  1022
        (dir + database(name), read_heap_digest(dir + Path.basic(name))))
wenzelm@62632
  1023
wenzelm@65281
  1024
    def find_database(name: String): Option[Path] =
wenzelm@65281
  1025
      input_dirs.map(_ + database(name)).find(_.is_file)
wenzelm@65281
  1026
wenzelm@62637
  1027
    def heap(name: String): Path =
wenzelm@65288
  1028
      input_dirs.map(_ + Path.basic(name)).find(_.is_file) getOrElse
wenzelm@62637
  1029
        error("Unknown logic " + quote(name) + " -- no heap file found in:\n" +
wenzelm@62769
  1030
          cat_lines(input_dirs.map(dir => "  " + dir.expand.implode)))
wenzelm@65287
  1031
wenzelm@65287
  1032
wenzelm@65296
  1033
    /* session info */
wenzelm@65281
  1034
wenzelm@68086
  1035
    def init_session_info(db: SQL.Database, name: String)
wenzelm@68086
  1036
    {
wenzelm@68086
  1037
      db.transaction {
wenzelm@68086
  1038
        db.create_table(Session_Info.table)
wenzelm@68086
  1039
        db.using_statement(
wenzelm@68086
  1040
          Session_Info.table.delete(Session_Info.session_name.where_equal(name)))(_.execute)
wenzelm@68086
  1041
      }
wenzelm@68086
  1042
    }
wenzelm@68086
  1043
wenzelm@65296
  1044
    def write_session_info(
wenzelm@65318
  1045
      db: SQL.Database,
wenzelm@65320
  1046
      name: String,
wenzelm@65318
  1047
      build_log: Build_Log.Session_Info,
wenzelm@65318
  1048
      build: Build.Session_Info)
wenzelm@65281
  1049
    {
wenzelm@65281
  1050
      db.transaction {
wenzelm@65698
  1051
        db.using_statement(Session_Info.table.insert())(stmt =>
wenzelm@65281
  1052
        {
wenzelm@65748
  1053
          stmt.string(1) = name
wenzelm@65857
  1054
          stmt.bytes(2) = Properties.encode(build_log.session_timing)
wenzelm@68018
  1055
          stmt.bytes(3) = Properties.compress(build_log.command_timings, cache = xz_cache)
wenzelm@68018
  1056
          stmt.bytes(4) = Properties.compress(build_log.theory_timings, cache = xz_cache)
wenzelm@68018
  1057
          stmt.bytes(5) = Properties.compress(build_log.ml_statistics, cache = xz_cache)
wenzelm@68018
  1058
          stmt.bytes(6) = Properties.compress(build_log.task_statistics, cache = xz_cache)
wenzelm@68018
  1059
          stmt.bytes(7) = Build_Log.compress_errors(build_log.errors, cache = xz_cache)
wenzelm@66873
  1060
          stmt.string(8) = build.sources
wenzelm@66873
  1061
          stmt.string(9) = cat_lines(build.input_heaps)
wenzelm@66873
  1062
          stmt.string(10) = build.output_heap getOrElse ""
wenzelm@66873
  1063
          stmt.int(11) = build.return_code
wenzelm@65281
  1064
          stmt.execute()
wenzelm@65281
  1065
        })
wenzelm@65281
  1066
      }
wenzelm@65281
  1067
    }
wenzelm@65281
  1068
wenzelm@65320
  1069
    def read_session_timing(db: SQL.Database, name: String): Properties.T =
wenzelm@65857
  1070
      Properties.decode(read_bytes(db, name, Session_Info.session_timing), Some(xml_cache))
wenzelm@65286
  1071
wenzelm@65320
  1072
    def read_command_timings(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1073
      read_properties(db, name, Session_Info.command_timings)
wenzelm@65286
  1074
wenzelm@66873
  1075
    def read_theory_timings(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@66873
  1076
      read_properties(db, name, Session_Info.theory_timings)
wenzelm@66873
  1077
wenzelm@65320
  1078
    def read_ml_statistics(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1079
      read_properties(db, name, Session_Info.ml_statistics)
wenzelm@65286
  1080
wenzelm@65320
  1081
    def read_task_statistics(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
  1082
      read_properties(db, name, Session_Info.task_statistics)
wenzelm@65286
  1083
wenzelm@65937
  1084
    def read_errors(db: SQL.Database, name: String): List[String] =
wenzelm@68018
  1085
      Build_Log.uncompress_errors(read_bytes(db, name, Session_Info.errors), cache = xz_cache)
wenzelm@65937
  1086
wenzelm@65320
  1087
    def read_build(db: SQL.Database, name: String): Option[Build.Session_Info] =
wenzelm@66744
  1088
    {
wenzelm@66957
  1089
      if (db.tables.contains(Session_Info.table.name)) {
wenzelm@66957
  1090
        db.using_statement(Session_Info.table.select(Session_Info.build_columns,
wenzelm@66957
  1091
          Session_Info.session_name.where_equal(name)))(stmt =>
wenzelm@66957
  1092
        {
wenzelm@66957
  1093
          val res = stmt.execute_query()
wenzelm@66957
  1094
          if (!res.next()) None
wenzelm@66957
  1095
          else {
wenzelm@66957
  1096
            Some(
wenzelm@66957
  1097
              Build.Session_Info(
wenzelm@66957
  1098
                res.string(Session_Info.sources),
wenzelm@66957
  1099
                split_lines(res.string(Session_Info.input_heaps)),
wenzelm@66957
  1100
                res.string(Session_Info.output_heap) match { case "" => None case s => Some(s) },
wenzelm@66957
  1101
                res.int(Session_Info.return_code)))
wenzelm@66957
  1102
          }
wenzelm@66957
  1103
        })
wenzelm@66957
  1104
      }
wenzelm@66957
  1105
      else None
wenzelm@66744
  1106
    }
wenzelm@65281
  1107
  }
wenzelm@62631
  1108
}