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