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