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