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