src/Pure/System/build.scala
author wenzelm
Fri Dec 07 13:38:32 2012 +0100 (2012-12-07)
changeset 50414 e17a1f179bb0
parent 50404 898cac1dad5e
child 50566 b43c4f660320
permissions -rw-r--r--
explore theory_body_files via future, for improved performance;
further internalization of header errors;
wenzelm@48276
     1
/*  Title:      Pure/System/build.scala
wenzelm@48276
     2
    Author:     Makarius
wenzelm@50367
     3
    Options:    :folding=explicit:collapseFolds=1:
wenzelm@48276
     4
wenzelm@48276
     5
Build and manage Isabelle sessions.
wenzelm@48276
     6
*/
wenzelm@48276
     7
wenzelm@48276
     8
package isabelle
wenzelm@48276
     9
wenzelm@48276
    10
wenzelm@48661
    11
import java.util.{Timer, TimerTask}
wenzelm@48548
    12
import java.io.{BufferedInputStream, FileInputStream,
wenzelm@48494
    13
  BufferedReader, InputStreamReader, IOException}
wenzelm@48494
    14
import java.util.zip.GZIPInputStream
wenzelm@48335
    15
wenzelm@48676
    16
import scala.collection.SortedSet
wenzelm@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@50367
    24
  class Progress {
wenzelm@50367
    25
    def echo(msg: String) {}
wenzelm@50367
    26
    def stopped: Boolean = false
wenzelm@50366
    27
  }
wenzelm@50366
    28
wenzelm@50367
    29
  object Ignore_Progress extends Progress
wenzelm@50366
    30
wenzelm@50366
    31
  object Console_Progress extends Progress {
wenzelm@50366
    32
    override def echo(msg: String) { java.lang.System.out.println(msg) }
wenzelm@50366
    33
  }
wenzelm@50366
    34
wenzelm@50366
    35
wenzelm@50366
    36
wenzelm@48337
    37
  /** session information **/
wenzelm@48334
    38
wenzelm@48675
    39
  // external version
wenzelm@48675
    40
  sealed case class Session_Entry(
wenzelm@48675
    41
    pos: Position.T,
wenzelm@48738
    42
    name: String,
wenzelm@48675
    43
    groups: List[String],
wenzelm@48738
    44
    path: String,
wenzelm@48675
    45
    parent: Option[String],
wenzelm@48675
    46
    description: String,
wenzelm@48675
    47
    options: List[Options.Spec],
wenzelm@48675
    48
    theories: List[(List[Options.Spec], List[String])],
wenzelm@48675
    49
    files: List[String])
wenzelm@48675
    50
wenzelm@48675
    51
  // internal version
wenzelm@48675
    52
  sealed case class Session_Info(
wenzelm@48737
    53
    select: Boolean,
wenzelm@48675
    54
    pos: Position.T,
wenzelm@48675
    55
    groups: List[String],
wenzelm@48675
    56
    dir: Path,
wenzelm@48675
    57
    parent: Option[String],
wenzelm@48675
    58
    description: String,
wenzelm@48675
    59
    options: Options,
wenzelm@48675
    60
    theories: List[(Options, List[Path])],
wenzelm@48675
    61
    files: List[Path],
wenzelm@48675
    62
    entry_digest: SHA1.Digest)
wenzelm@48675
    63
wenzelm@48675
    64
  def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
wenzelm@48675
    65
wenzelm@48737
    66
  def session_info(options: Options, select: Boolean, dir: Path, entry: Session_Entry)
wenzelm@48737
    67
      : (String, Session_Info) =
wenzelm@48675
    68
    try {
wenzelm@48738
    69
      val name = entry.name
wenzelm@48675
    70
wenzelm@48738
    71
      if (name == "") error("Bad session name")
wenzelm@48738
    72
      if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
wenzelm@48738
    73
      if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
wenzelm@48675
    74
wenzelm@48675
    75
      val session_options = options ++ entry.options
wenzelm@48675
    76
wenzelm@48675
    77
      val theories =
wenzelm@48675
    78
        entry.theories.map({ case (opts, thys) =>
wenzelm@48675
    79
          (session_options ++ opts, thys.map(Path.explode(_))) })
wenzelm@48675
    80
      val files = entry.files.map(Path.explode(_))
wenzelm@48738
    81
      val entry_digest = SHA1.digest((name, entry.parent, entry.options, entry.theories).toString)
wenzelm@48675
    82
wenzelm@48675
    83
      val info =
wenzelm@48738
    84
        Session_Info(select, entry.pos, entry.groups, dir + Path.explode(entry.path),
wenzelm@48738
    85
          entry.parent, entry.description, session_options, theories, files, entry_digest)
wenzelm@48675
    86
wenzelm@48738
    87
      (name, info)
wenzelm@48675
    88
    }
wenzelm@48675
    89
    catch {
wenzelm@48675
    90
      case ERROR(msg) =>
wenzelm@48675
    91
        error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@48992
    92
          quote(entry.name) + Position.here(entry.pos))
wenzelm@48675
    93
    }
wenzelm@48675
    94
wenzelm@48675
    95
wenzelm@48676
    96
  /* session tree */
wenzelm@48676
    97
wenzelm@48676
    98
  object Session_Tree
wenzelm@48676
    99
  {
wenzelm@48676
   100
    def apply(infos: Seq[(String, Session_Info)]): Session_Tree =
wenzelm@48676
   101
    {
wenzelm@48680
   102
      val graph1 =
wenzelm@48680
   103
        (Graph.string[Session_Info] /: infos) {
wenzelm@48684
   104
          case (graph, (name, info)) =>
wenzelm@48680
   105
            if (graph.defined(name))
wenzelm@48992
   106
              error("Duplicate session " + quote(name) + Position.here(info.pos))
wenzelm@48680
   107
            else graph.new_node(name, info)
wenzelm@48680
   108
        }
wenzelm@48680
   109
      val graph2 =
wenzelm@48680
   110
        (graph1 /: graph1.entries) {
wenzelm@48680
   111
          case (graph, (name, (info, _))) =>
wenzelm@48680
   112
            info.parent match {
wenzelm@48680
   113
              case None => graph
wenzelm@48680
   114
              case Some(parent) =>
wenzelm@48680
   115
                if (!graph.defined(parent))
wenzelm@48680
   116
                  error("Bad parent session " + quote(parent) + " for " +
wenzelm@48992
   117
                    quote(name) + Position.here(info.pos))
wenzelm@48676
   118
wenzelm@48680
   119
                try { graph.add_edge_acyclic(parent, name) }
wenzelm@48680
   120
                catch {
wenzelm@48680
   121
                  case exn: Graph.Cycles[_] =>
wenzelm@48680
   122
                    error(cat_lines(exn.cycles.map(cycle =>
wenzelm@48680
   123
                      "Cyclic session dependency of " +
wenzelm@48680
   124
                        cycle.map(c => quote(c.toString)).mkString(" via "))) +
wenzelm@48992
   125
                          Position.here(info.pos))
wenzelm@48680
   126
                }
wenzelm@48676
   127
            }
wenzelm@48676
   128
        }
wenzelm@48680
   129
      new Session_Tree(graph2)
wenzelm@48676
   130
    }
wenzelm@48676
   131
  }
wenzelm@48676
   132
wenzelm@48680
   133
  final class Session_Tree private(val graph: Graph[String, Session_Info])
wenzelm@48676
   134
    extends PartialFunction[String, Session_Info]
wenzelm@48676
   135
  {
wenzelm@48680
   136
    def apply(name: String): Session_Info = graph.get_node(name)
wenzelm@48680
   137
    def isDefinedAt(name: String): Boolean = graph.defined(name)
wenzelm@48676
   138
wenzelm@49131
   139
    def selection(requirements: Boolean, all_sessions: Boolean,
wenzelm@49131
   140
      session_groups: List[String], sessions: List[String]): (List[String], Session_Tree) =
wenzelm@48676
   141
    {
wenzelm@48676
   142
      val bad_sessions = sessions.filterNot(isDefinedAt(_))
wenzelm@48676
   143
      if (!bad_sessions.isEmpty) error("Undefined session(s): " + commas_quote(bad_sessions))
wenzelm@48676
   144
wenzelm@49131
   145
      val pre_selected =
wenzelm@48676
   146
      {
wenzelm@48676
   147
        if (all_sessions) graph.keys.toList
wenzelm@48676
   148
        else {
wenzelm@48737
   149
          val select_group = session_groups.toSet
wenzelm@48737
   150
          val select = sessions.toSet
wenzelm@48737
   151
          (for {
wenzelm@48737
   152
            (name, (info, _)) <- graph.entries
wenzelm@48737
   153
            if info.select || select(name) || apply(name).groups.exists(select_group)
wenzelm@48737
   154
          } yield name).toList
wenzelm@48676
   155
        }
wenzelm@48676
   156
      }
wenzelm@49131
   157
      val selected =
wenzelm@49131
   158
        if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
wenzelm@49131
   159
        else pre_selected
wenzelm@49131
   160
wenzelm@48676
   161
      val tree1 = new Session_Tree(graph.restrict(graph.all_preds(selected).toSet))
wenzelm@49131
   162
      (selected, tree1)
wenzelm@48676
   163
    }
wenzelm@48676
   164
wenzelm@48676
   165
    def topological_order: List[(String, Session_Info)] =
wenzelm@48676
   166
      graph.topological_order.map(name => (name, apply(name)))
wenzelm@48794
   167
wenzelm@48794
   168
    override def toString: String = graph.entries.map(_._1).toList.sorted.mkString(",")
wenzelm@48676
   169
  }
wenzelm@48676
   170
wenzelm@48676
   171
wenzelm@48675
   172
  /* parser */
wenzelm@48675
   173
wenzelm@48713
   174
  private val SESSION = "session"
wenzelm@48713
   175
  private val IN = "in"
wenzelm@48713
   176
  private val DESCRIPTION = "description"
wenzelm@48713
   177
  private val OPTIONS = "options"
wenzelm@48713
   178
  private val THEORIES = "theories"
wenzelm@48713
   179
  private val FILES = "files"
wenzelm@48713
   180
wenzelm@48713
   181
  lazy val root_syntax =
wenzelm@48738
   182
    Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" +
wenzelm@48718
   183
      (SESSION, Keyword.THY_DECL) + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
wenzelm@48713
   184
wenzelm@48675
   185
  private object Parser extends Parse.Parser
wenzelm@48675
   186
  {
wenzelm@48675
   187
    def session_entry(pos: Position.T): Parser[Session_Entry] =
wenzelm@48675
   188
    {
wenzelm@48675
   189
      val session_name = atom("session name", _.is_name)
wenzelm@48675
   190
wenzelm@48675
   191
      val option =
wenzelm@48675
   192
        name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@48862
   193
      val options = keyword("[") ~> rep1sep(option, keyword(",")) <~ keyword("]")
wenzelm@48675
   194
wenzelm@48675
   195
      val theories =
wenzelm@48739
   196
        keyword(THEORIES) ~! ((options | success(Nil)) ~ rep(theory_name)) ^^
wenzelm@48675
   197
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@48675
   198
wenzelm@48912
   199
      command(SESSION) ~!
wenzelm@48912
   200
        (session_name ~
wenzelm@48912
   201
          ((keyword("(") ~! (rep1(name) <~ keyword(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@48912
   202
          ((keyword(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
wenzelm@48912
   203
          (keyword("=") ~!
wenzelm@48912
   204
            (opt(session_name ~! keyword("+") ^^ { case x ~ _ => x }) ~
wenzelm@48912
   205
              ((keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
wenzelm@48912
   206
              ((keyword(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@48916
   207
              rep1(theories) ~
wenzelm@48912
   208
              ((keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil))))) ^^
wenzelm@48912
   209
        { case _ ~ (a ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h))) =>
wenzelm@48912
   210
            Session_Entry(pos, a, b, c, d, e, f, g, h) }
wenzelm@48675
   211
    }
wenzelm@48675
   212
wenzelm@48675
   213
    def parse_entries(root: Path): List[Session_Entry] =
wenzelm@48675
   214
    {
wenzelm@48713
   215
      val toks = root_syntax.scan(File.read(root))
wenzelm@48675
   216
      parse_all(rep(session_entry(root.position)), Token.reader(toks, root.implode)) match {
wenzelm@48675
   217
        case Success(result, _) => result
wenzelm@48675
   218
        case bad => error(bad.toString)
wenzelm@48675
   219
      }
wenzelm@48675
   220
    }
wenzelm@48675
   221
  }
wenzelm@48675
   222
wenzelm@48675
   223
wenzelm@48675
   224
  /* find sessions within certain directories */
wenzelm@48675
   225
wenzelm@48675
   226
  private val ROOT = Path.explode("ROOT")
wenzelm@48684
   227
  private val ROOTS = Path.explode("ROOTS")
wenzelm@48675
   228
wenzelm@48684
   229
  private def is_session_dir(dir: Path): Boolean =
wenzelm@48684
   230
    (dir + ROOT).is_file || (dir + ROOTS).is_file
wenzelm@48684
   231
wenzelm@48684
   232
  private def check_session_dir(dir: Path): Path =
wenzelm@48684
   233
    if (is_session_dir(dir)) dir
wenzelm@48684
   234
    else error("Bad session root directory: " + dir.toString)
wenzelm@48675
   235
wenzelm@48737
   236
  def find_sessions(options: Options, more_dirs: List[(Boolean, Path)]): Session_Tree =
wenzelm@48675
   237
  {
wenzelm@48737
   238
    def find_dir(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48737
   239
      find_root(select, dir) ::: find_roots(select, dir)
wenzelm@48684
   240
wenzelm@48737
   241
    def find_root(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48684
   242
    {
wenzelm@48684
   243
      val root = dir + ROOT
wenzelm@48737
   244
      if (root.is_file) Parser.parse_entries(root).map(session_info(options, select, dir, _))
wenzelm@48684
   245
      else Nil
wenzelm@48684
   246
    }
wenzelm@48684
   247
wenzelm@48737
   248
    def find_roots(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48684
   249
    {
wenzelm@48684
   250
      val roots = dir + ROOTS
wenzelm@48684
   251
      if (roots.is_file) {
wenzelm@48684
   252
        for {
wenzelm@48684
   253
          line <- split_lines(File.read(roots))
wenzelm@48684
   254
          if !(line == "" || line.startsWith("#"))
wenzelm@48684
   255
          dir1 =
wenzelm@48684
   256
            try { check_session_dir(dir + Path.explode(line)) }
wenzelm@48684
   257
            catch {
wenzelm@48684
   258
              case ERROR(msg) =>
wenzelm@48684
   259
                error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
wenzelm@48684
   260
            }
wenzelm@48737
   261
          info <- find_dir(select, dir1)
wenzelm@48684
   262
        } yield info
wenzelm@48684
   263
      }
wenzelm@48684
   264
      else Nil
wenzelm@48684
   265
    }
wenzelm@48684
   266
wenzelm@48737
   267
    val default_dirs = Isabelle_System.components().filter(is_session_dir(_)).map((false, _))
wenzelm@48737
   268
wenzelm@48737
   269
    more_dirs foreach { case (_, dir) => check_session_dir(dir) }
wenzelm@48737
   270
wenzelm@48684
   271
    Session_Tree(
wenzelm@48684
   272
      for {
wenzelm@48737
   273
        (select, dir) <- default_dirs ::: more_dirs
wenzelm@48737
   274
        info <- find_dir(select, dir)
wenzelm@48684
   275
      } yield info)
wenzelm@48349
   276
  }
wenzelm@48334
   277
wenzelm@48337
   278
wenzelm@48424
   279
wenzelm@48424
   280
  /** build **/
wenzelm@48424
   281
wenzelm@48676
   282
  /* queue */
wenzelm@48676
   283
wenzelm@48676
   284
  object Queue
wenzelm@48676
   285
  {
wenzelm@48676
   286
    def apply(tree: Session_Tree): Queue =
wenzelm@48676
   287
    {
wenzelm@48676
   288
      val graph = tree.graph
wenzelm@48678
   289
wenzelm@48678
   290
      def outdegree(name: String): Int = graph.imm_succs(name).size
wenzelm@48678
   291
      def timeout(name: String): Double = tree(name).options.real("timeout")
wenzelm@48678
   292
wenzelm@48678
   293
      object Ordering extends scala.math.Ordering[String]
wenzelm@48678
   294
      {
wenzelm@48678
   295
        def compare(name1: String, name2: String): Int =
wenzelm@48678
   296
          outdegree(name2) compare outdegree(name1) match {
wenzelm@48678
   297
            case 0 =>
wenzelm@48678
   298
              timeout(name2) compare timeout(name1) match {
wenzelm@48678
   299
                case 0 => name1 compare name2
wenzelm@48678
   300
                case ord => ord
wenzelm@48678
   301
              }
wenzelm@48678
   302
            case ord => ord
wenzelm@48678
   303
          }
wenzelm@48678
   304
      }
wenzelm@48678
   305
wenzelm@48678
   306
      new Queue(graph, SortedSet(graph.keys.toList: _*)(Ordering))
wenzelm@48676
   307
    }
wenzelm@48676
   308
  }
wenzelm@48676
   309
wenzelm@48680
   310
  final class Queue private(graph: Graph[String, Session_Info], order: SortedSet[String])
wenzelm@48676
   311
  {
wenzelm@48676
   312
    def is_inner(name: String): Boolean = !graph.is_maximal(name)
wenzelm@48676
   313
wenzelm@48676
   314
    def is_empty: Boolean = graph.is_empty
wenzelm@48676
   315
wenzelm@48676
   316
    def - (name: String): Queue = new Queue(graph.del_node(name), order - name)
wenzelm@48676
   317
wenzelm@48676
   318
    def dequeue(skip: String => Boolean): Option[(String, Session_Info)] =
wenzelm@48676
   319
    {
wenzelm@48676
   320
      val it = order.iterator.dropWhile(name => skip(name) || !graph.is_minimal(name))
wenzelm@48680
   321
      if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
wenzelm@48676
   322
      else None
wenzelm@48676
   323
    }
wenzelm@48676
   324
  }
wenzelm@48676
   325
wenzelm@48676
   326
wenzelm@48710
   327
  /* source dependencies and static content */
wenzelm@48422
   328
wenzelm@48710
   329
  sealed case class Session_Content(
wenzelm@48422
   330
    loaded_theories: Set[String],
wenzelm@48660
   331
    syntax: Outer_Syntax,
wenzelm@48794
   332
    sources: List[(Path, SHA1.Digest)],
wenzelm@48794
   333
    errors: List[String])
wenzelm@48794
   334
  {
wenzelm@48794
   335
    def check_errors: Session_Content =
wenzelm@48794
   336
    {
wenzelm@48794
   337
      if (errors.isEmpty) this
wenzelm@48794
   338
      else error(cat_lines(errors))
wenzelm@48794
   339
    }
wenzelm@48794
   340
  }
wenzelm@48422
   341
wenzelm@48710
   342
  sealed case class Deps(deps: Map[String, Session_Content])
wenzelm@48423
   343
  {
wenzelm@48583
   344
    def is_empty: Boolean = deps.isEmpty
wenzelm@48710
   345
    def apply(name: String): Session_Content = deps(name)
wenzelm@48504
   346
    def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
wenzelm@48423
   347
  }
wenzelm@48423
   348
wenzelm@50366
   349
  def dependencies(progress: Build.Progress, inlined_files: Boolean,
wenzelm@50366
   350
      verbose: Boolean, list_files: Boolean, tree: Session_Tree): Deps =
wenzelm@48710
   351
    Deps((Map.empty[String, Session_Content] /: tree.topological_order)(
wenzelm@48422
   352
      { case (deps, (name, info)) =>
wenzelm@48794
   353
          val (preloaded, parent_syntax, parent_errors) =
wenzelm@48422
   354
            info.parent match {
wenzelm@48870
   355
              case None =>
wenzelm@48870
   356
                (Set.empty[String], Outer_Syntax.init_pure(), Nil)
wenzelm@48794
   357
              case Some(parent_name) =>
wenzelm@48794
   358
                val parent = deps(parent_name)
wenzelm@48794
   359
                (parent.loaded_theories, parent.syntax, parent.errors)
wenzelm@48422
   360
            }
wenzelm@48870
   361
          val thy_info = new Thy_Info(new Thy_Load(preloaded, parent_syntax))
wenzelm@48422
   362
wenzelm@48903
   363
          if (verbose || list_files) {
wenzelm@48583
   364
            val groups =
wenzelm@48583
   365
              if (info.groups.isEmpty) ""
wenzelm@48583
   366
              else info.groups.mkString(" (", " ", ")")
wenzelm@50366
   367
            progress.echo("Session " + name + groups)
wenzelm@48583
   368
          }
wenzelm@48478
   369
wenzelm@48422
   370
          val thy_deps =
wenzelm@49098
   371
            thy_info.dependencies(inlined_files,
wenzelm@48422
   372
              info.theories.map(_._2).flatten.
wenzelm@50204
   373
                map(thy => Thy_Load.external_node(info.dir + Thy_Load.thy_path(thy))))
wenzelm@48422
   374
wenzelm@48872
   375
          val loaded_theories = thy_deps.loaded_theories
wenzelm@48883
   376
          val syntax = thy_deps.make_syntax
wenzelm@48660
   377
wenzelm@48423
   378
          val all_files =
wenzelm@50414
   379
            (thy_deps.deps.map({ case dep =>
wenzelm@50414
   380
              val thy = Path.explode(dep.name.node)
wenzelm@50414
   381
              val uses = dep.join_header.uses.map(p =>
wenzelm@50414
   382
                Path.explode(dep.name.dir) + Path.explode(p._1))
wenzelm@48422
   383
              thy :: uses
wenzelm@48904
   384
            }).flatten ::: info.files.map(file => info.dir + file)).map(_.expand)
wenzelm@48903
   385
wenzelm@48903
   386
          if (list_files)
wenzelm@50366
   387
            progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
wenzelm@48903
   388
wenzelm@48485
   389
          val sources =
wenzelm@49696
   390
            try { all_files.map(p => (p, SHA1.digest(p.file))) }
wenzelm@48485
   391
            catch {
wenzelm@48485
   392
              case ERROR(msg) =>
wenzelm@48675
   393
                error(msg + "\nThe error(s) above occurred in session " +
wenzelm@48992
   394
                  quote(name) + Position.here(info.pos))
wenzelm@48485
   395
            }
wenzelm@50414
   396
          val errors = parent_errors ::: thy_deps.deps.map(dep => dep.join_header.errors).flatten
wenzelm@48422
   397
wenzelm@48794
   398
          deps + (name -> Session_Content(loaded_theories, syntax, sources, errors))
wenzelm@48423
   399
      }))
wenzelm@48422
   400
wenzelm@49098
   401
  def session_content(inlined_files: Boolean, dirs: List[Path], session: String): Session_Content =
wenzelm@48710
   402
  {
wenzelm@50404
   403
    val options = Options.init()
wenzelm@48791
   404
    val (_, tree) =
wenzelm@49131
   405
      find_sessions(options, dirs.map((false, _))).selection(false, false, Nil, List(session))
wenzelm@50366
   406
    dependencies(Build.Ignore_Progress, inlined_files, false, false, tree)(session)
wenzelm@48710
   407
  }
wenzelm@48710
   408
wenzelm@48794
   409
  def outer_syntax(session: String): Outer_Syntax =
wenzelm@49098
   410
    session_content(false, Nil, session).check_errors.syntax
wenzelm@48710
   411
wenzelm@48422
   412
wenzelm@48424
   413
  /* jobs */
wenzelm@48341
   414
wenzelm@48675
   415
  private class Job(name: String, info: Session_Info, output: Path, do_output: Boolean,
wenzelm@48674
   416
    verbose: Boolean, browser_info: Path)
wenzelm@48418
   417
  {
wenzelm@48467
   418
    // global browser info dir
wenzelm@48674
   419
    if (info.options.bool("browser_info") && !(browser_info + Path.explode("index.html")).is_file)
wenzelm@48467
   420
    {
wenzelm@48467
   421
      browser_info.file.mkdirs()
wenzelm@48467
   422
      File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
wenzelm@48467
   423
        browser_info + Path.explode("isabelle.gif"))
wenzelm@48467
   424
      File.write(browser_info + Path.explode("index.html"),
wenzelm@48467
   425
        File.read(Path.explode("~~/lib/html/library_index_header.template")) +
wenzelm@48724
   426
        File.read(Path.explode("~~/lib/html/library_index_content.template")) +
wenzelm@48467
   427
        File.read(Path.explode("~~/lib/html/library_index_footer.template")))
wenzelm@48467
   428
    }
wenzelm@48467
   429
wenzelm@48674
   430
    def output_path: Option[Path] = if (do_output) Some(output) else None
wenzelm@48674
   431
wenzelm@48674
   432
    private val parent = info.parent.getOrElse("")
wenzelm@48418
   433
wenzelm@48698
   434
    private val args_file = File.tmp_file("args")
wenzelm@48698
   435
    File.write(args_file, YXML.string_of_body(
wenzelm@48698
   436
      if (is_pure(name)) Options.encode(info.options)
wenzelm@48698
   437
      else
wenzelm@48698
   438
        {
wenzelm@48698
   439
          import XML.Encode._
wenzelm@48698
   440
              pair(bool, pair(Options.encode, pair(bool, pair(Path.encode, pair(string,
wenzelm@48698
   441
                pair(string, list(pair(Options.encode, list(Path.encode)))))))))(
wenzelm@48698
   442
              (do_output, (info.options, (verbose, (browser_info, (parent,
wenzelm@48698
   443
                (name, info.theories)))))))
wenzelm@48698
   444
        }))
wenzelm@48698
   445
wenzelm@48674
   446
    private val env =
wenzelm@48698
   447
      Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output),
wenzelm@48698
   448
        (if (is_pure(name)) "ISABELLE_PROCESS_OPTIONS" else "ARGS_FILE") ->
wenzelm@48698
   449
          Isabelle_System.posix_path(args_file.getPath))
wenzelm@48698
   450
wenzelm@48674
   451
    private val script =
wenzelm@48511
   452
      if (is_pure(name)) {
wenzelm@48511
   453
        if (do_output) "./build " + name + " \"$OUTPUT\""
wenzelm@48511
   454
        else """ rm -f "$OUTPUT"; ./build """ + name
wenzelm@48511
   455
      }
wenzelm@48418
   456
      else {
wenzelm@48418
   457
        """
wenzelm@48418
   458
        . "$ISABELLE_HOME/lib/scripts/timestart.bash"
wenzelm@48418
   459
        """ +
wenzelm@48511
   460
          (if (do_output)
wenzelm@48511
   461
            """
wenzelm@48511
   462
            "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
wenzelm@48511
   463
            """
wenzelm@48418
   464
          else
wenzelm@48511
   465
            """
wenzelm@48511
   466
            rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
wenzelm@48511
   467
            """) +
wenzelm@48418
   468
        """
wenzelm@48418
   469
        RC="$?"
wenzelm@48418
   470
wenzelm@48418
   471
        . "$ISABELLE_HOME/lib/scripts/timestop.bash"
wenzelm@48418
   472
wenzelm@48418
   473
        if [ "$RC" -eq 0 ]; then
wenzelm@48418
   474
          echo "Finished $TARGET ($TIMES_REPORT)" >&2
wenzelm@48418
   475
        fi
wenzelm@48418
   476
wenzelm@48418
   477
        exit "$RC"
wenzelm@48418
   478
        """
wenzelm@48418
   479
      }
wenzelm@48674
   480
wenzelm@48674
   481
    private val (thread, result) =
wenzelm@48698
   482
      Simple_Thread.future("build") { Isabelle_System.bash_env(info.dir.file, env, script) }
wenzelm@48674
   483
wenzelm@48674
   484
    def terminate: Unit = thread.interrupt
wenzelm@48674
   485
    def is_finished: Boolean = result.is_finished
wenzelm@48674
   486
wenzelm@48674
   487
    @volatile private var timeout = false
wenzelm@50207
   488
    private val time = info.options.seconds("timeout")
wenzelm@48674
   489
    private val timer: Option[Timer] =
wenzelm@48674
   490
      if (time.seconds > 0.0) {
wenzelm@48674
   491
        val t = new Timer("build", true)
wenzelm@48674
   492
        t.schedule(new TimerTask { def run = { terminate; timeout = true } }, time.ms)
wenzelm@48674
   493
        Some(t)
wenzelm@48674
   494
      }
wenzelm@48674
   495
      else None
wenzelm@48674
   496
wenzelm@48674
   497
    def join: (String, String, Int) = {
wenzelm@48674
   498
      val (out, err, rc) = result.join
wenzelm@48674
   499
      args_file.delete
wenzelm@48674
   500
      timer.map(_.cancel())
wenzelm@48674
   501
wenzelm@48674
   502
      val err1 =
wenzelm@48674
   503
        if (rc == 130)
wenzelm@48674
   504
          (if (err.isEmpty || err.endsWith("\n")) err else err + "\n") +
wenzelm@48674
   505
          (if (timeout) "*** Timeout\n" else "*** Interrupt\n")
wenzelm@48674
   506
        else err
wenzelm@48674
   507
      (out, err1, rc)
wenzelm@48674
   508
    }
wenzelm@48364
   509
  }
wenzelm@48364
   510
wenzelm@48424
   511
wenzelm@48504
   512
  /* log files and corresponding heaps */
wenzelm@48504
   513
wenzelm@48505
   514
  private val LOG = Path.explode("log")
wenzelm@48505
   515
  private def log(name: String): Path = LOG + Path.basic(name)
wenzelm@48505
   516
  private def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@48504
   517
wenzelm@48505
   518
  private def sources_stamp(digests: List[SHA1.Digest]): String =
wenzelm@48504
   519
    digests.map(_.toString).sorted.mkString("sources: ", " ", "")
wenzelm@48504
   520
wenzelm@48639
   521
  private val no_heap: String = "heap: -"
wenzelm@48639
   522
wenzelm@48639
   523
  private def heap_stamp(heap: Option[Path]): String =
wenzelm@48504
   524
  {
wenzelm@48504
   525
    "heap: " +
wenzelm@48639
   526
      (heap match {
wenzelm@48504
   527
        case Some(path) =>
wenzelm@48504
   528
          val file = path.file
wenzelm@48504
   529
          if (file.isFile) file.length.toString + " " + file.lastModified.toString
wenzelm@48504
   530
          else "-"
wenzelm@48504
   531
        case None => "-"
wenzelm@48504
   532
      })
wenzelm@48504
   533
  }
wenzelm@48504
   534
wenzelm@48639
   535
  private def read_stamps(path: Path): Option[(String, String, String)] =
wenzelm@48639
   536
    if (path.is_file) {
wenzelm@48639
   537
      val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(path.file)))
wenzelm@50203
   538
      val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
wenzelm@48639
   539
      val (s, h1, h2) =
wenzelm@48639
   540
        try { (reader.readLine, reader.readLine, reader.readLine) }
wenzelm@48639
   541
        finally { reader.close }
wenzelm@48639
   542
      if (s != null && s.startsWith("sources: ") &&
wenzelm@48639
   543
          h1 != null && h1.startsWith("heap: ") &&
wenzelm@48639
   544
          h2 != null && h2.startsWith("heap: ")) Some((s, h1, h2))
wenzelm@48504
   545
      else None
wenzelm@48504
   546
    }
wenzelm@48504
   547
    else None
wenzelm@48504
   548
wenzelm@48504
   549
wenzelm@48425
   550
  /* build */
wenzelm@48424
   551
wenzelm@48509
   552
  def build(
wenzelm@50366
   553
    progress: Build.Progress,
wenzelm@50404
   554
    options: Options,
wenzelm@49131
   555
    requirements: Boolean = false,
wenzelm@48509
   556
    all_sessions: Boolean = false,
wenzelm@48511
   557
    build_heap: Boolean = false,
wenzelm@48595
   558
    clean_build: Boolean = false,
wenzelm@48737
   559
    more_dirs: List[(Boolean, Path)] = Nil,
wenzelm@48509
   560
    session_groups: List[String] = Nil,
wenzelm@48509
   561
    max_jobs: Int = 1,
wenzelm@48903
   562
    list_files: Boolean = false,
wenzelm@48509
   563
    no_build: Boolean = false,
wenzelm@48509
   564
    system_mode: Boolean = false,
wenzelm@48509
   565
    verbose: Boolean = false,
wenzelm@48509
   566
    sessions: List[String] = Nil): Int =
wenzelm@48341
   567
  {
wenzelm@49131
   568
    val full_tree = find_sessions(options, more_dirs)
wenzelm@49131
   569
    val (selected, selected_tree) =
wenzelm@49131
   570
      full_tree.selection(requirements, all_sessions, session_groups, sessions)
wenzelm@49131
   571
wenzelm@50366
   572
    val deps = dependencies(progress, true, verbose, list_files, selected_tree)
wenzelm@49131
   573
    val queue = Queue(selected_tree)
wenzelm@48368
   574
wenzelm@48504
   575
    def make_stamp(name: String): String =
wenzelm@49131
   576
      sources_stamp(selected_tree(name).entry_digest :: deps.sources(name))
wenzelm@48504
   577
wenzelm@48504
   578
    val (input_dirs, output_dir, browser_info) =
wenzelm@48504
   579
      if (system_mode) {
wenzelm@48504
   580
        val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@48504
   581
        (List(output_dir), output_dir, Path.explode("~~/browser_info"))
wenzelm@48504
   582
      }
wenzelm@48504
   583
      else {
wenzelm@48504
   584
        val output_dir = Path.explode("$ISABELLE_OUTPUT")
wenzelm@48504
   585
        (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
wenzelm@48504
   586
         Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48504
   587
      }
wenzelm@48363
   588
wenzelm@48373
   589
    // prepare log dir
wenzelm@48504
   590
    (output_dir + LOG).file.mkdirs()
wenzelm@48373
   591
wenzelm@48595
   592
    // optional cleanup
wenzelm@48595
   593
    if (clean_build) {
wenzelm@49131
   594
      for (name <- full_tree.graph.all_succs(selected)) {
wenzelm@48595
   595
        val files =
wenzelm@48595
   596
          List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
wenzelm@50366
   597
        if (!files.isEmpty) progress.echo("Cleaning " + name + " ...")
wenzelm@50366
   598
        if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
wenzelm@48595
   599
      }
wenzelm@48595
   600
    }
wenzelm@48595
   601
wenzelm@48425
   602
    // scheduler loop
wenzelm@48639
   603
    case class Result(current: Boolean, heap: String, rc: Int)
wenzelm@48639
   604
wenzelm@50366
   605
    def sleep(): Unit = Thread.sleep(500)
wenzelm@50366
   606
wenzelm@48425
   607
    @tailrec def loop(
wenzelm@48676
   608
      pending: Queue,
wenzelm@48674
   609
      running: Map[String, (String, Job)],
wenzelm@48639
   610
      results: Map[String, Result]): Map[String, Result] =
wenzelm@48425
   611
    {
wenzelm@48425
   612
      if (pending.is_empty) results
wenzelm@50367
   613
      else if (progress.stopped) {
wenzelm@50367
   614
        for ((_, (_, job)) <- running) job.terminate
wenzelm@50367
   615
        sleep(); loop(pending, running, results)
wenzelm@50367
   616
      }
wenzelm@48547
   617
      else
wenzelm@48674
   618
        running.find({ case (_, (_, job)) => job.is_finished }) match {
wenzelm@48674
   619
          case Some((name, (parent_heap, job))) =>
wenzelm@50367
   620
            //{{{ finish job
wenzelm@48424
   621
wenzelm@48547
   622
            val (out, err, rc) = job.join
wenzelm@50366
   623
            progress.echo(Library.trim_line(err))
wenzelm@48373
   624
wenzelm@48639
   625
            val heap =
wenzelm@48639
   626
              if (rc == 0) {
wenzelm@48639
   627
                (output_dir + log(name)).file.delete
wenzelm@48639
   628
wenzelm@48639
   629
                val sources = make_stamp(name)
wenzelm@48639
   630
                val heap = heap_stamp(job.output_path)
wenzelm@48639
   631
                File.write_gzip(output_dir + log_gz(name),
wenzelm@48674
   632
                  sources + "\n" + parent_heap + "\n" + heap + "\n" + out)
wenzelm@48639
   633
wenzelm@48639
   634
                heap
wenzelm@48639
   635
              }
wenzelm@48639
   636
              else {
wenzelm@48639
   637
                (output_dir + Path.basic(name)).file.delete
wenzelm@48639
   638
                (output_dir + log_gz(name)).file.delete
wenzelm@48639
   639
wenzelm@48639
   640
                File.write(output_dir + log(name), out)
wenzelm@50366
   641
                progress.echo(name + " FAILED")
wenzelm@48661
   642
                if (rc != 130) {
wenzelm@50366
   643
                  progress.echo("(see also " + (output_dir + log(name)).file.toString + ")")
wenzelm@48661
   644
                  val lines = split_lines(out)
wenzelm@48661
   645
                  val tail = lines.drop(lines.length - 20 max 0)
wenzelm@50366
   646
                  progress.echo("\n" + cat_lines(tail))
wenzelm@48661
   647
                }
wenzelm@48639
   648
wenzelm@48639
   649
                no_heap
wenzelm@48639
   650
              }
wenzelm@48639
   651
            loop(pending - name, running - name, results + (name -> Result(false, heap, rc)))
wenzelm@50367
   652
            //}}}
wenzelm@48547
   653
          case None if (running.size < (max_jobs max 1)) =>
wenzelm@50367
   654
            //{{{ check/start next job
wenzelm@48547
   655
            pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48547
   656
              case Some((name, info)) =>
wenzelm@48639
   657
                val parent_result =
wenzelm@48639
   658
                  info.parent match {
wenzelm@48639
   659
                    case None => Result(true, no_heap, 0)
wenzelm@48639
   660
                    case Some(parent) => results(parent)
wenzelm@48639
   661
                  }
wenzelm@48547
   662
                val output = output_dir + Path.basic(name)
wenzelm@48547
   663
                val do_output = build_heap || queue.is_inner(name)
wenzelm@48547
   664
wenzelm@48639
   665
                val (current, heap) =
wenzelm@48547
   666
                {
wenzelm@48548
   667
                  input_dirs.find(dir => (dir + log_gz(name)).is_file) match {
wenzelm@48547
   668
                    case Some(dir) =>
wenzelm@48639
   669
                      read_stamps(dir + log_gz(name)) match {
wenzelm@48639
   670
                        case Some((s, h1, h2)) =>
wenzelm@48639
   671
                          val heap = heap_stamp(Some(dir + Path.basic(name)))
wenzelm@48639
   672
                          (s == make_stamp(name) && h1 == parent_result.heap && h2 == heap &&
wenzelm@48639
   673
                            !(do_output && heap == no_heap), heap)
wenzelm@48639
   674
                        case None => (false, no_heap)
wenzelm@48547
   675
                      }
wenzelm@48639
   676
                    case None => (false, no_heap)
wenzelm@48504
   677
                  }
wenzelm@48547
   678
                }
wenzelm@48639
   679
                val all_current = current && parent_result.current
wenzelm@48528
   680
wenzelm@48547
   681
                if (all_current)
wenzelm@48639
   682
                  loop(pending - name, running, results + (name -> Result(true, heap, 0)))
wenzelm@48678
   683
                else if (no_build) {
wenzelm@50366
   684
                  if (verbose) progress.echo("Skipping " + name + " ...")
wenzelm@48639
   685
                  loop(pending - name, running, results + (name -> Result(false, heap, 1)))
wenzelm@48678
   686
                }
wenzelm@48639
   687
                else if (parent_result.rc == 0) {
wenzelm@50366
   688
                  progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
wenzelm@48674
   689
                  val job = new Job(name, info, output, do_output, verbose, browser_info)
wenzelm@48674
   690
                  loop(pending, running + (name -> (parent_result.heap, job)), results)
wenzelm@48547
   691
                }
wenzelm@48547
   692
                else {
wenzelm@50366
   693
                  progress.echo(name + " CANCELLED")
wenzelm@48639
   694
                  loop(pending - name, running, results + (name -> Result(false, heap, 1)))
wenzelm@48547
   695
                }
wenzelm@48547
   696
              case None => sleep(); loop(pending, running, results)
wenzelm@48425
   697
            }
wenzelm@50367
   698
            ///}}}
wenzelm@48425
   699
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   700
        }
wenzelm@48425
   701
    }
wenzelm@48425
   702
wenzelm@48583
   703
    val results =
wenzelm@48583
   704
      if (deps.is_empty) {
wenzelm@50366
   705
        progress.echo("### Nothing to build")
wenzelm@48583
   706
        Map.empty
wenzelm@48583
   707
      }
wenzelm@48583
   708
      else loop(queue, Map.empty, Map.empty)
wenzelm@48583
   709
wenzelm@48639
   710
    val rc = (0 /: results)({ case (rc1, (_, res)) => rc1 max res.rc })
wenzelm@48504
   711
    if (rc != 0 && (verbose || !no_build)) {
wenzelm@48552
   712
      val unfinished =
wenzelm@49951
   713
        (for ((name, res) <- results.iterator if res.rc != 0) yield name).toList
wenzelm@49951
   714
          .sorted(scala.math.Ordering.String)  // FIXME scala-2.10.0-RC1
wenzelm@50366
   715
      progress.echo("Unfinished session(s): " + commas(unfinished))
wenzelm@48473
   716
    }
wenzelm@48473
   717
    rc
wenzelm@48341
   718
  }
wenzelm@48341
   719
wenzelm@48341
   720
wenzelm@48346
   721
  /* command line entry point */
wenzelm@48341
   722
wenzelm@48341
   723
  def main(args: Array[String])
wenzelm@48341
   724
  {
wenzelm@48346
   725
    Command_Line.tool {
wenzelm@48346
   726
      args.toList match {
wenzelm@48346
   727
        case
wenzelm@49131
   728
          Properties.Value.Boolean(requirements) ::
wenzelm@48346
   729
          Properties.Value.Boolean(all_sessions) ::
wenzelm@48511
   730
          Properties.Value.Boolean(build_heap) ::
wenzelm@48595
   731
          Properties.Value.Boolean(clean_build) ::
wenzelm@48425
   732
          Properties.Value.Int(max_jobs) ::
wenzelm@48903
   733
          Properties.Value.Boolean(list_files) ::
wenzelm@48469
   734
          Properties.Value.Boolean(no_build) ::
wenzelm@48447
   735
          Properties.Value.Boolean(system_mode) ::
wenzelm@48425
   736
          Properties.Value.Boolean(verbose) ::
wenzelm@48737
   737
          Command_Line.Chunks(select_dirs, include_dirs, session_groups, build_options, sessions) =>
wenzelm@50404
   738
            val options = (Options.init() /: build_options)(_ + _)
wenzelm@48737
   739
            val dirs =
wenzelm@48737
   740
              select_dirs.map(d => (true, Path.explode(d))) :::
wenzelm@48737
   741
              include_dirs.map(d => (false, Path.explode(d)))
wenzelm@50404
   742
            build(Build.Console_Progress, options, requirements, all_sessions, build_heap,
wenzelm@50404
   743
              clean_build, dirs, session_groups, max_jobs, list_files, no_build, system_mode,
wenzelm@50366
   744
              verbose, sessions)
wenzelm@48346
   745
        case _ => error("Bad arguments:\n" + cat_lines(args))
wenzelm@48341
   746
      }
wenzelm@48346
   747
    }
wenzelm@48341
   748
  }
wenzelm@48276
   749
}
wenzelm@48276
   750