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