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