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