src/Pure/Tools/build.scala
author wenzelm
Fri Oct 09 16:09:16 2015 +0200 (2015-10-09)
changeset 61372 cf40b6b1de54
parent 61276 8a4bd05c1735
child 61375 0f91067f6f73
permissions -rw-r--r--
more Present operations on Scala side;
     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   /** session information **/
    23 
    24   // external version
    25   abstract class Entry
    26   sealed case class Chapter(name: String) extends Entry
    27   sealed case class Session_Entry(
    28     pos: Position.T,
    29     name: String,
    30     groups: List[String],
    31     path: String,
    32     parent: Option[String],
    33     description: String,
    34     options: List[Options.Spec],
    35     theories: List[(Boolean, List[Options.Spec], List[String])],
    36     files: List[String],
    37     document_files: List[(String, String)]) extends Entry
    38 
    39   // internal version
    40   sealed case class Session_Info(
    41     chapter: String,
    42     select: Boolean,
    43     pos: Position.T,
    44     groups: List[String],
    45     dir: Path,
    46     parent: Option[String],
    47     description: String,
    48     options: Options,
    49     theories: List[(Boolean, Options, List[Path])],
    50     files: List[Path],
    51     document_files: List[(Path, Path)],
    52     entry_digest: SHA1.Digest)
    53 
    54   def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
    55 
    56   def session_info(options: Options, select: Boolean, dir: Path,
    57       chapter: String, entry: Session_Entry): (String, Session_Info) =
    58     try {
    59       val name = entry.name
    60 
    61       if (name == "") error("Bad session name")
    62       if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
    63       if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
    64 
    65       val session_options = options ++ entry.options
    66 
    67       val theories =
    68         entry.theories.map({ case (global, opts, thys) =>
    69           (global, session_options ++ opts, thys.map(Path.explode(_))) })
    70       val files = entry.files.map(Path.explode(_))
    71       val document_files =
    72         entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
    73 
    74       val entry_digest =
    75         SHA1.digest((chapter, name, entry.parent, entry.options,
    76           entry.theories, entry.files, entry.document_files).toString)
    77 
    78       val info =
    79         Session_Info(chapter, select, entry.pos, entry.groups, dir + Path.explode(entry.path),
    80           entry.parent, entry.description, session_options, theories, files,
    81           document_files, entry_digest)
    82 
    83       (name, info)
    84     }
    85     catch {
    86       case ERROR(msg) =>
    87         error(msg + "\nThe error(s) above occurred in session entry " +
    88           quote(entry.name) + Position.here(entry.pos))
    89     }
    90 
    91 
    92   /* session tree */
    93 
    94   object Session_Tree
    95   {
    96     def apply(infos: Seq[(String, Session_Info)]): Session_Tree =
    97     {
    98       val graph1 =
    99         (Graph.string[Session_Info] /: infos) {
   100           case (graph, (name, info)) =>
   101             if (graph.defined(name))
   102               error("Duplicate session " + quote(name) + Position.here(info.pos) +
   103                 Position.here(graph.get_node(name).pos))
   104             else graph.new_node(name, info)
   105         }
   106       val graph2 =
   107         (graph1 /: graph1.iterator) {
   108           case (graph, (name, (info, _))) =>
   109             info.parent match {
   110               case None => graph
   111               case Some(parent) =>
   112                 if (!graph.defined(parent))
   113                   error("Bad parent session " + quote(parent) + " for " +
   114                     quote(name) + Position.here(info.pos))
   115 
   116                 try { graph.add_edge_acyclic(parent, name) }
   117                 catch {
   118                   case exn: Graph.Cycles[_] =>
   119                     error(cat_lines(exn.cycles.map(cycle =>
   120                       "Cyclic session dependency of " +
   121                         cycle.map(c => quote(c.toString)).mkString(" via "))) +
   122                           Position.here(info.pos))
   123                 }
   124             }
   125         }
   126       new Session_Tree(graph2)
   127     }
   128   }
   129 
   130   final class Session_Tree private(val graph: Graph[String, Session_Info])
   131     extends PartialFunction[String, Session_Info]
   132   {
   133     def apply(name: String): Session_Info = graph.get_node(name)
   134     def isDefinedAt(name: String): Boolean = graph.defined(name)
   135 
   136     def selection(
   137       requirements: Boolean = false,
   138       all_sessions: Boolean = false,
   139       exclude_session_groups: List[String] = Nil,
   140       exclude_sessions: List[String] = Nil,
   141       session_groups: List[String] = Nil,
   142       sessions: List[String] = Nil): (List[String], Session_Tree) =
   143     {
   144       val bad_sessions =
   145         SortedSet((exclude_sessions ::: sessions).filterNot(isDefinedAt(_)): _*).toList
   146       if (bad_sessions.nonEmpty) error("Undefined session(s): " + commas_quote(bad_sessions))
   147 
   148       val excluded =
   149       {
   150         val exclude_group = exclude_session_groups.toSet
   151         val exclude_group_sessions =
   152           (for {
   153             (name, (info, _)) <- graph.iterator
   154             if apply(name).groups.exists(exclude_group)
   155           } yield name).toList
   156         graph.all_succs(exclude_group_sessions ::: exclude_sessions).toSet
   157       }
   158 
   159       val pre_selected =
   160       {
   161         if (all_sessions) graph.keys
   162         else {
   163           val select_group = session_groups.toSet
   164           val select = sessions.toSet
   165           (for {
   166             (name, (info, _)) <- graph.iterator
   167             if info.select || select(name) || apply(name).groups.exists(select_group)
   168           } yield name).toList
   169         }
   170       }.filterNot(excluded)
   171 
   172       val selected =
   173         if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
   174         else pre_selected
   175 
   176       val graph1 = graph.restrict(graph.all_preds(selected).toSet)
   177       (selected, new Session_Tree(graph1))
   178     }
   179 
   180     def topological_order: List[(String, Session_Info)] =
   181       graph.topological_order.map(name => (name, apply(name)))
   182 
   183     override def toString: String = graph.keys_iterator.mkString("Session_Tree(", ", ", ")")
   184   }
   185 
   186 
   187   /* parser */
   188 
   189   val chapter_default = "Unsorted"
   190 
   191   private val CHAPTER = "chapter"
   192   private val SESSION = "session"
   193   private val IN = "in"
   194   private val DESCRIPTION = "description"
   195   private val OPTIONS = "options"
   196   private val GLOBAL_THEORIES = "global_theories"
   197   private val THEORIES = "theories"
   198   private val FILES = "files"
   199   private val DOCUMENT_FILES = "document_files"
   200 
   201   lazy val root_syntax =
   202     Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" +
   203       (CHAPTER, Keyword.THY_DECL) + (SESSION, Keyword.THY_DECL) +
   204       IN + DESCRIPTION + OPTIONS + GLOBAL_THEORIES + THEORIES + FILES + DOCUMENT_FILES
   205 
   206   object Parser extends Parse.Parser
   207   {
   208     private val chapter: Parser[Chapter] =
   209     {
   210       val chapter_name = atom("chapter name", _.is_name)
   211 
   212       command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
   213     }
   214 
   215     private val session_entry: Parser[Session_Entry] =
   216     {
   217       val session_name = atom("session name", _.is_name)
   218 
   219       val option =
   220         name ~ opt($$$("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
   221       val options = $$$("[") ~> rep1sep(option, $$$(",")) <~ $$$("]")
   222 
   223       val theories =
   224         ($$$(GLOBAL_THEORIES) | $$$(THEORIES)) ~!
   225           ((options | success(Nil)) ~ rep(theory_xname)) ^^
   226           { case x ~ (y ~ z) => (x == GLOBAL_THEORIES, y, z) }
   227 
   228       val document_files =
   229         $$$(DOCUMENT_FILES) ~!
   230           (($$$("(") ~! ($$$(IN) ~! (path ~ $$$(")"))) ^^
   231               { case _ ~ (_ ~ (x ~ _)) => x } | success("document")) ~
   232             rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
   233 
   234       command(SESSION) ~!
   235         (position(session_name) ~
   236           (($$$("(") ~! (rep1(name) <~ $$$(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
   237           (($$$(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
   238           ($$$("=") ~!
   239             (opt(session_name ~! $$$("+") ^^ { case x ~ _ => x }) ~
   240               (($$$(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
   241               (($$$(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
   242               rep1(theories) ~
   243               (($$$(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil)) ~
   244               (rep(document_files) ^^ (x => x.flatten))))) ^^
   245         { case _ ~ ((a, pos) ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i))) =>
   246             Session_Entry(pos, a, b, c, d, e, f, g, h, i) }
   247     }
   248 
   249     def parse_entries(root: Path): List[(String, Session_Entry)] =
   250     {
   251       val toks = Token.explode(root_syntax.keywords, File.read(root))
   252       val start = Token.Pos.file(root.implode)
   253 
   254       parse_all(rep(chapter | session_entry), Token.reader(toks, start)) match {
   255         case Success(result, _) =>
   256           var chapter = chapter_default
   257           val entries = new mutable.ListBuffer[(String, Session_Entry)]
   258           result.foreach {
   259             case Chapter(name) => chapter = name
   260             case session_entry: Session_Entry => entries += ((chapter, session_entry))
   261           }
   262           entries.toList
   263         case bad => error(bad.toString)
   264       }
   265     }
   266   }
   267 
   268 
   269   /* find sessions within certain directories */
   270 
   271   private val ROOT = Path.explode("ROOT")
   272   private val ROOTS = Path.explode("ROOTS")
   273 
   274   private def is_session_dir(dir: Path): Boolean =
   275     (dir + ROOT).is_file || (dir + ROOTS).is_file
   276 
   277   private def check_session_dir(dir: Path): Path =
   278     if (is_session_dir(dir)) dir
   279     else error("Bad session root directory: " + dir.toString)
   280 
   281   def find_sessions(options: Options, dirs: List[Path] = Nil, select_dirs: List[Path] = Nil)
   282     : Session_Tree =
   283   {
   284     def find_dir(select: Boolean, dir: Path): List[(String, Session_Info)] =
   285       find_root(select, dir) ::: find_roots(select, dir)
   286 
   287     def find_root(select: Boolean, dir: Path): List[(String, Session_Info)] =
   288     {
   289       val root = dir + ROOT
   290       if (root.is_file)
   291         Parser.parse_entries(root).map(p => session_info(options, select, dir, p._1, p._2))
   292       else Nil
   293     }
   294 
   295     def find_roots(select: Boolean, dir: Path): List[(String, Session_Info)] =
   296     {
   297       val roots = dir + ROOTS
   298       if (roots.is_file) {
   299         for {
   300           line <- split_lines(File.read(roots))
   301           if !(line == "" || line.startsWith("#"))
   302           dir1 =
   303             try { check_session_dir(dir + Path.explode(line)) }
   304             catch {
   305               case ERROR(msg) =>
   306                 error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
   307             }
   308           info <- find_dir(select, dir1)
   309         } yield info
   310       }
   311       else Nil
   312     }
   313 
   314     val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
   315     dirs.foreach(check_session_dir(_))
   316     select_dirs.foreach(check_session_dir(_))
   317 
   318     Session_Tree(
   319       for {
   320         (select, dir) <- (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _))
   321         info <- find_dir(select, dir)
   322       } yield info)
   323   }
   324 
   325 
   326 
   327   /** build **/
   328 
   329   /* queue */
   330 
   331   object Queue
   332   {
   333     def apply(tree: Session_Tree, load_timings: String => (List[Properties.T], Double)): Queue =
   334     {
   335       val graph = tree.graph
   336       val sessions = graph.keys
   337 
   338       val timings = Par_List.map((name: String) => (name, load_timings(name)), sessions)
   339       val command_timings =
   340         Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
   341       val session_timing =
   342         Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
   343 
   344       def outdegree(name: String): Int = graph.imm_succs(name).size
   345       def timeout(name: String): Double = tree(name).options.real("timeout")
   346 
   347       object Ordering extends scala.math.Ordering[String]
   348       {
   349         def compare_timing(name1: String, name2: String): Int =
   350         {
   351           val t1 = session_timing(name1)
   352           val t2 = session_timing(name2)
   353           if (t1 == 0.0 || t2 == 0.0) 0
   354           else t1 compare t2
   355         }
   356 
   357         def compare(name1: String, name2: String): Int =
   358           outdegree(name2) compare outdegree(name1) match {
   359             case 0 =>
   360               compare_timing(name2, name1) match {
   361                 case 0 =>
   362                   timeout(name2) compare timeout(name1) match {
   363                     case 0 => name1 compare name2
   364                     case ord => ord
   365                   }
   366                 case ord => ord
   367               }
   368             case ord => ord
   369           }
   370       }
   371 
   372       new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
   373     }
   374   }
   375 
   376   final class Queue private(
   377     graph: Graph[String, Session_Info],
   378     order: SortedSet[String],
   379     val command_timings: String => List[Properties.T])
   380   {
   381     def is_inner(name: String): Boolean = !graph.is_maximal(name)
   382 
   383     def is_empty: Boolean = graph.is_empty
   384 
   385     def - (name: String): Queue =
   386       new Queue(graph.del_node(name),
   387         order - name,  // FIXME scala-2.10.0 TreeSet problem!?
   388         command_timings)
   389 
   390     def dequeue(skip: String => Boolean): Option[(String, Session_Info)] =
   391     {
   392       val it = order.iterator.dropWhile(name =>
   393         skip(name)
   394           || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
   395           || !graph.is_minimal(name))
   396       if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
   397       else None
   398     }
   399   }
   400 
   401 
   402   /* source dependencies and static content */
   403 
   404   sealed case class Session_Content(
   405     loaded_theories: Set[String],
   406     known_theories: Map[String, Document.Node.Name],
   407     keywords: Thy_Header.Keywords,
   408     syntax: Outer_Syntax,
   409     sources: List[(Path, SHA1.Digest)],
   410     session_graph: Graph_Display.Graph)
   411 
   412   sealed case class Deps(deps: Map[String, Session_Content])
   413   {
   414     def is_empty: Boolean = deps.isEmpty
   415     def apply(name: String): Session_Content = deps(name)
   416     def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
   417   }
   418 
   419   def dependencies(
   420       progress: Progress = Ignore_Progress,
   421       inlined_files: Boolean = false,
   422       verbose: Boolean = false,
   423       list_files: Boolean = false,
   424       check_keywords: Set[String] = Set.empty,
   425       tree: Session_Tree): Deps =
   426     Deps((Map.empty[String, Session_Content] /: tree.topological_order)(
   427       { case (deps, (name, info)) =>
   428           if (progress.stopped) throw Exn.Interrupt()
   429 
   430           try {
   431             val (loaded_theories0, known_theories0, syntax0) =
   432               info.parent.map(deps(_)) match {
   433                 case None =>
   434                   (Set.empty[String], Map.empty[String, Document.Node.Name],
   435                     Thy_Header.bootstrap_syntax)
   436                 case Some(parent) =>
   437                   (parent.loaded_theories, parent.known_theories, parent.syntax)
   438               }
   439             val resources = new Resources(loaded_theories0, known_theories0, syntax0)
   440             val thy_info = new Thy_Info(resources)
   441 
   442             if (verbose || list_files) {
   443               val groups =
   444                 if (info.groups.isEmpty) ""
   445                 else info.groups.mkString(" (", " ", ")")
   446               progress.echo("Session " + info.chapter + "/" + name + groups)
   447             }
   448 
   449             val thy_deps =
   450             {
   451               val root_theories =
   452                 info.theories.flatMap({
   453                   case (global, _, thys) =>
   454                     thys.map(thy =>
   455                       (resources.node_name(
   456                         if (global) "" else name, info.dir + Resources.thy_path(thy)), info.pos))
   457                 })
   458               val thy_deps = thy_info.dependencies(name, root_theories)
   459 
   460               thy_deps.errors match {
   461                 case Nil => thy_deps
   462                 case errs => error(cat_lines(errs))
   463               }
   464             }
   465 
   466             val known_theories =
   467               (known_theories0 /: thy_deps.deps)({ case (known, dep) =>
   468                 val name = dep.name
   469                 known.get(name.theory) match {
   470                   case Some(name1) if name != name1 =>
   471                     error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
   472                   case _ =>
   473                     known + (name.theory -> name) + (Long_Name.base_name(name.theory) -> name)
   474                 }
   475               })
   476 
   477             val loaded_theories = thy_deps.loaded_theories
   478             val keywords = thy_deps.keywords
   479             val syntax = thy_deps.syntax.asInstanceOf[Outer_Syntax]
   480 
   481             val theory_files = thy_deps.deps.map(dep => Path.explode(dep.name.node))
   482             val loaded_files = if (inlined_files) thy_deps.loaded_files else Nil
   483 
   484             val all_files =
   485               (theory_files ::: loaded_files :::
   486                 info.files.map(file => info.dir + file) :::
   487                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   488 
   489             if (list_files)
   490               progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
   491 
   492             if (check_keywords.nonEmpty)
   493               Check_Keywords.check_keywords(progress, syntax.keywords, check_keywords, theory_files)
   494 
   495             val sources = all_files.map(p => (p, SHA1.digest(p.file)))
   496 
   497             val session_graph =
   498               Present.session_graph(info.parent getOrElse "", loaded_theories0, thy_deps.deps)
   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(sessions = sessions)
   519     dependencies(inlined_files = inlined_files, tree = 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, (File.standard_path(graph_file), (parent,
   561                 (info.chapter, (name, theories)))))))))))
   562         }))
   563 
   564     private val env =
   565       Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> File.standard_path(output),
   566         (if (is_pure(name)) "ISABELLE_PROCESS_OPTIONS" else "ARGS_FILE") ->
   567           File.standard_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: Bash.Result =
   628     {
   629       val res = result.join
   630 
   631       if (res.rc == 0 && !is_pure(name))
   632         Present.finish(progress, browser_info, graph_file, info, name)
   633 
   634       graph_file.delete
   635       args_file.delete
   636       timeout_request.foreach(_.cancel)
   637 
   638       if (res.rc == Exn.Interrupt.return_code) {
   639         if (was_timeout) res.add_err(Output.error_text("Timeout")).set_rc(1)
   640         else res.add_err(Output.error_text("Interrupt"))
   641       }
   642       else res
   643     }
   644   }
   645 
   646 
   647   /* inlined properties (YXML) */
   648 
   649   object Props
   650   {
   651     def parse(text: String): Properties.T = XML.Decode.properties(YXML.parse_body(text))
   652 
   653     def parse_lines(prefix: String, lines: List[String]): List[Properties.T] =
   654       for (line <- lines; s <- Library.try_unprefix(prefix, line)) yield parse(s)
   655 
   656     def find_parse_line(prefix: String, lines: List[String]): Option[Properties.T] =
   657       lines.find(_.startsWith(prefix)).map(line => parse(line.substring(prefix.length)))
   658   }
   659 
   660 
   661   /* log files */
   662 
   663   private val LOG = Path.explode("log")
   664   private def log(name: String): Path = LOG + Path.basic(name)
   665   private def log_gz(name: String): Path = log(name).ext("gz")
   666 
   667   private val SESSION_NAME = "\fSession.name = "
   668 
   669 
   670   sealed case class Log_Info(
   671     name: String,
   672     stats: List[Properties.T],
   673     tasks: List[Properties.T],
   674     command_timings: List[Properties.T],
   675     session_timing: Properties.T)
   676 
   677   def parse_log(full_stats: Boolean, text: String): Log_Info =
   678   {
   679     val lines = split_lines(text)
   680     val xml_cache = new XML.Cache()
   681     def parse_lines(prfx: String): List[Properties.T] =
   682       Props.parse_lines(prfx, lines).map(xml_cache.props(_))
   683 
   684     val name =
   685       lines.find(_.startsWith(SESSION_NAME)).map(_.substring(SESSION_NAME.length)) getOrElse ""
   686     val stats = if (full_stats) parse_lines("\fML_statistics = ") else Nil
   687     val tasks = if (full_stats) parse_lines("\ftask_statistics = ") else Nil
   688     val command_timings = parse_lines("\fcommand_timing = ")
   689     val session_timing = Props.find_parse_line("\fTiming = ", lines) getOrElse Nil
   690     Log_Info(name, stats, tasks, command_timings, session_timing)
   691   }
   692 
   693 
   694   /* sources and heaps */
   695 
   696   private def sources_stamp(digests: List[SHA1.Digest]): String =
   697     digests.map(_.toString).sorted.mkString("sources: ", " ", "")
   698 
   699   private val no_heap: String = "heap: -"
   700 
   701   private def heap_stamp(heap: Option[Path]): String =
   702   {
   703     "heap: " +
   704       (heap match {
   705         case Some(path) =>
   706           val file = path.file
   707           if (file.isFile) file.length.toString + " " + file.lastModified.toString
   708           else "-"
   709         case None => "-"
   710       })
   711   }
   712 
   713   private def read_stamps(path: Path): Option[(String, String, String)] =
   714     if (path.is_file) {
   715       val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(path.file)))
   716       val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
   717       val (s, h1, h2) =
   718         try { (reader.readLine, reader.readLine, reader.readLine) }
   719         finally { reader.close }
   720       if (s != null && s.startsWith("sources: ") &&
   721           h1 != null && h1.startsWith("heap: ") &&
   722           h2 != null && h2.startsWith("heap: ")) Some((s, h1, h2))
   723       else None
   724     }
   725     else None
   726 
   727 
   728   /* build_results */
   729 
   730   def build_results(
   731     options: Options,
   732     progress: Progress = Ignore_Progress,
   733     requirements: Boolean = false,
   734     all_sessions: Boolean = false,
   735     build_heap: Boolean = false,
   736     clean_build: Boolean = false,
   737     dirs: List[Path] = Nil,
   738     select_dirs: List[Path] = Nil,
   739     exclude_session_groups: List[String] = Nil,
   740     session_groups: List[String] = Nil,
   741     max_jobs: Int = 1,
   742     list_files: Boolean = false,
   743     check_keywords: Set[String] = Set.empty,
   744     no_build: Boolean = false,
   745     system_mode: Boolean = false,
   746     verbose: Boolean = false,
   747     exclude_sessions: List[String] = Nil,
   748     sessions: List[String] = Nil): Map[String, Int] =
   749   {
   750     /* session tree and dependencies */
   751 
   752     val full_tree = find_sessions(options.int("completion_limit") = 0, dirs, select_dirs)
   753     val (selected, selected_tree) =
   754       full_tree.selection(requirements, all_sessions,
   755         exclude_session_groups, exclude_sessions, session_groups, sessions)
   756 
   757     val deps = dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
   758 
   759     def make_stamp(name: String): String =
   760       sources_stamp(selected_tree(name).entry_digest :: deps.sources(name))
   761 
   762 
   763     /* persistent information */
   764 
   765     val (input_dirs, output_dir, browser_info) =
   766       if (system_mode) {
   767         val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
   768         (List(output_dir), output_dir, Path.explode("~~/browser_info"))
   769       }
   770       else {
   771         val output_dir = Path.explode("$ISABELLE_OUTPUT")
   772         (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
   773          Path.explode("$ISABELLE_BROWSER_INFO"))
   774       }
   775 
   776     def find_log(name: String): Option[(Path, Path)] =
   777       input_dirs.find(dir => (dir + log(name)).is_file).map(dir => (dir, dir + log(name)))
   778 
   779 
   780     /* queue with scheduling information */
   781 
   782     def load_timings(name: String): (List[Properties.T], Double) =
   783     {
   784       val (path, text) =
   785         find_log(name + ".gz") match {
   786           case Some((_, path)) => (path, File.read_gzip(path))
   787           case None =>
   788             find_log(name) match {
   789               case Some((_, path)) => (path, File.read(path))
   790               case None => (Path.current, "")
   791             }
   792         }
   793 
   794       def ignore_error(msg: String): (List[Properties.T], Double) =
   795       {
   796         Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
   797         (Nil, 0.0)
   798       }
   799 
   800       try {
   801         val info = parse_log(false, text)
   802         val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
   803         (info.command_timings, session_timing)
   804       }
   805       catch {
   806         case ERROR(msg) => ignore_error(msg)
   807         case exn: java.lang.Error => ignore_error(Exn.message(exn))
   808         case _: XML.Error => ignore_error("")
   809       }
   810     }
   811 
   812     val queue = Queue(selected_tree, load_timings)
   813 
   814 
   815     /* main build process */
   816 
   817     // prepare log dir
   818     Isabelle_System.mkdirs(output_dir + LOG)
   819 
   820     // optional cleanup
   821     if (clean_build) {
   822       for (name <- full_tree.graph.all_succs(selected)) {
   823         val files =
   824           List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
   825         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   826         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   827       }
   828     }
   829 
   830     // scheduler loop
   831     case class Result(current: Boolean, heap: String, rc: Int)
   832 
   833     def sleep()
   834     {
   835       try { Thread.sleep(500) }
   836       catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
   837     }
   838 
   839     @tailrec def loop(
   840       pending: Queue,
   841       running: Map[String, (String, Job)],
   842       results: Map[String, Result]): Map[String, Result] =
   843     {
   844       if (pending.is_empty) results
   845       else {
   846         if (progress.stopped)
   847           for ((_, (_, job)) <- running) job.terminate
   848 
   849         running.find({ case (_, (_, job)) => job.is_finished }) match {
   850           case Some((name, (parent_heap, job))) =>
   851             //{{{ finish job
   852 
   853             val res = job.join
   854             progress.echo(res.err)
   855 
   856             val heap =
   857               if (res.rc == 0) {
   858                 (output_dir + log(name)).file.delete
   859 
   860                 val sources = make_stamp(name)
   861                 val heap = heap_stamp(job.output_path)
   862                 File.write_gzip(output_dir + log_gz(name),
   863                   Library.terminate_lines(sources :: parent_heap :: heap :: res.out_lines))
   864 
   865                 heap
   866               }
   867               else {
   868                 (output_dir + Path.basic(name)).file.delete
   869                 (output_dir + log_gz(name)).file.delete
   870 
   871                 File.write(output_dir + log(name), Library.terminate_lines(res.out_lines))
   872                 progress.echo(name + " FAILED")
   873                 if (res.rc != Exn.Interrupt.return_code) {
   874                   progress.echo("(see also " + (output_dir + log(name)).file.toString + ")")
   875                   val lines = res.out_lines.filterNot(_.startsWith("\f"))
   876                   val tail = lines.drop(lines.length - 20 max 0)
   877                   progress.echo("\n" + cat_lines(tail))
   878                 }
   879 
   880                 no_heap
   881               }
   882             loop(pending - name, running - name,
   883               results + (name -> Result(false, heap, res.rc)))
   884             //}}}
   885           case None if running.size < (max_jobs max 1) =>
   886             //{{{ check/start next job
   887             pending.dequeue(running.isDefinedAt(_)) match {
   888               case Some((name, info)) =>
   889                 val parent_result =
   890                   info.parent match {
   891                     case None => Result(true, no_heap, 0)
   892                     case Some(parent) => results(parent)
   893                   }
   894                 val output = output_dir + Path.basic(name)
   895                 val do_output = build_heap || queue.is_inner(name)
   896 
   897                 val (current, heap) =
   898                 {
   899                   find_log(name + ".gz") match {
   900                     case Some((dir, path)) =>
   901                       read_stamps(path) match {
   902                         case Some((s, h1, h2)) =>
   903                           val heap = heap_stamp(Some(dir + Path.basic(name)))
   904                           (s == make_stamp(name) && h1 == parent_result.heap && h2 == heap &&
   905                             !(do_output && heap == no_heap), heap)
   906                         case None => (false, no_heap)
   907                       }
   908                     case None => (false, no_heap)
   909                   }
   910                 }
   911                 val all_current = current && parent_result.current
   912 
   913                 if (all_current)
   914                   loop(pending - name, running, results + (name -> Result(true, heap, 0)))
   915                 else if (no_build) {
   916                   if (verbose) progress.echo("Skipping " + name + " ...")
   917                   loop(pending - name, running, results + (name -> Result(false, heap, 1)))
   918                 }
   919                 else if (parent_result.rc == 0 && !progress.stopped) {
   920                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   921                   val job =
   922                     new Job(progress, name, info, output, do_output, verbose, browser_info,
   923                       deps(name).session_graph, queue.command_timings(name))
   924                   loop(pending, running + (name -> (parent_result.heap, job)), results)
   925                 }
   926                 else {
   927                   progress.echo(name + " CANCELLED")
   928                   loop(pending - name, running, results + (name -> Result(false, heap, 1)))
   929                 }
   930               case None => sleep(); loop(pending, running, results)
   931             }
   932             ///}}}
   933           case None => sleep(); loop(pending, running, results)
   934         }
   935       }
   936     }
   937 
   938 
   939     /* build results */
   940 
   941     val results =
   942       if (deps.is_empty) {
   943         progress.echo(Output.warning_text("Nothing to build"))
   944         Map.empty[String, Result]
   945       }
   946       else loop(queue, Map.empty, Map.empty)
   947 
   948 
   949     /* global browser info */
   950 
   951     if (!no_build) {
   952       val browser_chapters =
   953         (for {
   954           (name, result) <- results.iterator
   955           if result.rc == 0
   956           info = full_tree(name)
   957           if info.options.bool("browser_info")
   958         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   959             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   960 
   961       for ((chapter, entries) <- browser_chapters)
   962         Present.update_chapter_index(browser_info, chapter, entries)
   963 
   964       if (browser_chapters.nonEmpty) Present.make_global_index(browser_info)
   965     }
   966 
   967 
   968     /* results */
   969 
   970     results.map({ case (name, result) => (name, result.rc) })
   971   }
   972 
   973 
   974   /* build */
   975 
   976   def build(
   977     options: Options,
   978     progress: Progress = Ignore_Progress,
   979     requirements: Boolean = false,
   980     all_sessions: Boolean = false,
   981     build_heap: Boolean = false,
   982     clean_build: Boolean = false,
   983     dirs: List[Path] = Nil,
   984     select_dirs: List[Path] = Nil,
   985     exclude_session_groups: List[String] = Nil,
   986     session_groups: List[String] = Nil,
   987     max_jobs: Int = 1,
   988     list_files: Boolean = false,
   989     check_keywords: Set[String] = Set.empty,
   990     no_build: Boolean = false,
   991     system_mode: Boolean = false,
   992     verbose: Boolean = false,
   993     exclude_sessions: List[String] = Nil,
   994     sessions: List[String] = Nil): Int =
   995   {
   996     val results =
   997       build_results(options, progress, requirements, all_sessions, build_heap, clean_build,
   998         dirs, select_dirs, exclude_session_groups, session_groups, max_jobs, list_files,
   999         check_keywords, no_build, system_mode, verbose, exclude_sessions, 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, check_keywords,
  1028               build_options, exclude_session_groups, exclude_sessions, sessions) =>
  1029             val options = (Options.init() /: build_options)(_ + _)
  1030             val progress = new Console_Progress(verbose)
  1031             progress.interrupt_handler {
  1032               build(options, progress, requirements, all_sessions, build_heap, clean_build,
  1033                 dirs.map(Path.explode(_)), select_dirs.map(Path.explode(_)), exclude_session_groups,
  1034                 session_groups, max_jobs, list_files, check_keywords.toSet, no_build, system_mode,
  1035                 verbose, exclude_sessions, sessions)
  1036             }
  1037         case _ => error("Bad arguments:\n" + cat_lines(args))
  1038       }
  1039     }
  1040   }
  1041 
  1042 
  1043   /* PIDE protocol */
  1044 
  1045   def build_theories(
  1046     session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
  1047       session.get_protocol_handler(classOf[Handler].getName) match {
  1048         case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
  1049         case _ => error("Cannot invoke build_theories: bad protocol handler")
  1050       }
  1051 
  1052   class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
  1053   {
  1054     private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
  1055 
  1056     def build_theories(
  1057       session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
  1058     {
  1059       val promise = Future.promise[XML.Body]
  1060       val id = Document_ID.make().toString
  1061       pending.change(promises => promises + (id -> promise))
  1062       session.build_theories(id, master_dir, theories)
  1063       promise
  1064     }
  1065 
  1066     private def loading_theory(prover: Prover, msg: Prover.Protocol_Output): Boolean =
  1067       msg.properties match {
  1068         case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
  1069         case _ => false
  1070       }
  1071 
  1072     private def build_theories_result(prover: Prover, msg: Prover.Protocol_Output): Boolean =
  1073       msg.properties match {
  1074         case Markup.Build_Theories_Result(id) =>
  1075           pending.change_result(promises =>
  1076             promises.get(id) match {
  1077               case Some(promise) =>
  1078                 val error_message =
  1079                   try { YXML.parse_body(Symbol.decode(msg.text)) }
  1080                   catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
  1081                 promise.fulfill(error_message)
  1082                 (true, promises - id)
  1083               case None =>
  1084                 (false, promises)
  1085             })
  1086         case _ => false
  1087       }
  1088 
  1089     override def stop(prover: Prover): Unit =
  1090       pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
  1091 
  1092     val functions =
  1093       Map(
  1094         Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
  1095         Markup.LOADING_THEORY -> loading_theory _)
  1096   }
  1097 }