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