src/Pure/Thy/sessions.scala
author wenzelm
Sun Oct 01 17:59:26 2017 +0200 (21 months ago)
changeset 66743 ff05d922bc34
parent 66742 b3422f78270e
child 66744 fec1504e5f03
permissions -rw-r--r--
cache sources: invoke SHA1.digest at most once;
maintain imported_sources, as required for new theories;
     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     imported_sources: List[(Path, SHA1.Digest)] = Nil,
   119     session_graph: 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): Option[Outer_Syntax] =
   135       nodes(name).syntax orElse loaded_theory_syntax(name)
   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     def sources(name: String): List[SHA1.Digest] = session_bases(name).sources.map(_._2)
   152 
   153     def errors: List[String] =
   154       (for {
   155         (name, base) <- session_bases.iterator
   156         if base.errors.nonEmpty
   157       } yield cat_lines(base.errors) +
   158           "\nThe error(s) above occurred in session " + quote(name) + Position.here(base.pos)
   159       ).toList
   160 
   161     def check_errors: Deps =
   162       errors match {
   163         case Nil => this
   164         case errs => error(cat_lines(errs))
   165       }
   166   }
   167 
   168   def deps(sessions: T,
   169       progress: Progress = No_Progress,
   170       inlined_files: Boolean = false,
   171       verbose: Boolean = false,
   172       list_files: Boolean = false,
   173       check_keywords: Set[String] = Set.empty,
   174       global_theories: Map[String, String] = Map.empty): Deps =
   175   {
   176     var cache_sources = Map.empty[JFile, SHA1.Digest]
   177     def check_sources(paths: List[Path]): List[(Path, SHA1.Digest)] =
   178     {
   179       for {
   180         path <- paths
   181         file = path.file
   182         if cache_sources.isDefinedAt(file) || file.isFile
   183       }
   184       yield {
   185         cache_sources.get(file) match {
   186           case Some(digest) => (path, digest)
   187           case None =>
   188             val digest = SHA1.digest(file)
   189             cache_sources = cache_sources + (file -> digest)
   190             (path, digest)
   191         }
   192       }
   193     }
   194 
   195     val session_bases =
   196       (Map.empty[String, Base] /: sessions.imports_topological_order)({
   197         case (session_bases, info) =>
   198           if (progress.stopped) throw Exn.Interrupt()
   199 
   200           try {
   201             val parent_base: Sessions.Base =
   202               info.parent match {
   203                 case None => Base.bootstrap(global_theories)
   204                 case Some(parent) => session_bases(parent)
   205               }
   206             val imports_base: Sessions.Base =
   207               parent_base.copy(known =
   208                 Known.make(info.dir, parent_base :: info.imports.map(session_bases(_))))
   209 
   210             val resources = new Resources(imports_base)
   211 
   212             if (verbose || list_files) {
   213               val groups =
   214                 if (info.groups.isEmpty) ""
   215                 else info.groups.mkString(" (", " ", ")")
   216               progress.echo("Session " + info.chapter + "/" + info.name + groups)
   217             }
   218 
   219             val thy_deps =
   220               resources.thy_info.dependencies(
   221                 for { (_, thys) <- info.theories; (thy, pos) <- thys }
   222                 yield (resources.import_name(info.theory_qualifier, info.dir.implode, thy), pos))
   223 
   224             val overall_syntax = thy_deps.overall_syntax
   225 
   226             val theory_files = thy_deps.names.map(_.path)
   227             val loaded_files =
   228               if (inlined_files) {
   229                 if (Sessions.is_pure(info.name)) {
   230                   (Thy_Header.PURE -> resources.pure_files(overall_syntax, info.dir)) ::
   231                     thy_deps.loaded_files.filterNot(p => p._1 == Thy_Header.PURE)
   232                 }
   233                 else thy_deps.loaded_files
   234               }
   235               else Nil
   236 
   237             val session_files =
   238               (theory_files ::: loaded_files.flatMap(_._2) :::
   239                 info.files.map(file => info.dir + file) :::
   240                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   241 
   242             val imported_files = if (inlined_files) thy_deps.imported_files else Nil
   243 
   244             if (list_files)
   245               progress.echo(cat_lines(session_files.map(_.implode).sorted.map("  " + _)))
   246 
   247             if (check_keywords.nonEmpty) {
   248               Check_Keywords.check_keywords(
   249                 progress, overall_syntax.keywords, check_keywords, theory_files)
   250             }
   251 
   252             val session_graph: Graph_Display.Graph =
   253             {
   254               def session_node(name: String): Graph_Display.Node =
   255                 Graph_Display.Node("[" + name + "]", "session." + name)
   256 
   257               def node(name: Document.Node.Name): Graph_Display.Node =
   258               {
   259                 val qualifier = resources.theory_qualifier(name)
   260                 if (qualifier == info.theory_qualifier)
   261                   Graph_Display.Node(name.theory_base_name, "theory." + name.theory)
   262                 else session_node(qualifier)
   263               }
   264 
   265               val imports_subgraph =
   266                 sessions.imports_graph.restrict(
   267                   sessions.imports_graph.all_preds(info.parent.toList ::: info.imports).toSet)
   268 
   269               val graph0 =
   270                 (Graph_Display.empty_graph /: imports_subgraph.topological_order)(
   271                   { case (g, session) =>
   272                       val a = session_node(session)
   273                       val bs = imports_subgraph.imm_preds(session).toList.map(session_node(_))
   274                       ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
   275 
   276               (graph0 /: thy_deps.entries)(
   277                 { case (g, entry) =>
   278                     val a = node(entry.name)
   279                     val bs =
   280                       entry.header.imports.map({ case (name, _) => node(name) }).
   281                         filterNot(_ == a)
   282                     ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
   283             }
   284 
   285             val known =
   286               Known.make(info.dir, List(imports_base),
   287                 theories = thy_deps.names,
   288                 loaded_files = loaded_files)
   289 
   290             val sources_errors =
   291               for (p <- session_files if !p.is_file) yield "No such file: " + p
   292 
   293             val base =
   294               Base(
   295                 pos = info.pos,
   296                 global_theories = global_theories,
   297                 loaded_theories = thy_deps.loaded_theories,
   298                 known = known,
   299                 overall_syntax = overall_syntax,
   300                 sources = check_sources(session_files),
   301                 imported_sources = check_sources(imported_files),
   302                 session_graph = session_graph,
   303                 errors = thy_deps.errors ::: sources_errors,
   304                 imports = Some(imports_base))
   305 
   306             session_bases + (info.name -> base)
   307           }
   308           catch {
   309             case ERROR(msg) =>
   310               cat_error(msg, "The error(s) above occurred in session " +
   311                 quote(info.name) + Position.here(info.pos))
   312           }
   313       })
   314 
   315     Deps(session_bases, Known.make(Path.current, session_bases.toList.map(_._2)))
   316   }
   317 
   318   def session_base_errors(
   319     options: Options,
   320     session: String,
   321     dirs: List[Path] = Nil,
   322     inlined_files: Boolean = false,
   323     all_known: Boolean = false): (List[String], Base) =
   324   {
   325     val full_sessions = load(options, dirs = dirs)
   326     val global_theories = full_sessions.global_theories
   327     val (_, selected_sessions) = full_sessions.selection(Selection(sessions = List(session)))
   328 
   329     val sessions: T = if (all_known) full_sessions else selected_sessions
   330     val deps =
   331       Sessions.deps(sessions, inlined_files = inlined_files, global_theories = global_theories)
   332     val base = if (all_known) deps(session).copy(known = deps.all_known) else deps(session)
   333     (deps.errors, base)
   334   }
   335 
   336   def session_base(
   337     options: Options,
   338     session: String,
   339     dirs: List[Path] = Nil,
   340     inlined_files: Boolean = false,
   341     all_known: Boolean = false): Base =
   342   {
   343     val (errs, base) =
   344       session_base_errors(options, session, dirs = dirs,
   345         inlined_files = inlined_files, all_known = all_known)
   346     if (errs.isEmpty) base else error(cat_lines(errs))
   347   }
   348 
   349 
   350   /* cumulative session info */
   351 
   352   sealed case class Info(
   353     name: String,
   354     chapter: String,
   355     select: Boolean,
   356     pos: Position.T,
   357     groups: List[String],
   358     dir: Path,
   359     parent: Option[String],
   360     description: String,
   361     options: Options,
   362     imports: List[String],
   363     theories: List[(Options, List[(String, Position.T)])],
   364     global_theories: List[String],
   365     files: List[Path],
   366     document_files: List[(Path, Path)],
   367     meta_digest: SHA1.Digest)
   368   {
   369     def timeout: Time = Time.seconds(options.real("timeout") * options.real("timeout_scale"))
   370 
   371     def theory_qualifier: String =
   372       options.string("theory_qualifier") match {
   373         case "" => name
   374         case qualifier => qualifier
   375       }
   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.select || 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: Traversable[(String, 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, (name, info)) =>
   470           if (graph.defined(name))
   471             error("Duplicate session " + quote(name) + Position.here(info.pos) +
   472               Position.here(graph.get_node(name).pos))
   473           else graph.new_node(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 apply(name: String): Info = imports_graph.get_node(name)
   486     def get(name: String): Option[Info] =
   487       if (imports_graph.defined(name)) Some(imports_graph.get_node(name)) else None
   488 
   489     def global_theories: Map[String, String] =
   490       (Thy_Header.bootstrap_global_theories.toMap /:
   491         (for {
   492           (_, (info, _)) <- imports_graph.iterator
   493           thy <- info.global_theories.iterator }
   494          yield (thy, info)))({
   495             case (global, (thy, info)) =>
   496               val qualifier = info.theory_qualifier
   497               global.get(thy) match {
   498                 case Some(qualifier1) if qualifier != qualifier1 =>
   499                   error("Duplicate global theory " + quote(thy) + Position.here(info.pos))
   500                 case _ => global + (thy -> qualifier)
   501               }
   502           })
   503 
   504     def selection(select: Selection): (List[String], T) =
   505     {
   506       val (_, build_graph1) = select(build_graph)
   507       val (selected, imports_graph1) = select(imports_graph)
   508       (selected, new T(build_graph1, imports_graph1))
   509     }
   510 
   511     def build_ancestors(name: String): List[String] =
   512       build_graph.all_preds(List(name)).tail.reverse
   513 
   514     def build_descendants(names: List[String]): List[String] =
   515       build_graph.all_succs(names)
   516 
   517     def build_topological_order: List[Info] =
   518       build_graph.topological_order.map(apply(_))
   519 
   520     def imports_ancestors(name: String): List[String] =
   521       imports_graph.all_preds(List(name)).tail.reverse
   522 
   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 FILES = "files"
   545   private val DOCUMENT_FILES = "document_files"
   546 
   547   lazy val root_syntax =
   548     Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" + GLOBAL + IN +
   549       (CHAPTER, Keyword.THY_DECL) +
   550       (SESSION, Keyword.THY_DECL) +
   551       (DESCRIPTION, Keyword.QUASI_COMMAND) +
   552       (OPTIONS, Keyword.QUASI_COMMAND) +
   553       (SESSIONS, Keyword.QUASI_COMMAND) +
   554       (THEORIES, Keyword.QUASI_COMMAND) +
   555       (FILES, Keyword.QUASI_COMMAND) +
   556       (DOCUMENT_FILES, Keyword.QUASI_COMMAND)
   557 
   558   private object Parser extends Parse.Parser with Options.Parser
   559   {
   560     private abstract class Entry
   561     private sealed case class Chapter(name: String) extends Entry
   562     private sealed case class Session_Entry(
   563       pos: Position.T,
   564       name: String,
   565       groups: List[String],
   566       path: String,
   567       parent: Option[String],
   568       description: String,
   569       options: List[Options.Spec],
   570       imports: List[String],
   571       theories: List[(List[Options.Spec], List[((String, Position.T), Boolean)])],
   572       files: List[String],
   573       document_files: List[(String, String)]) extends Entry
   574     {
   575       def theories_no_position: List[(List[Options.Spec], List[(String, Boolean)])] =
   576         theories.map({ case (a, b) => (a, b.map({ case ((c, _), d) => (c, d) })) })
   577     }
   578 
   579     private val chapter: Parser[Chapter] =
   580     {
   581       val chapter_name = atom("chapter name", _.is_name)
   582 
   583       command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
   584     }
   585 
   586     private val session_entry: Parser[Session_Entry] =
   587     {
   588       val session_name = atom("session name", _.is_name)
   589 
   590       val option =
   591         option_name ~ opt($$$("=") ~! option_value ^^
   592           { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
   593       val options = $$$("[") ~> rep1sep(option, $$$(",")) <~ $$$("]")
   594 
   595       val global =
   596         ($$$("(") ~! $$$(GLOBAL) ~ $$$(")")) ^^ { case _ => true } | success(false)
   597 
   598       val theory_entry =
   599         position(theory_name) ~ global ^^ { case x ~ y => (x, y) }
   600 
   601       val theories =
   602         $$$(THEORIES) ~!
   603           ((options | success(Nil)) ~ rep(theory_entry)) ^^
   604           { case _ ~ (x ~ y) => (x, y) }
   605 
   606       val document_files =
   607         $$$(DOCUMENT_FILES) ~!
   608           (($$$("(") ~! ($$$(IN) ~! (path ~ $$$(")"))) ^^
   609               { case _ ~ (_ ~ (x ~ _)) => x } | success("document")) ~
   610             rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
   611 
   612       command(SESSION) ~!
   613         (position(session_name) ~
   614           (($$$("(") ~! (rep1(name) <~ $$$(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
   615           (($$$(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
   616           ($$$("=") ~!
   617             (opt(session_name ~! $$$("+") ^^ { case x ~ _ => x }) ~
   618               (($$$(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
   619               (($$$(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
   620               (($$$(SESSIONS) ~! rep(session_name)  ^^ { case _ ~ x => x }) | success(Nil)) ~
   621               rep1(theories) ~
   622               (($$$(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil)) ~
   623               (rep(document_files) ^^ (x => x.flatten))))) ^^
   624         { case _ ~ ((a, pos) ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i ~ j))) =>
   625             Session_Entry(pos, a, b, c, d, e, f, g, h, i, j) }
   626     }
   627 
   628     def parse(options: Options, select: Boolean, dir: Path): List[(String, Info)] =
   629     {
   630       def make_info(entry_chapter: String, entry: Session_Entry): (String, Info) =
   631       {
   632         try {
   633           val name = entry.name
   634 
   635           if (name == "" || name == DRAFT) error("Bad session name")
   636           if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
   637           if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
   638 
   639           val session_options = options ++ entry.options
   640 
   641           val theories =
   642             entry.theories.map({ case (opts, thys) => (session_options ++ opts, thys.map(_._1)) })
   643 
   644           val global_theories =
   645             for { (_, thys) <- entry.theories; ((thy, pos), global) <- thys if global }
   646             yield {
   647               val thy_name = Path.explode(thy).expand.base_name
   648               if (Long_Name.is_qualified(thy_name))
   649                 error("Bad qualified name for global theory " +
   650                   quote(thy_name) + Position.here(pos))
   651               else thy_name
   652             }
   653 
   654           val files = entry.files.map(Path.explode(_))
   655           val document_files =
   656             entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
   657 
   658           val meta_digest =
   659             SHA1.digest((entry_chapter, name, entry.parent, entry.options, entry.imports,
   660               entry.theories_no_position, entry.files, entry.document_files).toString)
   661 
   662           val info =
   663             Info(name, entry_chapter, select, entry.pos, entry.groups,
   664               dir + Path.explode(entry.path), entry.parent, entry.description, session_options,
   665               entry.imports, theories, global_theories, files, document_files, meta_digest)
   666 
   667           (name, info)
   668         }
   669         catch {
   670           case ERROR(msg) =>
   671             error(msg + "\nThe error(s) above occurred in session entry " +
   672               quote(entry.name) + Position.here(entry.pos))
   673         }
   674       }
   675 
   676       val root = dir + ROOT
   677       if (root.is_file) {
   678         val toks = Token.explode(root_syntax.keywords, File.read(root))
   679         val start = Token.Pos.file(root.implode)
   680 
   681         parse_all(rep(chapter | session_entry), Token.reader(toks, start)) match {
   682           case Success(result, _) =>
   683             var entry_chapter = "Unsorted"
   684             val infos = new mutable.ListBuffer[(String, Info)]
   685             result.foreach {
   686               case Chapter(name) => entry_chapter = name
   687               case entry: Session_Entry => infos += make_info(entry_chapter, entry)
   688             }
   689             infos.toList
   690           case bad => error(bad.toString)
   691         }
   692       }
   693       else Nil
   694     }
   695   }
   696 
   697 
   698   /* load sessions from certain directories */
   699 
   700   private def is_session_dir(dir: Path): Boolean =
   701     (dir + ROOT).is_file || (dir + ROOTS).is_file
   702 
   703   private def check_session_dir(dir: Path): Path =
   704     if (is_session_dir(dir)) File.pwd() + dir.expand
   705     else error("Bad session root directory: " + dir.toString)
   706 
   707   def directories(dirs: List[Path], select_dirs: List[Path]): List[(Boolean, Path)] =
   708   {
   709     val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
   710     (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _))
   711   }
   712 
   713   def load(options: Options, dirs: List[Path] = Nil, select_dirs: List[Path] = Nil): T =
   714   {
   715     def load_dir(select: Boolean, dir: Path): List[(String, Info)] =
   716       load_root(select, dir) ::: load_roots(select, dir)
   717 
   718     def load_root(select: Boolean, dir: Path): List[(String, Info)] =
   719       Parser.parse(options, select, dir)
   720 
   721     def load_roots(select: Boolean, dir: Path): List[(String, Info)] =
   722     {
   723       val roots = dir + ROOTS
   724       if (roots.is_file) {
   725         for {
   726           line <- split_lines(File.read(roots))
   727           if !(line == "" || line.startsWith("#"))
   728           dir1 =
   729             try { check_session_dir(dir + Path.explode(line)) }
   730             catch {
   731               case ERROR(msg) =>
   732                 error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
   733             }
   734           info <- load_dir(select, dir1)
   735         } yield info
   736       }
   737       else Nil
   738     }
   739 
   740     make(
   741       for {
   742         (select, dir) <- directories(dirs, select_dirs)
   743         info <- load_dir(select, check_session_dir(dir))
   744       } yield info)
   745   }
   746 
   747 
   748 
   749   /** heap file with SHA1 digest **/
   750 
   751   private val sha1_prefix = "SHA1:"
   752 
   753   def read_heap_digest(heap: Path): Option[String] =
   754   {
   755     if (heap.is_file) {
   756       val file = FileChannel.open(heap.file.toPath, StandardOpenOption.READ)
   757       try {
   758         val len = file.size
   759         val n = sha1_prefix.length + SHA1.digest_length
   760         if (len >= n) {
   761           file.position(len - n)
   762 
   763           val buf = ByteBuffer.allocate(n)
   764           var i = 0
   765           var m = 0
   766           do {
   767             m = file.read(buf)
   768             if (m != -1) i += m
   769           }
   770           while (m != -1 && n > i)
   771 
   772           if (i == n) {
   773             val prefix = new String(buf.array(), 0, sha1_prefix.length, UTF8.charset)
   774             val s = new String(buf.array(), sha1_prefix.length, SHA1.digest_length, UTF8.charset)
   775             if (prefix == sha1_prefix) Some(s) else None
   776           }
   777           else None
   778         }
   779         else None
   780       }
   781       finally { file.close }
   782     }
   783     else None
   784   }
   785 
   786   def write_heap_digest(heap: Path): String =
   787     read_heap_digest(heap) match {
   788       case None =>
   789         val s = SHA1.digest(heap).rep
   790         File.append(heap, sha1_prefix + s)
   791         s
   792       case Some(s) => s
   793     }
   794 
   795 
   796 
   797   /** persistent store **/
   798 
   799   object Session_Info
   800   {
   801     val session_name = SQL.Column.string("session_name", primary_key = true)
   802 
   803     // Build_Log.Session_Info
   804     val session_timing = SQL.Column.bytes("session_timing")
   805     val command_timings = SQL.Column.bytes("command_timings")
   806     val ml_statistics = SQL.Column.bytes("ml_statistics")
   807     val task_statistics = SQL.Column.bytes("task_statistics")
   808     val errors = SQL.Column.bytes("errors")
   809     val build_log_columns =
   810       List(session_name, session_timing, command_timings, ml_statistics, task_statistics, errors)
   811 
   812     // Build.Session_Info
   813     val sources = SQL.Column.string("sources")
   814     val input_heaps = SQL.Column.string("input_heaps")
   815     val output_heap = SQL.Column.string("output_heap")
   816     val return_code = SQL.Column.int("return_code")
   817     val build_columns = List(sources, input_heaps, output_heap, return_code)
   818 
   819     val table = SQL.Table("isabelle_session_info", build_log_columns ::: build_columns)
   820   }
   821 
   822   def store(system_mode: Boolean = false): Store = new Store(system_mode)
   823 
   824   class Store private[Sessions](system_mode: Boolean)
   825   {
   826     /* file names */
   827 
   828     def database(name: String): Path = Path.basic("log") + Path.basic(name).ext("db")
   829     def log(name: String): Path = Path.basic("log") + Path.basic(name)
   830     def log_gz(name: String): Path = log(name).ext("gz")
   831 
   832 
   833     /* SQL database content */
   834 
   835     val xml_cache = new XML.Cache()
   836 
   837     def read_bytes(db: SQL.Database, name: String, column: SQL.Column): Bytes =
   838       db.using_statement(Session_Info.table.select(List(column),
   839         Session_Info.session_name.where_equal(name)))(stmt =>
   840       {
   841         val res = stmt.execute_query()
   842         if (!res.next()) Bytes.empty else res.bytes(column)
   843       })
   844 
   845     def read_properties(db: SQL.Database, name: String, column: SQL.Column): List[Properties.T] =
   846       Properties.uncompress(read_bytes(db, name, column), Some(xml_cache))
   847 
   848 
   849     /* output */
   850 
   851     val browser_info: Path =
   852       if (system_mode) Path.explode("~~/browser_info")
   853       else Path.explode("$ISABELLE_BROWSER_INFO")
   854 
   855     val output_dir: Path =
   856       if (system_mode) Path.explode("~~/heaps/$ML_IDENTIFIER")
   857       else Path.explode("$ISABELLE_OUTPUT")
   858 
   859     override def toString: String = "Store(output_dir = " + output_dir.expand + ")"
   860 
   861     def prepare_output() { Isabelle_System.mkdirs(output_dir + Path.basic("log")) }
   862 
   863 
   864     /* input */
   865 
   866     private val input_dirs =
   867       if (system_mode) List(output_dir)
   868       else {
   869         val ml_ident = Path.explode("$ML_IDENTIFIER").expand
   870         output_dir :: Path.split(Isabelle_System.getenv_strict("ISABELLE_PATH")).map(_ + ml_ident)
   871       }
   872 
   873     def find_database_heap(name: String): Option[(Path, Option[String])] =
   874       input_dirs.find(dir => (dir + database(name)).is_file).map(dir =>
   875         (dir + database(name), read_heap_digest(dir + Path.basic(name))))
   876 
   877     def find_database(name: String): Option[Path] =
   878       input_dirs.map(_ + database(name)).find(_.is_file)
   879 
   880     def heap(name: String): Path =
   881       input_dirs.map(_ + Path.basic(name)).find(_.is_file) getOrElse
   882         error("Unknown logic " + quote(name) + " -- no heap file found in:\n" +
   883           cat_lines(input_dirs.map(dir => "  " + dir.expand.implode)))
   884 
   885 
   886     /* session info */
   887 
   888     def write_session_info(
   889       db: SQL.Database,
   890       name: String,
   891       build_log: Build_Log.Session_Info,
   892       build: Build.Session_Info)
   893     {
   894       db.transaction {
   895         db.create_table(Session_Info.table)
   896         db.using_statement(
   897           Session_Info.table.delete(Session_Info.session_name.where_equal(name)))(_.execute)
   898         db.using_statement(Session_Info.table.insert())(stmt =>
   899         {
   900           stmt.string(1) = name
   901           stmt.bytes(2) = Properties.encode(build_log.session_timing)
   902           stmt.bytes(3) = Properties.compress(build_log.command_timings)
   903           stmt.bytes(4) = Properties.compress(build_log.ml_statistics)
   904           stmt.bytes(5) = Properties.compress(build_log.task_statistics)
   905           stmt.bytes(6) = Build_Log.compress_errors(build_log.errors)
   906           stmt.string(7) = cat_lines(build.sources)
   907           stmt.string(8) = cat_lines(build.input_heaps)
   908           stmt.string(9) = build.output_heap getOrElse ""
   909           stmt.int(10) = build.return_code
   910           stmt.execute()
   911         })
   912       }
   913     }
   914 
   915     def read_session_timing(db: SQL.Database, name: String): Properties.T =
   916       Properties.decode(read_bytes(db, name, Session_Info.session_timing), Some(xml_cache))
   917 
   918     def read_command_timings(db: SQL.Database, name: String): List[Properties.T] =
   919       read_properties(db, name, Session_Info.command_timings)
   920 
   921     def read_ml_statistics(db: SQL.Database, name: String): List[Properties.T] =
   922       read_properties(db, name, Session_Info.ml_statistics)
   923 
   924     def read_task_statistics(db: SQL.Database, name: String): List[Properties.T] =
   925       read_properties(db, name, Session_Info.task_statistics)
   926 
   927     def read_errors(db: SQL.Database, name: String): List[String] =
   928       Build_Log.uncompress_errors(read_bytes(db, name, Session_Info.errors))
   929 
   930     def read_build(db: SQL.Database, name: String): Option[Build.Session_Info] =
   931       db.using_statement(Session_Info.table.select(Session_Info.build_columns,
   932         Session_Info.session_name.where_equal(name)))(stmt =>
   933       {
   934         val res = stmt.execute_query()
   935         if (!res.next()) None
   936         else {
   937           Some(
   938             Build.Session_Info(
   939               split_lines(res.string(Session_Info.sources)),
   940               split_lines(res.string(Session_Info.input_heaps)),
   941               res.string(Session_Info.output_heap) match { case "" => None case s => Some(s) },
   942               res.int(Session_Info.return_code)))
   943         }
   944       })
   945   }
   946 }