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