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