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