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