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