src/Pure/Tools/build.scala
author wenzelm
Sat Feb 23 12:55:59 2013 +0100 (2013-02-23)
changeset 51252 03d1fca818a4
parent 51244 d8ca566b22b3
child 51253 ab4c296a1e60
permissions -rw-r--r--
more explicit console interrupt handling;
wenzelm@50686
     1
/*  Title:      Pure/Tools/build.scala
wenzelm@48276
     2
    Author:     Makarius
wenzelm@50367
     3
    Options:    :folding=explicit:collapseFolds=1:
wenzelm@48276
     4
wenzelm@48276
     5
Build and manage Isabelle sessions.
wenzelm@48276
     6
*/
wenzelm@48276
     7
wenzelm@48276
     8
package isabelle
wenzelm@48276
     9
wenzelm@48276
    10
wenzelm@48661
    11
import java.util.{Timer, TimerTask}
wenzelm@48548
    12
import java.io.{BufferedInputStream, FileInputStream,
wenzelm@48494
    13
  BufferedReader, InputStreamReader, IOException}
wenzelm@48494
    14
import java.util.zip.GZIPInputStream
wenzelm@48335
    15
wenzelm@48676
    16
import scala.collection.SortedSet
wenzelm@48340
    17
import scala.annotation.tailrec
wenzelm@48337
    18
wenzelm@48335
    19
wenzelm@48276
    20
object Build
wenzelm@48276
    21
{
wenzelm@50366
    22
  /** progress context **/
wenzelm@50366
    23
wenzelm@50846
    24
  class Progress
wenzelm@50846
    25
  {
wenzelm@50367
    26
    def echo(msg: String) {}
wenzelm@50846
    27
    def theory(session: String, theory: String) {}
wenzelm@50367
    28
    def stopped: Boolean = false
wenzelm@50366
    29
  }
wenzelm@50366
    30
wenzelm@50367
    31
  object Ignore_Progress extends Progress
wenzelm@50366
    32
wenzelm@50846
    33
  class Console_Progress(verbose: Boolean) extends Progress
wenzelm@50846
    34
  {
wenzelm@50366
    35
    override def echo(msg: String) { java.lang.System.out.println(msg) }
wenzelm@50846
    36
    override def theory(session: String, theory: String): Unit =
wenzelm@50846
    37
      if (verbose) echo(session + ": theory " + theory)
wenzelm@51252
    38
wenzelm@51252
    39
    @volatile private var is_stopped = false
wenzelm@51252
    40
    def interrupt_handler[A](e: => A): A = Interrupt.handler { is_stopped = true } { e }
wenzelm@51252
    41
    override def stopped: Boolean = { val b = is_stopped; is_stopped = false; b  }
wenzelm@50366
    42
  }
wenzelm@50366
    43
wenzelm@50366
    44
wenzelm@50366
    45
wenzelm@48337
    46
  /** session information **/
wenzelm@48334
    47
wenzelm@48675
    48
  // external version
wenzelm@48675
    49
  sealed case class Session_Entry(
wenzelm@48675
    50
    pos: Position.T,
wenzelm@48738
    51
    name: String,
wenzelm@48675
    52
    groups: List[String],
wenzelm@48738
    53
    path: String,
wenzelm@48675
    54
    parent: Option[String],
wenzelm@48675
    55
    description: String,
wenzelm@48675
    56
    options: List[Options.Spec],
wenzelm@48675
    57
    theories: List[(List[Options.Spec], List[String])],
wenzelm@48675
    58
    files: List[String])
wenzelm@48675
    59
wenzelm@48675
    60
  // internal version
wenzelm@48675
    61
  sealed case class Session_Info(
wenzelm@48737
    62
    select: Boolean,
wenzelm@48675
    63
    pos: Position.T,
wenzelm@48675
    64
    groups: List[String],
wenzelm@48675
    65
    dir: Path,
wenzelm@48675
    66
    parent: Option[String],
wenzelm@48675
    67
    description: String,
wenzelm@48675
    68
    options: Options,
wenzelm@48675
    69
    theories: List[(Options, List[Path])],
wenzelm@48675
    70
    files: List[Path],
wenzelm@48675
    71
    entry_digest: SHA1.Digest)
wenzelm@48675
    72
wenzelm@48675
    73
  def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
wenzelm@48675
    74
wenzelm@48737
    75
  def session_info(options: Options, select: Boolean, dir: Path, entry: Session_Entry)
wenzelm@48737
    76
      : (String, Session_Info) =
wenzelm@48675
    77
    try {
wenzelm@48738
    78
      val name = entry.name
wenzelm@48675
    79
wenzelm@48738
    80
      if (name == "") error("Bad session name")
wenzelm@48738
    81
      if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
wenzelm@48738
    82
      if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
wenzelm@48675
    83
wenzelm@48675
    84
      val session_options = options ++ entry.options
wenzelm@48675
    85
wenzelm@48675
    86
      val theories =
wenzelm@48675
    87
        entry.theories.map({ case (opts, thys) =>
wenzelm@48675
    88
          (session_options ++ opts, thys.map(Path.explode(_))) })
wenzelm@48675
    89
      val files = entry.files.map(Path.explode(_))
wenzelm@48738
    90
      val entry_digest = SHA1.digest((name, entry.parent, entry.options, entry.theories).toString)
wenzelm@48675
    91
wenzelm@48675
    92
      val info =
wenzelm@48738
    93
        Session_Info(select, entry.pos, entry.groups, dir + Path.explode(entry.path),
wenzelm@48738
    94
          entry.parent, entry.description, session_options, theories, files, entry_digest)
wenzelm@48675
    95
wenzelm@48738
    96
      (name, info)
wenzelm@48675
    97
    }
wenzelm@48675
    98
    catch {
wenzelm@48675
    99
      case ERROR(msg) =>
wenzelm@48675
   100
        error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@48992
   101
          quote(entry.name) + Position.here(entry.pos))
wenzelm@48675
   102
    }
wenzelm@48675
   103
wenzelm@48675
   104
wenzelm@48676
   105
  /* session tree */
wenzelm@48676
   106
wenzelm@48676
   107
  object Session_Tree
wenzelm@48676
   108
  {
wenzelm@48676
   109
    def apply(infos: Seq[(String, Session_Info)]): Session_Tree =
wenzelm@48676
   110
    {
wenzelm@48680
   111
      val graph1 =
wenzelm@48680
   112
        (Graph.string[Session_Info] /: infos) {
wenzelm@48684
   113
          case (graph, (name, info)) =>
wenzelm@48680
   114
            if (graph.defined(name))
wenzelm@48992
   115
              error("Duplicate session " + quote(name) + Position.here(info.pos))
wenzelm@48680
   116
            else graph.new_node(name, info)
wenzelm@48680
   117
        }
wenzelm@48680
   118
      val graph2 =
wenzelm@48680
   119
        (graph1 /: graph1.entries) {
wenzelm@48680
   120
          case (graph, (name, (info, _))) =>
wenzelm@48680
   121
            info.parent match {
wenzelm@48680
   122
              case None => graph
wenzelm@48680
   123
              case Some(parent) =>
wenzelm@48680
   124
                if (!graph.defined(parent))
wenzelm@48680
   125
                  error("Bad parent session " + quote(parent) + " for " +
wenzelm@48992
   126
                    quote(name) + Position.here(info.pos))
wenzelm@48676
   127
wenzelm@48680
   128
                try { graph.add_edge_acyclic(parent, name) }
wenzelm@48680
   129
                catch {
wenzelm@48680
   130
                  case exn: Graph.Cycles[_] =>
wenzelm@48680
   131
                    error(cat_lines(exn.cycles.map(cycle =>
wenzelm@48680
   132
                      "Cyclic session dependency of " +
wenzelm@48680
   133
                        cycle.map(c => quote(c.toString)).mkString(" via "))) +
wenzelm@48992
   134
                          Position.here(info.pos))
wenzelm@48680
   135
                }
wenzelm@48676
   136
            }
wenzelm@48676
   137
        }
wenzelm@48680
   138
      new Session_Tree(graph2)
wenzelm@48676
   139
    }
wenzelm@48676
   140
  }
wenzelm@48676
   141
wenzelm@48680
   142
  final class Session_Tree private(val graph: Graph[String, Session_Info])
wenzelm@48676
   143
    extends PartialFunction[String, Session_Info]
wenzelm@48676
   144
  {
wenzelm@48680
   145
    def apply(name: String): Session_Info = graph.get_node(name)
wenzelm@48680
   146
    def isDefinedAt(name: String): Boolean = graph.defined(name)
wenzelm@48676
   147
wenzelm@49131
   148
    def selection(requirements: Boolean, all_sessions: Boolean,
wenzelm@49131
   149
      session_groups: List[String], sessions: List[String]): (List[String], Session_Tree) =
wenzelm@48676
   150
    {
wenzelm@48676
   151
      val bad_sessions = sessions.filterNot(isDefinedAt(_))
wenzelm@48676
   152
      if (!bad_sessions.isEmpty) error("Undefined session(s): " + commas_quote(bad_sessions))
wenzelm@48676
   153
wenzelm@49131
   154
      val pre_selected =
wenzelm@48676
   155
      {
wenzelm@48676
   156
        if (all_sessions) graph.keys.toList
wenzelm@48676
   157
        else {
wenzelm@48737
   158
          val select_group = session_groups.toSet
wenzelm@48737
   159
          val select = sessions.toSet
wenzelm@48737
   160
          (for {
wenzelm@48737
   161
            (name, (info, _)) <- graph.entries
wenzelm@48737
   162
            if info.select || select(name) || apply(name).groups.exists(select_group)
wenzelm@48737
   163
          } yield name).toList
wenzelm@48676
   164
        }
wenzelm@48676
   165
      }
wenzelm@49131
   166
      val selected =
wenzelm@49131
   167
        if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
wenzelm@49131
   168
        else pre_selected
wenzelm@49131
   169
wenzelm@48676
   170
      val tree1 = new Session_Tree(graph.restrict(graph.all_preds(selected).toSet))
wenzelm@49131
   171
      (selected, tree1)
wenzelm@48676
   172
    }
wenzelm@48676
   173
wenzelm@48676
   174
    def topological_order: List[(String, Session_Info)] =
wenzelm@48676
   175
      graph.topological_order.map(name => (name, apply(name)))
wenzelm@48794
   176
wenzelm@48794
   177
    override def toString: String = graph.entries.map(_._1).toList.sorted.mkString(",")
wenzelm@48676
   178
  }
wenzelm@48676
   179
wenzelm@48676
   180
wenzelm@48675
   181
  /* parser */
wenzelm@48675
   182
wenzelm@48713
   183
  private val SESSION = "session"
wenzelm@48713
   184
  private val IN = "in"
wenzelm@48713
   185
  private val DESCRIPTION = "description"
wenzelm@48713
   186
  private val OPTIONS = "options"
wenzelm@48713
   187
  private val THEORIES = "theories"
wenzelm@48713
   188
  private val FILES = "files"
wenzelm@48713
   189
wenzelm@48713
   190
  lazy val root_syntax =
wenzelm@48738
   191
    Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" +
wenzelm@48718
   192
      (SESSION, Keyword.THY_DECL) + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
wenzelm@48713
   193
wenzelm@48675
   194
  private object Parser extends Parse.Parser
wenzelm@48675
   195
  {
wenzelm@48675
   196
    def session_entry(pos: Position.T): Parser[Session_Entry] =
wenzelm@48675
   197
    {
wenzelm@48675
   198
      val session_name = atom("session name", _.is_name)
wenzelm@48675
   199
wenzelm@48675
   200
      val option =
wenzelm@48675
   201
        name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@48862
   202
      val options = keyword("[") ~> rep1sep(option, keyword(",")) <~ keyword("]")
wenzelm@48675
   203
wenzelm@48675
   204
      val theories =
wenzelm@48739
   205
        keyword(THEORIES) ~! ((options | success(Nil)) ~ rep(theory_name)) ^^
wenzelm@48675
   206
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@48675
   207
wenzelm@48912
   208
      command(SESSION) ~!
wenzelm@48912
   209
        (session_name ~
wenzelm@48912
   210
          ((keyword("(") ~! (rep1(name) <~ keyword(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@48912
   211
          ((keyword(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
wenzelm@48912
   212
          (keyword("=") ~!
wenzelm@48912
   213
            (opt(session_name ~! keyword("+") ^^ { case x ~ _ => x }) ~
wenzelm@48912
   214
              ((keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
wenzelm@48912
   215
              ((keyword(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@48916
   216
              rep1(theories) ~
wenzelm@48912
   217
              ((keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil))))) ^^
wenzelm@48912
   218
        { case _ ~ (a ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h))) =>
wenzelm@48912
   219
            Session_Entry(pos, a, b, c, d, e, f, g, h) }
wenzelm@48675
   220
    }
wenzelm@48675
   221
wenzelm@48675
   222
    def parse_entries(root: Path): List[Session_Entry] =
wenzelm@48675
   223
    {
wenzelm@48713
   224
      val toks = root_syntax.scan(File.read(root))
wenzelm@48675
   225
      parse_all(rep(session_entry(root.position)), Token.reader(toks, root.implode)) match {
wenzelm@48675
   226
        case Success(result, _) => result
wenzelm@48675
   227
        case bad => error(bad.toString)
wenzelm@48675
   228
      }
wenzelm@48675
   229
    }
wenzelm@48675
   230
  }
wenzelm@48675
   231
wenzelm@48675
   232
wenzelm@48675
   233
  /* find sessions within certain directories */
wenzelm@48675
   234
wenzelm@48675
   235
  private val ROOT = Path.explode("ROOT")
wenzelm@48684
   236
  private val ROOTS = Path.explode("ROOTS")
wenzelm@48675
   237
wenzelm@48684
   238
  private def is_session_dir(dir: Path): Boolean =
wenzelm@48684
   239
    (dir + ROOT).is_file || (dir + ROOTS).is_file
wenzelm@48684
   240
wenzelm@48684
   241
  private def check_session_dir(dir: Path): Path =
wenzelm@48684
   242
    if (is_session_dir(dir)) dir
wenzelm@48684
   243
    else error("Bad session root directory: " + dir.toString)
wenzelm@48675
   244
wenzelm@48737
   245
  def find_sessions(options: Options, more_dirs: List[(Boolean, Path)]): Session_Tree =
wenzelm@48675
   246
  {
wenzelm@48737
   247
    def find_dir(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48737
   248
      find_root(select, dir) ::: find_roots(select, dir)
wenzelm@48684
   249
wenzelm@48737
   250
    def find_root(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48684
   251
    {
wenzelm@48684
   252
      val root = dir + ROOT
wenzelm@48737
   253
      if (root.is_file) Parser.parse_entries(root).map(session_info(options, select, dir, _))
wenzelm@48684
   254
      else Nil
wenzelm@48684
   255
    }
wenzelm@48684
   256
wenzelm@48737
   257
    def find_roots(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48684
   258
    {
wenzelm@48684
   259
      val roots = dir + ROOTS
wenzelm@48684
   260
      if (roots.is_file) {
wenzelm@48684
   261
        for {
wenzelm@48684
   262
          line <- split_lines(File.read(roots))
wenzelm@48684
   263
          if !(line == "" || line.startsWith("#"))
wenzelm@48684
   264
          dir1 =
wenzelm@48684
   265
            try { check_session_dir(dir + Path.explode(line)) }
wenzelm@48684
   266
            catch {
wenzelm@48684
   267
              case ERROR(msg) =>
wenzelm@48684
   268
                error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
wenzelm@48684
   269
            }
wenzelm@48737
   270
          info <- find_dir(select, dir1)
wenzelm@48684
   271
        } yield info
wenzelm@48684
   272
      }
wenzelm@48684
   273
      else Nil
wenzelm@48684
   274
    }
wenzelm@48684
   275
wenzelm@48737
   276
    val default_dirs = Isabelle_System.components().filter(is_session_dir(_)).map((false, _))
wenzelm@48737
   277
wenzelm@48737
   278
    more_dirs foreach { case (_, dir) => check_session_dir(dir) }
wenzelm@48737
   279
wenzelm@48684
   280
    Session_Tree(
wenzelm@48684
   281
      for {
wenzelm@48737
   282
        (select, dir) <- default_dirs ::: more_dirs
wenzelm@48737
   283
        info <- find_dir(select, dir)
wenzelm@48684
   284
      } yield info)
wenzelm@48349
   285
  }
wenzelm@48334
   286
wenzelm@48337
   287
wenzelm@48424
   288
wenzelm@48424
   289
  /** build **/
wenzelm@48424
   290
wenzelm@48676
   291
  /* queue */
wenzelm@48676
   292
wenzelm@48676
   293
  object Queue
wenzelm@48676
   294
  {
wenzelm@51230
   295
    def apply(tree: Session_Tree, load_timings: String => (List[Properties.T], Double)): Queue =
wenzelm@48676
   296
    {
wenzelm@48676
   297
      val graph = tree.graph
wenzelm@51220
   298
      val sessions = graph.keys.toList
wenzelm@51220
   299
wenzelm@51230
   300
      val timings = sessions.map((name: String) =>
wenzelm@51230
   301
        if (tree(name).options.bool("parallel_proofs_reuse_timing")) (name, load_timings(name))
wenzelm@51230
   302
        else (name, (Nil, 0.0)))
wenzelm@51220
   303
      val command_timings =
wenzelm@51220
   304
        Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
wenzelm@51220
   305
      val session_timing =
wenzelm@51220
   306
        Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
wenzelm@48678
   307
wenzelm@48678
   308
      def outdegree(name: String): Int = graph.imm_succs(name).size
wenzelm@48678
   309
      def timeout(name: String): Double = tree(name).options.real("timeout")
wenzelm@48678
   310
wenzelm@48678
   311
      object Ordering extends scala.math.Ordering[String]
wenzelm@48678
   312
      {
wenzelm@51227
   313
        def compare_timing(name1: String, name2: String): Int =
wenzelm@51227
   314
        {
wenzelm@51227
   315
          val t1 = session_timing(name1)
wenzelm@51227
   316
          val t2 = session_timing(name2)
wenzelm@51227
   317
          if (t1 == 0.0 || t2 == 0.0) 0
wenzelm@51227
   318
          else t1 compare t2
wenzelm@51227
   319
        }
wenzelm@51227
   320
wenzelm@48678
   321
        def compare(name1: String, name2: String): Int =
wenzelm@51229
   322
          outdegree(name2) compare outdegree(name1) match {
wenzelm@48678
   323
            case 0 =>
wenzelm@51229
   324
              compare_timing(name2, name1) match {
wenzelm@51220
   325
                case 0 =>
wenzelm@51220
   326
                  timeout(name2) compare timeout(name1) match {
wenzelm@51220
   327
                    case 0 => name1 compare name2
wenzelm@51220
   328
                    case ord => ord
wenzelm@51220
   329
                  }
wenzelm@48678
   330
                case ord => ord
wenzelm@48678
   331
              }
wenzelm@48678
   332
            case ord => ord
wenzelm@48678
   333
          }
wenzelm@48678
   334
      }
wenzelm@48678
   335
wenzelm@51220
   336
      new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
wenzelm@48676
   337
    }
wenzelm@48676
   338
  }
wenzelm@48676
   339
wenzelm@51220
   340
  final class Queue private(
wenzelm@51220
   341
    graph: Graph[String, Session_Info],
wenzelm@51220
   342
    order: SortedSet[String],
wenzelm@51220
   343
    val command_timings: String => List[Properties.T])
wenzelm@48676
   344
  {
wenzelm@48676
   345
    def is_inner(name: String): Boolean = !graph.is_maximal(name)
wenzelm@48676
   346
wenzelm@48676
   347
    def is_empty: Boolean = graph.is_empty
wenzelm@48676
   348
wenzelm@51227
   349
    def - (name: String): Queue =
wenzelm@51227
   350
      new Queue(graph.del_node(name),
wenzelm@51227
   351
        order - name,  // FIXME scala-2.10.0 TreeSet problem!?
wenzelm@51227
   352
        command_timings)
wenzelm@48676
   353
wenzelm@48676
   354
    def dequeue(skip: String => Boolean): Option[(String, Session_Info)] =
wenzelm@48676
   355
    {
wenzelm@51227
   356
      val it = order.iterator.dropWhile(name =>
wenzelm@51227
   357
        skip(name)
wenzelm@51227
   358
          || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
wenzelm@51227
   359
          || !graph.is_minimal(name))
wenzelm@48680
   360
      if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
wenzelm@48676
   361
      else None
wenzelm@48676
   362
    }
wenzelm@48676
   363
  }
wenzelm@48676
   364
wenzelm@48676
   365
wenzelm@48710
   366
  /* source dependencies and static content */
wenzelm@48422
   367
wenzelm@48710
   368
  sealed case class Session_Content(
wenzelm@48422
   369
    loaded_theories: Set[String],
wenzelm@48660
   370
    syntax: Outer_Syntax,
wenzelm@48794
   371
    sources: List[(Path, SHA1.Digest)],
wenzelm@48794
   372
    errors: List[String])
wenzelm@48794
   373
  {
wenzelm@48794
   374
    def check_errors: Session_Content =
wenzelm@48794
   375
    {
wenzelm@48794
   376
      if (errors.isEmpty) this
wenzelm@48794
   377
      else error(cat_lines(errors))
wenzelm@48794
   378
    }
wenzelm@48794
   379
  }
wenzelm@48422
   380
wenzelm@48710
   381
  sealed case class Deps(deps: Map[String, Session_Content])
wenzelm@48423
   382
  {
wenzelm@48583
   383
    def is_empty: Boolean = deps.isEmpty
wenzelm@48710
   384
    def apply(name: String): Session_Content = deps(name)
wenzelm@48504
   385
    def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
wenzelm@48423
   386
  }
wenzelm@48423
   387
wenzelm@50366
   388
  def dependencies(progress: Build.Progress, inlined_files: Boolean,
wenzelm@50366
   389
      verbose: Boolean, list_files: Boolean, tree: Session_Tree): Deps =
wenzelm@48710
   390
    Deps((Map.empty[String, Session_Content] /: tree.topological_order)(
wenzelm@48422
   391
      { case (deps, (name, info)) =>
wenzelm@48794
   392
          val (preloaded, parent_syntax, parent_errors) =
wenzelm@48422
   393
            info.parent match {
wenzelm@48870
   394
              case None =>
wenzelm@48870
   395
                (Set.empty[String], Outer_Syntax.init_pure(), Nil)
wenzelm@48794
   396
              case Some(parent_name) =>
wenzelm@48794
   397
                val parent = deps(parent_name)
wenzelm@48794
   398
                (parent.loaded_theories, parent.syntax, parent.errors)
wenzelm@48422
   399
            }
wenzelm@48870
   400
          val thy_info = new Thy_Info(new Thy_Load(preloaded, parent_syntax))
wenzelm@48422
   401
wenzelm@48903
   402
          if (verbose || list_files) {
wenzelm@48583
   403
            val groups =
wenzelm@48583
   404
              if (info.groups.isEmpty) ""
wenzelm@48583
   405
              else info.groups.mkString(" (", " ", ")")
wenzelm@50366
   406
            progress.echo("Session " + name + groups)
wenzelm@48583
   407
          }
wenzelm@48478
   408
wenzelm@48422
   409
          val thy_deps =
wenzelm@49098
   410
            thy_info.dependencies(inlined_files,
wenzelm@48422
   411
              info.theories.map(_._2).flatten.
wenzelm@50566
   412
                map(thy => Thy_Load.path_node_name(info.dir + Thy_Load.thy_path(thy))))
wenzelm@48422
   413
wenzelm@48872
   414
          val loaded_theories = thy_deps.loaded_theories
wenzelm@48883
   415
          val syntax = thy_deps.make_syntax
wenzelm@48660
   416
wenzelm@48423
   417
          val all_files =
wenzelm@50414
   418
            (thy_deps.deps.map({ case dep =>
wenzelm@50414
   419
              val thy = Path.explode(dep.name.node)
wenzelm@50414
   420
              val uses = dep.join_header.uses.map(p =>
wenzelm@50414
   421
                Path.explode(dep.name.dir) + Path.explode(p._1))
wenzelm@48422
   422
              thy :: uses
wenzelm@48904
   423
            }).flatten ::: info.files.map(file => info.dir + file)).map(_.expand)
wenzelm@48903
   424
wenzelm@48903
   425
          if (list_files)
wenzelm@50366
   426
            progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
wenzelm@48903
   427
wenzelm@48485
   428
          val sources =
wenzelm@49696
   429
            try { all_files.map(p => (p, SHA1.digest(p.file))) }
wenzelm@48485
   430
            catch {
wenzelm@48485
   431
              case ERROR(msg) =>
wenzelm@48675
   432
                error(msg + "\nThe error(s) above occurred in session " +
wenzelm@48992
   433
                  quote(name) + Position.here(info.pos))
wenzelm@48485
   434
            }
wenzelm@50414
   435
          val errors = parent_errors ::: thy_deps.deps.map(dep => dep.join_header.errors).flatten
wenzelm@48422
   436
wenzelm@48794
   437
          deps + (name -> Session_Content(loaded_theories, syntax, sources, errors))
wenzelm@48423
   438
      }))
wenzelm@48422
   439
wenzelm@49098
   440
  def session_content(inlined_files: Boolean, dirs: List[Path], session: String): Session_Content =
wenzelm@48710
   441
  {
wenzelm@50404
   442
    val options = Options.init()
wenzelm@48791
   443
    val (_, tree) =
wenzelm@49131
   444
      find_sessions(options, dirs.map((false, _))).selection(false, false, Nil, List(session))
wenzelm@50366
   445
    dependencies(Build.Ignore_Progress, inlined_files, false, false, tree)(session)
wenzelm@48710
   446
  }
wenzelm@48710
   447
wenzelm@48794
   448
  def outer_syntax(session: String): Outer_Syntax =
wenzelm@49098
   449
    session_content(false, Nil, session).check_errors.syntax
wenzelm@48710
   450
wenzelm@48422
   451
wenzelm@48424
   452
  /* jobs */
wenzelm@48341
   453
wenzelm@50845
   454
  private class Job(progress: Build.Progress,
wenzelm@50845
   455
    name: String, val info: Session_Info, output: Path, do_output: Boolean,
wenzelm@51220
   456
    verbose: Boolean, browser_info: Path, command_timings: List[Properties.T])
wenzelm@48418
   457
  {
wenzelm@48467
   458
    // global browser info dir
wenzelm@48674
   459
    if (info.options.bool("browser_info") && !(browser_info + Path.explode("index.html")).is_file)
wenzelm@48467
   460
    {
wenzelm@50893
   461
      Isabelle_System.mkdirs(browser_info)
wenzelm@48467
   462
      File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
wenzelm@48467
   463
        browser_info + Path.explode("isabelle.gif"))
wenzelm@48467
   464
      File.write(browser_info + Path.explode("index.html"),
wenzelm@48467
   465
        File.read(Path.explode("~~/lib/html/library_index_header.template")) +
wenzelm@48724
   466
        File.read(Path.explode("~~/lib/html/library_index_content.template")) +
wenzelm@48467
   467
        File.read(Path.explode("~~/lib/html/library_index_footer.template")))
wenzelm@48467
   468
    }
wenzelm@48467
   469
wenzelm@48674
   470
    def output_path: Option[Path] = if (do_output) Some(output) else None
wenzelm@48674
   471
wenzelm@48674
   472
    private val parent = info.parent.getOrElse("")
wenzelm@48418
   473
wenzelm@48698
   474
    private val args_file = File.tmp_file("args")
wenzelm@48698
   475
    File.write(args_file, YXML.string_of_body(
wenzelm@48698
   476
      if (is_pure(name)) Options.encode(info.options)
wenzelm@48698
   477
      else
wenzelm@48698
   478
        {
wenzelm@48698
   479
          import XML.Encode._
wenzelm@51218
   480
              pair(list(properties), pair(bool, pair(Options.encode, pair(bool, pair(Path.encode,
wenzelm@51218
   481
                pair(string, pair(string, list(pair(Options.encode, list(Path.encode))))))))))(
wenzelm@51220
   482
              (command_timings, (do_output, (info.options, (verbose, (browser_info,
wenzelm@51218
   483
                (parent, (name, info.theories))))))))
wenzelm@48698
   484
        }))
wenzelm@48698
   485
wenzelm@48674
   486
    private val env =
wenzelm@48698
   487
      Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output),
wenzelm@48698
   488
        (if (is_pure(name)) "ISABELLE_PROCESS_OPTIONS" else "ARGS_FILE") ->
wenzelm@50715
   489
          Isabelle_System.posix_path(args_file))
wenzelm@48698
   490
wenzelm@48674
   491
    private val script =
wenzelm@48511
   492
      if (is_pure(name)) {
wenzelm@48511
   493
        if (do_output) "./build " + name + " \"$OUTPUT\""
wenzelm@48511
   494
        else """ rm -f "$OUTPUT"; ./build """ + name
wenzelm@48511
   495
      }
wenzelm@48418
   496
      else {
wenzelm@48418
   497
        """
wenzelm@48418
   498
        . "$ISABELLE_HOME/lib/scripts/timestart.bash"
wenzelm@48418
   499
        """ +
wenzelm@48511
   500
          (if (do_output)
wenzelm@48511
   501
            """
wenzelm@48511
   502
            "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
wenzelm@48511
   503
            """
wenzelm@48418
   504
          else
wenzelm@48511
   505
            """
wenzelm@48511
   506
            rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
wenzelm@48511
   507
            """) +
wenzelm@48418
   508
        """
wenzelm@48418
   509
        RC="$?"
wenzelm@48418
   510
wenzelm@48418
   511
        . "$ISABELLE_HOME/lib/scripts/timestop.bash"
wenzelm@48418
   512
wenzelm@48418
   513
        if [ "$RC" -eq 0 ]; then
wenzelm@48418
   514
          echo "Finished $TARGET ($TIMES_REPORT)" >&2
wenzelm@48418
   515
        fi
wenzelm@48418
   516
wenzelm@48418
   517
        exit "$RC"
wenzelm@48418
   518
        """
wenzelm@48418
   519
      }
wenzelm@48674
   520
wenzelm@48674
   521
    private val (thread, result) =
wenzelm@50845
   522
      Simple_Thread.future("build") {
wenzelm@50845
   523
        Isabelle_System.bash_env(info.dir.file, env, script,
wenzelm@50845
   524
          out_progress = (line: String) =>
wenzelm@50847
   525
            Library.try_unprefix("\floading_theory = ", line) match {
wenzelm@50847
   526
              case Some(theory) => progress.theory(name, theory)
wenzelm@50847
   527
              case None =>
wenzelm@50847
   528
            })
wenzelm@50845
   529
      }
wenzelm@48674
   530
wenzelm@48674
   531
    def terminate: Unit = thread.interrupt
wenzelm@48674
   532
    def is_finished: Boolean = result.is_finished
wenzelm@48674
   533
wenzelm@48674
   534
    @volatile private var timeout = false
wenzelm@50207
   535
    private val time = info.options.seconds("timeout")
wenzelm@48674
   536
    private val timer: Option[Timer] =
wenzelm@48674
   537
      if (time.seconds > 0.0) {
wenzelm@48674
   538
        val t = new Timer("build", true)
wenzelm@48674
   539
        t.schedule(new TimerTask { def run = { terminate; timeout = true } }, time.ms)
wenzelm@48674
   540
        Some(t)
wenzelm@48674
   541
      }
wenzelm@48674
   542
      else None
wenzelm@48674
   543
wenzelm@50845
   544
    def join: Isabelle_System.Bash_Result =
wenzelm@50845
   545
    {
wenzelm@50845
   546
      val res = result.join
wenzelm@50845
   547
wenzelm@48674
   548
      args_file.delete
wenzelm@48674
   549
      timer.map(_.cancel())
wenzelm@48674
   550
wenzelm@50845
   551
      if (res.rc == 130)
wenzelm@50845
   552
        res.add_err(if (timeout) "*** Timeout" else "*** Interrupt")
wenzelm@50845
   553
      else res
wenzelm@48674
   554
    }
wenzelm@48364
   555
  }
wenzelm@48364
   556
wenzelm@48424
   557
wenzelm@51045
   558
  /* inlined properties (YXML) */
wenzelm@50946
   559
wenzelm@50946
   560
  object Props
wenzelm@50946
   561
  {
wenzelm@51045
   562
    def parse(text: String): Properties.T = XML.Decode.properties(YXML.parse_body(text))
wenzelm@50946
   563
wenzelm@50946
   564
    def parse_lines(prefix: String, lines: List[String]): List[Properties.T] =
wenzelm@50946
   565
      for (line <- lines; s <- Library.try_unprefix(prefix, line)) yield parse(s)
wenzelm@50946
   566
wenzelm@50946
   567
    def find_parse_line(prefix: String, lines: List[String]): Option[Properties.T] =
wenzelm@50946
   568
      lines.find(_.startsWith(prefix)).map(line => parse(line.substring(prefix.length)))
wenzelm@50946
   569
  }
wenzelm@50946
   570
wenzelm@50946
   571
wenzelm@50777
   572
  /* log files */
wenzelm@48504
   573
wenzelm@48505
   574
  private val LOG = Path.explode("log")
wenzelm@48505
   575
  private def log(name: String): Path = LOG + Path.basic(name)
wenzelm@48505
   576
  private def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@48504
   577
wenzelm@50982
   578
  private val SESSION_NAME = "\fSession.name = "
wenzelm@50707
   579
  private val SESSION_PARENT_PATH = "\fSession.parent_path = "
wenzelm@50707
   580
wenzelm@50946
   581
wenzelm@50975
   582
  sealed case class Log_Info(
wenzelm@51220
   583
    name: String,
wenzelm@51220
   584
    stats: List[Properties.T],
wenzelm@51220
   585
    tasks: List[Properties.T],
wenzelm@51220
   586
    command_timings: List[Properties.T],
wenzelm@51220
   587
    session_timing: Properties.T)
wenzelm@50777
   588
wenzelm@51220
   589
  def parse_log(full_stats: Boolean, text: String): Log_Info =
wenzelm@50777
   590
  {
wenzelm@50777
   591
    val lines = split_lines(text)
wenzelm@51223
   592
    val xml_cache = new XML.Cache()
wenzelm@51223
   593
    def parse_lines(prfx: String): List[Properties.T] =
wenzelm@51223
   594
      Props.parse_lines(prfx, lines).map(xml_cache.cache_props)
wenzelm@51223
   595
wenzelm@50982
   596
    val name =
wenzelm@50982
   597
      lines.find(_.startsWith(SESSION_NAME)).map(_.substring(SESSION_NAME.length)) getOrElse ""
wenzelm@51223
   598
    val stats = if (full_stats) parse_lines("\fML_statistics = ") else Nil
wenzelm@51223
   599
    val tasks = if (full_stats) parse_lines("\ftask_statistics = ") else Nil
wenzelm@51223
   600
    val command_timings = parse_lines("\fcommand_timing = ")
wenzelm@51220
   601
    val session_timing = Props.find_parse_line("\fTiming = ", lines) getOrElse Nil
wenzelm@51220
   602
    Log_Info(name, stats, tasks, command_timings, session_timing)
wenzelm@50777
   603
  }
wenzelm@50777
   604
wenzelm@50777
   605
wenzelm@50777
   606
  /* sources and heaps */
wenzelm@50777
   607
wenzelm@48505
   608
  private def sources_stamp(digests: List[SHA1.Digest]): String =
wenzelm@48504
   609
    digests.map(_.toString).sorted.mkString("sources: ", " ", "")
wenzelm@48504
   610
wenzelm@48639
   611
  private val no_heap: String = "heap: -"
wenzelm@48639
   612
wenzelm@48639
   613
  private def heap_stamp(heap: Option[Path]): String =
wenzelm@48504
   614
  {
wenzelm@48504
   615
    "heap: " +
wenzelm@48639
   616
      (heap match {
wenzelm@48504
   617
        case Some(path) =>
wenzelm@48504
   618
          val file = path.file
wenzelm@48504
   619
          if (file.isFile) file.length.toString + " " + file.lastModified.toString
wenzelm@48504
   620
          else "-"
wenzelm@48504
   621
        case None => "-"
wenzelm@48504
   622
      })
wenzelm@48504
   623
  }
wenzelm@48504
   624
wenzelm@48639
   625
  private def read_stamps(path: Path): Option[(String, String, String)] =
wenzelm@48639
   626
    if (path.is_file) {
wenzelm@48639
   627
      val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(path.file)))
wenzelm@50203
   628
      val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
wenzelm@48639
   629
      val (s, h1, h2) =
wenzelm@48639
   630
        try { (reader.readLine, reader.readLine, reader.readLine) }
wenzelm@48639
   631
        finally { reader.close }
wenzelm@48639
   632
      if (s != null && s.startsWith("sources: ") &&
wenzelm@48639
   633
          h1 != null && h1.startsWith("heap: ") &&
wenzelm@48639
   634
          h2 != null && h2.startsWith("heap: ")) Some((s, h1, h2))
wenzelm@48504
   635
      else None
wenzelm@48504
   636
    }
wenzelm@48504
   637
    else None
wenzelm@48504
   638
wenzelm@48504
   639
wenzelm@48425
   640
  /* build */
wenzelm@48424
   641
wenzelm@48509
   642
  def build(
wenzelm@50366
   643
    progress: Build.Progress,
wenzelm@50404
   644
    options: Options,
wenzelm@49131
   645
    requirements: Boolean = false,
wenzelm@48509
   646
    all_sessions: Boolean = false,
wenzelm@48511
   647
    build_heap: Boolean = false,
wenzelm@48595
   648
    clean_build: Boolean = false,
wenzelm@48737
   649
    more_dirs: List[(Boolean, Path)] = Nil,
wenzelm@48509
   650
    session_groups: List[String] = Nil,
wenzelm@48509
   651
    max_jobs: Int = 1,
wenzelm@48903
   652
    list_files: Boolean = false,
wenzelm@48509
   653
    no_build: Boolean = false,
wenzelm@48509
   654
    system_mode: Boolean = false,
wenzelm@48509
   655
    verbose: Boolean = false,
wenzelm@48509
   656
    sessions: List[String] = Nil): Int =
wenzelm@48341
   657
  {
wenzelm@51220
   658
    /* session tree and dependencies */
wenzelm@51220
   659
wenzelm@49131
   660
    val full_tree = find_sessions(options, more_dirs)
wenzelm@49131
   661
    val (selected, selected_tree) =
wenzelm@49131
   662
      full_tree.selection(requirements, all_sessions, session_groups, sessions)
wenzelm@49131
   663
wenzelm@50366
   664
    val deps = dependencies(progress, true, verbose, list_files, selected_tree)
wenzelm@48368
   665
wenzelm@48504
   666
    def make_stamp(name: String): String =
wenzelm@49131
   667
      sources_stamp(selected_tree(name).entry_digest :: deps.sources(name))
wenzelm@48504
   668
wenzelm@51220
   669
wenzelm@51220
   670
    /* persistent information */
wenzelm@51220
   671
wenzelm@48504
   672
    val (input_dirs, output_dir, browser_info) =
wenzelm@48504
   673
      if (system_mode) {
wenzelm@48504
   674
        val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@48504
   675
        (List(output_dir), output_dir, Path.explode("~~/browser_info"))
wenzelm@48504
   676
      }
wenzelm@48504
   677
      else {
wenzelm@48504
   678
        val output_dir = Path.explode("$ISABELLE_OUTPUT")
wenzelm@48504
   679
        (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
wenzelm@48504
   680
         Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48504
   681
      }
wenzelm@48363
   682
wenzelm@51221
   683
    def find_log(name: String): Option[(Path, Path)] =
wenzelm@51221
   684
      input_dirs.find(dir => (dir + log(name)).is_file).map(dir => (dir, dir + log(name)))
wenzelm@51220
   685
wenzelm@51220
   686
wenzelm@51220
   687
    /* queue with scheduling information */
wenzelm@51220
   688
wenzelm@51230
   689
    def load_timings(name: String): (List[Properties.T], Double) =
wenzelm@51221
   690
    {
wenzelm@51221
   691
      val (path, text) =
wenzelm@51221
   692
        find_log(name + ".gz") match {
wenzelm@51221
   693
          case Some((_, path)) => (path, File.read_gzip(path))
wenzelm@51221
   694
          case None =>
wenzelm@51221
   695
            find_log(name) match {
wenzelm@51221
   696
              case Some((_, path)) => (path, File.read(path))
wenzelm@51221
   697
              case None => (Path.current, "")
wenzelm@51221
   698
            }
wenzelm@51221
   699
        }
wenzelm@51244
   700
wenzelm@51244
   701
      def ignore_error(msg: String): (List[Properties.T], Double) =
wenzelm@51244
   702
      {
wenzelm@51244
   703
        java.lang.System.err.println("### Ignoring bad log file: " + path +
wenzelm@51244
   704
          (if (msg == "") "" else "\n" + msg))
wenzelm@51244
   705
        (Nil, 0.0)
wenzelm@51244
   706
      }
wenzelm@51244
   707
wenzelm@51221
   708
      try {
wenzelm@51221
   709
        val info = parse_log(false, text)
wenzelm@51221
   710
        val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
wenzelm@51221
   711
        (info.command_timings, session_timing)
wenzelm@51220
   712
      }
wenzelm@51221
   713
      catch {
wenzelm@51244
   714
        case ERROR(msg) => ignore_error(msg)
wenzelm@51244
   715
        case _: XML.XML_Atom | _: XML.XML_Body => ignore_error("")
wenzelm@51221
   716
      }
wenzelm@51221
   717
    }
wenzelm@51220
   718
wenzelm@51230
   719
    val queue = Queue(selected_tree, load_timings)
wenzelm@51220
   720
wenzelm@51220
   721
wenzelm@51220
   722
    /* main build process */
wenzelm@51220
   723
wenzelm@48373
   724
    // prepare log dir
wenzelm@50893
   725
    Isabelle_System.mkdirs(output_dir + LOG)
wenzelm@48373
   726
wenzelm@48595
   727
    // optional cleanup
wenzelm@48595
   728
    if (clean_build) {
wenzelm@49131
   729
      for (name <- full_tree.graph.all_succs(selected)) {
wenzelm@48595
   730
        val files =
wenzelm@48595
   731
          List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
wenzelm@50366
   732
        if (!files.isEmpty) progress.echo("Cleaning " + name + " ...")
wenzelm@50366
   733
        if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
wenzelm@48595
   734
      }
wenzelm@48595
   735
    }
wenzelm@48595
   736
wenzelm@48425
   737
    // scheduler loop
wenzelm@50707
   738
    case class Result(current: Boolean, parent_path: Option[String], heap: String, rc: Int)
wenzelm@48639
   739
wenzelm@50366
   740
    def sleep(): Unit = Thread.sleep(500)
wenzelm@50366
   741
wenzelm@48425
   742
    @tailrec def loop(
wenzelm@48676
   743
      pending: Queue,
wenzelm@48674
   744
      running: Map[String, (String, Job)],
wenzelm@48639
   745
      results: Map[String, Result]): Map[String, Result] =
wenzelm@48425
   746
    {
wenzelm@48425
   747
      if (pending.is_empty) results
wenzelm@50367
   748
      else if (progress.stopped) {
wenzelm@50367
   749
        for ((_, (_, job)) <- running) job.terminate
wenzelm@50367
   750
        sleep(); loop(pending, running, results)
wenzelm@50367
   751
      }
wenzelm@48547
   752
      else
wenzelm@48674
   753
        running.find({ case (_, (_, job)) => job.is_finished }) match {
wenzelm@48674
   754
          case Some((name, (parent_heap, job))) =>
wenzelm@50367
   755
            //{{{ finish job
wenzelm@48424
   756
wenzelm@50845
   757
            val res = job.join
wenzelm@50845
   758
            progress.echo(res.err)
wenzelm@48373
   759
wenzelm@50707
   760
            val (parent_path, heap) =
wenzelm@50845
   761
              if (res.rc == 0) {
wenzelm@48639
   762
                (output_dir + log(name)).file.delete
wenzelm@48639
   763
wenzelm@48639
   764
                val sources = make_stamp(name)
wenzelm@48639
   765
                val heap = heap_stamp(job.output_path)
wenzelm@48639
   766
                File.write_gzip(output_dir + log_gz(name),
wenzelm@50845
   767
                  sources + "\n" + parent_heap + "\n" + heap + "\n" + res.out)
wenzelm@48639
   768
wenzelm@50707
   769
                val parent_path =
wenzelm@50707
   770
                  if (job.info.options.bool("browser_info"))
wenzelm@50982
   771
                    res.out_lines.find(_.startsWith(SESSION_PARENT_PATH))
wenzelm@50982
   772
                      .map(_.substring(SESSION_PARENT_PATH.length))
wenzelm@50707
   773
                  else None
wenzelm@50707
   774
wenzelm@50707
   775
                (parent_path, heap)
wenzelm@48639
   776
              }
wenzelm@48639
   777
              else {
wenzelm@48639
   778
                (output_dir + Path.basic(name)).file.delete
wenzelm@48639
   779
                (output_dir + log_gz(name)).file.delete
wenzelm@48639
   780
wenzelm@50845
   781
                File.write(output_dir + log(name), res.out)
wenzelm@50366
   782
                progress.echo(name + " FAILED")
wenzelm@50845
   783
                if (res.rc != 130) {
wenzelm@50366
   784
                  progress.echo("(see also " + (output_dir + log(name)).file.toString + ")")
wenzelm@50845
   785
                  val lines = res.out_lines.filterNot(_.startsWith("\f"))
wenzelm@50713
   786
                  val tail = lines.drop(lines.length - 20 max 0)
wenzelm@50366
   787
                  progress.echo("\n" + cat_lines(tail))
wenzelm@48661
   788
                }
wenzelm@48639
   789
wenzelm@50707
   790
                (None, no_heap)
wenzelm@48639
   791
              }
wenzelm@50707
   792
            loop(pending - name, running - name,
wenzelm@50845
   793
              results + (name -> Result(false, parent_path, heap, res.rc)))
wenzelm@50367
   794
            //}}}
wenzelm@48547
   795
          case None if (running.size < (max_jobs max 1)) =>
wenzelm@50367
   796
            //{{{ check/start next job
wenzelm@48547
   797
            pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48547
   798
              case Some((name, info)) =>
wenzelm@48639
   799
                val parent_result =
wenzelm@48639
   800
                  info.parent match {
wenzelm@50707
   801
                    case None => Result(true, None, no_heap, 0)
wenzelm@48639
   802
                    case Some(parent) => results(parent)
wenzelm@48639
   803
                  }
wenzelm@48547
   804
                val output = output_dir + Path.basic(name)
wenzelm@48547
   805
                val do_output = build_heap || queue.is_inner(name)
wenzelm@48547
   806
wenzelm@48639
   807
                val (current, heap) =
wenzelm@48547
   808
                {
wenzelm@51221
   809
                  find_log(name + ".gz") match {
wenzelm@51221
   810
                    case Some((dir, path)) =>
wenzelm@51220
   811
                      read_stamps(path) match {
wenzelm@48639
   812
                        case Some((s, h1, h2)) =>
wenzelm@51221
   813
                          val heap = heap_stamp(Some(dir + Path.basic(name)))
wenzelm@48639
   814
                          (s == make_stamp(name) && h1 == parent_result.heap && h2 == heap &&
wenzelm@48639
   815
                            !(do_output && heap == no_heap), heap)
wenzelm@48639
   816
                        case None => (false, no_heap)
wenzelm@48547
   817
                      }
wenzelm@48639
   818
                    case None => (false, no_heap)
wenzelm@48504
   819
                  }
wenzelm@48547
   820
                }
wenzelm@48639
   821
                val all_current = current && parent_result.current
wenzelm@48528
   822
wenzelm@48547
   823
                if (all_current)
wenzelm@50707
   824
                  loop(pending - name, running, results + (name -> Result(true, None, heap, 0)))
wenzelm@48678
   825
                else if (no_build) {
wenzelm@50366
   826
                  if (verbose) progress.echo("Skipping " + name + " ...")
wenzelm@50707
   827
                  loop(pending - name, running, results + (name -> Result(false, None, heap, 1)))
wenzelm@48678
   828
                }
wenzelm@48639
   829
                else if (parent_result.rc == 0) {
wenzelm@50366
   830
                  progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
wenzelm@51220
   831
                  val job =
wenzelm@51220
   832
                    new Job(progress, name, info, output, do_output, verbose, browser_info,
wenzelm@51220
   833
                      queue.command_timings(name))
wenzelm@48674
   834
                  loop(pending, running + (name -> (parent_result.heap, job)), results)
wenzelm@48547
   835
                }
wenzelm@48547
   836
                else {
wenzelm@50366
   837
                  progress.echo(name + " CANCELLED")
wenzelm@50707
   838
                  loop(pending - name, running, results + (name -> Result(false, None, heap, 1)))
wenzelm@48547
   839
                }
wenzelm@48547
   840
              case None => sleep(); loop(pending, running, results)
wenzelm@48425
   841
            }
wenzelm@50367
   842
            ///}}}
wenzelm@48425
   843
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   844
        }
wenzelm@48425
   845
    }
wenzelm@48425
   846
wenzelm@51220
   847
wenzelm@51220
   848
    /* build results */
wenzelm@51220
   849
wenzelm@48583
   850
    val results =
wenzelm@48583
   851
      if (deps.is_empty) {
wenzelm@50366
   852
        progress.echo("### Nothing to build")
wenzelm@50707
   853
        Map.empty[String, Result]
wenzelm@48583
   854
      }
wenzelm@48583
   855
      else loop(queue, Map.empty, Map.empty)
wenzelm@48583
   856
wenzelm@50707
   857
    val session_entries =
wenzelm@50707
   858
      (for ((name, res) <- results.iterator if res.parent_path.isDefined)
wenzelm@50707
   859
        yield (res.parent_path.get, name)).toList.groupBy(_._1).map(
wenzelm@50707
   860
          { case (p, es) => (p, es.map(_._2).sorted) })
wenzelm@50707
   861
    for ((p, names) <- session_entries)
wenzelm@50707
   862
      Present.update_index(browser_info + Path.explode(p), names)
wenzelm@50707
   863
wenzelm@48639
   864
    val rc = (0 /: results)({ case (rc1, (_, res)) => rc1 max res.rc })
wenzelm@48504
   865
    if (rc != 0 && (verbose || !no_build)) {
wenzelm@48552
   866
      val unfinished =
wenzelm@49951
   867
        (for ((name, res) <- results.iterator if res.rc != 0) yield name).toList
wenzelm@49951
   868
          .sorted(scala.math.Ordering.String)  // FIXME scala-2.10.0-RC1
wenzelm@50366
   869
      progress.echo("Unfinished session(s): " + commas(unfinished))
wenzelm@48473
   870
    }
wenzelm@48473
   871
    rc
wenzelm@48341
   872
  }
wenzelm@48341
   873
wenzelm@48341
   874
wenzelm@48346
   875
  /* command line entry point */
wenzelm@48341
   876
wenzelm@48341
   877
  def main(args: Array[String])
wenzelm@48341
   878
  {
wenzelm@48346
   879
    Command_Line.tool {
wenzelm@48346
   880
      args.toList match {
wenzelm@48346
   881
        case
wenzelm@49131
   882
          Properties.Value.Boolean(requirements) ::
wenzelm@48346
   883
          Properties.Value.Boolean(all_sessions) ::
wenzelm@48511
   884
          Properties.Value.Boolean(build_heap) ::
wenzelm@48595
   885
          Properties.Value.Boolean(clean_build) ::
wenzelm@48425
   886
          Properties.Value.Int(max_jobs) ::
wenzelm@48903
   887
          Properties.Value.Boolean(list_files) ::
wenzelm@48469
   888
          Properties.Value.Boolean(no_build) ::
wenzelm@48447
   889
          Properties.Value.Boolean(system_mode) ::
wenzelm@48425
   890
          Properties.Value.Boolean(verbose) ::
wenzelm@48737
   891
          Command_Line.Chunks(select_dirs, include_dirs, session_groups, build_options, sessions) =>
wenzelm@50404
   892
            val options = (Options.init() /: build_options)(_ + _)
wenzelm@48737
   893
            val dirs =
wenzelm@48737
   894
              select_dirs.map(d => (true, Path.explode(d))) :::
wenzelm@48737
   895
              include_dirs.map(d => (false, Path.explode(d)))
wenzelm@51252
   896
            val progress = new Build.Console_Progress(verbose)
wenzelm@51252
   897
            progress.interrupt_handler {
wenzelm@51252
   898
              build(progress, options, requirements, all_sessions,
wenzelm@51252
   899
                build_heap, clean_build, dirs, session_groups, max_jobs, list_files, no_build,
wenzelm@51252
   900
                system_mode, verbose, sessions)
wenzelm@51252
   901
            }
wenzelm@48346
   902
        case _ => error("Bad arguments:\n" + cat_lines(args))
wenzelm@48341
   903
      }
wenzelm@48346
   904
    }
wenzelm@48341
   905
  }
wenzelm@48276
   906
}
wenzelm@48276
   907