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