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