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