src/Pure/Tools/build.scala
author wenzelm
Tue Mar 15 22:01:26 2016 +0100 (2016-03-15)
changeset 62631 c39614ddb80b
parent 62630 bc772694cfbd
child 62632 cd991ba01ffd
permissions -rw-r--r--
clarified modules;
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@62631
   212
    val (_, tree) = Sessions.find(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@52114
   231
  private class Job(progress: Progress,
wenzelm@62631
   232
    name: String, val info: Sessions.Info, output: Path, do_output: Boolean, verbose: Boolean,
wenzelm@59445
   233
    browser_info: Path, session_graph: Graph_Display.Graph, command_timings: List[Properties.T])
wenzelm@48418
   234
  {
wenzelm@48674
   235
    def output_path: Option[Path] = if (do_output) Some(output) else None
wenzelm@62630
   236
    def output_save_state: String =
wenzelm@62630
   237
      if (do_output)
wenzelm@62630
   238
        "PolyML.SaveState.saveState " + ML_Syntax.print_string_raw(File.platform_path(output))
wenzelm@62630
   239
      else ""
wenzelm@48674
   240
wenzelm@48674
   241
    private val parent = info.parent.getOrElse("")
wenzelm@48418
   242
wenzelm@59445
   243
    private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
wenzelm@59445
   244
    try { isabelle.graphview.Graph_File.write(info.options, graph_file, session_graph) }
wenzelm@59445
   245
    catch { case ERROR(_) => /*error should be exposed in ML*/ }
wenzelm@59445
   246
wenzelm@62573
   247
    output.file.delete
wenzelm@62573
   248
wenzelm@62610
   249
    private val env =
wenzelm@62610
   250
      Isabelle_System.settings() +
wenzelm@62610
   251
        ("ISABELLE_ML_DEBUGGER" -> info.options.bool("ML_debugger").toString)
wenzelm@48698
   252
wenzelm@62573
   253
    private val future_result: Future[Process_Result] =
wenzelm@61559
   254
      Future.thread("build") {
wenzelm@62573
   255
        val process =
wenzelm@62631
   256
          if (Sessions.is_pure(name)) {
wenzelm@62573
   257
            val eval =
wenzelm@62573
   258
              "Command_Line.tool0 (fn () => (Session.finish (); Options.reset_default ();" +
wenzelm@62630
   259
              " Session.shutdown (); ML_Heap.share_common_data (); " + output_save_state + "));"
wenzelm@62573
   260
            ML_Process(info.options, "RAW_ML_SYSTEM", List("--use", "ROOT.ML", "--eval", eval),
wenzelm@62599
   261
              cwd = info.dir.file, env = env)
wenzelm@62573
   262
          }
wenzelm@62573
   263
          else {
wenzelm@62603
   264
            val args_file = Isabelle_System.tmp_file("build")
wenzelm@62603
   265
            File.write(args_file, YXML.string_of_body(
wenzelm@62599
   266
                {
wenzelm@62599
   267
                  val theories = info.theories.map(x => (x._2, x._3))
wenzelm@62599
   268
                  import XML.Encode._
wenzelm@62630
   269
                  pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
wenzelm@62599
   270
                    pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
wenzelm@62599
   271
                    pair(string, pair(string, pair(string,
wenzelm@62599
   272
                    list(pair(Options.encode, list(Path.encode)))))))))))))(
wenzelm@62630
   273
                  (Symbol.codes, (command_timings, (do_output, (verbose,
wenzelm@62599
   274
                    (browser_info, (info.document_files, (File.standard_path(graph_file),
wenzelm@62599
   275
                    (parent, (info.chapter, (name,
wenzelm@62599
   276
                    theories)))))))))))
wenzelm@62599
   277
                }))
wenzelm@62630
   278
            val eval =
wenzelm@62630
   279
              "Command_Line.tool0 (fn () => (" +
wenzelm@62630
   280
              "Build.build " + ML_Syntax.print_string_raw(File.standard_path(args_file)) +
wenzelm@62630
   281
              (if (do_output) "; ML_Heap.share_common_data (); " + output_save_state
wenzelm@62630
   282
               else "") + "));"
wenzelm@62630
   283
            ML_Process(info.options, parent, List("--eval", eval),
wenzelm@62610
   284
              cwd = info.dir.file, env = env, cleanup = () => args_file.delete)
wenzelm@62573
   285
          }
wenzelm@62573
   286
        process.result(
wenzelm@51962
   287
          progress_stdout = (line: String) =>
wenzelm@50847
   288
            Library.try_unprefix("\floading_theory = ", line) match {
wenzelm@50847
   289
              case Some(theory) => progress.theory(name, theory)
wenzelm@50847
   290
              case None =>
wenzelm@51962
   291
            },
wenzelm@51962
   292
          progress_limit =
wenzelm@51962
   293
            info.options.int("process_output_limit") match {
wenzelm@51962
   294
              case 0 => None
wenzelm@51962
   295
              case m => Some(m * 1000000L)
wenzelm@56871
   296
            },
wenzelm@56871
   297
          strict = false)
wenzelm@50845
   298
      }
wenzelm@48674
   299
wenzelm@62572
   300
    def terminate: Unit = future_result.cancel
wenzelm@62572
   301
    def is_finished: Boolean = future_result.is_finished
wenzelm@48674
   302
wenzelm@62569
   303
    @volatile private var was_timeout = false
wenzelm@56779
   304
    private val timeout_request: Option[Event_Timer.Request] =
wenzelm@56779
   305
    {
wenzelm@62569
   306
      if (info.timeout > Time.zero)
wenzelm@62569
   307
        Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
wenzelm@48674
   308
      else None
wenzelm@56779
   309
    }
wenzelm@48674
   310
wenzelm@62400
   311
    def join: Process_Result =
wenzelm@50845
   312
    {
wenzelm@62572
   313
      val result = future_result.join
wenzelm@50845
   314
wenzelm@62631
   315
      if (result.ok && !Sessions.is_pure(name))
wenzelm@61372
   316
        Present.finish(progress, browser_info, graph_file, info, name)
wenzelm@61372
   317
wenzelm@59445
   318
      graph_file.delete
wenzelm@56779
   319
      timeout_request.foreach(_.cancel)
wenzelm@48674
   320
wenzelm@62572
   321
      if (result.interrupted) {
wenzelm@62572
   322
        if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
wenzelm@62572
   323
        else result.error(Output.error_text("Interrupt"))
wenzelm@52063
   324
      }
wenzelm@62572
   325
      else result
wenzelm@48674
   326
    }
wenzelm@48364
   327
  }
wenzelm@48364
   328
wenzelm@48424
   329
wenzelm@51045
   330
  /* inlined properties (YXML) */
wenzelm@50946
   331
wenzelm@50946
   332
  object Props
wenzelm@50946
   333
  {
wenzelm@51045
   334
    def parse(text: String): Properties.T = XML.Decode.properties(YXML.parse_body(text))
wenzelm@50946
   335
wenzelm@50946
   336
    def parse_lines(prefix: String, lines: List[String]): List[Properties.T] =
wenzelm@50946
   337
      for (line <- lines; s <- Library.try_unprefix(prefix, line)) yield parse(s)
wenzelm@50946
   338
wenzelm@50946
   339
    def find_parse_line(prefix: String, lines: List[String]): Option[Properties.T] =
wenzelm@50946
   340
      lines.find(_.startsWith(prefix)).map(line => parse(line.substring(prefix.length)))
wenzelm@50946
   341
  }
wenzelm@50946
   342
wenzelm@50946
   343
wenzelm@50777
   344
  /* log files */
wenzelm@48504
   345
wenzelm@62628
   346
  private def log(name: String): Path = Path.basic("log") + Path.basic(name)
wenzelm@48505
   347
  private def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@48504
   348
wenzelm@50982
   349
  private val SESSION_NAME = "\fSession.name = "
wenzelm@50707
   350
wenzelm@50946
   351
wenzelm@50975
   352
  sealed case class Log_Info(
wenzelm@51220
   353
    name: String,
wenzelm@51220
   354
    stats: List[Properties.T],
wenzelm@51220
   355
    tasks: List[Properties.T],
wenzelm@51220
   356
    command_timings: List[Properties.T],
wenzelm@51220
   357
    session_timing: Properties.T)
wenzelm@50777
   358
wenzelm@51220
   359
  def parse_log(full_stats: Boolean, text: String): Log_Info =
wenzelm@50777
   360
  {
wenzelm@50777
   361
    val lines = split_lines(text)
wenzelm@51223
   362
    val xml_cache = new XML.Cache()
wenzelm@51223
   363
    def parse_lines(prfx: String): List[Properties.T] =
wenzelm@51663
   364
      Props.parse_lines(prfx, lines).map(xml_cache.props(_))
wenzelm@51223
   365
wenzelm@50982
   366
    val name =
wenzelm@50982
   367
      lines.find(_.startsWith(SESSION_NAME)).map(_.substring(SESSION_NAME.length)) getOrElse ""
wenzelm@51223
   368
    val stats = if (full_stats) parse_lines("\fML_statistics = ") else Nil
wenzelm@51223
   369
    val tasks = if (full_stats) parse_lines("\ftask_statistics = ") else Nil
wenzelm@51223
   370
    val command_timings = parse_lines("\fcommand_timing = ")
wenzelm@51220
   371
    val session_timing = Props.find_parse_line("\fTiming = ", lines) getOrElse Nil
wenzelm@51220
   372
    Log_Info(name, stats, tasks, command_timings, session_timing)
wenzelm@50777
   373
  }
wenzelm@50777
   374
wenzelm@50777
   375
wenzelm@50777
   376
  /* sources and heaps */
wenzelm@50777
   377
wenzelm@62628
   378
  private val SOURCES = "sources: "
wenzelm@62628
   379
  private val INPUT_HEAP = "input_heap: "
wenzelm@62628
   380
  private val OUTPUT_HEAP = "output_heap: "
wenzelm@62628
   381
  private val LOG_START = "log:"
wenzelm@62628
   382
  private val line_prefixes = List(SOURCES, INPUT_HEAP, OUTPUT_HEAP, LOG_START)
wenzelm@48504
   383
wenzelm@62628
   384
  private def sources_stamp(digests: List[SHA1.Digest]): String =
wenzelm@62628
   385
    digests.map(_.toString).sorted.mkString(SOURCES, " ", "")
wenzelm@48639
   386
wenzelm@62628
   387
  private def time_stamp(path: Path): Option[String] =
wenzelm@48504
   388
  {
wenzelm@62628
   389
    val file = path.file
wenzelm@62628
   390
    if (file.isFile) Some(file.length.toString + " " + file.lastModified.toString)
wenzelm@62628
   391
    else None
wenzelm@48504
   392
  }
wenzelm@48504
   393
wenzelm@62628
   394
  private def read_stamps(path: Path): Option[(String, List[String], List[String])] =
wenzelm@48639
   395
    if (path.is_file) {
wenzelm@62628
   396
      val stream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(path.file)))
wenzelm@50203
   397
      val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
wenzelm@62628
   398
      val lines =
wenzelm@62628
   399
      {
wenzelm@62628
   400
        val lines = new mutable.ListBuffer[String]
wenzelm@62628
   401
        try {
wenzelm@62628
   402
          var finished = false
wenzelm@62628
   403
          while (!finished) {
wenzelm@62628
   404
            val line = reader.readLine
wenzelm@62628
   405
            if (line != null && line_prefixes.exists(line.startsWith(_)))
wenzelm@62628
   406
              lines += line
wenzelm@62628
   407
            else finished = true
wenzelm@62628
   408
          }
wenzelm@62628
   409
        }
wenzelm@48639
   410
        finally { reader.close }
wenzelm@62628
   411
        lines.toList
wenzelm@62628
   412
      }
wenzelm@62628
   413
wenzelm@62628
   414
      if (!lines.isEmpty && lines.last.startsWith(LOG_START)) {
wenzelm@62628
   415
        lines.find(_.startsWith(SOURCES)).map(s =>
wenzelm@62628
   416
          (s, lines.filter(_.startsWith(INPUT_HEAP)), lines.filter(_.startsWith(OUTPUT_HEAP))))
wenzelm@62628
   417
      }
wenzelm@48504
   418
      else None
wenzelm@48504
   419
    }
wenzelm@48504
   420
    else None
wenzelm@48504
   421
wenzelm@48504
   422
wenzelm@62631
   423
wenzelm@62631
   424
  /** build_results **/
wenzelm@48424
   425
wenzelm@62403
   426
  class Build_Results private [Build](results: Map[String, Option[Process_Result]])
wenzelm@62403
   427
  {
wenzelm@62403
   428
    def sessions: Set[String] = results.keySet
wenzelm@62403
   429
    def cancelled(name: String): Boolean = results(name).isEmpty
wenzelm@62406
   430
    def apply(name: String): Process_Result = results(name).getOrElse(Process_Result(1))
wenzelm@62403
   431
    val rc = (0 /: results.iterator.map({ case (_, Some(r)) => r.rc case (_, None) => 1 }))(_ max _)
wenzelm@62406
   432
wenzelm@62406
   433
    override def toString: String = rc.toString
wenzelm@62403
   434
  }
wenzelm@62403
   435
wenzelm@52114
   436
  def build_results(
wenzelm@50404
   437
    options: Options,
wenzelm@52115
   438
    progress: Progress = Ignore_Progress,
wenzelm@49131
   439
    requirements: Boolean = false,
wenzelm@48509
   440
    all_sessions: Boolean = false,
wenzelm@48511
   441
    build_heap: Boolean = false,
wenzelm@48595
   442
    clean_build: Boolean = false,
wenzelm@56890
   443
    dirs: List[Path] = Nil,
wenzelm@56890
   444
    select_dirs: List[Path] = Nil,
wenzelm@60106
   445
    exclude_session_groups: List[String] = Nil,
wenzelm@48509
   446
    session_groups: List[String] = Nil,
wenzelm@48509
   447
    max_jobs: Int = 1,
wenzelm@48903
   448
    list_files: Boolean = false,
wenzelm@59891
   449
    check_keywords: Set[String] = Set.empty,
wenzelm@48509
   450
    no_build: Boolean = false,
wenzelm@48509
   451
    system_mode: Boolean = false,
wenzelm@48509
   452
    verbose: Boolean = false,
wenzelm@59892
   453
    exclude_sessions: List[String] = Nil,
wenzelm@62403
   454
    sessions: List[String] = Nil): Build_Results =
wenzelm@48341
   455
  {
wenzelm@51220
   456
    /* session tree and dependencies */
wenzelm@51220
   457
wenzelm@62631
   458
    val full_tree = Sessions.find(options.int("completion_limit") = 0, dirs, select_dirs)
wenzelm@49131
   459
    val (selected, selected_tree) =
wenzelm@60106
   460
      full_tree.selection(requirements, all_sessions,
wenzelm@60106
   461
        exclude_session_groups, exclude_sessions, session_groups, sessions)
wenzelm@49131
   462
wenzelm@59891
   463
    val deps = dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
wenzelm@48368
   464
wenzelm@62628
   465
    def session_sources_stamp(name: String): String =
wenzelm@62631
   466
      sources_stamp(selected_tree(name).meta_digest :: deps.sources(name))
wenzelm@48504
   467
wenzelm@51220
   468
wenzelm@51220
   469
    /* persistent information */
wenzelm@51220
   470
wenzelm@48504
   471
    val (input_dirs, output_dir, browser_info) =
wenzelm@48504
   472
      if (system_mode) {
wenzelm@48504
   473
        val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@48504
   474
        (List(output_dir), output_dir, Path.explode("~~/browser_info"))
wenzelm@48504
   475
      }
wenzelm@48504
   476
      else {
wenzelm@48504
   477
        val output_dir = Path.explode("$ISABELLE_OUTPUT")
wenzelm@48504
   478
        (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
wenzelm@48504
   479
         Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48504
   480
      }
wenzelm@48363
   481
wenzelm@51221
   482
    def find_log(name: String): Option[(Path, Path)] =
wenzelm@51221
   483
      input_dirs.find(dir => (dir + log(name)).is_file).map(dir => (dir, dir + log(name)))
wenzelm@51220
   484
wenzelm@51220
   485
wenzelm@51220
   486
    /* queue with scheduling information */
wenzelm@51220
   487
wenzelm@51230
   488
    def load_timings(name: String): (List[Properties.T], Double) =
wenzelm@51221
   489
    {
wenzelm@51221
   490
      val (path, text) =
wenzelm@51221
   491
        find_log(name + ".gz") match {
wenzelm@51221
   492
          case Some((_, path)) => (path, File.read_gzip(path))
wenzelm@51221
   493
          case None =>
wenzelm@51221
   494
            find_log(name) match {
wenzelm@51221
   495
              case Some((_, path)) => (path, File.read(path))
wenzelm@51221
   496
              case None => (Path.current, "")
wenzelm@51221
   497
            }
wenzelm@51221
   498
        }
wenzelm@51244
   499
wenzelm@51244
   500
      def ignore_error(msg: String): (List[Properties.T], Double) =
wenzelm@51244
   501
      {
wenzelm@56782
   502
        Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
wenzelm@51244
   503
        (Nil, 0.0)
wenzelm@51244
   504
      }
wenzelm@51244
   505
wenzelm@51221
   506
      try {
wenzelm@51221
   507
        val info = parse_log(false, text)
wenzelm@51221
   508
        val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
wenzelm@51221
   509
        (info.command_timings, session_timing)
wenzelm@51220
   510
      }
wenzelm@51221
   511
      catch {
wenzelm@51244
   512
        case ERROR(msg) => ignore_error(msg)
wenzelm@51986
   513
        case exn: java.lang.Error => ignore_error(Exn.message(exn))
wenzelm@51987
   514
        case _: XML.Error => ignore_error("")
wenzelm@51221
   515
      }
wenzelm@51221
   516
    }
wenzelm@51220
   517
wenzelm@51230
   518
    val queue = Queue(selected_tree, load_timings)
wenzelm@51220
   519
wenzelm@51220
   520
wenzelm@51220
   521
    /* main build process */
wenzelm@51220
   522
wenzelm@48373
   523
    // prepare log dir
wenzelm@62628
   524
    Isabelle_System.mkdirs(output_dir + Path.basic("log"))
wenzelm@48373
   525
wenzelm@48595
   526
    // optional cleanup
wenzelm@48595
   527
    if (clean_build) {
wenzelm@49131
   528
      for (name <- full_tree.graph.all_succs(selected)) {
wenzelm@48595
   529
        val files =
wenzelm@48595
   530
          List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
wenzelm@59319
   531
        if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
wenzelm@50366
   532
        if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
wenzelm@48595
   533
      }
wenzelm@48595
   534
    }
wenzelm@48595
   535
wenzelm@48425
   536
    // scheduler loop
wenzelm@62628
   537
    case class Result(current: Boolean, heaps: List[String], process: Option[Process_Result])
wenzelm@62402
   538
    {
wenzelm@62402
   539
      def ok: Boolean =
wenzelm@62402
   540
        process match {
wenzelm@62402
   541
          case None => false
wenzelm@62402
   542
          case Some(res) => res.rc == 0
wenzelm@62402
   543
        }
wenzelm@62402
   544
    }
wenzelm@48639
   545
wenzelm@56837
   546
    def sleep()
wenzelm@56837
   547
    {
wenzelm@56837
   548
      try { Thread.sleep(500) }
wenzelm@56861
   549
      catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
wenzelm@56837
   550
    }
wenzelm@50366
   551
wenzelm@48425
   552
    @tailrec def loop(
wenzelm@48676
   553
      pending: Queue,
wenzelm@62628
   554
      running: Map[String, (List[String], Job)],
wenzelm@48639
   555
      results: Map[String, Result]): Map[String, Result] =
wenzelm@48425
   556
    {
wenzelm@48425
   557
      if (pending.is_empty) results
wenzelm@51253
   558
      else {
wenzelm@51253
   559
        if (progress.stopped)
wenzelm@51253
   560
          for ((_, (_, job)) <- running) job.terminate
wenzelm@51253
   561
wenzelm@48674
   562
        running.find({ case (_, (_, job)) => job.is_finished }) match {
wenzelm@62628
   563
          case Some((name, (input_heaps, job))) =>
wenzelm@50367
   564
            //{{{ finish job
wenzelm@48424
   565
wenzelm@62401
   566
            val process_result = job.join
wenzelm@62573
   567
            process_result.err_lines.foreach(progress.echo(_))
wenzelm@62573
   568
            if (process_result.ok)
wenzelm@62573
   569
              progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
wenzelm@48373
   570
wenzelm@62404
   571
            val process_result_tail =
wenzelm@62404
   572
            {
wenzelm@62404
   573
              val lines = process_result.out_lines.filterNot(_.startsWith("\f"))
wenzelm@62409
   574
              val tail = job.info.options.int("process_output_tail")
wenzelm@62409
   575
              val lines1 = if (tail == 0) lines else lines.drop(lines.length - tail max 0)
wenzelm@62404
   576
              process_result.copy(out_lines =
wenzelm@62409
   577
                "(see also " + (output_dir + log(name)).file.toString + ")" :: lines1)
wenzelm@62404
   578
            }
wenzelm@62404
   579
wenzelm@62628
   580
            val heaps =
wenzelm@62401
   581
              if (process_result.ok) {
wenzelm@48639
   582
                (output_dir + log(name)).file.delete
wenzelm@62628
   583
                val heaps =
wenzelm@62628
   584
                  (for (path <- job.output_path; stamp <- time_stamp(path))
wenzelm@62628
   585
                    yield stamp).toList
wenzelm@48639
   586
wenzelm@48639
   587
                File.write_gzip(output_dir + log_gz(name),
wenzelm@62628
   588
                  Library.terminate_lines(
wenzelm@62628
   589
                    session_sources_stamp(name) ::
wenzelm@62628
   590
                    input_heaps.map(INPUT_HEAP + _) :::
wenzelm@62628
   591
                    heaps.map(OUTPUT_HEAP + _) :::
wenzelm@62628
   592
                    List(LOG_START) ::: process_result.out_lines))
wenzelm@48639
   593
wenzelm@62628
   594
                heaps
wenzelm@48639
   595
              }
wenzelm@48639
   596
              else {
wenzelm@48639
   597
                (output_dir + Path.basic(name)).file.delete
wenzelm@48639
   598
                (output_dir + log_gz(name)).file.delete
wenzelm@48639
   599
wenzelm@62401
   600
                File.write(output_dir + log(name), Library.terminate_lines(process_result.out_lines))
wenzelm@50366
   601
                progress.echo(name + " FAILED")
wenzelm@62404
   602
                if (!process_result.interrupted) progress.echo(process_result_tail.out)
wenzelm@48639
   603
wenzelm@62628
   604
                Nil
wenzelm@48639
   605
              }
wenzelm@50707
   606
            loop(pending - name, running - name,
wenzelm@62628
   607
              results + (name -> Result(false, heaps, Some(process_result_tail))))
wenzelm@50367
   608
            //}}}
wenzelm@60215
   609
          case None if running.size < (max_jobs max 1) =>
wenzelm@50367
   610
            //{{{ check/start next job
wenzelm@48547
   611
            pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48547
   612
              case Some((name, info)) =>
wenzelm@62628
   613
                val ancestor_results = selected_tree.ancestors(name).map(results(_))
wenzelm@62628
   614
                val ancestor_heaps = ancestor_results.map(_.heaps).flatten
wenzelm@62628
   615
wenzelm@48547
   616
                val output = output_dir + Path.basic(name)
wenzelm@62631
   617
                val do_output = build_heap || Sessions.is_pure(name) || queue.is_inner(name)
wenzelm@48547
   618
wenzelm@62628
   619
                val (current, heaps) =
wenzelm@48547
   620
                {
wenzelm@51221
   621
                  find_log(name + ".gz") match {
wenzelm@51221
   622
                    case Some((dir, path)) =>
wenzelm@51220
   623
                      read_stamps(path) match {
wenzelm@62628
   624
                        case Some((sources, input_heaps, output_heaps)) =>
wenzelm@62628
   625
                          val heaps = time_stamp(dir + Path.basic(name)).toList
wenzelm@62628
   626
                          val current =
wenzelm@62628
   627
                            sources == session_sources_stamp(name) &&
wenzelm@62628
   628
                            input_heaps == ancestor_heaps.map(INPUT_HEAP + _) &&
wenzelm@62628
   629
                            output_heaps == heaps.map(OUTPUT_HEAP + _) &&
wenzelm@62628
   630
                            !(do_output && heaps.isEmpty)
wenzelm@62628
   631
                          (current, heaps)
wenzelm@62628
   632
                        case None => (false, Nil)
wenzelm@48547
   633
                      }
wenzelm@62628
   634
                    case None => (false, Nil)
wenzelm@48504
   635
                  }
wenzelm@48547
   636
                }
wenzelm@62628
   637
                val all_current = current && ancestor_results.forall(_.current)
wenzelm@48528
   638
wenzelm@48547
   639
                if (all_current)
wenzelm@62402
   640
                  loop(pending - name, running,
wenzelm@62628
   641
                    results + (name -> Result(true, heaps, Some(Process_Result(0)))))
wenzelm@48678
   642
                else if (no_build) {
wenzelm@50366
   643
                  if (verbose) progress.echo("Skipping " + name + " ...")
wenzelm@62402
   644
                  loop(pending - name, running,
wenzelm@62628
   645
                    results + (name -> Result(false, heaps, Some(Process_Result(1)))))
wenzelm@48678
   646
                }
wenzelm@62628
   647
                else if (ancestor_results.forall(_.ok) && !progress.stopped) {
wenzelm@50366
   648
                  progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
wenzelm@51220
   649
                  val job =
wenzelm@51220
   650
                    new Job(progress, name, info, output, do_output, verbose, browser_info,
wenzelm@59445
   651
                      deps(name).session_graph, queue.command_timings(name))
wenzelm@62628
   652
                  loop(pending, running + (name -> (ancestor_heaps, job)), results)
wenzelm@48547
   653
                }
wenzelm@48547
   654
                else {
wenzelm@50366
   655
                  progress.echo(name + " CANCELLED")
wenzelm@62628
   656
                  loop(pending - name, running, results + (name -> Result(false, heaps, None)))
wenzelm@48547
   657
                }
wenzelm@48547
   658
              case None => sleep(); loop(pending, running, results)
wenzelm@48425
   659
            }
wenzelm@50367
   660
            ///}}}
wenzelm@48425
   661
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   662
        }
wenzelm@51253
   663
      }
wenzelm@48425
   664
    }
wenzelm@48425
   665
wenzelm@51220
   666
wenzelm@51220
   667
    /* build results */
wenzelm@51220
   668
wenzelm@48583
   669
    val results =
wenzelm@48583
   670
      if (deps.is_empty) {
wenzelm@56782
   671
        progress.echo(Output.warning_text("Nothing to build"))
wenzelm@50707
   672
        Map.empty[String, Result]
wenzelm@48583
   673
      }
wenzelm@48583
   674
      else loop(queue, Map.empty, Map.empty)
wenzelm@48583
   675
wenzelm@51418
   676
wenzelm@51418
   677
    /* global browser info */
wenzelm@51418
   678
wenzelm@51418
   679
    if (!no_build) {
wenzelm@51418
   680
      val browser_chapters =
wenzelm@51418
   681
        (for {
wenzelm@51418
   682
          (name, result) <- results.iterator
wenzelm@62631
   683
          if result.ok && !Sessions.is_pure(name)
wenzelm@51418
   684
          info = full_tree(name)
wenzelm@51418
   685
          if info.options.bool("browser_info")
wenzelm@51418
   686
        } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
wenzelm@51418
   687
            map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
wenzelm@51418
   688
wenzelm@51418
   689
      for ((chapter, entries) <- browser_chapters)
wenzelm@51418
   690
        Present.update_chapter_index(browser_info, chapter, entries)
wenzelm@51418
   691
wenzelm@61372
   692
      if (browser_chapters.nonEmpty) Present.make_global_index(browser_info)
wenzelm@51418
   693
    }
wenzelm@51418
   694
wenzelm@62403
   695
    new Build_Results((for ((name, result) <- results.iterator) yield (name, result.process)).toMap)
wenzelm@52114
   696
  }
wenzelm@52114
   697
wenzelm@52114
   698
wenzelm@62631
   699
wenzelm@62631
   700
  /** build **/
wenzelm@50707
   701
wenzelm@52114
   702
  def build(
wenzelm@52114
   703
    options: Options,
wenzelm@52115
   704
    progress: Progress = Ignore_Progress,
wenzelm@52114
   705
    requirements: Boolean = false,
wenzelm@52114
   706
    all_sessions: Boolean = false,
wenzelm@52114
   707
    build_heap: Boolean = false,
wenzelm@52114
   708
    clean_build: Boolean = false,
wenzelm@56890
   709
    dirs: List[Path] = Nil,
wenzelm@56890
   710
    select_dirs: List[Path] = Nil,
wenzelm@60106
   711
    exclude_session_groups: List[String] = Nil,
wenzelm@52114
   712
    session_groups: List[String] = Nil,
wenzelm@52114
   713
    max_jobs: Int = 1,
wenzelm@52114
   714
    list_files: Boolean = false,
wenzelm@59891
   715
    check_keywords: Set[String] = Set.empty,
wenzelm@52114
   716
    no_build: Boolean = false,
wenzelm@52114
   717
    system_mode: Boolean = false,
wenzelm@52114
   718
    verbose: Boolean = false,
wenzelm@59892
   719
    exclude_sessions: List[String] = Nil,
wenzelm@52114
   720
    sessions: List[String] = Nil): Int =
wenzelm@52114
   721
  {
wenzelm@52114
   722
    val results =
wenzelm@59892
   723
      build_results(options, progress, requirements, all_sessions, build_heap, clean_build,
wenzelm@60106
   724
        dirs, select_dirs, exclude_session_groups, session_groups, max_jobs, list_files,
wenzelm@60106
   725
        check_keywords, no_build, system_mode, verbose, exclude_sessions, sessions)
wenzelm@52114
   726
wenzelm@62403
   727
    if (results.rc != 0 && (verbose || !no_build)) {
wenzelm@48552
   728
      val unfinished =
wenzelm@62402
   729
        (for {
wenzelm@62403
   730
          name <- results.sessions.iterator
wenzelm@62406
   731
          if !results(name).ok
wenzelm@62402
   732
         } yield name).toList.sorted
wenzelm@50366
   733
      progress.echo("Unfinished session(s): " + commas(unfinished))
wenzelm@48473
   734
    }
wenzelm@62403
   735
wenzelm@62403
   736
    results.rc
wenzelm@48341
   737
  }
wenzelm@48341
   738
wenzelm@48341
   739
wenzelm@48346
   740
  /* command line entry point */
wenzelm@48341
   741
wenzelm@48341
   742
  def main(args: Array[String])
wenzelm@48341
   743
  {
wenzelm@48346
   744
    Command_Line.tool {
wenzelm@62590
   745
      def show_settings(): String =
wenzelm@62590
   746
        cat_lines(List(
wenzelm@62590
   747
          "ISABELLE_BUILD_OPTIONS=" +
wenzelm@62590
   748
            quote(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS")),
wenzelm@62590
   749
          "ISABELLE_BUILD_JAVA_OPTIONS=" +
wenzelm@62596
   750
            quote(Isabelle_System.getenv("ISABELLE_BUILD_JAVA_OPTIONS")),
wenzelm@62590
   751
          "",
wenzelm@62590
   752
          "ML_PLATFORM=" + quote(Isabelle_System.getenv("ML_PLATFORM")),
wenzelm@62590
   753
          "ML_HOME=" + quote(Isabelle_System.getenv("ML_HOME")),
wenzelm@62590
   754
          "ML_SYSTEM=" + quote(Isabelle_System.getenv("ML_SYSTEM")),
wenzelm@62590
   755
          "ML_OPTIONS=" + quote(Isabelle_System.getenv("ML_OPTIONS"))))
wenzelm@62590
   756
wenzelm@62590
   757
      val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
wenzelm@62590
   758
wenzelm@62590
   759
      var select_dirs: List[Path] = Nil
wenzelm@62590
   760
      var requirements = false
wenzelm@62590
   761
      var exclude_session_groups: List[String] = Nil
wenzelm@62590
   762
      var all_sessions = false
wenzelm@62590
   763
      var build_heap = false
wenzelm@62590
   764
      var clean_build = false
wenzelm@62590
   765
      var dirs: List[Path] = Nil
wenzelm@62590
   766
      var session_groups: List[String] = Nil
wenzelm@62590
   767
      var max_jobs = 1
wenzelm@62590
   768
      var check_keywords: Set[String] = Set.empty
wenzelm@62590
   769
      var list_files = false
wenzelm@62590
   770
      var no_build = false
wenzelm@62590
   771
      var options = (Options.init() /: build_options)(_ + _)
wenzelm@62590
   772
      var system_mode = false
wenzelm@62590
   773
      var verbose = false
wenzelm@62590
   774
      var exclude_sessions: List[String] = Nil
wenzelm@62590
   775
wenzelm@62590
   776
      val getopts = Getopts("""
wenzelm@62590
   777
Usage: isabelle build [OPTIONS] [SESSIONS ...]
wenzelm@62590
   778
wenzelm@62590
   779
  Options are:
wenzelm@62590
   780
    -D DIR       include session directory and select its sessions
wenzelm@62590
   781
    -R           operate on requirements of selected sessions
wenzelm@62590
   782
    -X NAME      exclude sessions from group NAME and all descendants
wenzelm@62590
   783
    -a           select all sessions
wenzelm@62590
   784
    -b           build heap images
wenzelm@62590
   785
    -c           clean build
wenzelm@62590
   786
    -d DIR       include session directory
wenzelm@62590
   787
    -g NAME      select session group NAME
wenzelm@62590
   788
    -j INT       maximum number of parallel jobs (default 1)
wenzelm@62590
   789
    -k KEYWORD   check theory sources for conflicts with proposed keywords
wenzelm@62590
   790
    -l           list session source files
wenzelm@62590
   791
    -n           no build -- test dependencies only
wenzelm@62590
   792
    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
wenzelm@62590
   793
    -s           system build mode: produce output in ISABELLE_HOME
wenzelm@62590
   794
    -v           verbose
wenzelm@62590
   795
    -x NAME      exclude session NAME and all descendants
wenzelm@62590
   796
wenzelm@62596
   797
  Build and manage Isabelle sessions, depending on implicit settings:
wenzelm@62596
   798
wenzelm@62590
   799
""" + Library.prefix_lines("  ", show_settings()),
wenzelm@62590
   800
        "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
wenzelm@62590
   801
        "R" -> (_ => requirements = true),
wenzelm@62590
   802
        "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
wenzelm@62590
   803
        "a" -> (_ => all_sessions = true),
wenzelm@62590
   804
        "b" -> (_ => build_heap = true),
wenzelm@62590
   805
        "c" -> (_ => clean_build = true),
wenzelm@62590
   806
        "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
wenzelm@62590
   807
        "g:" -> (arg => session_groups = session_groups ::: List(arg)),
wenzelm@62590
   808
        "j:" -> (arg => max_jobs = Properties.Value.Int.parse(arg)),
wenzelm@62590
   809
        "k:" -> (arg => check_keywords = check_keywords + arg),
wenzelm@62590
   810
        "l" -> (_ => list_files = true),
wenzelm@62590
   811
        "n" -> (_ => no_build = true),
wenzelm@62590
   812
        "o:" -> (arg => options = options + arg),
wenzelm@62590
   813
        "s" -> (_ => system_mode = true),
wenzelm@62590
   814
        "v" -> (_ => verbose = true),
wenzelm@62590
   815
        "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
wenzelm@62590
   816
wenzelm@62590
   817
      val sessions = getopts(args)
wenzelm@62590
   818
wenzelm@62590
   819
      val progress = new Console_Progress(verbose)
wenzelm@62590
   820
wenzelm@62595
   821
      if (verbose) {
wenzelm@62590
   822
        progress.echo(
wenzelm@62590
   823
          Library.trim_line(
wenzelm@62590
   824
            Isabelle_System.bash(
wenzelm@62596
   825
              """echo "Started at $(date) ($ML_IDENTIFIER on $(hostname))" """).out) + "\n")
wenzelm@62596
   826
        progress.echo(show_settings() + "\n")
wenzelm@48341
   827
      }
wenzelm@62590
   828
wenzelm@62595
   829
      val start_time = Time.now()
wenzelm@62590
   830
      val results =
wenzelm@62590
   831
        progress.interrupt_handler {
wenzelm@62590
   832
          build_results(options, progress, requirements, all_sessions, build_heap, clean_build,
wenzelm@62590
   833
            dirs, select_dirs, exclude_session_groups, session_groups, max_jobs, list_files,
wenzelm@62590
   834
            check_keywords, no_build, system_mode, verbose, exclude_sessions, sessions)
wenzelm@62590
   835
        }
wenzelm@62595
   836
      val elapsed_time = Time.now() - start_time
wenzelm@62590
   837
wenzelm@62595
   838
      if (verbose) {
wenzelm@62596
   839
        progress.echo("\n" +
wenzelm@62590
   840
          Library.trim_line(
wenzelm@62596
   841
            Isabelle_System.bash("""echo -n "Finished at "; date""").out))
wenzelm@62595
   842
      }
wenzelm@62590
   843
wenzelm@62595
   844
      val total_timing =
wenzelm@62595
   845
        (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
wenzelm@62595
   846
          copy(elapsed = elapsed_time)
wenzelm@62595
   847
      progress.echo(total_timing.message_resources)
wenzelm@62590
   848
wenzelm@62590
   849
      results.rc
wenzelm@48346
   850
    }
wenzelm@48341
   851
  }
wenzelm@59366
   852
wenzelm@59366
   853
wenzelm@59366
   854
  /* PIDE protocol */
wenzelm@59366
   855
wenzelm@59366
   856
  def build_theories(
wenzelm@59369
   857
    session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
wenzelm@59367
   858
      session.get_protocol_handler(classOf[Handler].getName) match {
wenzelm@59366
   859
        case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
wenzelm@59366
   860
        case _ => error("Cannot invoke build_theories: bad protocol handler")
wenzelm@59366
   861
      }
wenzelm@59366
   862
wenzelm@59367
   863
  class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
wenzelm@59366
   864
  {
wenzelm@59369
   865
    private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
wenzelm@59366
   866
wenzelm@59366
   867
    def build_theories(
wenzelm@59369
   868
      session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
wenzelm@59366
   869
    {
wenzelm@59369
   870
      val promise = Future.promise[XML.Body]
wenzelm@59366
   871
      val id = Document_ID.make().toString
wenzelm@59366
   872
      pending.change(promises => promises + (id -> promise))
wenzelm@59366
   873
      session.build_theories(id, master_dir, theories)
wenzelm@59366
   874
      promise
wenzelm@59366
   875
    }
wenzelm@59366
   876
wenzelm@59367
   877
    private def loading_theory(prover: Prover, msg: Prover.Protocol_Output): Boolean =
wenzelm@59367
   878
      msg.properties match {
wenzelm@59367
   879
        case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
wenzelm@59367
   880
        case _ => false
wenzelm@59367
   881
      }
wenzelm@59367
   882
wenzelm@59366
   883
    private def build_theories_result(prover: Prover, msg: Prover.Protocol_Output): Boolean =
wenzelm@59366
   884
      msg.properties match {
wenzelm@59369
   885
        case Markup.Build_Theories_Result(id) =>
wenzelm@59366
   886
          pending.change_result(promises =>
wenzelm@59366
   887
            promises.get(id) match {
wenzelm@59369
   888
              case Some(promise) =>
wenzelm@59369
   889
                val error_message =
wenzelm@59369
   890
                  try { YXML.parse_body(Symbol.decode(msg.text)) }
wenzelm@59369
   891
                  catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
wenzelm@59369
   892
                promise.fulfill(error_message)
wenzelm@59369
   893
                (true, promises - id)
wenzelm@59369
   894
              case None =>
wenzelm@59369
   895
                (false, promises)
wenzelm@59366
   896
            })
wenzelm@59366
   897
        case _ => false
wenzelm@59366
   898
      }
wenzelm@59366
   899
wenzelm@59366
   900
    override def stop(prover: Prover): Unit =
wenzelm@59366
   901
      pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
wenzelm@59366
   902
wenzelm@59367
   903
    val functions =
wenzelm@59367
   904
      Map(
wenzelm@59367
   905
        Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
wenzelm@59367
   906
        Markup.LOADING_THEORY -> loading_theory _)
wenzelm@59366
   907
  }
wenzelm@48276
   908
}