src/Pure/Tools/build.scala
author wenzelm
Wed Apr 30 22:34:11 2014 +0200 (2014-04-30)
changeset 56801 8dd9df88f647
parent 56782 433cf57550fa
child 56824 5ae68f53b7c2
permissions -rw-r--r--
some support for session-qualified theories: allow to refer to resources via qualified name instead of odd file-system path;
     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.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   }
    30 
    31   object Ignore_Progress extends Progress
    32 
    33   class Console_Progress(verbose: Boolean) extends Progress
    34   {
    35     override def echo(msg: String) { System.out.println(msg) }
    36     override def theory(session: String, theory: String): Unit =
    37       if (verbose) echo(session + ": theory " + theory)
    38 
    39     @volatile private var is_stopped = false
    40     def interrupt_handler[A](e: => A): A = Interrupt.handler { is_stopped = true } { e }
    41     override def stopped: Boolean = is_stopped
    42   }
    43 
    44 
    45 
    46   /** session information **/
    47 
    48   // external version
    49   abstract class Entry
    50   sealed case class Chapter(name: String) extends Entry
    51   sealed case class Session_Entry(
    52     pos: Position.T,
    53     name: String,
    54     groups: List[String],
    55     path: String,
    56     parent: Option[String],
    57     description: String,
    58     options: List[Options.Spec],
    59     theories: List[(Boolean, List[Options.Spec], List[String])],
    60     files: List[String],
    61     document_files: List[(String, 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[(Boolean, Options, List[Path])],
    74     files: List[Path],
    75     document_files: List[(Path, Path)],
    76     entry_digest: SHA1.Digest)
    77 
    78   def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
    79 
    80   def session_info(options: Options, select: Boolean, dir: Path,
    81       chapter: String, entry: Session_Entry): (String, Session_Info) =
    82     try {
    83       val name = entry.name
    84 
    85       if (name == "") error("Bad session name")
    86       if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
    87       if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
    88 
    89       val session_options = options ++ entry.options
    90 
    91       val theories =
    92         entry.theories.map({ case (global, opts, thys) =>
    93           (global, session_options ++ opts, thys.map(Path.explode(_))) })
    94       val files = entry.files.map(Path.explode(_))
    95       val document_files =
    96         entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
    97 
    98       val entry_digest =
    99         SHA1.digest((chapter, name, entry.parent, entry.options,
   100           entry.theories, entry.files, entry.document_files).toString)
   101 
   102       val info =
   103         Session_Info(chapter, select, entry.pos, entry.groups, dir + Path.explode(entry.path),
   104           entry.parent, entry.description, session_options, theories, files,
   105           document_files, entry_digest)
   106 
   107       (name, info)
   108     }
   109     catch {
   110       case ERROR(msg) =>
   111         error(msg + "\nThe error(s) above occurred in session entry " +
   112           quote(entry.name) + Position.here(entry.pos))
   113     }
   114 
   115 
   116   /* session tree */
   117 
   118   object Session_Tree
   119   {
   120     def apply(infos: Seq[(String, Session_Info)]): Session_Tree =
   121     {
   122       val graph1 =
   123         (Graph.string[Session_Info] /: infos) {
   124           case (graph, (name, info)) =>
   125             if (graph.defined(name))
   126               error("Duplicate session " + quote(name) + Position.here(info.pos) +
   127                 Position.here(graph.get_node(name).pos))
   128             else graph.new_node(name, info)
   129         }
   130       val graph2 =
   131         (graph1 /: graph1.iterator) {
   132           case (graph, (name, (info, _))) =>
   133             info.parent match {
   134               case None => graph
   135               case Some(parent) =>
   136                 if (!graph.defined(parent))
   137                   error("Bad parent session " + quote(parent) + " for " +
   138                     quote(name) + Position.here(info.pos))
   139 
   140                 try { graph.add_edge_acyclic(parent, name) }
   141                 catch {
   142                   case exn: Graph.Cycles[_] =>
   143                     error(cat_lines(exn.cycles.map(cycle =>
   144                       "Cyclic session dependency of " +
   145                         cycle.map(c => quote(c.toString)).mkString(" via "))) +
   146                           Position.here(info.pos))
   147                 }
   148             }
   149         }
   150       new Session_Tree(graph2)
   151     }
   152   }
   153 
   154   final class Session_Tree private(val graph: Graph[String, Session_Info])
   155     extends PartialFunction[String, Session_Info]
   156   {
   157     def apply(name: String): Session_Info = graph.get_node(name)
   158     def isDefinedAt(name: String): Boolean = graph.defined(name)
   159 
   160     def selection(requirements: Boolean, all_sessions: Boolean,
   161       session_groups: List[String], sessions: List[String]): (List[String], Session_Tree) =
   162     {
   163       val bad_sessions = sessions.filterNot(isDefinedAt(_))
   164       if (!bad_sessions.isEmpty) error("Undefined session(s): " + commas_quote(bad_sessions))
   165 
   166       val pre_selected =
   167       {
   168         if (all_sessions) graph.keys
   169         else {
   170           val select_group = session_groups.toSet
   171           val select = sessions.toSet
   172           (for {
   173             (name, (info, _)) <- graph.iterator
   174             if info.select || select(name) || apply(name).groups.exists(select_group)
   175           } yield name).toList
   176         }
   177       }
   178       val selected =
   179         if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
   180         else pre_selected
   181 
   182       val graph1 = graph.restrict(graph.all_preds(selected).toSet)
   183       (selected, new Session_Tree(graph1))
   184     }
   185 
   186     def topological_order: List[(String, Session_Info)] =
   187       graph.topological_order.map(name => (name, apply(name)))
   188 
   189     override def toString: String = graph.keys_iterator.mkString("Session_Tree(", ", ", ")")
   190   }
   191 
   192 
   193   /* parser */
   194 
   195   val chapter_default = "Unsorted"
   196 
   197   private val CHAPTER = "chapter"
   198   private val SESSION = "session"
   199   private val IN = "in"
   200   private val DESCRIPTION = "description"
   201   private val OPTIONS = "options"
   202   private val GLOBAL_THEORIES = "global_theories"
   203   private val THEORIES = "theories"
   204   private val FILES = "files"
   205   private val DOCUMENT_FILES = "document_files"
   206 
   207   lazy val root_syntax =
   208     Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" +
   209       (CHAPTER, Keyword.THY_DECL) + (SESSION, Keyword.THY_DECL) +
   210       IN + DESCRIPTION + OPTIONS + GLOBAL_THEORIES + THEORIES + FILES + DOCUMENT_FILES
   211 
   212   object Parser extends Parse.Parser
   213   {
   214     private val chapter: Parser[Chapter] =
   215     {
   216       val chapter_name = atom("chapter name", _.is_name)
   217 
   218       command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
   219     }
   220 
   221     private val session_entry: Parser[Session_Entry] =
   222     {
   223       val session_name = atom("session name", _.is_name)
   224 
   225       val option =
   226         name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
   227       val options = keyword("[") ~> rep1sep(option, keyword(",")) <~ keyword("]")
   228 
   229       val theories =
   230         (keyword(GLOBAL_THEORIES) | keyword(THEORIES)) ~!
   231           ((options | success(Nil)) ~ rep(theory_xname)) ^^
   232           { case x ~ (y ~ z) => (x == GLOBAL_THEORIES, y, z) }
   233 
   234       val document_files =
   235         keyword(DOCUMENT_FILES) ~!
   236           ((keyword("(") ~! (keyword(IN) ~! (path ~ keyword(")"))) ^^
   237               { case _ ~ (_ ~ (x ~ _)) => x } | success("document")) ~
   238             rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
   239 
   240       command(SESSION) ~!
   241         (session_name ~
   242           ((keyword("(") ~! (rep1(name) <~ keyword(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
   243           ((keyword(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
   244           (keyword("=") ~!
   245             (opt(session_name ~! keyword("+") ^^ { case x ~ _ => x }) ~
   246               ((keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
   247               ((keyword(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
   248               rep1(theories) ~
   249               ((keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil)) ~
   250               (rep(document_files) ^^ (x => x.flatten))))) ^^
   251         { case pos ~ (a ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i))) =>
   252             Session_Entry(pos, a, b, c, d, e, f, g, h, i) }
   253     }
   254 
   255     def parse_entries(root: Path): List[(String, Session_Entry)] =
   256     {
   257       val toks = root_syntax.scan(File.read(root))
   258 
   259       parse_all(rep(chapter | session_entry), Token.reader(toks, root.implode)) match {
   260         case Success(result, _) =>
   261           var chapter = chapter_default
   262           val entries = new mutable.ListBuffer[(String, Session_Entry)]
   263           result.foreach {
   264             case Chapter(name) => chapter = name
   265             case session_entry: Session_Entry => entries += ((chapter, session_entry))
   266           }
   267           entries.toList
   268         case bad => error(bad.toString)
   269       }
   270     }
   271   }
   272 
   273 
   274   /* find sessions within certain directories */
   275 
   276   private val ROOT = Path.explode("ROOT")
   277   private val ROOTS = Path.explode("ROOTS")
   278 
   279   private def is_session_dir(dir: Path): Boolean =
   280     (dir + ROOT).is_file || (dir + ROOTS).is_file
   281 
   282   private def check_session_dir(dir: Path): Path =
   283     if (is_session_dir(dir)) dir
   284     else error("Bad session root directory: " + dir.toString)
   285 
   286   def find_sessions(options: Options, more_dirs: List[(Boolean, Path)]): Session_Tree =
   287   {
   288     def find_dir(select: Boolean, dir: Path): List[(String, Session_Info)] =
   289       find_root(select, dir) ::: find_roots(select, dir)
   290 
   291     def find_root(select: Boolean, dir: Path): List[(String, Session_Info)] =
   292     {
   293       val root = dir + ROOT
   294       if (root.is_file)
   295         Parser.parse_entries(root).map(p => session_info(options, select, dir, p._1, p._2))
   296       else Nil
   297     }
   298 
   299     def find_roots(select: Boolean, dir: Path): List[(String, Session_Info)] =
   300     {
   301       val roots = dir + ROOTS
   302       if (roots.is_file) {
   303         for {
   304           line <- split_lines(File.read(roots))
   305           if !(line == "" || line.startsWith("#"))
   306           dir1 =
   307             try { check_session_dir(dir + Path.explode(line)) }
   308             catch {
   309               case ERROR(msg) =>
   310                 error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
   311             }
   312           info <- find_dir(select, dir1)
   313         } yield info
   314       }
   315       else Nil
   316     }
   317 
   318     val default_dirs = Isabelle_System.components().filter(is_session_dir(_)).map((false, _))
   319 
   320     more_dirs foreach { case (_, dir) => check_session_dir(dir) }
   321 
   322     Session_Tree(
   323       for {
   324         (select, dir) <- default_dirs ::: more_dirs
   325         info <- find_dir(select, dir)
   326       } yield info)
   327   }
   328 
   329 
   330 
   331   /** build **/
   332 
   333   /* queue */
   334 
   335   object Queue
   336   {
   337     def apply(tree: Session_Tree, load_timings: String => (List[Properties.T], Double)): Queue =
   338     {
   339       val graph = tree.graph
   340       val sessions = graph.keys
   341 
   342       val timings =
   343         sessions.par.map((name: String) =>
   344           Exn.capture { (name, load_timings(name)) }).toList.map(Exn.release(_))
   345       val command_timings =
   346         Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
   347       val session_timing =
   348         Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
   349 
   350       def outdegree(name: String): Int = graph.imm_succs(name).size
   351       def timeout(name: String): Double = tree(name).options.real("timeout")
   352 
   353       object Ordering extends scala.math.Ordering[String]
   354       {
   355         def compare_timing(name1: String, name2: String): Int =
   356         {
   357           val t1 = session_timing(name1)
   358           val t2 = session_timing(name2)
   359           if (t1 == 0.0 || t2 == 0.0) 0
   360           else t1 compare t2
   361         }
   362 
   363         def compare(name1: String, name2: String): Int =
   364           outdegree(name2) compare outdegree(name1) match {
   365             case 0 =>
   366               compare_timing(name2, name1) match {
   367                 case 0 =>
   368                   timeout(name2) compare timeout(name1) match {
   369                     case 0 => name1 compare name2
   370                     case ord => ord
   371                   }
   372                 case ord => ord
   373               }
   374             case ord => ord
   375           }
   376       }
   377 
   378       new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
   379     }
   380   }
   381 
   382   final class Queue private(
   383     graph: Graph[String, Session_Info],
   384     order: SortedSet[String],
   385     val command_timings: String => List[Properties.T])
   386   {
   387     def is_inner(name: String): Boolean = !graph.is_maximal(name)
   388 
   389     def is_empty: Boolean = graph.is_empty
   390 
   391     def - (name: String): Queue =
   392       new Queue(graph.del_node(name),
   393         order - name,  // FIXME scala-2.10.0 TreeSet problem!?
   394         command_timings)
   395 
   396     def dequeue(skip: String => Boolean): Option[(String, Session_Info)] =
   397     {
   398       val it = order.iterator.dropWhile(name =>
   399         skip(name)
   400           || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
   401           || !graph.is_minimal(name))
   402       if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
   403       else None
   404     }
   405   }
   406 
   407 
   408   /* source dependencies and static content */
   409 
   410   sealed case class Session_Content(
   411     loaded_theories: Set[String],
   412     known_theories: Map[String, Document.Node.Name],
   413     keywords: Thy_Header.Keywords,
   414     syntax: Outer_Syntax,
   415     sources: List[(Path, SHA1.Digest)])
   416 
   417   sealed case class Deps(deps: Map[String, Session_Content])
   418   {
   419     def is_empty: Boolean = deps.isEmpty
   420     def apply(name: String): Session_Content = deps(name)
   421     def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
   422   }
   423 
   424   def dependencies(progress: Progress, inlined_files: Boolean,
   425       verbose: Boolean, list_files: Boolean, tree: Session_Tree): Deps =
   426     Deps((Map.empty[String, Session_Content] /: tree.topological_order)(
   427       { case (deps, (name, info)) =>
   428           if (progress.stopped) throw Exn.Interrupt()
   429 
   430           try {
   431             val (loaded_theories0, known_theories0, syntax0) =
   432               info.parent.map(deps(_)) match {
   433                 case None =>
   434                   (Set.empty[String], Map.empty[String, Document.Node.Name], Outer_Syntax.init())
   435                 case Some(parent) =>
   436                   (parent.loaded_theories, parent.known_theories, parent.syntax)
   437               }
   438             val resources = new Resources(loaded_theories0, known_theories0, syntax0)
   439             val thy_info = new Thy_Info(resources)
   440 
   441             if (verbose || list_files) {
   442               val groups =
   443                 if (info.groups.isEmpty) ""
   444                 else info.groups.mkString(" (", " ", ")")
   445               progress.echo("Session " + info.chapter + "/" + name + groups)
   446             }
   447 
   448             val thy_deps =
   449             {
   450               val root_theories =
   451                 info.theories.flatMap({
   452                   case (global, _, thys) =>
   453                     thys.map(thy =>
   454                       (resources.node_name(
   455                         if (global) "" else name, info.dir + Resources.thy_path(thy)), info.pos))
   456                 })
   457               val thy_deps = thy_info.dependencies(name, root_theories)
   458 
   459               thy_deps.errors match {
   460                 case Nil => thy_deps
   461                 case errs => error(cat_lines(errs))
   462               }
   463             }
   464 
   465             val known_theories =
   466               (known_theories0 /: thy_deps.deps)({ case (known, dep) =>
   467                 val name = dep.name
   468                 known.get(name.theory) match {
   469                   case Some(name1) if name != name1 =>
   470                     error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
   471                   case _ =>
   472                     known + (name.theory -> name) + (Long_Name.base_name(name.theory) -> name)
   473                 }
   474               })
   475 
   476             val loaded_theories = thy_deps.loaded_theories
   477             val keywords = thy_deps.keywords
   478             val syntax = thy_deps.syntax.asInstanceOf[Outer_Syntax]
   479 
   480             val loaded_files = if (inlined_files) thy_deps.loaded_files else Nil
   481 
   482             val all_files =
   483               (thy_deps.deps.map(dep => Path.explode(dep.name.node)) ::: loaded_files :::
   484                 info.files.map(file => info.dir + file) :::
   485                 info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
   486 
   487             if (list_files) {
   488               progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
   489               for {
   490                 file <- all_files
   491                 if file.split_ext._2 == "ML"
   492               } {
   493                 val path = info.dir + file
   494                 try { Symbol.decode_strict(File.read(path)) }
   495                 catch {
   496                   case ERROR(msg) => cat_error(msg, "The error(s) above occurred in file " + path)
   497                 }
   498               }
   499             }
   500 
   501             val sources = all_files.map(p => (p, SHA1.digest(p.file)))
   502 
   503             val content =
   504               Session_Content(loaded_theories, known_theories, keywords, syntax, sources)
   505             deps + (name -> content)
   506           }
   507           catch {
   508             case ERROR(msg) =>
   509               cat_error(msg, "The error(s) above occurred in session " +
   510                 quote(name) + Position.here(info.pos))
   511           }
   512       }))
   513 
   514   def session_dependencies(
   515     options: Options,
   516     inlined_files: Boolean,
   517     dirs: List[Path],
   518     sessions: List[String]): Deps =
   519   {
   520     val (_, tree) =
   521       find_sessions(options, dirs.map((false, _))).selection(false, false, Nil, sessions)
   522     dependencies(Ignore_Progress, inlined_files, false, false, tree)
   523   }
   524 
   525   def session_content(
   526     options: Options,
   527     inlined_files: Boolean,
   528     dirs: List[Path],
   529     session: String): Session_Content =
   530   {
   531     session_dependencies(options, inlined_files, dirs, List(session))(session)
   532   }
   533 
   534   def outer_syntax(options: Options, session: String): Outer_Syntax =
   535     session_content(options, false, Nil, session).syntax
   536 
   537 
   538   /* jobs */
   539 
   540   private class Job(progress: Progress,
   541     name: String, val info: Session_Info, output: Path, do_output: Boolean,
   542     verbose: Boolean, browser_info: Path, command_timings: List[Properties.T])
   543   {
   544     def output_path: Option[Path] = if (do_output) Some(output) else None
   545 
   546     private val parent = info.parent.getOrElse("")
   547 
   548     private val args_file = Isabelle_System.tmp_file("args")
   549     File.write(args_file, YXML.string_of_body(
   550       if (is_pure(name)) Options.encode(info.options)
   551       else
   552         {
   553           val theories = info.theories.map(x => (x._2, x._3))
   554           import XML.Encode._
   555               pair(list(properties), pair(bool, pair(Options.encode, pair(bool, pair(Path.encode,
   556                 pair(list(pair(Path.encode, Path.encode)), pair(string, pair(string, pair(string,
   557                   list(pair(Options.encode, list(Path.encode))))))))))))(
   558               (command_timings, (do_output, (info.options, (verbose, (browser_info,
   559                 (info.document_files, (parent, (info.chapter, (name, theories))))))))))
   560         }))
   561 
   562     private val env =
   563       Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output),
   564         (if (is_pure(name)) "ISABELLE_PROCESS_OPTIONS" else "ARGS_FILE") ->
   565           Isabelle_System.posix_path(args_file))
   566 
   567     private val script =
   568       if (is_pure(name)) {
   569         if (do_output) "./build " + name + " \"$OUTPUT\""
   570         else """ rm -f "$OUTPUT"; ./build """ + name
   571       }
   572       else {
   573         """
   574         . "$ISABELLE_HOME/lib/scripts/timestart.bash"
   575         """ +
   576           (if (do_output)
   577             """
   578             "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
   579             """
   580           else
   581             """
   582             rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
   583             """) +
   584         """
   585         RC="$?"
   586 
   587         . "$ISABELLE_HOME/lib/scripts/timestop.bash"
   588 
   589         if [ "$RC" -eq 0 ]; then
   590           echo "Finished $TARGET ($TIMES_REPORT)" >&2
   591         fi
   592 
   593         exit "$RC"
   594         """
   595       }
   596 
   597     private val (thread, result) =
   598       Simple_Thread.future("build") {
   599         Isabelle_System.bash_env(info.dir.file, env, script,
   600           progress_stdout = (line: String) =>
   601             Library.try_unprefix("\floading_theory = ", line) match {
   602               case Some(theory) => progress.theory(name, theory)
   603               case None =>
   604             },
   605           progress_limit =
   606             info.options.int("process_output_limit") match {
   607               case 0 => None
   608               case m => Some(m * 1000000L)
   609             })
   610       }
   611 
   612     def terminate: Unit = thread.interrupt
   613     def is_finished: Boolean = result.is_finished
   614 
   615     @volatile private var was_timeout = false
   616     private val timeout_request: Option[Event_Timer.Request] =
   617     {
   618       val timeout = info.options.seconds("timeout")
   619       if (timeout > Time.zero)
   620         Some(Event_Timer.request(Time.now() + timeout) { terminate; was_timeout = true })
   621       else None
   622     }
   623 
   624     def join: Isabelle_System.Bash_Result =
   625     {
   626       val res = result.join
   627 
   628       args_file.delete
   629       timeout_request.foreach(_.cancel)
   630 
   631       if (res.rc == Exn.Interrupt.return_code) {
   632         if (was_timeout) res.add_err(Output.error_text("Timeout")).set_rc(1)
   633         else res.add_err(Output.error_text("Interrupt"))
   634       }
   635       else res
   636     }
   637   }
   638 
   639 
   640   /* inlined properties (YXML) */
   641 
   642   object Props
   643   {
   644     def parse(text: String): Properties.T = XML.Decode.properties(YXML.parse_body(text))
   645 
   646     def parse_lines(prefix: String, lines: List[String]): List[Properties.T] =
   647       for (line <- lines; s <- Library.try_unprefix(prefix, line)) yield parse(s)
   648 
   649     def find_parse_line(prefix: String, lines: List[String]): Option[Properties.T] =
   650       lines.find(_.startsWith(prefix)).map(line => parse(line.substring(prefix.length)))
   651   }
   652 
   653 
   654   /* log files */
   655 
   656   private val LOG = Path.explode("log")
   657   private def log(name: String): Path = LOG + Path.basic(name)
   658   private def log_gz(name: String): Path = log(name).ext("gz")
   659 
   660   private val SESSION_NAME = "\fSession.name = "
   661 
   662 
   663   sealed case class Log_Info(
   664     name: String,
   665     stats: List[Properties.T],
   666     tasks: List[Properties.T],
   667     command_timings: List[Properties.T],
   668     session_timing: Properties.T)
   669 
   670   def parse_log(full_stats: Boolean, text: String): Log_Info =
   671   {
   672     val lines = split_lines(text)
   673     val xml_cache = new XML.Cache()
   674     def parse_lines(prfx: String): List[Properties.T] =
   675       Props.parse_lines(prfx, lines).map(xml_cache.props(_))
   676 
   677     val name =
   678       lines.find(_.startsWith(SESSION_NAME)).map(_.substring(SESSION_NAME.length)) getOrElse ""
   679     val stats = if (full_stats) parse_lines("\fML_statistics = ") else Nil
   680     val tasks = if (full_stats) parse_lines("\ftask_statistics = ") else Nil
   681     val command_timings = parse_lines("\fcommand_timing = ")
   682     val session_timing = Props.find_parse_line("\fTiming = ", lines) getOrElse Nil
   683     Log_Info(name, stats, tasks, command_timings, session_timing)
   684   }
   685 
   686 
   687   /* sources and heaps */
   688 
   689   private def sources_stamp(digests: List[SHA1.Digest]): String =
   690     digests.map(_.toString).sorted.mkString("sources: ", " ", "")
   691 
   692   private val no_heap: String = "heap: -"
   693 
   694   private def heap_stamp(heap: Option[Path]): String =
   695   {
   696     "heap: " +
   697       (heap match {
   698         case Some(path) =>
   699           val file = path.file
   700           if (file.isFile) file.length.toString + " " + file.lastModified.toString
   701           else "-"
   702         case None => "-"
   703       })
   704   }
   705 
   706   private def read_stamps(path: Path): Option[(String, String, String)] =
   707     if (path.is_file) {
   708       val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(path.file)))
   709       val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
   710       val (s, h1, h2) =
   711         try { (reader.readLine, reader.readLine, reader.readLine) }
   712         finally { reader.close }
   713       if (s != null && s.startsWith("sources: ") &&
   714           h1 != null && h1.startsWith("heap: ") &&
   715           h2 != null && h2.startsWith("heap: ")) Some((s, h1, h2))
   716       else None
   717     }
   718     else None
   719 
   720 
   721   /* build_results */
   722 
   723   def build_results(
   724     options: Options,
   725     progress: Progress = Ignore_Progress,
   726     requirements: Boolean = false,
   727     all_sessions: Boolean = false,
   728     build_heap: Boolean = false,
   729     clean_build: Boolean = false,
   730     more_dirs: List[(Boolean, Path)] = Nil,
   731     session_groups: List[String] = Nil,
   732     max_jobs: Int = 1,
   733     list_files: Boolean = false,
   734     no_build: Boolean = false,
   735     system_mode: Boolean = false,
   736     verbose: Boolean = false,
   737     sessions: List[String] = Nil): Map[String, Int] =
   738   {
   739     /* session tree and dependencies */
   740 
   741     val full_tree = find_sessions(options, more_dirs)
   742     val (selected, selected_tree) =
   743       full_tree.selection(requirements, all_sessions, session_groups, sessions)
   744 
   745     val deps = dependencies(progress, true, verbose, list_files, selected_tree)
   746 
   747     def make_stamp(name: String): String =
   748       sources_stamp(selected_tree(name).entry_digest :: deps.sources(name))
   749 
   750 
   751     /* persistent information */
   752 
   753     val (input_dirs, output_dir, browser_info) =
   754       if (system_mode) {
   755         val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
   756         (List(output_dir), output_dir, Path.explode("~~/browser_info"))
   757       }
   758       else {
   759         val output_dir = Path.explode("$ISABELLE_OUTPUT")
   760         (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
   761          Path.explode("$ISABELLE_BROWSER_INFO"))
   762       }
   763 
   764     def find_log(name: String): Option[(Path, Path)] =
   765       input_dirs.find(dir => (dir + log(name)).is_file).map(dir => (dir, dir + log(name)))
   766 
   767 
   768     /* queue with scheduling information */
   769 
   770     def load_timings(name: String): (List[Properties.T], Double) =
   771     {
   772       val (path, text) =
   773         find_log(name + ".gz") match {
   774           case Some((_, path)) => (path, File.read_gzip(path))
   775           case None =>
   776             find_log(name) match {
   777               case Some((_, path)) => (path, File.read(path))
   778               case None => (Path.current, "")
   779             }
   780         }
   781 
   782       def ignore_error(msg: String): (List[Properties.T], Double) =
   783       {
   784         Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
   785         (Nil, 0.0)
   786       }
   787 
   788       try {
   789         val info = parse_log(false, text)
   790         val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
   791         (info.command_timings, session_timing)
   792       }
   793       catch {
   794         case ERROR(msg) => ignore_error(msg)
   795         case exn: java.lang.Error => ignore_error(Exn.message(exn))
   796         case _: XML.Error => ignore_error("")
   797       }
   798     }
   799 
   800     val queue = Queue(selected_tree, load_timings)
   801 
   802 
   803     /* main build process */
   804 
   805     // prepare log dir
   806     Isabelle_System.mkdirs(output_dir + LOG)
   807 
   808     // optional cleanup
   809     if (clean_build) {
   810       for (name <- full_tree.graph.all_succs(selected)) {
   811         val files =
   812           List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
   813         if (!files.isEmpty) progress.echo("Cleaning " + name + " ...")
   814         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   815       }
   816     }
   817 
   818     // scheduler loop
   819     case class Result(current: Boolean, heap: String, rc: Int)
   820 
   821     def sleep(): Unit = Thread.sleep(500)
   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     more_dirs: List[(Boolean, Path)] = Nil,
   977     session_groups: List[String] = Nil,
   978     max_jobs: Int = 1,
   979     list_files: Boolean = false,
   980     no_build: Boolean = false,
   981     system_mode: Boolean = false,
   982     verbose: Boolean = false,
   983     sessions: List[String] = Nil): Int =
   984   {
   985     val results =
   986       build_results(options, progress, requirements, all_sessions,
   987         build_heap, clean_build, more_dirs, session_groups, max_jobs, list_files, no_build,
   988         system_mode, verbose, sessions)
   989 
   990     val rc = (0 /: results)({ case (rc1, (_, rc2)) => rc1 max rc2 })
   991     if (rc != 0 && (verbose || !no_build)) {
   992       val unfinished =
   993         (for ((name, r) <- results.iterator if r != 0) yield name).toList.sorted
   994       progress.echo("Unfinished session(s): " + commas(unfinished))
   995     }
   996     rc
   997   }
   998 
   999 
  1000   /* command line entry point */
  1001 
  1002   def main(args: Array[String])
  1003   {
  1004     Command_Line.tool {
  1005       args.toList match {
  1006         case
  1007           Properties.Value.Boolean(requirements) ::
  1008           Properties.Value.Boolean(all_sessions) ::
  1009           Properties.Value.Boolean(build_heap) ::
  1010           Properties.Value.Boolean(clean_build) ::
  1011           Properties.Value.Int(max_jobs) ::
  1012           Properties.Value.Boolean(list_files) ::
  1013           Properties.Value.Boolean(no_build) ::
  1014           Properties.Value.Boolean(system_mode) ::
  1015           Properties.Value.Boolean(verbose) ::
  1016           Command_Line.Chunks(select_dirs, include_dirs, session_groups, build_options, sessions) =>
  1017             val options = (Options.init() /: build_options)(_ + _)
  1018             val more_dirs =
  1019               select_dirs.map(d => (true, Path.explode(d))) :::
  1020               include_dirs.map(d => (false, Path.explode(d)))
  1021             val progress = new Console_Progress(verbose)
  1022             progress.interrupt_handler {
  1023               build(options, progress, requirements, all_sessions,
  1024                 build_heap, clean_build, more_dirs, session_groups, max_jobs, list_files, no_build,
  1025                 system_mode, verbose, sessions)
  1026             }
  1027         case _ => error("Bad arguments:\n" + cat_lines(args))
  1028       }
  1029     }
  1030   }
  1031 }
  1032