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