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