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