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