src/Pure/Thy/sessions.scala
author wenzelm
Fri Mar 17 09:49:01 2017 +0100 (2017-03-17)
changeset 65283 042160aee6c2
parent 65282 f4c5f10829a0
child 65284 d189ff34b5b9
permissions -rw-r--r--
data representation with XML.Cache;
tuned;
wenzelm@62631
     1
/*  Title:      Pure/Thy/sessions.scala
wenzelm@62631
     2
    Author:     Makarius
wenzelm@62631
     3
wenzelm@62973
     4
Isabelle session information.
wenzelm@62631
     5
*/
wenzelm@62631
     6
wenzelm@62631
     7
package isabelle
wenzelm@62631
     8
wenzelm@62704
     9
import java.nio.ByteBuffer
wenzelm@62704
    10
import java.nio.channels.FileChannel
wenzelm@62704
    11
import java.nio.file.StandardOpenOption
wenzelm@62631
    12
wenzelm@62631
    13
import scala.collection.SortedSet
wenzelm@62631
    14
import scala.collection.mutable
wenzelm@62631
    15
wenzelm@62631
    16
wenzelm@62631
    17
object Sessions
wenzelm@62631
    18
{
wenzelm@62883
    19
  /* Pure */
wenzelm@62883
    20
wenzelm@63022
    21
  def pure_name(name: String): Boolean = name == Thy_Header.PURE
wenzelm@62883
    22
wenzelm@62902
    23
  def pure_files(resources: Resources, syntax: Outer_Syntax, dir: Path): List[Path] =
wenzelm@62902
    24
  {
wenzelm@62946
    25
    val roots = Thy_Header.ml_roots.map(_._1)
wenzelm@62902
    26
    val loaded_files =
wenzelm@62946
    27
      roots.flatMap(root => resources.loaded_files(syntax, File.read(dir + Path.explode(root))))
wenzelm@62946
    28
    (roots ::: loaded_files).map(file => dir + Path.explode(file))
wenzelm@62902
    29
  }
wenzelm@62883
    30
wenzelm@65254
    31
  def pure_base(options: Options): Base = session_base(options, Thy_Header.PURE)
wenzelm@65254
    32
wenzelm@62883
    33
wenzelm@65251
    34
  /* base info and source dependencies */
wenzelm@64856
    35
wenzelm@64856
    36
  object Base
wenzelm@64856
    37
  {
wenzelm@64856
    38
    lazy val bootstrap: Base =
wenzelm@64856
    39
      Base(keywords = Thy_Header.bootstrap_header, syntax = Thy_Header.bootstrap_syntax)
wenzelm@64856
    40
  }
wenzelm@64856
    41
wenzelm@64856
    42
  sealed case class Base(
wenzelm@64856
    43
    loaded_theories: Set[String] = Set.empty,
wenzelm@64856
    44
    known_theories: Map[String, Document.Node.Name] = Map.empty,
wenzelm@64856
    45
    keywords: Thy_Header.Keywords = Nil,
wenzelm@64856
    46
    syntax: Outer_Syntax = Outer_Syntax.empty,
wenzelm@64856
    47
    sources: List[(Path, SHA1.Digest)] = Nil,
wenzelm@64856
    48
    session_graph: Graph_Display.Graph = Graph_Display.empty_graph)
wenzelm@64856
    49
wenzelm@65251
    50
  sealed case class Deps(deps: Map[String, Base])
wenzelm@65251
    51
  {
wenzelm@65251
    52
    def is_empty: Boolean = deps.isEmpty
wenzelm@65251
    53
    def apply(name: String): Base = deps(name)
wenzelm@65251
    54
    def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
wenzelm@65251
    55
  }
wenzelm@64856
    56
wenzelm@65251
    57
  def dependencies(
wenzelm@65251
    58
      progress: Progress = No_Progress,
wenzelm@65251
    59
      inlined_files: Boolean = false,
wenzelm@65251
    60
      verbose: Boolean = false,
wenzelm@65251
    61
      list_files: Boolean = false,
wenzelm@65251
    62
      check_keywords: Set[String] = Set.empty,
wenzelm@65251
    63
      tree: Tree): Deps =
wenzelm@65251
    64
    Deps((Map.empty[String, Base] /: tree.topological_order)(
wenzelm@65251
    65
      { case (deps, (name, info)) =>
wenzelm@65251
    66
          if (progress.stopped) throw Exn.Interrupt()
wenzelm@65251
    67
wenzelm@65251
    68
          try {
wenzelm@65251
    69
            val resources =
wenzelm@65251
    70
              new Resources(
wenzelm@65251
    71
                info.parent match {
wenzelm@65251
    72
                  case None => Base.bootstrap
wenzelm@65251
    73
                  case Some(parent) => deps(parent)
wenzelm@65251
    74
                })
wenzelm@65251
    75
wenzelm@65251
    76
            if (verbose || list_files) {
wenzelm@65251
    77
              val groups =
wenzelm@65251
    78
                if (info.groups.isEmpty) ""
wenzelm@65251
    79
                else info.groups.mkString(" (", " ", ")")
wenzelm@65251
    80
              progress.echo("Session " + info.chapter + "/" + name + groups)
wenzelm@65251
    81
            }
wenzelm@65251
    82
wenzelm@65251
    83
            val thy_deps =
wenzelm@65251
    84
            {
wenzelm@65251
    85
              val root_theories =
wenzelm@65251
    86
                info.theories.flatMap({
wenzelm@65251
    87
                  case (global, _, thys) =>
wenzelm@65251
    88
                    thys.map(thy =>
wenzelm@65251
    89
                      (resources.node_name(
wenzelm@65251
    90
                        if (global) "" else name, info.dir + resources.thy_path(thy)), info.pos))
wenzelm@65251
    91
                })
wenzelm@65251
    92
              val thy_deps = resources.thy_info.dependencies(name, root_theories)
wenzelm@65251
    93
wenzelm@65251
    94
              thy_deps.errors match {
wenzelm@65251
    95
                case Nil => thy_deps
wenzelm@65251
    96
                case errs => error(cat_lines(errs))
wenzelm@65251
    97
              }
wenzelm@65251
    98
            }
wenzelm@65251
    99
wenzelm@65251
   100
            val known_theories =
wenzelm@65251
   101
              (resources.base.known_theories /: thy_deps.deps)({ case (known, dep) =>
wenzelm@65251
   102
                val name = dep.name
wenzelm@65251
   103
                known.get(name.theory) match {
wenzelm@65251
   104
                  case Some(name1) if name != name1 =>
wenzelm@65251
   105
                    error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
wenzelm@65251
   106
                  case _ =>
wenzelm@65251
   107
                    known + (name.theory -> name) + (Long_Name.base_name(name.theory) -> name)
wenzelm@65251
   108
                }
wenzelm@65251
   109
              })
wenzelm@65251
   110
wenzelm@65251
   111
            val loaded_theories = thy_deps.loaded_theories
wenzelm@65251
   112
            val keywords = thy_deps.keywords
wenzelm@65251
   113
            val syntax = thy_deps.syntax
wenzelm@65251
   114
wenzelm@65251
   115
            val theory_files = thy_deps.deps.map(dep => Path.explode(dep.name.node))
wenzelm@65251
   116
            val loaded_files =
wenzelm@65251
   117
              if (inlined_files) {
wenzelm@65251
   118
                val pure_files =
wenzelm@65251
   119
                  if (pure_name(name)) Sessions.pure_files(resources, syntax, info.dir)
wenzelm@65251
   120
                  else Nil
wenzelm@65251
   121
                pure_files ::: thy_deps.loaded_files
wenzelm@65251
   122
              }
wenzelm@65251
   123
              else Nil
wenzelm@65251
   124
wenzelm@65251
   125
            val all_files =
wenzelm@65251
   126
              (theory_files ::: loaded_files :::
wenzelm@65251
   127
                info.files.map(file => info.dir + file) :::
wenzelm@65251
   128
                info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
wenzelm@65251
   129
wenzelm@65251
   130
            if (list_files)
wenzelm@65251
   131
              progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
wenzelm@65251
   132
wenzelm@65251
   133
            if (check_keywords.nonEmpty)
wenzelm@65251
   134
              Check_Keywords.check_keywords(progress, syntax.keywords, check_keywords, theory_files)
wenzelm@65251
   135
wenzelm@65251
   136
            val sources = all_files.map(p => (p, SHA1.digest(p.file)))
wenzelm@65251
   137
wenzelm@65251
   138
            val session_graph =
wenzelm@65251
   139
              Present.session_graph(info.parent getOrElse "",
wenzelm@65251
   140
                resources.base.loaded_theories, thy_deps.deps)
wenzelm@65251
   141
wenzelm@65251
   142
            val base =
wenzelm@65251
   143
              Base(loaded_theories, known_theories, keywords, syntax, sources, session_graph)
wenzelm@65251
   144
            deps + (name -> base)
wenzelm@65251
   145
          }
wenzelm@65251
   146
          catch {
wenzelm@65251
   147
            case ERROR(msg) =>
wenzelm@65251
   148
              cat_error(msg, "The error(s) above occurred in session " +
wenzelm@65251
   149
                quote(name) + Position.here(info.pos))
wenzelm@65251
   150
          }
wenzelm@65251
   151
      }))
wenzelm@65251
   152
wenzelm@65251
   153
  def session_base(options: Options, session: String, dirs: List[Path] = Nil): Base =
wenzelm@65251
   154
  {
wenzelm@65251
   155
    val (_, tree) = load(options, dirs = dirs).selection(sessions = List(session))
wenzelm@65251
   156
    dependencies(tree = tree)(session)
wenzelm@65251
   157
  }
wenzelm@65251
   158
wenzelm@65251
   159
wenzelm@65251
   160
  /* session tree */
wenzelm@62631
   161
wenzelm@62631
   162
  sealed case class Info(
wenzelm@62631
   163
    chapter: String,
wenzelm@62631
   164
    select: Boolean,
wenzelm@62631
   165
    pos: Position.T,
wenzelm@62631
   166
    groups: List[String],
wenzelm@62631
   167
    dir: Path,
wenzelm@62631
   168
    parent: Option[String],
wenzelm@62631
   169
    description: String,
wenzelm@62631
   170
    options: Options,
wenzelm@62631
   171
    theories: List[(Boolean, Options, List[Path])],
wenzelm@62631
   172
    files: List[Path],
wenzelm@62631
   173
    document_files: List[(Path, Path)],
wenzelm@62631
   174
    meta_digest: SHA1.Digest)
wenzelm@62631
   175
  {
wenzelm@62631
   176
    def timeout: Time = Time.seconds(options.real("timeout") * options.real("timeout_scale"))
wenzelm@62631
   177
  }
wenzelm@62631
   178
wenzelm@62631
   179
  object Tree
wenzelm@62631
   180
  {
wenzelm@62631
   181
    def apply(infos: Seq[(String, Info)]): Tree =
wenzelm@62631
   182
    {
wenzelm@62631
   183
      val graph1 =
wenzelm@62631
   184
        (Graph.string[Info] /: infos) {
wenzelm@62631
   185
          case (graph, (name, info)) =>
wenzelm@62631
   186
            if (graph.defined(name))
wenzelm@62631
   187
              error("Duplicate session " + quote(name) + Position.here(info.pos) +
wenzelm@62631
   188
                Position.here(graph.get_node(name).pos))
wenzelm@62631
   189
            else graph.new_node(name, info)
wenzelm@62631
   190
        }
wenzelm@62631
   191
      val graph2 =
wenzelm@62631
   192
        (graph1 /: graph1.iterator) {
wenzelm@62631
   193
          case (graph, (name, (info, _))) =>
wenzelm@62631
   194
            info.parent match {
wenzelm@62631
   195
              case None => graph
wenzelm@62631
   196
              case Some(parent) =>
wenzelm@62631
   197
                if (!graph.defined(parent))
wenzelm@62631
   198
                  error("Bad parent session " + quote(parent) + " for " +
wenzelm@62631
   199
                    quote(name) + Position.here(info.pos))
wenzelm@62631
   200
wenzelm@62631
   201
                try { graph.add_edge_acyclic(parent, name) }
wenzelm@62631
   202
                catch {
wenzelm@62631
   203
                  case exn: Graph.Cycles[_] =>
wenzelm@62631
   204
                    error(cat_lines(exn.cycles.map(cycle =>
wenzelm@62631
   205
                      "Cyclic session dependency of " +
wenzelm@62631
   206
                        cycle.map(c => quote(c.toString)).mkString(" via "))) +
wenzelm@62631
   207
                          Position.here(info.pos))
wenzelm@62631
   208
                }
wenzelm@62631
   209
            }
wenzelm@62631
   210
        }
wenzelm@62631
   211
      new Tree(graph2)
wenzelm@62631
   212
    }
wenzelm@62631
   213
  }
wenzelm@62631
   214
wenzelm@62631
   215
  final class Tree private(val graph: Graph[String, Info])
wenzelm@62631
   216
    extends PartialFunction[String, Info]
wenzelm@62631
   217
  {
wenzelm@62631
   218
    def apply(name: String): Info = graph.get_node(name)
wenzelm@62631
   219
    def isDefinedAt(name: String): Boolean = graph.defined(name)
wenzelm@62631
   220
wenzelm@62631
   221
    def selection(
wenzelm@62631
   222
      requirements: Boolean = false,
wenzelm@62631
   223
      all_sessions: Boolean = false,
wenzelm@62631
   224
      exclude_session_groups: List[String] = Nil,
wenzelm@62631
   225
      exclude_sessions: List[String] = Nil,
wenzelm@62631
   226
      session_groups: List[String] = Nil,
wenzelm@62631
   227
      sessions: List[String] = Nil): (List[String], Tree) =
wenzelm@62631
   228
    {
wenzelm@62631
   229
      val bad_sessions =
wenzelm@62631
   230
        SortedSet((exclude_sessions ::: sessions).filterNot(isDefinedAt(_)): _*).toList
wenzelm@62631
   231
      if (bad_sessions.nonEmpty) error("Undefined session(s): " + commas_quote(bad_sessions))
wenzelm@62631
   232
wenzelm@62631
   233
      val excluded =
wenzelm@62631
   234
      {
wenzelm@62631
   235
        val exclude_group = exclude_session_groups.toSet
wenzelm@62631
   236
        val exclude_group_sessions =
wenzelm@62631
   237
          (for {
wenzelm@62631
   238
            (name, (info, _)) <- graph.iterator
wenzelm@62631
   239
            if apply(name).groups.exists(exclude_group)
wenzelm@62631
   240
          } yield name).toList
wenzelm@62631
   241
        graph.all_succs(exclude_group_sessions ::: exclude_sessions).toSet
wenzelm@62631
   242
      }
wenzelm@62631
   243
wenzelm@62631
   244
      val pre_selected =
wenzelm@62631
   245
      {
wenzelm@62631
   246
        if (all_sessions) graph.keys
wenzelm@62631
   247
        else {
wenzelm@62631
   248
          val select_group = session_groups.toSet
wenzelm@62631
   249
          val select = sessions.toSet
wenzelm@62631
   250
          (for {
wenzelm@62631
   251
            (name, (info, _)) <- graph.iterator
wenzelm@62631
   252
            if info.select || select(name) || apply(name).groups.exists(select_group)
wenzelm@62631
   253
          } yield name).toList
wenzelm@62631
   254
        }
wenzelm@62631
   255
      }.filterNot(excluded)
wenzelm@62631
   256
wenzelm@62631
   257
      val selected =
wenzelm@62631
   258
        if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
wenzelm@62631
   259
        else pre_selected
wenzelm@62631
   260
wenzelm@62631
   261
      val graph1 = graph.restrict(graph.all_preds(selected).toSet)
wenzelm@62631
   262
      (selected, new Tree(graph1))
wenzelm@62631
   263
    }
wenzelm@62631
   264
wenzelm@62631
   265
    def ancestors(name: String): List[String] =
wenzelm@62631
   266
      graph.all_preds(List(name)).tail.reverse
wenzelm@62631
   267
wenzelm@62631
   268
    def topological_order: List[(String, Info)] =
wenzelm@62631
   269
      graph.topological_order.map(name => (name, apply(name)))
wenzelm@62631
   270
wenzelm@62631
   271
    override def toString: String = graph.keys_iterator.mkString("Sessions.Tree(", ", ", ")")
wenzelm@62631
   272
  }
wenzelm@62631
   273
wenzelm@62631
   274
wenzelm@62631
   275
  /* parser */
wenzelm@62631
   276
wenzelm@62864
   277
  val ROOT = Path.explode("ROOT")
wenzelm@62864
   278
  val ROOTS = Path.explode("ROOTS")
wenzelm@62864
   279
wenzelm@62631
   280
  private val CHAPTER = "chapter"
wenzelm@62631
   281
  private val SESSION = "session"
wenzelm@62631
   282
  private val IN = "in"
wenzelm@62631
   283
  private val DESCRIPTION = "description"
wenzelm@62631
   284
  private val OPTIONS = "options"
wenzelm@62631
   285
  private val GLOBAL_THEORIES = "global_theories"
wenzelm@62631
   286
  private val THEORIES = "theories"
wenzelm@62631
   287
  private val FILES = "files"
wenzelm@62631
   288
  private val DOCUMENT_FILES = "document_files"
wenzelm@62631
   289
wenzelm@62631
   290
  lazy val root_syntax =
wenzelm@63443
   291
    Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" + IN +
wenzelm@63443
   292
      (CHAPTER, Keyword.THY_DECL) +
wenzelm@63443
   293
      (SESSION, Keyword.THY_DECL) +
wenzelm@63443
   294
      (DESCRIPTION, Keyword.QUASI_COMMAND) +
wenzelm@63443
   295
      (OPTIONS, Keyword.QUASI_COMMAND) +
wenzelm@63443
   296
      (GLOBAL_THEORIES, Keyword.QUASI_COMMAND) +
wenzelm@63443
   297
      (THEORIES, Keyword.QUASI_COMMAND) +
wenzelm@63443
   298
      (FILES, Keyword.QUASI_COMMAND) +
wenzelm@63443
   299
      (DOCUMENT_FILES, Keyword.QUASI_COMMAND)
wenzelm@62631
   300
wenzelm@62968
   301
  private object Parser extends Parse.Parser with Options.Parser
wenzelm@62631
   302
  {
wenzelm@62631
   303
    private abstract class Entry
wenzelm@62631
   304
    private sealed case class Chapter(name: String) extends Entry
wenzelm@62631
   305
    private sealed case class Session_Entry(
wenzelm@62631
   306
      pos: Position.T,
wenzelm@62631
   307
      name: String,
wenzelm@62631
   308
      groups: List[String],
wenzelm@62631
   309
      path: String,
wenzelm@62631
   310
      parent: Option[String],
wenzelm@62631
   311
      description: String,
wenzelm@62631
   312
      options: List[Options.Spec],
wenzelm@62631
   313
      theories: List[(Boolean, List[Options.Spec], List[String])],
wenzelm@62631
   314
      files: List[String],
wenzelm@62631
   315
      document_files: List[(String, String)]) extends Entry
wenzelm@62631
   316
wenzelm@62631
   317
    private val chapter: Parser[Chapter] =
wenzelm@62631
   318
    {
wenzelm@62631
   319
      val chapter_name = atom("chapter name", _.is_name)
wenzelm@62631
   320
wenzelm@62631
   321
      command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
wenzelm@62631
   322
    }
wenzelm@62631
   323
wenzelm@62631
   324
    private val session_entry: Parser[Session_Entry] =
wenzelm@62631
   325
    {
wenzelm@62631
   326
      val session_name = atom("session name", _.is_name)
wenzelm@62631
   327
wenzelm@62631
   328
      val option =
wenzelm@62968
   329
        option_name ~ opt($$$("=") ~! option_value ^^
wenzelm@62968
   330
          { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@62631
   331
      val options = $$$("[") ~> rep1sep(option, $$$(",")) <~ $$$("]")
wenzelm@62631
   332
wenzelm@62631
   333
      val theories =
wenzelm@62631
   334
        ($$$(GLOBAL_THEORIES) | $$$(THEORIES)) ~!
wenzelm@62969
   335
          ((options | success(Nil)) ~ rep(theory_name)) ^^
wenzelm@62631
   336
          { case x ~ (y ~ z) => (x == GLOBAL_THEORIES, y, z) }
wenzelm@62631
   337
wenzelm@62631
   338
      val document_files =
wenzelm@62631
   339
        $$$(DOCUMENT_FILES) ~!
wenzelm@62631
   340
          (($$$("(") ~! ($$$(IN) ~! (path ~ $$$(")"))) ^^
wenzelm@62631
   341
              { case _ ~ (_ ~ (x ~ _)) => x } | success("document")) ~
wenzelm@62631
   342
            rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
wenzelm@62631
   343
wenzelm@62631
   344
      command(SESSION) ~!
wenzelm@62631
   345
        (position(session_name) ~
wenzelm@62631
   346
          (($$$("(") ~! (rep1(name) <~ $$$(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   347
          (($$$(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
wenzelm@62631
   348
          ($$$("=") ~!
wenzelm@62631
   349
            (opt(session_name ~! $$$("+") ^^ { case x ~ _ => x }) ~
wenzelm@62631
   350
              (($$$(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
wenzelm@62631
   351
              (($$$(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   352
              rep1(theories) ~
wenzelm@62631
   353
              (($$$(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   354
              (rep(document_files) ^^ (x => x.flatten))))) ^^
wenzelm@62631
   355
        { case _ ~ ((a, pos) ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i))) =>
wenzelm@62631
   356
            Session_Entry(pos, a, b, c, d, e, f, g, h, i) }
wenzelm@62631
   357
    }
wenzelm@62631
   358
wenzelm@62631
   359
    def parse(options: Options, select: Boolean, dir: Path): List[(String, Info)] =
wenzelm@62631
   360
    {
wenzelm@62631
   361
      def make_info(entry_chapter: String, entry: Session_Entry): (String, Info) =
wenzelm@62631
   362
      {
wenzelm@62631
   363
        try {
wenzelm@62631
   364
          val name = entry.name
wenzelm@62631
   365
wenzelm@62631
   366
          if (name == "") error("Bad session name")
wenzelm@62883
   367
          if (pure_name(name) && entry.parent.isDefined) error("Illegal parent session")
wenzelm@62883
   368
          if (!pure_name(name) && !entry.parent.isDefined) error("Missing parent session")
wenzelm@62631
   369
wenzelm@62631
   370
          val session_options = options ++ entry.options
wenzelm@62631
   371
wenzelm@62631
   372
          val theories =
wenzelm@62631
   373
            entry.theories.map({ case (global, opts, thys) =>
wenzelm@62631
   374
              (global, session_options ++ opts, thys.map(Path.explode(_))) })
wenzelm@62631
   375
          val files = entry.files.map(Path.explode(_))
wenzelm@62631
   376
          val document_files =
wenzelm@62631
   377
            entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
wenzelm@62631
   378
wenzelm@62631
   379
          val meta_digest =
wenzelm@62631
   380
            SHA1.digest((entry_chapter, name, entry.parent, entry.options,
wenzelm@62631
   381
              entry.theories, entry.files, entry.document_files).toString)
wenzelm@62631
   382
wenzelm@62631
   383
          val info =
wenzelm@62631
   384
            Info(entry_chapter, select, entry.pos, entry.groups, dir + Path.explode(entry.path),
wenzelm@62631
   385
              entry.parent, entry.description, session_options, theories, files,
wenzelm@62631
   386
              document_files, meta_digest)
wenzelm@62631
   387
wenzelm@62631
   388
          (name, info)
wenzelm@62631
   389
        }
wenzelm@62631
   390
        catch {
wenzelm@62631
   391
          case ERROR(msg) =>
wenzelm@62631
   392
            error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@62631
   393
              quote(entry.name) + Position.here(entry.pos))
wenzelm@62631
   394
        }
wenzelm@62631
   395
      }
wenzelm@62631
   396
wenzelm@62631
   397
      val root = dir + ROOT
wenzelm@62631
   398
      if (root.is_file) {
wenzelm@62631
   399
        val toks = Token.explode(root_syntax.keywords, File.read(root))
wenzelm@62631
   400
        val start = Token.Pos.file(root.implode)
wenzelm@62631
   401
wenzelm@62631
   402
        parse_all(rep(chapter | session_entry), Token.reader(toks, start)) match {
wenzelm@62631
   403
          case Success(result, _) =>
wenzelm@62631
   404
            var entry_chapter = "Unsorted"
wenzelm@62631
   405
            val infos = new mutable.ListBuffer[(String, Info)]
wenzelm@62631
   406
            result.foreach {
wenzelm@62631
   407
              case Chapter(name) => entry_chapter = name
wenzelm@62631
   408
              case entry: Session_Entry => infos += make_info(entry_chapter, entry)
wenzelm@62631
   409
            }
wenzelm@62631
   410
            infos.toList
wenzelm@62631
   411
          case bad => error(bad.toString)
wenzelm@62631
   412
        }
wenzelm@62631
   413
      }
wenzelm@62631
   414
      else Nil
wenzelm@62631
   415
    }
wenzelm@62631
   416
  }
wenzelm@62631
   417
wenzelm@62631
   418
wenzelm@62635
   419
  /* load sessions from certain directories */
wenzelm@62631
   420
wenzelm@62631
   421
  private def is_session_dir(dir: Path): Boolean =
wenzelm@62631
   422
    (dir + ROOT).is_file || (dir + ROOTS).is_file
wenzelm@62631
   423
wenzelm@62631
   424
  private def check_session_dir(dir: Path): Path =
wenzelm@62631
   425
    if (is_session_dir(dir)) dir
wenzelm@62631
   426
    else error("Bad session root directory: " + dir.toString)
wenzelm@62631
   427
wenzelm@62635
   428
  def load(options: Options, dirs: List[Path] = Nil, select_dirs: List[Path] = Nil): Tree =
wenzelm@62631
   429
  {
wenzelm@62635
   430
    def load_dir(select: Boolean, dir: Path): List[(String, Info)] =
wenzelm@62635
   431
      load_root(select, dir) ::: load_roots(select, dir)
wenzelm@62631
   432
wenzelm@62635
   433
    def load_root(select: Boolean, dir: Path): List[(String, Info)] =
wenzelm@62631
   434
      Parser.parse(options, select, dir)
wenzelm@62631
   435
wenzelm@62635
   436
    def load_roots(select: Boolean, dir: Path): List[(String, Info)] =
wenzelm@62631
   437
    {
wenzelm@62631
   438
      val roots = dir + ROOTS
wenzelm@62631
   439
      if (roots.is_file) {
wenzelm@62631
   440
        for {
wenzelm@62631
   441
          line <- split_lines(File.read(roots))
wenzelm@62631
   442
          if !(line == "" || line.startsWith("#"))
wenzelm@62631
   443
          dir1 =
wenzelm@62631
   444
            try { check_session_dir(dir + Path.explode(line)) }
wenzelm@62631
   445
            catch {
wenzelm@62631
   446
              case ERROR(msg) =>
wenzelm@62631
   447
                error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
wenzelm@62631
   448
            }
wenzelm@62635
   449
          info <- load_dir(select, dir1)
wenzelm@62631
   450
        } yield info
wenzelm@62631
   451
      }
wenzelm@62631
   452
      else Nil
wenzelm@62631
   453
    }
wenzelm@62631
   454
wenzelm@62631
   455
    val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
wenzelm@62631
   456
    dirs.foreach(check_session_dir(_))
wenzelm@62631
   457
    select_dirs.foreach(check_session_dir(_))
wenzelm@62631
   458
wenzelm@62631
   459
    Tree(
wenzelm@62631
   460
      for {
wenzelm@62631
   461
        (select, dir) <- (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _))
wenzelm@62635
   462
        info <- load_dir(select, dir)
wenzelm@62631
   463
      } yield info)
wenzelm@62631
   464
  }
wenzelm@62632
   465
wenzelm@62632
   466
wenzelm@62637
   467
wenzelm@62704
   468
  /** heap file with SHA1 digest **/
wenzelm@62704
   469
wenzelm@62704
   470
  private val sha1_prefix = "SHA1:"
wenzelm@62704
   471
wenzelm@62704
   472
  def read_heap_digest(heap: Path): Option[String] =
wenzelm@62704
   473
  {
wenzelm@62704
   474
    if (heap.is_file) {
wenzelm@62704
   475
      val file = FileChannel.open(heap.file.toPath, StandardOpenOption.READ)
wenzelm@62704
   476
      try {
wenzelm@62704
   477
        val len = file.size
wenzelm@62704
   478
        val n = sha1_prefix.length + SHA1.digest_length
wenzelm@62704
   479
        if (len >= n) {
wenzelm@62704
   480
          file.position(len - n)
wenzelm@62704
   481
wenzelm@62704
   482
          val buf = ByteBuffer.allocate(n)
wenzelm@62704
   483
          var i = 0
wenzelm@62704
   484
          var m = 0
wenzelm@62704
   485
          do {
wenzelm@62704
   486
            m = file.read(buf)
wenzelm@62704
   487
            if (m != -1) i += m
wenzelm@62704
   488
          }
wenzelm@62704
   489
          while (m != -1 && n > i)
wenzelm@62704
   490
wenzelm@62704
   491
          if (i == n) {
wenzelm@62704
   492
            val prefix = new String(buf.array(), 0, sha1_prefix.length, UTF8.charset)
wenzelm@62704
   493
            val s = new String(buf.array(), sha1_prefix.length, SHA1.digest_length, UTF8.charset)
wenzelm@62704
   494
            if (prefix == sha1_prefix) Some(s) else None
wenzelm@62704
   495
          }
wenzelm@62704
   496
          else None
wenzelm@62704
   497
        }
wenzelm@62704
   498
        else None
wenzelm@62704
   499
      }
wenzelm@62704
   500
      finally { file.close }
wenzelm@62704
   501
    }
wenzelm@62704
   502
    else None
wenzelm@62704
   503
  }
wenzelm@62704
   504
wenzelm@62704
   505
  def write_heap_digest(heap: Path): String =
wenzelm@62704
   506
    read_heap_digest(heap) match {
wenzelm@62704
   507
      case None =>
wenzelm@62704
   508
        val s = SHA1.digest(heap).rep
wenzelm@62704
   509
        File.append(heap, sha1_prefix + s)
wenzelm@62704
   510
        s
wenzelm@62704
   511
      case Some(s) => s
wenzelm@62704
   512
    }
wenzelm@62704
   513
wenzelm@62704
   514
wenzelm@62704
   515
wenzelm@62637
   516
  /** persistent store **/
wenzelm@62632
   517
wenzelm@62632
   518
  def store(system_mode: Boolean = false): Store = new Store(system_mode)
wenzelm@62632
   519
wenzelm@63996
   520
  class Store private[Sessions](system_mode: Boolean)
wenzelm@62632
   521
  {
wenzelm@65278
   522
    /* file names */
wenzelm@65278
   523
wenzelm@65281
   524
    def database(name: String): Path = Path.basic("log") + Path.basic(name).ext("db")
wenzelm@65278
   525
    def log(name: String): Path = Path.basic("log") + Path.basic(name)
wenzelm@65278
   526
    def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@65278
   527
wenzelm@65278
   528
wenzelm@65283
   529
    /* data representation */
wenzelm@65283
   530
wenzelm@65283
   531
    val xml_cache: XML.Cache = new XML.Cache()
wenzelm@65283
   532
wenzelm@65283
   533
    def encode_properties(ps: Properties.T): Bytes =
wenzelm@65283
   534
      Bytes(YXML.string_of_body(XML.Encode.properties(ps)))
wenzelm@65283
   535
wenzelm@65283
   536
    def decode_properties(bs: Bytes): Properties.T =
wenzelm@65283
   537
      xml_cache.props(XML.Decode.properties(YXML.parse_body(bs.text)))
wenzelm@65283
   538
wenzelm@65283
   539
    def compress_properties(ps: List[Properties.T], options: XZ.Options = XZ.options()): Bytes =
wenzelm@65283
   540
    {
wenzelm@65283
   541
      if (ps.isEmpty) Bytes.empty
wenzelm@65283
   542
      else Bytes(YXML.string_of_body(XML.Encode.list(XML.Encode.properties)(ps))).compress(options)
wenzelm@65283
   543
    }
wenzelm@65283
   544
wenzelm@65283
   545
    def uncompress_properties(bs: Bytes): List[Properties.T] =
wenzelm@65283
   546
    {
wenzelm@65283
   547
      if (bs.isEmpty) Nil
wenzelm@65283
   548
      else
wenzelm@65283
   549
        XML.Decode.list(XML.Decode.properties)(YXML.parse_body(bs.uncompress().text)).
wenzelm@65283
   550
          map(xml_cache.props(_))
wenzelm@65283
   551
    }
wenzelm@65283
   552
wenzelm@65283
   553
wenzelm@62637
   554
    /* output */
wenzelm@62632
   555
wenzelm@62632
   556
    val browser_info: Path =
wenzelm@62632
   557
      if (system_mode) Path.explode("~~/browser_info")
wenzelm@62632
   558
      else Path.explode("$ISABELLE_BROWSER_INFO")
wenzelm@62632
   559
wenzelm@62637
   560
    val output_dir: Path =
wenzelm@62637
   561
      if (system_mode) Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@62637
   562
      else Path.explode("$ISABELLE_OUTPUT")
wenzelm@62637
   563
wenzelm@62637
   564
    def prepare_output() { Isabelle_System.mkdirs(output_dir + Path.basic("log")) }
wenzelm@62637
   565
wenzelm@62637
   566
wenzelm@62637
   567
    /* input */
wenzelm@62637
   568
wenzelm@62637
   569
    private val input_dirs =
wenzelm@62632
   570
      if (system_mode) List(output_dir)
wenzelm@62633
   571
      else {
wenzelm@62633
   572
        val ml_ident = Path.explode("$ML_IDENTIFIER").expand
wenzelm@62633
   573
        output_dir :: Path.split(Isabelle_System.getenv_strict("ISABELLE_PATH")).map(_ + ml_ident)
wenzelm@62633
   574
      }
wenzelm@62632
   575
wenzelm@62636
   576
    def find(name: String): Option[(Path, Option[String])] =
wenzelm@62632
   577
      input_dirs.find(dir => (dir + log_gz(name)).is_file).map(dir =>
wenzelm@62704
   578
        (dir + log_gz(name), read_heap_digest(dir + Path.basic(name))))
wenzelm@62632
   579
wenzelm@65281
   580
    def find_database(name: String): Option[Path] =
wenzelm@65281
   581
      input_dirs.map(_ + database(name)).find(_.is_file)
wenzelm@65281
   582
wenzelm@62633
   583
    def find_log(name: String): Option[Path] =
wenzelm@62633
   584
      input_dirs.map(_ + log(name)).find(_.is_file)
wenzelm@62633
   585
wenzelm@62633
   586
    def find_log_gz(name: String): Option[Path] =
wenzelm@62633
   587
      input_dirs.map(_ + log_gz(name)).find(_.is_file)
wenzelm@62632
   588
wenzelm@62637
   589
    def find_heap(name: String): Option[Path] =
wenzelm@62637
   590
      input_dirs.map(_ + Path.basic(name)).find(_.is_file)
wenzelm@62637
   591
wenzelm@62637
   592
    def heap(name: String): Path =
wenzelm@62637
   593
      find_heap(name) getOrElse
wenzelm@62637
   594
        error("Unknown logic " + quote(name) + " -- no heap file found in:\n" +
wenzelm@62769
   595
          cat_lines(input_dirs.map(dir => "  " + dir.expand.implode)))
wenzelm@62632
   596
  }
wenzelm@65281
   597
wenzelm@65281
   598
wenzelm@65283
   599
  /* session info */
wenzelm@65281
   600
wenzelm@65281
   601
  object Session_Info
wenzelm@65281
   602
  {
wenzelm@65281
   603
    // Build_Log.Session_Info
wenzelm@65281
   604
    val session_name = SQL.Column.string("session_name")
wenzelm@65281
   605
    val session_timing = SQL.Column.bytes("session_timing")
wenzelm@65281
   606
    val command_timings = SQL.Column.bytes("command_timings")
wenzelm@65281
   607
    val ml_statistics = SQL.Column.bytes("ml_statistics")
wenzelm@65281
   608
    val task_statistics = SQL.Column.bytes("task_statistics")
wenzelm@65281
   609
wenzelm@65281
   610
    // Build.Session_Info
wenzelm@65281
   611
    val sources = SQL.Column.string("sources")
wenzelm@65282
   612
    val input_heaps = SQL.Column.string("input_heaps")
wenzelm@65281
   613
    val output_heap = SQL.Column.string("output_heap")
wenzelm@65281
   614
    val return_code = SQL.Column.int("return_code")
wenzelm@65281
   615
wenzelm@65281
   616
    val table = SQL.Table("isabelle_session_info",
wenzelm@65281
   617
      List(session_name, session_timing, command_timings, ml_statistics, task_statistics,
wenzelm@65282
   618
        sources, input_heaps, output_heap, return_code))
wenzelm@65281
   619
wenzelm@65283
   620
    def write_data(store: Store, db: SQLite.Database,
wenzelm@65283
   621
      build_log: Build_Log.Session_Info, build: Build.Session_Info)
wenzelm@65281
   622
    {
wenzelm@65281
   623
      db.transaction {
wenzelm@65281
   624
        db.drop_table(table)
wenzelm@65281
   625
        db.create_table(table)
wenzelm@65281
   626
        using(db.insert_statement(table))(stmt =>
wenzelm@65281
   627
        {
wenzelm@65283
   628
          db.set_string(stmt, 1, build_log.session_name)
wenzelm@65283
   629
          db.set_bytes(stmt, 2, store.encode_properties(build_log.session_timing))
wenzelm@65283
   630
          db.set_bytes(stmt, 3, store.compress_properties(build_log.command_timings))
wenzelm@65283
   631
          db.set_bytes(stmt, 4, store.compress_properties(build_log.ml_statistics))
wenzelm@65283
   632
          db.set_bytes(stmt, 5, store.compress_properties(build_log.task_statistics))
wenzelm@65283
   633
          db.set_string(stmt, 6, build.sources)
wenzelm@65283
   634
          db.set_string(stmt, 7, build.input_heaps)
wenzelm@65283
   635
          db.set_string(stmt, 8, build.output_heap)
wenzelm@65283
   636
          db.set_int(stmt, 9, build.return_code)
wenzelm@65281
   637
          stmt.execute()
wenzelm@65281
   638
        })
wenzelm@65281
   639
      }
wenzelm@65281
   640
    }
wenzelm@65281
   641
wenzelm@65283
   642
    def read_data(store: Store, db: SQLite.Database)
wenzelm@65283
   643
      : Option[(Build_Log.Session_Info, Build.Session_Info)] =
wenzelm@65281
   644
    {
wenzelm@65281
   645
      using(db.select_statement(table, table.columns))(stmt =>
wenzelm@65281
   646
      {
wenzelm@65281
   647
        val rs = stmt.executeQuery
wenzelm@65281
   648
        if (!rs.next) None
wenzelm@65281
   649
        else {
wenzelm@65283
   650
          val build_log =
wenzelm@65281
   651
            Build_Log.Session_Info(
wenzelm@65281
   652
              db.string(rs, session_name.name),
wenzelm@65283
   653
              store.decode_properties(db.bytes(rs, session_timing.name)),
wenzelm@65283
   654
              store.uncompress_properties(db.bytes(rs, command_timings.name)),
wenzelm@65283
   655
              store.uncompress_properties(db.bytes(rs, ml_statistics.name)),
wenzelm@65283
   656
              store.uncompress_properties(db.bytes(rs, task_statistics.name)))
wenzelm@65283
   657
          val build =
wenzelm@65281
   658
            Build.Session_Info(
wenzelm@65281
   659
              db.string(rs, sources.name),
wenzelm@65282
   660
              db.string(rs, input_heaps.name),
wenzelm@65281
   661
              db.string(rs, output_heap.name),
wenzelm@65281
   662
              db.int(rs, return_code.name))
wenzelm@65283
   663
          Some((build_log, build))
wenzelm@65281
   664
        }
wenzelm@65281
   665
      })
wenzelm@65281
   666
    }
wenzelm@65281
   667
  }
wenzelm@62631
   668
}