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