src/Pure/Tools/build.scala
author wenzelm
Tue Mar 14 00:13:38 2017 +0100 (2017-03-14)
changeset 65220 420f55912b3e
parent 65219 ed4b47b8c7dc
child 65250 13a6c81534a8
permissions -rw-r--r--
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 = No_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_base(options: Options, session: String, dirs: List[Path] = Nil): Sessions.Base =
   203   {
   204     val (_, tree) = Sessions.load(options, dirs = dirs).selection(sessions = List(session))
   205     dependencies(tree = tree)(session)
   206   }
   207 
   208 
   209   /* jobs */
   210 
   211   private class Job(progress: Progress, name: String, val info: Sessions.Info, tree: Sessions.Tree,
   212     store: Sessions.Store, do_output: Boolean, verbose: Boolean, val numa_node: Option[Int],
   213     session_graph: Graph_Display.Graph, command_timings: List[Properties.T])
   214   {
   215     val output = store.output_dir + Path.basic(name)
   216     def output_path: Option[Path] = if (do_output) Some(output) else None
   217     def output_save_state: String =
   218       if (do_output) "ML_Heap.save_child " + ML_Syntax.print_string0(File.platform_path(output))
   219       else ""
   220     output.file.delete
   221 
   222     private val parent = info.parent.getOrElse("")
   223 
   224     private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
   225     try { isabelle.graphview.Graph_File.write(info.options, graph_file, session_graph) }
   226     catch { case ERROR(_) => /*error should be exposed in ML*/ }
   227 
   228     private val env =
   229       Isabelle_System.settings() +
   230         ("ISABELLE_ML_DEBUGGER" -> info.options.bool("ML_debugger").toString)
   231 
   232     private val future_result: Future[Process_Result] =
   233       Future.thread("build") {
   234         val args_file = Isabelle_System.tmp_file("build")
   235         File.write(args_file, YXML.string_of_body(
   236             {
   237               val theories = info.theories.map(x => (x._2, x._3))
   238               import XML.Encode._
   239               pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
   240                 pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
   241                 pair(string, pair(string, pair(string,
   242                 list(pair(Options.encode, list(Path.encode)))))))))))))(
   243               (Symbol.codes, (command_timings, (do_output, (verbose,
   244                 (store.browser_info, (info.document_files, (File.standard_path(graph_file),
   245                 (parent, (info.chapter, (name,
   246                 theories)))))))))))
   247             }))
   248 
   249         val eval =
   250           "Command_Line.tool0 (fn () => (" +
   251           "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
   252           (if (do_output) "; ML_Heap.share_common_data (); " + output_save_state
   253            else "") + "));"
   254 
   255         val process_options =
   256           numa_node match {
   257             case None => info.options
   258             case Some(n) => info.options.string("ML_process_policy") = NUMA.policy(n)
   259           }
   260         val process =
   261           if (Sessions.pure_name(name)) {
   262             ML_Process(process_options, raw_ml_system = true, cwd = info.dir.file,
   263               args =
   264                 (for ((root, _) <- Thy_Header.ml_roots) yield List("--use", root)).flatten :::
   265                 List("--eval", eval),
   266               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   267           }
   268           else {
   269             ML_Process(process_options, parent, List("--eval", eval), cwd = info.dir.file,
   270               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   271           }
   272 
   273         process.result(
   274           progress_stdout = (line: String) =>
   275             Library.try_unprefix("\floading_theory = ", line) match {
   276               case Some(theory) => progress.theory(name, theory)
   277               case None =>
   278             },
   279           progress_limit =
   280             info.options.int("process_output_limit") match {
   281               case 0 => None
   282               case m => Some(m * 1000000L)
   283             },
   284           strict = false)
   285       }
   286 
   287     def terminate: Unit = future_result.cancel
   288     def is_finished: Boolean = future_result.is_finished
   289 
   290     @volatile private var was_timeout = false
   291     private val timeout_request: Option[Event_Timer.Request] =
   292     {
   293       if (info.timeout > Time.zero)
   294         Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
   295       else None
   296     }
   297 
   298     def join: Process_Result =
   299     {
   300       val result = future_result.join
   301 
   302       if (result.ok)
   303         Present.finish(progress, store.browser_info, graph_file, info, name)
   304 
   305       graph_file.delete
   306       timeout_request.foreach(_.cancel)
   307 
   308       if (result.interrupted) {
   309         if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
   310         else result.error(Output.error_text("Interrupt"))
   311       }
   312       else result
   313     }
   314   }
   315 
   316 
   317   /* sources and heaps */
   318 
   319   private val SOURCES = "sources: "
   320   private val INPUT_HEAP = "input_heap: "
   321   private val OUTPUT_HEAP = "output_heap: "
   322   private val LOG_START = "log:"
   323   private val line_prefixes = List(SOURCES, INPUT_HEAP, OUTPUT_HEAP, LOG_START)
   324 
   325   private def sources_stamp(digests: List[SHA1.Digest]): String =
   326     digests.map(_.toString).sorted.mkString(SOURCES, " ", "")
   327 
   328   private def read_stamps(path: Path): Option[(String, List[String], List[String])] =
   329     if (path.is_file) {
   330       val stream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(path.file)))
   331       val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
   332       val lines =
   333       {
   334         val lines = new mutable.ListBuffer[String]
   335         try {
   336           var finished = false
   337           while (!finished) {
   338             val line = reader.readLine
   339             if (line != null && line_prefixes.exists(line.startsWith(_)))
   340               lines += line
   341             else finished = true
   342           }
   343         }
   344         finally { reader.close }
   345         lines.toList
   346       }
   347 
   348       if (!lines.isEmpty && lines.last.startsWith(LOG_START)) {
   349         lines.find(_.startsWith(SOURCES)).map(s =>
   350           (s, lines.filter(_.startsWith(INPUT_HEAP)), lines.filter(_.startsWith(OUTPUT_HEAP))))
   351       }
   352       else None
   353     }
   354     else None
   355 
   356 
   357 
   358   /** build with results **/
   359 
   360   class Results private[Build](results: Map[String, (Option[Process_Result], Sessions.Info)])
   361   {
   362     def sessions: Set[String] = results.keySet
   363     def cancelled(name: String): Boolean = results(name)._1.isEmpty
   364     def apply(name: String): Process_Result = results(name)._1.getOrElse(Process_Result(1))
   365     def info(name: String): Sessions.Info = results(name)._2
   366     val rc = (0 /: results.iterator.map({ case (_, (Some(r), _)) => r.rc case (_, (None, _)) => 1 }))(_ max _)
   367     def ok: Boolean = rc == 0
   368 
   369     override def toString: String = rc.toString
   370   }
   371 
   372   def build(
   373     options: Options,
   374     progress: Progress = No_Progress,
   375     build_heap: Boolean = false,
   376     clean_build: Boolean = false,
   377     dirs: List[Path] = Nil,
   378     select_dirs: List[Path] = Nil,
   379     numa_shuffling: Boolean = false,
   380     max_jobs: Int = 1,
   381     list_files: Boolean = false,
   382     check_keywords: Set[String] = Set.empty,
   383     no_build: Boolean = false,
   384     system_mode: Boolean = false,
   385     verbose: Boolean = false,
   386     requirements: Boolean = false,
   387     all_sessions: Boolean = false,
   388     exclude_session_groups: List[String] = Nil,
   389     exclude_sessions: List[String] = Nil,
   390     session_groups: List[String] = Nil,
   391     sessions: List[String] = Nil): Results =
   392   {
   393     build_selection(
   394       options = options,
   395       progress = progress,
   396       build_heap = build_heap,
   397       clean_build = clean_build,
   398       dirs = dirs,
   399       select_dirs = select_dirs,
   400       numa_shuffling = numa_shuffling,
   401       max_jobs = max_jobs,
   402       list_files = list_files,
   403       check_keywords = check_keywords,
   404       no_build = no_build,
   405       system_mode = system_mode,
   406       verbose = verbose,
   407       selection = { full_tree =>
   408         full_tree.selection(requirements, all_sessions,
   409           exclude_session_groups, exclude_sessions, session_groups, sessions) })
   410   }
   411 
   412   def build_selection(
   413     options: Options,
   414     progress: Progress = No_Progress,
   415     build_heap: Boolean = false,
   416     clean_build: Boolean = false,
   417     dirs: List[Path] = Nil,
   418     select_dirs: List[Path] = Nil,
   419     numa_shuffling: Boolean = false,
   420     max_jobs: Int = 1,
   421     list_files: Boolean = false,
   422     check_keywords: Set[String] = Set.empty,
   423     no_build: Boolean = false,
   424     system_mode: Boolean = false,
   425     verbose: Boolean = false,
   426     selection: Sessions.Tree => (List[String], Sessions.Tree) =
   427       (_.selection(all_sessions = true))): Results =
   428   {
   429     /* session selection and dependencies */
   430 
   431     val build_options = options.int.update("completion_limit", 0).bool.update("ML_statistics", true)
   432     val full_tree = Sessions.load(build_options, dirs, select_dirs)
   433     val (selected, selected_tree) = selection(full_tree)
   434     val deps = dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
   435 
   436     def session_sources_stamp(name: String): String =
   437       sources_stamp(selected_tree(name).meta_digest :: deps.sources(name))
   438 
   439     val store = Sessions.store(system_mode)
   440 
   441 
   442     /* queue with scheduling information */
   443 
   444     def load_timings(name: String): (List[Properties.T], Double) =
   445     {
   446       val (path, text) =
   447         store.find_log_gz(name) match {
   448           case Some(path) => (path, File.read_gzip(path))
   449           case None =>
   450             store.find_log(name) match {
   451               case Some(path) => (path, File.read(path))
   452               case None => (Path.current, "")
   453             }
   454         }
   455 
   456       def ignore_error(msg: String): (List[Properties.T], Double) =
   457       {
   458         Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
   459         (Nil, 0.0)
   460       }
   461 
   462       try {
   463         val info = Build_Log.Log_File(name, text).parse_session_info(name, command_timings = true)
   464         val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
   465         (info.command_timings, session_timing)
   466       }
   467       catch {
   468         case ERROR(msg) => ignore_error(msg)
   469         case exn: java.lang.Error => ignore_error(Exn.message(exn))
   470         case _: XML.Error => ignore_error("")
   471       }
   472     }
   473 
   474     val queue = Queue(selected_tree, load_timings)
   475 
   476 
   477     /* main build process */
   478 
   479     store.prepare_output()
   480 
   481     // optional cleanup
   482     if (clean_build) {
   483       for (name <- full_tree.graph.all_succs(selected)) {
   484         val files =
   485           List(Path.basic(name), Sessions.log(name), Sessions.log_gz(name)).
   486             map(store.output_dir + _).filter(_.is_file)
   487         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   488         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   489       }
   490     }
   491 
   492     // scheduler loop
   493     case class Result(
   494       current: Boolean, heap_stamp: Option[String],
   495       process: Option[Process_Result], info: Sessions.Info)
   496     {
   497       def ok: Boolean =
   498         process match {
   499           case None => false
   500           case Some(res) => res.rc == 0
   501         }
   502     }
   503 
   504     def sleep()
   505     {
   506       try { Thread.sleep(500) }
   507       catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
   508     }
   509 
   510     val numa_nodes = new NUMA.Nodes(numa_shuffling)
   511 
   512     @tailrec def loop(
   513       pending: Queue,
   514       running: Map[String, (List[String], Job)],
   515       results: Map[String, Result]): Map[String, Result] =
   516     {
   517       def used_node(i: Int): Boolean =
   518         running.iterator.exists(
   519           { case (_, (_, job)) => job.numa_node.isDefined && job.numa_node.get == i })
   520 
   521       if (pending.is_empty) results
   522       else {
   523         if (progress.stopped)
   524           for ((_, (_, job)) <- running) job.terminate
   525 
   526         running.find({ case (_, (_, job)) => job.is_finished }) match {
   527           case Some((name, (input_heaps, job))) =>
   528             //{{{ finish job
   529 
   530             val process_result = job.join
   531             process_result.err_lines.foreach(progress.echo(_))
   532             if (process_result.ok)
   533               progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
   534 
   535             val process_result_tail =
   536             {
   537               val lines = process_result.out_lines.filterNot(_.startsWith("\f"))
   538               val tail = job.info.options.int("process_output_tail")
   539               val lines1 = if (tail == 0) lines else lines.drop(lines.length - tail max 0)
   540               process_result.copy(
   541                 out_lines =
   542                   "(see also " + (store.output_dir + Sessions.log(name)).file.toString + ")" ::
   543                   lines1)
   544             }
   545 
   546             val heap_stamp =
   547               if (process_result.ok) {
   548                 (store.output_dir + Sessions.log(name)).file.delete
   549                 val heap_stamp =
   550                   for (path <- job.output_path if path.is_file)
   551                     yield Sessions.write_heap_digest(path)
   552 
   553                 File.write_gzip(store.output_dir + Sessions.log_gz(name),
   554                   terminate_lines(
   555                     session_sources_stamp(name) ::
   556                     input_heaps.map(INPUT_HEAP + _) :::
   557                     heap_stamp.toList.map(OUTPUT_HEAP + _) :::
   558                     List(LOG_START) ::: process_result.out_lines))
   559 
   560                 heap_stamp
   561               }
   562               else {
   563                 (store.output_dir + Path.basic(name)).file.delete
   564                 (store.output_dir + Sessions.log_gz(name)).file.delete
   565 
   566                 File.write(store.output_dir + Sessions.log(name),
   567                   terminate_lines(process_result.out_lines))
   568                 progress.echo(name + " FAILED")
   569                 if (!process_result.interrupted) progress.echo(process_result_tail.out)
   570 
   571                 None
   572               }
   573             loop(pending - name, running - name,
   574               results + (name -> Result(false, heap_stamp, Some(process_result_tail), job.info)))
   575             //}}}
   576           case None if running.size < (max_jobs max 1) =>
   577             //{{{ check/start next job
   578             pending.dequeue(running.isDefinedAt(_)) match {
   579               case Some((name, info)) =>
   580                 val ancestor_results = selected_tree.ancestors(name).map(results(_))
   581                 val ancestor_heaps = ancestor_results.flatMap(_.heap_stamp)
   582 
   583                 val do_output = build_heap || Sessions.pure_name(name) || queue.is_inner(name)
   584 
   585                 val (current, heap_stamp) =
   586                 {
   587                   store.find(name) match {
   588                     case Some((log_gz, heap_stamp)) =>
   589                       read_stamps(log_gz) match {
   590                         case Some((sources, input_heaps, output_heaps)) =>
   591                           val current =
   592                             sources == session_sources_stamp(name) &&
   593                             input_heaps == ancestor_heaps.map(INPUT_HEAP + _) &&
   594                             output_heaps == heap_stamp.toList.map(OUTPUT_HEAP + _) &&
   595                             !(do_output && heap_stamp.isEmpty)
   596                           (current, heap_stamp)
   597                         case None => (false, None)
   598                       }
   599                     case None => (false, None)
   600                   }
   601                 }
   602                 val all_current = current && ancestor_results.forall(_.current)
   603 
   604                 if (all_current)
   605                   loop(pending - name, running,
   606                     results + (name -> Result(true, heap_stamp, Some(Process_Result(0)), info)))
   607                 else if (no_build) {
   608                   if (verbose) progress.echo("Skipping " + name + " ...")
   609                   loop(pending - name, running,
   610                     results + (name -> Result(false, heap_stamp, Some(Process_Result(1)), info)))
   611                 }
   612                 else if (ancestor_results.forall(_.ok) && !progress.stopped) {
   613                   val numa_node = numa_nodes.next(used_node(_))
   614                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   615                   val job =
   616                     new Job(progress, name, info, selected_tree, store, do_output, verbose,
   617                       numa_node, deps(name).session_graph, queue.command_timings(name))
   618                   loop(pending, running + (name -> (ancestor_heaps, job)), results)
   619                 }
   620                 else {
   621                   progress.echo(name + " CANCELLED")
   622                   loop(pending - name, running, 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(Output.warning_text("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_tree(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 select_dirs: List[Path] = Nil
   686     var numa_shuffling = false
   687     var requirements = false
   688     var exclude_session_groups: List[String] = Nil
   689     var all_sessions = false
   690     var build_heap = false
   691     var clean_build = false
   692     var dirs: List[Path] = Nil
   693     var session_groups: List[String] = Nil
   694     var max_jobs = 1
   695     var check_keywords: Set[String] = Set.empty
   696     var list_files = false
   697     var no_build = false
   698     var options = (Options.init() /: build_options)(_ + _)
   699     var system_mode = false
   700     var verbose = false
   701     var exclude_sessions: List[String] = Nil
   702 
   703     val getopts = Getopts("""
   704 Usage: isabelle build [OPTIONS] [SESSIONS ...]
   705 
   706   Options are:
   707     -D DIR       include session directory and select its sessions
   708     -N           cyclic shuffling of NUMA CPU nodes (performance tuning)
   709     -R           operate on requirements of selected sessions
   710     -X NAME      exclude sessions from group NAME and all descendants
   711     -a           select all sessions
   712     -b           build heap images
   713     -c           clean build
   714     -d DIR       include session directory
   715     -g NAME      select session group NAME
   716     -j INT       maximum number of parallel jobs (default 1)
   717     -k KEYWORD   check theory sources for conflicts with proposed keywords
   718     -l           list session source files
   719     -n           no build -- test dependencies only
   720     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   721     -s           system build mode: produce output in ISABELLE_HOME
   722     -v           verbose
   723     -x NAME      exclude session NAME and all descendants
   724 
   725   Build and manage Isabelle sessions, depending on implicit settings:
   726 
   727 """ + Library.prefix_lines("  ", Build_Log.Settings.show()) + "\n",
   728       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   729       "N" -> (_ => numa_shuffling = true),
   730       "R" -> (_ => requirements = true),
   731       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   732       "a" -> (_ => all_sessions = true),
   733       "b" -> (_ => build_heap = true),
   734       "c" -> (_ => clean_build = true),
   735       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   736       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   737       "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
   738       "k:" -> (arg => check_keywords = check_keywords + arg),
   739       "l" -> (_ => list_files = true),
   740       "n" -> (_ => no_build = true),
   741       "o:" -> (arg => options = options + arg),
   742       "s" -> (_ => system_mode = true),
   743       "v" -> (_ => verbose = true),
   744       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   745 
   746     val sessions = getopts(args)
   747 
   748     val progress = new Console_Progress(verbose = verbose)
   749 
   750     val start_date = Date.now()
   751 
   752     if (verbose) {
   753       progress.echo(
   754         "Started at " + Build_Log.print_date(start_date) +
   755           " (" + Isabelle_System.getenv("ML_IDENTIFIER") + " on " + Isabelle_System.hostname() +")")
   756       progress.echo(Build_Log.Settings.show() + "\n")
   757     }
   758 
   759     val results =
   760       progress.interrupt_handler {
   761         build(options, progress,
   762           build_heap = build_heap,
   763           clean_build = clean_build,
   764           dirs = dirs,
   765           select_dirs = select_dirs,
   766           numa_shuffling = NUMA.enabled_warning(numa_shuffling),
   767           max_jobs = max_jobs,
   768           list_files = list_files,
   769           check_keywords = check_keywords,
   770           no_build = no_build,
   771           system_mode = system_mode,
   772           verbose = verbose,
   773           requirements = requirements,
   774           all_sessions = all_sessions,
   775           exclude_session_groups = exclude_session_groups,
   776           exclude_sessions = exclude_sessions,
   777           session_groups = session_groups,
   778           sessions = sessions)
   779       }
   780     val end_date = Date.now()
   781     val elapsed_time = end_date.time - start_date.time
   782 
   783     if (verbose) {
   784       progress.echo("\nFinished at " + Build_Log.print_date(end_date))
   785     }
   786 
   787     val total_timing =
   788       (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
   789         copy(elapsed = elapsed_time)
   790     progress.echo(total_timing.message_resources)
   791 
   792     sys.exit(results.rc)
   793   })
   794 
   795 
   796   /* PIDE protocol */
   797 
   798   def build_theories(
   799     session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   800       session.get_protocol_handler(classOf[Handler].getName) match {
   801         case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
   802         case _ => error("Cannot invoke build_theories: bad protocol handler")
   803       }
   804 
   805   class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
   806   {
   807     private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
   808 
   809     override def exit(): Unit =
   810       pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
   811 
   812     def build_theories(
   813       session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   814     {
   815       val promise = Future.promise[XML.Body]
   816       val id = Document_ID.make().toString
   817       pending.change(promises => promises + (id -> promise))
   818       session.build_theories(id, master_dir, theories)
   819       promise
   820     }
   821 
   822     private def loading_theory(msg: Prover.Protocol_Output): Boolean =
   823       msg.properties match {
   824         case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
   825         case _ => false
   826       }
   827 
   828     private def build_theories_result(msg: Prover.Protocol_Output): Boolean =
   829       msg.properties match {
   830         case Markup.Build_Theories_Result(id) =>
   831           pending.change_result(promises =>
   832             promises.get(id) match {
   833               case Some(promise) =>
   834                 val error_message =
   835                   try { YXML.parse_body(Symbol.decode(msg.text)) }
   836                   catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
   837                 promise.fulfill(error_message)
   838                 (true, promises - id)
   839               case None =>
   840                 (false, promises)
   841             })
   842         case _ => false
   843       }
   844 
   845     val functions =
   846       List(
   847         Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
   848         Markup.LOADING_THEORY -> loading_theory _)
   849   }
   850 }