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