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