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