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