src/Pure/Tools/build.scala
author wenzelm
Mon Jan 09 20:47:45 2017 +0100 (2017-01-09)
changeset 64856 5e9bf964510a
parent 64855 8fcc23e8e1d9
child 64909 8007f10195af
permissions -rw-r--r--
clarified modules;
tuned;
wenzelm@50686
     1
/*  Title:      Pure/Tools/build.scala
wenzelm@48276
     2
    Author:     Makarius
wenzelm@57923
     3
    Options:    :folding=explicit:
wenzelm@48276
     4
wenzelm@48276
     5
Build and manage Isabelle sessions.
wenzelm@48276
     6
*/
wenzelm@48276
     7
wenzelm@48276
     8
package isabelle
wenzelm@48276
     9
wenzelm@48276
    10
wenzelm@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@51397
    16
import scala.collection.mutable
wenzelm@48340
    17
import scala.annotation.tailrec
wenzelm@48337
    18
wenzelm@48335
    19
wenzelm@48276
    20
object Build
wenzelm@48276
    21
{
wenzelm@62631
    22
  /** auxiliary **/
wenzelm@48424
    23
wenzelm@48676
    24
  /* queue */
wenzelm@48676
    25
wenzelm@62631
    26
  private object Queue
wenzelm@48676
    27
  {
wenzelm@62631
    28
    def apply(tree: Sessions.Tree, load_timings: String => (List[Properties.T], Double)): Queue =
wenzelm@48676
    29
    {
wenzelm@48676
    30
      val graph = tree.graph
wenzelm@56372
    31
      val sessions = graph.keys
wenzelm@51220
    32
wenzelm@59136
    33
      val timings = Par_List.map((name: String) => (name, load_timings(name)), sessions)
wenzelm@51220
    34
      val command_timings =
wenzelm@51220
    35
        Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
wenzelm@51220
    36
      val session_timing =
wenzelm@51220
    37
        Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
wenzelm@48678
    38
wenzelm@48678
    39
      def outdegree(name: String): Int = graph.imm_succs(name).size
wenzelm@48678
    40
wenzelm@48678
    41
      object Ordering extends scala.math.Ordering[String]
wenzelm@48678
    42
      {
wenzelm@51227
    43
        def compare_timing(name1: String, name2: String): Int =
wenzelm@51227
    44
        {
wenzelm@51227
    45
          val t1 = session_timing(name1)
wenzelm@51227
    46
          val t2 = session_timing(name2)
wenzelm@51227
    47
          if (t1 == 0.0 || t2 == 0.0) 0
wenzelm@51227
    48
          else t1 compare t2
wenzelm@51227
    49
        }
wenzelm@51227
    50
wenzelm@48678
    51
        def compare(name1: String, name2: String): Int =
wenzelm@51229
    52
          outdegree(name2) compare outdegree(name1) match {
wenzelm@48678
    53
            case 0 =>
wenzelm@51229
    54
              compare_timing(name2, name1) match {
wenzelm@51220
    55
                case 0 =>
wenzelm@61602
    56
                  tree(name2).timeout compare tree(name1).timeout match {
wenzelm@51220
    57
                    case 0 => name1 compare name2
wenzelm@51220
    58
                    case ord => ord
wenzelm@51220
    59
                  }
wenzelm@48678
    60
                case ord => ord
wenzelm@48678
    61
              }
wenzelm@48678
    62
            case ord => ord
wenzelm@48678
    63
          }
wenzelm@48678
    64
      }
wenzelm@48678
    65
wenzelm@51220
    66
      new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
wenzelm@48676
    67
    }
wenzelm@48676
    68
  }
wenzelm@48676
    69
wenzelm@62631
    70
  private final class Queue private(
wenzelm@62631
    71
    graph: Graph[String, Sessions.Info],
wenzelm@51220
    72
    order: SortedSet[String],
wenzelm@51220
    73
    val command_timings: String => List[Properties.T])
wenzelm@48676
    74
  {
wenzelm@48676
    75
    def is_inner(name: String): Boolean = !graph.is_maximal(name)
wenzelm@48676
    76
wenzelm@48676
    77
    def is_empty: Boolean = graph.is_empty
wenzelm@48676
    78
wenzelm@51227
    79
    def - (name: String): Queue =
wenzelm@51227
    80
      new Queue(graph.del_node(name),
wenzelm@51227
    81
        order - name,  // FIXME scala-2.10.0 TreeSet problem!?
wenzelm@51227
    82
        command_timings)
wenzelm@48676
    83
wenzelm@62631
    84
    def dequeue(skip: String => Boolean): Option[(String, Sessions.Info)] =
wenzelm@48676
    85
    {
wenzelm@51227
    86
      val it = order.iterator.dropWhile(name =>
wenzelm@51227
    87
        skip(name)
wenzelm@51227
    88
          || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
wenzelm@51227
    89
          || !graph.is_minimal(name))
wenzelm@48680
    90
      if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
wenzelm@48676
    91
      else None
wenzelm@48676
    92
    }
wenzelm@48676
    93
  }
wenzelm@48676
    94
wenzelm@48676
    95
wenzelm@48710
    96
  /* source dependencies and static content */
wenzelm@48422
    97
wenzelm@64856
    98
  sealed case class Deps(deps: Map[String, Sessions.Base])
wenzelm@48423
    99
  {
wenzelm@48583
   100
    def is_empty: Boolean = deps.isEmpty
wenzelm@64856
   101
    def apply(name: String): Sessions.Base = deps(name)
wenzelm@48504
   102
    def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
wenzelm@48423
   103
  }
wenzelm@48423
   104
wenzelm@59891
   105
  def dependencies(
wenzelm@59891
   106
      progress: Progress = Ignore_Progress,
wenzelm@59891
   107
      inlined_files: Boolean = false,
wenzelm@59891
   108
      verbose: Boolean = false,
wenzelm@59891
   109
      list_files: Boolean = false,
wenzelm@59891
   110
      check_keywords: Set[String] = Set.empty,
wenzelm@62631
   111
      tree: Sessions.Tree): Deps =
wenzelm@64856
   112
    Deps((Map.empty[String, Sessions.Base] /: tree.topological_order)(
wenzelm@48422
   113
      { case (deps, (name, info)) =>
wenzelm@56668
   114
          if (progress.stopped) throw Exn.Interrupt()
wenzelm@56668
   115
wenzelm@54549
   116
          try {
wenzelm@64856
   117
            val resources =
wenzelm@64856
   118
              new Resources(
wenzelm@64856
   119
                info.parent match {
wenzelm@64856
   120
                  case None => Sessions.Base.bootstrap
wenzelm@64856
   121
                  case Some(parent) => deps(parent)
wenzelm@64856
   122
                })
wenzelm@48422
   123
wenzelm@54549
   124
            if (verbose || list_files) {
wenzelm@54549
   125
              val groups =
wenzelm@54549
   126
                if (info.groups.isEmpty) ""
wenzelm@54549
   127
                else info.groups.mkString(" (", " ", ")")
wenzelm@54549
   128
              progress.echo("Session " + info.chapter + "/" + name + groups)
wenzelm@54549
   129
            }
wenzelm@48478
   130
wenzelm@54549
   131
            val thy_deps =
wenzelm@56801
   132
            {
wenzelm@56801
   133
              val root_theories =
wenzelm@56801
   134
                info.theories.flatMap({
wenzelm@56801
   135
                  case (global, _, thys) =>
wenzelm@56801
   136
                    thys.map(thy =>
wenzelm@56801
   137
                      (resources.node_name(
wenzelm@56801
   138
                        if (global) "" else name, info.dir + Resources.thy_path(thy)), info.pos))
wenzelm@56801
   139
                })
wenzelm@64839
   140
              val thy_deps = resources.thy_info.dependencies(name, root_theories)
wenzelm@48422
   141
wenzelm@56801
   142
              thy_deps.errors match {
wenzelm@56801
   143
                case Nil => thy_deps
wenzelm@56801
   144
                case errs => error(cat_lines(errs))
wenzelm@56801
   145
              }
wenzelm@54549
   146
            }
wenzelm@51294
   147
wenzelm@56801
   148
            val known_theories =
wenzelm@64856
   149
              (resources.base.known_theories /: thy_deps.deps)({ case (known, dep) =>
wenzelm@56801
   150
                val name = dep.name
wenzelm@56801
   151
                known.get(name.theory) match {
wenzelm@56801
   152
                  case Some(name1) if name != name1 =>
wenzelm@56801
   153
                    error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
wenzelm@56801
   154
                  case _ =>
wenzelm@56801
   155
                    known + (name.theory -> name) + (Long_Name.base_name(name.theory) -> name)
wenzelm@56801
   156
                }
wenzelm@56801
   157
              })
wenzelm@56801
   158
wenzelm@54549
   159
            val loaded_theories = thy_deps.loaded_theories
wenzelm@54549
   160
            val keywords = thy_deps.keywords
wenzelm@63865
   161
            val syntax = thy_deps.syntax
wenzelm@48660
   162
wenzelm@59891
   163
            val theory_files = thy_deps.deps.map(dep => Path.explode(dep.name.node))
wenzelm@62866
   164
            val loaded_files =
wenzelm@62902
   165
              if (inlined_files) {
wenzelm@62902
   166
                val pure_files =
wenzelm@62902
   167
                  if (Sessions.pure_name(name)) Sessions.pure_files(resources, syntax, info.dir)
wenzelm@62902
   168
                  else Nil
wenzelm@62902
   169
                pure_files ::: thy_deps.loaded_files
wenzelm@62902
   170
              }
wenzelm@62866
   171
              else Nil
wenzelm@48903
   172
wenzelm@54549
   173
            val all_files =
wenzelm@59891
   174
              (theory_files ::: loaded_files :::
wenzelm@56533
   175
                info.files.map(file => info.dir + file) :::
wenzelm@56533
   176
                info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
wenzelm@54549
   177
wenzelm@56824
   178
            if (list_files)
wenzelm@54549
   179
              progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
wenzelm@54549
   180
wenzelm@59895
   181
            if (check_keywords.nonEmpty)
wenzelm@59895
   182
              Check_Keywords.check_keywords(progress, syntax.keywords, check_keywords, theory_files)
wenzelm@59891
   183
wenzelm@54549
   184
            val sources = all_files.map(p => (p, SHA1.digest(p.file)))
wenzelm@48903
   185
wenzelm@60077
   186
            val session_graph =
wenzelm@64856
   187
              Present.session_graph(info.parent getOrElse "",
wenzelm@64856
   188
                resources.base.loaded_theories, thy_deps.deps)
wenzelm@59444
   189
wenzelm@64856
   190
            val base =
wenzelm@64856
   191
              Sessions.Base(
wenzelm@64856
   192
                loaded_theories, known_theories, keywords, syntax, sources, session_graph)
wenzelm@64856
   193
            deps + (name -> base)
wenzelm@54549
   194
          }
wenzelm@54549
   195
          catch {
wenzelm@54549
   196
            case ERROR(msg) =>
wenzelm@54549
   197
              cat_error(msg, "The error(s) above occurred in session " +
wenzelm@54549
   198
                quote(name) + Position.here(info.pos))
wenzelm@54549
   199
          }
wenzelm@48423
   200
      }))
wenzelm@48422
   201
wenzelm@52439
   202
  def session_dependencies(
wenzelm@52439
   203
    options: Options,
wenzelm@52439
   204
    inlined_files: Boolean,
wenzelm@52439
   205
    dirs: List[Path],
wenzelm@52439
   206
    sessions: List[String]): Deps =
wenzelm@48710
   207
  {
wenzelm@62635
   208
    val (_, tree) = Sessions.load(options, dirs = dirs).selection(sessions = sessions)
wenzelm@59891
   209
    dependencies(inlined_files = inlined_files, tree = tree)
wenzelm@48710
   210
  }
wenzelm@48710
   211
wenzelm@64856
   212
  def session_base(
wenzelm@52439
   213
    options: Options,
wenzelm@52439
   214
    inlined_files: Boolean,
wenzelm@52439
   215
    dirs: List[Path],
wenzelm@64856
   216
    session: String): Sessions.Base =
wenzelm@52439
   217
  {
wenzelm@52439
   218
    session_dependencies(options, inlined_files, dirs, List(session))(session)
wenzelm@52439
   219
  }
wenzelm@52439
   220
wenzelm@64738
   221
  def outer_syntax(options: Options, dirs: List[Path], session: String): Outer_Syntax =
wenzelm@64856
   222
    session_base(options, false, dirs, session).syntax
wenzelm@48710
   223
wenzelm@48422
   224
wenzelm@48424
   225
  /* jobs */
wenzelm@48341
   226
wenzelm@62637
   227
  private class Job(progress: Progress, name: String, val info: Sessions.Info, tree: Sessions.Tree,
wenzelm@64265
   228
    store: Sessions.Store, do_output: Boolean, verbose: Boolean, val numa_node: Option[Int],
wenzelm@62633
   229
    session_graph: Graph_Display.Graph, command_timings: List[Properties.T])
wenzelm@48418
   230
  {
wenzelm@62633
   231
    val output = store.output_dir + Path.basic(name)
wenzelm@48674
   232
    def output_path: Option[Path] = if (do_output) Some(output) else None
wenzelm@62630
   233
    def output_save_state: String =
wenzelm@62825
   234
      if (do_output) "ML_Heap.save_child " + ML_Syntax.print_string0(File.platform_path(output))
wenzelm@62630
   235
      else ""
wenzelm@62633
   236
    output.file.delete
wenzelm@48674
   237
wenzelm@48674
   238
    private val parent = info.parent.getOrElse("")
wenzelm@48418
   239
wenzelm@59445
   240
    private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
wenzelm@59445
   241
    try { isabelle.graphview.Graph_File.write(info.options, graph_file, session_graph) }
wenzelm@59445
   242
    catch { case ERROR(_) => /*error should be exposed in ML*/ }
wenzelm@59445
   243
wenzelm@62610
   244
    private val env =
wenzelm@62610
   245
      Isabelle_System.settings() +
wenzelm@62610
   246
        ("ISABELLE_ML_DEBUGGER" -> info.options.bool("ML_debugger").toString)
wenzelm@48698
   247
wenzelm@62573
   248
    private val future_result: Future[Process_Result] =
wenzelm@61559
   249
      Future.thread("build") {
wenzelm@62944
   250
        val args_file = Isabelle_System.tmp_file("build")
wenzelm@62944
   251
        File.write(args_file, YXML.string_of_body(
wenzelm@62944
   252
            {
wenzelm@62944
   253
              val theories = info.theories.map(x => (x._2, x._3))
wenzelm@62944
   254
              import XML.Encode._
wenzelm@62944
   255
              pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
wenzelm@62944
   256
                pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
wenzelm@62944
   257
                pair(string, pair(string, pair(string,
wenzelm@62944
   258
                list(pair(Options.encode, list(Path.encode)))))))))))))(
wenzelm@62944
   259
              (Symbol.codes, (command_timings, (do_output, (verbose,
wenzelm@62944
   260
                (store.browser_info, (info.document_files, (File.standard_path(graph_file),
wenzelm@62944
   261
                (parent, (info.chapter, (name,
wenzelm@62944
   262
                theories)))))))))))
wenzelm@62944
   263
            }))
wenzelm@62944
   264
wenzelm@62944
   265
        val eval =
wenzelm@62944
   266
          "Command_Line.tool0 (fn () => (" +
wenzelm@62944
   267
          "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
wenzelm@62944
   268
          (if (do_output) "; ML_Heap.share_common_data (); " + output_save_state
wenzelm@62944
   269
           else "") + "));"
wenzelm@64265
   270
wenzelm@64265
   271
        val process_options =
wenzelm@64265
   272
          numa_node match {
wenzelm@64265
   273
            case None => info.options
wenzelm@64265
   274
            case Some(n) => info.options.string("ML_process_policy") = NUMA.policy(n)
wenzelm@64265
   275
          }
wenzelm@62573
   276
        val process =
wenzelm@62883
   277
          if (Sessions.pure_name(name)) {
wenzelm@64265
   278
            ML_Process(process_options, raw_ml_system = true, cwd = info.dir.file,
wenzelm@62946
   279
              args =
wenzelm@62946
   280
                (for ((root, _) <- Thy_Header.ml_roots) yield List("--use", root)).flatten :::
wenzelm@62946
   281
                List("--eval", eval),
wenzelm@62944
   282
              env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
wenzelm@62573
   283
          }
wenzelm@62573
   284
          else {
wenzelm@64265
   285
            ML_Process(process_options, parent, List("--eval", eval), cwd = info.dir.file,
wenzelm@62637
   286
              env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
wenzelm@62573
   287
          }
wenzelm@64265
   288
wenzelm@62573
   289
        process.result(
wenzelm@51962
   290
          progress_stdout = (line: String) =>
wenzelm@50847
   291
            Library.try_unprefix("\floading_theory = ", line) match {
wenzelm@50847
   292
              case Some(theory) => progress.theory(name, theory)
wenzelm@50847
   293
              case None =>
wenzelm@51962
   294
            },
wenzelm@51962
   295
          progress_limit =
wenzelm@51962
   296
            info.options.int("process_output_limit") match {
wenzelm@51962
   297
              case 0 => None
wenzelm@51962
   298
              case m => Some(m * 1000000L)
wenzelm@56871
   299
            },
wenzelm@56871
   300
          strict = false)
wenzelm@50845
   301
      }
wenzelm@48674
   302
wenzelm@62572
   303
    def terminate: Unit = future_result.cancel
wenzelm@62572
   304
    def is_finished: Boolean = future_result.is_finished
wenzelm@48674
   305
wenzelm@62569
   306
    @volatile private var was_timeout = false
wenzelm@56779
   307
    private val timeout_request: Option[Event_Timer.Request] =
wenzelm@56779
   308
    {
wenzelm@62569
   309
      if (info.timeout > Time.zero)
wenzelm@62569
   310
        Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
wenzelm@48674
   311
      else None
wenzelm@56779
   312
    }
wenzelm@48674
   313
wenzelm@62400
   314
    def join: Process_Result =
wenzelm@50845
   315
    {
wenzelm@62572
   316
      val result = future_result.join
wenzelm@50845
   317
wenzelm@62944
   318
      if (result.ok)
wenzelm@62633
   319
        Present.finish(progress, store.browser_info, graph_file, info, name)
wenzelm@61372
   320
wenzelm@59445
   321
      graph_file.delete
wenzelm@56779
   322
      timeout_request.foreach(_.cancel)
wenzelm@48674
   323
wenzelm@62572
   324
      if (result.interrupted) {
wenzelm@62572
   325
        if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
wenzelm@62572
   326
        else result.error(Output.error_text("Interrupt"))
wenzelm@52063
   327
      }
wenzelm@62572
   328
      else result
wenzelm@48674
   329
    }
wenzelm@48364
   330
  }
wenzelm@48364
   331
wenzelm@48424
   332
wenzelm@50777
   333
  /* sources and heaps */
wenzelm@50777
   334
wenzelm@62628
   335
  private val SOURCES = "sources: "
wenzelm@62628
   336
  private val INPUT_HEAP = "input_heap: "
wenzelm@62628
   337
  private val OUTPUT_HEAP = "output_heap: "
wenzelm@62628
   338
  private val LOG_START = "log:"
wenzelm@62628
   339
  private val line_prefixes = List(SOURCES, INPUT_HEAP, OUTPUT_HEAP, LOG_START)
wenzelm@48504
   340
wenzelm@62628
   341
  private def sources_stamp(digests: List[SHA1.Digest]): String =
wenzelm@62628
   342
    digests.map(_.toString).sorted.mkString(SOURCES, " ", "")
wenzelm@48639
   343
wenzelm@62628
   344
  private def read_stamps(path: Path): Option[(String, List[String], List[String])] =
wenzelm@48639
   345
    if (path.is_file) {
wenzelm@62628
   346
      val stream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(path.file)))
wenzelm@50203
   347
      val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
wenzelm@62628
   348
      val lines =
wenzelm@62628
   349
      {
wenzelm@62628
   350
        val lines = new mutable.ListBuffer[String]
wenzelm@62628
   351
        try {
wenzelm@62628
   352
          var finished = false
wenzelm@62628
   353
          while (!finished) {
wenzelm@62628
   354
            val line = reader.readLine
wenzelm@62628
   355
            if (line != null && line_prefixes.exists(line.startsWith(_)))
wenzelm@62628
   356
              lines += line
wenzelm@62628
   357
            else finished = true
wenzelm@62628
   358
          }
wenzelm@62628
   359
        }
wenzelm@48639
   360
        finally { reader.close }
wenzelm@62628
   361
        lines.toList
wenzelm@62628
   362
      }
wenzelm@62628
   363
wenzelm@62628
   364
      if (!lines.isEmpty && lines.last.startsWith(LOG_START)) {
wenzelm@62628
   365
        lines.find(_.startsWith(SOURCES)).map(s =>
wenzelm@62628
   366
          (s, lines.filter(_.startsWith(INPUT_HEAP)), lines.filter(_.startsWith(OUTPUT_HEAP))))
wenzelm@62628
   367
      }
wenzelm@48504
   368
      else None
wenzelm@48504
   369
    }
wenzelm@48504
   370
    else None
wenzelm@48504
   371
wenzelm@48504
   372
wenzelm@62631
   373
wenzelm@62641
   374
  /** build with results **/
wenzelm@48424
   375
wenzelm@63996
   376
  class Results private[Build](results: Map[String, (Option[Process_Result], Sessions.Info)])
wenzelm@62403
   377
  {
wenzelm@62403
   378
    def sessions: Set[String] = results.keySet
lars@63082
   379
    def cancelled(name: String): Boolean = results(name)._1.isEmpty
lars@63082
   380
    def apply(name: String): Process_Result = results(name)._1.getOrElse(Process_Result(1))
lars@63082
   381
    def info(name: String): Sessions.Info = results(name)._2
lars@63082
   382
    val rc = (0 /: results.iterator.map({ case (_, (Some(r), _)) => r.rc case (_, (None, _)) => 1 }))(_ max _)
wenzelm@62641
   383
    def ok: Boolean = rc == 0
wenzelm@62406
   384
wenzelm@62406
   385
    override def toString: String = rc.toString
wenzelm@62403
   386
  }
wenzelm@62403
   387
wenzelm@62641
   388
  def build(
wenzelm@50404
   389
    options: Options,
wenzelm@52115
   390
    progress: Progress = Ignore_Progress,
wenzelm@48511
   391
    build_heap: Boolean = false,
wenzelm@48595
   392
    clean_build: Boolean = false,
wenzelm@56890
   393
    dirs: List[Path] = Nil,
wenzelm@56890
   394
    select_dirs: List[Path] = Nil,
wenzelm@64265
   395
    numa_shuffling: Boolean = false,
wenzelm@48509
   396
    max_jobs: Int = 1,
wenzelm@48903
   397
    list_files: Boolean = false,
wenzelm@59891
   398
    check_keywords: Set[String] = Set.empty,
wenzelm@48509
   399
    no_build: Boolean = false,
wenzelm@48509
   400
    system_mode: Boolean = false,
wenzelm@48509
   401
    verbose: Boolean = false,
wenzelm@63224
   402
    requirements: Boolean = false,
wenzelm@63224
   403
    all_sessions: Boolean = false,
wenzelm@63224
   404
    exclude_session_groups: List[String] = Nil,
wenzelm@59892
   405
    exclude_sessions: List[String] = Nil,
wenzelm@63224
   406
    session_groups: List[String] = Nil,
wenzelm@62641
   407
    sessions: List[String] = Nil): Results =
wenzelm@48341
   408
  {
wenzelm@63224
   409
    build_selection(
wenzelm@63224
   410
      options = options,
wenzelm@63224
   411
      progress = progress,
wenzelm@63224
   412
      build_heap = build_heap,
wenzelm@63224
   413
      clean_build = clean_build,
wenzelm@63224
   414
      dirs = dirs,
wenzelm@63224
   415
      select_dirs = select_dirs,
wenzelm@64265
   416
      numa_shuffling = numa_shuffling,
wenzelm@63224
   417
      max_jobs = max_jobs,
wenzelm@63224
   418
      list_files = list_files,
wenzelm@63224
   419
      check_keywords = check_keywords,
wenzelm@63224
   420
      no_build = no_build,
wenzelm@63224
   421
      system_mode = system_mode,
wenzelm@63224
   422
      verbose = verbose,
wenzelm@63224
   423
      selection = { full_tree =>
wenzelm@63224
   424
        full_tree.selection(requirements, all_sessions,
wenzelm@63224
   425
          exclude_session_groups, exclude_sessions, session_groups, sessions) })
wenzelm@63224
   426
  }
wenzelm@63224
   427
wenzelm@63224
   428
  def build_selection(
wenzelm@63224
   429
    options: Options,
wenzelm@63224
   430
    progress: Progress = Ignore_Progress,
wenzelm@63224
   431
    build_heap: Boolean = false,
wenzelm@63224
   432
    clean_build: Boolean = false,
wenzelm@63224
   433
    dirs: List[Path] = Nil,
wenzelm@63224
   434
    select_dirs: List[Path] = Nil,
wenzelm@64265
   435
    numa_shuffling: Boolean = false,
wenzelm@63224
   436
    max_jobs: Int = 1,
wenzelm@63224
   437
    list_files: Boolean = false,
wenzelm@63224
   438
    check_keywords: Set[String] = Set.empty,
wenzelm@63224
   439
    no_build: Boolean = false,
wenzelm@63224
   440
    system_mode: Boolean = false,
wenzelm@63224
   441
    verbose: Boolean = false,
wenzelm@63224
   442
    selection: Sessions.Tree => (List[String], Sessions.Tree) =
wenzelm@63224
   443
      (_.selection(all_sessions = true))): Results =
wenzelm@63224
   444
  {
wenzelm@63224
   445
    /* session selection and dependencies */
wenzelm@51220
   446
wenzelm@62714
   447
    val build_options = options.int.update("completion_limit", 0).bool.update("ML_statistics", true)
wenzelm@62714
   448
    val full_tree = Sessions.load(build_options, dirs, select_dirs)
wenzelm@63224
   449
    val (selected, selected_tree) = selection(full_tree)
wenzelm@59891
   450
    val deps = dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
wenzelm@48368
   451
wenzelm@62628
   452
    def session_sources_stamp(name: String): String =
wenzelm@62631
   453
      sources_stamp(selected_tree(name).meta_digest :: deps.sources(name))
wenzelm@48504
   454
wenzelm@62632
   455
    val store = Sessions.store(system_mode)
wenzelm@51220
   456
wenzelm@51220
   457
wenzelm@51220
   458
    /* queue with scheduling information */
wenzelm@51220
   459
wenzelm@51230
   460
    def load_timings(name: String): (List[Properties.T], Double) =
wenzelm@51221
   461
    {
wenzelm@51221
   462
      val (path, text) =
wenzelm@62632
   463
        store.find_log_gz(name) match {
wenzelm@62632
   464
          case Some(path) => (path, File.read_gzip(path))
wenzelm@51221
   465
          case None =>
wenzelm@62632
   466
            store.find_log(name) match {
wenzelm@62632
   467
              case Some(path) => (path, File.read(path))
wenzelm@51221
   468
              case None => (Path.current, "")
wenzelm@51221
   469
            }
wenzelm@51221
   470
        }
wenzelm@51244
   471
wenzelm@51244
   472
      def ignore_error(msg: String): (List[Properties.T], Double) =
wenzelm@51244
   473
      {
wenzelm@56782
   474
        Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
wenzelm@51244
   475
        (Nil, 0.0)
wenzelm@51244
   476
      }
wenzelm@51244
   477
wenzelm@51221
   478
      try {
wenzelm@64082
   479
        val info = Build_Log.Log_File(name, text).parse_session_info(name, command_timings = true)
wenzelm@51221
   480
        val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
wenzelm@51221
   481
        (info.command_timings, session_timing)
wenzelm@51220
   482
      }
wenzelm@51221
   483
      catch {
wenzelm@51244
   484
        case ERROR(msg) => ignore_error(msg)
wenzelm@51986
   485
        case exn: java.lang.Error => ignore_error(Exn.message(exn))
wenzelm@51987
   486
        case _: XML.Error => ignore_error("")
wenzelm@51221
   487
      }
wenzelm@51221
   488
    }
wenzelm@51220
   489
wenzelm@51230
   490
    val queue = Queue(selected_tree, load_timings)
wenzelm@51220
   491
wenzelm@51220
   492
wenzelm@51220
   493
    /* main build process */
wenzelm@51220
   494
wenzelm@62632
   495
    store.prepare_output()
wenzelm@48373
   496
wenzelm@48595
   497
    // optional cleanup
wenzelm@48595
   498
    if (clean_build) {
wenzelm@49131
   499
      for (name <- full_tree.graph.all_succs(selected)) {
wenzelm@48595
   500
        val files =
wenzelm@62632
   501
          List(Path.basic(name), Sessions.log(name), Sessions.log_gz(name)).
wenzelm@62632
   502
            map(store.output_dir + _).filter(_.is_file)
wenzelm@59319
   503
        if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
wenzelm@50366
   504
        if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
wenzelm@48595
   505
      }
wenzelm@48595
   506
    }
wenzelm@48595
   507
wenzelm@48425
   508
    // scheduler loop
lars@63082
   509
    case class Result(
lars@63082
   510
      current: Boolean, heap_stamp: Option[String],
lars@63082
   511
      process: Option[Process_Result], info: Sessions.Info)
wenzelm@62402
   512
    {
wenzelm@62402
   513
      def ok: Boolean =
wenzelm@62402
   514
        process match {
wenzelm@62402
   515
          case None => false
wenzelm@62402
   516
          case Some(res) => res.rc == 0
wenzelm@62402
   517
        }
wenzelm@62402
   518
    }
wenzelm@48639
   519
wenzelm@56837
   520
    def sleep()
wenzelm@56837
   521
    {
wenzelm@56837
   522
      try { Thread.sleep(500) }
wenzelm@56861
   523
      catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
wenzelm@56837
   524
    }
wenzelm@50366
   525
wenzelm@64265
   526
    val numa_nodes = new NUMA.Nodes(numa_shuffling)
wenzelm@64265
   527
wenzelm@48425
   528
    @tailrec def loop(
wenzelm@48676
   529
      pending: Queue,
wenzelm@62628
   530
      running: Map[String, (List[String], Job)],
wenzelm@48639
   531
      results: Map[String, Result]): Map[String, Result] =
wenzelm@48425
   532
    {
wenzelm@64265
   533
      def used_node(i: Int): Boolean =
wenzelm@64265
   534
        running.iterator.exists(
wenzelm@64265
   535
          { case (_, (_, job)) => job.numa_node.isDefined && job.numa_node.get == i })
wenzelm@64265
   536
wenzelm@48425
   537
      if (pending.is_empty) results
wenzelm@51253
   538
      else {
wenzelm@51253
   539
        if (progress.stopped)
wenzelm@51253
   540
          for ((_, (_, job)) <- running) job.terminate
wenzelm@51253
   541
wenzelm@48674
   542
        running.find({ case (_, (_, job)) => job.is_finished }) match {
wenzelm@62628
   543
          case Some((name, (input_heaps, job))) =>
wenzelm@50367
   544
            //{{{ finish job
wenzelm@48424
   545
wenzelm@62401
   546
            val process_result = job.join
wenzelm@62573
   547
            process_result.err_lines.foreach(progress.echo(_))
wenzelm@62573
   548
            if (process_result.ok)
wenzelm@62573
   549
              progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
wenzelm@48373
   550
wenzelm@62404
   551
            val process_result_tail =
wenzelm@62404
   552
            {
wenzelm@62404
   553
              val lines = process_result.out_lines.filterNot(_.startsWith("\f"))
wenzelm@62409
   554
              val tail = job.info.options.int("process_output_tail")
wenzelm@62409
   555
              val lines1 = if (tail == 0) lines else lines.drop(lines.length - tail max 0)
wenzelm@62632
   556
              process_result.copy(
wenzelm@62632
   557
                out_lines =
wenzelm@62632
   558
                  "(see also " + (store.output_dir + Sessions.log(name)).file.toString + ")" ::
wenzelm@62632
   559
                  lines1)
wenzelm@62404
   560
            }
wenzelm@62404
   561
wenzelm@62636
   562
            val heap_stamp =
wenzelm@62401
   563
              if (process_result.ok) {
wenzelm@62632
   564
                (store.output_dir + Sessions.log(name)).file.delete
wenzelm@62636
   565
                val heap_stamp =
wenzelm@62704
   566
                  for (path <- job.output_path if path.is_file)
wenzelm@62704
   567
                    yield Sessions.write_heap_digest(path)
wenzelm@48639
   568
wenzelm@62632
   569
                File.write_gzip(store.output_dir + Sessions.log_gz(name),
wenzelm@64173
   570
                  terminate_lines(
wenzelm@62628
   571
                    session_sources_stamp(name) ::
wenzelm@62628
   572
                    input_heaps.map(INPUT_HEAP + _) :::
wenzelm@62636
   573
                    heap_stamp.toList.map(OUTPUT_HEAP + _) :::
wenzelm@62628
   574
                    List(LOG_START) ::: process_result.out_lines))
wenzelm@48639
   575
wenzelm@62636
   576
                heap_stamp
wenzelm@48639
   577
              }
wenzelm@48639
   578
              else {
wenzelm@62632
   579
                (store.output_dir + Path.basic(name)).file.delete
wenzelm@62632
   580
                (store.output_dir + Sessions.log_gz(name)).file.delete
wenzelm@48639
   581
wenzelm@62632
   582
                File.write(store.output_dir + Sessions.log(name),
wenzelm@64173
   583
                  terminate_lines(process_result.out_lines))
wenzelm@50366
   584
                progress.echo(name + " FAILED")
wenzelm@62404
   585
                if (!process_result.interrupted) progress.echo(process_result_tail.out)
wenzelm@48639
   586
wenzelm@62636
   587
                None
wenzelm@48639
   588
              }
wenzelm@50707
   589
            loop(pending - name, running - name,
lars@63082
   590
              results + (name -> Result(false, heap_stamp, Some(process_result_tail), job.info)))
wenzelm@50367
   591
            //}}}
wenzelm@60215
   592
          case None if running.size < (max_jobs max 1) =>
wenzelm@50367
   593
            //{{{ check/start next job
wenzelm@48547
   594
            pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48547
   595
              case Some((name, info)) =>
wenzelm@62628
   596
                val ancestor_results = selected_tree.ancestors(name).map(results(_))
wenzelm@62636
   597
                val ancestor_heaps = ancestor_results.flatMap(_.heap_stamp)
wenzelm@62628
   598
wenzelm@62883
   599
                val do_output = build_heap || Sessions.pure_name(name) || queue.is_inner(name)
wenzelm@48547
   600
wenzelm@62636
   601
                val (current, heap_stamp) =
wenzelm@48547
   602
                {
wenzelm@62632
   603
                  store.find(name) match {
wenzelm@62636
   604
                    case Some((log_gz, heap_stamp)) =>
wenzelm@62632
   605
                      read_stamps(log_gz) match {
wenzelm@62628
   606
                        case Some((sources, input_heaps, output_heaps)) =>
wenzelm@62628
   607
                          val current =
wenzelm@62628
   608
                            sources == session_sources_stamp(name) &&
wenzelm@62628
   609
                            input_heaps == ancestor_heaps.map(INPUT_HEAP + _) &&
wenzelm@62636
   610
                            output_heaps == heap_stamp.toList.map(OUTPUT_HEAP + _) &&
wenzelm@62636
   611
                            !(do_output && heap_stamp.isEmpty)
wenzelm@62636
   612
                          (current, heap_stamp)
wenzelm@62636
   613
                        case None => (false, None)
wenzelm@48547
   614
                      }
wenzelm@62636
   615
                    case None => (false, None)
wenzelm@48504
   616
                  }
wenzelm@48547
   617
                }
wenzelm@62628
   618
                val all_current = current && ancestor_results.forall(_.current)
wenzelm@48528
   619
wenzelm@48547
   620
                if (all_current)
wenzelm@62402
   621
                  loop(pending - name, running,
lars@63082
   622
                    results + (name -> Result(true, heap_stamp, Some(Process_Result(0)), info)))
wenzelm@48678
   623
                else if (no_build) {
wenzelm@50366
   624
                  if (verbose) progress.echo("Skipping " + name + " ...")
wenzelm@62402
   625
                  loop(pending - name, running,
lars@63082
   626
                    results + (name -> Result(false, heap_stamp, Some(Process_Result(1)), info)))
wenzelm@48678
   627
                }
wenzelm@62628
   628
                else if (ancestor_results.forall(_.ok) && !progress.stopped) {
wenzelm@64265
   629
                  val numa_node = numa_nodes.next(used_node(_))
wenzelm@50366
   630
                  progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
wenzelm@51220
   631
                  val job =
wenzelm@62637
   632
                    new Job(progress, name, info, selected_tree, store, do_output, verbose,
wenzelm@64265
   633
                      numa_node, deps(name).session_graph, queue.command_timings(name))
wenzelm@62628
   634
                  loop(pending, running + (name -> (ancestor_heaps, job)), results)
wenzelm@48547
   635
                }
wenzelm@48547
   636
                else {
wenzelm@50366
   637
                  progress.echo(name + " CANCELLED")
lars@63082
   638
                  loop(pending - name, running, results + (name -> Result(false, heap_stamp, None, info)))
wenzelm@48547
   639
                }
wenzelm@48547
   640
              case None => sleep(); loop(pending, running, results)
wenzelm@48425
   641
            }
wenzelm@50367
   642
            ///}}}
wenzelm@48425
   643
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   644
        }
wenzelm@51253
   645
      }
wenzelm@48425
   646
    }
wenzelm@48425
   647
wenzelm@51220
   648
wenzelm@51220
   649
    /* build results */
wenzelm@51220
   650
wenzelm@62641
   651
    val results0 =
wenzelm@48583
   652
      if (deps.is_empty) {
wenzelm@56782
   653
        progress.echo(Output.warning_text("Nothing to build"))
wenzelm@50707
   654
        Map.empty[String, Result]
wenzelm@48583
   655
      }
wenzelm@48583
   656
      else loop(queue, Map.empty, Map.empty)
wenzelm@48583
   657
wenzelm@62641
   658
    val results =
wenzelm@64265
   659
      new Results(
wenzelm@64265
   660
        (for ((name, result) <- results0.iterator)
wenzelm@64265
   661
          yield (name, (result.process, result.info))).toMap)
wenzelm@62641
   662
wenzelm@62641
   663
    if (results.rc != 0 && (verbose || !no_build)) {
wenzelm@62641
   664
      val unfinished =
wenzelm@62641
   665
        (for {
wenzelm@62641
   666
          name <- results.sessions.iterator
wenzelm@62641
   667
          if !results(name).ok
wenzelm@62641
   668
         } yield name).toList.sorted
wenzelm@62641
   669
      progress.echo("Unfinished session(s): " + commas(unfinished))
wenzelm@62641
   670
    }
wenzelm@62641
   671
wenzelm@51418
   672
wenzelm@51418
   673
    /* global browser info */
wenzelm@51418
   674
wenzelm@51418
   675
    if (!no_build) {
wenzelm@51418
   676
      val browser_chapters =
wenzelm@51418
   677
        (for {
wenzelm@62641
   678
          (name, result) <- results0.iterator
wenzelm@62944
   679
          if result.ok
wenzelm@51418
   680
          info = full_tree(name)
wenzelm@51418
   681
          if info.options.bool("browser_info")
wenzelm@51418
   682
        } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
wenzelm@51418
   683
            map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
wenzelm@51418
   684
wenzelm@51418
   685
      for ((chapter, entries) <- browser_chapters)
wenzelm@62632
   686
        Present.update_chapter_index(store.browser_info, chapter, entries)
wenzelm@51418
   687
wenzelm@62632
   688
      if (browser_chapters.nonEmpty) Present.make_global_index(store.browser_info)
wenzelm@51418
   689
    }
wenzelm@51418
   690
wenzelm@62641
   691
    results
wenzelm@48341
   692
  }
wenzelm@48341
   693
wenzelm@48341
   694
wenzelm@62833
   695
  /* Isabelle tool wrapper */
wenzelm@48341
   696
wenzelm@62833
   697
  val isabelle_tool = Isabelle_Tool("build", "build and manage Isabelle sessions", args =>
wenzelm@48341
   698
  {
wenzelm@62833
   699
    val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
wenzelm@62590
   700
wenzelm@62833
   701
    var select_dirs: List[Path] = Nil
wenzelm@64265
   702
    var numa_shuffling = false
wenzelm@62833
   703
    var requirements = false
wenzelm@62833
   704
    var exclude_session_groups: List[String] = Nil
wenzelm@62833
   705
    var all_sessions = false
wenzelm@62833
   706
    var build_heap = false
wenzelm@62833
   707
    var clean_build = false
wenzelm@62833
   708
    var dirs: List[Path] = Nil
wenzelm@62833
   709
    var session_groups: List[String] = Nil
wenzelm@62833
   710
    var max_jobs = 1
wenzelm@62833
   711
    var check_keywords: Set[String] = Set.empty
wenzelm@62833
   712
    var list_files = false
wenzelm@62833
   713
    var no_build = false
wenzelm@62833
   714
    var options = (Options.init() /: build_options)(_ + _)
wenzelm@62833
   715
    var system_mode = false
wenzelm@62833
   716
    var verbose = false
wenzelm@62833
   717
    var exclude_sessions: List[String] = Nil
wenzelm@62590
   718
wenzelm@62833
   719
    val getopts = Getopts("""
wenzelm@62590
   720
Usage: isabelle build [OPTIONS] [SESSIONS ...]
wenzelm@62590
   721
wenzelm@62590
   722
  Options are:
wenzelm@62590
   723
    -D DIR       include session directory and select its sessions
wenzelm@64265
   724
    -N           cyclic shuffling of NUMA CPU nodes (performance tuning)
wenzelm@62590
   725
    -R           operate on requirements of selected sessions
wenzelm@62590
   726
    -X NAME      exclude sessions from group NAME and all descendants
wenzelm@62590
   727
    -a           select all sessions
wenzelm@62590
   728
    -b           build heap images
wenzelm@62590
   729
    -c           clean build
wenzelm@62590
   730
    -d DIR       include session directory
wenzelm@62590
   731
    -g NAME      select session group NAME
wenzelm@62590
   732
    -j INT       maximum number of parallel jobs (default 1)
wenzelm@62590
   733
    -k KEYWORD   check theory sources for conflicts with proposed keywords
wenzelm@62590
   734
    -l           list session source files
wenzelm@62590
   735
    -n           no build -- test dependencies only
wenzelm@62590
   736
    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
wenzelm@62590
   737
    -s           system build mode: produce output in ISABELLE_HOME
wenzelm@62590
   738
    -v           verbose
wenzelm@62590
   739
    -x NAME      exclude session NAME and all descendants
wenzelm@62590
   740
wenzelm@62596
   741
  Build and manage Isabelle sessions, depending on implicit settings:
wenzelm@62596
   742
wenzelm@64455
   743
""" + Library.prefix_lines("  ", Build_Log.Settings.show()) + "\n",
wenzelm@62833
   744
      "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
wenzelm@64265
   745
      "N" -> (_ => numa_shuffling = true),
wenzelm@62833
   746
      "R" -> (_ => requirements = true),
wenzelm@62833
   747
      "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
wenzelm@62833
   748
      "a" -> (_ => all_sessions = true),
wenzelm@62833
   749
      "b" -> (_ => build_heap = true),
wenzelm@62833
   750
      "c" -> (_ => clean_build = true),
wenzelm@62833
   751
      "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
wenzelm@62833
   752
      "g:" -> (arg => session_groups = session_groups ::: List(arg)),
wenzelm@63805
   753
      "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
wenzelm@62833
   754
      "k:" -> (arg => check_keywords = check_keywords + arg),
wenzelm@62833
   755
      "l" -> (_ => list_files = true),
wenzelm@62833
   756
      "n" -> (_ => no_build = true),
wenzelm@62833
   757
      "o:" -> (arg => options = options + arg),
wenzelm@62833
   758
      "s" -> (_ => system_mode = true),
wenzelm@62833
   759
      "v" -> (_ => verbose = true),
wenzelm@62833
   760
      "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
wenzelm@62590
   761
wenzelm@62833
   762
    val sessions = getopts(args)
wenzelm@62590
   763
wenzelm@64115
   764
    val progress = new Console_Progress(verbose = verbose)
wenzelm@62590
   765
wenzelm@64140
   766
    val start_date = Date.now()
wenzelm@64140
   767
wenzelm@62833
   768
    if (verbose) {
wenzelm@62833
   769
      progress.echo(
wenzelm@64155
   770
        "Started at " + Build_Log.print_date(start_date) +
wenzelm@64140
   771
          " (" + Isabelle_System.getenv("ML_IDENTIFIER") + " on " + Isabelle_System.hostname() +")")
wenzelm@64081
   772
      progress.echo(Build_Log.Settings.show() + "\n")
wenzelm@62833
   773
    }
wenzelm@62590
   774
wenzelm@62833
   775
    val results =
wenzelm@62833
   776
      progress.interrupt_handler {
wenzelm@63224
   777
        build(options, progress,
wenzelm@63224
   778
          build_heap = build_heap,
wenzelm@63224
   779
          clean_build = clean_build,
wenzelm@63224
   780
          dirs = dirs,
wenzelm@63224
   781
          select_dirs = select_dirs,
wenzelm@64265
   782
          numa_shuffling = NUMA.enabled_warning(numa_shuffling),
wenzelm@63224
   783
          max_jobs = max_jobs,
wenzelm@63224
   784
          list_files = list_files,
wenzelm@63224
   785
          check_keywords = check_keywords,
wenzelm@63224
   786
          no_build = no_build,
wenzelm@63224
   787
          system_mode = system_mode,
wenzelm@63224
   788
          verbose = verbose,
wenzelm@63224
   789
          requirements = requirements,
wenzelm@63224
   790
          all_sessions = all_sessions,
wenzelm@63224
   791
          exclude_session_groups = exclude_session_groups,
wenzelm@63224
   792
          exclude_sessions = exclude_sessions,
wenzelm@63224
   793
          session_groups = session_groups,
wenzelm@63224
   794
          sessions = sessions)
wenzelm@62833
   795
      }
wenzelm@64140
   796
    val end_date = Date.now()
wenzelm@64140
   797
    val elapsed_time = end_date.time - start_date.time
wenzelm@62590
   798
wenzelm@62833
   799
    if (verbose) {
wenzelm@64155
   800
      progress.echo("\nFinished at " + Build_Log.print_date(end_date))
wenzelm@62833
   801
    }
wenzelm@62590
   802
wenzelm@62833
   803
    val total_timing =
wenzelm@62833
   804
      (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
wenzelm@62833
   805
        copy(elapsed = elapsed_time)
wenzelm@62833
   806
    progress.echo(total_timing.message_resources)
wenzelm@62590
   807
wenzelm@62833
   808
    sys.exit(results.rc)
wenzelm@62833
   809
  })
wenzelm@59366
   810
wenzelm@59366
   811
wenzelm@59366
   812
  /* PIDE protocol */
wenzelm@59366
   813
wenzelm@59366
   814
  def build_theories(
wenzelm@59369
   815
    session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
wenzelm@59367
   816
      session.get_protocol_handler(classOf[Handler].getName) match {
wenzelm@59366
   817
        case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
wenzelm@59366
   818
        case _ => error("Cannot invoke build_theories: bad protocol handler")
wenzelm@59366
   819
      }
wenzelm@59366
   820
wenzelm@59367
   821
  class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
wenzelm@59366
   822
  {
wenzelm@59369
   823
    private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
wenzelm@59366
   824
wenzelm@59366
   825
    def build_theories(
wenzelm@59369
   826
      session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
wenzelm@59366
   827
    {
wenzelm@59369
   828
      val promise = Future.promise[XML.Body]
wenzelm@59366
   829
      val id = Document_ID.make().toString
wenzelm@59366
   830
      pending.change(promises => promises + (id -> promise))
wenzelm@59366
   831
      session.build_theories(id, master_dir, theories)
wenzelm@59366
   832
      promise
wenzelm@59366
   833
    }
wenzelm@59366
   834
wenzelm@59367
   835
    private def loading_theory(prover: Prover, msg: Prover.Protocol_Output): Boolean =
wenzelm@59367
   836
      msg.properties match {
wenzelm@59367
   837
        case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
wenzelm@59367
   838
        case _ => false
wenzelm@59367
   839
      }
wenzelm@59367
   840
wenzelm@59366
   841
    private def build_theories_result(prover: Prover, msg: Prover.Protocol_Output): Boolean =
wenzelm@59366
   842
      msg.properties match {
wenzelm@59369
   843
        case Markup.Build_Theories_Result(id) =>
wenzelm@59366
   844
          pending.change_result(promises =>
wenzelm@59366
   845
            promises.get(id) match {
wenzelm@59369
   846
              case Some(promise) =>
wenzelm@59369
   847
                val error_message =
wenzelm@59369
   848
                  try { YXML.parse_body(Symbol.decode(msg.text)) }
wenzelm@59369
   849
                  catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
wenzelm@59369
   850
                promise.fulfill(error_message)
wenzelm@59369
   851
                (true, promises - id)
wenzelm@59369
   852
              case None =>
wenzelm@59369
   853
                (false, promises)
wenzelm@59366
   854
            })
wenzelm@59366
   855
        case _ => false
wenzelm@59366
   856
      }
wenzelm@59366
   857
wenzelm@59366
   858
    override def stop(prover: Prover): Unit =
wenzelm@59366
   859
      pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
wenzelm@59366
   860
wenzelm@59367
   861
    val functions =
wenzelm@59367
   862
      Map(
wenzelm@59367
   863
        Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
wenzelm@59367
   864
        Markup.LOADING_THEORY -> loading_theory _)
wenzelm@59366
   865
  }
wenzelm@48276
   866
}