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