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