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