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