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