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