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