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