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