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