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