src/Pure/Tools/build.scala
author wenzelm
Mon Jan 09 20:47:45 2017 +0100 (2017-01-09)
changeset 64856 5e9bf964510a
parent 64855 8fcc23e8e1d9
child 64909 8007f10195af
permissions -rw-r--r--
clarified modules;
tuned;
     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   /* source dependencies and static content */
    97 
    98   sealed case class Deps(deps: Map[String, Sessions.Base])
    99   {
   100     def is_empty: Boolean = deps.isEmpty
   101     def apply(name: String): Sessions.Base = deps(name)
   102     def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
   103   }
   104 
   105   def dependencies(
   106       progress: Progress = Ignore_Progress,
   107       inlined_files: Boolean = false,
   108       verbose: Boolean = false,
   109       list_files: Boolean = false,
   110       check_keywords: Set[String] = Set.empty,
   111       tree: Sessions.Tree): Deps =
   112     Deps((Map.empty[String, Sessions.Base] /: tree.topological_order)(
   113       { case (deps, (name, info)) =>
   114           if (progress.stopped) throw Exn.Interrupt()
   115 
   116           try {
   117             val resources =
   118               new Resources(
   119                 info.parent match {
   120                   case None => Sessions.Base.bootstrap
   121                   case Some(parent) => deps(parent)
   122                 })
   123 
   124             if (verbose || list_files) {
   125               val groups =
   126                 if (info.groups.isEmpty) ""
   127                 else info.groups.mkString(" (", " ", ")")
   128               progress.echo("Session " + info.chapter + "/" + name + groups)
   129             }
   130 
   131             val thy_deps =
   132             {
   133               val root_theories =
   134                 info.theories.flatMap({
   135                   case (global, _, thys) =>
   136                     thys.map(thy =>
   137                       (resources.node_name(
   138                         if (global) "" else name, info.dir + Resources.thy_path(thy)), info.pos))
   139                 })
   140               val thy_deps = resources.thy_info.dependencies(name, root_theories)
   141 
   142               thy_deps.errors match {
   143                 case Nil => thy_deps
   144                 case errs => error(cat_lines(errs))
   145               }
   146             }
   147 
   148             val known_theories =
   149               (resources.base.known_theories /: thy_deps.deps)({ case (known, dep) =>
   150                 val name = dep.name
   151                 known.get(name.theory) match {
   152                   case Some(name1) if name != name1 =>
   153                     error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
   154                   case _ =>
   155                     known + (name.theory -> name) + (Long_Name.base_name(name.theory) -> name)
   156                 }
   157               })
   158 
   159             val loaded_theories = thy_deps.loaded_theories
   160             val keywords = thy_deps.keywords
   161             val syntax = thy_deps.syntax
   162 
   163             val theory_files = thy_deps.deps.map(dep => Path.explode(dep.name.node))
   164             val loaded_files =
   165               if (inlined_files) {
   166                 val pure_files =
   167                   if (Sessions.pure_name(name)) Sessions.pure_files(resources, syntax, info.dir)
   168                   else Nil
   169                 pure_files ::: thy_deps.loaded_files
   170               }
   171               else Nil
   172 
   173             val all_files =
   174               (theory_files ::: loaded_files :::
   175                 info.files.map(file => info.dir + file) :::
   176                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   177 
   178             if (list_files)
   179               progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
   180 
   181             if (check_keywords.nonEmpty)
   182               Check_Keywords.check_keywords(progress, syntax.keywords, check_keywords, theory_files)
   183 
   184             val sources = all_files.map(p => (p, SHA1.digest(p.file)))
   185 
   186             val session_graph =
   187               Present.session_graph(info.parent getOrElse "",
   188                 resources.base.loaded_theories, thy_deps.deps)
   189 
   190             val base =
   191               Sessions.Base(
   192                 loaded_theories, known_theories, keywords, syntax, sources, session_graph)
   193             deps + (name -> base)
   194           }
   195           catch {
   196             case ERROR(msg) =>
   197               cat_error(msg, "The error(s) above occurred in session " +
   198                 quote(name) + Position.here(info.pos))
   199           }
   200       }))
   201 
   202   def session_dependencies(
   203     options: Options,
   204     inlined_files: Boolean,
   205     dirs: List[Path],
   206     sessions: List[String]): Deps =
   207   {
   208     val (_, tree) = Sessions.load(options, dirs = dirs).selection(sessions = sessions)
   209     dependencies(inlined_files = inlined_files, tree = tree)
   210   }
   211 
   212   def session_base(
   213     options: Options,
   214     inlined_files: Boolean,
   215     dirs: List[Path],
   216     session: String): Sessions.Base =
   217   {
   218     session_dependencies(options, inlined_files, dirs, List(session))(session)
   219   }
   220 
   221   def outer_syntax(options: Options, dirs: List[Path], session: String): Outer_Syntax =
   222     session_base(options, false, dirs, session).syntax
   223 
   224 
   225   /* jobs */
   226 
   227   private class Job(progress: Progress, name: String, val info: Sessions.Info, tree: Sessions.Tree,
   228     store: Sessions.Store, do_output: Boolean, verbose: Boolean, val numa_node: Option[Int],
   229     session_graph: Graph_Display.Graph, command_timings: List[Properties.T])
   230   {
   231     val output = store.output_dir + Path.basic(name)
   232     def output_path: Option[Path] = if (do_output) Some(output) else None
   233     def output_save_state: String =
   234       if (do_output) "ML_Heap.save_child " + ML_Syntax.print_string0(File.platform_path(output))
   235       else ""
   236     output.file.delete
   237 
   238     private val parent = info.parent.getOrElse("")
   239 
   240     private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
   241     try { isabelle.graphview.Graph_File.write(info.options, graph_file, session_graph) }
   242     catch { case ERROR(_) => /*error should be exposed in ML*/ }
   243 
   244     private val env =
   245       Isabelle_System.settings() +
   246         ("ISABELLE_ML_DEBUGGER" -> info.options.bool("ML_debugger").toString)
   247 
   248     private val future_result: Future[Process_Result] =
   249       Future.thread("build") {
   250         val args_file = Isabelle_System.tmp_file("build")
   251         File.write(args_file, YXML.string_of_body(
   252             {
   253               val theories = info.theories.map(x => (x._2, x._3))
   254               import XML.Encode._
   255               pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
   256                 pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
   257                 pair(string, pair(string, pair(string,
   258                 list(pair(Options.encode, list(Path.encode)))))))))))))(
   259               (Symbol.codes, (command_timings, (do_output, (verbose,
   260                 (store.browser_info, (info.document_files, (File.standard_path(graph_file),
   261                 (parent, (info.chapter, (name,
   262                 theories)))))))))))
   263             }))
   264 
   265         val eval =
   266           "Command_Line.tool0 (fn () => (" +
   267           "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
   268           (if (do_output) "; ML_Heap.share_common_data (); " + output_save_state
   269            else "") + "));"
   270 
   271         val process_options =
   272           numa_node match {
   273             case None => info.options
   274             case Some(n) => info.options.string("ML_process_policy") = NUMA.policy(n)
   275           }
   276         val process =
   277           if (Sessions.pure_name(name)) {
   278             ML_Process(process_options, raw_ml_system = true, cwd = info.dir.file,
   279               args =
   280                 (for ((root, _) <- Thy_Header.ml_roots) yield List("--use", root)).flatten :::
   281                 List("--eval", eval),
   282               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   283           }
   284           else {
   285             ML_Process(process_options, parent, List("--eval", eval), cwd = info.dir.file,
   286               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   287           }
   288 
   289         process.result(
   290           progress_stdout = (line: String) =>
   291             Library.try_unprefix("\floading_theory = ", line) match {
   292               case Some(theory) => progress.theory(name, theory)
   293               case None =>
   294             },
   295           progress_limit =
   296             info.options.int("process_output_limit") match {
   297               case 0 => None
   298               case m => Some(m * 1000000L)
   299             },
   300           strict = false)
   301       }
   302 
   303     def terminate: Unit = future_result.cancel
   304     def is_finished: Boolean = future_result.is_finished
   305 
   306     @volatile private var was_timeout = false
   307     private val timeout_request: Option[Event_Timer.Request] =
   308     {
   309       if (info.timeout > Time.zero)
   310         Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
   311       else None
   312     }
   313 
   314     def join: Process_Result =
   315     {
   316       val result = future_result.join
   317 
   318       if (result.ok)
   319         Present.finish(progress, store.browser_info, graph_file, info, name)
   320 
   321       graph_file.delete
   322       timeout_request.foreach(_.cancel)
   323 
   324       if (result.interrupted) {
   325         if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
   326         else result.error(Output.error_text("Interrupt"))
   327       }
   328       else result
   329     }
   330   }
   331 
   332 
   333   /* sources and heaps */
   334 
   335   private val SOURCES = "sources: "
   336   private val INPUT_HEAP = "input_heap: "
   337   private val OUTPUT_HEAP = "output_heap: "
   338   private val LOG_START = "log:"
   339   private val line_prefixes = List(SOURCES, INPUT_HEAP, OUTPUT_HEAP, LOG_START)
   340 
   341   private def sources_stamp(digests: List[SHA1.Digest]): String =
   342     digests.map(_.toString).sorted.mkString(SOURCES, " ", "")
   343 
   344   private def read_stamps(path: Path): Option[(String, List[String], List[String])] =
   345     if (path.is_file) {
   346       val stream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(path.file)))
   347       val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
   348       val lines =
   349       {
   350         val lines = new mutable.ListBuffer[String]
   351         try {
   352           var finished = false
   353           while (!finished) {
   354             val line = reader.readLine
   355             if (line != null && line_prefixes.exists(line.startsWith(_)))
   356               lines += line
   357             else finished = true
   358           }
   359         }
   360         finally { reader.close }
   361         lines.toList
   362       }
   363 
   364       if (!lines.isEmpty && lines.last.startsWith(LOG_START)) {
   365         lines.find(_.startsWith(SOURCES)).map(s =>
   366           (s, lines.filter(_.startsWith(INPUT_HEAP)), lines.filter(_.startsWith(OUTPUT_HEAP))))
   367       }
   368       else None
   369     }
   370     else None
   371 
   372 
   373 
   374   /** build with results **/
   375 
   376   class Results private[Build](results: Map[String, (Option[Process_Result], Sessions.Info)])
   377   {
   378     def sessions: Set[String] = results.keySet
   379     def cancelled(name: String): Boolean = results(name)._1.isEmpty
   380     def apply(name: String): Process_Result = results(name)._1.getOrElse(Process_Result(1))
   381     def info(name: String): Sessions.Info = results(name)._2
   382     val rc = (0 /: results.iterator.map({ case (_, (Some(r), _)) => r.rc case (_, (None, _)) => 1 }))(_ max _)
   383     def ok: Boolean = rc == 0
   384 
   385     override def toString: String = rc.toString
   386   }
   387 
   388   def build(
   389     options: Options,
   390     progress: Progress = Ignore_Progress,
   391     build_heap: Boolean = false,
   392     clean_build: Boolean = false,
   393     dirs: List[Path] = Nil,
   394     select_dirs: List[Path] = Nil,
   395     numa_shuffling: Boolean = false,
   396     max_jobs: Int = 1,
   397     list_files: Boolean = false,
   398     check_keywords: Set[String] = Set.empty,
   399     no_build: Boolean = false,
   400     system_mode: Boolean = false,
   401     verbose: Boolean = false,
   402     requirements: Boolean = false,
   403     all_sessions: Boolean = false,
   404     exclude_session_groups: List[String] = Nil,
   405     exclude_sessions: List[String] = Nil,
   406     session_groups: List[String] = Nil,
   407     sessions: List[String] = Nil): Results =
   408   {
   409     build_selection(
   410       options = options,
   411       progress = progress,
   412       build_heap = build_heap,
   413       clean_build = clean_build,
   414       dirs = dirs,
   415       select_dirs = select_dirs,
   416       numa_shuffling = numa_shuffling,
   417       max_jobs = max_jobs,
   418       list_files = list_files,
   419       check_keywords = check_keywords,
   420       no_build = no_build,
   421       system_mode = system_mode,
   422       verbose = verbose,
   423       selection = { full_tree =>
   424         full_tree.selection(requirements, all_sessions,
   425           exclude_session_groups, exclude_sessions, session_groups, sessions) })
   426   }
   427 
   428   def build_selection(
   429     options: Options,
   430     progress: Progress = Ignore_Progress,
   431     build_heap: Boolean = false,
   432     clean_build: Boolean = false,
   433     dirs: List[Path] = Nil,
   434     select_dirs: List[Path] = Nil,
   435     numa_shuffling: Boolean = false,
   436     max_jobs: Int = 1,
   437     list_files: Boolean = false,
   438     check_keywords: Set[String] = Set.empty,
   439     no_build: Boolean = false,
   440     system_mode: Boolean = false,
   441     verbose: Boolean = false,
   442     selection: Sessions.Tree => (List[String], Sessions.Tree) =
   443       (_.selection(all_sessions = true))): Results =
   444   {
   445     /* session selection and dependencies */
   446 
   447     val build_options = options.int.update("completion_limit", 0).bool.update("ML_statistics", true)
   448     val full_tree = Sessions.load(build_options, dirs, select_dirs)
   449     val (selected, selected_tree) = selection(full_tree)
   450     val deps = dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
   451 
   452     def session_sources_stamp(name: String): String =
   453       sources_stamp(selected_tree(name).meta_digest :: deps.sources(name))
   454 
   455     val store = Sessions.store(system_mode)
   456 
   457 
   458     /* queue with scheduling information */
   459 
   460     def load_timings(name: String): (List[Properties.T], Double) =
   461     {
   462       val (path, text) =
   463         store.find_log_gz(name) match {
   464           case Some(path) => (path, File.read_gzip(path))
   465           case None =>
   466             store.find_log(name) match {
   467               case Some(path) => (path, File.read(path))
   468               case None => (Path.current, "")
   469             }
   470         }
   471 
   472       def ignore_error(msg: String): (List[Properties.T], Double) =
   473       {
   474         Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
   475         (Nil, 0.0)
   476       }
   477 
   478       try {
   479         val info = Build_Log.Log_File(name, text).parse_session_info(name, command_timings = true)
   480         val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
   481         (info.command_timings, session_timing)
   482       }
   483       catch {
   484         case ERROR(msg) => ignore_error(msg)
   485         case exn: java.lang.Error => ignore_error(Exn.message(exn))
   486         case _: XML.Error => ignore_error("")
   487       }
   488     }
   489 
   490     val queue = Queue(selected_tree, load_timings)
   491 
   492 
   493     /* main build process */
   494 
   495     store.prepare_output()
   496 
   497     // optional cleanup
   498     if (clean_build) {
   499       for (name <- full_tree.graph.all_succs(selected)) {
   500         val files =
   501           List(Path.basic(name), Sessions.log(name), Sessions.log_gz(name)).
   502             map(store.output_dir + _).filter(_.is_file)
   503         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   504         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   505       }
   506     }
   507 
   508     // scheduler loop
   509     case class Result(
   510       current: Boolean, heap_stamp: Option[String],
   511       process: Option[Process_Result], info: Sessions.Info)
   512     {
   513       def ok: Boolean =
   514         process match {
   515           case None => false
   516           case Some(res) => res.rc == 0
   517         }
   518     }
   519 
   520     def sleep()
   521     {
   522       try { Thread.sleep(500) }
   523       catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
   524     }
   525 
   526     val numa_nodes = new NUMA.Nodes(numa_shuffling)
   527 
   528     @tailrec def loop(
   529       pending: Queue,
   530       running: Map[String, (List[String], Job)],
   531       results: Map[String, Result]): Map[String, Result] =
   532     {
   533       def used_node(i: Int): Boolean =
   534         running.iterator.exists(
   535           { case (_, (_, job)) => job.numa_node.isDefined && job.numa_node.get == i })
   536 
   537       if (pending.is_empty) results
   538       else {
   539         if (progress.stopped)
   540           for ((_, (_, job)) <- running) job.terminate
   541 
   542         running.find({ case (_, (_, job)) => job.is_finished }) match {
   543           case Some((name, (input_heaps, job))) =>
   544             //{{{ finish job
   545 
   546             val process_result = job.join
   547             process_result.err_lines.foreach(progress.echo(_))
   548             if (process_result.ok)
   549               progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
   550 
   551             val process_result_tail =
   552             {
   553               val lines = process_result.out_lines.filterNot(_.startsWith("\f"))
   554               val tail = job.info.options.int("process_output_tail")
   555               val lines1 = if (tail == 0) lines else lines.drop(lines.length - tail max 0)
   556               process_result.copy(
   557                 out_lines =
   558                   "(see also " + (store.output_dir + Sessions.log(name)).file.toString + ")" ::
   559                   lines1)
   560             }
   561 
   562             val heap_stamp =
   563               if (process_result.ok) {
   564                 (store.output_dir + Sessions.log(name)).file.delete
   565                 val heap_stamp =
   566                   for (path <- job.output_path if path.is_file)
   567                     yield Sessions.write_heap_digest(path)
   568 
   569                 File.write_gzip(store.output_dir + Sessions.log_gz(name),
   570                   terminate_lines(
   571                     session_sources_stamp(name) ::
   572                     input_heaps.map(INPUT_HEAP + _) :::
   573                     heap_stamp.toList.map(OUTPUT_HEAP + _) :::
   574                     List(LOG_START) ::: process_result.out_lines))
   575 
   576                 heap_stamp
   577               }
   578               else {
   579                 (store.output_dir + Path.basic(name)).file.delete
   580                 (store.output_dir + Sessions.log_gz(name)).file.delete
   581 
   582                 File.write(store.output_dir + Sessions.log(name),
   583                   terminate_lines(process_result.out_lines))
   584                 progress.echo(name + " FAILED")
   585                 if (!process_result.interrupted) progress.echo(process_result_tail.out)
   586 
   587                 None
   588               }
   589             loop(pending - name, running - name,
   590               results + (name -> Result(false, heap_stamp, Some(process_result_tail), job.info)))
   591             //}}}
   592           case None if running.size < (max_jobs max 1) =>
   593             //{{{ check/start next job
   594             pending.dequeue(running.isDefinedAt(_)) match {
   595               case Some((name, info)) =>
   596                 val ancestor_results = selected_tree.ancestors(name).map(results(_))
   597                 val ancestor_heaps = ancestor_results.flatMap(_.heap_stamp)
   598 
   599                 val do_output = build_heap || Sessions.pure_name(name) || queue.is_inner(name)
   600 
   601                 val (current, heap_stamp) =
   602                 {
   603                   store.find(name) match {
   604                     case Some((log_gz, heap_stamp)) =>
   605                       read_stamps(log_gz) match {
   606                         case Some((sources, input_heaps, output_heaps)) =>
   607                           val current =
   608                             sources == session_sources_stamp(name) &&
   609                             input_heaps == ancestor_heaps.map(INPUT_HEAP + _) &&
   610                             output_heaps == heap_stamp.toList.map(OUTPUT_HEAP + _) &&
   611                             !(do_output && heap_stamp.isEmpty)
   612                           (current, heap_stamp)
   613                         case None => (false, None)
   614                       }
   615                     case None => (false, None)
   616                   }
   617                 }
   618                 val all_current = current && ancestor_results.forall(_.current)
   619 
   620                 if (all_current)
   621                   loop(pending - name, running,
   622                     results + (name -> Result(true, heap_stamp, Some(Process_Result(0)), info)))
   623                 else if (no_build) {
   624                   if (verbose) progress.echo("Skipping " + name + " ...")
   625                   loop(pending - name, running,
   626                     results + (name -> Result(false, heap_stamp, Some(Process_Result(1)), info)))
   627                 }
   628                 else if (ancestor_results.forall(_.ok) && !progress.stopped) {
   629                   val numa_node = numa_nodes.next(used_node(_))
   630                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   631                   val job =
   632                     new Job(progress, name, info, selected_tree, store, do_output, verbose,
   633                       numa_node, deps(name).session_graph, queue.command_timings(name))
   634                   loop(pending, running + (name -> (ancestor_heaps, job)), results)
   635                 }
   636                 else {
   637                   progress.echo(name + " CANCELLED")
   638                   loop(pending - name, running, results + (name -> Result(false, heap_stamp, None, info)))
   639                 }
   640               case None => sleep(); loop(pending, running, results)
   641             }
   642             ///}}}
   643           case None => sleep(); loop(pending, running, results)
   644         }
   645       }
   646     }
   647 
   648 
   649     /* build results */
   650 
   651     val results0 =
   652       if (deps.is_empty) {
   653         progress.echo(Output.warning_text("Nothing to build"))
   654         Map.empty[String, Result]
   655       }
   656       else loop(queue, Map.empty, Map.empty)
   657 
   658     val results =
   659       new Results(
   660         (for ((name, result) <- results0.iterator)
   661           yield (name, (result.process, result.info))).toMap)
   662 
   663     if (results.rc != 0 && (verbose || !no_build)) {
   664       val unfinished =
   665         (for {
   666           name <- results.sessions.iterator
   667           if !results(name).ok
   668          } yield name).toList.sorted
   669       progress.echo("Unfinished session(s): " + commas(unfinished))
   670     }
   671 
   672 
   673     /* global browser info */
   674 
   675     if (!no_build) {
   676       val browser_chapters =
   677         (for {
   678           (name, result) <- results0.iterator
   679           if result.ok
   680           info = full_tree(name)
   681           if info.options.bool("browser_info")
   682         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   683             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   684 
   685       for ((chapter, entries) <- browser_chapters)
   686         Present.update_chapter_index(store.browser_info, chapter, entries)
   687 
   688       if (browser_chapters.nonEmpty) Present.make_global_index(store.browser_info)
   689     }
   690 
   691     results
   692   }
   693 
   694 
   695   /* Isabelle tool wrapper */
   696 
   697   val isabelle_tool = Isabelle_Tool("build", "build and manage Isabelle sessions", args =>
   698   {
   699     val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
   700 
   701     var select_dirs: List[Path] = Nil
   702     var numa_shuffling = false
   703     var requirements = false
   704     var exclude_session_groups: List[String] = Nil
   705     var all_sessions = false
   706     var build_heap = false
   707     var clean_build = false
   708     var dirs: List[Path] = Nil
   709     var session_groups: List[String] = Nil
   710     var max_jobs = 1
   711     var check_keywords: Set[String] = Set.empty
   712     var list_files = false
   713     var no_build = false
   714     var options = (Options.init() /: build_options)(_ + _)
   715     var system_mode = false
   716     var verbose = false
   717     var exclude_sessions: List[String] = Nil
   718 
   719     val getopts = Getopts("""
   720 Usage: isabelle build [OPTIONS] [SESSIONS ...]
   721 
   722   Options are:
   723     -D DIR       include session directory and select its sessions
   724     -N           cyclic shuffling of NUMA CPU nodes (performance tuning)
   725     -R           operate on requirements of selected sessions
   726     -X NAME      exclude sessions from group NAME and all descendants
   727     -a           select all sessions
   728     -b           build heap images
   729     -c           clean build
   730     -d DIR       include session directory
   731     -g NAME      select session group NAME
   732     -j INT       maximum number of parallel jobs (default 1)
   733     -k KEYWORD   check theory sources for conflicts with proposed keywords
   734     -l           list session source files
   735     -n           no build -- test dependencies only
   736     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   737     -s           system build mode: produce output in ISABELLE_HOME
   738     -v           verbose
   739     -x NAME      exclude session NAME and all descendants
   740 
   741   Build and manage Isabelle sessions, depending on implicit settings:
   742 
   743 """ + Library.prefix_lines("  ", Build_Log.Settings.show()) + "\n",
   744       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   745       "N" -> (_ => numa_shuffling = true),
   746       "R" -> (_ => requirements = true),
   747       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   748       "a" -> (_ => all_sessions = true),
   749       "b" -> (_ => build_heap = true),
   750       "c" -> (_ => clean_build = true),
   751       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   752       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   753       "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
   754       "k:" -> (arg => check_keywords = check_keywords + arg),
   755       "l" -> (_ => list_files = true),
   756       "n" -> (_ => no_build = true),
   757       "o:" -> (arg => options = options + arg),
   758       "s" -> (_ => system_mode = true),
   759       "v" -> (_ => verbose = true),
   760       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   761 
   762     val sessions = getopts(args)
   763 
   764     val progress = new Console_Progress(verbose = verbose)
   765 
   766     val start_date = Date.now()
   767 
   768     if (verbose) {
   769       progress.echo(
   770         "Started at " + Build_Log.print_date(start_date) +
   771           " (" + Isabelle_System.getenv("ML_IDENTIFIER") + " on " + Isabelle_System.hostname() +")")
   772       progress.echo(Build_Log.Settings.show() + "\n")
   773     }
   774 
   775     val results =
   776       progress.interrupt_handler {
   777         build(options, progress,
   778           build_heap = build_heap,
   779           clean_build = clean_build,
   780           dirs = dirs,
   781           select_dirs = select_dirs,
   782           numa_shuffling = NUMA.enabled_warning(numa_shuffling),
   783           max_jobs = max_jobs,
   784           list_files = list_files,
   785           check_keywords = check_keywords,
   786           no_build = no_build,
   787           system_mode = system_mode,
   788           verbose = verbose,
   789           requirements = requirements,
   790           all_sessions = all_sessions,
   791           exclude_session_groups = exclude_session_groups,
   792           exclude_sessions = exclude_sessions,
   793           session_groups = session_groups,
   794           sessions = sessions)
   795       }
   796     val end_date = Date.now()
   797     val elapsed_time = end_date.time - start_date.time
   798 
   799     if (verbose) {
   800       progress.echo("\nFinished at " + Build_Log.print_date(end_date))
   801     }
   802 
   803     val total_timing =
   804       (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
   805         copy(elapsed = elapsed_time)
   806     progress.echo(total_timing.message_resources)
   807 
   808     sys.exit(results.rc)
   809   })
   810 
   811 
   812   /* PIDE protocol */
   813 
   814   def build_theories(
   815     session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   816       session.get_protocol_handler(classOf[Handler].getName) match {
   817         case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
   818         case _ => error("Cannot invoke build_theories: bad protocol handler")
   819       }
   820 
   821   class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
   822   {
   823     private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
   824 
   825     def build_theories(
   826       session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   827     {
   828       val promise = Future.promise[XML.Body]
   829       val id = Document_ID.make().toString
   830       pending.change(promises => promises + (id -> promise))
   831       session.build_theories(id, master_dir, theories)
   832       promise
   833     }
   834 
   835     private def loading_theory(prover: Prover, msg: Prover.Protocol_Output): Boolean =
   836       msg.properties match {
   837         case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
   838         case _ => false
   839       }
   840 
   841     private def build_theories_result(prover: Prover, msg: Prover.Protocol_Output): Boolean =
   842       msg.properties match {
   843         case Markup.Build_Theories_Result(id) =>
   844           pending.change_result(promises =>
   845             promises.get(id) match {
   846               case Some(promise) =>
   847                 val error_message =
   848                   try { YXML.parse_body(Symbol.decode(msg.text)) }
   849                   catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
   850                 promise.fulfill(error_message)
   851                 (true, promises - id)
   852               case None =>
   853                 (false, promises)
   854             })
   855         case _ => false
   856       }
   857 
   858     override def stop(prover: Prover): Unit =
   859       pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
   860 
   861     val functions =
   862       Map(
   863         Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
   864         Markup.LOADING_THEORY -> loading_theory _)
   865   }
   866 }