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