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