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