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