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