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