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