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