src/Pure/Tools/build.scala
author wenzelm
Wed Mar 16 20:50:38 2016 +0100 (2016-03-16)
changeset 62638 751cf9f3d433
parent 62637 0189fe0f6452
child 62641 0b1b7465f2ef
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.asInstanceOf[Outer_Syntax]
   174 
   175             val theory_files = thy_deps.deps.map(dep => Path.explode(dep.name.node))
   176             val loaded_files = if (inlined_files) thy_deps.loaded_files else Nil
   177 
   178             val all_files =
   179               (theory_files ::: loaded_files :::
   180                 info.files.map(file => info.dir + file) :::
   181                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   182 
   183             if (list_files)
   184               progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
   185 
   186             if (check_keywords.nonEmpty)
   187               Check_Keywords.check_keywords(progress, syntax.keywords, check_keywords, theory_files)
   188 
   189             val sources = all_files.map(p => (p, SHA1.digest(p.file)))
   190 
   191             val session_graph =
   192               Present.session_graph(info.parent getOrElse "", loaded_theories0, thy_deps.deps)
   193 
   194             val content =
   195               Session_Content(loaded_theories, known_theories, keywords, syntax,
   196                 sources, session_graph)
   197             deps + (name -> content)
   198           }
   199           catch {
   200             case ERROR(msg) =>
   201               cat_error(msg, "The error(s) above occurred in session " +
   202                 quote(name) + Position.here(info.pos))
   203           }
   204       }))
   205 
   206   def session_dependencies(
   207     options: Options,
   208     inlined_files: Boolean,
   209     dirs: List[Path],
   210     sessions: List[String]): Deps =
   211   {
   212     val (_, tree) = Sessions.load(options, dirs = dirs).selection(sessions = sessions)
   213     dependencies(inlined_files = inlined_files, tree = tree)
   214   }
   215 
   216   def session_content(
   217     options: Options,
   218     inlined_files: Boolean,
   219     dirs: List[Path],
   220     session: String): Session_Content =
   221   {
   222     session_dependencies(options, inlined_files, dirs, List(session))(session)
   223   }
   224 
   225   def outer_syntax(options: Options, session: String): Outer_Syntax =
   226     session_content(options, false, Nil, session).syntax
   227 
   228 
   229   /* jobs */
   230 
   231   private class Job(progress: Progress, name: String, val info: Sessions.Info, tree: Sessions.Tree,
   232     store: Sessions.Store, do_output: Boolean, verbose: Boolean,
   233     session_graph: Graph_Display.Graph, command_timings: List[Properties.T])
   234   {
   235     val output = store.output_dir + Path.basic(name)
   236     def output_path: Option[Path] = if (do_output) Some(output) else None
   237     def output_save_state: String =
   238       if (do_output)
   239         "PolyML.SaveState.saveChild (" + ML_Syntax.print_string0(File.platform_path(output)) +
   240           ", List.length (PolyML.SaveState.showHierarchy ()))"
   241       else ""
   242     output.file.delete
   243 
   244     private val parent = info.parent.getOrElse("")
   245 
   246     private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
   247     try { isabelle.graphview.Graph_File.write(info.options, graph_file, session_graph) }
   248     catch { case ERROR(_) => /*error should be exposed in ML*/ }
   249 
   250     private val env =
   251       Isabelle_System.settings() +
   252         ("ISABELLE_ML_DEBUGGER" -> info.options.bool("ML_debugger").toString)
   253 
   254     private val future_result: Future[Process_Result] =
   255       Future.thread("build") {
   256         val process =
   257           if (Sessions.is_pure(name)) {
   258             val eval =
   259               "Command_Line.tool0 (fn () => (Session.finish (); Options.reset_default ();" +
   260               " Session.shutdown (); ML_Heap.share_common_data (); " + output_save_state + "));"
   261             ML_Process(info.options, "RAW_ML_SYSTEM", List("--use", "ROOT.ML", "--eval", eval),
   262               cwd = info.dir.file, env = env, tree = Some(tree), store = store)
   263           }
   264           else {
   265             val args_file = Isabelle_System.tmp_file("build")
   266             File.write(args_file, YXML.string_of_body(
   267                 {
   268                   val theories = info.theories.map(x => (x._2, x._3))
   269                   import XML.Encode._
   270                   pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
   271                     pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
   272                     pair(string, pair(string, pair(string,
   273                     list(pair(Options.encode, list(Path.encode)))))))))))))(
   274                   (Symbol.codes, (command_timings, (do_output, (verbose,
   275                     (store.browser_info, (info.document_files, (File.standard_path(graph_file),
   276                     (parent, (info.chapter, (name,
   277                     theories)))))))))))
   278                 }))
   279             val eval =
   280               "Command_Line.tool0 (fn () => (" +
   281               "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
   282               (if (do_output) "; ML_Heap.share_common_data (); " + output_save_state
   283                else "") + "));"
   284             ML_Process(info.options, parent, List("--eval", eval), cwd = info.dir.file,
   285               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   286           }
   287         process.result(
   288           progress_stdout = (line: String) =>
   289             Library.try_unprefix("\floading_theory = ", line) match {
   290               case Some(theory) => progress.theory(name, theory)
   291               case None =>
   292             },
   293           progress_limit =
   294             info.options.int("process_output_limit") match {
   295               case 0 => None
   296               case m => Some(m * 1000000L)
   297             },
   298           strict = false)
   299       }
   300 
   301     def terminate: Unit = future_result.cancel
   302     def is_finished: Boolean = future_result.is_finished
   303 
   304     @volatile private var was_timeout = false
   305     private val timeout_request: Option[Event_Timer.Request] =
   306     {
   307       if (info.timeout > Time.zero)
   308         Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
   309       else None
   310     }
   311 
   312     def join: Process_Result =
   313     {
   314       val result = future_result.join
   315 
   316       if (result.ok && !Sessions.is_pure(name))
   317         Present.finish(progress, store.browser_info, graph_file, info, name)
   318 
   319       graph_file.delete
   320       timeout_request.foreach(_.cancel)
   321 
   322       if (result.interrupted) {
   323         if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
   324         else result.error(Output.error_text("Interrupt"))
   325       }
   326       else result
   327     }
   328   }
   329 
   330 
   331   /* inlined properties (YXML) */
   332 
   333   object Props
   334   {
   335     def parse(text: String): Properties.T = XML.Decode.properties(YXML.parse_body(text))
   336 
   337     def parse_lines(prefix: String, lines: List[String]): List[Properties.T] =
   338       for (line <- lines; s <- Library.try_unprefix(prefix, line)) yield parse(s)
   339 
   340     def find_parse_line(prefix: String, lines: List[String]): Option[Properties.T] =
   341       lines.find(_.startsWith(prefix)).map(line => parse(line.substring(prefix.length)))
   342   }
   343 
   344 
   345   /* log files */
   346 
   347   private val SESSION_NAME = "\fSession.name = "
   348 
   349   sealed case class Log_Info(
   350     name: String,
   351     stats: List[Properties.T],
   352     tasks: List[Properties.T],
   353     command_timings: List[Properties.T],
   354     session_timing: Properties.T)
   355 
   356   def parse_log(full_stats: Boolean, text: String): Log_Info =
   357   {
   358     val lines = split_lines(text)
   359     val xml_cache = new XML.Cache()
   360     def parse_lines(prfx: String): List[Properties.T] =
   361       Props.parse_lines(prfx, lines).map(xml_cache.props(_))
   362 
   363     val name =
   364       lines.find(_.startsWith(SESSION_NAME)).map(_.substring(SESSION_NAME.length)) getOrElse ""
   365     val stats = if (full_stats) parse_lines("\fML_statistics = ") else Nil
   366     val tasks = if (full_stats) parse_lines("\ftask_statistics = ") else Nil
   367     val command_timings = parse_lines("\fcommand_timing = ")
   368     val session_timing = Props.find_parse_line("\fTiming = ", lines) getOrElse Nil
   369     Log_Info(name, stats, tasks, command_timings, session_timing)
   370   }
   371 
   372 
   373   /* sources and heaps */
   374 
   375   private val SOURCES = "sources: "
   376   private val INPUT_HEAP = "input_heap: "
   377   private val OUTPUT_HEAP = "output_heap: "
   378   private val LOG_START = "log:"
   379   private val line_prefixes = List(SOURCES, INPUT_HEAP, OUTPUT_HEAP, LOG_START)
   380 
   381   private def sources_stamp(digests: List[SHA1.Digest]): String =
   382     digests.map(_.toString).sorted.mkString(SOURCES, " ", "")
   383 
   384   private def read_stamps(path: Path): Option[(String, List[String], List[String])] =
   385     if (path.is_file) {
   386       val stream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(path.file)))
   387       val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
   388       val lines =
   389       {
   390         val lines = new mutable.ListBuffer[String]
   391         try {
   392           var finished = false
   393           while (!finished) {
   394             val line = reader.readLine
   395             if (line != null && line_prefixes.exists(line.startsWith(_)))
   396               lines += line
   397             else finished = true
   398           }
   399         }
   400         finally { reader.close }
   401         lines.toList
   402       }
   403 
   404       if (!lines.isEmpty && lines.last.startsWith(LOG_START)) {
   405         lines.find(_.startsWith(SOURCES)).map(s =>
   406           (s, lines.filter(_.startsWith(INPUT_HEAP)), lines.filter(_.startsWith(OUTPUT_HEAP))))
   407       }
   408       else None
   409     }
   410     else None
   411 
   412 
   413 
   414   /** build_results **/
   415 
   416   class Build_Results private [Build](results: Map[String, Option[Process_Result]])
   417   {
   418     def sessions: Set[String] = results.keySet
   419     def cancelled(name: String): Boolean = results(name).isEmpty
   420     def apply(name: String): Process_Result = results(name).getOrElse(Process_Result(1))
   421     val rc = (0 /: results.iterator.map({ case (_, Some(r)) => r.rc case (_, None) => 1 }))(_ max _)
   422 
   423     override def toString: String = rc.toString
   424   }
   425 
   426   def build_results(
   427     options: Options,
   428     progress: Progress = Ignore_Progress,
   429     requirements: Boolean = false,
   430     all_sessions: Boolean = false,
   431     build_heap: Boolean = false,
   432     clean_build: Boolean = false,
   433     dirs: List[Path] = Nil,
   434     select_dirs: List[Path] = Nil,
   435     exclude_session_groups: List[String] = Nil,
   436     session_groups: List[String] = 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     exclude_sessions: List[String] = Nil,
   444     sessions: List[String] = Nil): Build_Results =
   445   {
   446     /* session tree and dependencies */
   447 
   448     val full_tree = Sessions.load(options.int("completion_limit") = 0, dirs, select_dirs)
   449     val (selected, selected_tree) =
   450       full_tree.selection(requirements, all_sessions,
   451         exclude_session_groups, exclude_sessions, session_groups, sessions)
   452 
   453     val deps = dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
   454 
   455     def session_sources_stamp(name: String): String =
   456       sources_stamp(selected_tree(name).meta_digest :: deps.sources(name))
   457 
   458     val store = Sessions.store(system_mode)
   459 
   460 
   461     /* queue with scheduling information */
   462 
   463     def load_timings(name: String): (List[Properties.T], Double) =
   464     {
   465       val (path, text) =
   466         store.find_log_gz(name) match {
   467           case Some(path) => (path, File.read_gzip(path))
   468           case None =>
   469             store.find_log(name) match {
   470               case Some(path) => (path, File.read(path))
   471               case None => (Path.current, "")
   472             }
   473         }
   474 
   475       def ignore_error(msg: String): (List[Properties.T], Double) =
   476       {
   477         Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
   478         (Nil, 0.0)
   479       }
   480 
   481       try {
   482         val info = parse_log(false, text)
   483         val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
   484         (info.command_timings, session_timing)
   485       }
   486       catch {
   487         case ERROR(msg) => ignore_error(msg)
   488         case exn: java.lang.Error => ignore_error(Exn.message(exn))
   489         case _: XML.Error => ignore_error("")
   490       }
   491     }
   492 
   493     val queue = Queue(selected_tree, load_timings)
   494 
   495 
   496     /* main build process */
   497 
   498     store.prepare_output()
   499 
   500     // optional cleanup
   501     if (clean_build) {
   502       for (name <- full_tree.graph.all_succs(selected)) {
   503         val files =
   504           List(Path.basic(name), Sessions.log(name), Sessions.log_gz(name)).
   505             map(store.output_dir + _).filter(_.is_file)
   506         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   507         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   508       }
   509     }
   510 
   511     // scheduler loop
   512     case class Result(current: Boolean, heap_stamp: Option[String], process: Option[Process_Result])
   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; stamp <- File.time_stamp(path))
   562                     yield stamp
   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))))
   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.is_pure(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)))))
   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)))))
   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)))
   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 results =
   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 
   653     /* global browser info */
   654 
   655     if (!no_build) {
   656       val browser_chapters =
   657         (for {
   658           (name, result) <- results.iterator
   659           if result.ok && !Sessions.is_pure(name)
   660           info = full_tree(name)
   661           if info.options.bool("browser_info")
   662         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   663             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   664 
   665       for ((chapter, entries) <- browser_chapters)
   666         Present.update_chapter_index(store.browser_info, chapter, entries)
   667 
   668       if (browser_chapters.nonEmpty) Present.make_global_index(store.browser_info)
   669     }
   670 
   671     new Build_Results((for ((name, result) <- results.iterator) yield (name, result.process)).toMap)
   672   }
   673 
   674 
   675 
   676   /** build **/
   677 
   678   def build(
   679     options: Options,
   680     progress: Progress = Ignore_Progress,
   681     requirements: Boolean = false,
   682     all_sessions: Boolean = false,
   683     build_heap: Boolean = false,
   684     clean_build: Boolean = false,
   685     dirs: List[Path] = Nil,
   686     select_dirs: List[Path] = Nil,
   687     exclude_session_groups: List[String] = Nil,
   688     session_groups: List[String] = Nil,
   689     max_jobs: Int = 1,
   690     list_files: Boolean = false,
   691     check_keywords: Set[String] = Set.empty,
   692     no_build: Boolean = false,
   693     system_mode: Boolean = false,
   694     verbose: Boolean = false,
   695     exclude_sessions: List[String] = Nil,
   696     sessions: List[String] = Nil): Int =
   697   {
   698     val results =
   699       build_results(options, progress, requirements, all_sessions, build_heap, clean_build,
   700         dirs, select_dirs, exclude_session_groups, session_groups, max_jobs, list_files,
   701         check_keywords, no_build, system_mode, verbose, exclude_sessions, sessions)
   702 
   703     if (results.rc != 0 && (verbose || !no_build)) {
   704       val unfinished =
   705         (for {
   706           name <- results.sessions.iterator
   707           if !results(name).ok
   708          } yield name).toList.sorted
   709       progress.echo("Unfinished session(s): " + commas(unfinished))
   710     }
   711 
   712     results.rc
   713   }
   714 
   715 
   716   /* command line entry point */
   717 
   718   def main(args: Array[String])
   719   {
   720     Command_Line.tool {
   721       def show_settings(): String =
   722         cat_lines(List(
   723           "ISABELLE_BUILD_OPTIONS=" +
   724             quote(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS")),
   725           "ISABELLE_BUILD_JAVA_OPTIONS=" +
   726             quote(Isabelle_System.getenv("ISABELLE_BUILD_JAVA_OPTIONS")),
   727           "",
   728           "ML_PLATFORM=" + quote(Isabelle_System.getenv("ML_PLATFORM")),
   729           "ML_HOME=" + quote(Isabelle_System.getenv("ML_HOME")),
   730           "ML_SYSTEM=" + quote(Isabelle_System.getenv("ML_SYSTEM")),
   731           "ML_OPTIONS=" + quote(Isabelle_System.getenv("ML_OPTIONS"))))
   732 
   733       val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
   734 
   735       var select_dirs: List[Path] = Nil
   736       var requirements = false
   737       var exclude_session_groups: List[String] = Nil
   738       var all_sessions = false
   739       var build_heap = false
   740       var clean_build = false
   741       var dirs: List[Path] = Nil
   742       var session_groups: List[String] = Nil
   743       var max_jobs = 1
   744       var check_keywords: Set[String] = Set.empty
   745       var list_files = false
   746       var no_build = false
   747       var options = (Options.init() /: build_options)(_ + _)
   748       var system_mode = false
   749       var verbose = false
   750       var exclude_sessions: List[String] = Nil
   751 
   752       val getopts = Getopts("""
   753 Usage: isabelle build [OPTIONS] [SESSIONS ...]
   754 
   755   Options are:
   756     -D DIR       include session directory and select its sessions
   757     -R           operate on requirements of selected sessions
   758     -X NAME      exclude sessions from group NAME and all descendants
   759     -a           select all sessions
   760     -b           build heap images
   761     -c           clean build
   762     -d DIR       include session directory
   763     -g NAME      select session group NAME
   764     -j INT       maximum number of parallel jobs (default 1)
   765     -k KEYWORD   check theory sources for conflicts with proposed keywords
   766     -l           list session source files
   767     -n           no build -- test dependencies only
   768     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   769     -s           system build mode: produce output in ISABELLE_HOME
   770     -v           verbose
   771     -x NAME      exclude session NAME and all descendants
   772 
   773   Build and manage Isabelle sessions, depending on implicit settings:
   774 
   775 """ + Library.prefix_lines("  ", show_settings()),
   776         "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   777         "R" -> (_ => requirements = true),
   778         "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   779         "a" -> (_ => all_sessions = true),
   780         "b" -> (_ => build_heap = true),
   781         "c" -> (_ => clean_build = true),
   782         "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   783         "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   784         "j:" -> (arg => max_jobs = Properties.Value.Int.parse(arg)),
   785         "k:" -> (arg => check_keywords = check_keywords + arg),
   786         "l" -> (_ => list_files = true),
   787         "n" -> (_ => no_build = true),
   788         "o:" -> (arg => options = options + arg),
   789         "s" -> (_ => system_mode = true),
   790         "v" -> (_ => verbose = true),
   791         "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   792 
   793       val sessions = getopts(args)
   794 
   795       val progress = new Console_Progress(verbose)
   796 
   797       if (verbose) {
   798         progress.echo(
   799           Library.trim_line(
   800             Isabelle_System.bash(
   801               """echo "Started at $(date) ($ML_IDENTIFIER on $(hostname))" """).out) + "\n")
   802         progress.echo(show_settings() + "\n")
   803       }
   804 
   805       val start_time = Time.now()
   806       val results =
   807         progress.interrupt_handler {
   808           build_results(options, progress, requirements, all_sessions, build_heap, clean_build,
   809             dirs, select_dirs, exclude_session_groups, session_groups, max_jobs, list_files,
   810             check_keywords, no_build, system_mode, verbose, exclude_sessions, sessions)
   811         }
   812       val elapsed_time = Time.now() - start_time
   813 
   814       if (verbose) {
   815         progress.echo("\n" +
   816           Library.trim_line(
   817             Isabelle_System.bash("""echo -n "Finished at "; date""").out))
   818       }
   819 
   820       val total_timing =
   821         (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
   822           copy(elapsed = elapsed_time)
   823       progress.echo(total_timing.message_resources)
   824 
   825       results.rc
   826     }
   827   }
   828 
   829 
   830   /* PIDE protocol */
   831 
   832   def build_theories(
   833     session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   834       session.get_protocol_handler(classOf[Handler].getName) match {
   835         case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
   836         case _ => error("Cannot invoke build_theories: bad protocol handler")
   837       }
   838 
   839   class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
   840   {
   841     private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
   842 
   843     def build_theories(
   844       session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   845     {
   846       val promise = Future.promise[XML.Body]
   847       val id = Document_ID.make().toString
   848       pending.change(promises => promises + (id -> promise))
   849       session.build_theories(id, master_dir, theories)
   850       promise
   851     }
   852 
   853     private def loading_theory(prover: Prover, msg: Prover.Protocol_Output): Boolean =
   854       msg.properties match {
   855         case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
   856         case _ => false
   857       }
   858 
   859     private def build_theories_result(prover: Prover, msg: Prover.Protocol_Output): Boolean =
   860       msg.properties match {
   861         case Markup.Build_Theories_Result(id) =>
   862           pending.change_result(promises =>
   863             promises.get(id) match {
   864               case Some(promise) =>
   865                 val error_message =
   866                   try { YXML.parse_body(Symbol.decode(msg.text)) }
   867                   catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
   868                 promise.fulfill(error_message)
   869                 (true, promises - id)
   870               case None =>
   871                 (false, promises)
   872             })
   873         case _ => false
   874       }
   875 
   876     override def stop(prover: Prover): Unit =
   877       pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
   878 
   879     val functions =
   880       Map(
   881         Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
   882         Markup.LOADING_THEORY -> loading_theory _)
   883   }
   884 }