src/Pure/Tools/build.scala
author wenzelm
Fri May 02 20:01:45 2014 +0200 (2014-05-02)
changeset 56831 e3ccf0809d51
parent 56824 5ae68f53b7c2
child 56837 5a598f1eecfd
permissions -rw-r--r--
prefer scala.Console with its support for thread-local redirection;
     1 /*  Title:      Pure/Tools/build.scala
     2     Author:     Makarius
     3     Options:    :folding=explicit:collapseFolds=1:
     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   /** progress context **/
    23 
    24   class Progress
    25   {
    26     def echo(msg: String) {}
    27     def theory(session: String, theory: String) {}
    28     def stopped: Boolean = false
    29   }
    30 
    31   object Ignore_Progress extends Progress
    32 
    33   class Console_Progress(verbose: Boolean) extends Progress
    34   {
    35     override def echo(msg: String) { Console.println(msg) }
    36     override def theory(session: String, theory: String): Unit =
    37       if (verbose) echo(session + ": theory " + theory)
    38 
    39     @volatile private var is_stopped = false
    40     def interrupt_handler[A](e: => A): A = Interrupt.handler { is_stopped = true } { e }
    41     override def stopped: Boolean = is_stopped
    42   }
    43 
    44 
    45 
    46   /** session information **/
    47 
    48   // external version
    49   abstract class Entry
    50   sealed case class Chapter(name: String) extends Entry
    51   sealed case class Session_Entry(
    52     pos: Position.T,
    53     name: String,
    54     groups: List[String],
    55     path: String,
    56     parent: Option[String],
    57     description: String,
    58     options: List[Options.Spec],
    59     theories: List[(Boolean, List[Options.Spec], List[String])],
    60     files: List[String],
    61     document_files: List[(String, String)]) extends Entry
    62 
    63   // internal version
    64   sealed case class Session_Info(
    65     chapter: String,
    66     select: Boolean,
    67     pos: Position.T,
    68     groups: List[String],
    69     dir: Path,
    70     parent: Option[String],
    71     description: String,
    72     options: Options,
    73     theories: List[(Boolean, Options, List[Path])],
    74     files: List[Path],
    75     document_files: List[(Path, Path)],
    76     entry_digest: SHA1.Digest)
    77 
    78   def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
    79 
    80   def session_info(options: Options, select: Boolean, dir: Path,
    81       chapter: String, entry: Session_Entry): (String, Session_Info) =
    82     try {
    83       val name = entry.name
    84 
    85       if (name == "") error("Bad session name")
    86       if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
    87       if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
    88 
    89       val session_options = options ++ entry.options
    90 
    91       val theories =
    92         entry.theories.map({ case (global, opts, thys) =>
    93           (global, session_options ++ opts, thys.map(Path.explode(_))) })
    94       val files = entry.files.map(Path.explode(_))
    95       val document_files =
    96         entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
    97 
    98       val entry_digest =
    99         SHA1.digest((chapter, name, entry.parent, entry.options,
   100           entry.theories, entry.files, entry.document_files).toString)
   101 
   102       val info =
   103         Session_Info(chapter, select, entry.pos, entry.groups, dir + Path.explode(entry.path),
   104           entry.parent, entry.description, session_options, theories, files,
   105           document_files, entry_digest)
   106 
   107       (name, info)
   108     }
   109     catch {
   110       case ERROR(msg) =>
   111         error(msg + "\nThe error(s) above occurred in session entry " +
   112           quote(entry.name) + Position.here(entry.pos))
   113     }
   114 
   115 
   116   /* session tree */
   117 
   118   object Session_Tree
   119   {
   120     def apply(infos: Seq[(String, Session_Info)]): Session_Tree =
   121     {
   122       val graph1 =
   123         (Graph.string[Session_Info] /: infos) {
   124           case (graph, (name, info)) =>
   125             if (graph.defined(name))
   126               error("Duplicate session " + quote(name) + Position.here(info.pos) +
   127                 Position.here(graph.get_node(name).pos))
   128             else graph.new_node(name, info)
   129         }
   130       val graph2 =
   131         (graph1 /: graph1.iterator) {
   132           case (graph, (name, (info, _))) =>
   133             info.parent match {
   134               case None => graph
   135               case Some(parent) =>
   136                 if (!graph.defined(parent))
   137                   error("Bad parent session " + quote(parent) + " for " +
   138                     quote(name) + Position.here(info.pos))
   139 
   140                 try { graph.add_edge_acyclic(parent, name) }
   141                 catch {
   142                   case exn: Graph.Cycles[_] =>
   143                     error(cat_lines(exn.cycles.map(cycle =>
   144                       "Cyclic session dependency of " +
   145                         cycle.map(c => quote(c.toString)).mkString(" via "))) +
   146                           Position.here(info.pos))
   147                 }
   148             }
   149         }
   150       new Session_Tree(graph2)
   151     }
   152   }
   153 
   154   final class Session_Tree private(val graph: Graph[String, Session_Info])
   155     extends PartialFunction[String, Session_Info]
   156   {
   157     def apply(name: String): Session_Info = graph.get_node(name)
   158     def isDefinedAt(name: String): Boolean = graph.defined(name)
   159 
   160     def selection(requirements: Boolean, all_sessions: Boolean,
   161       session_groups: List[String], sessions: List[String]): (List[String], Session_Tree) =
   162     {
   163       val bad_sessions = sessions.filterNot(isDefinedAt(_))
   164       if (!bad_sessions.isEmpty) error("Undefined session(s): " + commas_quote(bad_sessions))
   165 
   166       val pre_selected =
   167       {
   168         if (all_sessions) graph.keys
   169         else {
   170           val select_group = session_groups.toSet
   171           val select = sessions.toSet
   172           (for {
   173             (name, (info, _)) <- graph.iterator
   174             if info.select || select(name) || apply(name).groups.exists(select_group)
   175           } yield name).toList
   176         }
   177       }
   178       val selected =
   179         if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
   180         else pre_selected
   181 
   182       val graph1 = graph.restrict(graph.all_preds(selected).toSet)
   183       (selected, new Session_Tree(graph1))
   184     }
   185 
   186     def topological_order: List[(String, Session_Info)] =
   187       graph.topological_order.map(name => (name, apply(name)))
   188 
   189     override def toString: String = graph.keys_iterator.mkString("Session_Tree(", ", ", ")")
   190   }
   191 
   192 
   193   /* parser */
   194 
   195   val chapter_default = "Unsorted"
   196 
   197   private val CHAPTER = "chapter"
   198   private val SESSION = "session"
   199   private val IN = "in"
   200   private val DESCRIPTION = "description"
   201   private val OPTIONS = "options"
   202   private val GLOBAL_THEORIES = "global_theories"
   203   private val THEORIES = "theories"
   204   private val FILES = "files"
   205   private val DOCUMENT_FILES = "document_files"
   206 
   207   lazy val root_syntax =
   208     Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" +
   209       (CHAPTER, Keyword.THY_DECL) + (SESSION, Keyword.THY_DECL) +
   210       IN + DESCRIPTION + OPTIONS + GLOBAL_THEORIES + THEORIES + FILES + DOCUMENT_FILES
   211 
   212   object Parser extends Parse.Parser
   213   {
   214     private val chapter: Parser[Chapter] =
   215     {
   216       val chapter_name = atom("chapter name", _.is_name)
   217 
   218       command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
   219     }
   220 
   221     private val session_entry: Parser[Session_Entry] =
   222     {
   223       val session_name = atom("session name", _.is_name)
   224 
   225       val option =
   226         name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
   227       val options = keyword("[") ~> rep1sep(option, keyword(",")) <~ keyword("]")
   228 
   229       val theories =
   230         (keyword(GLOBAL_THEORIES) | keyword(THEORIES)) ~!
   231           ((options | success(Nil)) ~ rep(theory_xname)) ^^
   232           { case x ~ (y ~ z) => (x == GLOBAL_THEORIES, y, z) }
   233 
   234       val document_files =
   235         keyword(DOCUMENT_FILES) ~!
   236           ((keyword("(") ~! (keyword(IN) ~! (path ~ keyword(")"))) ^^
   237               { case _ ~ (_ ~ (x ~ _)) => x } | success("document")) ~
   238             rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
   239 
   240       command(SESSION) ~!
   241         (session_name ~
   242           ((keyword("(") ~! (rep1(name) <~ keyword(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
   243           ((keyword(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
   244           (keyword("=") ~!
   245             (opt(session_name ~! keyword("+") ^^ { case x ~ _ => x }) ~
   246               ((keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
   247               ((keyword(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
   248               rep1(theories) ~
   249               ((keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil)) ~
   250               (rep(document_files) ^^ (x => x.flatten))))) ^^
   251         { case pos ~ (a ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i))) =>
   252             Session_Entry(pos, a, b, c, d, e, f, g, h, i) }
   253     }
   254 
   255     def parse_entries(root: Path): List[(String, Session_Entry)] =
   256     {
   257       val toks = root_syntax.scan(File.read(root))
   258 
   259       parse_all(rep(chapter | session_entry), Token.reader(toks, root.implode)) match {
   260         case Success(result, _) =>
   261           var chapter = chapter_default
   262           val entries = new mutable.ListBuffer[(String, Session_Entry)]
   263           result.foreach {
   264             case Chapter(name) => chapter = name
   265             case session_entry: Session_Entry => entries += ((chapter, session_entry))
   266           }
   267           entries.toList
   268         case bad => error(bad.toString)
   269       }
   270     }
   271   }
   272 
   273 
   274   /* find sessions within certain directories */
   275 
   276   private val ROOT = Path.explode("ROOT")
   277   private val ROOTS = Path.explode("ROOTS")
   278 
   279   private def is_session_dir(dir: Path): Boolean =
   280     (dir + ROOT).is_file || (dir + ROOTS).is_file
   281 
   282   private def check_session_dir(dir: Path): Path =
   283     if (is_session_dir(dir)) dir
   284     else error("Bad session root directory: " + dir.toString)
   285 
   286   def find_sessions(options: Options, more_dirs: List[(Boolean, Path)]): Session_Tree =
   287   {
   288     def find_dir(select: Boolean, dir: Path): List[(String, Session_Info)] =
   289       find_root(select, dir) ::: find_roots(select, dir)
   290 
   291     def find_root(select: Boolean, dir: Path): List[(String, Session_Info)] =
   292     {
   293       val root = dir + ROOT
   294       if (root.is_file)
   295         Parser.parse_entries(root).map(p => session_info(options, select, dir, p._1, p._2))
   296       else Nil
   297     }
   298 
   299     def find_roots(select: Boolean, dir: Path): List[(String, Session_Info)] =
   300     {
   301       val roots = dir + ROOTS
   302       if (roots.is_file) {
   303         for {
   304           line <- split_lines(File.read(roots))
   305           if !(line == "" || line.startsWith("#"))
   306           dir1 =
   307             try { check_session_dir(dir + Path.explode(line)) }
   308             catch {
   309               case ERROR(msg) =>
   310                 error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
   311             }
   312           info <- find_dir(select, dir1)
   313         } yield info
   314       }
   315       else Nil
   316     }
   317 
   318     val default_dirs = Isabelle_System.components().filter(is_session_dir(_)).map((false, _))
   319 
   320     more_dirs foreach { case (_, dir) => check_session_dir(dir) }
   321 
   322     Session_Tree(
   323       for {
   324         (select, dir) <- default_dirs ::: more_dirs
   325         info <- find_dir(select, dir)
   326       } yield info)
   327   }
   328 
   329 
   330 
   331   /** build **/
   332 
   333   /* queue */
   334 
   335   object Queue
   336   {
   337     def apply(tree: Session_Tree, load_timings: String => (List[Properties.T], Double)): Queue =
   338     {
   339       val graph = tree.graph
   340       val sessions = graph.keys
   341 
   342       val timings =
   343         sessions.par.map((name: String) =>
   344           Exn.capture { (name, load_timings(name)) }).toList.map(Exn.release(_))
   345       val command_timings =
   346         Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
   347       val session_timing =
   348         Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
   349 
   350       def outdegree(name: String): Int = graph.imm_succs(name).size
   351       def timeout(name: String): Double = tree(name).options.real("timeout")
   352 
   353       object Ordering extends scala.math.Ordering[String]
   354       {
   355         def compare_timing(name1: String, name2: String): Int =
   356         {
   357           val t1 = session_timing(name1)
   358           val t2 = session_timing(name2)
   359           if (t1 == 0.0 || t2 == 0.0) 0
   360           else t1 compare t2
   361         }
   362 
   363         def compare(name1: String, name2: String): Int =
   364           outdegree(name2) compare outdegree(name1) match {
   365             case 0 =>
   366               compare_timing(name2, name1) match {
   367                 case 0 =>
   368                   timeout(name2) compare timeout(name1) match {
   369                     case 0 => name1 compare name2
   370                     case ord => ord
   371                   }
   372                 case ord => ord
   373               }
   374             case ord => ord
   375           }
   376       }
   377 
   378       new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
   379     }
   380   }
   381 
   382   final class Queue private(
   383     graph: Graph[String, Session_Info],
   384     order: SortedSet[String],
   385     val command_timings: String => List[Properties.T])
   386   {
   387     def is_inner(name: String): Boolean = !graph.is_maximal(name)
   388 
   389     def is_empty: Boolean = graph.is_empty
   390 
   391     def - (name: String): Queue =
   392       new Queue(graph.del_node(name),
   393         order - name,  // FIXME scala-2.10.0 TreeSet problem!?
   394         command_timings)
   395 
   396     def dequeue(skip: String => Boolean): Option[(String, Session_Info)] =
   397     {
   398       val it = order.iterator.dropWhile(name =>
   399         skip(name)
   400           || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
   401           || !graph.is_minimal(name))
   402       if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
   403       else None
   404     }
   405   }
   406 
   407 
   408   /* source dependencies and static content */
   409 
   410   sealed case class Session_Content(
   411     loaded_theories: Set[String],
   412     known_theories: Map[String, Document.Node.Name],
   413     keywords: Thy_Header.Keywords,
   414     syntax: Outer_Syntax,
   415     sources: List[(Path, SHA1.Digest)])
   416 
   417   sealed case class Deps(deps: Map[String, Session_Content])
   418   {
   419     def is_empty: Boolean = deps.isEmpty
   420     def apply(name: String): Session_Content = deps(name)
   421     def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
   422   }
   423 
   424   def dependencies(progress: Progress, inlined_files: Boolean,
   425       verbose: Boolean, list_files: Boolean, tree: Session_Tree): Deps =
   426     Deps((Map.empty[String, Session_Content] /: tree.topological_order)(
   427       { case (deps, (name, info)) =>
   428           if (progress.stopped) throw Exn.Interrupt()
   429 
   430           try {
   431             val (loaded_theories0, known_theories0, syntax0) =
   432               info.parent.map(deps(_)) match {
   433                 case None =>
   434                   (Set.empty[String], Map.empty[String, Document.Node.Name], Outer_Syntax.init())
   435                 case Some(parent) =>
   436                   (parent.loaded_theories, parent.known_theories, parent.syntax)
   437               }
   438             val resources = new Resources(loaded_theories0, known_theories0, syntax0)
   439             val thy_info = new Thy_Info(resources)
   440 
   441             if (verbose || list_files) {
   442               val groups =
   443                 if (info.groups.isEmpty) ""
   444                 else info.groups.mkString(" (", " ", ")")
   445               progress.echo("Session " + info.chapter + "/" + name + groups)
   446             }
   447 
   448             val thy_deps =
   449             {
   450               val root_theories =
   451                 info.theories.flatMap({
   452                   case (global, _, thys) =>
   453                     thys.map(thy =>
   454                       (resources.node_name(
   455                         if (global) "" else name, info.dir + Resources.thy_path(thy)), info.pos))
   456                 })
   457               val thy_deps = thy_info.dependencies(name, root_theories)
   458 
   459               thy_deps.errors match {
   460                 case Nil => thy_deps
   461                 case errs => error(cat_lines(errs))
   462               }
   463             }
   464 
   465             val known_theories =
   466               (known_theories0 /: thy_deps.deps)({ case (known, dep) =>
   467                 val name = dep.name
   468                 known.get(name.theory) match {
   469                   case Some(name1) if name != name1 =>
   470                     error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
   471                   case _ =>
   472                     known + (name.theory -> name) + (Long_Name.base_name(name.theory) -> name)
   473                 }
   474               })
   475 
   476             val loaded_theories = thy_deps.loaded_theories
   477             val keywords = thy_deps.keywords
   478             val syntax = thy_deps.syntax.asInstanceOf[Outer_Syntax]
   479 
   480             val loaded_files = if (inlined_files) thy_deps.loaded_files else Nil
   481 
   482             val all_files =
   483               (thy_deps.deps.map(dep => Path.explode(dep.name.node)) ::: loaded_files :::
   484                 info.files.map(file => info.dir + file) :::
   485                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   486 
   487             if (list_files)
   488               progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
   489 
   490             val sources = all_files.map(p => (p, SHA1.digest(p.file)))
   491 
   492             val content =
   493               Session_Content(loaded_theories, known_theories, keywords, syntax, sources)
   494             deps + (name -> content)
   495           }
   496           catch {
   497             case ERROR(msg) =>
   498               cat_error(msg, "The error(s) above occurred in session " +
   499                 quote(name) + Position.here(info.pos))
   500           }
   501       }))
   502 
   503   def session_dependencies(
   504     options: Options,
   505     inlined_files: Boolean,
   506     dirs: List[Path],
   507     sessions: List[String]): Deps =
   508   {
   509     val (_, tree) =
   510       find_sessions(options, dirs.map((false, _))).selection(false, false, Nil, sessions)
   511     dependencies(Ignore_Progress, inlined_files, false, false, tree)
   512   }
   513 
   514   def session_content(
   515     options: Options,
   516     inlined_files: Boolean,
   517     dirs: List[Path],
   518     session: String): Session_Content =
   519   {
   520     session_dependencies(options, inlined_files, dirs, List(session))(session)
   521   }
   522 
   523   def outer_syntax(options: Options, session: String): Outer_Syntax =
   524     session_content(options, false, Nil, session).syntax
   525 
   526 
   527   /* jobs */
   528 
   529   private class Job(progress: Progress,
   530     name: String, val info: Session_Info, output: Path, do_output: Boolean,
   531     verbose: Boolean, browser_info: Path, command_timings: List[Properties.T])
   532   {
   533     def output_path: Option[Path] = if (do_output) Some(output) else None
   534 
   535     private val parent = info.parent.getOrElse("")
   536 
   537     private val args_file = Isabelle_System.tmp_file("args")
   538     File.write(args_file, YXML.string_of_body(
   539       if (is_pure(name)) Options.encode(info.options)
   540       else
   541         {
   542           val theories = info.theories.map(x => (x._2, x._3))
   543           import XML.Encode._
   544               pair(list(properties), pair(bool, pair(Options.encode, pair(bool, pair(Path.encode,
   545                 pair(list(pair(Path.encode, Path.encode)), pair(string, pair(string, pair(string,
   546                   list(pair(Options.encode, list(Path.encode))))))))))))(
   547               (command_timings, (do_output, (info.options, (verbose, (browser_info,
   548                 (info.document_files, (parent, (info.chapter, (name, theories))))))))))
   549         }))
   550 
   551     private val env =
   552       Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output),
   553         (if (is_pure(name)) "ISABELLE_PROCESS_OPTIONS" else "ARGS_FILE") ->
   554           Isabelle_System.posix_path(args_file))
   555 
   556     private val script =
   557       if (is_pure(name)) {
   558         if (do_output) "./build " + name + " \"$OUTPUT\""
   559         else """ rm -f "$OUTPUT"; ./build """ + name
   560       }
   561       else {
   562         """
   563         . "$ISABELLE_HOME/lib/scripts/timestart.bash"
   564         """ +
   565           (if (do_output)
   566             """
   567             "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
   568             """
   569           else
   570             """
   571             rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
   572             """) +
   573         """
   574         RC="$?"
   575 
   576         . "$ISABELLE_HOME/lib/scripts/timestop.bash"
   577 
   578         if [ "$RC" -eq 0 ]; then
   579           echo "Finished $TARGET ($TIMES_REPORT)" >&2
   580         fi
   581 
   582         exit "$RC"
   583         """
   584       }
   585 
   586     private val (thread, result) =
   587       Simple_Thread.future("build") {
   588         Isabelle_System.bash_env(info.dir.file, env, script,
   589           progress_stdout = (line: String) =>
   590             Library.try_unprefix("\floading_theory = ", line) match {
   591               case Some(theory) => progress.theory(name, theory)
   592               case None =>
   593             },
   594           progress_limit =
   595             info.options.int("process_output_limit") match {
   596               case 0 => None
   597               case m => Some(m * 1000000L)
   598             })
   599       }
   600 
   601     def terminate: Unit = thread.interrupt
   602     def is_finished: Boolean = result.is_finished
   603 
   604     @volatile private var was_timeout = false
   605     private val timeout_request: Option[Event_Timer.Request] =
   606     {
   607       val timeout = info.options.seconds("timeout")
   608       if (timeout > Time.zero)
   609         Some(Event_Timer.request(Time.now() + timeout) { terminate; was_timeout = true })
   610       else None
   611     }
   612 
   613     def join: Isabelle_System.Bash_Result =
   614     {
   615       val res = result.join
   616 
   617       args_file.delete
   618       timeout_request.foreach(_.cancel)
   619 
   620       if (res.rc == Exn.Interrupt.return_code) {
   621         if (was_timeout) res.add_err(Output.error_text("Timeout")).set_rc(1)
   622         else res.add_err(Output.error_text("Interrupt"))
   623       }
   624       else res
   625     }
   626   }
   627 
   628 
   629   /* inlined properties (YXML) */
   630 
   631   object Props
   632   {
   633     def parse(text: String): Properties.T = XML.Decode.properties(YXML.parse_body(text))
   634 
   635     def parse_lines(prefix: String, lines: List[String]): List[Properties.T] =
   636       for (line <- lines; s <- Library.try_unprefix(prefix, line)) yield parse(s)
   637 
   638     def find_parse_line(prefix: String, lines: List[String]): Option[Properties.T] =
   639       lines.find(_.startsWith(prefix)).map(line => parse(line.substring(prefix.length)))
   640   }
   641 
   642 
   643   /* log files */
   644 
   645   private val LOG = Path.explode("log")
   646   private def log(name: String): Path = LOG + Path.basic(name)
   647   private def log_gz(name: String): Path = log(name).ext("gz")
   648 
   649   private val SESSION_NAME = "\fSession.name = "
   650 
   651 
   652   sealed case class Log_Info(
   653     name: String,
   654     stats: List[Properties.T],
   655     tasks: List[Properties.T],
   656     command_timings: List[Properties.T],
   657     session_timing: Properties.T)
   658 
   659   def parse_log(full_stats: Boolean, text: String): Log_Info =
   660   {
   661     val lines = split_lines(text)
   662     val xml_cache = new XML.Cache()
   663     def parse_lines(prfx: String): List[Properties.T] =
   664       Props.parse_lines(prfx, lines).map(xml_cache.props(_))
   665 
   666     val name =
   667       lines.find(_.startsWith(SESSION_NAME)).map(_.substring(SESSION_NAME.length)) getOrElse ""
   668     val stats = if (full_stats) parse_lines("\fML_statistics = ") else Nil
   669     val tasks = if (full_stats) parse_lines("\ftask_statistics = ") else Nil
   670     val command_timings = parse_lines("\fcommand_timing = ")
   671     val session_timing = Props.find_parse_line("\fTiming = ", lines) getOrElse Nil
   672     Log_Info(name, stats, tasks, command_timings, session_timing)
   673   }
   674 
   675 
   676   /* sources and heaps */
   677 
   678   private def sources_stamp(digests: List[SHA1.Digest]): String =
   679     digests.map(_.toString).sorted.mkString("sources: ", " ", "")
   680 
   681   private val no_heap: String = "heap: -"
   682 
   683   private def heap_stamp(heap: Option[Path]): String =
   684   {
   685     "heap: " +
   686       (heap match {
   687         case Some(path) =>
   688           val file = path.file
   689           if (file.isFile) file.length.toString + " " + file.lastModified.toString
   690           else "-"
   691         case None => "-"
   692       })
   693   }
   694 
   695   private def read_stamps(path: Path): Option[(String, String, String)] =
   696     if (path.is_file) {
   697       val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(path.file)))
   698       val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
   699       val (s, h1, h2) =
   700         try { (reader.readLine, reader.readLine, reader.readLine) }
   701         finally { reader.close }
   702       if (s != null && s.startsWith("sources: ") &&
   703           h1 != null && h1.startsWith("heap: ") &&
   704           h2 != null && h2.startsWith("heap: ")) Some((s, h1, h2))
   705       else None
   706     }
   707     else None
   708 
   709 
   710   /* build_results */
   711 
   712   def build_results(
   713     options: Options,
   714     progress: Progress = Ignore_Progress,
   715     requirements: Boolean = false,
   716     all_sessions: Boolean = false,
   717     build_heap: Boolean = false,
   718     clean_build: Boolean = false,
   719     more_dirs: List[(Boolean, Path)] = Nil,
   720     session_groups: List[String] = Nil,
   721     max_jobs: Int = 1,
   722     list_files: Boolean = false,
   723     no_build: Boolean = false,
   724     system_mode: Boolean = false,
   725     verbose: Boolean = false,
   726     sessions: List[String] = Nil): Map[String, Int] =
   727   {
   728     /* session tree and dependencies */
   729 
   730     val full_tree = find_sessions(options, more_dirs)
   731     val (selected, selected_tree) =
   732       full_tree.selection(requirements, all_sessions, session_groups, sessions)
   733 
   734     val deps = dependencies(progress, true, verbose, list_files, selected_tree)
   735 
   736     def make_stamp(name: String): String =
   737       sources_stamp(selected_tree(name).entry_digest :: deps.sources(name))
   738 
   739 
   740     /* persistent information */
   741 
   742     val (input_dirs, output_dir, browser_info) =
   743       if (system_mode) {
   744         val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
   745         (List(output_dir), output_dir, Path.explode("~~/browser_info"))
   746       }
   747       else {
   748         val output_dir = Path.explode("$ISABELLE_OUTPUT")
   749         (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
   750          Path.explode("$ISABELLE_BROWSER_INFO"))
   751       }
   752 
   753     def find_log(name: String): Option[(Path, Path)] =
   754       input_dirs.find(dir => (dir + log(name)).is_file).map(dir => (dir, dir + log(name)))
   755 
   756 
   757     /* queue with scheduling information */
   758 
   759     def load_timings(name: String): (List[Properties.T], Double) =
   760     {
   761       val (path, text) =
   762         find_log(name + ".gz") match {
   763           case Some((_, path)) => (path, File.read_gzip(path))
   764           case None =>
   765             find_log(name) match {
   766               case Some((_, path)) => (path, File.read(path))
   767               case None => (Path.current, "")
   768             }
   769         }
   770 
   771       def ignore_error(msg: String): (List[Properties.T], Double) =
   772       {
   773         Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
   774         (Nil, 0.0)
   775       }
   776 
   777       try {
   778         val info = parse_log(false, text)
   779         val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
   780         (info.command_timings, session_timing)
   781       }
   782       catch {
   783         case ERROR(msg) => ignore_error(msg)
   784         case exn: java.lang.Error => ignore_error(Exn.message(exn))
   785         case _: XML.Error => ignore_error("")
   786       }
   787     }
   788 
   789     val queue = Queue(selected_tree, load_timings)
   790 
   791 
   792     /* main build process */
   793 
   794     // prepare log dir
   795     Isabelle_System.mkdirs(output_dir + LOG)
   796 
   797     // optional cleanup
   798     if (clean_build) {
   799       for (name <- full_tree.graph.all_succs(selected)) {
   800         val files =
   801           List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
   802         if (!files.isEmpty) progress.echo("Cleaning " + name + " ...")
   803         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   804       }
   805     }
   806 
   807     // scheduler loop
   808     case class Result(current: Boolean, heap: String, rc: Int)
   809 
   810     def sleep(): Unit = Thread.sleep(500)
   811 
   812     @tailrec def loop(
   813       pending: Queue,
   814       running: Map[String, (String, Job)],
   815       results: Map[String, Result]): Map[String, Result] =
   816     {
   817       if (pending.is_empty) results
   818       else {
   819         if (progress.stopped)
   820           for ((_, (_, job)) <- running) job.terminate
   821 
   822         running.find({ case (_, (_, job)) => job.is_finished }) match {
   823           case Some((name, (parent_heap, job))) =>
   824             //{{{ finish job
   825 
   826             val res = job.join
   827             progress.echo(res.err)
   828 
   829             val heap =
   830               if (res.rc == 0) {
   831                 (output_dir + log(name)).file.delete
   832 
   833                 val sources = make_stamp(name)
   834                 val heap = heap_stamp(job.output_path)
   835                 File.write_gzip(output_dir + log_gz(name),
   836                   Library.terminate_lines(sources :: parent_heap :: heap :: res.out_lines))
   837 
   838                 heap
   839               }
   840               else {
   841                 (output_dir + Path.basic(name)).file.delete
   842                 (output_dir + log_gz(name)).file.delete
   843 
   844                 File.write(output_dir + log(name), Library.terminate_lines(res.out_lines))
   845                 progress.echo(name + " FAILED")
   846                 if (res.rc != Exn.Interrupt.return_code) {
   847                   progress.echo("(see also " + (output_dir + log(name)).file.toString + ")")
   848                   val lines = res.out_lines.filterNot(_.startsWith("\f"))
   849                   val tail = lines.drop(lines.length - 20 max 0)
   850                   progress.echo("\n" + cat_lines(tail))
   851                 }
   852 
   853                 no_heap
   854               }
   855             loop(pending - name, running - name,
   856               results + (name -> Result(false, heap, res.rc)))
   857             //}}}
   858           case None if (running.size < (max_jobs max 1)) =>
   859             //{{{ check/start next job
   860             pending.dequeue(running.isDefinedAt(_)) match {
   861               case Some((name, info)) =>
   862                 val parent_result =
   863                   info.parent match {
   864                     case None => Result(true, no_heap, 0)
   865                     case Some(parent) => results(parent)
   866                   }
   867                 val output = output_dir + Path.basic(name)
   868                 val do_output = build_heap || queue.is_inner(name)
   869 
   870                 val (current, heap) =
   871                 {
   872                   find_log(name + ".gz") match {
   873                     case Some((dir, path)) =>
   874                       read_stamps(path) match {
   875                         case Some((s, h1, h2)) =>
   876                           val heap = heap_stamp(Some(dir + Path.basic(name)))
   877                           (s == make_stamp(name) && h1 == parent_result.heap && h2 == heap &&
   878                             !(do_output && heap == no_heap), heap)
   879                         case None => (false, no_heap)
   880                       }
   881                     case None => (false, no_heap)
   882                   }
   883                 }
   884                 val all_current = current && parent_result.current
   885 
   886                 if (all_current)
   887                   loop(pending - name, running, results + (name -> Result(true, heap, 0)))
   888                 else if (no_build) {
   889                   if (verbose) progress.echo("Skipping " + name + " ...")
   890                   loop(pending - name, running, results + (name -> Result(false, heap, 1)))
   891                 }
   892                 else if (parent_result.rc == 0 && !progress.stopped) {
   893                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   894                   val job =
   895                     new Job(progress, name, info, output, do_output, verbose, browser_info,
   896                       queue.command_timings(name))
   897                   loop(pending, running + (name -> (parent_result.heap, job)), results)
   898                 }
   899                 else {
   900                   progress.echo(name + " CANCELLED")
   901                   loop(pending - name, running, results + (name -> Result(false, heap, 1)))
   902                 }
   903               case None => sleep(); loop(pending, running, results)
   904             }
   905             ///}}}
   906           case None => sleep(); loop(pending, running, results)
   907         }
   908       }
   909     }
   910 
   911 
   912     /* build results */
   913 
   914     val results =
   915       if (deps.is_empty) {
   916         progress.echo(Output.warning_text("Nothing to build"))
   917         Map.empty[String, Result]
   918       }
   919       else loop(queue, Map.empty, Map.empty)
   920 
   921 
   922     /* global browser info */
   923 
   924     if (!no_build) {
   925       val browser_chapters =
   926         (for {
   927           (name, result) <- results.iterator
   928           if result.rc == 0
   929           info = full_tree(name)
   930           if info.options.bool("browser_info")
   931         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   932             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   933 
   934       for ((chapter, entries) <- browser_chapters)
   935         Present.update_chapter_index(browser_info, chapter, entries)
   936 
   937       if (!browser_chapters.isEmpty && !(browser_info + Path.explode("index.html")).is_file)
   938       {
   939         Isabelle_System.mkdirs(browser_info)
   940         File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
   941           browser_info + Path.explode("isabelle.gif"))
   942         File.write(browser_info + Path.explode("index.html"),
   943           File.read(Path.explode("~~/lib/html/library_index_header.template")) +
   944           File.read(Path.explode("~~/lib/html/library_index_content.template")) +
   945           File.read(Path.explode("~~/lib/html/library_index_footer.template")))
   946       }
   947     }
   948 
   949 
   950     /* results */
   951 
   952     results.map({ case (name, result) => (name, result.rc) })
   953   }
   954 
   955 
   956   /* build */
   957 
   958   def build(
   959     options: Options,
   960     progress: Progress = Ignore_Progress,
   961     requirements: Boolean = false,
   962     all_sessions: Boolean = false,
   963     build_heap: Boolean = false,
   964     clean_build: Boolean = false,
   965     more_dirs: List[(Boolean, Path)] = Nil,
   966     session_groups: List[String] = Nil,
   967     max_jobs: Int = 1,
   968     list_files: Boolean = false,
   969     no_build: Boolean = false,
   970     system_mode: Boolean = false,
   971     verbose: Boolean = false,
   972     sessions: List[String] = Nil): Int =
   973   {
   974     val results =
   975       build_results(options, progress, requirements, all_sessions,
   976         build_heap, clean_build, more_dirs, session_groups, max_jobs, list_files, no_build,
   977         system_mode, verbose, sessions)
   978 
   979     val rc = (0 /: results)({ case (rc1, (_, rc2)) => rc1 max rc2 })
   980     if (rc != 0 && (verbose || !no_build)) {
   981       val unfinished =
   982         (for ((name, r) <- results.iterator if r != 0) yield name).toList.sorted
   983       progress.echo("Unfinished session(s): " + commas(unfinished))
   984     }
   985     rc
   986   }
   987 
   988 
   989   /* command line entry point */
   990 
   991   def main(args: Array[String])
   992   {
   993     Command_Line.tool {
   994       args.toList match {
   995         case
   996           Properties.Value.Boolean(requirements) ::
   997           Properties.Value.Boolean(all_sessions) ::
   998           Properties.Value.Boolean(build_heap) ::
   999           Properties.Value.Boolean(clean_build) ::
  1000           Properties.Value.Int(max_jobs) ::
  1001           Properties.Value.Boolean(list_files) ::
  1002           Properties.Value.Boolean(no_build) ::
  1003           Properties.Value.Boolean(system_mode) ::
  1004           Properties.Value.Boolean(verbose) ::
  1005           Command_Line.Chunks(select_dirs, include_dirs, session_groups, build_options, sessions) =>
  1006             val options = (Options.init() /: build_options)(_ + _)
  1007             val more_dirs =
  1008               select_dirs.map(d => (true, Path.explode(d))) :::
  1009               include_dirs.map(d => (false, Path.explode(d)))
  1010             val progress = new Console_Progress(verbose)
  1011             progress.interrupt_handler {
  1012               build(options, progress, requirements, all_sessions,
  1013                 build_heap, clean_build, more_dirs, session_groups, max_jobs, list_files, no_build,
  1014                 system_mode, verbose, sessions)
  1015             }
  1016         case _ => error("Bad arguments:\n" + cat_lines(args))
  1017       }
  1018     }
  1019   }
  1020 }
  1021