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