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