src/Pure/Tools/build.scala
author wenzelm
Wed Apr 23 12:39:23 2014 +0200 (2014-04-23)
changeset 56667 65e84b0ef974
parent 56533 cd8b6d849b6a
child 56668 56335a8e2e8b
permissions -rw-r--r--
more abstract Exn.Interrupt and POSIX return code;
     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           try {
   427             val (preloaded, parent_syntax) =
   428               info.parent match {
   429                 case None =>
   430                   (Set.empty[String], Outer_Syntax.init())
   431                 case Some(parent_name) =>
   432                   val parent = deps(parent_name)
   433                   (parent.loaded_theories, parent.syntax)
   434               }
   435             val resources = new Resources(preloaded, parent_syntax)
   436             val thy_info = new Thy_Info(resources)
   437 
   438             if (verbose || list_files) {
   439               val groups =
   440                 if (info.groups.isEmpty) ""
   441                 else info.groups.mkString(" (", " ", ")")
   442               progress.echo("Session " + info.chapter + "/" + name + groups)
   443             }
   444 
   445             val thy_deps =
   446               thy_info.dependencies(
   447                 info.theories.map(_._2).flatten.
   448                   map(thy => (resources.node_name(info.dir + Resources.thy_path(thy)), info.pos)))
   449 
   450             thy_deps.errors match {
   451               case Nil =>
   452               case errs => error(cat_lines(errs))
   453             }
   454 
   455             val loaded_theories = thy_deps.loaded_theories
   456             val keywords = thy_deps.keywords
   457             val syntax = thy_deps.syntax.asInstanceOf[Outer_Syntax]
   458 
   459             val loaded_files = if (inlined_files) thy_deps.loaded_files else Nil
   460 
   461             val all_files =
   462               (thy_deps.deps.map(dep => Path.explode(dep.name.node)) ::: loaded_files :::
   463                 info.files.map(file => info.dir + file) :::
   464                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   465 
   466             if (list_files) {
   467               progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
   468               for {
   469                 file <- all_files
   470                 if file.split_ext._2 == "ML"
   471               } {
   472                 val path = info.dir + file
   473                 try { Symbol.decode_strict(File.read(path)) }
   474                 catch {
   475                   case ERROR(msg) => cat_error(msg, "The error(s) above occurred in file " + path)
   476                 }
   477               }
   478             }
   479 
   480             val sources = all_files.map(p => (p, SHA1.digest(p.file)))
   481 
   482             deps + (name -> Session_Content(loaded_theories, keywords, syntax, sources))
   483           }
   484           catch {
   485             case ERROR(msg) =>
   486               cat_error(msg, "The error(s) above occurred in session " +
   487                 quote(name) + Position.here(info.pos))
   488           }
   489       }))
   490 
   491   def session_dependencies(
   492     options: Options,
   493     inlined_files: Boolean,
   494     dirs: List[Path],
   495     sessions: List[String]): Deps =
   496   {
   497     val (_, tree) =
   498       find_sessions(options, dirs.map((false, _))).selection(false, false, Nil, sessions)
   499     dependencies(Ignore_Progress, inlined_files, false, false, tree)
   500   }
   501 
   502   def session_content(
   503     options: Options,
   504     inlined_files: Boolean,
   505     dirs: List[Path],
   506     session: String): Session_Content =
   507   {
   508     session_dependencies(options, inlined_files, dirs, List(session))(session)
   509   }
   510 
   511   def outer_syntax(options: Options, session: String): Outer_Syntax =
   512     session_content(options, false, Nil, session).syntax
   513 
   514 
   515   /* jobs */
   516 
   517   private class Job(progress: Progress,
   518     name: String, val info: Session_Info, output: Path, do_output: Boolean,
   519     verbose: Boolean, browser_info: Path, command_timings: List[Properties.T])
   520   {
   521     def output_path: Option[Path] = if (do_output) Some(output) else None
   522 
   523     private val parent = info.parent.getOrElse("")
   524 
   525     private val args_file = Isabelle_System.tmp_file("args")
   526     File.write(args_file, YXML.string_of_body(
   527       if (is_pure(name)) Options.encode(info.options)
   528       else
   529         {
   530           import XML.Encode._
   531               pair(list(properties), pair(bool, pair(Options.encode, pair(bool, pair(Path.encode,
   532                 pair(list(pair(Path.encode, Path.encode)), pair(string, pair(string, pair(string,
   533                   list(pair(Options.encode, list(Path.encode))))))))))))(
   534               (command_timings, (do_output, (info.options, (verbose, (browser_info,
   535                 (info.document_files, (parent, (info.chapter, (name, info.theories))))))))))
   536         }))
   537 
   538     private val env =
   539       Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output),
   540         (if (is_pure(name)) "ISABELLE_PROCESS_OPTIONS" else "ARGS_FILE") ->
   541           Isabelle_System.posix_path(args_file))
   542 
   543     private val script =
   544       if (is_pure(name)) {
   545         if (do_output) "./build " + name + " \"$OUTPUT\""
   546         else """ rm -f "$OUTPUT"; ./build """ + name
   547       }
   548       else {
   549         """
   550         . "$ISABELLE_HOME/lib/scripts/timestart.bash"
   551         """ +
   552           (if (do_output)
   553             """
   554             "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
   555             """
   556           else
   557             """
   558             rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
   559             """) +
   560         """
   561         RC="$?"
   562 
   563         . "$ISABELLE_HOME/lib/scripts/timestop.bash"
   564 
   565         if [ "$RC" -eq 0 ]; then
   566           echo "Finished $TARGET ($TIMES_REPORT)" >&2
   567         fi
   568 
   569         exit "$RC"
   570         """
   571       }
   572 
   573     private val (thread, result) =
   574       Simple_Thread.future("build") {
   575         Isabelle_System.bash_env(info.dir.file, env, script,
   576           progress_stdout = (line: String) =>
   577             Library.try_unprefix("\floading_theory = ", line) match {
   578               case Some(theory) => progress.theory(name, theory)
   579               case None =>
   580             },
   581           progress_limit =
   582             info.options.int("process_output_limit") match {
   583               case 0 => None
   584               case m => Some(m * 1000000L)
   585             })
   586       }
   587 
   588     def terminate: Unit = thread.interrupt
   589     def is_finished: Boolean = result.is_finished
   590 
   591     @volatile private var timeout = false
   592     private val time = info.options.seconds("timeout")
   593     private val timer: Option[Timer] =
   594       if (time.seconds > 0.0) {
   595         val t = new Timer("build", true)
   596         t.schedule(new TimerTask { def run = { terminate; timeout = true } }, time.ms)
   597         Some(t)
   598       }
   599       else None
   600 
   601     def join: Isabelle_System.Bash_Result =
   602     {
   603       val res = result.join
   604 
   605       args_file.delete
   606       timer.map(_.cancel())
   607 
   608       if (res.rc == Exn.Interrupt.return_code) {
   609         if (timeout) res.add_err("*** Timeout").set_rc(1)
   610         else res.add_err("*** 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         System.err.println("### Ignoring bad log file: " + path +
   762           (if (msg == "") "" else "\n" + msg))
   763         (Nil, 0.0)
   764       }
   765 
   766       try {
   767         val info = parse_log(false, text)
   768         val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
   769         (info.command_timings, session_timing)
   770       }
   771       catch {
   772         case ERROR(msg) => ignore_error(msg)
   773         case exn: java.lang.Error => ignore_error(Exn.message(exn))
   774         case _: XML.Error => ignore_error("")
   775       }
   776     }
   777 
   778     val queue = Queue(selected_tree, load_timings)
   779 
   780 
   781     /* main build process */
   782 
   783     // prepare log dir
   784     Isabelle_System.mkdirs(output_dir + LOG)
   785 
   786     // optional cleanup
   787     if (clean_build) {
   788       for (name <- full_tree.graph.all_succs(selected)) {
   789         val files =
   790           List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
   791         if (!files.isEmpty) progress.echo("Cleaning " + name + " ...")
   792         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   793       }
   794     }
   795 
   796     // scheduler loop
   797     case class Result(current: Boolean, heap: String, rc: Int)
   798 
   799     def sleep(): Unit = Thread.sleep(500)
   800 
   801     @tailrec def loop(
   802       pending: Queue,
   803       running: Map[String, (String, Job)],
   804       results: Map[String, Result]): Map[String, Result] =
   805     {
   806       if (pending.is_empty) results
   807       else {
   808         if (progress.stopped)
   809           for ((_, (_, job)) <- running) job.terminate
   810 
   811         running.find({ case (_, (_, job)) => job.is_finished }) match {
   812           case Some((name, (parent_heap, job))) =>
   813             //{{{ finish job
   814 
   815             val res = job.join
   816             progress.echo(res.err)
   817 
   818             val heap =
   819               if (res.rc == 0) {
   820                 (output_dir + log(name)).file.delete
   821 
   822                 val sources = make_stamp(name)
   823                 val heap = heap_stamp(job.output_path)
   824                 File.write_gzip(output_dir + log_gz(name),
   825                   Library.terminate_lines(sources :: parent_heap :: heap :: res.out_lines))
   826 
   827                 heap
   828               }
   829               else {
   830                 (output_dir + Path.basic(name)).file.delete
   831                 (output_dir + log_gz(name)).file.delete
   832 
   833                 File.write(output_dir + log(name), Library.terminate_lines(res.out_lines))
   834                 progress.echo(name + " FAILED")
   835                 if (res.rc != Exn.Interrupt.return_code) {
   836                   progress.echo("(see also " + (output_dir + log(name)).file.toString + ")")
   837                   val lines = res.out_lines.filterNot(_.startsWith("\f"))
   838                   val tail = lines.drop(lines.length - 20 max 0)
   839                   progress.echo("\n" + cat_lines(tail))
   840                 }
   841 
   842                 no_heap
   843               }
   844             loop(pending - name, running - name,
   845               results + (name -> Result(false, heap, res.rc)))
   846             //}}}
   847           case None if (running.size < (max_jobs max 1)) =>
   848             //{{{ check/start next job
   849             pending.dequeue(running.isDefinedAt(_)) match {
   850               case Some((name, info)) =>
   851                 val parent_result =
   852                   info.parent match {
   853                     case None => Result(true, no_heap, 0)
   854                     case Some(parent) => results(parent)
   855                   }
   856                 val output = output_dir + Path.basic(name)
   857                 val do_output = build_heap || queue.is_inner(name)
   858 
   859                 val (current, heap) =
   860                 {
   861                   find_log(name + ".gz") match {
   862                     case Some((dir, path)) =>
   863                       read_stamps(path) match {
   864                         case Some((s, h1, h2)) =>
   865                           val heap = heap_stamp(Some(dir + Path.basic(name)))
   866                           (s == make_stamp(name) && h1 == parent_result.heap && h2 == heap &&
   867                             !(do_output && heap == no_heap), heap)
   868                         case None => (false, no_heap)
   869                       }
   870                     case None => (false, no_heap)
   871                   }
   872                 }
   873                 val all_current = current && parent_result.current
   874 
   875                 if (all_current)
   876                   loop(pending - name, running, results + (name -> Result(true, heap, 0)))
   877                 else if (no_build) {
   878                   if (verbose) progress.echo("Skipping " + name + " ...")
   879                   loop(pending - name, running, results + (name -> Result(false, heap, 1)))
   880                 }
   881                 else if (parent_result.rc == 0 && !progress.stopped) {
   882                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   883                   val job =
   884                     new Job(progress, name, info, output, do_output, verbose, browser_info,
   885                       queue.command_timings(name))
   886                   loop(pending, running + (name -> (parent_result.heap, job)), results)
   887                 }
   888                 else {
   889                   progress.echo(name + " CANCELLED")
   890                   loop(pending - name, running, results + (name -> Result(false, heap, 1)))
   891                 }
   892               case None => sleep(); loop(pending, running, results)
   893             }
   894             ///}}}
   895           case None => sleep(); loop(pending, running, results)
   896         }
   897       }
   898     }
   899 
   900 
   901     /* build results */
   902 
   903     val results =
   904       if (deps.is_empty) {
   905         progress.echo("### Nothing to build")
   906         Map.empty[String, Result]
   907       }
   908       else loop(queue, Map.empty, Map.empty)
   909 
   910 
   911     /* global browser info */
   912 
   913     if (!no_build) {
   914       val browser_chapters =
   915         (for {
   916           (name, result) <- results.iterator
   917           if result.rc == 0
   918           info = full_tree(name)
   919           if info.options.bool("browser_info")
   920         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   921             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   922 
   923       for ((chapter, entries) <- browser_chapters)
   924         Present.update_chapter_index(browser_info, chapter, entries)
   925 
   926       if (!browser_chapters.isEmpty && !(browser_info + Path.explode("index.html")).is_file)
   927       {
   928         Isabelle_System.mkdirs(browser_info)
   929         File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
   930           browser_info + Path.explode("isabelle.gif"))
   931         File.write(browser_info + Path.explode("index.html"),
   932           File.read(Path.explode("~~/lib/html/library_index_header.template")) +
   933           File.read(Path.explode("~~/lib/html/library_index_content.template")) +
   934           File.read(Path.explode("~~/lib/html/library_index_footer.template")))
   935       }
   936     }
   937 
   938 
   939     /* results */
   940 
   941     results.map({ case (name, result) => (name, result.rc) })
   942   }
   943 
   944 
   945   /* build */
   946 
   947   def build(
   948     options: Options,
   949     progress: Progress = Ignore_Progress,
   950     requirements: Boolean = false,
   951     all_sessions: Boolean = false,
   952     build_heap: Boolean = false,
   953     clean_build: Boolean = false,
   954     more_dirs: List[(Boolean, Path)] = Nil,
   955     session_groups: List[String] = Nil,
   956     max_jobs: Int = 1,
   957     list_files: Boolean = false,
   958     no_build: Boolean = false,
   959     system_mode: Boolean = false,
   960     verbose: Boolean = false,
   961     sessions: List[String] = Nil): Int =
   962   {
   963     val results =
   964       build_results(options, progress, requirements, all_sessions,
   965         build_heap, clean_build, more_dirs, session_groups, max_jobs, list_files, no_build,
   966         system_mode, verbose, sessions)
   967 
   968     val rc = (0 /: results)({ case (rc1, (_, rc2)) => rc1 max rc2 })
   969     if (rc != 0 && (verbose || !no_build)) {
   970       val unfinished =
   971         (for ((name, r) <- results.iterator if r != 0) yield name).toList.sorted
   972       progress.echo("Unfinished session(s): " + commas(unfinished))
   973     }
   974     rc
   975   }
   976 
   977 
   978   /* command line entry point */
   979 
   980   def main(args: Array[String])
   981   {
   982     Command_Line.tool {
   983       args.toList match {
   984         case
   985           Properties.Value.Boolean(requirements) ::
   986           Properties.Value.Boolean(all_sessions) ::
   987           Properties.Value.Boolean(build_heap) ::
   988           Properties.Value.Boolean(clean_build) ::
   989           Properties.Value.Int(max_jobs) ::
   990           Properties.Value.Boolean(list_files) ::
   991           Properties.Value.Boolean(no_build) ::
   992           Properties.Value.Boolean(system_mode) ::
   993           Properties.Value.Boolean(verbose) ::
   994           Command_Line.Chunks(select_dirs, include_dirs, session_groups, build_options, sessions) =>
   995             val options = (Options.init() /: build_options)(_ + _)
   996             val more_dirs =
   997               select_dirs.map(d => (true, Path.explode(d))) :::
   998               include_dirs.map(d => (false, Path.explode(d)))
   999             val progress = new Console_Progress(verbose)
  1000             progress.interrupt_handler {
  1001               build(options, progress, requirements, all_sessions,
  1002                 build_heap, clean_build, more_dirs, session_groups, max_jobs, list_files, no_build,
  1003                 system_mode, verbose, sessions)
  1004             }
  1005         case _ => error("Bad arguments:\n" + cat_lines(args))
  1006       }
  1007     }
  1008   }
  1009 }
  1010