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