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