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