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