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