src/Pure/System/build.scala
author wenzelm
Sat Jul 21 22:13:50 2012 +0200 (2012-07-21)
changeset 48421 c4d337782de4
parent 48419 6d7b6e47f3ef
child 48422 9613780a805b
permissions -rw-r--r--
propagate defined options;
misc tuning;
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@48421
    44
    sealed abstract class Status
wenzelm@48421
    45
    case object Pending extends Status
wenzelm@48421
    46
    case object Running extends Status
wenzelm@48421
    47
wenzelm@48349
    48
    sealed case class Info(
wenzelm@48349
    49
      dir: Path,
wenzelm@48418
    50
      parent: Option[String],
wenzelm@48349
    51
      description: String,
wenzelm@48349
    52
      options: Options,
wenzelm@48421
    53
      theories: List[(Options, List[Path])],
wenzelm@48421
    54
      files: List[Path],
wenzelm@48421
    55
      status: Status = Pending)
wenzelm@48421
    56
wenzelm@48421
    57
wenzelm@48421
    58
    /* Queue */
wenzelm@48349
    59
wenzelm@48349
    60
    object Queue
wenzelm@48349
    61
    {
wenzelm@48349
    62
      val empty: Queue = new Queue()
wenzelm@48349
    63
    }
wenzelm@48349
    64
wenzelm@48349
    65
    final class Queue private(
wenzelm@48349
    66
      keys: Map[String, Key] = Map.empty,
wenzelm@48349
    67
      graph: Graph[Key, Info] = Graph.empty(Key.Ordering))
wenzelm@48349
    68
    {
wenzelm@48351
    69
      def defined(name: String): Boolean = keys.isDefinedAt(name)
wenzelm@48349
    70
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@48363
    92
      def required(names: List[String]): Queue =
wenzelm@48363
    93
      {
wenzelm@48363
    94
        val req = graph.all_preds(names.map(keys(_))).map(_.name).toSet
wenzelm@48363
    95
        val keys1 = keys -- keys.keySet.filter(name => !req(name))
wenzelm@48363
    96
        val graph1 = graph.restrict(key => keys1.isDefinedAt(key.name))
wenzelm@48363
    97
        new Queue(keys1, graph1)
wenzelm@48363
    98
      }
wenzelm@48363
    99
wenzelm@48351
   100
      def topological_order: List[(Key, Info)] =
wenzelm@48351
   101
        graph.topological_order.map(key => (key, graph.get_node(key)))
wenzelm@48349
   102
    }
wenzelm@48349
   103
  }
wenzelm@48334
   104
wenzelm@48337
   105
wenzelm@48337
   106
  /* parsing */
wenzelm@48337
   107
wenzelm@48337
   108
  private case class Session_Entry(
wenzelm@48337
   109
    name: String,
wenzelm@48337
   110
    reset: Boolean,
wenzelm@48349
   111
    order: Int,
wenzelm@48337
   112
    path: Option[String],
wenzelm@48347
   113
    parent: Option[String],
wenzelm@48337
   114
    description: String,
wenzelm@48421
   115
    options: List[Options.Spec],
wenzelm@48421
   116
    theories: List[(List[Options.Spec], List[String])],
wenzelm@48337
   117
    files: List[String])
wenzelm@48337
   118
wenzelm@48334
   119
  private object Parser extends Parse.Parser
wenzelm@48334
   120
  {
wenzelm@48334
   121
    val SESSION = "session"
wenzelm@48334
   122
    val IN = "in"
wenzelm@48334
   123
    val DESCRIPTION = "description"
wenzelm@48334
   124
    val OPTIONS = "options"
wenzelm@48334
   125
    val THEORIES = "theories"
wenzelm@48334
   126
    val FILES = "files"
wenzelm@48334
   127
wenzelm@48334
   128
    val syntax =
wenzelm@48336
   129
      Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
wenzelm@48336
   130
        SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
wenzelm@48334
   131
wenzelm@48337
   132
    val session_entry: Parser[Session_Entry] =
wenzelm@48334
   133
    {
wenzelm@48334
   134
      val session_name = atom("session name", _.is_name)
wenzelm@48334
   135
      val theory_name = atom("theory name", _.is_name)
wenzelm@48280
   136
wenzelm@48334
   137
      val option =
wenzelm@48334
   138
        name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@48337
   139
      val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
wenzelm@48334
   140
wenzelm@48334
   141
      val theories =
wenzelm@48334
   142
        keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
wenzelm@48334
   143
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@48334
   144
wenzelm@48334
   145
      ((keyword(SESSION) ~! session_name) ^^ { case _ ~ x => x }) ~
wenzelm@48336
   146
        (keyword("!") ^^^ true | success(false)) ~
wenzelm@48349
   147
        (keyword("(") ~! (nat <~ keyword(")")) ^^ { case _ ~ x => x } | success(Integer.MAX_VALUE)) ~
wenzelm@48337
   148
        (opt(keyword(IN) ~! string ^^ { case _ ~ x => x })) ~
wenzelm@48347
   149
        (keyword("=") ~> opt(session_name <~ keyword("+"))) ~
wenzelm@48334
   150
        (keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x } | success("")) ~
wenzelm@48334
   151
        (keyword(OPTIONS) ~! options ^^ { case _ ~ x => x } | success(Nil)) ~
wenzelm@48347
   152
        rep(theories) ~
wenzelm@48336
   153
        (keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x } | success(Nil)) ^^
wenzelm@48349
   154
          { case a ~ b ~ c ~ d ~ e ~ f ~ g ~ h ~ i => Session_Entry(a, b, c, d, e, f, g, h, i) }
wenzelm@48334
   155
    }
wenzelm@48334
   156
wenzelm@48409
   157
    def parse_entries(root: JFile): List[Session_Entry] =
wenzelm@48334
   158
    {
wenzelm@48411
   159
      val toks = syntax.scan(File.read(root))
wenzelm@48337
   160
      parse_all(rep(session_entry), Token.reader(toks, root.toString)) match {
wenzelm@48334
   161
        case Success(result, _) => result
wenzelm@48334
   162
        case bad => error(bad.toString)
wenzelm@48334
   163
      }
wenzelm@48334
   164
    }
wenzelm@48334
   165
  }
wenzelm@48280
   166
wenzelm@48337
   167
wenzelm@48341
   168
  /* find sessions */
wenzelm@48337
   169
wenzelm@48361
   170
  private val ROOT = Path.explode("ROOT")
wenzelm@48361
   171
  private val SESSIONS = Path.explode("etc/sessions")
wenzelm@48361
   172
wenzelm@48364
   173
  private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
wenzelm@48364
   174
wenzelm@48421
   175
  private def sessions_root(options: Options, dir: Path, root: JFile, queue: Session.Queue)
wenzelm@48421
   176
    : Session.Queue =
wenzelm@48280
   177
  {
wenzelm@48361
   178
    (queue /: Parser.parse_entries(root))((queue1, entry) =>
wenzelm@48337
   179
      try {
wenzelm@48347
   180
        if (entry.name == "") error("Bad session name")
wenzelm@48347
   181
wenzelm@48337
   182
        val full_name =
wenzelm@48364
   183
          if (is_pure(entry.name)) {
wenzelm@48347
   184
            if (entry.parent.isDefined) error("Illegal parent session")
wenzelm@48347
   185
            else entry.name
wenzelm@48347
   186
          }
wenzelm@48347
   187
          else
wenzelm@48347
   188
            entry.parent match {
wenzelm@48361
   189
              case Some(parent_name) if queue1.defined(parent_name) =>
wenzelm@48347
   190
                if (entry.reset) entry.name
wenzelm@48351
   191
                else parent_name + "-" + entry.name
wenzelm@48351
   192
              case _ => error("Bad parent session")
wenzelm@48347
   193
            }
wenzelm@48339
   194
wenzelm@48337
   195
        val path =
wenzelm@48337
   196
          entry.path match {
wenzelm@48337
   197
            case Some(p) => Path.explode(p)
wenzelm@48337
   198
            case None => Path.basic(entry.name)
wenzelm@48337
   199
          }
wenzelm@48339
   200
wenzelm@48351
   201
        val key = Session.Key(full_name, entry.order)
wenzelm@48421
   202
wenzelm@48421
   203
        val theories =
wenzelm@48421
   204
          entry.theories.map({ case (opts, thys) => (options ++ opts, thys.map(Path.explode(_))) })
wenzelm@48421
   205
        val files = entry.files.map(Path.explode(_))
wenzelm@48418
   206
        val info =
wenzelm@48418
   207
          Session.Info(dir + path, entry.parent,
wenzelm@48421
   208
            entry.description, options ++ entry.options, theories, files)
wenzelm@48351
   209
wenzelm@48418
   210
        queue1 + (key, info)
wenzelm@48337
   211
      }
wenzelm@48337
   212
      catch {
wenzelm@48337
   213
        case ERROR(msg) =>
wenzelm@48337
   214
          error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@48370
   215
            quote(entry.name) + Position.str_of(Position.file(root)))
wenzelm@48352
   216
      })
wenzelm@48352
   217
  }
wenzelm@48352
   218
wenzelm@48421
   219
  private def sessions_dir(options: Options, strict: Boolean, dir: Path, queue: Session.Queue)
wenzelm@48421
   220
    : Session.Queue =
wenzelm@48352
   221
  {
wenzelm@48373
   222
    val root = (dir + ROOT).file
wenzelm@48421
   223
    if (root.isFile) sessions_root(options, dir, root, queue)
wenzelm@48352
   224
    else if (strict) error("Bad session root file: " + quote(root.toString))
wenzelm@48361
   225
    else queue
wenzelm@48352
   226
  }
wenzelm@48352
   227
wenzelm@48421
   228
  private def sessions_catalog(options: Options, dir: Path, catalog: JFile, queue: Session.Queue)
wenzelm@48421
   229
    : Session.Queue =
wenzelm@48352
   230
  {
wenzelm@48354
   231
    val dirs =
wenzelm@48411
   232
      split_lines(File.read(catalog)).filterNot(line => line == "" || line.startsWith("#"))
wenzelm@48361
   233
    (queue /: dirs)((queue1, dir1) =>
wenzelm@48352
   234
      try {
wenzelm@48352
   235
        val dir2 = dir + Path.explode(dir1)
wenzelm@48421
   236
        if (dir2.file.isDirectory) sessions_dir(options, true, dir2, queue1)
wenzelm@48352
   237
        else error("Bad session directory: " + dir2.toString)
wenzelm@48337
   238
      }
wenzelm@48352
   239
      catch {
wenzelm@48352
   240
        case ERROR(msg) =>
wenzelm@48352
   241
          error(msg + "\nThe error(s) above occurred in session catalog " + quote(catalog.toString))
wenzelm@48352
   242
      })
wenzelm@48352
   243
  }
wenzelm@48352
   244
wenzelm@48421
   245
  def find_sessions(options: Options, all_sessions: Boolean, sessions: List[String],
wenzelm@48419
   246
    more_dirs: List[Path]): Session.Queue =
wenzelm@48352
   247
  {
wenzelm@48361
   248
    var queue = Session.Queue.empty
wenzelm@48352
   249
wenzelm@48352
   250
    for (dir <- Isabelle_System.components()) {
wenzelm@48421
   251
      queue = sessions_dir(options, false, dir, queue)
wenzelm@48352
   252
wenzelm@48373
   253
      val catalog = (dir + SESSIONS).file
wenzelm@48352
   254
      if (catalog.isFile)
wenzelm@48421
   255
        queue = sessions_catalog(options, dir, catalog, queue)
wenzelm@48337
   256
    }
wenzelm@48352
   257
wenzelm@48421
   258
    for (dir <- more_dirs) queue = sessions_dir(options, true, dir, queue)
wenzelm@48352
   259
wenzelm@48419
   260
    sessions.filter(name => !queue.defined(name)) match {
wenzelm@48419
   261
      case Nil =>
wenzelm@48419
   262
      case bad => error("Undefined session(s): " + commas_quote(bad))
wenzelm@48419
   263
    }
wenzelm@48419
   264
wenzelm@48419
   265
    if (all_sessions) queue else queue.required(sessions)
wenzelm@48280
   266
  }
wenzelm@48341
   267
wenzelm@48341
   268
wenzelm@48341
   269
wenzelm@48341
   270
  /** build **/
wenzelm@48341
   271
wenzelm@48373
   272
  private def echo(msg: String) { java.lang.System.out.println(msg) }
wenzelm@48373
   273
  private def echo_n(msg: String) { java.lang.System.out.print(msg) }
wenzelm@48373
   274
wenzelm@48418
   275
  class Build_Job(cwd: JFile, env: Map[String, String], script: String, args: String)
wenzelm@48364
   276
  {
wenzelm@48418
   277
    private val args_file = File.tmp_file("args")
wenzelm@48418
   278
    private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
wenzelm@48418
   279
    File.write(args_file, args)
wenzelm@48418
   280
wenzelm@48418
   281
    private val (thread, result) = Simple_Thread.future("build_job") {
wenzelm@48418
   282
      Isabelle_System.bash_env(cwd, env1, script)
wenzelm@48418
   283
    }
wenzelm@48418
   284
wenzelm@48418
   285
    def terminate: Unit = thread.interrupt
wenzelm@48418
   286
    def is_finished: Boolean = result.is_finished
wenzelm@48418
   287
    def join: (String, String, Int) = { val rc = result.join; args_file.delete; rc }
wenzelm@48418
   288
  }
wenzelm@48418
   289
wenzelm@48419
   290
  private def build_job(save: Boolean, name: String, info: Session.Info): Build_Job =
wenzelm@48418
   291
  {
wenzelm@48418
   292
    val parent = info.parent.getOrElse("")
wenzelm@48418
   293
wenzelm@48373
   294
    val cwd = info.dir.file
wenzelm@48418
   295
    val env = Map("INPUT" -> parent, "TARGET" -> name)
wenzelm@48364
   296
    val script =
wenzelm@48419
   297
      if (is_pure(name)) "./build " + (if (save) "-b " else "") + name
wenzelm@48418
   298
      else {
wenzelm@48418
   299
        """
wenzelm@48418
   300
        . "$ISABELLE_HOME/lib/scripts/timestart.bash"
wenzelm@48418
   301
        """ +
wenzelm@48419
   302
          (if (save)
wenzelm@48418
   303
            """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$TARGET" """
wenzelm@48418
   304
          else
wenzelm@48418
   305
            """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT" """) +
wenzelm@48418
   306
        """
wenzelm@48418
   307
        RC="$?"
wenzelm@48418
   308
wenzelm@48418
   309
        . "$ISABELLE_HOME/lib/scripts/timestop.bash"
wenzelm@48418
   310
wenzelm@48418
   311
        if [ "$RC" -eq 0 ]; then
wenzelm@48418
   312
          echo "Finished $TARGET ($TIMES_REPORT)" >&2
wenzelm@48418
   313
        fi
wenzelm@48418
   314
wenzelm@48418
   315
        exit "$RC"
wenzelm@48418
   316
        """
wenzelm@48418
   317
      }
wenzelm@48418
   318
    val args_xml =
wenzelm@48418
   319
    {
wenzelm@48418
   320
      import XML.Encode._
wenzelm@48421
   321
      pair(bool, pair(string, pair(string, list(string))))(
wenzelm@48421
   322
        save, (parent, (name, info.theories.map(_._2).flatten.map(_.implode))))
wenzelm@48418
   323
    }
wenzelm@48418
   324
    new Build_Job(cwd, env, script, YXML.string_of_body(args_xml))
wenzelm@48364
   325
  }
wenzelm@48364
   326
wenzelm@48341
   327
  def build(all_sessions: Boolean, build_images: Boolean, list_only: Boolean,
wenzelm@48419
   328
    more_dirs: List[Path], more_options: List[String], sessions: List[String]): Int =
wenzelm@48341
   329
  {
wenzelm@48419
   330
    val options = (Options.init() /: more_options)(_.define_simple(_))
wenzelm@48421
   331
    val queue = find_sessions(options, all_sessions, sessions, more_dirs)
wenzelm@48368
   332
wenzelm@48363
   333
wenzelm@48373
   334
    // prepare browser info dir
wenzelm@48419
   335
    if (options.bool("browser_info") &&
wenzelm@48373
   336
      !Path.explode("$ISABELLE_BROWSER_INFO/index.html").file.isFile)
wenzelm@48373
   337
    {
wenzelm@48373
   338
      Path.explode("$ISABELLE_BROWSER_INFO").file.mkdirs()
wenzelm@48411
   339
      File.copy(Path.explode("$ISABELLE_HOME/lib/logo/isabelle.gif"),
wenzelm@48411
   340
        Path.explode("$ISABELLE_BROWSER_INFO/isabelle.gif"))
wenzelm@48411
   341
      File.write(Path.explode("$ISABELLE_BROWSER_INFO/index.html"),
wenzelm@48411
   342
        File.read(Path.explode("$ISABELLE_HOME/lib/html/library_index_header.template")) +
wenzelm@48411
   343
        File.read(Path.explode("$ISABELLE_HOME/lib/html/library_index_content.template")) +
wenzelm@48411
   344
        File.read(Path.explode("$ISABELLE_HOME/lib/html/library_index_footer.template")))
wenzelm@48364
   345
    }
wenzelm@48341
   346
wenzelm@48373
   347
    // prepare log dir
wenzelm@48373
   348
    val log_dir = Path.explode("$ISABELLE_OUTPUT/log")
wenzelm@48373
   349
    log_dir.file.mkdirs()
wenzelm@48373
   350
wenzelm@48373
   351
    // run jobs
wenzelm@48373
   352
    val rcs =
wenzelm@48419
   353
      for ((key, info) <- queue.topological_order) yield
wenzelm@48373
   354
      {
wenzelm@48419
   355
        val name = key.name
wenzelm@48419
   356
wenzelm@48419
   357
        if (list_only) { echo(name + " in " + info.dir); 0 }
wenzelm@48373
   358
        else {
wenzelm@48419
   359
          val save = build_images || queue.is_inner(name)
wenzelm@48419
   360
          echo((if (save) "Building " else "Running ") + name + " ...")
wenzelm@48373
   361
wenzelm@48419
   362
          val (out, err, rc) = build_job(save, name, info).join
wenzelm@48373
   363
          echo_n(err)
wenzelm@48373
   364
wenzelm@48419
   365
          val log = log_dir + Path.basic(name)
wenzelm@48373
   366
          if (rc == 0) {
wenzelm@48411
   367
            File.write_zip(log.ext("gz"), out)
wenzelm@48373
   368
          }
wenzelm@48373
   369
          else {
wenzelm@48411
   370
            File.write(log, out)
wenzelm@48419
   371
            echo(name + " FAILED")
wenzelm@48373
   372
            echo("(see also " + log.file + ")")
wenzelm@48373
   373
            val lines = split_lines(out)
wenzelm@48373
   374
            val tail = lines.drop(lines.length - 20 max 0)
wenzelm@48373
   375
            echo("\n" + cat_lines(tail))
wenzelm@48373
   376
          }
wenzelm@48373
   377
          rc
wenzelm@48373
   378
        }
wenzelm@48373
   379
      }
wenzelm@48373
   380
    (0 /: rcs)(_ max _)
wenzelm@48341
   381
  }
wenzelm@48341
   382
wenzelm@48341
   383
wenzelm@48346
   384
  /* command line entry point */
wenzelm@48341
   385
wenzelm@48341
   386
  def main(args: Array[String])
wenzelm@48341
   387
  {
wenzelm@48346
   388
    Command_Line.tool {
wenzelm@48346
   389
      args.toList match {
wenzelm@48346
   390
        case
wenzelm@48346
   391
          Properties.Value.Boolean(all_sessions) ::
wenzelm@48346
   392
          Properties.Value.Boolean(build_images) ::
wenzelm@48346
   393
          Properties.Value.Boolean(list_only) ::
wenzelm@48346
   394
          Command_Line.Chunks(more_dirs, options, sessions) =>
wenzelm@48346
   395
            build(all_sessions, build_images, list_only,
wenzelm@48346
   396
              more_dirs.map(Path.explode), options, sessions)
wenzelm@48346
   397
        case _ => error("Bad arguments:\n" + cat_lines(args))
wenzelm@48341
   398
      }
wenzelm@48346
   399
    }
wenzelm@48341
   400
  }
wenzelm@48276
   401
}
wenzelm@48276
   402