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