src/Pure/Tools/build.scala
author wenzelm
Tue Mar 15 16:23:27 2016 +0100 (2016-03-15)
changeset 62630 bc772694cfbd
parent 62628 6031191a8d9c
child 62631 c39614ddb80b
permissions -rw-r--r--
ML save_state under control of Isabelle/Scala;
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@48337
    22
  /** session information **/
wenzelm@48334
    23
wenzelm@48675
    24
  // external version
wenzelm@51397
    25
  abstract class Entry
wenzelm@51397
    26
  sealed case class Chapter(name: String) extends Entry
wenzelm@48675
    27
  sealed case class Session_Entry(
wenzelm@48675
    28
    pos: Position.T,
wenzelm@48738
    29
    name: String,
wenzelm@48675
    30
    groups: List[String],
wenzelm@48738
    31
    path: String,
wenzelm@48675
    32
    parent: Option[String],
wenzelm@48675
    33
    description: String,
wenzelm@48675
    34
    options: List[Options.Spec],
wenzelm@56801
    35
    theories: List[(Boolean, List[Options.Spec], List[String])],
wenzelm@56533
    36
    files: List[String],
wenzelm@56533
    37
    document_files: List[(String, String)]) extends Entry
wenzelm@48675
    38
wenzelm@48675
    39
  // internal version
wenzelm@48675
    40
  sealed case class Session_Info(
wenzelm@51397
    41
    chapter: String,
wenzelm@48737
    42
    select: Boolean,
wenzelm@48675
    43
    pos: Position.T,
wenzelm@48675
    44
    groups: List[String],
wenzelm@48675
    45
    dir: Path,
wenzelm@48675
    46
    parent: Option[String],
wenzelm@48675
    47
    description: String,
wenzelm@48675
    48
    options: Options,
wenzelm@56801
    49
    theories: List[(Boolean, Options, List[Path])],
wenzelm@48675
    50
    files: List[Path],
wenzelm@56533
    51
    document_files: List[(Path, Path)],
wenzelm@48675
    52
    entry_digest: SHA1.Digest)
wenzelm@61602
    53
  {
wenzelm@61602
    54
    def timeout: Time = Time.seconds(options.real("timeout") * options.real("timeout_scale"))
wenzelm@61602
    55
  }
wenzelm@48675
    56
wenzelm@62508
    57
  def is_pure(name: String): Boolean = name == "Pure"
wenzelm@48675
    58
wenzelm@51397
    59
  def session_info(options: Options, select: Boolean, dir: Path,
wenzelm@51397
    60
      chapter: String, entry: Session_Entry): (String, Session_Info) =
wenzelm@48675
    61
    try {
wenzelm@48738
    62
      val name = entry.name
wenzelm@48675
    63
wenzelm@48738
    64
      if (name == "") error("Bad session name")
wenzelm@48738
    65
      if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
wenzelm@48738
    66
      if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
wenzelm@48675
    67
wenzelm@48675
    68
      val session_options = options ++ entry.options
wenzelm@48675
    69
wenzelm@48675
    70
      val theories =
wenzelm@56801
    71
        entry.theories.map({ case (global, opts, thys) =>
wenzelm@56801
    72
          (global, session_options ++ opts, thys.map(Path.explode(_))) })
wenzelm@48675
    73
      val files = entry.files.map(Path.explode(_))
wenzelm@56533
    74
      val document_files =
wenzelm@56533
    75
        entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
wenzelm@56533
    76
wenzelm@51397
    77
      val entry_digest =
wenzelm@56533
    78
        SHA1.digest((chapter, name, entry.parent, entry.options,
wenzelm@56533
    79
          entry.theories, entry.files, entry.document_files).toString)
wenzelm@48675
    80
wenzelm@48675
    81
      val info =
wenzelm@51397
    82
        Session_Info(chapter, select, entry.pos, entry.groups, dir + Path.explode(entry.path),
wenzelm@56533
    83
          entry.parent, entry.description, session_options, theories, files,
wenzelm@56533
    84
          document_files, entry_digest)
wenzelm@48675
    85
wenzelm@48738
    86
      (name, info)
wenzelm@48675
    87
    }
wenzelm@48675
    88
    catch {
wenzelm@48675
    89
      case ERROR(msg) =>
wenzelm@48675
    90
        error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@48992
    91
          quote(entry.name) + Position.here(entry.pos))
wenzelm@48675
    92
    }
wenzelm@48675
    93
wenzelm@48675
    94
wenzelm@48676
    95
  /* session tree */
wenzelm@48676
    96
wenzelm@48676
    97
  object Session_Tree
wenzelm@48676
    98
  {
wenzelm@48676
    99
    def apply(infos: Seq[(String, Session_Info)]): Session_Tree =
wenzelm@48676
   100
    {
wenzelm@48680
   101
      val graph1 =
wenzelm@48680
   102
        (Graph.string[Session_Info] /: infos) {
wenzelm@48684
   103
          case (graph, (name, info)) =>
wenzelm@48680
   104
            if (graph.defined(name))
wenzelm@54939
   105
              error("Duplicate session " + quote(name) + Position.here(info.pos) +
wenzelm@54939
   106
                Position.here(graph.get_node(name).pos))
wenzelm@48680
   107
            else graph.new_node(name, info)
wenzelm@48680
   108
        }
wenzelm@48680
   109
      val graph2 =
wenzelm@56372
   110
        (graph1 /: graph1.iterator) {
wenzelm@48680
   111
          case (graph, (name, (info, _))) =>
wenzelm@48680
   112
            info.parent match {
wenzelm@48680
   113
              case None => graph
wenzelm@48680
   114
              case Some(parent) =>
wenzelm@48680
   115
                if (!graph.defined(parent))
wenzelm@48680
   116
                  error("Bad parent session " + quote(parent) + " for " +
wenzelm@48992
   117
                    quote(name) + Position.here(info.pos))
wenzelm@48676
   118
wenzelm@48680
   119
                try { graph.add_edge_acyclic(parent, name) }
wenzelm@48680
   120
                catch {
wenzelm@48680
   121
                  case exn: Graph.Cycles[_] =>
wenzelm@48680
   122
                    error(cat_lines(exn.cycles.map(cycle =>
wenzelm@48680
   123
                      "Cyclic session dependency of " +
wenzelm@48680
   124
                        cycle.map(c => quote(c.toString)).mkString(" via "))) +
wenzelm@48992
   125
                          Position.here(info.pos))
wenzelm@48680
   126
                }
wenzelm@48676
   127
            }
wenzelm@48676
   128
        }
wenzelm@48680
   129
      new Session_Tree(graph2)
wenzelm@48676
   130
    }
wenzelm@48676
   131
  }
wenzelm@48676
   132
wenzelm@48680
   133
  final class Session_Tree private(val graph: Graph[String, Session_Info])
wenzelm@48676
   134
    extends PartialFunction[String, Session_Info]
wenzelm@48676
   135
  {
wenzelm@48680
   136
    def apply(name: String): Session_Info = graph.get_node(name)
wenzelm@48680
   137
    def isDefinedAt(name: String): Boolean = graph.defined(name)
wenzelm@48676
   138
wenzelm@59892
   139
    def selection(
wenzelm@59892
   140
      requirements: Boolean = false,
wenzelm@59892
   141
      all_sessions: Boolean = false,
wenzelm@60106
   142
      exclude_session_groups: List[String] = Nil,
wenzelm@60106
   143
      exclude_sessions: List[String] = Nil,
wenzelm@59892
   144
      session_groups: List[String] = Nil,
wenzelm@59892
   145
      sessions: List[String] = Nil): (List[String], Session_Tree) =
wenzelm@48676
   146
    {
wenzelm@59892
   147
      val bad_sessions =
wenzelm@59892
   148
        SortedSet((exclude_sessions ::: sessions).filterNot(isDefinedAt(_)): _*).toList
wenzelm@59319
   149
      if (bad_sessions.nonEmpty) error("Undefined session(s): " + commas_quote(bad_sessions))
wenzelm@48676
   150
wenzelm@60106
   151
      val excluded =
wenzelm@60106
   152
      {
wenzelm@60106
   153
        val exclude_group = exclude_session_groups.toSet
wenzelm@60106
   154
        val exclude_group_sessions =
wenzelm@60106
   155
          (for {
wenzelm@60106
   156
            (name, (info, _)) <- graph.iterator
wenzelm@60106
   157
            if apply(name).groups.exists(exclude_group)
wenzelm@60106
   158
          } yield name).toList
wenzelm@60106
   159
        graph.all_succs(exclude_group_sessions ::: exclude_sessions).toSet
wenzelm@60106
   160
      }
wenzelm@60106
   161
wenzelm@49131
   162
      val pre_selected =
wenzelm@48676
   163
      {
wenzelm@56372
   164
        if (all_sessions) graph.keys
wenzelm@48676
   165
        else {
wenzelm@48737
   166
          val select_group = session_groups.toSet
wenzelm@48737
   167
          val select = sessions.toSet
wenzelm@48737
   168
          (for {
wenzelm@56372
   169
            (name, (info, _)) <- graph.iterator
wenzelm@48737
   170
            if info.select || select(name) || apply(name).groups.exists(select_group)
wenzelm@48737
   171
          } yield name).toList
wenzelm@48676
   172
        }
wenzelm@59892
   173
      }.filterNot(excluded)
wenzelm@59892
   174
wenzelm@49131
   175
      val selected =
wenzelm@49131
   176
        if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
wenzelm@49131
   177
        else pre_selected
wenzelm@49131
   178
wenzelm@56801
   179
      val graph1 = graph.restrict(graph.all_preds(selected).toSet)
wenzelm@56801
   180
      (selected, new Session_Tree(graph1))
wenzelm@48676
   181
    }
wenzelm@48676
   182
wenzelm@62628
   183
    def ancestors(name: String): List[String] =
wenzelm@62628
   184
      graph.all_preds(List(name)).tail.reverse
wenzelm@62628
   185
wenzelm@48676
   186
    def topological_order: List[(String, Session_Info)] =
wenzelm@48676
   187
      graph.topological_order.map(name => (name, apply(name)))
wenzelm@48794
   188
wenzelm@56372
   189
    override def toString: String = graph.keys_iterator.mkString("Session_Tree(", ", ", ")")
wenzelm@48676
   190
  }
wenzelm@48676
   191
wenzelm@48676
   192
wenzelm@48675
   193
  /* parser */
wenzelm@48675
   194
wenzelm@51397
   195
  val chapter_default = "Unsorted"
wenzelm@51397
   196
wenzelm@51397
   197
  private val CHAPTER = "chapter"
wenzelm@48713
   198
  private val SESSION = "session"
wenzelm@48713
   199
  private val IN = "in"
wenzelm@48713
   200
  private val DESCRIPTION = "description"
wenzelm@48713
   201
  private val OPTIONS = "options"
wenzelm@56801
   202
  private val GLOBAL_THEORIES = "global_theories"
wenzelm@48713
   203
  private val THEORIES = "theories"
wenzelm@48713
   204
  private val FILES = "files"
wenzelm@56533
   205
  private val DOCUMENT_FILES = "document_files"
wenzelm@48713
   206
wenzelm@48713
   207
  lazy val root_syntax =
wenzelm@48738
   208
    Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" +
wenzelm@51397
   209
      (CHAPTER, Keyword.THY_DECL) + (SESSION, Keyword.THY_DECL) +
wenzelm@56801
   210
      IN + DESCRIPTION + OPTIONS + GLOBAL_THEORIES + THEORIES + FILES + DOCUMENT_FILES
wenzelm@48713
   211
wenzelm@56780
   212
  object Parser extends Parse.Parser
wenzelm@48675
   213
  {
wenzelm@56780
   214
    private val chapter: Parser[Chapter] =
wenzelm@51397
   215
    {
wenzelm@51397
   216
      val chapter_name = atom("chapter name", _.is_name)
wenzelm@51397
   217
wenzelm@51397
   218
      command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
wenzelm@51397
   219
    }
wenzelm@51397
   220
wenzelm@56780
   221
    private val session_entry: Parser[Session_Entry] =
wenzelm@48675
   222
    {
wenzelm@48675
   223
      val session_name = atom("session name", _.is_name)
wenzelm@48675
   224
wenzelm@48675
   225
      val option =
wenzelm@58908
   226
        name ~ opt($$$("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@58908
   227
      val options = $$$("[") ~> rep1sep(option, $$$(",")) <~ $$$("]")
wenzelm@48675
   228
wenzelm@48675
   229
      val theories =
wenzelm@58908
   230
        ($$$(GLOBAL_THEORIES) | $$$(THEORIES)) ~!
wenzelm@56801
   231
          ((options | success(Nil)) ~ rep(theory_xname)) ^^
wenzelm@56801
   232
          { case x ~ (y ~ z) => (x == GLOBAL_THEORIES, y, z) }
wenzelm@48675
   233
wenzelm@56533
   234
      val document_files =
wenzelm@58908
   235
        $$$(DOCUMENT_FILES) ~!
wenzelm@58908
   236
          (($$$("(") ~! ($$$(IN) ~! (path ~ $$$(")"))) ^^
wenzelm@56533
   237
              { case _ ~ (_ ~ (x ~ _)) => x } | success("document")) ~
wenzelm@56533
   238
            rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
wenzelm@56533
   239
wenzelm@59811
   240
      command(SESSION) ~!
wenzelm@59811
   241
        (position(session_name) ~
wenzelm@58908
   242
          (($$$("(") ~! (rep1(name) <~ $$$(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@58908
   243
          (($$$(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
wenzelm@58908
   244
          ($$$("=") ~!
wenzelm@58908
   245
            (opt(session_name ~! $$$("+") ^^ { case x ~ _ => x }) ~
wenzelm@58908
   246
              (($$$(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
wenzelm@58908
   247
              (($$$(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@48916
   248
              rep1(theories) ~
wenzelm@58908
   249
              (($$$(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@56533
   250
              (rep(document_files) ^^ (x => x.flatten))))) ^^
wenzelm@59811
   251
        { case _ ~ ((a, pos) ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i))) =>
wenzelm@56533
   252
            Session_Entry(pos, a, b, c, d, e, f, g, h, i) }
wenzelm@48675
   253
    }
wenzelm@48675
   254
wenzelm@51397
   255
    def parse_entries(root: Path): List[(String, Session_Entry)] =
wenzelm@48675
   256
    {
wenzelm@59083
   257
      val toks = Token.explode(root_syntax.keywords, File.read(root))
wenzelm@59705
   258
      val start = Token.Pos.file(root.implode)
wenzelm@51397
   259
wenzelm@59705
   260
      parse_all(rep(chapter | session_entry), Token.reader(toks, start)) match {
wenzelm@51397
   261
        case Success(result, _) =>
wenzelm@51397
   262
          var chapter = chapter_default
wenzelm@51397
   263
          val entries = new mutable.ListBuffer[(String, Session_Entry)]
wenzelm@51397
   264
          result.foreach {
wenzelm@51397
   265
            case Chapter(name) => chapter = name
wenzelm@51397
   266
            case session_entry: Session_Entry => entries += ((chapter, session_entry))
wenzelm@51397
   267
          }
wenzelm@51397
   268
          entries.toList
wenzelm@48675
   269
        case bad => error(bad.toString)
wenzelm@48675
   270
      }
wenzelm@48675
   271
    }
wenzelm@48675
   272
  }
wenzelm@48675
   273
wenzelm@48675
   274
wenzelm@48675
   275
  /* find sessions within certain directories */
wenzelm@48675
   276
wenzelm@48675
   277
  private val ROOT = Path.explode("ROOT")
wenzelm@48684
   278
  private val ROOTS = Path.explode("ROOTS")
wenzelm@48675
   279
wenzelm@48684
   280
  private def is_session_dir(dir: Path): Boolean =
wenzelm@48684
   281
    (dir + ROOT).is_file || (dir + ROOTS).is_file
wenzelm@48684
   282
wenzelm@48684
   283
  private def check_session_dir(dir: Path): Path =
wenzelm@48684
   284
    if (is_session_dir(dir)) dir
wenzelm@48684
   285
    else error("Bad session root directory: " + dir.toString)
wenzelm@48675
   286
wenzelm@56890
   287
  def find_sessions(options: Options, dirs: List[Path] = Nil, select_dirs: List[Path] = Nil)
wenzelm@56890
   288
    : Session_Tree =
wenzelm@48675
   289
  {
wenzelm@48737
   290
    def find_dir(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48737
   291
      find_root(select, dir) ::: find_roots(select, dir)
wenzelm@48684
   292
wenzelm@48737
   293
    def find_root(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48684
   294
    {
wenzelm@48684
   295
      val root = dir + ROOT
wenzelm@51397
   296
      if (root.is_file)
wenzelm@51397
   297
        Parser.parse_entries(root).map(p => session_info(options, select, dir, p._1, p._2))
wenzelm@48684
   298
      else Nil
wenzelm@48684
   299
    }
wenzelm@48684
   300
wenzelm@48737
   301
    def find_roots(select: Boolean, dir: Path): List[(String, Session_Info)] =
wenzelm@48684
   302
    {
wenzelm@48684
   303
      val roots = dir + ROOTS
wenzelm@48684
   304
      if (roots.is_file) {
wenzelm@48684
   305
        for {
wenzelm@48684
   306
          line <- split_lines(File.read(roots))
wenzelm@48684
   307
          if !(line == "" || line.startsWith("#"))
wenzelm@48684
   308
          dir1 =
wenzelm@48684
   309
            try { check_session_dir(dir + Path.explode(line)) }
wenzelm@48684
   310
            catch {
wenzelm@48684
   311
              case ERROR(msg) =>
wenzelm@48684
   312
                error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
wenzelm@48684
   313
            }
wenzelm@48737
   314
          info <- find_dir(select, dir1)
wenzelm@48684
   315
        } yield info
wenzelm@48684
   316
      }
wenzelm@48684
   317
      else Nil
wenzelm@48684
   318
    }
wenzelm@48684
   319
wenzelm@56890
   320
    val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
wenzelm@56890
   321
    dirs.foreach(check_session_dir(_))
wenzelm@56890
   322
    select_dirs.foreach(check_session_dir(_))
wenzelm@48737
   323
wenzelm@48684
   324
    Session_Tree(
wenzelm@48684
   325
      for {
wenzelm@56890
   326
        (select, dir) <- (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _))
wenzelm@48737
   327
        info <- find_dir(select, dir)
wenzelm@48684
   328
      } yield info)
wenzelm@48349
   329
  }
wenzelm@48334
   330
wenzelm@48337
   331
wenzelm@48424
   332
wenzelm@48424
   333
  /** build **/
wenzelm@48424
   334
wenzelm@48676
   335
  /* queue */
wenzelm@48676
   336
wenzelm@48676
   337
  object Queue
wenzelm@48676
   338
  {
wenzelm@51230
   339
    def apply(tree: Session_Tree, load_timings: String => (List[Properties.T], Double)): Queue =
wenzelm@48676
   340
    {
wenzelm@48676
   341
      val graph = tree.graph
wenzelm@56372
   342
      val sessions = graph.keys
wenzelm@51220
   343
wenzelm@59136
   344
      val timings = Par_List.map((name: String) => (name, load_timings(name)), sessions)
wenzelm@51220
   345
      val command_timings =
wenzelm@51220
   346
        Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
wenzelm@51220
   347
      val session_timing =
wenzelm@51220
   348
        Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
wenzelm@48678
   349
wenzelm@48678
   350
      def outdegree(name: String): Int = graph.imm_succs(name).size
wenzelm@48678
   351
wenzelm@48678
   352
      object Ordering extends scala.math.Ordering[String]
wenzelm@48678
   353
      {
wenzelm@51227
   354
        def compare_timing(name1: String, name2: String): Int =
wenzelm@51227
   355
        {
wenzelm@51227
   356
          val t1 = session_timing(name1)
wenzelm@51227
   357
          val t2 = session_timing(name2)
wenzelm@51227
   358
          if (t1 == 0.0 || t2 == 0.0) 0
wenzelm@51227
   359
          else t1 compare t2
wenzelm@51227
   360
        }
wenzelm@51227
   361
wenzelm@48678
   362
        def compare(name1: String, name2: String): Int =
wenzelm@51229
   363
          outdegree(name2) compare outdegree(name1) match {
wenzelm@48678
   364
            case 0 =>
wenzelm@51229
   365
              compare_timing(name2, name1) match {
wenzelm@51220
   366
                case 0 =>
wenzelm@61602
   367
                  tree(name2).timeout compare tree(name1).timeout match {
wenzelm@51220
   368
                    case 0 => name1 compare name2
wenzelm@51220
   369
                    case ord => ord
wenzelm@51220
   370
                  }
wenzelm@48678
   371
                case ord => ord
wenzelm@48678
   372
              }
wenzelm@48678
   373
            case ord => ord
wenzelm@48678
   374
          }
wenzelm@48678
   375
      }
wenzelm@48678
   376
wenzelm@51220
   377
      new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
wenzelm@48676
   378
    }
wenzelm@48676
   379
  }
wenzelm@48676
   380
wenzelm@51220
   381
  final class Queue private(
wenzelm@51220
   382
    graph: Graph[String, Session_Info],
wenzelm@51220
   383
    order: SortedSet[String],
wenzelm@51220
   384
    val command_timings: String => List[Properties.T])
wenzelm@48676
   385
  {
wenzelm@48676
   386
    def is_inner(name: String): Boolean = !graph.is_maximal(name)
wenzelm@48676
   387
wenzelm@48676
   388
    def is_empty: Boolean = graph.is_empty
wenzelm@48676
   389
wenzelm@51227
   390
    def - (name: String): Queue =
wenzelm@51227
   391
      new Queue(graph.del_node(name),
wenzelm@51227
   392
        order - name,  // FIXME scala-2.10.0 TreeSet problem!?
wenzelm@51227
   393
        command_timings)
wenzelm@48676
   394
wenzelm@48676
   395
    def dequeue(skip: String => Boolean): Option[(String, Session_Info)] =
wenzelm@48676
   396
    {
wenzelm@51227
   397
      val it = order.iterator.dropWhile(name =>
wenzelm@51227
   398
        skip(name)
wenzelm@51227
   399
          || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
wenzelm@51227
   400
          || !graph.is_minimal(name))
wenzelm@48680
   401
      if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
wenzelm@48676
   402
      else None
wenzelm@48676
   403
    }
wenzelm@48676
   404
  }
wenzelm@48676
   405
wenzelm@48676
   406
wenzelm@48710
   407
  /* source dependencies and static content */
wenzelm@48422
   408
wenzelm@48710
   409
  sealed case class Session_Content(
wenzelm@48422
   410
    loaded_theories: Set[String],
wenzelm@56801
   411
    known_theories: Map[String, Document.Node.Name],
wenzelm@52439
   412
    keywords: Thy_Header.Keywords,
wenzelm@48660
   413
    syntax: Outer_Syntax,
wenzelm@59444
   414
    sources: List[(Path, SHA1.Digest)],
wenzelm@59444
   415
    session_graph: Graph_Display.Graph)
wenzelm@48422
   416
wenzelm@48710
   417
  sealed case class Deps(deps: Map[String, Session_Content])
wenzelm@48423
   418
  {
wenzelm@48583
   419
    def is_empty: Boolean = deps.isEmpty
wenzelm@48710
   420
    def apply(name: String): Session_Content = deps(name)
wenzelm@48504
   421
    def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
wenzelm@48423
   422
  }
wenzelm@48423
   423
wenzelm@59891
   424
  def dependencies(
wenzelm@59891
   425
      progress: Progress = Ignore_Progress,
wenzelm@59891
   426
      inlined_files: Boolean = false,
wenzelm@59891
   427
      verbose: Boolean = false,
wenzelm@59891
   428
      list_files: Boolean = false,
wenzelm@59891
   429
      check_keywords: Set[String] = Set.empty,
wenzelm@59891
   430
      tree: Session_Tree): Deps =
wenzelm@48710
   431
    Deps((Map.empty[String, Session_Content] /: tree.topological_order)(
wenzelm@48422
   432
      { case (deps, (name, info)) =>
wenzelm@56668
   433
          if (progress.stopped) throw Exn.Interrupt()
wenzelm@56668
   434
wenzelm@54549
   435
          try {
wenzelm@56801
   436
            val (loaded_theories0, known_theories0, syntax0) =
wenzelm@56801
   437
              info.parent.map(deps(_)) match {
wenzelm@54549
   438
                case None =>
wenzelm@58928
   439
                  (Set.empty[String], Map.empty[String, Document.Node.Name],
wenzelm@59736
   440
                    Thy_Header.bootstrap_syntax)
wenzelm@56801
   441
                case Some(parent) =>
wenzelm@56801
   442
                  (parent.loaded_theories, parent.known_theories, parent.syntax)
wenzelm@54549
   443
              }
wenzelm@56801
   444
            val resources = new Resources(loaded_theories0, known_theories0, syntax0)
wenzelm@56208
   445
            val thy_info = new Thy_Info(resources)
wenzelm@48422
   446
wenzelm@54549
   447
            if (verbose || list_files) {
wenzelm@54549
   448
              val groups =
wenzelm@54549
   449
                if (info.groups.isEmpty) ""
wenzelm@54549
   450
                else info.groups.mkString(" (", " ", ")")
wenzelm@54549
   451
              progress.echo("Session " + info.chapter + "/" + name + groups)
wenzelm@54549
   452
            }
wenzelm@48478
   453
wenzelm@54549
   454
            val thy_deps =
wenzelm@56801
   455
            {
wenzelm@56801
   456
              val root_theories =
wenzelm@56801
   457
                info.theories.flatMap({
wenzelm@56801
   458
                  case (global, _, thys) =>
wenzelm@56801
   459
                    thys.map(thy =>
wenzelm@56801
   460
                      (resources.node_name(
wenzelm@56801
   461
                        if (global) "" else name, info.dir + Resources.thy_path(thy)), info.pos))
wenzelm@56801
   462
                })
wenzelm@56801
   463
              val thy_deps = thy_info.dependencies(name, root_theories)
wenzelm@48422
   464
wenzelm@56801
   465
              thy_deps.errors match {
wenzelm@56801
   466
                case Nil => thy_deps
wenzelm@56801
   467
                case errs => error(cat_lines(errs))
wenzelm@56801
   468
              }
wenzelm@54549
   469
            }
wenzelm@51294
   470
wenzelm@56801
   471
            val known_theories =
wenzelm@56801
   472
              (known_theories0 /: thy_deps.deps)({ case (known, dep) =>
wenzelm@56801
   473
                val name = dep.name
wenzelm@56801
   474
                known.get(name.theory) match {
wenzelm@56801
   475
                  case Some(name1) if name != name1 =>
wenzelm@56801
   476
                    error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
wenzelm@56801
   477
                  case _ =>
wenzelm@56801
   478
                    known + (name.theory -> name) + (Long_Name.base_name(name.theory) -> name)
wenzelm@56801
   479
                }
wenzelm@56801
   480
              })
wenzelm@56801
   481
wenzelm@54549
   482
            val loaded_theories = thy_deps.loaded_theories
wenzelm@54549
   483
            val keywords = thy_deps.keywords
wenzelm@56393
   484
            val syntax = thy_deps.syntax.asInstanceOf[Outer_Syntax]
wenzelm@48660
   485
wenzelm@59891
   486
            val theory_files = thy_deps.deps.map(dep => Path.explode(dep.name.node))
wenzelm@56392
   487
            val loaded_files = if (inlined_files) thy_deps.loaded_files else Nil
wenzelm@48903
   488
wenzelm@54549
   489
            val all_files =
wenzelm@59891
   490
              (theory_files ::: loaded_files :::
wenzelm@56533
   491
                info.files.map(file => info.dir + file) :::
wenzelm@56533
   492
                info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
wenzelm@54549
   493
wenzelm@56824
   494
            if (list_files)
wenzelm@54549
   495
              progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
wenzelm@54549
   496
wenzelm@59895
   497
            if (check_keywords.nonEmpty)
wenzelm@59895
   498
              Check_Keywords.check_keywords(progress, syntax.keywords, check_keywords, theory_files)
wenzelm@59891
   499
wenzelm@54549
   500
            val sources = all_files.map(p => (p, SHA1.digest(p.file)))
wenzelm@48903
   501
wenzelm@60077
   502
            val session_graph =
wenzelm@60077
   503
              Present.session_graph(info.parent getOrElse "", loaded_theories0, thy_deps.deps)
wenzelm@59444
   504
wenzelm@56801
   505
            val content =
wenzelm@59444
   506
              Session_Content(loaded_theories, known_theories, keywords, syntax,
wenzelm@59444
   507
                sources, session_graph)
wenzelm@56801
   508
            deps + (name -> content)
wenzelm@54549
   509
          }
wenzelm@54549
   510
          catch {
wenzelm@54549
   511
            case ERROR(msg) =>
wenzelm@54549
   512
              cat_error(msg, "The error(s) above occurred in session " +
wenzelm@54549
   513
                quote(name) + Position.here(info.pos))
wenzelm@54549
   514
          }
wenzelm@48423
   515
      }))
wenzelm@48422
   516
wenzelm@52439
   517
  def session_dependencies(
wenzelm@52439
   518
    options: Options,
wenzelm@52439
   519
    inlined_files: Boolean,
wenzelm@52439
   520
    dirs: List[Path],
wenzelm@52439
   521
    sessions: List[String]): Deps =
wenzelm@48710
   522
  {
wenzelm@59892
   523
    val (_, tree) = find_sessions(options, dirs = dirs).selection(sessions = sessions)
wenzelm@59891
   524
    dependencies(inlined_files = inlined_files, tree = tree)
wenzelm@48710
   525
  }
wenzelm@48710
   526
wenzelm@52439
   527
  def session_content(
wenzelm@52439
   528
    options: Options,
wenzelm@52439
   529
    inlined_files: Boolean,
wenzelm@52439
   530
    dirs: List[Path],
wenzelm@52439
   531
    session: String): Session_Content =
wenzelm@52439
   532
  {
wenzelm@52439
   533
    session_dependencies(options, inlined_files, dirs, List(session))(session)
wenzelm@52439
   534
  }
wenzelm@52439
   535
wenzelm@52439
   536
  def outer_syntax(options: Options, session: String): Outer_Syntax =
wenzelm@52439
   537
    session_content(options, false, Nil, session).syntax
wenzelm@48710
   538
wenzelm@48422
   539
wenzelm@48424
   540
  /* jobs */
wenzelm@48341
   541
wenzelm@52114
   542
  private class Job(progress: Progress,
wenzelm@59445
   543
    name: String, val info: Session_Info, output: Path, do_output: Boolean, verbose: Boolean,
wenzelm@59445
   544
    browser_info: Path, session_graph: Graph_Display.Graph, command_timings: List[Properties.T])
wenzelm@48418
   545
  {
wenzelm@48674
   546
    def output_path: Option[Path] = if (do_output) Some(output) else None
wenzelm@62630
   547
    def output_save_state: String =
wenzelm@62630
   548
      if (do_output)
wenzelm@62630
   549
        "PolyML.SaveState.saveState " + ML_Syntax.print_string_raw(File.platform_path(output))
wenzelm@62630
   550
      else ""
wenzelm@48674
   551
wenzelm@48674
   552
    private val parent = info.parent.getOrElse("")
wenzelm@48418
   553
wenzelm@59445
   554
    private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
wenzelm@59445
   555
    try { isabelle.graphview.Graph_File.write(info.options, graph_file, session_graph) }
wenzelm@59445
   556
    catch { case ERROR(_) => /*error should be exposed in ML*/ }
wenzelm@59445
   557
wenzelm@62573
   558
    output.file.delete
wenzelm@62573
   559
wenzelm@62610
   560
    private val env =
wenzelm@62610
   561
      Isabelle_System.settings() +
wenzelm@62610
   562
        ("ISABELLE_ML_DEBUGGER" -> info.options.bool("ML_debugger").toString)
wenzelm@48698
   563
wenzelm@62573
   564
    private val future_result: Future[Process_Result] =
wenzelm@61559
   565
      Future.thread("build") {
wenzelm@62573
   566
        val process =
wenzelm@62573
   567
          if (is_pure(name)) {
wenzelm@62573
   568
            val eval =
wenzelm@62573
   569
              "Command_Line.tool0 (fn () => (Session.finish (); Options.reset_default ();" +
wenzelm@62630
   570
              " Session.shutdown (); ML_Heap.share_common_data (); " + output_save_state + "));"
wenzelm@62573
   571
            ML_Process(info.options, "RAW_ML_SYSTEM", List("--use", "ROOT.ML", "--eval", eval),
wenzelm@62599
   572
              cwd = info.dir.file, env = env)
wenzelm@62573
   573
          }
wenzelm@62573
   574
          else {
wenzelm@62603
   575
            val args_file = Isabelle_System.tmp_file("build")
wenzelm@62603
   576
            File.write(args_file, YXML.string_of_body(
wenzelm@62599
   577
                {
wenzelm@62599
   578
                  val theories = info.theories.map(x => (x._2, x._3))
wenzelm@62599
   579
                  import XML.Encode._
wenzelm@62630
   580
                  pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
wenzelm@62599
   581
                    pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
wenzelm@62599
   582
                    pair(string, pair(string, pair(string,
wenzelm@62599
   583
                    list(pair(Options.encode, list(Path.encode)))))))))))))(
wenzelm@62630
   584
                  (Symbol.codes, (command_timings, (do_output, (verbose,
wenzelm@62599
   585
                    (browser_info, (info.document_files, (File.standard_path(graph_file),
wenzelm@62599
   586
                    (parent, (info.chapter, (name,
wenzelm@62599
   587
                    theories)))))))))))
wenzelm@62599
   588
                }))
wenzelm@62630
   589
            val eval =
wenzelm@62630
   590
              "Command_Line.tool0 (fn () => (" +
wenzelm@62630
   591
              "Build.build " + ML_Syntax.print_string_raw(File.standard_path(args_file)) +
wenzelm@62630
   592
              (if (do_output) "; ML_Heap.share_common_data (); " + output_save_state
wenzelm@62630
   593
               else "") + "));"
wenzelm@62630
   594
            ML_Process(info.options, parent, List("--eval", eval),
wenzelm@62610
   595
              cwd = info.dir.file, env = env, cleanup = () => args_file.delete)
wenzelm@62573
   596
          }
wenzelm@62573
   597
        process.result(
wenzelm@51962
   598
          progress_stdout = (line: String) =>
wenzelm@50847
   599
            Library.try_unprefix("\floading_theory = ", line) match {
wenzelm@50847
   600
              case Some(theory) => progress.theory(name, theory)
wenzelm@50847
   601
              case None =>
wenzelm@51962
   602
            },
wenzelm@51962
   603
          progress_limit =
wenzelm@51962
   604
            info.options.int("process_output_limit") match {
wenzelm@51962
   605
              case 0 => None
wenzelm@51962
   606
              case m => Some(m * 1000000L)
wenzelm@56871
   607
            },
wenzelm@56871
   608
          strict = false)
wenzelm@50845
   609
      }
wenzelm@48674
   610
wenzelm@62572
   611
    def terminate: Unit = future_result.cancel
wenzelm@62572
   612
    def is_finished: Boolean = future_result.is_finished
wenzelm@48674
   613
wenzelm@62569
   614
    @volatile private var was_timeout = false
wenzelm@56779
   615
    private val timeout_request: Option[Event_Timer.Request] =
wenzelm@56779
   616
    {
wenzelm@62569
   617
      if (info.timeout > Time.zero)
wenzelm@62569
   618
        Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
wenzelm@48674
   619
      else None
wenzelm@56779
   620
    }
wenzelm@48674
   621
wenzelm@62400
   622
    def join: Process_Result =
wenzelm@50845
   623
    {
wenzelm@62572
   624
      val result = future_result.join
wenzelm@50845
   625
wenzelm@62572
   626
      if (result.ok && !is_pure(name))
wenzelm@61372
   627
        Present.finish(progress, browser_info, graph_file, info, name)
wenzelm@61372
   628
wenzelm@59445
   629
      graph_file.delete
wenzelm@56779
   630
      timeout_request.foreach(_.cancel)
wenzelm@48674
   631
wenzelm@62572
   632
      if (result.interrupted) {
wenzelm@62572
   633
        if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
wenzelm@62572
   634
        else result.error(Output.error_text("Interrupt"))
wenzelm@52063
   635
      }
wenzelm@62572
   636
      else result
wenzelm@48674
   637
    }
wenzelm@48364
   638
  }
wenzelm@48364
   639
wenzelm@48424
   640
wenzelm@51045
   641
  /* inlined properties (YXML) */
wenzelm@50946
   642
wenzelm@50946
   643
  object Props
wenzelm@50946
   644
  {
wenzelm@51045
   645
    def parse(text: String): Properties.T = XML.Decode.properties(YXML.parse_body(text))
wenzelm@50946
   646
wenzelm@50946
   647
    def parse_lines(prefix: String, lines: List[String]): List[Properties.T] =
wenzelm@50946
   648
      for (line <- lines; s <- Library.try_unprefix(prefix, line)) yield parse(s)
wenzelm@50946
   649
wenzelm@50946
   650
    def find_parse_line(prefix: String, lines: List[String]): Option[Properties.T] =
wenzelm@50946
   651
      lines.find(_.startsWith(prefix)).map(line => parse(line.substring(prefix.length)))
wenzelm@50946
   652
  }
wenzelm@50946
   653
wenzelm@50946
   654
wenzelm@50777
   655
  /* log files */
wenzelm@48504
   656
wenzelm@62628
   657
  private def log(name: String): Path = Path.basic("log") + Path.basic(name)
wenzelm@48505
   658
  private def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@48504
   659
wenzelm@50982
   660
  private val SESSION_NAME = "\fSession.name = "
wenzelm@50707
   661
wenzelm@50946
   662
wenzelm@50975
   663
  sealed case class Log_Info(
wenzelm@51220
   664
    name: String,
wenzelm@51220
   665
    stats: List[Properties.T],
wenzelm@51220
   666
    tasks: List[Properties.T],
wenzelm@51220
   667
    command_timings: List[Properties.T],
wenzelm@51220
   668
    session_timing: Properties.T)
wenzelm@50777
   669
wenzelm@51220
   670
  def parse_log(full_stats: Boolean, text: String): Log_Info =
wenzelm@50777
   671
  {
wenzelm@50777
   672
    val lines = split_lines(text)
wenzelm@51223
   673
    val xml_cache = new XML.Cache()
wenzelm@51223
   674
    def parse_lines(prfx: String): List[Properties.T] =
wenzelm@51663
   675
      Props.parse_lines(prfx, lines).map(xml_cache.props(_))
wenzelm@51223
   676
wenzelm@50982
   677
    val name =
wenzelm@50982
   678
      lines.find(_.startsWith(SESSION_NAME)).map(_.substring(SESSION_NAME.length)) getOrElse ""
wenzelm@51223
   679
    val stats = if (full_stats) parse_lines("\fML_statistics = ") else Nil
wenzelm@51223
   680
    val tasks = if (full_stats) parse_lines("\ftask_statistics = ") else Nil
wenzelm@51223
   681
    val command_timings = parse_lines("\fcommand_timing = ")
wenzelm@51220
   682
    val session_timing = Props.find_parse_line("\fTiming = ", lines) getOrElse Nil
wenzelm@51220
   683
    Log_Info(name, stats, tasks, command_timings, session_timing)
wenzelm@50777
   684
  }
wenzelm@50777
   685
wenzelm@50777
   686
wenzelm@50777
   687
  /* sources and heaps */
wenzelm@50777
   688
wenzelm@62628
   689
  private val SOURCES = "sources: "
wenzelm@62628
   690
  private val INPUT_HEAP = "input_heap: "
wenzelm@62628
   691
  private val OUTPUT_HEAP = "output_heap: "
wenzelm@62628
   692
  private val LOG_START = "log:"
wenzelm@62628
   693
  private val line_prefixes = List(SOURCES, INPUT_HEAP, OUTPUT_HEAP, LOG_START)
wenzelm@48504
   694
wenzelm@62628
   695
  private def sources_stamp(digests: List[SHA1.Digest]): String =
wenzelm@62628
   696
    digests.map(_.toString).sorted.mkString(SOURCES, " ", "")
wenzelm@48639
   697
wenzelm@62628
   698
  private def time_stamp(path: Path): Option[String] =
wenzelm@48504
   699
  {
wenzelm@62628
   700
    val file = path.file
wenzelm@62628
   701
    if (file.isFile) Some(file.length.toString + " " + file.lastModified.toString)
wenzelm@62628
   702
    else None
wenzelm@48504
   703
  }
wenzelm@48504
   704
wenzelm@62628
   705
  private def read_stamps(path: Path): Option[(String, List[String], List[String])] =
wenzelm@48639
   706
    if (path.is_file) {
wenzelm@62628
   707
      val stream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(path.file)))
wenzelm@50203
   708
      val reader = new BufferedReader(new InputStreamReader(stream, UTF8.charset))
wenzelm@62628
   709
      val lines =
wenzelm@62628
   710
      {
wenzelm@62628
   711
        val lines = new mutable.ListBuffer[String]
wenzelm@62628
   712
        try {
wenzelm@62628
   713
          var finished = false
wenzelm@62628
   714
          while (!finished) {
wenzelm@62628
   715
            val line = reader.readLine
wenzelm@62628
   716
            if (line != null && line_prefixes.exists(line.startsWith(_)))
wenzelm@62628
   717
              lines += line
wenzelm@62628
   718
            else finished = true
wenzelm@62628
   719
          }
wenzelm@62628
   720
        }
wenzelm@48639
   721
        finally { reader.close }
wenzelm@62628
   722
        lines.toList
wenzelm@62628
   723
      }
wenzelm@62628
   724
wenzelm@62628
   725
      if (!lines.isEmpty && lines.last.startsWith(LOG_START)) {
wenzelm@62628
   726
        lines.find(_.startsWith(SOURCES)).map(s =>
wenzelm@62628
   727
          (s, lines.filter(_.startsWith(INPUT_HEAP)), lines.filter(_.startsWith(OUTPUT_HEAP))))
wenzelm@62628
   728
      }
wenzelm@48504
   729
      else None
wenzelm@48504
   730
    }
wenzelm@48504
   731
    else None
wenzelm@48504
   732
wenzelm@48504
   733
wenzelm@52114
   734
  /* build_results */
wenzelm@48424
   735
wenzelm@62403
   736
  class Build_Results private [Build](results: Map[String, Option[Process_Result]])
wenzelm@62403
   737
  {
wenzelm@62403
   738
    def sessions: Set[String] = results.keySet
wenzelm@62403
   739
    def cancelled(name: String): Boolean = results(name).isEmpty
wenzelm@62406
   740
    def apply(name: String): Process_Result = results(name).getOrElse(Process_Result(1))
wenzelm@62403
   741
    val rc = (0 /: results.iterator.map({ case (_, Some(r)) => r.rc case (_, None) => 1 }))(_ max _)
wenzelm@62406
   742
wenzelm@62406
   743
    override def toString: String = rc.toString
wenzelm@62403
   744
  }
wenzelm@62403
   745
wenzelm@52114
   746
  def build_results(
wenzelm@50404
   747
    options: Options,
wenzelm@52115
   748
    progress: Progress = Ignore_Progress,
wenzelm@49131
   749
    requirements: Boolean = false,
wenzelm@48509
   750
    all_sessions: Boolean = false,
wenzelm@48511
   751
    build_heap: Boolean = false,
wenzelm@48595
   752
    clean_build: Boolean = false,
wenzelm@56890
   753
    dirs: List[Path] = Nil,
wenzelm@56890
   754
    select_dirs: List[Path] = Nil,
wenzelm@60106
   755
    exclude_session_groups: List[String] = Nil,
wenzelm@48509
   756
    session_groups: List[String] = Nil,
wenzelm@48509
   757
    max_jobs: Int = 1,
wenzelm@48903
   758
    list_files: Boolean = false,
wenzelm@59891
   759
    check_keywords: Set[String] = Set.empty,
wenzelm@48509
   760
    no_build: Boolean = false,
wenzelm@48509
   761
    system_mode: Boolean = false,
wenzelm@48509
   762
    verbose: Boolean = false,
wenzelm@59892
   763
    exclude_sessions: List[String] = Nil,
wenzelm@62403
   764
    sessions: List[String] = Nil): Build_Results =
wenzelm@48341
   765
  {
wenzelm@51220
   766
    /* session tree and dependencies */
wenzelm@51220
   767
wenzelm@59723
   768
    val full_tree = find_sessions(options.int("completion_limit") = 0, dirs, select_dirs)
wenzelm@49131
   769
    val (selected, selected_tree) =
wenzelm@60106
   770
      full_tree.selection(requirements, all_sessions,
wenzelm@60106
   771
        exclude_session_groups, exclude_sessions, session_groups, sessions)
wenzelm@49131
   772
wenzelm@59891
   773
    val deps = dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
wenzelm@48368
   774
wenzelm@62628
   775
    def session_sources_stamp(name: String): String =
wenzelm@49131
   776
      sources_stamp(selected_tree(name).entry_digest :: deps.sources(name))
wenzelm@48504
   777
wenzelm@51220
   778
wenzelm@51220
   779
    /* persistent information */
wenzelm@51220
   780
wenzelm@48504
   781
    val (input_dirs, output_dir, browser_info) =
wenzelm@48504
   782
      if (system_mode) {
wenzelm@48504
   783
        val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@48504
   784
        (List(output_dir), output_dir, Path.explode("~~/browser_info"))
wenzelm@48504
   785
      }
wenzelm@48504
   786
      else {
wenzelm@48504
   787
        val output_dir = Path.explode("$ISABELLE_OUTPUT")
wenzelm@48504
   788
        (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
wenzelm@48504
   789
         Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48504
   790
      }
wenzelm@48363
   791
wenzelm@51221
   792
    def find_log(name: String): Option[(Path, Path)] =
wenzelm@51221
   793
      input_dirs.find(dir => (dir + log(name)).is_file).map(dir => (dir, dir + log(name)))
wenzelm@51220
   794
wenzelm@51220
   795
wenzelm@51220
   796
    /* queue with scheduling information */
wenzelm@51220
   797
wenzelm@51230
   798
    def load_timings(name: String): (List[Properties.T], Double) =
wenzelm@51221
   799
    {
wenzelm@51221
   800
      val (path, text) =
wenzelm@51221
   801
        find_log(name + ".gz") match {
wenzelm@51221
   802
          case Some((_, path)) => (path, File.read_gzip(path))
wenzelm@51221
   803
          case None =>
wenzelm@51221
   804
            find_log(name) match {
wenzelm@51221
   805
              case Some((_, path)) => (path, File.read(path))
wenzelm@51221
   806
              case None => (Path.current, "")
wenzelm@51221
   807
            }
wenzelm@51221
   808
        }
wenzelm@51244
   809
wenzelm@51244
   810
      def ignore_error(msg: String): (List[Properties.T], Double) =
wenzelm@51244
   811
      {
wenzelm@56782
   812
        Output.warning("Ignoring bad log file: " + path + (if (msg == "") "" else "\n" + msg))
wenzelm@51244
   813
        (Nil, 0.0)
wenzelm@51244
   814
      }
wenzelm@51244
   815
wenzelm@51221
   816
      try {
wenzelm@51221
   817
        val info = parse_log(false, text)
wenzelm@51221
   818
        val session_timing = Markup.Elapsed.unapply(info.session_timing) getOrElse 0.0
wenzelm@51221
   819
        (info.command_timings, session_timing)
wenzelm@51220
   820
      }
wenzelm@51221
   821
      catch {
wenzelm@51244
   822
        case ERROR(msg) => ignore_error(msg)
wenzelm@51986
   823
        case exn: java.lang.Error => ignore_error(Exn.message(exn))
wenzelm@51987
   824
        case _: XML.Error => ignore_error("")
wenzelm@51221
   825
      }
wenzelm@51221
   826
    }
wenzelm@51220
   827
wenzelm@51230
   828
    val queue = Queue(selected_tree, load_timings)
wenzelm@51220
   829
wenzelm@51220
   830
wenzelm@51220
   831
    /* main build process */
wenzelm@51220
   832
wenzelm@48373
   833
    // prepare log dir
wenzelm@62628
   834
    Isabelle_System.mkdirs(output_dir + Path.basic("log"))
wenzelm@48373
   835
wenzelm@48595
   836
    // optional cleanup
wenzelm@48595
   837
    if (clean_build) {
wenzelm@49131
   838
      for (name <- full_tree.graph.all_succs(selected)) {
wenzelm@48595
   839
        val files =
wenzelm@48595
   840
          List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
wenzelm@59319
   841
        if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
wenzelm@50366
   842
        if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
wenzelm@48595
   843
      }
wenzelm@48595
   844
    }
wenzelm@48595
   845
wenzelm@48425
   846
    // scheduler loop
wenzelm@62628
   847
    case class Result(current: Boolean, heaps: List[String], process: Option[Process_Result])
wenzelm@62402
   848
    {
wenzelm@62402
   849
      def ok: Boolean =
wenzelm@62402
   850
        process match {
wenzelm@62402
   851
          case None => false
wenzelm@62402
   852
          case Some(res) => res.rc == 0
wenzelm@62402
   853
        }
wenzelm@62402
   854
    }
wenzelm@48639
   855
wenzelm@56837
   856
    def sleep()
wenzelm@56837
   857
    {
wenzelm@56837
   858
      try { Thread.sleep(500) }
wenzelm@56861
   859
      catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
wenzelm@56837
   860
    }
wenzelm@50366
   861
wenzelm@48425
   862
    @tailrec def loop(
wenzelm@48676
   863
      pending: Queue,
wenzelm@62628
   864
      running: Map[String, (List[String], Job)],
wenzelm@48639
   865
      results: Map[String, Result]): Map[String, Result] =
wenzelm@48425
   866
    {
wenzelm@48425
   867
      if (pending.is_empty) results
wenzelm@51253
   868
      else {
wenzelm@51253
   869
        if (progress.stopped)
wenzelm@51253
   870
          for ((_, (_, job)) <- running) job.terminate
wenzelm@51253
   871
wenzelm@48674
   872
        running.find({ case (_, (_, job)) => job.is_finished }) match {
wenzelm@62628
   873
          case Some((name, (input_heaps, job))) =>
wenzelm@50367
   874
            //{{{ finish job
wenzelm@48424
   875
wenzelm@62401
   876
            val process_result = job.join
wenzelm@62573
   877
            process_result.err_lines.foreach(progress.echo(_))
wenzelm@62573
   878
            if (process_result.ok)
wenzelm@62573
   879
              progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
wenzelm@48373
   880
wenzelm@62404
   881
            val process_result_tail =
wenzelm@62404
   882
            {
wenzelm@62404
   883
              val lines = process_result.out_lines.filterNot(_.startsWith("\f"))
wenzelm@62409
   884
              val tail = job.info.options.int("process_output_tail")
wenzelm@62409
   885
              val lines1 = if (tail == 0) lines else lines.drop(lines.length - tail max 0)
wenzelm@62404
   886
              process_result.copy(out_lines =
wenzelm@62409
   887
                "(see also " + (output_dir + log(name)).file.toString + ")" :: lines1)
wenzelm@62404
   888
            }
wenzelm@62404
   889
wenzelm@62628
   890
            val heaps =
wenzelm@62401
   891
              if (process_result.ok) {
wenzelm@48639
   892
                (output_dir + log(name)).file.delete
wenzelm@62628
   893
                val heaps =
wenzelm@62628
   894
                  (for (path <- job.output_path; stamp <- time_stamp(path))
wenzelm@62628
   895
                    yield stamp).toList
wenzelm@48639
   896
wenzelm@48639
   897
                File.write_gzip(output_dir + log_gz(name),
wenzelm@62628
   898
                  Library.terminate_lines(
wenzelm@62628
   899
                    session_sources_stamp(name) ::
wenzelm@62628
   900
                    input_heaps.map(INPUT_HEAP + _) :::
wenzelm@62628
   901
                    heaps.map(OUTPUT_HEAP + _) :::
wenzelm@62628
   902
                    List(LOG_START) ::: process_result.out_lines))
wenzelm@48639
   903
wenzelm@62628
   904
                heaps
wenzelm@48639
   905
              }
wenzelm@48639
   906
              else {
wenzelm@48639
   907
                (output_dir + Path.basic(name)).file.delete
wenzelm@48639
   908
                (output_dir + log_gz(name)).file.delete
wenzelm@48639
   909
wenzelm@62401
   910
                File.write(output_dir + log(name), Library.terminate_lines(process_result.out_lines))
wenzelm@50366
   911
                progress.echo(name + " FAILED")
wenzelm@62404
   912
                if (!process_result.interrupted) progress.echo(process_result_tail.out)
wenzelm@48639
   913
wenzelm@62628
   914
                Nil
wenzelm@48639
   915
              }
wenzelm@50707
   916
            loop(pending - name, running - name,
wenzelm@62628
   917
              results + (name -> Result(false, heaps, Some(process_result_tail))))
wenzelm@50367
   918
            //}}}
wenzelm@60215
   919
          case None if running.size < (max_jobs max 1) =>
wenzelm@50367
   920
            //{{{ check/start next job
wenzelm@48547
   921
            pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48547
   922
              case Some((name, info)) =>
wenzelm@62628
   923
                val ancestor_results = selected_tree.ancestors(name).map(results(_))
wenzelm@62628
   924
                val ancestor_heaps = ancestor_results.map(_.heaps).flatten
wenzelm@62628
   925
wenzelm@48547
   926
                val output = output_dir + Path.basic(name)
wenzelm@62477
   927
                val do_output = build_heap || is_pure(name) || queue.is_inner(name)
wenzelm@48547
   928
wenzelm@62628
   929
                val (current, heaps) =
wenzelm@48547
   930
                {
wenzelm@51221
   931
                  find_log(name + ".gz") match {
wenzelm@51221
   932
                    case Some((dir, path)) =>
wenzelm@51220
   933
                      read_stamps(path) match {
wenzelm@62628
   934
                        case Some((sources, input_heaps, output_heaps)) =>
wenzelm@62628
   935
                          val heaps = time_stamp(dir + Path.basic(name)).toList
wenzelm@62628
   936
                          val current =
wenzelm@62628
   937
                            sources == session_sources_stamp(name) &&
wenzelm@62628
   938
                            input_heaps == ancestor_heaps.map(INPUT_HEAP + _) &&
wenzelm@62628
   939
                            output_heaps == heaps.map(OUTPUT_HEAP + _) &&
wenzelm@62628
   940
                            !(do_output && heaps.isEmpty)
wenzelm@62628
   941
                          (current, heaps)
wenzelm@62628
   942
                        case None => (false, Nil)
wenzelm@48547
   943
                      }
wenzelm@62628
   944
                    case None => (false, Nil)
wenzelm@48504
   945
                  }
wenzelm@48547
   946
                }
wenzelm@62628
   947
                val all_current = current && ancestor_results.forall(_.current)
wenzelm@48528
   948
wenzelm@48547
   949
                if (all_current)
wenzelm@62402
   950
                  loop(pending - name, running,
wenzelm@62628
   951
                    results + (name -> Result(true, heaps, Some(Process_Result(0)))))
wenzelm@48678
   952
                else if (no_build) {
wenzelm@50366
   953
                  if (verbose) progress.echo("Skipping " + name + " ...")
wenzelm@62402
   954
                  loop(pending - name, running,
wenzelm@62628
   955
                    results + (name -> Result(false, heaps, Some(Process_Result(1)))))
wenzelm@48678
   956
                }
wenzelm@62628
   957
                else if (ancestor_results.forall(_.ok) && !progress.stopped) {
wenzelm@50366
   958
                  progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
wenzelm@51220
   959
                  val job =
wenzelm@51220
   960
                    new Job(progress, name, info, output, do_output, verbose, browser_info,
wenzelm@59445
   961
                      deps(name).session_graph, queue.command_timings(name))
wenzelm@62628
   962
                  loop(pending, running + (name -> (ancestor_heaps, job)), results)
wenzelm@48547
   963
                }
wenzelm@48547
   964
                else {
wenzelm@50366
   965
                  progress.echo(name + " CANCELLED")
wenzelm@62628
   966
                  loop(pending - name, running, results + (name -> Result(false, heaps, None)))
wenzelm@48547
   967
                }
wenzelm@48547
   968
              case None => sleep(); loop(pending, running, results)
wenzelm@48425
   969
            }
wenzelm@50367
   970
            ///}}}
wenzelm@48425
   971
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   972
        }
wenzelm@51253
   973
      }
wenzelm@48425
   974
    }
wenzelm@48425
   975
wenzelm@51220
   976
wenzelm@51220
   977
    /* build results */
wenzelm@51220
   978
wenzelm@48583
   979
    val results =
wenzelm@48583
   980
      if (deps.is_empty) {
wenzelm@56782
   981
        progress.echo(Output.warning_text("Nothing to build"))
wenzelm@50707
   982
        Map.empty[String, Result]
wenzelm@48583
   983
      }
wenzelm@48583
   984
      else loop(queue, Map.empty, Map.empty)
wenzelm@48583
   985
wenzelm@51418
   986
wenzelm@51418
   987
    /* global browser info */
wenzelm@51418
   988
wenzelm@51418
   989
    if (!no_build) {
wenzelm@51418
   990
      val browser_chapters =
wenzelm@51418
   991
        (for {
wenzelm@51418
   992
          (name, result) <- results.iterator
wenzelm@62402
   993
          if result.ok && !is_pure(name)
wenzelm@51418
   994
          info = full_tree(name)
wenzelm@51418
   995
          if info.options.bool("browser_info")
wenzelm@51418
   996
        } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
wenzelm@51418
   997
            map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
wenzelm@51418
   998
wenzelm@51418
   999
      for ((chapter, entries) <- browser_chapters)
wenzelm@51418
  1000
        Present.update_chapter_index(browser_info, chapter, entries)
wenzelm@51418
  1001
wenzelm@61372
  1002
      if (browser_chapters.nonEmpty) Present.make_global_index(browser_info)
wenzelm@51418
  1003
    }
wenzelm@51418
  1004
wenzelm@62403
  1005
    new Build_Results((for ((name, result) <- results.iterator) yield (name, result.process)).toMap)
wenzelm@52114
  1006
  }
wenzelm@52114
  1007
wenzelm@52114
  1008
wenzelm@52114
  1009
  /* build */
wenzelm@50707
  1010
wenzelm@52114
  1011
  def build(
wenzelm@52114
  1012
    options: Options,
wenzelm@52115
  1013
    progress: Progress = Ignore_Progress,
wenzelm@52114
  1014
    requirements: Boolean = false,
wenzelm@52114
  1015
    all_sessions: Boolean = false,
wenzelm@52114
  1016
    build_heap: Boolean = false,
wenzelm@52114
  1017
    clean_build: Boolean = false,
wenzelm@56890
  1018
    dirs: List[Path] = Nil,
wenzelm@56890
  1019
    select_dirs: List[Path] = Nil,
wenzelm@60106
  1020
    exclude_session_groups: List[String] = Nil,
wenzelm@52114
  1021
    session_groups: List[String] = Nil,
wenzelm@52114
  1022
    max_jobs: Int = 1,
wenzelm@52114
  1023
    list_files: Boolean = false,
wenzelm@59891
  1024
    check_keywords: Set[String] = Set.empty,
wenzelm@52114
  1025
    no_build: Boolean = false,
wenzelm@52114
  1026
    system_mode: Boolean = false,
wenzelm@52114
  1027
    verbose: Boolean = false,
wenzelm@59892
  1028
    exclude_sessions: List[String] = Nil,
wenzelm@52114
  1029
    sessions: List[String] = Nil): Int =
wenzelm@52114
  1030
  {
wenzelm@52114
  1031
    val results =
wenzelm@59892
  1032
      build_results(options, progress, requirements, all_sessions, build_heap, clean_build,
wenzelm@60106
  1033
        dirs, select_dirs, exclude_session_groups, session_groups, max_jobs, list_files,
wenzelm@60106
  1034
        check_keywords, no_build, system_mode, verbose, exclude_sessions, sessions)
wenzelm@52114
  1035
wenzelm@62403
  1036
    if (results.rc != 0 && (verbose || !no_build)) {
wenzelm@48552
  1037
      val unfinished =
wenzelm@62402
  1038
        (for {
wenzelm@62403
  1039
          name <- results.sessions.iterator
wenzelm@62406
  1040
          if !results(name).ok
wenzelm@62402
  1041
         } yield name).toList.sorted
wenzelm@50366
  1042
      progress.echo("Unfinished session(s): " + commas(unfinished))
wenzelm@48473
  1043
    }
wenzelm@62403
  1044
wenzelm@62403
  1045
    results.rc
wenzelm@48341
  1046
  }
wenzelm@48341
  1047
wenzelm@48341
  1048
wenzelm@48346
  1049
  /* command line entry point */
wenzelm@48341
  1050
wenzelm@48341
  1051
  def main(args: Array[String])
wenzelm@48341
  1052
  {
wenzelm@48346
  1053
    Command_Line.tool {
wenzelm@62590
  1054
      def show_settings(): String =
wenzelm@62590
  1055
        cat_lines(List(
wenzelm@62590
  1056
          "ISABELLE_BUILD_OPTIONS=" +
wenzelm@62590
  1057
            quote(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS")),
wenzelm@62590
  1058
          "ISABELLE_BUILD_JAVA_OPTIONS=" +
wenzelm@62596
  1059
            quote(Isabelle_System.getenv("ISABELLE_BUILD_JAVA_OPTIONS")),
wenzelm@62590
  1060
          "",
wenzelm@62590
  1061
          "ML_PLATFORM=" + quote(Isabelle_System.getenv("ML_PLATFORM")),
wenzelm@62590
  1062
          "ML_HOME=" + quote(Isabelle_System.getenv("ML_HOME")),
wenzelm@62590
  1063
          "ML_SYSTEM=" + quote(Isabelle_System.getenv("ML_SYSTEM")),
wenzelm@62590
  1064
          "ML_OPTIONS=" + quote(Isabelle_System.getenv("ML_OPTIONS"))))
wenzelm@62590
  1065
wenzelm@62590
  1066
      val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
wenzelm@62590
  1067
wenzelm@62590
  1068
      var select_dirs: List[Path] = Nil
wenzelm@62590
  1069
      var requirements = false
wenzelm@62590
  1070
      var exclude_session_groups: List[String] = Nil
wenzelm@62590
  1071
      var all_sessions = false
wenzelm@62590
  1072
      var build_heap = false
wenzelm@62590
  1073
      var clean_build = false
wenzelm@62590
  1074
      var dirs: List[Path] = Nil
wenzelm@62590
  1075
      var session_groups: List[String] = Nil
wenzelm@62590
  1076
      var max_jobs = 1
wenzelm@62590
  1077
      var check_keywords: Set[String] = Set.empty
wenzelm@62590
  1078
      var list_files = false
wenzelm@62590
  1079
      var no_build = false
wenzelm@62590
  1080
      var options = (Options.init() /: build_options)(_ + _)
wenzelm@62590
  1081
      var system_mode = false
wenzelm@62590
  1082
      var verbose = false
wenzelm@62590
  1083
      var exclude_sessions: List[String] = Nil
wenzelm@62590
  1084
wenzelm@62590
  1085
      val getopts = Getopts("""
wenzelm@62590
  1086
Usage: isabelle build [OPTIONS] [SESSIONS ...]
wenzelm@62590
  1087
wenzelm@62590
  1088
  Options are:
wenzelm@62590
  1089
    -D DIR       include session directory and select its sessions
wenzelm@62590
  1090
    -R           operate on requirements of selected sessions
wenzelm@62590
  1091
    -X NAME      exclude sessions from group NAME and all descendants
wenzelm@62590
  1092
    -a           select all sessions
wenzelm@62590
  1093
    -b           build heap images
wenzelm@62590
  1094
    -c           clean build
wenzelm@62590
  1095
    -d DIR       include session directory
wenzelm@62590
  1096
    -g NAME      select session group NAME
wenzelm@62590
  1097
    -j INT       maximum number of parallel jobs (default 1)
wenzelm@62590
  1098
    -k KEYWORD   check theory sources for conflicts with proposed keywords
wenzelm@62590
  1099
    -l           list session source files
wenzelm@62590
  1100
    -n           no build -- test dependencies only
wenzelm@62590
  1101
    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
wenzelm@62590
  1102
    -s           system build mode: produce output in ISABELLE_HOME
wenzelm@62590
  1103
    -v           verbose
wenzelm@62590
  1104
    -x NAME      exclude session NAME and all descendants
wenzelm@62590
  1105
wenzelm@62596
  1106
  Build and manage Isabelle sessions, depending on implicit settings:
wenzelm@62596
  1107
wenzelm@62590
  1108
""" + Library.prefix_lines("  ", show_settings()),
wenzelm@62590
  1109
        "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
wenzelm@62590
  1110
        "R" -> (_ => requirements = true),
wenzelm@62590
  1111
        "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
wenzelm@62590
  1112
        "a" -> (_ => all_sessions = true),
wenzelm@62590
  1113
        "b" -> (_ => build_heap = true),
wenzelm@62590
  1114
        "c" -> (_ => clean_build = true),
wenzelm@62590
  1115
        "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
wenzelm@62590
  1116
        "g:" -> (arg => session_groups = session_groups ::: List(arg)),
wenzelm@62590
  1117
        "j:" -> (arg => max_jobs = Properties.Value.Int.parse(arg)),
wenzelm@62590
  1118
        "k:" -> (arg => check_keywords = check_keywords + arg),
wenzelm@62590
  1119
        "l" -> (_ => list_files = true),
wenzelm@62590
  1120
        "n" -> (_ => no_build = true),
wenzelm@62590
  1121
        "o:" -> (arg => options = options + arg),
wenzelm@62590
  1122
        "s" -> (_ => system_mode = true),
wenzelm@62590
  1123
        "v" -> (_ => verbose = true),
wenzelm@62590
  1124
        "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
wenzelm@62590
  1125
wenzelm@62590
  1126
      val sessions = getopts(args)
wenzelm@62590
  1127
wenzelm@62590
  1128
      val progress = new Console_Progress(verbose)
wenzelm@62590
  1129
wenzelm@62595
  1130
      if (verbose) {
wenzelm@62590
  1131
        progress.echo(
wenzelm@62590
  1132
          Library.trim_line(
wenzelm@62590
  1133
            Isabelle_System.bash(
wenzelm@62596
  1134
              """echo "Started at $(date) ($ML_IDENTIFIER on $(hostname))" """).out) + "\n")
wenzelm@62596
  1135
        progress.echo(show_settings() + "\n")
wenzelm@48341
  1136
      }
wenzelm@62590
  1137
wenzelm@62595
  1138
      val start_time = Time.now()
wenzelm@62590
  1139
      val results =
wenzelm@62590
  1140
        progress.interrupt_handler {
wenzelm@62590
  1141
          build_results(options, progress, requirements, all_sessions, build_heap, clean_build,
wenzelm@62590
  1142
            dirs, select_dirs, exclude_session_groups, session_groups, max_jobs, list_files,
wenzelm@62590
  1143
            check_keywords, no_build, system_mode, verbose, exclude_sessions, sessions)
wenzelm@62590
  1144
        }
wenzelm@62595
  1145
      val elapsed_time = Time.now() - start_time
wenzelm@62590
  1146
wenzelm@62595
  1147
      if (verbose) {
wenzelm@62596
  1148
        progress.echo("\n" +
wenzelm@62590
  1149
          Library.trim_line(
wenzelm@62596
  1150
            Isabelle_System.bash("""echo -n "Finished at "; date""").out))
wenzelm@62595
  1151
      }
wenzelm@62590
  1152
wenzelm@62595
  1153
      val total_timing =
wenzelm@62595
  1154
        (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
wenzelm@62595
  1155
          copy(elapsed = elapsed_time)
wenzelm@62595
  1156
      progress.echo(total_timing.message_resources)
wenzelm@62590
  1157
wenzelm@62590
  1158
      results.rc
wenzelm@48346
  1159
    }
wenzelm@48341
  1160
  }
wenzelm@59366
  1161
wenzelm@59366
  1162
wenzelm@59366
  1163
  /* PIDE protocol */
wenzelm@59366
  1164
wenzelm@59366
  1165
  def build_theories(
wenzelm@59369
  1166
    session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
wenzelm@59367
  1167
      session.get_protocol_handler(classOf[Handler].getName) match {
wenzelm@59366
  1168
        case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
wenzelm@59366
  1169
        case _ => error("Cannot invoke build_theories: bad protocol handler")
wenzelm@59366
  1170
      }
wenzelm@59366
  1171
wenzelm@59367
  1172
  class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
wenzelm@59366
  1173
  {
wenzelm@59369
  1174
    private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
wenzelm@59366
  1175
wenzelm@59366
  1176
    def build_theories(
wenzelm@59369
  1177
      session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
wenzelm@59366
  1178
    {
wenzelm@59369
  1179
      val promise = Future.promise[XML.Body]
wenzelm@59366
  1180
      val id = Document_ID.make().toString
wenzelm@59366
  1181
      pending.change(promises => promises + (id -> promise))
wenzelm@59366
  1182
      session.build_theories(id, master_dir, theories)
wenzelm@59366
  1183
      promise
wenzelm@59366
  1184
    }
wenzelm@59366
  1185
wenzelm@59367
  1186
    private def loading_theory(prover: Prover, msg: Prover.Protocol_Output): Boolean =
wenzelm@59367
  1187
      msg.properties match {
wenzelm@59367
  1188
        case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
wenzelm@59367
  1189
        case _ => false
wenzelm@59367
  1190
      }
wenzelm@59367
  1191
wenzelm@59366
  1192
    private def build_theories_result(prover: Prover, msg: Prover.Protocol_Output): Boolean =
wenzelm@59366
  1193
      msg.properties match {
wenzelm@59369
  1194
        case Markup.Build_Theories_Result(id) =>
wenzelm@59366
  1195
          pending.change_result(promises =>
wenzelm@59366
  1196
            promises.get(id) match {
wenzelm@59369
  1197
              case Some(promise) =>
wenzelm@59369
  1198
                val error_message =
wenzelm@59369
  1199
                  try { YXML.parse_body(Symbol.decode(msg.text)) }
wenzelm@59369
  1200
                  catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
wenzelm@59369
  1201
                promise.fulfill(error_message)
wenzelm@59369
  1202
                (true, promises - id)
wenzelm@59369
  1203
              case None =>
wenzelm@59369
  1204
                (false, promises)
wenzelm@59366
  1205
            })
wenzelm@59366
  1206
        case _ => false
wenzelm@59366
  1207
      }
wenzelm@59366
  1208
wenzelm@59366
  1209
    override def stop(prover: Prover): Unit =
wenzelm@59366
  1210
      pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
wenzelm@59366
  1211
wenzelm@59367
  1212
    val functions =
wenzelm@59367
  1213
      Map(
wenzelm@59367
  1214
        Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
wenzelm@59367
  1215
        Markup.LOADING_THEORY -> loading_theory _)
wenzelm@59366
  1216
  }
wenzelm@48276
  1217
}