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