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