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