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