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