src/Pure/Tools/build.scala
author wenzelm
Sat Mar 18 20:35:58 2017 +0100 (2017-03-18)
changeset 65312 34d56ca5b548
parent 65308 8f58102afa22
child 65313 347ed6219dab
permissions -rw-r--r--
more uniform options;
     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   /* persistent build info */
    25 
    26   sealed case class Session_Info(
    27     sources: List[String],
    28     input_heaps: List[String],
    29     output_heap: Option[String],
    30     return_code: Int)
    31 
    32 
    33   /* queue with scheduling information */
    34 
    35   private object Queue
    36   {
    37     def load_timings(store: Sessions.Store, name: String): (List[Properties.T], Double) =
    38     {
    39       val no_timings: (List[Properties.T], Double) = (Nil, 0.0)
    40 
    41       store.find_database(name) match {
    42         case None => no_timings
    43         case Some(database) =>
    44           def ignore_error(msg: String) =
    45           {
    46             Output.warning("Ignoring bad database: " + database + (if (msg == "") "" else "\n" + msg))
    47             no_timings
    48           }
    49           try {
    50             using(SQLite.open_database(database))(db =>
    51             {
    52               val build_log = store.read_build_log(db, name, command_timings = true)
    53               val session_timing = Markup.Elapsed.unapply(build_log.session_timing) getOrElse 0.0
    54               (build_log.command_timings, session_timing)
    55             })
    56           }
    57           catch {
    58             case ERROR(msg) => ignore_error(msg)
    59             case exn: java.lang.Error => ignore_error(Exn.message(exn))
    60             case _: XML.Error => ignore_error("")
    61           }
    62       }
    63     }
    64 
    65     def apply(tree: Sessions.Tree, store: Sessions.Store): Queue =
    66     {
    67       val graph = tree.graph
    68       val sessions = graph.keys
    69 
    70       val timings = sessions.map(name => (name, load_timings(store, name)))
    71       val command_timings =
    72         Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
    73       val session_timing =
    74         Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
    75 
    76       def outdegree(name: String): Int = graph.imm_succs(name).size
    77 
    78       object Ordering extends scala.math.Ordering[String]
    79       {
    80         def compare_timing(name1: String, name2: String): Int =
    81         {
    82           val t1 = session_timing(name1)
    83           val t2 = session_timing(name2)
    84           if (t1 == 0.0 || t2 == 0.0) 0
    85           else t1 compare t2
    86         }
    87 
    88         def compare(name1: String, name2: String): Int =
    89           outdegree(name2) compare outdegree(name1) match {
    90             case 0 =>
    91               compare_timing(name2, name1) match {
    92                 case 0 =>
    93                   tree(name2).timeout compare tree(name1).timeout match {
    94                     case 0 => name1 compare name2
    95                     case ord => ord
    96                   }
    97                 case ord => ord
    98               }
    99             case ord => ord
   100           }
   101       }
   102 
   103       new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
   104     }
   105   }
   106 
   107   private final class Queue private(
   108     graph: Graph[String, Sessions.Info],
   109     order: SortedSet[String],
   110     val command_timings: String => List[Properties.T])
   111   {
   112     def is_inner(name: String): Boolean = !graph.is_maximal(name)
   113 
   114     def is_empty: Boolean = graph.is_empty
   115 
   116     def - (name: String): Queue =
   117       new Queue(graph.del_node(name),
   118         order - name,  // FIXME scala-2.10.0 TreeSet problem!?
   119         command_timings)
   120 
   121     def dequeue(skip: String => Boolean): Option[(String, Sessions.Info)] =
   122     {
   123       val it = order.iterator.dropWhile(name =>
   124         skip(name)
   125           || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
   126           || !graph.is_minimal(name))
   127       if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
   128       else None
   129     }
   130   }
   131 
   132 
   133   /* job: running prover process */
   134 
   135   private class Job(progress: Progress,
   136     name: String,
   137     val info: Sessions.Info,
   138     tree: Sessions.Tree,
   139     store: Sessions.Store,
   140     do_output: Boolean,
   141     verbose: Boolean,
   142     pide: Boolean,
   143     val numa_node: Option[Int],
   144     session_graph: Graph_Display.Graph,
   145     command_timings: List[Properties.T])
   146   {
   147     val output = store.output_dir + Path.basic(name)
   148     def output_path: Option[Path] = if (do_output) Some(output) else None
   149     output.file.delete
   150 
   151     val options =
   152       numa_node match {
   153         case None => info.options
   154         case Some(n) => info.options.string("ML_process_policy") = NUMA.policy(n)
   155       }
   156 
   157     private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
   158     try { isabelle.graphview.Graph_File.write(options, graph_file, session_graph) }
   159     catch { case ERROR(_) => /*error should be exposed in ML*/ }
   160 
   161     private val future_result: Future[Process_Result] =
   162       Future.thread("build") {
   163         val parent = info.parent.getOrElse("")
   164 
   165         val args_yxml =
   166           YXML.string_of_body(
   167             {
   168               val theories = info.theories.map(x => (x._2, x._3))
   169               import XML.Encode._
   170               pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
   171                 pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
   172                 pair(string, pair(string, pair(string, pair(Path.encode,
   173                 list(pair(Options.encode, list(Path.encode))))))))))))))(
   174               (Symbol.codes, (command_timings, (do_output, (verbose,
   175                 (store.browser_info, (info.document_files, (File.standard_path(graph_file),
   176                 (parent, (info.chapter, (name, (Path.current,
   177                 theories))))))))))))
   178             })
   179 
   180         val env =
   181           Isabelle_System.settings() +
   182             ("ISABELLE_ML_DEBUGGER" -> options.bool("ML_debugger").toString)
   183 
   184         def save_heap: String =
   185           "ML_Heap.share_common_data (); ML_Heap.save_child " +
   186             ML_Syntax.print_string0(File.platform_path(output))
   187 
   188         if (pide) {
   189           error("FIXME")
   190         }
   191         else {
   192           val args_file = Isabelle_System.tmp_file("build")
   193           File.write(args_file, args_yxml)
   194 
   195           val eval =
   196             "Command_Line.tool0 (fn () => (" +
   197             "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
   198             (if (do_output) "; " + save_heap else "") + "));"
   199 
   200           val process =
   201             if (Sessions.pure_name(name)) {
   202               ML_Process(options, raw_ml_system = true, cwd = info.dir.file,
   203                 args =
   204                   (for ((root, _) <- Thy_Header.ml_roots) yield List("--use", root)).flatten :::
   205                   List("--eval", eval),
   206                 env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   207             }
   208             else {
   209               ML_Process(options, parent, List("--eval", eval), cwd = info.dir.file,
   210                 env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   211             }
   212 
   213           process.result(
   214             progress_stdout = (line: String) =>
   215               Library.try_unprefix("\floading_theory = ", line) match {
   216                 case Some(theory) => progress.theory(name, theory)
   217                 case None =>
   218               },
   219             progress_limit =
   220               options.int("process_output_limit") match {
   221                 case 0 => None
   222                 case m => Some(m * 1000000L)
   223               },
   224             strict = false)
   225         }
   226       }
   227 
   228     def terminate: Unit = future_result.cancel
   229     def is_finished: Boolean = future_result.is_finished
   230 
   231     @volatile private var was_timeout = false
   232     private val timeout_request: Option[Event_Timer.Request] =
   233     {
   234       if (info.timeout > Time.zero)
   235         Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
   236       else None
   237     }
   238 
   239     def join: Process_Result =
   240     {
   241       val result = future_result.join
   242 
   243       if (result.ok)
   244         Present.finish(progress, store.browser_info, graph_file, info, name)
   245 
   246       graph_file.delete
   247       timeout_request.foreach(_.cancel)
   248 
   249       if (result.interrupted) {
   250         if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
   251         else result.error(Output.error_text("Interrupt"))
   252       }
   253       else result
   254     }
   255   }
   256 
   257 
   258 
   259   /** build with results **/
   260 
   261   class Results private[Build](results: Map[String, (Option[Process_Result], Sessions.Info)])
   262   {
   263     def sessions: Set[String] = results.keySet
   264     def cancelled(name: String): Boolean = results(name)._1.isEmpty
   265     def apply(name: String): Process_Result = results(name)._1.getOrElse(Process_Result(1))
   266     def info(name: String): Sessions.Info = results(name)._2
   267     val rc =
   268       (0 /: results.iterator.map(
   269         { case (_, (Some(r), _)) => r.rc case (_, (None, _)) => 1 }))(_ max _)
   270     def ok: Boolean = rc == 0
   271 
   272     override def toString: String = rc.toString
   273   }
   274 
   275   def build(
   276     options: Options,
   277     progress: Progress = No_Progress,
   278     build_heap: Boolean = false,
   279     clean_build: Boolean = false,
   280     dirs: List[Path] = Nil,
   281     select_dirs: List[Path] = Nil,
   282     numa_shuffling: Boolean = false,
   283     max_jobs: Int = 1,
   284     list_files: Boolean = false,
   285     check_keywords: Set[String] = Set.empty,
   286     no_build: Boolean = false,
   287     system_mode: Boolean = false,
   288     verbose: Boolean = false,
   289     pide: Boolean = false,
   290     requirements: Boolean = false,
   291     all_sessions: Boolean = false,
   292     exclude_session_groups: List[String] = Nil,
   293     exclude_sessions: List[String] = Nil,
   294     session_groups: List[String] = Nil,
   295     sessions: List[String] = Nil): Results =
   296   {
   297     build_selection(
   298       options = options,
   299       progress = progress,
   300       build_heap = build_heap,
   301       clean_build = clean_build,
   302       dirs = dirs,
   303       select_dirs = select_dirs,
   304       numa_shuffling = numa_shuffling,
   305       max_jobs = max_jobs,
   306       list_files = list_files,
   307       check_keywords = check_keywords,
   308       no_build = no_build,
   309       system_mode = system_mode,
   310       verbose = verbose,
   311       pide = pide,
   312       selection = { full_tree =>
   313         full_tree.selection(requirements, all_sessions,
   314           exclude_session_groups, exclude_sessions, session_groups, sessions) })
   315   }
   316 
   317   def build_selection(
   318     options: Options,
   319     progress: Progress = No_Progress,
   320     build_heap: Boolean = false,
   321     clean_build: Boolean = false,
   322     dirs: List[Path] = Nil,
   323     select_dirs: List[Path] = Nil,
   324     numa_shuffling: Boolean = false,
   325     max_jobs: Int = 1,
   326     list_files: Boolean = false,
   327     check_keywords: Set[String] = Set.empty,
   328     no_build: Boolean = false,
   329     system_mode: Boolean = false,
   330     verbose: Boolean = false,
   331     pide: Boolean = false,
   332     selection: Sessions.Tree => (List[String], Sessions.Tree) =
   333       (_.selection(all_sessions = true))): Results =
   334   {
   335     /* session selection and dependencies */
   336 
   337     val build_options = options.int.update("completion_limit", 0).bool.update("ML_statistics", true)
   338     val full_tree = Sessions.load(build_options, dirs, select_dirs)
   339     val (selected, selected_tree) = selection(full_tree)
   340     val deps =
   341       Sessions.dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
   342 
   343     def sources_stamp(name: String): List[String] =
   344       (selected_tree(name).meta_digest :: deps.sources(name)).map(_.toString).sorted
   345 
   346 
   347     /* main build process */
   348 
   349     val store = Sessions.store(system_mode)
   350     val queue = Queue(selected_tree, store)
   351 
   352     store.prepare_output()
   353 
   354     // optional cleanup
   355     if (clean_build) {
   356       for (name <- full_tree.graph.all_succs(selected)) {
   357         val files =
   358           List(Path.basic(name), store.database(name), store.log(name), store.log_gz(name)).
   359             map(store.output_dir + _).filter(_.is_file)
   360         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   361         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   362       }
   363     }
   364 
   365     // scheduler loop
   366     case class Result(
   367       current: Boolean, heap_stamp: Option[String],
   368       process: Option[Process_Result], info: Sessions.Info)
   369     {
   370       def ok: Boolean =
   371         process match {
   372           case None => false
   373           case Some(res) => res.rc == 0
   374         }
   375     }
   376 
   377     def sleep()
   378     {
   379       try { Thread.sleep(500) }
   380       catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
   381     }
   382 
   383     val numa_nodes = new NUMA.Nodes(numa_shuffling)
   384 
   385     @tailrec def loop(
   386       pending: Queue,
   387       running: Map[String, (List[String], Job)],
   388       results: Map[String, Result]): Map[String, Result] =
   389     {
   390       def used_node(i: Int): Boolean =
   391         running.iterator.exists(
   392           { case (_, (_, job)) => job.numa_node.isDefined && job.numa_node.get == i })
   393 
   394       if (pending.is_empty) results
   395       else {
   396         if (progress.stopped)
   397           for ((_, (_, job)) <- running) job.terminate
   398 
   399         running.find({ case (_, (_, job)) => job.is_finished }) match {
   400           case Some((name, (input_heaps, job))) =>
   401             //{{{ finish job
   402 
   403             val process_result = job.join
   404             process_result.err_lines.foreach(progress.echo(_))
   405             if (process_result.ok)
   406               progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
   407 
   408             val log_lines = process_result.out_lines.filterNot(_.startsWith("\f"))
   409             val process_result_tail =
   410             {
   411               val tail = job.info.options.int("process_output_tail")
   412               process_result.copy(
   413                 out_lines =
   414                   "(see also " + (store.output_dir + store.log(name)).file.toString + ")" ::
   415                   (if (tail == 0) log_lines else log_lines.drop(log_lines.length - tail max 0)))
   416             }
   417 
   418             val heap_stamp =
   419               if (process_result.ok) {
   420                 (store.output_dir + store.log(name)).file.delete
   421                 val heap_stamp =
   422                   for (path <- job.output_path if path.is_file)
   423                     yield Sessions.write_heap_digest(path)
   424 
   425                 File.write_gzip(store.output_dir + store.log_gz(name), terminate_lines(log_lines))
   426 
   427                 heap_stamp
   428               }
   429               else {
   430                 (store.output_dir + Path.basic(name)).file.delete
   431                 (store.output_dir + store.log_gz(name)).file.delete
   432 
   433                 File.write(store.output_dir + store.log(name), terminate_lines(log_lines))
   434                 progress.echo(name + " FAILED")
   435                 if (!process_result.interrupted) progress.echo(process_result_tail.out)
   436 
   437                 None
   438               }
   439 
   440             // write database
   441             {
   442               val database = store.output_dir + store.database(name)
   443               database.file.delete
   444 
   445               using(SQLite.open_database(database))(db =>
   446                 store.write_session_info(db,
   447                   build_log =
   448                     Build_Log.Log_File(name, process_result.out_lines).
   449                       parse_session_info(name,
   450                         command_timings = true, ml_statistics = true, task_statistics = true),
   451                   build =
   452                     Session_Info(sources_stamp(name), input_heaps, heap_stamp, process_result.rc)))
   453             }
   454 
   455             loop(pending - name, running - name,
   456               results + (name -> Result(false, heap_stamp, Some(process_result_tail), job.info)))
   457             //}}}
   458           case None if running.size < (max_jobs max 1) =>
   459             //{{{ check/start next job
   460             pending.dequeue(running.isDefinedAt(_)) match {
   461               case Some((name, info)) =>
   462                 val ancestor_results = selected_tree.ancestors(name).map(results(_))
   463                 val ancestor_heaps = ancestor_results.flatMap(_.heap_stamp)
   464 
   465                 val do_output = build_heap || Sessions.pure_name(name) || queue.is_inner(name)
   466 
   467                 val (current, heap_stamp) =
   468                 {
   469                   store.find_database_heap(name) match {
   470                     case Some((database, heap_stamp)) =>
   471                       using(SQLite.open_database(database))(store.read_build(_)) match {
   472                         case Some(build) =>
   473                           val current =
   474                             build.sources == sources_stamp(name) &&
   475                             build.input_heaps == ancestor_heaps &&
   476                             build.output_heap == heap_stamp &&
   477                             !(do_output && heap_stamp.isEmpty) &&
   478                             build.return_code == 0
   479                           (current, heap_stamp)
   480                         case None => (false, None)
   481                       }
   482                     case None => (false, None)
   483                   }
   484                 }
   485                 val all_current = current && ancestor_results.forall(_.current)
   486 
   487                 if (all_current)
   488                   loop(pending - name, running,
   489                     results + (name -> Result(true, heap_stamp, Some(Process_Result(0)), info)))
   490                 else if (no_build) {
   491                   if (verbose) progress.echo("Skipping " + name + " ...")
   492                   loop(pending - name, running,
   493                     results + (name -> Result(false, heap_stamp, Some(Process_Result(1)), info)))
   494                 }
   495                 else if (ancestor_results.forall(_.ok) && !progress.stopped) {
   496                   val numa_node = numa_nodes.next(used_node(_))
   497                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   498                   val job =
   499                     new Job(progress, name, info, selected_tree, store, do_output, verbose,
   500                       pide, numa_node, deps(name).session_graph, queue.command_timings(name))
   501                   loop(pending, running + (name -> (ancestor_heaps, job)), results)
   502                 }
   503                 else {
   504                   progress.echo(name + " CANCELLED")
   505                   loop(pending - name, running,
   506                     results + (name -> Result(false, heap_stamp, None, info)))
   507                 }
   508               case None => sleep(); loop(pending, running, results)
   509             }
   510             ///}}}
   511           case None => sleep(); loop(pending, running, results)
   512         }
   513       }
   514     }
   515 
   516 
   517     /* build results */
   518 
   519     val results0 =
   520       if (deps.is_empty) {
   521         progress.echo(Output.warning_text("Nothing to build"))
   522         Map.empty[String, Result]
   523       }
   524       else loop(queue, Map.empty, Map.empty)
   525 
   526     val results =
   527       new Results(
   528         (for ((name, result) <- results0.iterator)
   529           yield (name, (result.process, result.info))).toMap)
   530 
   531     if (results.rc != 0 && (verbose || !no_build)) {
   532       val unfinished =
   533         (for {
   534           name <- results.sessions.iterator
   535           if !results(name).ok
   536          } yield name).toList.sorted
   537       progress.echo("Unfinished session(s): " + commas(unfinished))
   538     }
   539 
   540 
   541     /* global browser info */
   542 
   543     if (!no_build) {
   544       val browser_chapters =
   545         (for {
   546           (name, result) <- results0.iterator
   547           if result.ok
   548           info = full_tree(name)
   549           if info.options.bool("browser_info")
   550         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   551             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   552 
   553       for ((chapter, entries) <- browser_chapters)
   554         Present.update_chapter_index(store.browser_info, chapter, entries)
   555 
   556       if (browser_chapters.nonEmpty) Present.make_global_index(store.browser_info)
   557     }
   558 
   559     results
   560   }
   561 
   562 
   563   /* Isabelle tool wrapper */
   564 
   565   val isabelle_tool = Isabelle_Tool("build", "build and manage Isabelle sessions", args =>
   566   {
   567     val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
   568 
   569     var select_dirs: List[Path] = Nil
   570     var numa_shuffling = false
   571     var pide = false
   572     var requirements = false
   573     var exclude_session_groups: List[String] = Nil
   574     var all_sessions = false
   575     var build_heap = false
   576     var clean_build = false
   577     var dirs: List[Path] = Nil
   578     var session_groups: List[String] = Nil
   579     var max_jobs = 1
   580     var check_keywords: Set[String] = Set.empty
   581     var list_files = false
   582     var no_build = false
   583     var options = (Options.init() /: build_options)(_ + _)
   584     var system_mode = false
   585     var verbose = false
   586     var exclude_sessions: List[String] = Nil
   587 
   588     val getopts = Getopts("""
   589 Usage: isabelle build [OPTIONS] [SESSIONS ...]
   590 
   591   Options are:
   592     -D DIR       include session directory and select its sessions
   593     -N           cyclic shuffling of NUMA CPU nodes (performance tuning)
   594     -P           build via PIDE protocol
   595     -R           operate on requirements of selected sessions
   596     -X NAME      exclude sessions from group NAME and all descendants
   597     -a           select all sessions
   598     -b           build heap images
   599     -c           clean build
   600     -d DIR       include session directory
   601     -g NAME      select session group NAME
   602     -j INT       maximum number of parallel jobs (default 1)
   603     -k KEYWORD   check theory sources for conflicts with proposed keywords
   604     -l           list session source files
   605     -n           no build -- test dependencies only
   606     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   607     -s           system build mode: produce output in ISABELLE_HOME
   608     -v           verbose
   609     -x NAME      exclude session NAME and all descendants
   610 
   611   Build and manage Isabelle sessions, depending on implicit settings:
   612 
   613 """ + Library.prefix_lines("  ", Build_Log.Settings.show()) + "\n",
   614       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   615       "N" -> (_ => numa_shuffling = true),
   616       "P" -> (_ => pide = true),
   617       "R" -> (_ => requirements = true),
   618       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   619       "a" -> (_ => all_sessions = true),
   620       "b" -> (_ => build_heap = true),
   621       "c" -> (_ => clean_build = true),
   622       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   623       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   624       "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
   625       "k:" -> (arg => check_keywords = check_keywords + arg),
   626       "l" -> (_ => list_files = true),
   627       "n" -> (_ => no_build = true),
   628       "o:" -> (arg => options = options + arg),
   629       "s" -> (_ => system_mode = true),
   630       "v" -> (_ => verbose = true),
   631       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   632 
   633     val sessions = getopts(args)
   634 
   635     val progress = new Console_Progress(verbose = verbose)
   636 
   637     val start_date = Date.now()
   638 
   639     if (verbose) {
   640       progress.echo(
   641         "Started at " + Build_Log.print_date(start_date) +
   642           " (" + Isabelle_System.getenv("ML_IDENTIFIER") + " on " + Isabelle_System.hostname() +")")
   643       progress.echo(Build_Log.Settings.show() + "\n")
   644     }
   645 
   646     val results =
   647       progress.interrupt_handler {
   648         build(options, progress,
   649           build_heap = build_heap,
   650           clean_build = clean_build,
   651           dirs = dirs,
   652           select_dirs = select_dirs,
   653           numa_shuffling = NUMA.enabled_warning(numa_shuffling),
   654           max_jobs = max_jobs,
   655           list_files = list_files,
   656           check_keywords = check_keywords,
   657           no_build = no_build,
   658           system_mode = system_mode,
   659           verbose = verbose,
   660           pide = pide,
   661           requirements = requirements,
   662           all_sessions = all_sessions,
   663           exclude_session_groups = exclude_session_groups,
   664           exclude_sessions = exclude_sessions,
   665           session_groups = session_groups,
   666           sessions = sessions)
   667       }
   668     val end_date = Date.now()
   669     val elapsed_time = end_date.time - start_date.time
   670 
   671     if (verbose) {
   672       progress.echo("\nFinished at " + Build_Log.print_date(end_date))
   673     }
   674 
   675     val total_timing =
   676       (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
   677         copy(elapsed = elapsed_time)
   678     progress.echo(total_timing.message_resources)
   679 
   680     sys.exit(results.rc)
   681   })
   682 
   683 
   684   /* PIDE protocol */
   685 
   686   def build_theories(
   687     session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   688       session.get_protocol_handler(classOf[Handler].getName) match {
   689         case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
   690         case _ => error("Cannot invoke build_theories: bad protocol handler")
   691       }
   692 
   693   class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
   694   {
   695     private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
   696 
   697     override def exit(): Unit =
   698       pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
   699 
   700     def build_theories(
   701       session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   702     {
   703       val promise = Future.promise[XML.Body]
   704       val id = Document_ID.make().toString
   705       pending.change(promises => promises + (id -> promise))
   706       session.build_theories(id, master_dir, theories)
   707       promise
   708     }
   709 
   710     private def loading_theory(msg: Prover.Protocol_Output): Boolean =
   711       msg.properties match {
   712         case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
   713         case _ => false
   714       }
   715 
   716     private def build_theories_result(msg: Prover.Protocol_Output): Boolean =
   717       msg.properties match {
   718         case Markup.Build_Theories_Result(id) =>
   719           pending.change_result(promises =>
   720             promises.get(id) match {
   721               case Some(promise) =>
   722                 val error_message =
   723                   try { YXML.parse_body(Symbol.decode(msg.text)) }
   724                   catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
   725                 promise.fulfill(error_message)
   726                 (true, promises - id)
   727               case None =>
   728                 (false, promises)
   729             })
   730         case _ => false
   731       }
   732 
   733     val functions =
   734       List(
   735         Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
   736         Markup.LOADING_THEORY -> loading_theory _)
   737   }
   738 }