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