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