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