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