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