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