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