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