src/Pure/Thy/sessions.scala
author wenzelm
Tue Oct 31 19:29:24 2017 +0100 (20 months ago)
changeset 66966 f3f9a492bee6
parent 66965 9cec50354099
child 66967 e365c91c72a9
permissions -rw-r--r--
clarified 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 theory_qualifier(name: Document.Node.Name): String =
   127       global_theories.getOrElse(name.theory, Long_Name.qualifier(name.theory))
   128 
   129     def loaded_theory(name: String): Boolean = loaded_theories.defined(name)
   130     def loaded_theory(name: Document.Node.Name): Boolean = loaded_theory(name.theory)
   131 
   132     def loaded_theory_syntax(name: String): Option[Outer_Syntax] =
   133       if (loaded_theory(name)) Some(loaded_theories.get_node(name)) else None
   134     def loaded_theory_syntax(name: Document.Node.Name): Option[Outer_Syntax] =
   135       loaded_theory_syntax(name.theory)
   136 
   137     def node_syntax(nodes: Document.Nodes, name: Document.Node.Name): Outer_Syntax =
   138       nodes(name).syntax orElse loaded_theory_syntax(name) getOrElse overall_syntax
   139 
   140     def known_theory(name: String): Option[Document.Node.Name] =
   141       known.theories.get(name)
   142 
   143     def dest_known_theories: List[(String, String)] =
   144       for ((theory, node_name) <- known.theories.toList)
   145         yield (theory, node_name.node)
   146 
   147     def get_imports: Base = imports getOrElse Base.bootstrap(global_theories)
   148   }
   149 
   150   sealed case class Deps(session_bases: Map[String, Base], all_known: Known)
   151   {
   152     def is_empty: Boolean = session_bases.isEmpty
   153     def apply(name: String): Base = session_bases(name)
   154 
   155     def imported_sources(name: String): List[SHA1.Digest] =
   156       session_bases(name).imported_sources.map(_._2)
   157 
   158     def sources(name: String): List[SHA1.Digest] =
   159       session_bases(name).sources.map(_._2)
   160 
   161     def errors: List[String] =
   162       (for {
   163         (name, base) <- session_bases.iterator
   164         if base.errors.nonEmpty
   165       } yield cat_lines(base.errors) +
   166           "\nThe error(s) above occurred in session " + quote(name) + Position.here(base.pos)
   167       ).toList
   168 
   169     def check_errors: Deps =
   170       errors match {
   171         case Nil => this
   172         case errs => error(cat_lines(errs))
   173       }
   174   }
   175 
   176   def deps(sessions: T,
   177       global_theories: Map[String, String],
   178       progress: Progress = No_Progress,
   179       inlined_files: Boolean = false,
   180       verbose: Boolean = false,
   181       list_files: Boolean = false,
   182       check_keywords: Set[String] = Set.empty): Deps =
   183   {
   184     var cache_sources = Map.empty[JFile, SHA1.Digest]
   185     def check_sources(paths: List[Path]): List[(Path, SHA1.Digest)] =
   186     {
   187       for {
   188         path <- paths
   189         file = path.file
   190         if cache_sources.isDefinedAt(file) || file.isFile
   191       }
   192       yield {
   193         cache_sources.get(file) match {
   194           case Some(digest) => (path, digest)
   195           case None =>
   196             val digest = SHA1.digest(file)
   197             cache_sources = cache_sources + (file -> digest)
   198             (path, digest)
   199         }
   200       }
   201     }
   202 
   203     val session_bases =
   204       (Map.empty[String, Base] /: sessions.imports_topological_order)({
   205         case (session_bases, info) =>
   206           if (progress.stopped) throw Exn.Interrupt()
   207 
   208           try {
   209             val parent_base: Sessions.Base =
   210               info.parent match {
   211                 case None => Base.bootstrap(global_theories)
   212                 case Some(parent) => session_bases(parent)
   213               }
   214             val imports_base: Sessions.Base =
   215               parent_base.copy(known =
   216                 Known.make(info.dir, parent_base :: info.imports.map(session_bases(_))))
   217 
   218             val resources = new Resources(imports_base)
   219 
   220             if (verbose || list_files) {
   221               val groups =
   222                 if (info.groups.isEmpty) ""
   223                 else info.groups.mkString(" (", " ", ")")
   224               progress.echo("Session " + info.chapter + "/" + info.name + groups)
   225             }
   226 
   227             val thy_deps =
   228               resources.dependencies(
   229                 for { (_, thys) <- info.theories; (thy, pos) <- thys }
   230                 yield (resources.import_name(info.name, info.dir.implode, thy), pos))
   231 
   232             val overall_syntax = thy_deps.overall_syntax
   233 
   234             val theory_files = thy_deps.names.map(_.path)
   235             val loaded_files =
   236               if (inlined_files) {
   237                 if (Sessions.is_pure(info.name)) {
   238                   (Thy_Header.PURE -> resources.pure_files(overall_syntax, info.dir)) ::
   239                     thy_deps.loaded_files.filterNot(p => p._1 == Thy_Header.PURE)
   240                 }
   241                 else thy_deps.loaded_files
   242               }
   243               else Nil
   244 
   245             val session_files =
   246               (theory_files ::: loaded_files.flatMap(_._2) :::
   247                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   248 
   249             val imported_files = if (inlined_files) thy_deps.imported_files else Nil
   250 
   251             if (list_files)
   252               progress.echo(cat_lines(session_files.map(_.implode).sorted.map("  " + _)))
   253 
   254             if (check_keywords.nonEmpty) {
   255               Check_Keywords.check_keywords(
   256                 progress, overall_syntax.keywords, check_keywords, theory_files)
   257             }
   258 
   259             val session_graph_display: Graph_Display.Graph =
   260             {
   261               def session_node(name: String): Graph_Display.Node =
   262                 Graph_Display.Node("[" + name + "]", "session." + name)
   263 
   264               def node(name: Document.Node.Name): Graph_Display.Node =
   265               {
   266                 val qualifier = imports_base.theory_qualifier(name)
   267                 if (qualifier == info.name)
   268                   Graph_Display.Node(name.theory_base_name, "theory." + name.theory)
   269                 else session_node(qualifier)
   270               }
   271 
   272               val imports_subgraph =
   273                 sessions.imports_graph.restrict(sessions.imports_graph.all_preds(info.deps).toSet)
   274 
   275               val graph0 =
   276                 (Graph_Display.empty_graph /: imports_subgraph.topological_order)(
   277                   { case (g, session) =>
   278                       val a = session_node(session)
   279                       val bs = imports_subgraph.imm_preds(session).toList.map(session_node(_))
   280                       ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
   281 
   282               (graph0 /: thy_deps.entries)(
   283                 { case (g, entry) =>
   284                     val a = node(entry.name)
   285                     val bs =
   286                       entry.header.imports.map({ case (name, _) => node(name) }).
   287                         filterNot(_ == a)
   288                     ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
   289             }
   290 
   291             val known =
   292               Known.make(info.dir, List(imports_base),
   293                 theories = thy_deps.names,
   294                 loaded_files = loaded_files)
   295 
   296             val sources_errors =
   297               for (p <- session_files if !p.is_file) yield "No such file: " + p
   298 
   299             val base =
   300               Base(
   301                 pos = info.pos,
   302                 global_theories = global_theories,
   303                 loaded_theories = thy_deps.loaded_theories,
   304                 known = known,
   305                 overall_syntax = overall_syntax,
   306                 imported_sources = check_sources(imported_files),
   307                 sources = check_sources(session_files),
   308                 session_graph_display = session_graph_display,
   309                 errors = thy_deps.errors ::: sources_errors,
   310                 imports = Some(imports_base))
   311 
   312             session_bases + (info.name -> base)
   313           }
   314           catch {
   315             case ERROR(msg) =>
   316               cat_error(msg, "The error(s) above occurred in session " +
   317                 quote(info.name) + Position.here(info.pos))
   318           }
   319       })
   320 
   321     Deps(session_bases, Known.make(Path.current, session_bases.toList.map(_._2)))
   322   }
   323 
   324 
   325   /* base info */
   326 
   327   def session_base_info(
   328     options: Options,
   329     session: String,
   330     dirs: List[Path] = Nil,
   331     inlined_files: Boolean = false,
   332     all_known: Boolean = false): Base_Info =
   333   {
   334     val full_sessions = load(options, dirs = dirs)
   335     val global_theories = full_sessions.global_theories
   336     val (_, selected_sessions) = full_sessions.selection(Selection(sessions = List(session)))
   337 
   338     val sessions: T = if (all_known) full_sessions else selected_sessions
   339     val deps = Sessions.deps(sessions, global_theories, inlined_files = inlined_files)
   340     val base = if (all_known) deps(session).copy(known = deps.all_known) else deps(session)
   341 
   342     new Base_Info(session, sessions, deps, base)
   343   }
   344 
   345   final class Base_Info private [Sessions](
   346     val session: String, val sessions: T, val deps: Deps, val base: Base)
   347   {
   348     override def toString: String = session
   349 
   350     def errors: List[String] = deps.errors
   351     def check_base: Base = if (errors.isEmpty) base else error(cat_lines(errors))
   352   }
   353 
   354 
   355   /* cumulative session info */
   356 
   357   sealed case class Info(
   358     name: String,
   359     chapter: String,
   360     dir_selected: Boolean,
   361     pos: Position.T,
   362     groups: List[String],
   363     dir: Path,
   364     parent: Option[String],
   365     description: String,
   366     options: Options,
   367     imports: List[String],
   368     theories: List[(Options, List[(String, Position.T)])],
   369     global_theories: List[String],
   370     document_files: List[(Path, Path)],
   371     meta_digest: SHA1.Digest)
   372   {
   373     def deps: List[String] = parent.toList ::: imports
   374 
   375     def timeout: Time = Time.seconds(options.real("timeout") * options.real("timeout_scale"))
   376   }
   377 
   378   object Selection
   379   {
   380     val empty: Selection = Selection()
   381     val all: Selection = Selection(all_sessions = true)
   382   }
   383 
   384   sealed case class Selection(
   385     requirements: Boolean = false,
   386     all_sessions: Boolean = false,
   387     base_sessions: List[String] = Nil,
   388     exclude_session_groups: List[String] = Nil,
   389     exclude_sessions: List[String] = Nil,
   390     session_groups: List[String] = Nil,
   391     sessions: List[String] = Nil)
   392   {
   393     def ++ (other: Selection): Selection =
   394       Selection(
   395         requirements = requirements || other.requirements,
   396         all_sessions = all_sessions || other.all_sessions,
   397         base_sessions = Library.merge(base_sessions, other.base_sessions),
   398         exclude_session_groups = Library.merge(exclude_session_groups, other.exclude_session_groups),
   399         exclude_sessions = Library.merge(exclude_sessions, other.exclude_sessions),
   400         session_groups = Library.merge(session_groups, other.session_groups),
   401         sessions = Library.merge(sessions, other.sessions))
   402 
   403     def apply(graph: Graph[String, Info]): (List[String], Graph[String, Info]) =
   404     {
   405       val bad_sessions =
   406         SortedSet((base_sessions ::: exclude_sessions ::: sessions).
   407           filterNot(graph.defined(_)): _*).toList
   408       if (bad_sessions.nonEmpty)
   409         error("Undefined session(s): " + commas_quote(bad_sessions))
   410 
   411       val excluded =
   412       {
   413         val exclude_group = exclude_session_groups.toSet
   414         val exclude_group_sessions =
   415           (for {
   416             (name, (info, _)) <- graph.iterator
   417             if graph.get_node(name).groups.exists(exclude_group)
   418           } yield name).toList
   419         graph.all_succs(exclude_group_sessions ::: exclude_sessions).toSet
   420       }
   421 
   422       val pre_selected =
   423       {
   424         if (all_sessions) graph.keys
   425         else {
   426           val select_group = session_groups.toSet
   427           val select = sessions.toSet ++ graph.all_succs(base_sessions)
   428           (for {
   429             (name, (info, _)) <- graph.iterator
   430             if info.dir_selected || select(name) || graph.get_node(name).groups.exists(select_group)
   431           } yield name).toList
   432         }
   433       }.filterNot(excluded)
   434 
   435       val selected =
   436         if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
   437         else pre_selected
   438 
   439       (selected, graph.restrict(graph.all_preds(selected).toSet))
   440     }
   441   }
   442 
   443   def make(infos: List[Info]): T =
   444   {
   445     def add_edges(graph: Graph[String, Info], kind: String, edges: Info => Traversable[String])
   446       : Graph[String, Info] =
   447     {
   448       def add_edge(pos: Position.T, name: String, g: Graph[String, Info], parent: String) =
   449       {
   450         if (!g.defined(parent))
   451           error("Bad " + kind + " session " + quote(parent) + " for " +
   452             quote(name) + Position.here(pos))
   453 
   454         try { g.add_edge_acyclic(parent, name) }
   455         catch {
   456           case exn: Graph.Cycles[_] =>
   457             error(cat_lines(exn.cycles.map(cycle =>
   458               "Cyclic session dependency of " +
   459                 cycle.map(c => quote(c.toString)).mkString(" via "))) + Position.here(pos))
   460         }
   461       }
   462       (graph /: graph.iterator) {
   463         case (g, (name, (info, _))) => (g /: edges(info))(add_edge(info.pos, name, _, _))
   464       }
   465     }
   466 
   467     val graph0 =
   468       (Graph.string[Info] /: infos) {
   469         case (graph, info) =>
   470           if (graph.defined(info.name))
   471             error("Duplicate session " + quote(info.name) + Position.here(info.pos) +
   472               Position.here(graph.get_node(info.name).pos))
   473           else graph.new_node(info.name, info)
   474       }
   475     val graph1 = add_edges(graph0, "parent", _.parent)
   476     val graph2 = add_edges(graph1, "imports", _.imports)
   477 
   478     new T(graph1, graph2)
   479   }
   480 
   481   final class T private[Sessions](
   482       val build_graph: Graph[String, Info],
   483       val imports_graph: Graph[String, Info])
   484   {
   485     def build_graph_display: Graph_Display.Graph = Graph_Display.make_graph(build_graph)
   486     def imports_graph_display: Graph_Display.Graph = Graph_Display.make_graph(imports_graph)
   487 
   488     def apply(name: String): Info = imports_graph.get_node(name)
   489     def get(name: String): Option[Info] =
   490       if (imports_graph.defined(name)) Some(imports_graph.get_node(name)) else None
   491 
   492     def global_theories: Map[String, String] =
   493       (Thy_Header.bootstrap_global_theories.toMap /:
   494         (for {
   495           (_, (info, _)) <- imports_graph.iterator
   496           thy <- info.global_theories.iterator }
   497          yield (thy, info)))({
   498             case (global, (thy, info)) =>
   499               val qualifier = info.name
   500               global.get(thy) match {
   501                 case Some(qualifier1) if qualifier != qualifier1 =>
   502                   error("Duplicate global theory " + quote(thy) + Position.here(info.pos))
   503                 case _ => global + (thy -> qualifier)
   504               }
   505           })
   506 
   507     def selection(select: Selection): (List[String], T) =
   508     {
   509       val (_, build_graph1) = select(build_graph)
   510       val (selected, imports_graph1) = select(imports_graph)
   511       (selected, new T(build_graph1, imports_graph1))
   512     }
   513 
   514     def build_descendants(names: List[String]): List[String] =
   515       build_graph.all_succs(names)
   516     def build_requirements(names: List[String]): List[String] =
   517       build_graph.all_preds(names).reverse
   518     def build_topological_order: List[Info] =
   519       build_graph.topological_order.map(apply(_))
   520 
   521     def imports_descendants(names: List[String]): List[String] =
   522       imports_graph.all_succs(names)
   523     def imports_requirements(names: List[String]): List[String] =
   524       imports_graph.all_preds(names).reverse
   525     def imports_topological_order: List[Info] =
   526       imports_graph.topological_order.map(apply(_))
   527 
   528     override def toString: String =
   529       imports_graph.keys_iterator.mkString("Sessions.T(", ", ", ")")
   530   }
   531 
   532 
   533   /* parser */
   534 
   535   val ROOT = Path.explode("ROOT")
   536   val ROOTS = Path.explode("ROOTS")
   537 
   538   private val CHAPTER = "chapter"
   539   private val SESSION = "session"
   540   private val IN = "in"
   541   private val DESCRIPTION = "description"
   542   private val OPTIONS = "options"
   543   private val SESSIONS = "sessions"
   544   private val THEORIES = "theories"
   545   private val GLOBAL = "global"
   546   private val DOCUMENT_FILES = "document_files"
   547 
   548   lazy val root_syntax =
   549     Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" + GLOBAL + IN +
   550       (CHAPTER, Keyword.THY_DECL) +
   551       (SESSION, Keyword.THY_DECL) +
   552       (DESCRIPTION, Keyword.QUASI_COMMAND) +
   553       (OPTIONS, Keyword.QUASI_COMMAND) +
   554       (SESSIONS, Keyword.QUASI_COMMAND) +
   555       (THEORIES, Keyword.QUASI_COMMAND) +
   556       (DOCUMENT_FILES, Keyword.QUASI_COMMAND)
   557 
   558   abstract class Entry
   559   sealed case class Chapter(name: String) extends Entry
   560   sealed case class Session_Entry(
   561     pos: Position.T,
   562     name: String,
   563     groups: List[String],
   564     path: String,
   565     parent: Option[String],
   566     description: String,
   567     options: List[Options.Spec],
   568     imports: List[String],
   569     theories: List[(List[Options.Spec], List[((String, Position.T), Boolean)])],
   570     document_files: List[(String, String)]) extends Entry
   571   {
   572     def theories_no_position: List[(List[Options.Spec], List[(String, Boolean)])] =
   573       theories.map({ case (a, b) => (a, b.map({ case ((c, _), d) => (c, d) })) })
   574   }
   575 
   576   private object Parser extends Parse.Parser with Options.Parser
   577   {
   578     private val chapter: Parser[Chapter] =
   579     {
   580       val chapter_name = atom("chapter name", _.is_name)
   581 
   582       command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
   583     }
   584 
   585     private val session_entry: Parser[Session_Entry] =
   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[Info] =
   643   {
   644     def make_info(entry_chapter: String, entry: Session_Entry): 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         Info(name, entry_chapter, select, entry.pos, entry.groups,
   680           path.dir + Path.explode(entry.path), entry.parent, entry.description, session_options,
   681           entry.imports, theories, global_theories, document_files, meta_digest)
   682       }
   683       catch {
   684         case ERROR(msg) =>
   685           error(msg + "\nThe error(s) above occurred in session entry " +
   686             quote(entry.name) + Position.here(entry.pos))
   687       }
   688     }
   689 
   690     var entry_chapter = "Unsorted"
   691     val infos = new mutable.ListBuffer[Info]
   692     parse_root(path).foreach {
   693       case Chapter(name) => entry_chapter = name
   694       case entry: Session_Entry => infos += make_info(entry_chapter, entry)
   695     }
   696     infos.toList
   697   }
   698 
   699   def parse_roots(roots: Path): List[String] =
   700   {
   701     for {
   702       line <- split_lines(File.read(roots))
   703       if !(line == "" || line.startsWith("#"))
   704     } yield line
   705   }
   706 
   707 
   708   /* load sessions from certain directories */
   709 
   710   private def is_session_dir(dir: Path): Boolean =
   711     (dir + ROOT).is_file || (dir + ROOTS).is_file
   712 
   713   private def check_session_dir(dir: Path): Path =
   714     if (is_session_dir(dir)) File.pwd() + dir.expand
   715     else error("Bad session root directory: " + dir.toString)
   716 
   717   def directories(dirs: List[Path], select_dirs: List[Path]): List[(Boolean, Path)] =
   718   {
   719     val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
   720     (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _))
   721   }
   722 
   723   def load(options: Options, dirs: List[Path] = Nil, select_dirs: List[Path] = Nil): T =
   724   {
   725     def load_dir(select: Boolean, dir: Path): List[(Boolean, Path)] =
   726       load_root(select, dir) ::: load_roots(select, dir)
   727 
   728     def load_root(select: Boolean, dir: Path): List[(Boolean, Path)] =
   729     {
   730       val root = dir + ROOT
   731       if (root.is_file) List((select, root)) else Nil
   732     }
   733 
   734     def load_roots(select: Boolean, dir: Path): List[(Boolean, Path)] =
   735     {
   736       val roots = dir + ROOTS
   737       if (roots.is_file) {
   738         for {
   739           entry <- parse_roots(roots)
   740           dir1 =
   741             try { check_session_dir(dir + Path.explode(entry)) }
   742             catch {
   743               case ERROR(msg) =>
   744                 error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
   745             }
   746           res <- load_dir(select, dir1)
   747         } yield res
   748       }
   749       else Nil
   750     }
   751 
   752     val roots =
   753       for {
   754         (select, dir) <- directories(dirs, select_dirs)
   755         res <- load_dir(select, check_session_dir(dir))
   756       } yield res
   757 
   758     val unique_roots =
   759       ((Map.empty[JFile, (Boolean, Path)] /: roots) { case (m, (select, path)) =>
   760         val file = path.canonical_file
   761         m.get(file) match {
   762           case None => m + (file -> (select, path))
   763           case Some((select1, path1)) => m + (file -> (select1 || select, path1))
   764         }
   765       }).toList.map(_._2)
   766 
   767     make(unique_roots.flatMap(p => read_root(options, p._1, p._2)))
   768   }
   769 
   770 
   771 
   772   /** heap file with SHA1 digest **/
   773 
   774   private val sha1_prefix = "SHA1:"
   775 
   776   def read_heap_digest(heap: Path): Option[String] =
   777   {
   778     if (heap.is_file) {
   779       val file = FileChannel.open(heap.file.toPath, StandardOpenOption.READ)
   780       try {
   781         val len = file.size
   782         val n = sha1_prefix.length + SHA1.digest_length
   783         if (len >= n) {
   784           file.position(len - n)
   785 
   786           val buf = ByteBuffer.allocate(n)
   787           var i = 0
   788           var m = 0
   789           do {
   790             m = file.read(buf)
   791             if (m != -1) i += m
   792           }
   793           while (m != -1 && n > i)
   794 
   795           if (i == n) {
   796             val prefix = new String(buf.array(), 0, sha1_prefix.length, UTF8.charset)
   797             val s = new String(buf.array(), sha1_prefix.length, SHA1.digest_length, UTF8.charset)
   798             if (prefix == sha1_prefix) Some(s) else None
   799           }
   800           else None
   801         }
   802         else None
   803       }
   804       finally { file.close }
   805     }
   806     else None
   807   }
   808 
   809   def write_heap_digest(heap: Path): String =
   810     read_heap_digest(heap) match {
   811       case None =>
   812         val s = SHA1.digest(heap).rep
   813         File.append(heap, sha1_prefix + s)
   814         s
   815       case Some(s) => s
   816     }
   817 
   818 
   819 
   820   /** persistent store **/
   821 
   822   object Session_Info
   823   {
   824     val session_name = SQL.Column.string("session_name").make_primary_key
   825 
   826     // Build_Log.Session_Info
   827     val session_timing = SQL.Column.bytes("session_timing")
   828     val command_timings = SQL.Column.bytes("command_timings")
   829     val theory_timings = SQL.Column.bytes("theory_timings")
   830     val ml_statistics = SQL.Column.bytes("ml_statistics")
   831     val task_statistics = SQL.Column.bytes("task_statistics")
   832     val errors = SQL.Column.bytes("errors")
   833     val build_log_columns =
   834       List(session_name, session_timing, command_timings, theory_timings,
   835         ml_statistics, task_statistics, errors)
   836 
   837     // Build.Session_Info
   838     val sources = SQL.Column.string("sources")
   839     val input_heaps = SQL.Column.string("input_heaps")
   840     val output_heap = SQL.Column.string("output_heap")
   841     val return_code = SQL.Column.int("return_code")
   842     val build_columns = List(sources, input_heaps, output_heap, return_code)
   843 
   844     val table = SQL.Table("isabelle_session_info", build_log_columns ::: build_columns)
   845   }
   846 
   847   def store(system_mode: Boolean = false): Store = new Store(system_mode)
   848 
   849   class Store private[Sessions](system_mode: Boolean)
   850   {
   851     /* file names */
   852 
   853     def database(name: String): Path = Path.basic("log") + Path.basic(name).ext("db")
   854     def log(name: String): Path = Path.basic("log") + Path.basic(name)
   855     def log_gz(name: String): Path = log(name).ext("gz")
   856 
   857 
   858     /* SQL database content */
   859 
   860     val xml_cache = new XML.Cache()
   861 
   862     def read_bytes(db: SQL.Database, name: String, column: SQL.Column): Bytes =
   863       db.using_statement(Session_Info.table.select(List(column),
   864         Session_Info.session_name.where_equal(name)))(stmt =>
   865       {
   866         val res = stmt.execute_query()
   867         if (!res.next()) Bytes.empty else res.bytes(column)
   868       })
   869 
   870     def read_properties(db: SQL.Database, name: String, column: SQL.Column): List[Properties.T] =
   871       Properties.uncompress(read_bytes(db, name, column), Some(xml_cache))
   872 
   873 
   874     /* output */
   875 
   876     val browser_info: Path =
   877       if (system_mode) Path.explode("~~/browser_info")
   878       else Path.explode("$ISABELLE_BROWSER_INFO")
   879 
   880     val output_dir: Path =
   881       if (system_mode) Path.explode("~~/heaps/$ML_IDENTIFIER")
   882       else Path.explode("$ISABELLE_OUTPUT")
   883 
   884     override def toString: String = "Store(output_dir = " + output_dir.expand + ")"
   885 
   886     def prepare_output() { Isabelle_System.mkdirs(output_dir + Path.basic("log")) }
   887 
   888 
   889     /* input */
   890 
   891     private val input_dirs =
   892       if (system_mode) List(output_dir)
   893       else {
   894         val ml_ident = Path.explode("$ML_IDENTIFIER").expand
   895         output_dir :: Path.split(Isabelle_System.getenv_strict("ISABELLE_PATH")).map(_ + ml_ident)
   896       }
   897 
   898     def find_database_heap(name: String): Option[(Path, Option[String])] =
   899       input_dirs.find(dir => (dir + database(name)).is_file).map(dir =>
   900         (dir + database(name), read_heap_digest(dir + Path.basic(name))))
   901 
   902     def find_database(name: String): Option[Path] =
   903       input_dirs.map(_ + database(name)).find(_.is_file)
   904 
   905     def heap(name: String): Path =
   906       input_dirs.map(_ + Path.basic(name)).find(_.is_file) getOrElse
   907         error("Unknown logic " + quote(name) + " -- no heap file found in:\n" +
   908           cat_lines(input_dirs.map(dir => "  " + dir.expand.implode)))
   909 
   910 
   911     /* session info */
   912 
   913     def write_session_info(
   914       db: SQL.Database,
   915       name: String,
   916       build_log: Build_Log.Session_Info,
   917       build: Build.Session_Info)
   918     {
   919       db.transaction {
   920         db.create_table(Session_Info.table)
   921         db.using_statement(
   922           Session_Info.table.delete(Session_Info.session_name.where_equal(name)))(_.execute)
   923         db.using_statement(Session_Info.table.insert())(stmt =>
   924         {
   925           stmt.string(1) = name
   926           stmt.bytes(2) = Properties.encode(build_log.session_timing)
   927           stmt.bytes(3) = Properties.compress(build_log.command_timings)
   928           stmt.bytes(4) = Properties.compress(build_log.theory_timings)
   929           stmt.bytes(5) = Properties.compress(build_log.ml_statistics)
   930           stmt.bytes(6) = Properties.compress(build_log.task_statistics)
   931           stmt.bytes(7) = Build_Log.compress_errors(build_log.errors)
   932           stmt.string(8) = build.sources
   933           stmt.string(9) = cat_lines(build.input_heaps)
   934           stmt.string(10) = build.output_heap getOrElse ""
   935           stmt.int(11) = 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_theory_timings(db: SQL.Database, name: String): List[Properties.T] =
   948       read_properties(db, name, Session_Info.theory_timings)
   949 
   950     def read_ml_statistics(db: SQL.Database, name: String): List[Properties.T] =
   951       read_properties(db, name, Session_Info.ml_statistics)
   952 
   953     def read_task_statistics(db: SQL.Database, name: String): List[Properties.T] =
   954       read_properties(db, name, Session_Info.task_statistics)
   955 
   956     def read_errors(db: SQL.Database, name: String): List[String] =
   957       Build_Log.uncompress_errors(read_bytes(db, name, Session_Info.errors))
   958 
   959     def read_build(db: SQL.Database, name: String): Option[Build.Session_Info] =
   960     {
   961       if (db.tables.contains(Session_Info.table.name)) {
   962         db.using_statement(Session_Info.table.select(Session_Info.build_columns,
   963           Session_Info.session_name.where_equal(name)))(stmt =>
   964         {
   965           val res = stmt.execute_query()
   966           if (!res.next()) None
   967           else {
   968             Some(
   969               Build.Session_Info(
   970                 res.string(Session_Info.sources),
   971                 split_lines(res.string(Session_Info.input_heaps)),
   972                 res.string(Session_Info.output_heap) match { case "" => None case s => Some(s) },
   973                 res.int(Session_Info.return_code)))
   974           }
   975         })
   976       }
   977       else None
   978     }
   979   }
   980 }