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