1 /* Title: Pure/System/build.scala
4 Build and manage Isabelle sessions.
10 import java.io.{File => JFile}
12 import scala.collection.mutable
13 import scala.annotation.tailrec
18 /** session information **/
26 object Ordering extends scala.math.Ordering[Key]
28 def compare(key1: Key, key2: Key): Int =
29 key1.order compare key2.order match {
30 case 0 => key1.name compare key2.name
36 sealed case class Key(name: String, order: Int)
38 override def toString: String = name
44 sealed case class Info(
47 parent: Option[String],
48 parent_base_name: Option[String],
51 theories: List[(Options, List[Path])],
60 val empty: Queue = new Queue()
63 final class Queue private(
64 keys: Map[String, Key] = Map.empty,
65 graph: Graph[Key, Info] = Graph.empty(Key.Ordering))
67 def is_empty: Boolean = graph.is_empty
69 def apply(name: String): Info = graph.get_node(keys(name))
70 def defined(name: String): Boolean = keys.isDefinedAt(name)
71 def is_inner(name: String): Boolean = !graph.is_maximal(keys(name))
73 def + (key: Key, info: Info): Queue =
76 if (defined(key.name)) error("Duplicate session: " + quote(key.name))
77 else keys + (key.name -> key)
81 graph.new_node(key, info).add_deps_acyclic(key, info.parent.toList.map(keys(_)))
84 case exn: Graph.Cycles[_] =>
85 error(cat_lines(exn.cycles.map(cycle =>
86 "Cyclic session dependency of " +
87 cycle.map(key => quote(key.toString)).mkString(" via "))))
89 new Queue(keys1, graph1)
92 def - (name: String): Queue = new Queue(keys - name, graph.del_node(keys(name)))
94 def required(names: List[String]): Queue =
96 val req = graph.all_preds(names.map(keys(_))).map(_.name).toSet
97 val keys1 = keys -- keys.keySet.filter(name => !req(name))
98 val graph1 = graph.restrict(key => keys1.isDefinedAt(key.name))
99 new Queue(keys1, graph1)
102 def dequeue(skip: String => Boolean): Option[(String, Info)] =
104 val it = graph.entries.dropWhile(
105 { case (key, (_, (deps, _))) => !deps.isEmpty || skip(key.name) })
106 if (it.hasNext) { val (key, (info, _)) = it.next; Some((key.name, info)) }
110 def topological_order: List[(String, Info)] =
111 graph.topological_order.map(key => (key.name, graph.get_node(key)))
118 private case class Session_Entry(
122 path: Option[String],
123 parent: Option[String],
125 options: List[Options.Spec],
126 theories: List[(List[Options.Spec], List[String])],
129 private object Parser extends Parse.Parser
131 val SESSION = "session"
133 val DESCRIPTION = "description"
134 val OPTIONS = "options"
135 val THEORIES = "theories"
139 Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
140 SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
142 val session_entry: Parser[Session_Entry] =
144 val session_name = atom("session name", _.is_name)
147 name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
148 val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
151 keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
152 { case _ ~ (x ~ y) => (x, y) }
154 ((keyword(SESSION) ~! session_name) ^^ { case _ ~ x => x }) ~
155 (keyword("!") ^^^ true | success(false)) ~
156 (keyword("(") ~! (nat <~ keyword(")")) ^^ { case _ ~ x => x } | success(Integer.MAX_VALUE)) ~
157 (opt(keyword(IN) ~! string ^^ { case _ ~ x => x })) ~
158 (keyword("=") ~> opt(session_name <~ keyword("+"))) ~
159 (keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x } | success("")) ~
160 (keyword(OPTIONS) ~! options ^^ { case _ ~ x => x } | success(Nil)) ~
162 (keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x } | success(Nil)) ^^
163 { case a ~ b ~ c ~ d ~ e ~ f ~ g ~ h ~ i => Session_Entry(a, b, c, d, e, f, g, h, i) }
166 def parse_entries(root: JFile): List[Session_Entry] =
168 val toks = syntax.scan(File.read(root))
169 parse_all(rep(session_entry), Token.reader(toks, root.toString)) match {
170 case Success(result, _) => result
171 case bad => error(bad.toString)
179 private val ROOT = Path.explode("ROOT")
180 private val SESSIONS = Path.explode("etc/sessions")
182 private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
184 private def sessions_root(options: Options, dir: Path, root: JFile, queue: Session.Queue)
187 (queue /: Parser.parse_entries(root))((queue1, entry) =>
189 if (entry.name == "") error("Bad session name")
191 val (full_name, parent_base_name) =
192 if (is_pure(entry.name)) {
193 if (entry.parent.isDefined) error("Illegal parent session")
194 else (entry.name, None: Option[String])
198 case Some(parent_name) if queue1.defined(parent_name) =>
200 if (entry.this_name) entry.name
201 else parent_name + "-" + entry.name
202 val parent_base_name = Some(queue1(parent_name).base_name)
203 (full_name, parent_base_name)
204 case _ => error("Bad parent session")
209 case Some(p) => Path.explode(p)
210 case None => Path.basic(entry.name)
213 val key = Session.Key(full_name, entry.order)
215 val session_options = options ++ entry.options
218 entry.theories.map({ case (opts, thys) =>
219 (session_options ++ opts, thys.map(Path.explode(_))) })
220 val files = entry.files.map(Path.explode(_))
221 val digest = SHA1.digest((full_name, entry.parent, entry.options, entry.theories).toString)
224 Session.Info(entry.name, dir + path, entry.parent, parent_base_name,
225 entry.description, session_options, theories, files, digest)
231 error(msg + "\nThe error(s) above occurred in session entry " +
232 quote(entry.name) + Position.str_of(Position.file(root)))
236 private def sessions_dir(options: Options, strict: Boolean, dir: Path, queue: Session.Queue)
239 val root = (dir + ROOT).file
240 if (root.isFile) sessions_root(options, dir, root, queue)
241 else if (strict) error("Bad session root file: " + quote(root.toString))
245 private def sessions_catalog(options: Options, dir: Path, catalog: JFile, queue: Session.Queue)
249 split_lines(File.read(catalog)).filterNot(line => line == "" || line.startsWith("#"))
250 (queue /: dirs)((queue1, dir1) =>
252 val dir2 = dir + Path.explode(dir1)
253 if (dir2.file.isDirectory) sessions_dir(options, true, dir2, queue1)
254 else error("Bad session directory: " + dir2.toString)
258 error(msg + "\nThe error(s) above occurred in session catalog " + quote(catalog.toString))
262 def find_sessions(options: Options, all_sessions: Boolean, sessions: List[String],
263 more_dirs: List[Path]): Session.Queue =
265 var queue = Session.Queue.empty
267 for (dir <- Isabelle_System.components()) {
268 queue = sessions_dir(options, false, dir, queue)
270 val catalog = (dir + SESSIONS).file
272 queue = sessions_catalog(options, dir, catalog, queue)
275 for (dir <- more_dirs) queue = sessions_dir(options, true, dir, queue)
277 sessions.filter(name => !queue.defined(name)) match {
279 case bad => error("Undefined session(s): " + commas_quote(bad))
282 if (all_sessions) queue else queue.required(sessions)
289 private def echo(msg: String) { java.lang.System.out.println(msg) }
290 private def sleep(): Unit = Thread.sleep(500)
295 sealed case class Node(
296 loaded_theories: Set[String],
297 sources: List[(Path, SHA1.Digest)])
299 sealed case class Deps(deps: Map[String, Node])
301 def sources(name: String): List[(Path, SHA1.Digest)] = deps(name).sources
304 def dependencies(verbose: Boolean, queue: Session.Queue): Deps =
305 Deps((Map.empty[String, Node] /: queue.topological_order)(
306 { case (deps, (name, info)) =>
309 case None => Set.empty[String]
310 case Some(parent) => deps(parent).loaded_theories
312 val thy_info = new Thy_Info(new Thy_Load(preloaded))
314 if (verbose) echo("Checking " + name)
317 thy_info.dependencies(
318 info.theories.map(_._2).flatten.
319 map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
321 val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
324 thy_deps.map({ case (n, h) =>
325 val thy = Path.explode(n.node).expand
329 d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
333 }).flatten ::: info.files.map(file => info.dir + file)
334 val sources = all_files.map(p => (p, SHA1.digest(p)))
336 deps + (name -> Node(loaded_theories, sources))
342 private class Job(cwd: JFile, env: Map[String, String], script: String, args: String)
344 private val args_file = File.tmp_file("args")
345 private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
346 File.write(args_file, args)
348 private val (thread, result) =
349 Simple_Thread.future("build") { Isabelle_System.bash_env(cwd, env1, script) }
351 def terminate: Unit = thread.interrupt
352 def is_finished: Boolean = result.is_finished
353 def join: (String, String, Int) = { val res = result.join; args_file.delete; res }
356 private def start_job(name: String, info: Session.Info, output: Option[String],
357 options: Options, timing: Boolean, verbose: Boolean, browser_info: Path): Job =
359 // global browser info dir
360 if (options.bool("browser_info") && !(browser_info + Path.explode("index.html")).file.isFile)
362 browser_info.file.mkdirs()
363 File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
364 browser_info + Path.explode("isabelle.gif"))
365 File.write(browser_info + Path.explode("index.html"),
366 File.read(Path.explode("~~/lib/html/library_index_header.template")) +
367 File.read(Path.explode("~~/lib/html/library_index_content.template")) +
368 File.read(Path.explode("~~/lib/html/library_index_footer.template")))
371 val parent = info.parent.getOrElse("")
372 val parent_base_name = info.parent_base_name.getOrElse("")
374 val cwd = info.dir.file
375 val env = Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> output.getOrElse(""))
377 if (is_pure(name)) "./build " + name + " \"$OUTPUT\""
380 . "$ISABELLE_HOME/lib/scripts/timestart.bash"
382 (if (output.isDefined)
383 """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT" """
385 """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT" """) +
389 . "$ISABELLE_HOME/lib/scripts/timestop.bash"
391 if [ "$RC" -eq 0 ]; then
392 echo "Finished $TARGET ($TIMES_REPORT)" >&2
401 pair(bool, pair(Options.encode, pair(bool, pair(bool, pair(Path.encode, pair(string,
402 pair(string, pair(string, list(pair(Options.encode, list(Path.encode)))))))))))(
403 (output.isDefined, (options, (timing, (verbose, (browser_info, (parent_base_name,
404 (name, (info.base_name, info.theories)))))))))
406 new Job(cwd, env, script, YXML.string_of_body(args_xml))
412 def build(all_sessions: Boolean, build_images: Boolean, max_jobs: Int,
413 no_build: Boolean, system_mode: Boolean, timing: Boolean, verbose: Boolean,
414 more_dirs: List[Path], more_options: List[String], sessions: List[String]): Int =
416 val options = (Options.init() /: more_options)(_.define_simple(_))
417 val queue = find_sessions(options, all_sessions, sessions, more_dirs)
418 val deps = dependencies(verbose, queue)
420 val (output_dir, browser_info) =
421 if (system_mode) (Path.explode("~~/heaps/$ML_IDENTIFIER"), Path.explode("~~/browser_info"))
422 else (Path.explode("$ISABELLE_OUTPUT"), Path.explode("$ISABELLE_BROWSER_INFO"))
425 val log_dir = output_dir + Path.explode("log")
426 log_dir.file.mkdirs()
430 pending: Session.Queue,
431 running: Map[String, Job],
432 results: Map[String, Int]): Map[String, Int] =
434 if (pending.is_empty) results
435 else if (running.exists({ case (_, job) => job.is_finished })) {
436 val (name, job) = running.find({ case (_, job) => job.is_finished }).get
438 val (out, err, rc) = job.join
439 echo(Library.trim_line(err))
441 val log = log_dir + Path.basic(name)
444 (queue(name).digest :: deps.sources(name).map(_._2)).map(_.toString).sorted
445 .mkString("sources: ", " ", "\n")
446 File.write_zip(log.ext("gz"), sources + out)
450 echo(name + " FAILED")
451 echo("(see also " + log.file + ")")
452 val lines = split_lines(out)
453 val tail = lines.drop(lines.length - 20 max 0)
454 echo("\n" + cat_lines(tail))
456 loop(pending - name, running - name, results + (name -> rc))
458 else if (running.size < (max_jobs max 1)) {
459 pending.dequeue(running.isDefinedAt(_)) match {
460 case Some((name, info)) =>
462 loop(pending - name, running, results + (name -> 0))
464 else if (info.parent.map(results(_)).forall(_ == 0)) {
466 if (build_images || queue.is_inner(name))
467 Some(Isabelle_System.standard_path(output_dir + Path.basic(name)))
469 echo((if (output.isDefined) "Building " else "Running ") + name + " ...")
470 val job = start_job(name, info, output, info.options, timing, verbose, browser_info)
471 loop(pending, running + (name -> job), results)
474 echo(name + " CANCELLED")
475 loop(pending - name, running, results + (name -> 1))
477 case None => sleep(); loop(pending, running, results)
480 else { sleep(); loop(pending, running, results) }
483 val results = loop(queue, Map.empty, Map.empty)
484 val rc = (0 /: results)({ case (rc1, (_, rc2)) => rc1 max rc2 })
486 val unfinished = (for ((name, r) <- results.iterator if r != 0) yield name).toList.sorted
487 echo("Unfinished session(s): " + commas(unfinished))
493 /* command line entry point */
495 def main(args: Array[String])
500 Properties.Value.Boolean(all_sessions) ::
501 Properties.Value.Boolean(build_images) ::
502 Properties.Value.Int(max_jobs) ::
503 Properties.Value.Boolean(no_build) ::
504 Properties.Value.Boolean(system_mode) ::
505 Properties.Value.Boolean(timing) ::
506 Properties.Value.Boolean(verbose) ::
507 Command_Line.Chunks(more_dirs, options, sessions) =>
508 build(all_sessions, build_images, max_jobs, no_build, system_mode, timing,
509 verbose, more_dirs.map(Path.explode), options, sessions)
510 case _ => error("Bad arguments:\n" + cat_lines(args))