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