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