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