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