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