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