src/Pure/Tools/build.scala
author wenzelm
Mon Jan 09 20:31:00 2017 +0100 (2017-01-09)
changeset 64855 8fcc23e8e1d9
parent 64854 f5aa712e6250
child 64856 5e9bf964510a
permissions -rw-r--r--
tuned;
     1 /*  Title:      Pure/Tools/build.scala
     2     Author:     Makarius
     3     Options:    :folding=explicit:
     4 
     5 Build and manage Isabelle sessions.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import java.io.{BufferedInputStream, FileInputStream,
    12   BufferedReader, InputStreamReader, IOException}
    13 import java.util.zip.GZIPInputStream
    14 
    15 import scala.collection.SortedSet
    16 import scala.collection.mutable
    17 import scala.annotation.tailrec
    18 
    19 
    20 object Build
    21 {
    22   /** auxiliary **/
    23 
    24   /* queue */
    25 
    26   private object Queue
    27   {
    28     def apply(tree: Sessions.Tree, load_timings: String => (List[Properties.T], Double)): Queue =
    29     {
    30       val graph = tree.graph
    31       val sessions = graph.keys
    32 
    33       val timings = Par_List.map((name: String) => (name, load_timings(name)), sessions)
    34       val command_timings =
    35         Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
    36       val session_timing =
    37         Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
    38 
    39       def outdegree(name: String): Int = graph.imm_succs(name).size
    40 
    41       object Ordering extends scala.math.Ordering[String]
    42       {
    43         def compare_timing(name1: String, name2: String): Int =
    44         {
    45           val t1 = session_timing(name1)
    46           val t2 = session_timing(name2)
    47           if (t1 == 0.0 || t2 == 0.0) 0
    48           else t1 compare t2
    49         }
    50 
    51         def compare(name1: String, name2: String): Int =
    52           outdegree(name2) compare outdegree(name1) match {
    53             case 0 =>
    54               compare_timing(name2, name1) match {
    55                 case 0 =>
    56                   tree(name2).timeout compare tree(name1).timeout match {
    57                     case 0 => name1 compare name2
    58                     case ord => ord
    59                   }
    60                 case ord => ord
    61               }
    62             case ord => ord
    63           }
    64       }
    65 
    66       new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
    67     }
    68   }
    69 
    70   private final class Queue private(
    71     graph: Graph[String, Sessions.Info],
    72     order: SortedSet[String],
    73     val command_timings: String => List[Properties.T])
    74   {
    75     def is_inner(name: String): Boolean = !graph.is_maximal(name)
    76 
    77     def is_empty: Boolean = graph.is_empty
    78 
    79     def - (name: String): Queue =
    80       new Queue(graph.del_node(name),
    81         order - name,  // FIXME scala-2.10.0 TreeSet problem!?
    82         command_timings)
    83 
    84     def dequeue(skip: String => Boolean): Option[(String, Sessions.Info)] =
    85     {
    86       val it = order.iterator.dropWhile(name =>
    87         skip(name)
    88           || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
    89           || !graph.is_minimal(name))
    90       if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
    91       else None
    92     }
    93   }
    94 
    95 
    96   /* source dependencies and static content */
    97 
    98   object Session_Content
    99   {
   100     val empty: Session_Content =
   101       Session_Content(Set.empty, Map.empty, Nil, Outer_Syntax.empty,
   102         Nil, Graph_Display.empty_graph)
   103 
   104     lazy val bootstrap: Session_Content =
   105       Session_Content(Set.empty, Map.empty, Thy_Header.bootstrap_header,
   106         Thy_Header.bootstrap_syntax, Nil, Graph_Display.empty_graph)
   107   }
   108 
   109   sealed case class Session_Content(
   110     loaded_theories: Set[String],
   111     known_theories: Map[String, Document.Node.Name],
   112     keywords: Thy_Header.Keywords,
   113     syntax: Outer_Syntax,
   114     sources: List[(Path, SHA1.Digest)],
   115     session_graph: Graph_Display.Graph)
   116 
   117   sealed case class Deps(deps: Map[String, Session_Content])
   118   {
   119     def is_empty: Boolean = deps.isEmpty
   120     def apply(name: String): Session_Content = deps(name)
   121     def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
   122   }
   123 
   124   def dependencies(
   125       progress: Progress = Ignore_Progress,
   126       inlined_files: Boolean = false,
   127       verbose: Boolean = false,
   128       list_files: Boolean = false,
   129       check_keywords: Set[String] = Set.empty,
   130       tree: Sessions.Tree): Deps =
   131     Deps((Map.empty[String, Session_Content] /: tree.topological_order)(
   132       { case (deps, (name, info)) =>
   133           if (progress.stopped) throw Exn.Interrupt()
   134 
   135           try {
   136             val base =
   137               info.parent match {
   138                 case None => Session_Content.bootstrap
   139                 case Some(parent) => deps(parent)
   140               }
   141             val resources = new Resources(base)
   142 
   143             if (verbose || list_files) {
   144               val groups =
   145                 if (info.groups.isEmpty) ""
   146                 else info.groups.mkString(" (", " ", ")")
   147               progress.echo("Session " + info.chapter + "/" + name + groups)
   148             }
   149 
   150             val thy_deps =
   151             {
   152               val root_theories =
   153                 info.theories.flatMap({
   154                   case (global, _, thys) =>
   155                     thys.map(thy =>
   156                       (resources.node_name(
   157                         if (global) "" else name, info.dir + Resources.thy_path(thy)), info.pos))
   158                 })
   159               val thy_deps = resources.thy_info.dependencies(name, root_theories)
   160 
   161               thy_deps.errors match {
   162                 case Nil => thy_deps
   163                 case errs => error(cat_lines(errs))
   164               }
   165             }
   166 
   167             val known_theories =
   168               (base.known_theories /: thy_deps.deps)({ case (known, dep) =>
   169                 val name = dep.name
   170                 known.get(name.theory) match {
   171                   case Some(name1) if name != name1 =>
   172                     error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
   173                   case _ =>
   174                     known + (name.theory -> name) + (Long_Name.base_name(name.theory) -> name)
   175                 }
   176               })
   177 
   178             val loaded_theories = thy_deps.loaded_theories
   179             val keywords = thy_deps.keywords
   180             val syntax = thy_deps.syntax
   181 
   182             val theory_files = thy_deps.deps.map(dep => Path.explode(dep.name.node))
   183             val loaded_files =
   184               if (inlined_files) {
   185                 val pure_files =
   186                   if (Sessions.pure_name(name)) Sessions.pure_files(resources, syntax, info.dir)
   187                   else Nil
   188                 pure_files ::: thy_deps.loaded_files
   189               }
   190               else Nil
   191 
   192             val all_files =
   193               (theory_files ::: loaded_files :::
   194                 info.files.map(file => info.dir + file) :::
   195                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   196 
   197             if (list_files)
   198               progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
   199 
   200             if (check_keywords.nonEmpty)
   201               Check_Keywords.check_keywords(progress, syntax.keywords, check_keywords, theory_files)
   202 
   203             val sources = all_files.map(p => (p, SHA1.digest(p.file)))
   204 
   205             val session_graph =
   206               Present.session_graph(info.parent getOrElse "", base.loaded_theories, thy_deps.deps)
   207 
   208             val content =
   209               Session_Content(loaded_theories, known_theories, keywords, syntax,
   210                 sources, session_graph)
   211             deps + (name -> content)
   212           }
   213           catch {
   214             case ERROR(msg) =>
   215               cat_error(msg, "The error(s) above occurred in session " +
   216                 quote(name) + Position.here(info.pos))
   217           }
   218       }))
   219 
   220   def session_dependencies(
   221     options: Options,
   222     inlined_files: Boolean,
   223     dirs: List[Path],
   224     sessions: List[String]): Deps =
   225   {
   226     val (_, tree) = Sessions.load(options, dirs = dirs).selection(sessions = sessions)
   227     dependencies(inlined_files = inlined_files, tree = tree)
   228   }
   229 
   230   def session_content(
   231     options: Options,
   232     inlined_files: Boolean,
   233     dirs: List[Path],
   234     session: String): Session_Content =
   235   {
   236     session_dependencies(options, inlined_files, dirs, List(session))(session)
   237   }
   238 
   239   def outer_syntax(options: Options, dirs: List[Path], session: String): Outer_Syntax =
   240     session_content(options, false, dirs, session).syntax
   241 
   242 
   243   /* jobs */
   244 
   245   private class Job(progress: Progress, name: String, val info: Sessions.Info, tree: Sessions.Tree,
   246     store: Sessions.Store, do_output: Boolean, verbose: Boolean, val numa_node: Option[Int],
   247     session_graph: Graph_Display.Graph, command_timings: List[Properties.T])
   248   {
   249     val output = store.output_dir + Path.basic(name)
   250     def output_path: Option[Path] = if (do_output) Some(output) else None
   251     def output_save_state: String =
   252       if (do_output) "ML_Heap.save_child " + ML_Syntax.print_string0(File.platform_path(output))
   253       else ""
   254     output.file.delete
   255 
   256     private val parent = info.parent.getOrElse("")
   257 
   258     private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
   259     try { isabelle.graphview.Graph_File.write(info.options, graph_file, session_graph) }
   260     catch { case ERROR(_) => /*error should be exposed in ML*/ }
   261 
   262     private val env =
   263       Isabelle_System.settings() +
   264         ("ISABELLE_ML_DEBUGGER" -> info.options.bool("ML_debugger").toString)
   265 
   266     private val future_result: Future[Process_Result] =
   267       Future.thread("build") {
   268         val args_file = Isabelle_System.tmp_file("build")
   269         File.write(args_file, YXML.string_of_body(
   270             {
   271               val theories = info.theories.map(x => (x._2, x._3))
   272               import XML.Encode._
   273               pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
   274                 pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
   275                 pair(string, pair(string, pair(string,
   276                 list(pair(Options.encode, list(Path.encode)))))))))))))(
   277               (Symbol.codes, (command_timings, (do_output, (verbose,
   278                 (store.browser_info, (info.document_files, (File.standard_path(graph_file),
   279                 (parent, (info.chapter, (name,
   280                 theories)))))))))))
   281             }))
   282 
   283         val eval =
   284           "Command_Line.tool0 (fn () => (" +
   285           "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
   286           (if (do_output) "; ML_Heap.share_common_data (); " + output_save_state
   287            else "") + "));"
   288 
   289         val process_options =
   290           numa_node match {
   291             case None => info.options
   292             case Some(n) => info.options.string("ML_process_policy") = NUMA.policy(n)
   293           }
   294         val process =
   295           if (Sessions.pure_name(name)) {
   296             ML_Process(process_options, raw_ml_system = true, cwd = info.dir.file,
   297               args =
   298                 (for ((root, _) <- Thy_Header.ml_roots) yield List("--use", root)).flatten :::
   299                 List("--eval", eval),
   300               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   301           }
   302           else {
   303             ML_Process(process_options, parent, List("--eval", eval), cwd = info.dir.file,
   304               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   305           }
   306 
   307         process.result(
   308           progress_stdout = (line: String) =>
   309             Library.try_unprefix("\floading_theory = ", line) match {
   310               case Some(theory) => progress.theory(name, theory)
   311               case None =>
   312             },
   313           progress_limit =
   314             info.options.int("process_output_limit") match {
   315               case 0 => None
   316               case m => Some(m * 1000000L)
   317             },
   318           strict = false)
   319       }
   320 
   321     def terminate: Unit = future_result.cancel
   322     def is_finished: Boolean = future_result.is_finished
   323 
   324     @volatile private var was_timeout = false
   325     private val timeout_request: Option[Event_Timer.Request] =
   326     {
   327       if (info.timeout > Time.zero)
   328         Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
   329       else None
   330     }
   331 
   332     def join: Process_Result =
   333     {
   334       val result = future_result.join
   335 
   336       if (result.ok)
   337         Present.finish(progress, store.browser_info, graph_file, info, name)
   338 
   339       graph_file.delete
   340       timeout_request.foreach(_.cancel)
   341 
   342       if (result.interrupted) {
   343         if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
   344         else result.error(Output.error_text("Interrupt"))
   345       }
   346       else result
   347     }
   348   }
   349 
   350 
   351   /* sources and heaps */
   352 
   353   private val SOURCES = "sources: "
   354   private val INPUT_HEAP = "input_heap: "
   355   private val OUTPUT_HEAP = "output_heap: "
   356   private val LOG_START = "log:"
   357   private val line_prefixes = List(SOURCES, INPUT_HEAP, OUTPUT_HEAP, LOG_START)
   358 
   359   private def sources_stamp(digests: List[SHA1.Digest]): String =
   360     digests.map(_.toString).sorted.mkString(SOURCES, " ", "")
   361 
   362   private def read_stamps(path: Path): Option[(String, List[String], List[String])] =
   363     if (path.is_file) {
   364       val stream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(path.file)))
   365       val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
   366       val lines =
   367       {
   368         val lines = new mutable.ListBuffer[String]
   369         try {
   370           var finished = false
   371           while (!finished) {
   372             val line = reader.readLine
   373             if (line != null && line_prefixes.exists(line.startsWith(_)))
   374               lines += line
   375             else finished = true
   376           }
   377         }
   378         finally { reader.close }
   379         lines.toList
   380       }
   381 
   382       if (!lines.isEmpty && lines.last.startsWith(LOG_START)) {
   383         lines.find(_.startsWith(SOURCES)).map(s =>
   384           (s, lines.filter(_.startsWith(INPUT_HEAP)), lines.filter(_.startsWith(OUTPUT_HEAP))))
   385       }
   386       else None
   387     }
   388     else None
   389 
   390 
   391 
   392   /** build with results **/
   393 
   394   class Results private[Build](results: Map[String, (Option[Process_Result], Sessions.Info)])
   395   {
   396     def sessions: Set[String] = results.keySet
   397     def cancelled(name: String): Boolean = results(name)._1.isEmpty
   398     def apply(name: String): Process_Result = results(name)._1.getOrElse(Process_Result(1))
   399     def info(name: String): Sessions.Info = results(name)._2
   400     val rc = (0 /: results.iterator.map({ case (_, (Some(r), _)) => r.rc case (_, (None, _)) => 1 }))(_ max _)
   401     def ok: Boolean = rc == 0
   402 
   403     override def toString: String = rc.toString
   404   }
   405 
   406   def build(
   407     options: Options,
   408     progress: Progress = Ignore_Progress,
   409     build_heap: Boolean = false,
   410     clean_build: Boolean = false,
   411     dirs: List[Path] = Nil,
   412     select_dirs: List[Path] = Nil,
   413     numa_shuffling: Boolean = false,
   414     max_jobs: Int = 1,
   415     list_files: Boolean = false,
   416     check_keywords: Set[String] = Set.empty,
   417     no_build: Boolean = false,
   418     system_mode: Boolean = false,
   419     verbose: Boolean = false,
   420     requirements: Boolean = false,
   421     all_sessions: Boolean = false,
   422     exclude_session_groups: List[String] = Nil,
   423     exclude_sessions: List[String] = Nil,
   424     session_groups: List[String] = Nil,
   425     sessions: List[String] = Nil): Results =
   426   {
   427     build_selection(
   428       options = options,
   429       progress = progress,
   430       build_heap = build_heap,
   431       clean_build = clean_build,
   432       dirs = dirs,
   433       select_dirs = select_dirs,
   434       numa_shuffling = numa_shuffling,
   435       max_jobs = max_jobs,
   436       list_files = list_files,
   437       check_keywords = check_keywords,
   438       no_build = no_build,
   439       system_mode = system_mode,
   440       verbose = verbose,
   441       selection = { full_tree =>
   442         full_tree.selection(requirements, all_sessions,
   443           exclude_session_groups, exclude_sessions, session_groups, sessions) })
   444   }
   445 
   446   def build_selection(
   447     options: Options,
   448     progress: Progress = Ignore_Progress,
   449     build_heap: Boolean = false,
   450     clean_build: Boolean = false,
   451     dirs: List[Path] = Nil,
   452     select_dirs: List[Path] = Nil,
   453     numa_shuffling: Boolean = false,
   454     max_jobs: Int = 1,
   455     list_files: Boolean = false,
   456     check_keywords: Set[String] = Set.empty,
   457     no_build: Boolean = false,
   458     system_mode: Boolean = false,
   459     verbose: Boolean = false,
   460     selection: Sessions.Tree => (List[String], Sessions.Tree) =
   461       (_.selection(all_sessions = true))): Results =
   462   {
   463     /* session selection and dependencies */
   464 
   465     val build_options = options.int.update("completion_limit", 0).bool.update("ML_statistics", true)
   466     val full_tree = Sessions.load(build_options, dirs, select_dirs)
   467     val (selected, selected_tree) = selection(full_tree)
   468     val deps = dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
   469 
   470     def session_sources_stamp(name: String): String =
   471       sources_stamp(selected_tree(name).meta_digest :: deps.sources(name))
   472 
   473     val store = Sessions.store(system_mode)
   474 
   475 
   476     /* queue with scheduling information */
   477 
   478     def load_timings(name: String): (List[Properties.T], Double) =
   479     {
   480       val (path, text) =
   481         store.find_log_gz(name) match {
   482           case Some(path) => (path, File.read_gzip(path))
   483           case None =>
   484             store.find_log(name) match {
   485               case Some(path) => (path, File.read(path))
   486               case None => (Path.current, "")
   487             }
   488         }
   489 
   490       def ignore_error(msg: String): (List[Properties.T], Double) =
   491       {
   492         Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
   493         (Nil, 0.0)
   494       }
   495 
   496       try {
   497         val info = Build_Log.Log_File(name, text).parse_session_info(name, command_timings = true)
   498         val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
   499         (info.command_timings, session_timing)
   500       }
   501       catch {
   502         case ERROR(msg) => ignore_error(msg)
   503         case exn: java.lang.Error => ignore_error(Exn.message(exn))
   504         case _: XML.Error => ignore_error("")
   505       }
   506     }
   507 
   508     val queue = Queue(selected_tree, load_timings)
   509 
   510 
   511     /* main build process */
   512 
   513     store.prepare_output()
   514 
   515     // optional cleanup
   516     if (clean_build) {
   517       for (name <- full_tree.graph.all_succs(selected)) {
   518         val files =
   519           List(Path.basic(name), Sessions.log(name), Sessions.log_gz(name)).
   520             map(store.output_dir + _).filter(_.is_file)
   521         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   522         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   523       }
   524     }
   525 
   526     // scheduler loop
   527     case class Result(
   528       current: Boolean, heap_stamp: Option[String],
   529       process: Option[Process_Result], info: Sessions.Info)
   530     {
   531       def ok: Boolean =
   532         process match {
   533           case None => false
   534           case Some(res) => res.rc == 0
   535         }
   536     }
   537 
   538     def sleep()
   539     {
   540       try { Thread.sleep(500) }
   541       catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
   542     }
   543 
   544     val numa_nodes = new NUMA.Nodes(numa_shuffling)
   545 
   546     @tailrec def loop(
   547       pending: Queue,
   548       running: Map[String, (List[String], Job)],
   549       results: Map[String, Result]): Map[String, Result] =
   550     {
   551       def used_node(i: Int): Boolean =
   552         running.iterator.exists(
   553           { case (_, (_, job)) => job.numa_node.isDefined && job.numa_node.get == i })
   554 
   555       if (pending.is_empty) results
   556       else {
   557         if (progress.stopped)
   558           for ((_, (_, job)) <- running) job.terminate
   559 
   560         running.find({ case (_, (_, job)) => job.is_finished }) match {
   561           case Some((name, (input_heaps, job))) =>
   562             //{{{ finish job
   563 
   564             val process_result = job.join
   565             process_result.err_lines.foreach(progress.echo(_))
   566             if (process_result.ok)
   567               progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
   568 
   569             val process_result_tail =
   570             {
   571               val lines = process_result.out_lines.filterNot(_.startsWith("\f"))
   572               val tail = job.info.options.int("process_output_tail")
   573               val lines1 = if (tail == 0) lines else lines.drop(lines.length - tail max 0)
   574               process_result.copy(
   575                 out_lines =
   576                   "(see also " + (store.output_dir + Sessions.log(name)).file.toString + ")" ::
   577                   lines1)
   578             }
   579 
   580             val heap_stamp =
   581               if (process_result.ok) {
   582                 (store.output_dir + Sessions.log(name)).file.delete
   583                 val heap_stamp =
   584                   for (path <- job.output_path if path.is_file)
   585                     yield Sessions.write_heap_digest(path)
   586 
   587                 File.write_gzip(store.output_dir + Sessions.log_gz(name),
   588                   terminate_lines(
   589                     session_sources_stamp(name) ::
   590                     input_heaps.map(INPUT_HEAP + _) :::
   591                     heap_stamp.toList.map(OUTPUT_HEAP + _) :::
   592                     List(LOG_START) ::: process_result.out_lines))
   593 
   594                 heap_stamp
   595               }
   596               else {
   597                 (store.output_dir + Path.basic(name)).file.delete
   598                 (store.output_dir + Sessions.log_gz(name)).file.delete
   599 
   600                 File.write(store.output_dir + Sessions.log(name),
   601                   terminate_lines(process_result.out_lines))
   602                 progress.echo(name + " FAILED")
   603                 if (!process_result.interrupted) progress.echo(process_result_tail.out)
   604 
   605                 None
   606               }
   607             loop(pending - name, running - name,
   608               results + (name -> Result(false, heap_stamp, Some(process_result_tail), job.info)))
   609             //}}}
   610           case None if running.size < (max_jobs max 1) =>
   611             //{{{ check/start next job
   612             pending.dequeue(running.isDefinedAt(_)) match {
   613               case Some((name, info)) =>
   614                 val ancestor_results = selected_tree.ancestors(name).map(results(_))
   615                 val ancestor_heaps = ancestor_results.flatMap(_.heap_stamp)
   616 
   617                 val do_output = build_heap || Sessions.pure_name(name) || queue.is_inner(name)
   618 
   619                 val (current, heap_stamp) =
   620                 {
   621                   store.find(name) match {
   622                     case Some((log_gz, heap_stamp)) =>
   623                       read_stamps(log_gz) match {
   624                         case Some((sources, input_heaps, output_heaps)) =>
   625                           val current =
   626                             sources == session_sources_stamp(name) &&
   627                             input_heaps == ancestor_heaps.map(INPUT_HEAP + _) &&
   628                             output_heaps == heap_stamp.toList.map(OUTPUT_HEAP + _) &&
   629                             !(do_output && heap_stamp.isEmpty)
   630                           (current, heap_stamp)
   631                         case None => (false, None)
   632                       }
   633                     case None => (false, None)
   634                   }
   635                 }
   636                 val all_current = current && ancestor_results.forall(_.current)
   637 
   638                 if (all_current)
   639                   loop(pending - name, running,
   640                     results + (name -> Result(true, heap_stamp, Some(Process_Result(0)), info)))
   641                 else if (no_build) {
   642                   if (verbose) progress.echo("Skipping " + name + " ...")
   643                   loop(pending - name, running,
   644                     results + (name -> Result(false, heap_stamp, Some(Process_Result(1)), info)))
   645                 }
   646                 else if (ancestor_results.forall(_.ok) && !progress.stopped) {
   647                   val numa_node = numa_nodes.next(used_node(_))
   648                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   649                   val job =
   650                     new Job(progress, name, info, selected_tree, store, do_output, verbose,
   651                       numa_node, deps(name).session_graph, queue.command_timings(name))
   652                   loop(pending, running + (name -> (ancestor_heaps, job)), results)
   653                 }
   654                 else {
   655                   progress.echo(name + " CANCELLED")
   656                   loop(pending - name, running, results + (name -> Result(false, heap_stamp, None, info)))
   657                 }
   658               case None => sleep(); loop(pending, running, results)
   659             }
   660             ///}}}
   661           case None => sleep(); loop(pending, running, results)
   662         }
   663       }
   664     }
   665 
   666 
   667     /* build results */
   668 
   669     val results0 =
   670       if (deps.is_empty) {
   671         progress.echo(Output.warning_text("Nothing to build"))
   672         Map.empty[String, Result]
   673       }
   674       else loop(queue, Map.empty, Map.empty)
   675 
   676     val results =
   677       new Results(
   678         (for ((name, result) <- results0.iterator)
   679           yield (name, (result.process, result.info))).toMap)
   680 
   681     if (results.rc != 0 && (verbose || !no_build)) {
   682       val unfinished =
   683         (for {
   684           name <- results.sessions.iterator
   685           if !results(name).ok
   686          } yield name).toList.sorted
   687       progress.echo("Unfinished session(s): " + commas(unfinished))
   688     }
   689 
   690 
   691     /* global browser info */
   692 
   693     if (!no_build) {
   694       val browser_chapters =
   695         (for {
   696           (name, result) <- results0.iterator
   697           if result.ok
   698           info = full_tree(name)
   699           if info.options.bool("browser_info")
   700         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   701             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   702 
   703       for ((chapter, entries) <- browser_chapters)
   704         Present.update_chapter_index(store.browser_info, chapter, entries)
   705 
   706       if (browser_chapters.nonEmpty) Present.make_global_index(store.browser_info)
   707     }
   708 
   709     results
   710   }
   711 
   712 
   713   /* Isabelle tool wrapper */
   714 
   715   val isabelle_tool = Isabelle_Tool("build", "build and manage Isabelle sessions", args =>
   716   {
   717     val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
   718 
   719     var select_dirs: List[Path] = Nil
   720     var numa_shuffling = false
   721     var requirements = false
   722     var exclude_session_groups: List[String] = Nil
   723     var all_sessions = false
   724     var build_heap = false
   725     var clean_build = false
   726     var dirs: List[Path] = Nil
   727     var session_groups: List[String] = Nil
   728     var max_jobs = 1
   729     var check_keywords: Set[String] = Set.empty
   730     var list_files = false
   731     var no_build = false
   732     var options = (Options.init() /: build_options)(_ + _)
   733     var system_mode = false
   734     var verbose = false
   735     var exclude_sessions: List[String] = Nil
   736 
   737     val getopts = Getopts("""
   738 Usage: isabelle build [OPTIONS] [SESSIONS ...]
   739 
   740   Options are:
   741     -D DIR       include session directory and select its sessions
   742     -N           cyclic shuffling of NUMA CPU nodes (performance tuning)
   743     -R           operate on requirements of selected sessions
   744     -X NAME      exclude sessions from group NAME and all descendants
   745     -a           select all sessions
   746     -b           build heap images
   747     -c           clean build
   748     -d DIR       include session directory
   749     -g NAME      select session group NAME
   750     -j INT       maximum number of parallel jobs (default 1)
   751     -k KEYWORD   check theory sources for conflicts with proposed keywords
   752     -l           list session source files
   753     -n           no build -- test dependencies only
   754     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   755     -s           system build mode: produce output in ISABELLE_HOME
   756     -v           verbose
   757     -x NAME      exclude session NAME and all descendants
   758 
   759   Build and manage Isabelle sessions, depending on implicit settings:
   760 
   761 """ + Library.prefix_lines("  ", Build_Log.Settings.show()) + "\n",
   762       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   763       "N" -> (_ => numa_shuffling = true),
   764       "R" -> (_ => requirements = true),
   765       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   766       "a" -> (_ => all_sessions = true),
   767       "b" -> (_ => build_heap = true),
   768       "c" -> (_ => clean_build = true),
   769       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   770       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   771       "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
   772       "k:" -> (arg => check_keywords = check_keywords + arg),
   773       "l" -> (_ => list_files = true),
   774       "n" -> (_ => no_build = true),
   775       "o:" -> (arg => options = options + arg),
   776       "s" -> (_ => system_mode = true),
   777       "v" -> (_ => verbose = true),
   778       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   779 
   780     val sessions = getopts(args)
   781 
   782     val progress = new Console_Progress(verbose = verbose)
   783 
   784     val start_date = Date.now()
   785 
   786     if (verbose) {
   787       progress.echo(
   788         "Started at " + Build_Log.print_date(start_date) +
   789           " (" + Isabelle_System.getenv("ML_IDENTIFIER") + " on " + Isabelle_System.hostname() +")")
   790       progress.echo(Build_Log.Settings.show() + "\n")
   791     }
   792 
   793     val results =
   794       progress.interrupt_handler {
   795         build(options, progress,
   796           build_heap = build_heap,
   797           clean_build = clean_build,
   798           dirs = dirs,
   799           select_dirs = select_dirs,
   800           numa_shuffling = NUMA.enabled_warning(numa_shuffling),
   801           max_jobs = max_jobs,
   802           list_files = list_files,
   803           check_keywords = check_keywords,
   804           no_build = no_build,
   805           system_mode = system_mode,
   806           verbose = verbose,
   807           requirements = requirements,
   808           all_sessions = all_sessions,
   809           exclude_session_groups = exclude_session_groups,
   810           exclude_sessions = exclude_sessions,
   811           session_groups = session_groups,
   812           sessions = sessions)
   813       }
   814     val end_date = Date.now()
   815     val elapsed_time = end_date.time - start_date.time
   816 
   817     if (verbose) {
   818       progress.echo("\nFinished at " + Build_Log.print_date(end_date))
   819     }
   820 
   821     val total_timing =
   822       (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
   823         copy(elapsed = elapsed_time)
   824     progress.echo(total_timing.message_resources)
   825 
   826     sys.exit(results.rc)
   827   })
   828 
   829 
   830   /* PIDE protocol */
   831 
   832   def build_theories(
   833     session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   834       session.get_protocol_handler(classOf[Handler].getName) match {
   835         case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
   836         case _ => error("Cannot invoke build_theories: bad protocol handler")
   837       }
   838 
   839   class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
   840   {
   841     private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
   842 
   843     def build_theories(
   844       session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   845     {
   846       val promise = Future.promise[XML.Body]
   847       val id = Document_ID.make().toString
   848       pending.change(promises => promises + (id -> promise))
   849       session.build_theories(id, master_dir, theories)
   850       promise
   851     }
   852 
   853     private def loading_theory(prover: Prover, msg: Prover.Protocol_Output): Boolean =
   854       msg.properties match {
   855         case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
   856         case _ => false
   857       }
   858 
   859     private def build_theories_result(prover: Prover, msg: Prover.Protocol_Output): Boolean =
   860       msg.properties match {
   861         case Markup.Build_Theories_Result(id) =>
   862           pending.change_result(promises =>
   863             promises.get(id) match {
   864               case Some(promise) =>
   865                 val error_message =
   866                   try { YXML.parse_body(Symbol.decode(msg.text)) }
   867                   catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
   868                 promise.fulfill(error_message)
   869                 (true, promises - id)
   870               case None =>
   871                 (false, promises)
   872             })
   873         case _ => false
   874       }
   875 
   876     override def stop(prover: Prover): Unit =
   877       pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
   878 
   879     val functions =
   880       Map(
   881         Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
   882         Markup.LOADING_THEORY -> loading_theory _)
   883   }
   884 }