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