src/Pure/System/build.scala
author wenzelm
Tue Jul 24 21:07:54 2012 +0200 (2012-07-24)
changeset 48485 2cbc3d284cd8
parent 48484 70898d016538
child 48494 00eb5be9e76b
permissions -rw-r--r--
tuned error;
wenzelm@48276
     1
/*  Title:      Pure/System/build.scala
wenzelm@48276
     2
    Author:     Makarius
wenzelm@48276
     3
wenzelm@48276
     4
Build and manage Isabelle sessions.
wenzelm@48276
     5
*/
wenzelm@48276
     6
wenzelm@48276
     7
package isabelle
wenzelm@48276
     8
wenzelm@48276
     9
wenzelm@48409
    10
import java.io.{File => JFile}
wenzelm@48335
    11
wenzelm@48337
    12
import scala.collection.mutable
wenzelm@48340
    13
import scala.annotation.tailrec
wenzelm@48337
    14
wenzelm@48335
    15
wenzelm@48276
    16
object Build
wenzelm@48276
    17
{
wenzelm@48337
    18
  /** session information **/
wenzelm@48334
    19
wenzelm@48349
    20
  object Session
wenzelm@48349
    21
  {
wenzelm@48421
    22
    /* Key */
wenzelm@48421
    23
wenzelm@48349
    24
    object Key
wenzelm@48349
    25
    {
wenzelm@48349
    26
      object Ordering extends scala.math.Ordering[Key]
wenzelm@48349
    27
      {
wenzelm@48349
    28
        def compare(key1: Key, key2: Key): Int =
wenzelm@48350
    29
          key1.order compare key2.order match {
wenzelm@48349
    30
            case 0 => key1.name compare key2.name
wenzelm@48349
    31
            case ord => ord
wenzelm@48349
    32
          }
wenzelm@48349
    33
      }
wenzelm@48349
    34
    }
wenzelm@48349
    35
wenzelm@48349
    36
    sealed case class Key(name: String, order: Int)
wenzelm@48349
    37
    {
wenzelm@48349
    38
      override def toString: String = name
wenzelm@48349
    39
    }
wenzelm@48349
    40
wenzelm@48421
    41
wenzelm@48421
    42
    /* Info */
wenzelm@48421
    43
wenzelm@48349
    44
    sealed case class Info(
wenzelm@48457
    45
      base_name: String,
wenzelm@48349
    46
      dir: Path,
wenzelm@48418
    47
      parent: Option[String],
wenzelm@48482
    48
      parent_base_name: Option[String],
wenzelm@48349
    49
      description: String,
wenzelm@48349
    50
      options: Options,
wenzelm@48421
    51
      theories: List[(Options, List[Path])],
wenzelm@48421
    52
      files: List[Path],
wenzelm@48424
    53
      digest: SHA1.Digest)
wenzelm@48421
    54
wenzelm@48421
    55
wenzelm@48421
    56
    /* Queue */
wenzelm@48349
    57
wenzelm@48349
    58
    object Queue
wenzelm@48349
    59
    {
wenzelm@48349
    60
      val empty: Queue = new Queue()
wenzelm@48349
    61
    }
wenzelm@48349
    62
wenzelm@48349
    63
    final class Queue private(
wenzelm@48349
    64
      keys: Map[String, Key] = Map.empty,
wenzelm@48349
    65
      graph: Graph[Key, Info] = Graph.empty(Key.Ordering))
wenzelm@48349
    66
    {
wenzelm@48425
    67
      def is_empty: Boolean = graph.is_empty
wenzelm@48425
    68
wenzelm@48425
    69
      def apply(name: String): Info = graph.get_node(keys(name))
wenzelm@48351
    70
      def defined(name: String): Boolean = keys.isDefinedAt(name)
wenzelm@48419
    71
      def is_inner(name: String): Boolean = !graph.is_maximal(keys(name))
wenzelm@48419
    72
wenzelm@48418
    73
      def + (key: Key, info: Info): Queue =
wenzelm@48349
    74
      {
wenzelm@48349
    75
        val keys1 =
wenzelm@48351
    76
          if (defined(key.name)) error("Duplicate session: " + quote(key.name))
wenzelm@48351
    77
          else keys + (key.name -> key)
wenzelm@48349
    78
wenzelm@48349
    79
        val graph1 =
wenzelm@48349
    80
          try {
wenzelm@48418
    81
            graph.new_node(key, info).add_deps_acyclic(key, info.parent.toList.map(keys(_)))
wenzelm@48349
    82
          }
wenzelm@48349
    83
          catch {
wenzelm@48349
    84
            case exn: Graph.Cycles[_] =>
wenzelm@48349
    85
              error(cat_lines(exn.cycles.map(cycle =>
wenzelm@48349
    86
                "Cyclic session dependency of " +
wenzelm@48349
    87
                  cycle.map(key => quote(key.toString)).mkString(" via "))))
wenzelm@48349
    88
          }
wenzelm@48349
    89
        new Queue(keys1, graph1)
wenzelm@48349
    90
      }
wenzelm@48349
    91
wenzelm@48425
    92
      def - (name: String): Queue = new Queue(keys - name, graph.del_node(keys(name)))
wenzelm@48425
    93
wenzelm@48363
    94
      def required(names: List[String]): Queue =
wenzelm@48363
    95
      {
wenzelm@48363
    96
        val req = graph.all_preds(names.map(keys(_))).map(_.name).toSet
wenzelm@48363
    97
        val keys1 = keys -- keys.keySet.filter(name => !req(name))
wenzelm@48363
    98
        val graph1 = graph.restrict(key => keys1.isDefinedAt(key.name))
wenzelm@48363
    99
        new Queue(keys1, graph1)
wenzelm@48363
   100
      }
wenzelm@48363
   101
wenzelm@48425
   102
      def dequeue(skip: String => Boolean): Option[(String, Info)] =
wenzelm@48425
   103
      {
wenzelm@48425
   104
        val it = graph.entries.dropWhile(
wenzelm@48425
   105
          { case (key, (_, (deps, _))) => !deps.isEmpty || skip(key.name) })
wenzelm@48425
   106
        if (it.hasNext) { val (key, (info, _)) = it.next; Some((key.name, info)) }
wenzelm@48425
   107
        else None
wenzelm@48425
   108
      }
wenzelm@48425
   109
wenzelm@48422
   110
      def topological_order: List[(String, Info)] =
wenzelm@48422
   111
        graph.topological_order.map(key => (key.name, graph.get_node(key)))
wenzelm@48349
   112
    }
wenzelm@48349
   113
  }
wenzelm@48334
   114
wenzelm@48337
   115
wenzelm@48337
   116
  /* parsing */
wenzelm@48337
   117
wenzelm@48337
   118
  private case class Session_Entry(
wenzelm@48337
   119
    name: String,
wenzelm@48462
   120
    this_name: Boolean,
wenzelm@48349
   121
    order: Int,
wenzelm@48337
   122
    path: Option[String],
wenzelm@48347
   123
    parent: Option[String],
wenzelm@48337
   124
    description: String,
wenzelm@48421
   125
    options: List[Options.Spec],
wenzelm@48421
   126
    theories: List[(List[Options.Spec], List[String])],
wenzelm@48337
   127
    files: List[String])
wenzelm@48337
   128
wenzelm@48334
   129
  private object Parser extends Parse.Parser
wenzelm@48334
   130
  {
wenzelm@48334
   131
    val SESSION = "session"
wenzelm@48334
   132
    val IN = "in"
wenzelm@48334
   133
    val DESCRIPTION = "description"
wenzelm@48334
   134
    val OPTIONS = "options"
wenzelm@48334
   135
    val THEORIES = "theories"
wenzelm@48334
   136
    val FILES = "files"
wenzelm@48334
   137
wenzelm@48334
   138
    val syntax =
wenzelm@48336
   139
      Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
wenzelm@48336
   140
        SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
wenzelm@48334
   141
wenzelm@48337
   142
    val session_entry: Parser[Session_Entry] =
wenzelm@48334
   143
    {
wenzelm@48334
   144
      val session_name = atom("session name", _.is_name)
wenzelm@48280
   145
wenzelm@48334
   146
      val option =
wenzelm@48334
   147
        name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@48337
   148
      val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
wenzelm@48334
   149
wenzelm@48334
   150
      val theories =
wenzelm@48334
   151
        keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
wenzelm@48334
   152
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@48334
   153
wenzelm@48334
   154
      ((keyword(SESSION) ~! session_name) ^^ { case _ ~ x => x }) ~
wenzelm@48336
   155
        (keyword("!") ^^^ true | success(false)) ~
wenzelm@48349
   156
        (keyword("(") ~! (nat <~ keyword(")")) ^^ { case _ ~ x => x } | success(Integer.MAX_VALUE)) ~
wenzelm@48337
   157
        (opt(keyword(IN) ~! string ^^ { case _ ~ x => x })) ~
wenzelm@48347
   158
        (keyword("=") ~> opt(session_name <~ keyword("+"))) ~
wenzelm@48334
   159
        (keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x } | success("")) ~
wenzelm@48334
   160
        (keyword(OPTIONS) ~! options ^^ { case _ ~ x => x } | success(Nil)) ~
wenzelm@48347
   161
        rep(theories) ~
wenzelm@48336
   162
        (keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x } | success(Nil)) ^^
wenzelm@48349
   163
          { case a ~ b ~ c ~ d ~ e ~ f ~ g ~ h ~ i => Session_Entry(a, b, c, d, e, f, g, h, i) }
wenzelm@48334
   164
    }
wenzelm@48334
   165
wenzelm@48409
   166
    def parse_entries(root: JFile): List[Session_Entry] =
wenzelm@48334
   167
    {
wenzelm@48411
   168
      val toks = syntax.scan(File.read(root))
wenzelm@48337
   169
      parse_all(rep(session_entry), Token.reader(toks, root.toString)) match {
wenzelm@48334
   170
        case Success(result, _) => result
wenzelm@48334
   171
        case bad => error(bad.toString)
wenzelm@48334
   172
      }
wenzelm@48334
   173
    }
wenzelm@48334
   174
  }
wenzelm@48280
   175
wenzelm@48337
   176
wenzelm@48341
   177
  /* find sessions */
wenzelm@48337
   178
wenzelm@48361
   179
  private val ROOT = Path.explode("ROOT")
wenzelm@48361
   180
  private val SESSIONS = Path.explode("etc/sessions")
wenzelm@48361
   181
wenzelm@48364
   182
  private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
wenzelm@48364
   183
wenzelm@48421
   184
  private def sessions_root(options: Options, dir: Path, root: JFile, queue: Session.Queue)
wenzelm@48421
   185
    : Session.Queue =
wenzelm@48280
   186
  {
wenzelm@48361
   187
    (queue /: Parser.parse_entries(root))((queue1, entry) =>
wenzelm@48337
   188
      try {
wenzelm@48347
   189
        if (entry.name == "") error("Bad session name")
wenzelm@48347
   190
wenzelm@48482
   191
        val (full_name, parent_base_name) =
wenzelm@48364
   192
          if (is_pure(entry.name)) {
wenzelm@48347
   193
            if (entry.parent.isDefined) error("Illegal parent session")
wenzelm@48482
   194
            else (entry.name, None: Option[String])
wenzelm@48347
   195
          }
wenzelm@48347
   196
          else
wenzelm@48347
   197
            entry.parent match {
wenzelm@48361
   198
              case Some(parent_name) if queue1.defined(parent_name) =>
wenzelm@48482
   199
                val full_name =
wenzelm@48482
   200
                  if (entry.this_name) entry.name
wenzelm@48482
   201
                  else parent_name + "-" + entry.name
wenzelm@48482
   202
                val parent_base_name = Some(queue1(parent_name).base_name)
wenzelm@48482
   203
                (full_name, parent_base_name)
wenzelm@48351
   204
              case _ => error("Bad parent session")
wenzelm@48347
   205
            }
wenzelm@48339
   206
wenzelm@48337
   207
        val path =
wenzelm@48337
   208
          entry.path match {
wenzelm@48337
   209
            case Some(p) => Path.explode(p)
wenzelm@48337
   210
            case None => Path.basic(entry.name)
wenzelm@48337
   211
          }
wenzelm@48339
   212
wenzelm@48351
   213
        val key = Session.Key(full_name, entry.order)
wenzelm@48421
   214
wenzelm@48467
   215
        val session_options = options ++ entry.options
wenzelm@48467
   216
wenzelm@48421
   217
        val theories =
wenzelm@48467
   218
          entry.theories.map({ case (opts, thys) =>
wenzelm@48467
   219
            (session_options ++ opts, thys.map(Path.explode(_))) })
wenzelm@48421
   220
        val files = entry.files.map(Path.explode(_))
wenzelm@48423
   221
        val digest = SHA1.digest((full_name, entry.parent, entry.options, entry.theories).toString)
wenzelm@48423
   222
wenzelm@48418
   223
        val info =
wenzelm@48482
   224
          Session.Info(entry.name, dir + path, entry.parent, parent_base_name,
wenzelm@48467
   225
            entry.description, session_options, theories, files, digest)
wenzelm@48351
   226
wenzelm@48418
   227
        queue1 + (key, info)
wenzelm@48337
   228
      }
wenzelm@48337
   229
      catch {
wenzelm@48337
   230
        case ERROR(msg) =>
wenzelm@48337
   231
          error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@48370
   232
            quote(entry.name) + Position.str_of(Position.file(root)))
wenzelm@48352
   233
      })
wenzelm@48352
   234
  }
wenzelm@48352
   235
wenzelm@48421
   236
  private def sessions_dir(options: Options, strict: Boolean, dir: Path, queue: Session.Queue)
wenzelm@48421
   237
    : Session.Queue =
wenzelm@48352
   238
  {
wenzelm@48373
   239
    val root = (dir + ROOT).file
wenzelm@48421
   240
    if (root.isFile) sessions_root(options, dir, root, queue)
wenzelm@48352
   241
    else if (strict) error("Bad session root file: " + quote(root.toString))
wenzelm@48361
   242
    else queue
wenzelm@48352
   243
  }
wenzelm@48352
   244
wenzelm@48421
   245
  private def sessions_catalog(options: Options, dir: Path, catalog: JFile, queue: Session.Queue)
wenzelm@48421
   246
    : Session.Queue =
wenzelm@48352
   247
  {
wenzelm@48354
   248
    val dirs =
wenzelm@48411
   249
      split_lines(File.read(catalog)).filterNot(line => line == "" || line.startsWith("#"))
wenzelm@48361
   250
    (queue /: dirs)((queue1, dir1) =>
wenzelm@48352
   251
      try {
wenzelm@48352
   252
        val dir2 = dir + Path.explode(dir1)
wenzelm@48421
   253
        if (dir2.file.isDirectory) sessions_dir(options, true, dir2, queue1)
wenzelm@48352
   254
        else error("Bad session directory: " + dir2.toString)
wenzelm@48337
   255
      }
wenzelm@48352
   256
      catch {
wenzelm@48352
   257
        case ERROR(msg) =>
wenzelm@48352
   258
          error(msg + "\nThe error(s) above occurred in session catalog " + quote(catalog.toString))
wenzelm@48352
   259
      })
wenzelm@48352
   260
  }
wenzelm@48352
   261
wenzelm@48421
   262
  def find_sessions(options: Options, all_sessions: Boolean, sessions: List[String],
wenzelm@48419
   263
    more_dirs: List[Path]): Session.Queue =
wenzelm@48352
   264
  {
wenzelm@48361
   265
    var queue = Session.Queue.empty
wenzelm@48352
   266
wenzelm@48352
   267
    for (dir <- Isabelle_System.components()) {
wenzelm@48421
   268
      queue = sessions_dir(options, false, dir, queue)
wenzelm@48352
   269
wenzelm@48373
   270
      val catalog = (dir + SESSIONS).file
wenzelm@48352
   271
      if (catalog.isFile)
wenzelm@48421
   272
        queue = sessions_catalog(options, dir, catalog, queue)
wenzelm@48337
   273
    }
wenzelm@48352
   274
wenzelm@48421
   275
    for (dir <- more_dirs) queue = sessions_dir(options, true, dir, queue)
wenzelm@48352
   276
wenzelm@48419
   277
    sessions.filter(name => !queue.defined(name)) match {
wenzelm@48419
   278
      case Nil =>
wenzelm@48419
   279
      case bad => error("Undefined session(s): " + commas_quote(bad))
wenzelm@48419
   280
    }
wenzelm@48419
   281
wenzelm@48419
   282
    if (all_sessions) queue else queue.required(sessions)
wenzelm@48280
   283
  }
wenzelm@48341
   284
wenzelm@48341
   285
wenzelm@48424
   286
wenzelm@48424
   287
  /** build **/
wenzelm@48424
   288
wenzelm@48478
   289
  private def echo(msg: String) { java.lang.System.out.println(msg) }
wenzelm@48478
   290
  private def sleep(): Unit = Thread.sleep(500)
wenzelm@48478
   291
wenzelm@48478
   292
wenzelm@48422
   293
  /* dependencies */
wenzelm@48422
   294
wenzelm@48422
   295
  sealed case class Node(
wenzelm@48422
   296
    loaded_theories: Set[String],
wenzelm@48423
   297
    sources: List[(Path, SHA1.Digest)])
wenzelm@48422
   298
wenzelm@48423
   299
  sealed case class Deps(deps: Map[String, Node])
wenzelm@48423
   300
  {
wenzelm@48423
   301
    def sources(name: String): List[(Path, SHA1.Digest)] = deps(name).sources
wenzelm@48423
   302
  }
wenzelm@48423
   303
wenzelm@48478
   304
  def dependencies(verbose: Boolean, queue: Session.Queue): Deps =
wenzelm@48423
   305
    Deps((Map.empty[String, Node] /: queue.topological_order)(
wenzelm@48422
   306
      { case (deps, (name, info)) =>
wenzelm@48422
   307
          val preloaded =
wenzelm@48422
   308
            info.parent match {
wenzelm@48422
   309
              case None => Set.empty[String]
wenzelm@48422
   310
              case Some(parent) => deps(parent).loaded_theories
wenzelm@48422
   311
            }
wenzelm@48422
   312
          val thy_info = new Thy_Info(new Thy_Load(preloaded))
wenzelm@48422
   313
wenzelm@48478
   314
          if (verbose) echo("Checking " + name)
wenzelm@48478
   315
wenzelm@48422
   316
          val thy_deps =
wenzelm@48422
   317
            thy_info.dependencies(
wenzelm@48422
   318
              info.theories.map(_._2).flatten.
wenzelm@48422
   319
                map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
wenzelm@48422
   320
wenzelm@48422
   321
          val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
wenzelm@48423
   322
wenzelm@48423
   323
          val all_files =
wenzelm@48422
   324
            thy_deps.map({ case (n, h) =>
wenzelm@48422
   325
              val thy = Path.explode(n.node).expand
wenzelm@48422
   326
              val uses =
wenzelm@48422
   327
                h match {
wenzelm@48422
   328
                  case Exn.Res(d) =>
wenzelm@48422
   329
                    d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
wenzelm@48422
   330
                  case _ => Nil
wenzelm@48422
   331
                }
wenzelm@48422
   332
              thy :: uses
wenzelm@48422
   333
            }).flatten ::: info.files.map(file => info.dir + file)
wenzelm@48485
   334
          val sources =
wenzelm@48485
   335
            try { all_files.map(p => (p, SHA1.digest(p))) }
wenzelm@48485
   336
            catch {
wenzelm@48485
   337
              case ERROR(msg) =>
wenzelm@48485
   338
                error(msg + "\nThe error(s) above occurred in session " + quote(name))
wenzelm@48485
   339
            }
wenzelm@48422
   340
wenzelm@48422
   341
          deps + (name -> Node(loaded_theories, sources))
wenzelm@48423
   342
      }))
wenzelm@48422
   343
wenzelm@48422
   344
wenzelm@48424
   345
  /* jobs */
wenzelm@48341
   346
wenzelm@48424
   347
  private class Job(cwd: JFile, env: Map[String, String], script: String, args: String)
wenzelm@48364
   348
  {
wenzelm@48418
   349
    private val args_file = File.tmp_file("args")
wenzelm@48418
   350
    private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
wenzelm@48418
   351
    File.write(args_file, args)
wenzelm@48418
   352
wenzelm@48424
   353
    private val (thread, result) =
wenzelm@48424
   354
      Simple_Thread.future("build") { Isabelle_System.bash_env(cwd, env1, script) }
wenzelm@48418
   355
wenzelm@48418
   356
    def terminate: Unit = thread.interrupt
wenzelm@48418
   357
    def is_finished: Boolean = result.is_finished
wenzelm@48425
   358
    def join: (String, String, Int) = { val res = result.join; args_file.delete; res }
wenzelm@48418
   359
  }
wenzelm@48418
   360
wenzelm@48457
   361
  private def start_job(name: String, info: Session.Info, output: Option[String],
wenzelm@48459
   362
    options: Options, timing: Boolean, verbose: Boolean, browser_info: Path): Job =
wenzelm@48418
   363
  {
wenzelm@48467
   364
    // global browser info dir
wenzelm@48467
   365
    if (options.bool("browser_info") && !(browser_info + Path.explode("index.html")).file.isFile)
wenzelm@48467
   366
    {
wenzelm@48467
   367
      browser_info.file.mkdirs()
wenzelm@48467
   368
      File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
wenzelm@48467
   369
        browser_info + Path.explode("isabelle.gif"))
wenzelm@48467
   370
      File.write(browser_info + Path.explode("index.html"),
wenzelm@48467
   371
        File.read(Path.explode("~~/lib/html/library_index_header.template")) +
wenzelm@48467
   372
        File.read(Path.explode("~~/lib/html/library_index_content.template")) +
wenzelm@48467
   373
        File.read(Path.explode("~~/lib/html/library_index_footer.template")))
wenzelm@48467
   374
    }
wenzelm@48467
   375
wenzelm@48418
   376
    val parent = info.parent.getOrElse("")
wenzelm@48482
   377
    val parent_base_name = info.parent_base_name.getOrElse("")
wenzelm@48418
   378
wenzelm@48373
   379
    val cwd = info.dir.file
wenzelm@48447
   380
    val env = Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> output.getOrElse(""))
wenzelm@48364
   381
    val script =
wenzelm@48447
   382
      if (is_pure(name)) "./build " + name + " \"$OUTPUT\""
wenzelm@48418
   383
      else {
wenzelm@48418
   384
        """
wenzelm@48418
   385
        . "$ISABELLE_HOME/lib/scripts/timestart.bash"
wenzelm@48418
   386
        """ +
wenzelm@48447
   387
          (if (output.isDefined)
wenzelm@48447
   388
            """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT" """
wenzelm@48418
   389
          else
wenzelm@48418
   390
            """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT" """) +
wenzelm@48418
   391
        """
wenzelm@48418
   392
        RC="$?"
wenzelm@48418
   393
wenzelm@48418
   394
        . "$ISABELLE_HOME/lib/scripts/timestop.bash"
wenzelm@48418
   395
wenzelm@48418
   396
        if [ "$RC" -eq 0 ]; then
wenzelm@48418
   397
          echo "Finished $TARGET ($TIMES_REPORT)" >&2
wenzelm@48418
   398
        fi
wenzelm@48418
   399
wenzelm@48418
   400
        exit "$RC"
wenzelm@48418
   401
        """
wenzelm@48418
   402
      }
wenzelm@48418
   403
    val args_xml =
wenzelm@48418
   404
    {
wenzelm@48418
   405
      import XML.Encode._
wenzelm@48459
   406
          pair(bool, pair(Options.encode, pair(bool, pair(bool, pair(Path.encode, pair(string,
wenzelm@48459
   407
            pair(string, pair(string, list(pair(Options.encode, list(Path.encode)))))))))))(
wenzelm@48482
   408
          (output.isDefined, (options, (timing, (verbose, (browser_info, (parent_base_name,
wenzelm@48459
   409
            (name, (info.base_name, info.theories)))))))))
wenzelm@48418
   410
    }
wenzelm@48424
   411
    new Job(cwd, env, script, YXML.string_of_body(args_xml))
wenzelm@48364
   412
  }
wenzelm@48364
   413
wenzelm@48424
   414
wenzelm@48425
   415
  /* build */
wenzelm@48424
   416
wenzelm@48425
   417
  def build(all_sessions: Boolean, build_images: Boolean, max_jobs: Int,
wenzelm@48469
   418
    no_build: Boolean, system_mode: Boolean, timing: Boolean, verbose: Boolean,
wenzelm@48419
   419
    more_dirs: List[Path], more_options: List[String], sessions: List[String]): Int =
wenzelm@48341
   420
  {
wenzelm@48419
   421
    val options = (Options.init() /: more_options)(_.define_simple(_))
wenzelm@48421
   422
    val queue = find_sessions(options, all_sessions, sessions, more_dirs)
wenzelm@48478
   423
    val deps = dependencies(verbose, queue)
wenzelm@48368
   424
wenzelm@48447
   425
    val (output_dir, browser_info) =
wenzelm@48447
   426
      if (system_mode) (Path.explode("~~/heaps/$ML_IDENTIFIER"), Path.explode("~~/browser_info"))
wenzelm@48447
   427
      else (Path.explode("$ISABELLE_OUTPUT"), Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48363
   428
wenzelm@48373
   429
    // prepare log dir
wenzelm@48447
   430
    val log_dir = output_dir + Path.explode("log")
wenzelm@48373
   431
    log_dir.file.mkdirs()
wenzelm@48373
   432
wenzelm@48425
   433
    // scheduler loop
wenzelm@48425
   434
    @tailrec def loop(
wenzelm@48425
   435
      pending: Session.Queue,
wenzelm@48425
   436
      running: Map[String, Job],
wenzelm@48425
   437
      results: Map[String, Int]): Map[String, Int] =
wenzelm@48425
   438
    {
wenzelm@48425
   439
      if (pending.is_empty) results
wenzelm@48425
   440
      else if (running.exists({ case (_, job) => job.is_finished })) {
wenzelm@48425
   441
        val (name, job) = running.find({ case (_, job) => job.is_finished }).get
wenzelm@48424
   442
wenzelm@48425
   443
        val (out, err, rc) = job.join
wenzelm@48425
   444
        echo(Library.trim_line(err))
wenzelm@48373
   445
wenzelm@48425
   446
        val log = log_dir + Path.basic(name)
wenzelm@48425
   447
        if (rc == 0) {
wenzelm@48425
   448
          val sources =
wenzelm@48425
   449
            (queue(name).digest :: deps.sources(name).map(_._2)).map(_.toString).sorted
wenzelm@48425
   450
              .mkString("sources: ", " ", "\n")
wenzelm@48425
   451
          File.write_zip(log.ext("gz"), sources + out)
wenzelm@48425
   452
        }
wenzelm@48425
   453
        else {
wenzelm@48425
   454
          File.write(log, out)
wenzelm@48425
   455
          echo(name + " FAILED")
wenzelm@48425
   456
          echo("(see also " + log.file + ")")
wenzelm@48425
   457
          val lines = split_lines(out)
wenzelm@48425
   458
          val tail = lines.drop(lines.length - 20 max 0)
wenzelm@48425
   459
          echo("\n" + cat_lines(tail))
wenzelm@48425
   460
        }
wenzelm@48425
   461
        loop(pending - name, running - name, results + (name -> rc))
wenzelm@48425
   462
      }
wenzelm@48425
   463
      else if (running.size < (max_jobs max 1)) {
wenzelm@48425
   464
        pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48425
   465
          case Some((name, info)) =>
wenzelm@48471
   466
            if (no_build) {
wenzelm@48425
   467
              loop(pending - name, running, results + (name -> 0))
wenzelm@48425
   468
            }
wenzelm@48425
   469
            else if (info.parent.map(results(_)).forall(_ == 0)) {
wenzelm@48447
   470
              val output =
wenzelm@48447
   471
                if (build_images || queue.is_inner(name))
wenzelm@48447
   472
                  Some(Isabelle_System.standard_path(output_dir + Path.basic(name)))
wenzelm@48447
   473
                else None
wenzelm@48447
   474
              echo((if (output.isDefined) "Building " else "Running ") + name + " ...")
wenzelm@48467
   475
              val job = start_job(name, info, output, info.options, timing, verbose, browser_info)
wenzelm@48425
   476
              loop(pending, running + (name -> job), results)
wenzelm@48425
   477
            }
wenzelm@48425
   478
            else {
wenzelm@48425
   479
              echo(name + " CANCELLED")
wenzelm@48425
   480
              loop(pending - name, running, results + (name -> 1))
wenzelm@48425
   481
            }
wenzelm@48425
   482
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   483
        }
wenzelm@48373
   484
      }
wenzelm@48425
   485
      else { sleep(); loop(pending, running, results) }
wenzelm@48425
   486
    }
wenzelm@48425
   487
wenzelm@48473
   488
    val results = loop(queue, Map.empty, Map.empty)
wenzelm@48473
   489
    val rc = (0 /: results)({ case (rc1, (_, rc2)) => rc1 max rc2 })
wenzelm@48473
   490
    if (rc != 0) {
wenzelm@48473
   491
      val unfinished = (for ((name, r) <- results.iterator if r != 0) yield name).toList.sorted
wenzelm@48473
   492
      echo("Unfinished session(s): " + commas(unfinished))
wenzelm@48473
   493
    }
wenzelm@48473
   494
    rc
wenzelm@48341
   495
  }
wenzelm@48341
   496
wenzelm@48341
   497
wenzelm@48346
   498
  /* command line entry point */
wenzelm@48341
   499
wenzelm@48341
   500
  def main(args: Array[String])
wenzelm@48341
   501
  {
wenzelm@48346
   502
    Command_Line.tool {
wenzelm@48346
   503
      args.toList match {
wenzelm@48346
   504
        case
wenzelm@48346
   505
          Properties.Value.Boolean(all_sessions) ::
wenzelm@48346
   506
          Properties.Value.Boolean(build_images) ::
wenzelm@48425
   507
          Properties.Value.Int(max_jobs) ::
wenzelm@48469
   508
          Properties.Value.Boolean(no_build) ::
wenzelm@48447
   509
          Properties.Value.Boolean(system_mode) ::
wenzelm@48459
   510
          Properties.Value.Boolean(timing) ::
wenzelm@48425
   511
          Properties.Value.Boolean(verbose) ::
wenzelm@48346
   512
          Command_Line.Chunks(more_dirs, options, sessions) =>
wenzelm@48469
   513
            build(all_sessions, build_images, max_jobs, no_build, system_mode, timing,
wenzelm@48447
   514
              verbose, more_dirs.map(Path.explode), options, sessions)
wenzelm@48346
   515
        case _ => error("Bad arguments:\n" + cat_lines(args))
wenzelm@48341
   516
      }
wenzelm@48346
   517
    }
wenzelm@48341
   518
  }
wenzelm@48276
   519
}
wenzelm@48276
   520