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