src/Pure/Thy/sessions.scala
author wenzelm
Thu Aug 31 16:30:46 2017 +0200 (21 months ago)
changeset 66571 0fdeb24e535e
parent 66243 453f9cabddb5
child 66573 a6401a6417cf
permissions -rw-r--r--
clarified errors;
wenzelm@62631
     1
/*  Title:      Pure/Thy/sessions.scala
wenzelm@62631
     2
    Author:     Makarius
wenzelm@62631
     3
wenzelm@65430
     4
Cumulative session information.
wenzelm@62631
     5
*/
wenzelm@62631
     6
wenzelm@62631
     7
package isabelle
wenzelm@62631
     8
wenzelm@65461
     9
import java.io.{File => JFile}
wenzelm@62704
    10
import java.nio.ByteBuffer
wenzelm@62704
    11
import java.nio.channels.FileChannel
wenzelm@62704
    12
import java.nio.file.StandardOpenOption
wenzelm@62631
    13
wenzelm@62631
    14
import scala.collection.SortedSet
wenzelm@62631
    15
import scala.collection.mutable
wenzelm@62631
    16
wenzelm@62631
    17
wenzelm@62631
    18
object Sessions
wenzelm@62631
    19
{
wenzelm@65360
    20
  /* base info and source dependencies */
wenzelm@62883
    21
wenzelm@65445
    22
  val DRAFT = "Draft"
wenzelm@65445
    23
wenzelm@65360
    24
  def is_pure(name: String): Boolean = name == Thy_Header.PURE
wenzelm@64856
    25
wenzelm@65495
    26
  object Known
wenzelm@64856
    27
  {
wenzelm@65495
    28
    val empty: Known = Known()
wenzelm@65360
    29
wenzelm@65495
    30
    def make(local_dir: Path, bases: List[Base], theories: List[Document.Node.Name]): Known =
wenzelm@65427
    31
    {
wenzelm@65463
    32
      def bases_iterator(local: Boolean) =
wenzelm@65463
    33
        for {
wenzelm@65463
    34
          base <- bases.iterator
wenzelm@65499
    35
          (_, name) <- (if (local) base.known.theories_local else base.known.theories).iterator
wenzelm@65463
    36
        } yield name
wenzelm@65463
    37
wenzelm@65463
    38
      def local_theories_iterator =
wenzelm@65463
    39
      {
wenzelm@65833
    40
        val local_path = local_dir.canonical_file.toPath
wenzelm@65463
    41
        theories.iterator.filter(name =>
wenzelm@65833
    42
          Path.explode(name.node).canonical_file.toPath.startsWith(local_path))
wenzelm@65463
    43
      }
wenzelm@65427
    44
wenzelm@65461
    45
      val known_theories =
wenzelm@65463
    46
        (Map.empty[String, Document.Node.Name] /: (bases_iterator(false) ++ theories.iterator))({
wenzelm@65461
    47
          case (known, name) =>
wenzelm@65461
    48
            known.get(name.theory) match {
wenzelm@65461
    49
              case Some(name1) if name != name1 =>
wenzelm@65461
    50
                error("Duplicate theory " + quote(name.node) + " vs. " + quote(name1.node))
wenzelm@65461
    51
              case _ => known + (name.theory -> name)
wenzelm@65461
    52
            }
wenzelm@65461
    53
          })
wenzelm@65463
    54
      val known_theories_local =
wenzelm@65463
    55
        (Map.empty[String, Document.Node.Name] /:
wenzelm@65463
    56
            (bases_iterator(true) ++ local_theories_iterator))({
wenzelm@65463
    57
          case (known, name) => known + (name.theory -> name)
wenzelm@65463
    58
        })
wenzelm@65461
    59
      val known_files =
wenzelm@65463
    60
        (Map.empty[JFile, List[Document.Node.Name]] /:
wenzelm@65463
    61
            (bases_iterator(true) ++ bases_iterator(false) ++ theories.iterator))({
wenzelm@65461
    62
          case (known, name) =>
wenzelm@65833
    63
            val file = Path.explode(name.node).canonical_file
wenzelm@65463
    64
            val theories1 = known.getOrElse(file, Nil)
wenzelm@65463
    65
            if (theories1.exists(name1 => name.node == name1.node && name.theory == name1.theory))
wenzelm@65461
    66
              known
wenzelm@65463
    67
            else known + (file -> (name :: theories1))
wenzelm@65427
    68
        })
wenzelm@65495
    69
      Known(known_theories, known_theories_local,
wenzelm@65463
    70
        known_files.iterator.map(p => (p._1, p._2.reverse)).toMap)
wenzelm@65427
    71
    }
wenzelm@64856
    72
  }
wenzelm@64856
    73
wenzelm@65495
    74
  sealed case class Known(
wenzelm@65499
    75
    theories: Map[String, Document.Node.Name] = Map.empty,
wenzelm@65499
    76
    theories_local: Map[String, Document.Node.Name] = Map.empty,
wenzelm@65499
    77
    files: Map[JFile, List[Document.Node.Name]] = Map.empty)
wenzelm@65355
    78
  {
wenzelm@65495
    79
    def platform_path: Known =
wenzelm@65499
    80
      copy(theories = for ((a, b) <- theories) yield (a, b.map(File.platform_path(_))),
wenzelm@65499
    81
        theories_local = for ((a, b) <- theories_local) yield (a, b.map(File.platform_path(_))),
wenzelm@65499
    82
        files = for ((a, b) <- files) yield (a, b.map(c => c.map(File.platform_path(_)))))
wenzelm@65524
    83
wenzelm@66195
    84
    def get_file(file: JFile, bootstrap: Boolean = false): Option[Document.Node.Name] =
wenzelm@66195
    85
    {
wenzelm@66234
    86
      val res = files.getOrElse(File.canonical(file), Nil).headOption
wenzelm@66195
    87
      if (bootstrap) res.map(_.map_theory(Thy_Header.bootstrap_name(_))) else res
wenzelm@66195
    88
    }
wenzelm@65495
    89
  }
wenzelm@65495
    90
wenzelm@65495
    91
  object Base
wenzelm@65495
    92
  {
wenzelm@65495
    93
    def pure(options: Options): Base = session_base(options, Thy_Header.PURE)
wenzelm@65495
    94
wenzelm@65495
    95
    def bootstrap(global_theories: Map[String, String]): Base =
wenzelm@65495
    96
      Base(
wenzelm@65495
    97
        global_theories = global_theories,
wenzelm@65495
    98
        keywords = Thy_Header.bootstrap_header,
wenzelm@65495
    99
        syntax = Thy_Header.bootstrap_syntax)
wenzelm@65495
   100
  }
wenzelm@65495
   101
wenzelm@65495
   102
  sealed case class Base(
wenzelm@66571
   103
    pos: Position.T = Position.none,
wenzelm@65540
   104
    imports: Option[Base] = None,
wenzelm@65495
   105
    global_theories: Map[String, String] = Map.empty,
wenzelm@65495
   106
    loaded_theories: Map[String, String] = Map.empty,
wenzelm@65495
   107
    known: Known = Known.empty,
wenzelm@65495
   108
    keywords: Thy_Header.Keywords = Nil,
wenzelm@65495
   109
    syntax: Outer_Syntax = Outer_Syntax.empty,
wenzelm@65495
   110
    sources: List[(Path, SHA1.Digest)] = Nil,
wenzelm@66571
   111
    session_graph: Graph_Display.Graph = Graph_Display.empty_graph,
wenzelm@66571
   112
    errors: List[String] = Nil)
wenzelm@65495
   113
  {
wenzelm@65540
   114
    def get_imports: Base = imports getOrElse Base.bootstrap(global_theories)
wenzelm@65540
   115
wenzelm@65495
   116
    def platform_path: Base = copy(known = known.platform_path)
wenzelm@65463
   117
wenzelm@65355
   118
    def loaded_theory(name: Document.Node.Name): Boolean =
wenzelm@65429
   119
      loaded_theories.isDefinedAt(name.theory)
wenzelm@65432
   120
wenzelm@65498
   121
    def known_theory(name: String): Option[Document.Node.Name] =
wenzelm@65499
   122
      known.theories.get(name)
wenzelm@65498
   123
wenzelm@65432
   124
    def dest_known_theories: List[(String, String)] =
wenzelm@65499
   125
      for ((theory, node_name) <- known.theories.toList)
wenzelm@65432
   126
        yield (theory, node_name.node)
wenzelm@65355
   127
  }
wenzelm@64856
   128
wenzelm@65495
   129
  sealed case class Deps(session_bases: Map[String, Base], all_known: Known)
wenzelm@65251
   130
  {
wenzelm@65463
   131
    def is_empty: Boolean = session_bases.isEmpty
wenzelm@65463
   132
    def apply(name: String): Base = session_bases(name)
wenzelm@65463
   133
    def sources(name: String): List[SHA1.Digest] = session_bases(name).sources.map(_._2)
wenzelm@66571
   134
wenzelm@66571
   135
    def errors: List[String] =
wenzelm@66571
   136
      (for {
wenzelm@66571
   137
        (name, base) <- session_bases.iterator
wenzelm@66571
   138
        if base.errors.nonEmpty
wenzelm@66571
   139
      } yield cat_lines(base.errors) +
wenzelm@66571
   140
          "\nThe error(s) above occurred in session " + quote(name) + Position.here(base.pos)
wenzelm@66571
   141
      ).toList
wenzelm@66571
   142
wenzelm@66571
   143
    def check_errors: Deps =
wenzelm@66571
   144
      errors match {
wenzelm@66571
   145
        case Nil => this
wenzelm@66571
   146
        case errs => error(cat_lines(errs))
wenzelm@66571
   147
      }
wenzelm@65251
   148
  }
wenzelm@64856
   149
wenzelm@65415
   150
  def deps(sessions: T,
wenzelm@65251
   151
      progress: Progress = No_Progress,
wenzelm@65251
   152
      inlined_files: Boolean = false,
wenzelm@65251
   153
      verbose: Boolean = false,
wenzelm@65251
   154
      list_files: Boolean = false,
wenzelm@65251
   155
      check_keywords: Set[String] = Set.empty,
wenzelm@65463
   156
      global_theories: Map[String, String] = Map.empty,
wenzelm@65495
   157
      all_known: Boolean = false): Deps =
wenzelm@65372
   158
  {
wenzelm@65463
   159
    val session_bases =
wenzelm@65463
   160
      (Map.empty[String, Base] /: sessions.imports_topological_order)({
wenzelm@65519
   161
        case (session_bases, info) =>
wenzelm@65463
   162
          if (progress.stopped) throw Exn.Interrupt()
wenzelm@65251
   163
wenzelm@65463
   164
          try {
wenzelm@65496
   165
            val parent_base: Sessions.Base =
wenzelm@65463
   166
              info.parent match {
wenzelm@65475
   167
                case None => Base.bootstrap(global_theories)
wenzelm@65463
   168
                case Some(parent) => session_bases(parent)
wenzelm@65463
   169
              }
wenzelm@65496
   170
            val imports_base: Sessions.Base =
wenzelm@65496
   171
              parent_base.copy(known =
wenzelm@65496
   172
                Known.make(info.dir, parent_base :: info.imports.map(session_bases(_)), Nil))
wenzelm@65496
   173
wenzelm@65532
   174
            val resources = new Resources(imports_base)
wenzelm@65251
   175
wenzelm@65463
   176
            if (verbose || list_files) {
wenzelm@65463
   177
              val groups =
wenzelm@65463
   178
                if (info.groups.isEmpty) ""
wenzelm@65463
   179
                else info.groups.mkString(" (", " ", ")")
wenzelm@65519
   180
              progress.echo("Session " + info.chapter + "/" + info.name + groups)
wenzelm@65463
   181
            }
wenzelm@65251
   182
wenzelm@65463
   183
            val thy_deps =
wenzelm@65463
   184
            {
wenzelm@65463
   185
              val root_theories =
wenzelm@65463
   186
                info.theories.flatMap({ case (_, thys) =>
wenzelm@65517
   187
                  thys.map({ case (thy, pos) =>
wenzelm@65528
   188
                    (resources.import_name(info.theory_qualifier, info.dir.implode, thy), pos) })
wenzelm@65463
   189
                })
wenzelm@66571
   190
              resources.thy_info.dependencies(root_theories)
wenzelm@65251
   191
            }
wenzelm@65251
   192
wenzelm@65463
   193
            val syntax = thy_deps.syntax
wenzelm@65251
   194
wenzelm@65463
   195
            val theory_files = thy_deps.deps.map(dep => Path.explode(dep.name.node))
wenzelm@65463
   196
            val loaded_files =
wenzelm@65463
   197
              if (inlined_files) {
wenzelm@65463
   198
                val pure_files =
wenzelm@65519
   199
                  if (is_pure(info.name)) {
wenzelm@65463
   200
                    val roots = Thy_Header.ml_roots.map(p => info.dir + Path.explode(p._1))
wenzelm@65463
   201
                    val files =
wenzelm@65463
   202
                      roots.flatMap(root => resources.loaded_files(syntax, File.read(root))).
wenzelm@65463
   203
                        map(file => info.dir + Path.explode(file))
wenzelm@65463
   204
                    roots ::: files
wenzelm@65463
   205
                  }
wenzelm@65463
   206
                  else Nil
wenzelm@65463
   207
                pure_files ::: thy_deps.loaded_files
wenzelm@65463
   208
              }
wenzelm@65463
   209
              else Nil
wenzelm@65251
   210
wenzelm@65463
   211
            val all_files =
wenzelm@65463
   212
              (theory_files ::: loaded_files :::
wenzelm@65463
   213
                info.files.map(file => info.dir + file) :::
wenzelm@65463
   214
                info.document_files.map(file => info.dir + file._1 + file._2)).map(_.expand)
wenzelm@65463
   215
wenzelm@65463
   216
            if (list_files)
wenzelm@65463
   217
              progress.echo(cat_lines(all_files.map(_.implode).sorted.map("  " + _)))
wenzelm@65463
   218
wenzelm@65463
   219
            if (check_keywords.nonEmpty)
wenzelm@65463
   220
              Check_Keywords.check_keywords(progress, syntax.keywords, check_keywords, theory_files)
wenzelm@65251
   221
wenzelm@65507
   222
            val session_graph: Graph_Display.Graph =
wenzelm@65507
   223
            {
wenzelm@65507
   224
              def session_node(name: String): Graph_Display.Node =
wenzelm@65507
   225
                Graph_Display.Node("[" + name + "]", "session." + name)
wenzelm@65507
   226
wenzelm@65507
   227
              def node(name: Document.Node.Name): Graph_Display.Node =
wenzelm@65507
   228
              {
wenzelm@65528
   229
                val qualifier = resources.theory_qualifier(name)
wenzelm@65528
   230
                if (qualifier == info.theory_qualifier)
wenzelm@65507
   231
                  Graph_Display.Node(name.theory_base_name, "theory." + name.theory)
wenzelm@65528
   232
                else session_node(qualifier)
wenzelm@65507
   233
              }
wenzelm@65507
   234
wenzelm@65507
   235
              val imports_subgraph =
wenzelm@65507
   236
                sessions.imports_graph.restrict(
wenzelm@65507
   237
                  sessions.imports_graph.all_preds(info.parent.toList ::: info.imports).toSet)
wenzelm@65507
   238
wenzelm@65507
   239
              val graph0 =
wenzelm@65507
   240
                (Graph_Display.empty_graph /: imports_subgraph.topological_order)(
wenzelm@65507
   241
                  { case (g, session) =>
wenzelm@65507
   242
                      val a = session_node(session)
wenzelm@65507
   243
                      val bs = imports_subgraph.imm_preds(session).toList.map(session_node(_))
wenzelm@65507
   244
                      ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
wenzelm@65507
   245
wenzelm@65507
   246
              (graph0 /: thy_deps.deps)(
wenzelm@65507
   247
                { case (g, dep) =>
wenzelm@65507
   248
                    val a = node(dep.name)
wenzelm@65507
   249
                    val bs =
wenzelm@65507
   250
                      dep.header.imports.map({ case (name, _) => node(name) }).
wenzelm@65507
   251
                        filterNot(_ == a)
wenzelm@65507
   252
                    ((g /: (a :: bs))(_.default_node(_, Nil)) /: bs)(_.add_edge(_, a)) })
wenzelm@65507
   253
            }
wenzelm@65507
   254
wenzelm@65463
   255
            val base =
wenzelm@66571
   256
              Base(
wenzelm@66571
   257
                pos = info.pos,
wenzelm@66571
   258
                imports = Some(imports_base),
wenzelm@65540
   259
                global_theories = global_theories,
wenzelm@65463
   260
                loaded_theories = thy_deps.loaded_theories,
wenzelm@65496
   261
                known = Known.make(info.dir, List(imports_base), thy_deps.deps.map(_.name)),
wenzelm@65463
   262
                keywords = thy_deps.keywords,
wenzelm@65463
   263
                syntax = syntax,
wenzelm@65463
   264
                sources = all_files.map(p => (p, SHA1.digest(p.file))),
wenzelm@66571
   265
                session_graph = session_graph,
wenzelm@66571
   266
                errors = thy_deps.errors)
wenzelm@65251
   267
wenzelm@65519
   268
            session_bases + (info.name -> base)
wenzelm@65463
   269
          }
wenzelm@65463
   270
          catch {
wenzelm@65463
   271
            case ERROR(msg) =>
wenzelm@65463
   272
              cat_error(msg, "The error(s) above occurred in session " +
wenzelm@65519
   273
                quote(info.name) + Position.here(info.pos))
wenzelm@65463
   274
          }
wenzelm@65463
   275
      })
wenzelm@65251
   276
wenzelm@65496
   277
    Deps(session_bases,
wenzelm@65495
   278
      if (all_known) Known.make(Path.current, session_bases.toList.map(_._2), Nil)
wenzelm@65496
   279
      else Known.empty)
wenzelm@65372
   280
  }
wenzelm@65251
   281
wenzelm@66571
   282
  def session_base_errors(
wenzelm@65428
   283
    options: Options,
wenzelm@65428
   284
    session: String,
wenzelm@65428
   285
    dirs: List[Path] = Nil,
wenzelm@66571
   286
    all_known: Boolean = false): (List[String], Base) =
wenzelm@65251
   287
  {
wenzelm@65415
   288
    val full_sessions = load(options, dirs = dirs)
wenzelm@65428
   289
    val global_theories = full_sessions.global_theories
wenzelm@65428
   290
    val selected_sessions = full_sessions.selection(Selection(sessions = List(session)))._2
wenzelm@65372
   291
wenzelm@65495
   292
    if (all_known) {
wenzelm@66243
   293
      val deps =
wenzelm@66243
   294
        Sessions.deps(full_sessions, global_theories = global_theories, all_known = all_known)
wenzelm@66571
   295
      (deps.errors, deps(session).copy(known = deps.all_known))
wenzelm@66571
   296
    }
wenzelm@66571
   297
    else {
wenzelm@66571
   298
      val deps =
wenzelm@66571
   299
        Sessions.deps(selected_sessions, global_theories = global_theories)
wenzelm@66571
   300
      (deps.errors, deps(session))
wenzelm@65428
   301
    }
wenzelm@66571
   302
  }
wenzelm@66571
   303
wenzelm@66571
   304
  def session_base(
wenzelm@66571
   305
    options: Options,
wenzelm@66571
   306
    session: String,
wenzelm@66571
   307
    dirs: List[Path] = Nil,
wenzelm@66571
   308
    all_known: Boolean = false): Base =
wenzelm@66571
   309
  {
wenzelm@66571
   310
    session_base_errors(options, session, dirs = dirs, all_known = all_known) match {
wenzelm@66571
   311
      case (Nil, base) => base
wenzelm@66571
   312
      case (errs, _) => error(cat_lines(errs))
wenzelm@66571
   313
    }
wenzelm@65251
   314
  }
wenzelm@65251
   315
wenzelm@65251
   316
wenzelm@65415
   317
  /* cumulative session info */
wenzelm@62631
   318
wenzelm@62631
   319
  sealed case class Info(
wenzelm@65519
   320
    name: String,
wenzelm@62631
   321
    chapter: String,
wenzelm@62631
   322
    select: Boolean,
wenzelm@62631
   323
    pos: Position.T,
wenzelm@62631
   324
    groups: List[String],
wenzelm@62631
   325
    dir: Path,
wenzelm@62631
   326
    parent: Option[String],
wenzelm@62631
   327
    description: String,
wenzelm@62631
   328
    options: Options,
wenzelm@65420
   329
    imports: List[String],
wenzelm@65517
   330
    theories: List[(Options, List[(String, Position.T)])],
wenzelm@65374
   331
    global_theories: List[String],
wenzelm@62631
   332
    files: List[Path],
wenzelm@62631
   333
    document_files: List[(Path, Path)],
wenzelm@62631
   334
    meta_digest: SHA1.Digest)
wenzelm@62631
   335
  {
wenzelm@62631
   336
    def timeout: Time = Time.seconds(options.real("timeout") * options.real("timeout_scale"))
wenzelm@65456
   337
wenzelm@65520
   338
    def theory_qualifier: String =
wenzelm@65456
   339
      options.string("theory_qualifier") match {
wenzelm@65520
   340
        case "" => name
wenzelm@65457
   341
        case qualifier => qualifier
wenzelm@65456
   342
      }
wenzelm@62631
   343
  }
wenzelm@62631
   344
wenzelm@65419
   345
  object Selection
wenzelm@65419
   346
  {
wenzelm@65422
   347
    val empty: Selection = Selection()
wenzelm@65525
   348
    val all: Selection = Selection(all_sessions = true)
wenzelm@65419
   349
  }
wenzelm@65419
   350
wenzelm@65419
   351
  sealed case class Selection(
wenzelm@65419
   352
    requirements: Boolean = false,
wenzelm@65419
   353
    all_sessions: Boolean = false,
wenzelm@65419
   354
    exclude_session_groups: List[String] = Nil,
wenzelm@65419
   355
    exclude_sessions: List[String] = Nil,
wenzelm@65419
   356
    session_groups: List[String] = Nil,
wenzelm@65419
   357
    sessions: List[String] = Nil)
wenzelm@65419
   358
  {
wenzelm@65422
   359
    def + (other: Selection): Selection =
wenzelm@65422
   360
      Selection(
wenzelm@65422
   361
        requirements = requirements || other.requirements,
wenzelm@65422
   362
        all_sessions = all_sessions || other.all_sessions,
wenzelm@65422
   363
        exclude_session_groups = exclude_session_groups ::: other.exclude_session_groups,
wenzelm@65422
   364
        exclude_sessions = exclude_sessions ::: other.exclude_sessions,
wenzelm@65422
   365
        session_groups = session_groups ::: other.session_groups,
wenzelm@65422
   366
        sessions = sessions ::: other.sessions)
wenzelm@65422
   367
wenzelm@65419
   368
    def apply(graph: Graph[String, Info]): (List[String], Graph[String, Info]) =
wenzelm@65419
   369
    {
wenzelm@65419
   370
      val bad_sessions =
wenzelm@65419
   371
        SortedSet((exclude_sessions ::: sessions).filterNot(graph.defined(_)): _*).toList
wenzelm@65419
   372
      if (bad_sessions.nonEmpty) error("Undefined session(s): " + commas_quote(bad_sessions))
wenzelm@65419
   373
wenzelm@65419
   374
      val excluded =
wenzelm@65419
   375
      {
wenzelm@65419
   376
        val exclude_group = exclude_session_groups.toSet
wenzelm@65419
   377
        val exclude_group_sessions =
wenzelm@65419
   378
          (for {
wenzelm@65419
   379
            (name, (info, _)) <- graph.iterator
wenzelm@65419
   380
            if graph.get_node(name).groups.exists(exclude_group)
wenzelm@65419
   381
          } yield name).toList
wenzelm@65419
   382
        graph.all_succs(exclude_group_sessions ::: exclude_sessions).toSet
wenzelm@65419
   383
      }
wenzelm@65419
   384
wenzelm@65419
   385
      val pre_selected =
wenzelm@65419
   386
      {
wenzelm@65419
   387
        if (all_sessions) graph.keys
wenzelm@65419
   388
        else {
wenzelm@65419
   389
          val select_group = session_groups.toSet
wenzelm@65419
   390
          val select = sessions.toSet
wenzelm@65419
   391
          (for {
wenzelm@65419
   392
            (name, (info, _)) <- graph.iterator
wenzelm@65419
   393
            if info.select || select(name) || graph.get_node(name).groups.exists(select_group)
wenzelm@65419
   394
          } yield name).toList
wenzelm@65419
   395
        }
wenzelm@65419
   396
      }.filterNot(excluded)
wenzelm@65419
   397
wenzelm@65419
   398
      val selected =
wenzelm@65419
   399
        if (requirements) (graph.all_preds(pre_selected).toSet -- pre_selected).toList
wenzelm@65419
   400
        else pre_selected
wenzelm@65419
   401
wenzelm@65419
   402
      (selected, graph.restrict(graph.all_preds(selected).toSet))
wenzelm@65419
   403
    }
wenzelm@65419
   404
  }
wenzelm@65419
   405
wenzelm@65415
   406
  def make(infos: Traversable[(String, Info)]): T =
wenzelm@62631
   407
  {
wenzelm@65420
   408
    def add_edges(graph: Graph[String, Info], kind: String, edges: Info => Traversable[String])
wenzelm@65420
   409
      : Graph[String, Info] =
wenzelm@65420
   410
    {
wenzelm@65420
   411
      def add_edge(pos: Position.T, name: String, g: Graph[String, Info], parent: String) =
wenzelm@65420
   412
      {
wenzelm@65420
   413
        if (!g.defined(parent))
wenzelm@65420
   414
          error("Bad " + kind + " session " + quote(parent) + " for " +
wenzelm@65420
   415
            quote(name) + Position.here(pos))
wenzelm@65420
   416
wenzelm@65420
   417
        try { g.add_edge_acyclic(parent, name) }
wenzelm@65420
   418
        catch {
wenzelm@65420
   419
          case exn: Graph.Cycles[_] =>
wenzelm@65420
   420
            error(cat_lines(exn.cycles.map(cycle =>
wenzelm@65420
   421
              "Cyclic session dependency of " +
wenzelm@65420
   422
                cycle.map(c => quote(c.toString)).mkString(" via "))) + Position.here(pos))
wenzelm@65420
   423
        }
wenzelm@65420
   424
      }
wenzelm@65420
   425
      (graph /: graph.iterator) {
wenzelm@65420
   426
        case (g, (name, (info, _))) => (g /: edges(info))(add_edge(info.pos, name, _, _))
wenzelm@65420
   427
      }
wenzelm@65420
   428
    }
wenzelm@65420
   429
wenzelm@65420
   430
    val graph0 =
wenzelm@65415
   431
      (Graph.string[Info] /: infos) {
wenzelm@65415
   432
        case (graph, (name, info)) =>
wenzelm@65415
   433
          if (graph.defined(name))
wenzelm@65415
   434
            error("Duplicate session " + quote(name) + Position.here(info.pos) +
wenzelm@65415
   435
              Position.here(graph.get_node(name).pos))
wenzelm@65415
   436
          else graph.new_node(name, info)
wenzelm@65415
   437
      }
wenzelm@65420
   438
    val graph1 = add_edges(graph0, "parent", _.parent)
wenzelm@65420
   439
    val graph2 = add_edges(graph1, "imports", _.imports)
wenzelm@62631
   440
wenzelm@65420
   441
    new T(graph1, graph2)
wenzelm@62631
   442
  }
wenzelm@62631
   443
wenzelm@65420
   444
  final class T private[Sessions](
wenzelm@65420
   445
      val build_graph: Graph[String, Info],
wenzelm@65420
   446
      val imports_graph: Graph[String, Info])
wenzelm@62631
   447
  {
wenzelm@65420
   448
    def apply(name: String): Info = imports_graph.get_node(name)
wenzelm@65420
   449
    def get(name: String): Option[Info] =
wenzelm@65420
   450
      if (imports_graph.defined(name)) Some(imports_graph.get_node(name)) else None
wenzelm@62631
   451
wenzelm@65457
   452
    def global_theories: Map[String, String] =
wenzelm@65490
   453
      (Thy_Header.bootstrap_global_theories.toMap /:
wenzelm@65424
   454
        (for {
wenzelm@65519
   455
          (_, (info, _)) <- imports_graph.iterator
wenzelm@65519
   456
          thy <- info.global_theories.iterator }
wenzelm@65519
   457
         yield (thy, info)))({
wenzelm@65519
   458
            case (global, (thy, info)) =>
wenzelm@65520
   459
              val qualifier = info.theory_qualifier
wenzelm@65457
   460
              global.get(thy) match {
wenzelm@65457
   461
                case Some(qualifier1) if qualifier != qualifier1 =>
wenzelm@65457
   462
                  error("Duplicate global theory " + quote(thy) + Position.here(info.pos))
wenzelm@65457
   463
                case _ => global + (thy -> qualifier)
wenzelm@65457
   464
              }
wenzelm@65457
   465
          })
wenzelm@65372
   466
wenzelm@65419
   467
    def selection(select: Selection): (List[String], T) =
wenzelm@62631
   468
    {
wenzelm@65420
   469
      val (_, build_graph1) = select(build_graph)
wenzelm@65420
   470
      val (selected, imports_graph1) = select(imports_graph)
wenzelm@65420
   471
      (selected, new T(build_graph1, imports_graph1))
wenzelm@62631
   472
    }
wenzelm@62631
   473
wenzelm@65420
   474
    def build_ancestors(name: String): List[String] =
wenzelm@65420
   475
      build_graph.all_preds(List(name)).tail.reverse
wenzelm@65420
   476
wenzelm@65420
   477
    def build_descendants(names: List[String]): List[String] =
wenzelm@65420
   478
      build_graph.all_succs(names)
wenzelm@62631
   479
wenzelm@65519
   480
    def build_topological_order: List[Info] =
wenzelm@65519
   481
      build_graph.topological_order.map(apply(_))
wenzelm@62631
   482
wenzelm@65566
   483
    def imports_ancestors(name: String): List[String] =
wenzelm@65566
   484
      imports_graph.all_preds(List(name)).tail.reverse
wenzelm@65566
   485
wenzelm@65519
   486
    def imports_topological_order: List[Info] =
wenzelm@65519
   487
      imports_graph.topological_order.map(apply(_))
wenzelm@65420
   488
wenzelm@65420
   489
    override def toString: String =
wenzelm@65420
   490
      imports_graph.keys_iterator.mkString("Sessions.T(", ", ", ")")
wenzelm@62631
   491
  }
wenzelm@62631
   492
wenzelm@62631
   493
wenzelm@62631
   494
  /* parser */
wenzelm@62631
   495
wenzelm@62864
   496
  val ROOT = Path.explode("ROOT")
wenzelm@62864
   497
  val ROOTS = Path.explode("ROOTS")
wenzelm@62864
   498
wenzelm@62631
   499
  private val CHAPTER = "chapter"
wenzelm@62631
   500
  private val SESSION = "session"
wenzelm@62631
   501
  private val IN = "in"
wenzelm@62631
   502
  private val DESCRIPTION = "description"
wenzelm@62631
   503
  private val OPTIONS = "options"
wenzelm@65420
   504
  private val SESSIONS = "sessions"
wenzelm@62631
   505
  private val THEORIES = "theories"
wenzelm@65374
   506
  private val GLOBAL = "global"
wenzelm@62631
   507
  private val FILES = "files"
wenzelm@62631
   508
  private val DOCUMENT_FILES = "document_files"
wenzelm@62631
   509
wenzelm@62631
   510
  lazy val root_syntax =
wenzelm@65374
   511
    Outer_Syntax.init() + "(" + ")" + "+" + "," + "=" + "[" + "]" + GLOBAL + IN +
wenzelm@63443
   512
      (CHAPTER, Keyword.THY_DECL) +
wenzelm@63443
   513
      (SESSION, Keyword.THY_DECL) +
wenzelm@63443
   514
      (DESCRIPTION, Keyword.QUASI_COMMAND) +
wenzelm@63443
   515
      (OPTIONS, Keyword.QUASI_COMMAND) +
wenzelm@65420
   516
      (SESSIONS, Keyword.QUASI_COMMAND) +
wenzelm@63443
   517
      (THEORIES, Keyword.QUASI_COMMAND) +
wenzelm@63443
   518
      (FILES, Keyword.QUASI_COMMAND) +
wenzelm@63443
   519
      (DOCUMENT_FILES, Keyword.QUASI_COMMAND)
wenzelm@62631
   520
wenzelm@62968
   521
  private object Parser extends Parse.Parser with Options.Parser
wenzelm@62631
   522
  {
wenzelm@62631
   523
    private abstract class Entry
wenzelm@62631
   524
    private sealed case class Chapter(name: String) extends Entry
wenzelm@62631
   525
    private sealed case class Session_Entry(
wenzelm@62631
   526
      pos: Position.T,
wenzelm@62631
   527
      name: String,
wenzelm@62631
   528
      groups: List[String],
wenzelm@62631
   529
      path: String,
wenzelm@62631
   530
      parent: Option[String],
wenzelm@62631
   531
      description: String,
wenzelm@62631
   532
      options: List[Options.Spec],
wenzelm@65420
   533
      imports: List[String],
wenzelm@65517
   534
      theories: List[(List[Options.Spec], List[((String, Position.T), Boolean)])],
wenzelm@62631
   535
      files: List[String],
wenzelm@62631
   536
      document_files: List[(String, String)]) extends Entry
wenzelm@65580
   537
    {
wenzelm@65580
   538
      def theories_no_position: List[(List[Options.Spec], List[(String, Boolean)])] =
wenzelm@65580
   539
        theories.map({ case (a, b) => (a, b.map({ case ((c, _), d) => (c, d) })) })
wenzelm@65580
   540
    }
wenzelm@62631
   541
wenzelm@62631
   542
    private val chapter: Parser[Chapter] =
wenzelm@62631
   543
    {
wenzelm@62631
   544
      val chapter_name = atom("chapter name", _.is_name)
wenzelm@62631
   545
wenzelm@62631
   546
      command(CHAPTER) ~! chapter_name ^^ { case _ ~ a => Chapter(a) }
wenzelm@62631
   547
    }
wenzelm@62631
   548
wenzelm@62631
   549
    private val session_entry: Parser[Session_Entry] =
wenzelm@62631
   550
    {
wenzelm@62631
   551
      val session_name = atom("session name", _.is_name)
wenzelm@62631
   552
wenzelm@62631
   553
      val option =
wenzelm@62968
   554
        option_name ~ opt($$$("=") ~! option_value ^^
wenzelm@62968
   555
          { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@62631
   556
      val options = $$$("[") ~> rep1sep(option, $$$(",")) <~ $$$("]")
wenzelm@62631
   557
wenzelm@65374
   558
      val global =
wenzelm@65374
   559
        ($$$("(") ~! $$$(GLOBAL) ~ $$$(")")) ^^ { case _ => true } | success(false)
wenzelm@65374
   560
wenzelm@65374
   561
      val theory_entry =
wenzelm@65517
   562
        position(theory_name) ~ global ^^ { case x ~ y => (x, y) }
wenzelm@65374
   563
wenzelm@62631
   564
      val theories =
wenzelm@65374
   565
        $$$(THEORIES) ~!
wenzelm@65374
   566
          ((options | success(Nil)) ~ rep(theory_entry)) ^^
wenzelm@65374
   567
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@62631
   568
wenzelm@62631
   569
      val document_files =
wenzelm@62631
   570
        $$$(DOCUMENT_FILES) ~!
wenzelm@62631
   571
          (($$$("(") ~! ($$$(IN) ~! (path ~ $$$(")"))) ^^
wenzelm@62631
   572
              { case _ ~ (_ ~ (x ~ _)) => x } | success("document")) ~
wenzelm@62631
   573
            rep1(path)) ^^ { case _ ~ (x ~ y) => y.map((x, _)) }
wenzelm@62631
   574
wenzelm@62631
   575
      command(SESSION) ~!
wenzelm@62631
   576
        (position(session_name) ~
wenzelm@62631
   577
          (($$$("(") ~! (rep1(name) <~ $$$(")")) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   578
          (($$$(IN) ~! path ^^ { case _ ~ x => x }) | success(".")) ~
wenzelm@62631
   579
          ($$$("=") ~!
wenzelm@62631
   580
            (opt(session_name ~! $$$("+") ^^ { case x ~ _ => x }) ~
wenzelm@62631
   581
              (($$$(DESCRIPTION) ~! text ^^ { case _ ~ x => x }) | success("")) ~
wenzelm@62631
   582
              (($$$(OPTIONS) ~! options ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@65420
   583
              (($$$(SESSIONS) ~! rep(session_name)  ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   584
              rep1(theories) ~
wenzelm@62631
   585
              (($$$(FILES) ~! rep1(path) ^^ { case _ ~ x => x }) | success(Nil)) ~
wenzelm@62631
   586
              (rep(document_files) ^^ (x => x.flatten))))) ^^
wenzelm@65420
   587
        { case _ ~ ((a, pos) ~ b ~ c ~ (_ ~ (d ~ e ~ f ~ g ~ h ~ i ~ j))) =>
wenzelm@65420
   588
            Session_Entry(pos, a, b, c, d, e, f, g, h, i, j) }
wenzelm@62631
   589
    }
wenzelm@62631
   590
wenzelm@62631
   591
    def parse(options: Options, select: Boolean, dir: Path): List[(String, Info)] =
wenzelm@62631
   592
    {
wenzelm@62631
   593
      def make_info(entry_chapter: String, entry: Session_Entry): (String, Info) =
wenzelm@62631
   594
      {
wenzelm@62631
   595
        try {
wenzelm@62631
   596
          val name = entry.name
wenzelm@62631
   597
wenzelm@65445
   598
          if (name == "" || name == DRAFT) error("Bad session name")
wenzelm@65360
   599
          if (is_pure(name) && entry.parent.isDefined) error("Illegal parent session")
wenzelm@65360
   600
          if (!is_pure(name) && !entry.parent.isDefined) error("Missing parent session")
wenzelm@62631
   601
wenzelm@62631
   602
          val session_options = options ++ entry.options
wenzelm@62631
   603
wenzelm@62631
   604
          val theories =
wenzelm@65392
   605
            entry.theories.map({ case (opts, thys) => (session_options ++ opts, thys.map(_._1)) })
wenzelm@65374
   606
wenzelm@65374
   607
          val global_theories =
wenzelm@65517
   608
            for { (_, thys) <- entry.theories; ((thy, pos), global) <- thys if global }
wenzelm@65374
   609
            yield {
wenzelm@65999
   610
              val thy_name = Path.explode(thy).expand.base_name
wenzelm@65374
   611
              if (Long_Name.is_qualified(thy_name))
wenzelm@65517
   612
                error("Bad qualified name for global theory " +
wenzelm@65517
   613
                  quote(thy_name) + Position.here(pos))
wenzelm@65374
   614
              else thy_name
wenzelm@65374
   615
            }
wenzelm@65374
   616
wenzelm@62631
   617
          val files = entry.files.map(Path.explode(_))
wenzelm@62631
   618
          val document_files =
wenzelm@62631
   619
            entry.document_files.map({ case (s1, s2) => (Path.explode(s1), Path.explode(s2)) })
wenzelm@62631
   620
wenzelm@62631
   621
          val meta_digest =
wenzelm@65580
   622
            SHA1.digest((entry_chapter, name, entry.parent, entry.options, entry.imports,
wenzelm@65580
   623
              entry.theories_no_position, entry.files, entry.document_files).toString)
wenzelm@62631
   624
wenzelm@62631
   625
          val info =
wenzelm@65519
   626
            Info(name, entry_chapter, select, entry.pos, entry.groups,
wenzelm@65519
   627
              dir + Path.explode(entry.path), entry.parent, entry.description, session_options,
wenzelm@65519
   628
              entry.imports, theories, global_theories, files, document_files, meta_digest)
wenzelm@62631
   629
wenzelm@62631
   630
          (name, info)
wenzelm@62631
   631
        }
wenzelm@62631
   632
        catch {
wenzelm@62631
   633
          case ERROR(msg) =>
wenzelm@62631
   634
            error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@62631
   635
              quote(entry.name) + Position.here(entry.pos))
wenzelm@62631
   636
        }
wenzelm@62631
   637
      }
wenzelm@62631
   638
wenzelm@62631
   639
      val root = dir + ROOT
wenzelm@62631
   640
      if (root.is_file) {
wenzelm@62631
   641
        val toks = Token.explode(root_syntax.keywords, File.read(root))
wenzelm@62631
   642
        val start = Token.Pos.file(root.implode)
wenzelm@62631
   643
wenzelm@62631
   644
        parse_all(rep(chapter | session_entry), Token.reader(toks, start)) match {
wenzelm@62631
   645
          case Success(result, _) =>
wenzelm@62631
   646
            var entry_chapter = "Unsorted"
wenzelm@62631
   647
            val infos = new mutable.ListBuffer[(String, Info)]
wenzelm@62631
   648
            result.foreach {
wenzelm@62631
   649
              case Chapter(name) => entry_chapter = name
wenzelm@62631
   650
              case entry: Session_Entry => infos += make_info(entry_chapter, entry)
wenzelm@62631
   651
            }
wenzelm@62631
   652
            infos.toList
wenzelm@62631
   653
          case bad => error(bad.toString)
wenzelm@62631
   654
        }
wenzelm@62631
   655
      }
wenzelm@62631
   656
      else Nil
wenzelm@62631
   657
    }
wenzelm@62631
   658
  }
wenzelm@62631
   659
wenzelm@62631
   660
wenzelm@62635
   661
  /* load sessions from certain directories */
wenzelm@62631
   662
wenzelm@62631
   663
  private def is_session_dir(dir: Path): Boolean =
wenzelm@62631
   664
    (dir + ROOT).is_file || (dir + ROOTS).is_file
wenzelm@62631
   665
wenzelm@62631
   666
  private def check_session_dir(dir: Path): Path =
wenzelm@65468
   667
    if (is_session_dir(dir)) File.pwd() + dir.expand
wenzelm@62631
   668
    else error("Bad session root directory: " + dir.toString)
wenzelm@62631
   669
wenzelm@65561
   670
  def directories(dirs: List[Path], select_dirs: List[Path]): List[(Boolean, Path)] =
wenzelm@65561
   671
  {
wenzelm@65561
   672
    val default_dirs = Isabelle_System.components().filter(is_session_dir(_))
wenzelm@65561
   673
    (default_dirs ::: dirs).map((false, _)) ::: select_dirs.map((true, _))
wenzelm@65561
   674
  }
wenzelm@65561
   675
wenzelm@65415
   676
  def load(options: Options, dirs: List[Path] = Nil, select_dirs: List[Path] = Nil): T =
wenzelm@62631
   677
  {
wenzelm@62635
   678
    def load_dir(select: Boolean, dir: Path): List[(String, Info)] =
wenzelm@62635
   679
      load_root(select, dir) ::: load_roots(select, dir)
wenzelm@62631
   680
wenzelm@62635
   681
    def load_root(select: Boolean, dir: Path): List[(String, Info)] =
wenzelm@62631
   682
      Parser.parse(options, select, dir)
wenzelm@62631
   683
wenzelm@62635
   684
    def load_roots(select: Boolean, dir: Path): List[(String, Info)] =
wenzelm@62631
   685
    {
wenzelm@62631
   686
      val roots = dir + ROOTS
wenzelm@62631
   687
      if (roots.is_file) {
wenzelm@62631
   688
        for {
wenzelm@62631
   689
          line <- split_lines(File.read(roots))
wenzelm@62631
   690
          if !(line == "" || line.startsWith("#"))
wenzelm@62631
   691
          dir1 =
wenzelm@62631
   692
            try { check_session_dir(dir + Path.explode(line)) }
wenzelm@62631
   693
            catch {
wenzelm@62631
   694
              case ERROR(msg) =>
wenzelm@62631
   695
                error(msg + "\nThe error(s) above occurred in session catalog " + roots.toString)
wenzelm@62631
   696
            }
wenzelm@62635
   697
          info <- load_dir(select, dir1)
wenzelm@62631
   698
        } yield info
wenzelm@62631
   699
      }
wenzelm@62631
   700
      else Nil
wenzelm@62631
   701
    }
wenzelm@62631
   702
wenzelm@65415
   703
    make(
wenzelm@62631
   704
      for {
wenzelm@65561
   705
        (select, dir) <- directories(dirs, select_dirs)
wenzelm@65468
   706
        info <- load_dir(select, check_session_dir(dir))
wenzelm@62631
   707
      } yield info)
wenzelm@62631
   708
  }
wenzelm@62632
   709
wenzelm@62632
   710
wenzelm@62637
   711
wenzelm@62704
   712
  /** heap file with SHA1 digest **/
wenzelm@62704
   713
wenzelm@62704
   714
  private val sha1_prefix = "SHA1:"
wenzelm@62704
   715
wenzelm@62704
   716
  def read_heap_digest(heap: Path): Option[String] =
wenzelm@62704
   717
  {
wenzelm@62704
   718
    if (heap.is_file) {
wenzelm@62704
   719
      val file = FileChannel.open(heap.file.toPath, StandardOpenOption.READ)
wenzelm@62704
   720
      try {
wenzelm@62704
   721
        val len = file.size
wenzelm@62704
   722
        val n = sha1_prefix.length + SHA1.digest_length
wenzelm@62704
   723
        if (len >= n) {
wenzelm@62704
   724
          file.position(len - n)
wenzelm@62704
   725
wenzelm@62704
   726
          val buf = ByteBuffer.allocate(n)
wenzelm@62704
   727
          var i = 0
wenzelm@62704
   728
          var m = 0
wenzelm@62704
   729
          do {
wenzelm@62704
   730
            m = file.read(buf)
wenzelm@62704
   731
            if (m != -1) i += m
wenzelm@62704
   732
          }
wenzelm@62704
   733
          while (m != -1 && n > i)
wenzelm@62704
   734
wenzelm@62704
   735
          if (i == n) {
wenzelm@62704
   736
            val prefix = new String(buf.array(), 0, sha1_prefix.length, UTF8.charset)
wenzelm@62704
   737
            val s = new String(buf.array(), sha1_prefix.length, SHA1.digest_length, UTF8.charset)
wenzelm@62704
   738
            if (prefix == sha1_prefix) Some(s) else None
wenzelm@62704
   739
          }
wenzelm@62704
   740
          else None
wenzelm@62704
   741
        }
wenzelm@62704
   742
        else None
wenzelm@62704
   743
      }
wenzelm@62704
   744
      finally { file.close }
wenzelm@62704
   745
    }
wenzelm@62704
   746
    else None
wenzelm@62704
   747
  }
wenzelm@62704
   748
wenzelm@62704
   749
  def write_heap_digest(heap: Path): String =
wenzelm@62704
   750
    read_heap_digest(heap) match {
wenzelm@62704
   751
      case None =>
wenzelm@62704
   752
        val s = SHA1.digest(heap).rep
wenzelm@62704
   753
        File.append(heap, sha1_prefix + s)
wenzelm@62704
   754
        s
wenzelm@62704
   755
      case Some(s) => s
wenzelm@62704
   756
    }
wenzelm@62704
   757
wenzelm@62704
   758
wenzelm@62704
   759
wenzelm@62637
   760
  /** persistent store **/
wenzelm@62632
   761
wenzelm@65296
   762
  object Session_Info
wenzelm@65296
   763
  {
wenzelm@65326
   764
    val session_name = SQL.Column.string("session_name", primary_key = true)
wenzelm@65326
   765
wenzelm@65296
   766
    // Build_Log.Session_Info
wenzelm@65296
   767
    val session_timing = SQL.Column.bytes("session_timing")
wenzelm@65296
   768
    val command_timings = SQL.Column.bytes("command_timings")
wenzelm@65296
   769
    val ml_statistics = SQL.Column.bytes("ml_statistics")
wenzelm@65296
   770
    val task_statistics = SQL.Column.bytes("task_statistics")
wenzelm@65934
   771
    val errors = SQL.Column.bytes("errors")
wenzelm@65296
   772
    val build_log_columns =
wenzelm@65934
   773
      List(session_name, session_timing, command_timings, ml_statistics, task_statistics, errors)
wenzelm@65296
   774
wenzelm@65296
   775
    // Build.Session_Info
wenzelm@65296
   776
    val sources = SQL.Column.string("sources")
wenzelm@65296
   777
    val input_heaps = SQL.Column.string("input_heaps")
wenzelm@65296
   778
    val output_heap = SQL.Column.string("output_heap")
wenzelm@65296
   779
    val return_code = SQL.Column.int("return_code")
wenzelm@65296
   780
    val build_columns = List(sources, input_heaps, output_heap, return_code)
wenzelm@65296
   781
wenzelm@65296
   782
    val table = SQL.Table("isabelle_session_info", build_log_columns ::: build_columns)
wenzelm@65296
   783
  }
wenzelm@65296
   784
wenzelm@62632
   785
  def store(system_mode: Boolean = false): Store = new Store(system_mode)
wenzelm@62632
   786
wenzelm@65857
   787
  class Store private[Sessions](system_mode: Boolean)
wenzelm@62632
   788
  {
wenzelm@65278
   789
    /* file names */
wenzelm@65278
   790
wenzelm@65281
   791
    def database(name: String): Path = Path.basic("log") + Path.basic(name).ext("db")
wenzelm@65278
   792
    def log(name: String): Path = Path.basic("log") + Path.basic(name)
wenzelm@65278
   793
    def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@65278
   794
wenzelm@65278
   795
wenzelm@65286
   796
    /* SQL database content */
wenzelm@65283
   797
wenzelm@65857
   798
    val xml_cache = new XML.Cache()
wenzelm@65857
   799
wenzelm@65320
   800
    def read_bytes(db: SQL.Database, name: String, column: SQL.Column): Bytes =
wenzelm@65698
   801
      db.using_statement(Session_Info.table.select(List(column),
wenzelm@65699
   802
        Session_Info.session_name.where_equal(name)))(stmt =>
wenzelm@65291
   803
      {
wenzelm@65740
   804
        val res = stmt.execute_query()
wenzelm@65740
   805
        if (!res.next()) Bytes.empty else res.bytes(column)
wenzelm@65291
   806
      })
wenzelm@65285
   807
wenzelm@65320
   808
    def read_properties(db: SQL.Database, name: String, column: SQL.Column): List[Properties.T] =
wenzelm@65857
   809
      Properties.uncompress(read_bytes(db, name, column), Some(xml_cache))
wenzelm@65286
   810
wenzelm@65283
   811
wenzelm@62637
   812
    /* output */
wenzelm@62632
   813
wenzelm@62632
   814
    val browser_info: Path =
wenzelm@62632
   815
      if (system_mode) Path.explode("~~/browser_info")
wenzelm@62632
   816
      else Path.explode("$ISABELLE_BROWSER_INFO")
wenzelm@62632
   817
wenzelm@62637
   818
    val output_dir: Path =
wenzelm@62637
   819
      if (system_mode) Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@62637
   820
      else Path.explode("$ISABELLE_OUTPUT")
wenzelm@62637
   821
wenzelm@65298
   822
    override def toString: String = "Store(output_dir = " + output_dir.expand + ")"
wenzelm@65298
   823
wenzelm@62637
   824
    def prepare_output() { Isabelle_System.mkdirs(output_dir + Path.basic("log")) }
wenzelm@62637
   825
wenzelm@62637
   826
wenzelm@62637
   827
    /* input */
wenzelm@62637
   828
wenzelm@62637
   829
    private val input_dirs =
wenzelm@62632
   830
      if (system_mode) List(output_dir)
wenzelm@62633
   831
      else {
wenzelm@62633
   832
        val ml_ident = Path.explode("$ML_IDENTIFIER").expand
wenzelm@62633
   833
        output_dir :: Path.split(Isabelle_System.getenv_strict("ISABELLE_PATH")).map(_ + ml_ident)
wenzelm@62633
   834
      }
wenzelm@62632
   835
wenzelm@65291
   836
    def find_database_heap(name: String): Option[(Path, Option[String])] =
wenzelm@65291
   837
      input_dirs.find(dir => (dir + database(name)).is_file).map(dir =>
wenzelm@65291
   838
        (dir + database(name), read_heap_digest(dir + Path.basic(name))))
wenzelm@62632
   839
wenzelm@65281
   840
    def find_database(name: String): Option[Path] =
wenzelm@65281
   841
      input_dirs.map(_ + database(name)).find(_.is_file)
wenzelm@65281
   842
wenzelm@62637
   843
    def heap(name: String): Path =
wenzelm@65288
   844
      input_dirs.map(_ + Path.basic(name)).find(_.is_file) getOrElse
wenzelm@62637
   845
        error("Unknown logic " + quote(name) + " -- no heap file found in:\n" +
wenzelm@62769
   846
          cat_lines(input_dirs.map(dir => "  " + dir.expand.implode)))
wenzelm@65287
   847
wenzelm@65287
   848
wenzelm@65296
   849
    /* session info */
wenzelm@65281
   850
wenzelm@65296
   851
    def write_session_info(
wenzelm@65318
   852
      db: SQL.Database,
wenzelm@65320
   853
      name: String,
wenzelm@65318
   854
      build_log: Build_Log.Session_Info,
wenzelm@65318
   855
      build: Build.Session_Info)
wenzelm@65281
   856
    {
wenzelm@65281
   857
      db.transaction {
wenzelm@65296
   858
        db.create_table(Session_Info.table)
wenzelm@65698
   859
        db.using_statement(
wenzelm@65699
   860
          Session_Info.table.delete(Session_Info.session_name.where_equal(name)))(_.execute)
wenzelm@65698
   861
        db.using_statement(Session_Info.table.insert())(stmt =>
wenzelm@65281
   862
        {
wenzelm@65748
   863
          stmt.string(1) = name
wenzelm@65857
   864
          stmt.bytes(2) = Properties.encode(build_log.session_timing)
wenzelm@65857
   865
          stmt.bytes(3) = Properties.compress(build_log.command_timings)
wenzelm@65857
   866
          stmt.bytes(4) = Properties.compress(build_log.ml_statistics)
wenzelm@65857
   867
          stmt.bytes(5) = Properties.compress(build_log.task_statistics)
wenzelm@65937
   868
          stmt.bytes(6) = Build_Log.compress_errors(build_log.errors)
wenzelm@65934
   869
          stmt.string(7) = cat_lines(build.sources)
wenzelm@65934
   870
          stmt.string(8) = cat_lines(build.input_heaps)
wenzelm@65934
   871
          stmt.string(9) = build.output_heap getOrElse ""
wenzelm@65934
   872
          stmt.int(10) = build.return_code
wenzelm@65281
   873
          stmt.execute()
wenzelm@65281
   874
        })
wenzelm@65281
   875
      }
wenzelm@65281
   876
    }
wenzelm@65281
   877
wenzelm@65320
   878
    def read_session_timing(db: SQL.Database, name: String): Properties.T =
wenzelm@65857
   879
      Properties.decode(read_bytes(db, name, Session_Info.session_timing), Some(xml_cache))
wenzelm@65286
   880
wenzelm@65320
   881
    def read_command_timings(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
   882
      read_properties(db, name, Session_Info.command_timings)
wenzelm@65286
   883
wenzelm@65320
   884
    def read_ml_statistics(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
   885
      read_properties(db, name, Session_Info.ml_statistics)
wenzelm@65286
   886
wenzelm@65320
   887
    def read_task_statistics(db: SQL.Database, name: String): List[Properties.T] =
wenzelm@65320
   888
      read_properties(db, name, Session_Info.task_statistics)
wenzelm@65286
   889
wenzelm@65937
   890
    def read_errors(db: SQL.Database, name: String): List[String] =
wenzelm@65937
   891
      Build_Log.uncompress_errors(read_bytes(db, name, Session_Info.errors))
wenzelm@65937
   892
wenzelm@65320
   893
    def read_build(db: SQL.Database, name: String): Option[Build.Session_Info] =
wenzelm@65698
   894
      db.using_statement(Session_Info.table.select(Session_Info.build_columns,
wenzelm@65699
   895
        Session_Info.session_name.where_equal(name)))(stmt =>
wenzelm@65285
   896
      {
wenzelm@65740
   897
        val res = stmt.execute_query()
wenzelm@65740
   898
        if (!res.next()) None
wenzelm@65285
   899
        else {
wenzelm@65285
   900
          Some(
wenzelm@65281
   901
            Build.Session_Info(
wenzelm@65740
   902
              split_lines(res.string(Session_Info.sources)),
wenzelm@65740
   903
              split_lines(res.string(Session_Info.input_heaps)),
wenzelm@65740
   904
              res.string(Session_Info.output_heap) match { case "" => None case s => Some(s) },
wenzelm@65740
   905
              res.int(Session_Info.return_code)))
wenzelm@65281
   906
        }
wenzelm@65281
   907
      })
wenzelm@65281
   908
  }
wenzelm@62631
   909
}