src/Pure/PIDE/document.scala
author wenzelm
Sat Mar 01 12:07:26 2014 +0100 (2014-03-01)
changeset 55820 61869776ce1f
parent 55801 28b59620f0d0
child 56176 0bc9b0ad6287
permissions -rw-r--r--
tuned signature -- more explicit Document.Elements;
wenzelm@36676
     1
/*  Title:      Pure/PIDE/document.scala
wenzelm@36676
     2
    Author:     Makarius
wenzelm@36676
     3
wenzelm@38150
     4
Document as collection of named nodes, each consisting of an editable
wenzelm@38418
     5
list of commands, associated with asynchronous execution process.
wenzelm@36676
     6
*/
wenzelm@34407
     7
wenzelm@34871
     8
package isabelle
wenzelm@34318
     9
wenzelm@34760
    10
wenzelm@38150
    11
import scala.collection.mutable
wenzelm@37073
    12
wenzelm@37073
    13
wenzelm@34823
    14
object Document
wenzelm@34483
    15
{
wenzelm@38424
    16
  /** document structure **/
wenzelm@38424
    17
wenzelm@52977
    18
  /* overlays -- print functions with arguments */
wenzelm@52977
    19
wenzelm@52977
    20
  object Overlays
wenzelm@52977
    21
  {
wenzelm@52977
    22
    val empty = new Overlays(Map.empty)
wenzelm@52977
    23
  }
wenzelm@52977
    24
wenzelm@52977
    25
  final class Overlays private(rep: Map[Node.Name, Node.Overlays])
wenzelm@52977
    26
  {
wenzelm@52977
    27
    def apply(name: Document.Node.Name): Node.Overlays =
wenzelm@52977
    28
      rep.getOrElse(name, Node.Overlays.empty)
wenzelm@52977
    29
wenzelm@52977
    30
    private def update(name: Node.Name, f: Node.Overlays => Node.Overlays): Overlays =
wenzelm@52977
    31
    {
wenzelm@52977
    32
      val node_overlays = f(apply(name))
wenzelm@52977
    33
      new Overlays(if (node_overlays.is_empty) rep - name else rep + (name -> node_overlays))
wenzelm@52977
    34
    }
wenzelm@52977
    35
wenzelm@52977
    36
    def insert(command: Command, fn: String, args: List[String]): Overlays =
wenzelm@52977
    37
      update(command.node_name, _.insert(command, fn, args))
wenzelm@52977
    38
wenzelm@52977
    39
    def remove(command: Command, fn: String, args: List[String]): Overlays =
wenzelm@52977
    40
      update(command.node_name, _.remove(command, fn, args))
wenzelm@55800
    41
wenzelm@55800
    42
    override def toString: String = rep.mkString("Overlays(", ",", ")")
wenzelm@52977
    43
  }
wenzelm@52977
    44
wenzelm@52977
    45
wenzelm@55783
    46
  /* document blobs: auxiliary files */
wenzelm@55783
    47
wenzelm@55783
    48
  sealed case class Blob(bytes: Bytes, file: Command.File, changed: Boolean)
wenzelm@55783
    49
wenzelm@55783
    50
  object Blobs
wenzelm@55783
    51
  {
wenzelm@55783
    52
    def apply(blobs: Map[Node.Name, Blob]): Blobs = new Blobs(blobs)
wenzelm@55783
    53
    val empty: Blobs = apply(Map.empty)
wenzelm@55783
    54
  }
wenzelm@55783
    55
wenzelm@55783
    56
  final class Blobs private(blobs: Map[Node.Name, Blob])
wenzelm@55783
    57
  {
wenzelm@55801
    58
    private lazy val digests: Map[SHA1.Digest, Blob] =
wenzelm@55801
    59
      for ((_, blob) <- blobs) yield (blob.bytes.sha1_digest, blob)
wenzelm@55801
    60
wenzelm@55801
    61
    def get(digest: SHA1.Digest): Option[Blob] = digests.get(digest)
wenzelm@55783
    62
    def get(name: Node.Name): Option[Blob] = blobs.get(name)
wenzelm@55783
    63
wenzelm@55783
    64
    def changed(name: Node.Name): Boolean =
wenzelm@55783
    65
      get(name) match {
wenzelm@55783
    66
        case Some(blob) => blob.changed
wenzelm@55783
    67
        case None => false
wenzelm@55783
    68
      }
wenzelm@55783
    69
wenzelm@55800
    70
    override def toString: String = blobs.mkString("Blobs(", ",", ")")
wenzelm@55783
    71
  }
wenzelm@55783
    72
wenzelm@55783
    73
wenzelm@55783
    74
  /* document nodes: theories and auxiliary files */
wenzelm@38424
    75
wenzelm@44615
    76
  type Edit[A, B] = (Node.Name, Node.Edit[A, B])
wenzelm@44384
    77
  type Edit_Text = Edit[Text.Edit, Text.Perspective]
wenzelm@52849
    78
  type Edit_Command = Edit[Command.Edit, Command.Perspective]
wenzelm@38151
    79
wenzelm@38151
    80
  object Node
wenzelm@38151
    81
  {
wenzelm@52887
    82
    val empty: Node = new Node()
wenzelm@52887
    83
wenzelm@52887
    84
wenzelm@52887
    85
    /* header and name */
wenzelm@52887
    86
wenzelm@48707
    87
    sealed case class Header(
wenzelm@46938
    88
      imports: List[Name],
wenzelm@48706
    89
      keywords: Thy_Header.Keywords,
wenzelm@48707
    90
      errors: List[String] = Nil)
wenzelm@48707
    91
    {
wenzelm@48707
    92
      def error(msg: String): Header = copy(errors = errors ::: List(msg))
wenzelm@54549
    93
wenzelm@54549
    94
      def cat_errors(msg2: String): Header =
wenzelm@54549
    95
        copy(errors = errors.map(msg1 => Library.cat_message(msg1, msg2)))
wenzelm@48707
    96
    }
wenzelm@48707
    97
wenzelm@51294
    98
    def bad_header(msg: String): Header = Header(Nil, Nil, List(msg))
wenzelm@46737
    99
wenzelm@54509
   100
    val no_header = bad_header("No theory header")
wenzelm@54509
   101
wenzelm@44957
   102
    object Name
wenzelm@44957
   103
    {
wenzelm@54515
   104
      val empty = Name("")
wenzelm@46723
   105
wenzelm@46723
   106
      object Ordering extends scala.math.Ordering[Name]
wenzelm@46723
   107
      {
wenzelm@46723
   108
        def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
wenzelm@46723
   109
      }
wenzelm@44957
   110
    }
wenzelm@52887
   111
wenzelm@54515
   112
    sealed case class Name(node: String, master_dir: String = "", theory: String = "")
wenzelm@44615
   113
    {
wenzelm@44615
   114
      override def hashCode: Int = node.hashCode
wenzelm@44615
   115
      override def equals(that: Any): Boolean =
wenzelm@44615
   116
        that match {
wenzelm@44615
   117
          case other: Name => node == other.node
wenzelm@44615
   118
          case _ => false
wenzelm@44615
   119
        }
wenzelm@54509
   120
wenzelm@54509
   121
      def is_theory: Boolean = !theory.isEmpty
wenzelm@54510
   122
      override def toString: String = if (is_theory) theory else node
wenzelm@44615
   123
    }
wenzelm@44615
   124
wenzelm@52887
   125
wenzelm@52977
   126
    /* node overlays */
wenzelm@52887
   127
wenzelm@52887
   128
    object Overlays
wenzelm@52887
   129
    {
wenzelm@52976
   130
      val empty = new Overlays(Multi_Map.empty)
wenzelm@52887
   131
    }
wenzelm@52887
   132
wenzelm@52977
   133
    final class Overlays private(rep: Multi_Map[Command, (String, List[String])])
wenzelm@52887
   134
    {
wenzelm@52887
   135
      def commands: Set[Command] = rep.keySet
wenzelm@52887
   136
      def is_empty: Boolean = rep.isEmpty
wenzelm@52977
   137
      def dest: List[(Command, (String, List[String]))] = rep.iterator.toList
wenzelm@52977
   138
      def insert(cmd: Command, fn: String, args: List[String]): Overlays =
wenzelm@52977
   139
        new Overlays(rep.insert(cmd, (fn, args)))
wenzelm@52977
   140
      def remove(cmd: Command, fn: String, args: List[String]): Overlays =
wenzelm@52977
   141
        new Overlays(rep.remove(cmd, (fn, args)))
wenzelm@55800
   142
wenzelm@55800
   143
      override def toString: String = rep.mkString("Node.Overlays(", ",", ")")
wenzelm@52887
   144
    }
wenzelm@52887
   145
wenzelm@52887
   146
wenzelm@52887
   147
    /* edits */
wenzelm@52887
   148
wenzelm@44384
   149
    sealed abstract class Edit[A, B]
wenzelm@44156
   150
    {
wenzelm@44383
   151
      def foreach(f: A => Unit)
wenzelm@44383
   152
      {
wenzelm@44156
   153
        this match {
wenzelm@44383
   154
          case Edits(es) => es.foreach(f)
wenzelm@44383
   155
          case _ =>
wenzelm@44156
   156
        }
wenzelm@44383
   157
      }
wenzelm@44156
   158
    }
wenzelm@44384
   159
    case class Clear[A, B]() extends Edit[A, B]
wenzelm@54562
   160
    case class Blob[A, B]() extends Edit[A, B]
wenzelm@54562
   161
wenzelm@44384
   162
    case class Edits[A, B](edits: List[A]) extends Edit[A, B]
wenzelm@48707
   163
    case class Deps[A, B](header: Header) extends Edit[A, B]
wenzelm@52849
   164
    case class Perspective[A, B](required: Boolean, visible: B, overlays: Overlays) extends Edit[A, B]
wenzelm@52808
   165
    type Perspective_Text = Perspective[Text.Edit, Text.Perspective]
wenzelm@52849
   166
    type Perspective_Command = Perspective[Command.Edit, Command.Perspective]
wenzelm@44156
   167
wenzelm@52887
   168
wenzelm@52887
   169
    /* commands */
wenzelm@52887
   170
wenzelm@52901
   171
    object Commands
wenzelm@52901
   172
    {
wenzelm@52901
   173
      def apply(commands: Linear_Set[Command]): Commands = new Commands(commands)
wenzelm@52901
   174
      val empty: Commands = apply(Linear_Set.empty)
wenzelm@52901
   175
wenzelm@52901
   176
      def starts(commands: Iterator[Command], offset: Text.Offset = 0)
wenzelm@52901
   177
        : Iterator[(Command, Text.Offset)] =
wenzelm@52901
   178
      {
wenzelm@52901
   179
        var i = offset
wenzelm@52901
   180
        for (command <- commands) yield {
wenzelm@52901
   181
          val start = i
wenzelm@52901
   182
          i += command.length
wenzelm@52901
   183
          (command, start)
wenzelm@52901
   184
        }
wenzelm@52901
   185
      }
wenzelm@52901
   186
wenzelm@52901
   187
      private val block_size = 1024
wenzelm@52901
   188
    }
wenzelm@52901
   189
wenzelm@52901
   190
    final class Commands private(val commands: Linear_Set[Command])
wenzelm@38227
   191
    {
wenzelm@54462
   192
      lazy val thy_load_commands: List[Command] =
wenzelm@54513
   193
        commands.iterator.filter(cmd => !cmd.blobs.isEmpty).toList
wenzelm@54462
   194
wenzelm@52901
   195
      private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
wenzelm@52901
   196
      {
wenzelm@52901
   197
        val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
wenzelm@52901
   198
        var next_block = 0
wenzelm@52901
   199
        var last_stop = 0
wenzelm@52901
   200
        for ((command, start) <- Commands.starts(commands.iterator)) {
wenzelm@52901
   201
          last_stop = start + command.length
wenzelm@52901
   202
          while (last_stop + 1 > next_block) {
wenzelm@52901
   203
            blocks += (command -> start)
wenzelm@52901
   204
            next_block += Commands.block_size
wenzelm@52901
   205
          }
wenzelm@52901
   206
        }
wenzelm@52901
   207
        (blocks.toArray, Text.Range(0, last_stop))
wenzelm@52901
   208
      }
wenzelm@52901
   209
wenzelm@52901
   210
      private def full_range: Text.Range = full_index._2
wenzelm@52901
   211
wenzelm@52901
   212
      def range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
wenzelm@52901
   213
      {
wenzelm@52901
   214
        if (!commands.isEmpty && full_range.contains(i)) {
wenzelm@52901
   215
          val (cmd0, start0) = full_index._1(i / Commands.block_size)
wenzelm@52901
   216
          Node.Commands.starts(commands.iterator(cmd0), start0) dropWhile {
wenzelm@52901
   217
            case (cmd, start) => start + cmd.length <= i }
wenzelm@52901
   218
        }
wenzelm@52901
   219
        else Iterator.empty
wenzelm@38227
   220
      }
wenzelm@38227
   221
    }
wenzelm@38151
   222
  }
wenzelm@38151
   223
wenzelm@46712
   224
  final class Node private(
wenzelm@55435
   225
    val is_blob: Boolean = false,
wenzelm@48707
   226
    val header: Node.Header = Node.bad_header("Bad theory header"),
wenzelm@52849
   227
    val perspective: Node.Perspective_Command =
wenzelm@52887
   228
      Node.Perspective(false, Command.Perspective.empty, Node.Overlays.empty),
wenzelm@52901
   229
    _commands: Node.Commands = Node.Commands.empty)
wenzelm@38151
   230
  {
wenzelm@46680
   231
    def clear: Node = new Node(header = header)
wenzelm@46680
   232
wenzelm@55435
   233
    def init_blob: Node = new Node(is_blob = true)
wenzelm@55435
   234
wenzelm@48707
   235
    def update_header(new_header: Node.Header): Node =
wenzelm@55435
   236
      new Node(is_blob, new_header, perspective, _commands)
wenzelm@46680
   237
wenzelm@52849
   238
    def update_perspective(new_perspective: Node.Perspective_Command): Node =
wenzelm@55435
   239
      new Node(is_blob, header, new_perspective, _commands)
wenzelm@46680
   240
wenzelm@52849
   241
    def same_perspective(other_perspective: Node.Perspective_Command): Boolean =
wenzelm@52849
   242
      perspective.required == other_perspective.required &&
wenzelm@52849
   243
      perspective.visible.same(other_perspective.visible) &&
wenzelm@52849
   244
      perspective.overlays == other_perspective.overlays
wenzelm@52808
   245
wenzelm@52901
   246
    def commands: Linear_Set[Command] = _commands.commands
wenzelm@54462
   247
    def thy_load_commands: List[Command] = _commands.thy_load_commands
wenzelm@43697
   248
wenzelm@52901
   249
    def update_commands(new_commands: Linear_Set[Command]): Node =
wenzelm@52918
   250
      if (new_commands eq _commands.commands) this
wenzelm@55435
   251
      else new Node(is_blob, header, perspective, Node.Commands(new_commands))
wenzelm@38151
   252
wenzelm@38569
   253
    def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
wenzelm@52901
   254
      _commands.range(i)
wenzelm@38151
   255
wenzelm@38569
   256
    def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
wenzelm@38569
   257
      command_range(range.start) takeWhile { case (_, start) => start < range.stop }
wenzelm@38151
   258
wenzelm@38879
   259
    def command_start(cmd: Command): Option[Text.Offset] =
wenzelm@52901
   260
      Node.Commands.starts(commands.iterator).find(_._1 == cmd).map(_._2)
wenzelm@38151
   261
  }
wenzelm@38151
   262
wenzelm@38151
   263
wenzelm@46723
   264
  /* development graph */
wenzelm@46723
   265
wenzelm@46723
   266
  object Nodes
wenzelm@46723
   267
  {
wenzelm@46723
   268
    val empty: Nodes = new Nodes(Graph.empty(Node.Name.Ordering))
wenzelm@46723
   269
  }
wenzelm@46723
   270
wenzelm@46723
   271
  final class Nodes private(graph: Graph[Node.Name, Node])
wenzelm@46723
   272
  {
wenzelm@46723
   273
    def get_name(s: String): Option[Node.Name] =
wenzelm@46723
   274
      graph.keys.find(name => name.node == s)
wenzelm@46723
   275
wenzelm@46723
   276
    def apply(name: Node.Name): Node =
wenzelm@46723
   277
      graph.default_node(name, Node.empty).get_node(name)
wenzelm@46723
   278
wenzelm@46723
   279
    def + (entry: (Node.Name, Node)): Nodes =
wenzelm@46723
   280
    {
wenzelm@46723
   281
      val (name, node) = entry
wenzelm@48707
   282
      val imports = node.header.imports
wenzelm@46723
   283
      val graph1 =
wenzelm@46739
   284
        (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
wenzelm@46723
   285
      val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
wenzelm@46739
   286
      val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
wenzelm@46723
   287
      new Nodes(graph3.map_node(name, _ => node))
wenzelm@46723
   288
    }
wenzelm@46723
   289
wenzelm@46723
   290
    def entries: Iterator[(Node.Name, Node)] =
wenzelm@46723
   291
      graph.entries.map({ case (name, (node, _)) => (name, node) })
wenzelm@46723
   292
wenzelm@54528
   293
    def thy_load_commands(file_name: Node.Name): List[Command] =
wenzelm@54528
   294
      (for {
wenzelm@54528
   295
        (_, node) <- entries
wenzelm@54528
   296
        cmd <- node.thy_load_commands.iterator
wenzelm@54530
   297
        name <- cmd.blobs_names.iterator
wenzelm@54528
   298
        if name == file_name
wenzelm@54528
   299
      } yield cmd).toList
wenzelm@54528
   300
wenzelm@46942
   301
    def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
wenzelm@46723
   302
    def topological_order: List[Node.Name] = graph.topological_order
wenzelm@46723
   303
  }
wenzelm@46723
   304
wenzelm@46723
   305
wenzelm@38424
   306
wenzelm@38424
   307
  /** versioning **/
wenzelm@38424
   308
wenzelm@38424
   309
  /* particular document versions */
wenzelm@34485
   310
wenzelm@38417
   311
  object Version
wenzelm@38417
   312
  {
wenzelm@46681
   313
    val init: Version = new Version()
wenzelm@46681
   314
wenzelm@46941
   315
    def make(syntax: Outer_Syntax, nodes: Nodes): Version =
wenzelm@52530
   316
      new Version(Document_ID.make(), syntax, nodes)
wenzelm@38417
   317
  }
wenzelm@38417
   318
wenzelm@46712
   319
  final class Version private(
wenzelm@52530
   320
    val id: Document_ID.Version = Document_ID.none,
wenzelm@46941
   321
    val syntax: Outer_Syntax = Outer_Syntax.empty,
wenzelm@46723
   322
    val nodes: Nodes = Nodes.empty)
wenzelm@46941
   323
  {
wenzelm@52530
   324
    def is_init: Boolean = id == Document_ID.none
wenzelm@55777
   325
wenzelm@55777
   326
    override def toString: String = "Version(" + id + ")"
wenzelm@46941
   327
  }
immler@34660
   328
wenzelm@34859
   329
wenzelm@38424
   330
  /* changes of plain text, eventually resulting in document edits */
wenzelm@38227
   331
wenzelm@38227
   332
  object Change
wenzelm@38227
   333
  {
wenzelm@46678
   334
    val init: Change = new Change()
wenzelm@46678
   335
wenzelm@46678
   336
    def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
wenzelm@46678
   337
      new Change(Some(previous), edits, version)
wenzelm@38227
   338
  }
wenzelm@38227
   339
wenzelm@46712
   340
  final class Change private(
wenzelm@46677
   341
    val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
wenzelm@46677
   342
    val edits: List[Edit_Text] = Nil,
wenzelm@46677
   343
    val version: Future[Version] = Future.value(Version.init))
wenzelm@38227
   344
  {
wenzelm@44672
   345
    def is_finished: Boolean =
wenzelm@44672
   346
      (previous match { case None => true case Some(future) => future.is_finished }) &&
wenzelm@44672
   347
      version.is_finished
wenzelm@44672
   348
wenzelm@46678
   349
    def truncate: Change = new Change(None, Nil, version)
wenzelm@38227
   350
  }
wenzelm@38227
   351
wenzelm@38227
   352
wenzelm@38841
   353
  /* history navigation */
wenzelm@38841
   354
wenzelm@38841
   355
  object History
wenzelm@38841
   356
  {
wenzelm@46679
   357
    val init: History = new History()
wenzelm@38841
   358
  }
wenzelm@38841
   359
wenzelm@46712
   360
  final class History private(
wenzelm@46679
   361
    val undo_list: List[Change] = List(Change.init))  // non-empty list
wenzelm@38841
   362
  {
wenzelm@46679
   363
    def tip: Change = undo_list.head
wenzelm@46679
   364
    def + (change: Change): History = new History(change :: undo_list)
wenzelm@38841
   365
wenzelm@46679
   366
    def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
wenzelm@46679
   367
    {
wenzelm@46679
   368
      val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
wenzelm@46679
   369
      val (retained, dropped) = undo_list.splitAt(n max retain)
wenzelm@46679
   370
wenzelm@46679
   371
      retained.splitAt(retained.length - 1) match {
wenzelm@46679
   372
        case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
wenzelm@46679
   373
        case _ => None
wenzelm@46679
   374
      }
wenzelm@46679
   375
    }
wenzelm@38841
   376
  }
wenzelm@38841
   377
wenzelm@38841
   378
wenzelm@55820
   379
  /* markup elements */
wenzelm@38841
   380
wenzelm@55820
   381
  object Elements
wenzelm@55820
   382
  {
wenzelm@55820
   383
    def apply(elems: Set[String]): Elements = new Elements(elems)
wenzelm@55820
   384
    def apply(elems: String*): Elements = apply(Set(elems: _*))
wenzelm@55820
   385
    val empty: Elements = apply()
wenzelm@55820
   386
    val full: Elements = new Full_Elements
wenzelm@55820
   387
  }
wenzelm@55820
   388
wenzelm@55820
   389
  sealed class Elements private[Document](private val rep: Set[String])
wenzelm@55820
   390
  {
wenzelm@55820
   391
    def apply(elem: String): Boolean = rep.contains(elem)
wenzelm@55820
   392
    def + (elem: String): Elements = new Elements(rep + elem)
wenzelm@55820
   393
    def ++ (elems: Elements): Elements = new Elements(rep ++ elems.rep)
wenzelm@55820
   394
    override def toString: String = rep.mkString("Elements(", ",", ")")
wenzelm@55820
   395
  }
wenzelm@55820
   396
wenzelm@55820
   397
  private class Full_Elements extends Elements(Set.empty)
wenzelm@55820
   398
  {
wenzelm@55820
   399
    override def apply(elem: String): Boolean = true
wenzelm@55820
   400
    override def toString: String = "Full_Elements()"
wenzelm@55820
   401
  }
wenzelm@55820
   402
wenzelm@55820
   403
wenzelm@55820
   404
  /* snapshot */
wenzelm@38424
   405
wenzelm@52972
   406
  object Snapshot
wenzelm@52972
   407
  {
wenzelm@52972
   408
    val init = State.init.snapshot()
wenzelm@52972
   409
  }
wenzelm@52972
   410
wenzelm@38424
   411
  abstract class Snapshot
wenzelm@38424
   412
  {
wenzelm@44582
   413
    val state: State
wenzelm@38424
   414
    val version: Version
wenzelm@38424
   415
    val is_outdated: Boolean
wenzelm@55649
   416
wenzelm@38427
   417
    def convert(i: Text.Offset): Text.Offset
wenzelm@52889
   418
    def revert(i: Text.Offset): Text.Offset
wenzelm@39177
   419
    def convert(range: Text.Range): Text.Range
wenzelm@39177
   420
    def revert(range: Text.Range): Text.Range
wenzelm@52972
   421
wenzelm@52972
   422
    val node_name: Node.Name
wenzelm@52972
   423
    val node: Node
wenzelm@55432
   424
    val thy_load_commands: List[Command]
wenzelm@51494
   425
    def eq_content(other: Snapshot): Boolean
wenzelm@55649
   426
wenzelm@55651
   427
    def cumulate[A](
wenzelm@55649
   428
      range: Text.Range,
wenzelm@55649
   429
      info: A,
wenzelm@55820
   430
      elements: Elements,
wenzelm@55651
   431
      result: Command.State => (A, Text.Markup) => Option[A],
wenzelm@55651
   432
      status: Boolean = false): List[Text.Info[A]]
wenzelm@55651
   433
wenzelm@55651
   434
    def select[A](
wenzelm@55649
   435
      range: Text.Range,
wenzelm@55820
   436
      elements: Elements,
wenzelm@55651
   437
      result: Command.State => Text.Markup => Option[A],
wenzelm@55651
   438
      status: Boolean = false): List[Text.Info[A]]
wenzelm@38424
   439
  }
wenzelm@38424
   440
wenzelm@55820
   441
wenzelm@55820
   442
wenzelm@55820
   443
  /** global state -- document structure, execution process, editing history **/
wenzelm@55820
   444
wenzelm@52563
   445
  type Assign_Update =
wenzelm@52563
   446
    List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
wenzelm@44476
   447
wenzelm@38370
   448
  object State
wenzelm@38370
   449
  {
wenzelm@38373
   450
    class Fail(state: State) extends Exception
wenzelm@38373
   451
wenzelm@44479
   452
    object Assignment
wenzelm@44479
   453
    {
wenzelm@46683
   454
      val init: Assignment = new Assignment()
wenzelm@44479
   455
    }
wenzelm@38370
   456
wenzelm@46712
   457
    final class Assignment private(
wenzelm@52530
   458
      val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
wenzelm@46677
   459
      val is_finished: Boolean = false)
wenzelm@38370
   460
    {
wenzelm@44477
   461
      def check_finished: Assignment = { require(is_finished); this }
wenzelm@47388
   462
      def unfinished: Assignment = new Assignment(command_execs, false)
wenzelm@44479
   463
wenzelm@52563
   464
      def assign(update: Assign_Update): Assignment =
wenzelm@38370
   465
      {
wenzelm@38976
   466
        require(!is_finished)
wenzelm@44479
   467
        val command_execs1 =
wenzelm@52563
   468
          (command_execs /: update) {
wenzelm@52563
   469
            case (res, (command_id, exec_ids)) =>
wenzelm@52563
   470
              if (exec_ids.isEmpty) res - command_id
wenzelm@52563
   471
              else res + (command_id -> exec_ids)
wenzelm@44479
   472
          }
wenzelm@47388
   473
        new Assignment(command_execs1, true)
wenzelm@38150
   474
      }
wenzelm@38370
   475
    }
wenzelm@46682
   476
wenzelm@46682
   477
    val init: State =
wenzelm@52563
   478
      State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
wenzelm@38370
   479
  }
wenzelm@38370
   480
wenzelm@46712
   481
  final case class State private(
wenzelm@52530
   482
    val versions: Map[Document_ID.Version, Version] = Map.empty,
wenzelm@54519
   483
    val blobs: Set[SHA1.Digest] = Set.empty,   // inlined files
wenzelm@52530
   484
    val commands: Map[Document_ID.Command, Command.State] = Map.empty,  // static markup from define_command
wenzelm@52530
   485
    val execs: Map[Document_ID.Exec, Command.State] = Map.empty,  // dynamic markup from execution
wenzelm@52530
   486
    val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
wenzelm@38841
   487
    val history: History = History.init)
wenzelm@38370
   488
  {
wenzelm@38373
   489
    private def fail[A]: A = throw new State.Fail(this)
wenzelm@38370
   490
wenzelm@44479
   491
    def define_version(version: Version, assignment: State.Assignment): State =
wenzelm@38370
   492
    {
wenzelm@38417
   493
      val id = version.id
wenzelm@38417
   494
      copy(versions = versions + (id -> version),
wenzelm@44479
   495
        assignments = assignments + (id -> assignment.unfinished))
wenzelm@38370
   496
    }
wenzelm@38370
   497
wenzelm@54519
   498
    def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
wenzelm@54519
   499
    def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
wenzelm@54519
   500
wenzelm@38373
   501
    def define_command(command: Command): State =
wenzelm@38373
   502
    {
wenzelm@38373
   503
      val id = command.id
wenzelm@49414
   504
      copy(commands = commands + (id -> command.init_state))
wenzelm@38373
   505
    }
wenzelm@38373
   506
wenzelm@52530
   507
    def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
wenzelm@44582
   508
wenzelm@52531
   509
    def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
wenzelm@44582
   510
      commands.get(id) orElse execs.get(id) match {
wenzelm@44582
   511
        case None => None
wenzelm@44582
   512
        case Some(st) =>
wenzelm@44582
   513
          val command = st.command
wenzelm@46681
   514
          val node = version.nodes(command.node_name)
wenzelm@54328
   515
          if (node.commands.contains(command)) Some((node, command)) else None
wenzelm@44582
   516
      }
wenzelm@38373
   517
wenzelm@52530
   518
    def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
wenzelm@52564
   519
    def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
wenzelm@52564
   520
    def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
wenzelm@52563
   521
    def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
wenzelm@38370
   522
wenzelm@52531
   523
    def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
wenzelm@38370
   524
      execs.get(id) match {
wenzelm@44446
   525
        case Some(st) =>
wenzelm@49527
   526
          val new_st = st + (id, message)
wenzelm@44446
   527
          (new_st, copy(execs = execs + (id -> new_st)))
wenzelm@38370
   528
        case None =>
wenzelm@38370
   529
          commands.get(id) match {
wenzelm@38370
   530
            case Some(st) =>
wenzelm@49527
   531
              val new_st = st + (id, message)
wenzelm@38370
   532
              (new_st, copy(commands = commands + (id -> new_st)))
wenzelm@38370
   533
            case None => fail
wenzelm@38370
   534
          }
wenzelm@38370
   535
      }
wenzelm@38370
   536
wenzelm@52563
   537
    def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
wenzelm@38370
   538
    {
wenzelm@38417
   539
      val version = the_version(id)
wenzelm@38370
   540
wenzelm@52566
   541
      def upd(exec_id: Document_ID.Exec, st: Command.State)
wenzelm@52566
   542
          : Option[(Document_ID.Exec, Command.State)] =
wenzelm@52566
   543
        if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
wenzelm@52566
   544
wenzelm@44543
   545
      val (changed_commands, new_execs) =
wenzelm@52563
   546
        ((Nil: List[Command], execs) /: update) {
wenzelm@52566
   547
          case ((commands1, execs1), (command_id, exec)) =>
wenzelm@52566
   548
            val st = the_static_state(command_id)
wenzelm@52566
   549
            val command = st.command
wenzelm@52527
   550
            val commands2 = command :: commands1
wenzelm@44543
   551
            val execs2 =
wenzelm@44543
   552
              exec match {
wenzelm@52527
   553
                case Nil => execs1
wenzelm@52527
   554
                case eval_id :: print_ids =>
wenzelm@52566
   555
                  execs1 ++ upd(eval_id, st) ++
wenzelm@52566
   556
                    (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
wenzelm@44543
   557
              }
wenzelm@44543
   558
            (commands2, execs2)
wenzelm@38370
   559
        }
wenzelm@52563
   560
      val new_assignment = the_assignment(version).assign(update)
wenzelm@43722
   561
      val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
wenzelm@44476
   562
wenzelm@44543
   563
      (changed_commands, new_state)
wenzelm@38370
   564
    }
wenzelm@38370
   565
wenzelm@38417
   566
    def is_assigned(version: Version): Boolean =
wenzelm@43722
   567
      assignments.get(version.id) match {
wenzelm@38370
   568
        case Some(assgn) => assgn.is_finished
wenzelm@38370
   569
        case None => false
wenzelm@38370
   570
      }
wenzelm@38370
   571
wenzelm@44436
   572
    def is_stable(change: Change): Boolean =
wenzelm@44436
   573
      change.is_finished && is_assigned(change.version.get_finished)
wenzelm@44436
   574
wenzelm@46944
   575
    def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
wenzelm@44672
   576
    def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
wenzelm@44436
   577
    def tip_stable: Boolean = is_stable(history.tip)
wenzelm@44475
   578
    def tip_version: Version = history.tip.version.get_finished
wenzelm@44436
   579
wenzelm@44446
   580
    def continue_history(
wenzelm@44446
   581
        previous: Future[Version],
wenzelm@40479
   582
        edits: List[Edit_Text],
wenzelm@43722
   583
        version: Future[Version]): (Change, State) =
wenzelm@38841
   584
    {
wenzelm@46678
   585
      val change = Change.make(previous, edits, version)
wenzelm@38841
   586
      (change, copy(history = history + change))
wenzelm@38841
   587
    }
wenzelm@38841
   588
wenzelm@44672
   589
    def prune_history(retain: Int = 0): (List[Version], State) =
wenzelm@44672
   590
    {
wenzelm@46679
   591
      history.prune(is_stable, retain) match {
wenzelm@46679
   592
        case Some((dropped, history1)) =>
wenzelm@44672
   593
          val dropped_versions = dropped.map(change => change.version.get_finished)
wenzelm@46679
   594
          val state1 = copy(history = history1)
wenzelm@44672
   595
          (dropped_versions, state1)
wenzelm@46679
   596
        case None => fail
wenzelm@44672
   597
      }
wenzelm@44672
   598
    }
wenzelm@44672
   599
wenzelm@52530
   600
    def removed_versions(removed: List[Document_ID.Version]): State =
wenzelm@44676
   601
    {
wenzelm@44676
   602
      val versions1 = versions -- removed
wenzelm@44676
   603
      val assignments1 = assignments -- removed
wenzelm@54519
   604
      var blobs1 = Set.empty[SHA1.Digest]
wenzelm@52530
   605
      var commands1 = Map.empty[Document_ID.Command, Command.State]
wenzelm@52530
   606
      var execs1 = Map.empty[Document_ID.Exec, Command.State]
wenzelm@44676
   607
      for {
wenzelm@44676
   608
        (version_id, version) <- versions1.iterator
wenzelm@46997
   609
        command_execs = assignments1(version_id).command_execs
wenzelm@46723
   610
        (_, node) <- version.nodes.entries
wenzelm@44676
   611
        command <- node.commands.iterator
wenzelm@44676
   612
      } {
wenzelm@54519
   613
        for (digest <- command.blobs_digests; if !blobs1.contains(digest))
wenzelm@54519
   614
          blobs1 += digest
wenzelm@54519
   615
wenzelm@52568
   616
        if (!commands1.isDefinedAt(command.id))
wenzelm@52568
   617
          commands.get(command.id).foreach(st => commands1 += (command.id -> st))
wenzelm@54519
   618
wenzelm@52568
   619
        for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
wenzelm@52527
   620
          if (!execs1.isDefinedAt(exec_id))
wenzelm@52527
   621
            execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
wenzelm@44676
   622
        }
wenzelm@44676
   623
      }
wenzelm@54519
   624
      copy(versions = versions1, blobs = blobs1, commands = commands1, execs = execs1,
wenzelm@54519
   625
        assignments = assignments1)
wenzelm@44676
   626
    }
wenzelm@44676
   627
wenzelm@44613
   628
    def command_state(version: Version, command: Command): Command.State =
wenzelm@44613
   629
    {
wenzelm@44613
   630
      require(is_assigned(version))
wenzelm@44613
   631
      try {
wenzelm@52527
   632
        the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
wenzelm@52564
   633
          .map(the_dynamic_state(_)) match {
wenzelm@52527
   634
            case eval_state :: print_states => (eval_state /: print_states)(_ ++ _)
wenzelm@52527
   635
            case Nil => fail
wenzelm@52527
   636
          }
wenzelm@44613
   637
      }
wenzelm@47395
   638
      catch {
wenzelm@47395
   639
        case _: State.Fail =>
wenzelm@52564
   640
          try { the_static_state(command.id) }
wenzelm@49414
   641
          catch { case _: State.Fail => command.init_state }
wenzelm@47395
   642
      }
wenzelm@44613
   643
    }
wenzelm@44613
   644
wenzelm@49645
   645
    def markup_to_XML(version: Version, node: Node, filter: XML.Elem => Boolean): XML.Body =
wenzelm@49645
   646
      node.commands.toList.map(cmd => command_state(version, cmd).markup_to_XML(filter)).flatten
wenzelm@38841
   647
wenzelm@38841
   648
    // persistent user-view
wenzelm@49346
   649
    def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
wenzelm@49346
   650
      : Snapshot =
wenzelm@38370
   651
    {
wenzelm@44672
   652
      val stable = recent_stable
wenzelm@44436
   653
      val latest = history.tip
wenzelm@38841
   654
wenzelm@44156
   655
      // FIXME proper treatment of removed nodes
wenzelm@38841
   656
      val edits =
wenzelm@38841
   657
        (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
wenzelm@44156
   658
            (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
wenzelm@38841
   659
      lazy val reverse_edits = edits.reverse
wenzelm@38841
   660
wenzelm@38841
   661
      new Snapshot
wenzelm@38841
   662
      {
wenzelm@52972
   663
        /* global information */
wenzelm@52972
   664
wenzelm@44582
   665
        val state = State.this
wenzelm@39698
   666
        val version = stable.version.get_finished
wenzelm@38841
   667
        val is_outdated = !(pending_edits.isEmpty && latest == stable)
wenzelm@38841
   668
wenzelm@55649
   669
wenzelm@55649
   670
        /* local node content */
wenzelm@55649
   671
wenzelm@38841
   672
        def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
wenzelm@38841
   673
        def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
wenzelm@43425
   674
        def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
wenzelm@43425
   675
        def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
wenzelm@39177
   676
wenzelm@52972
   677
        val node_name = name
wenzelm@52972
   678
        val node = version.nodes(name)
wenzelm@52972
   679
wenzelm@55432
   680
        val thy_load_commands: List[Command] =
wenzelm@55432
   681
          if (node_name.is_theory) Nil
wenzelm@55432
   682
          else version.nodes.thy_load_commands(node_name)
wenzelm@55432
   683
wenzelm@51494
   684
        def eq_content(other: Snapshot): Boolean =
wenzelm@55434
   685
        {
wenzelm@55434
   686
          def eq_commands(commands: (Command, Command)): Boolean =
wenzelm@55434
   687
            state.command_state(version, commands._1) eq_content
wenzelm@55434
   688
              other.state.command_state(other.version, commands._2)
wenzelm@55434
   689
wenzelm@49346
   690
          !is_outdated && !other.is_outdated &&
wenzelm@55434
   691
          node.commands.size == other.node.commands.size &&
wenzelm@55434
   692
          (node.commands.iterator zip other.node.commands.iterator).forall(eq_commands) &&
wenzelm@55434
   693
          thy_load_commands.length == other.thy_load_commands.length &&
wenzelm@55434
   694
          (thy_load_commands zip other.thy_load_commands).forall(eq_commands)
wenzelm@55434
   695
        }
wenzelm@49346
   696
wenzelm@55649
   697
wenzelm@55649
   698
        /* cumulate markup */
wenzelm@55649
   699
wenzelm@55651
   700
        def cumulate[A](
wenzelm@55649
   701
          range: Text.Range,
wenzelm@55649
   702
          info: A,
wenzelm@55820
   703
          elements: Elements,
wenzelm@55651
   704
          result: Command.State => (A, Text.Markup) => Option[A],
wenzelm@55651
   705
          status: Boolean = false): List[Text.Info[A]] =
wenzelm@45459
   706
        {
wenzelm@45467
   707
          val former_range = revert(range)
wenzelm@55432
   708
          thy_load_commands match {
wenzelm@55432
   709
            case thy_load_command :: _ =>
wenzelm@55432
   710
              val file_name = node_name.node
wenzelm@55649
   711
              val markup_index = Command.Markup_Index(status, file_name)
wenzelm@55432
   712
              (for {
wenzelm@55432
   713
                chunk <- thy_load_command.chunks.get(file_name).iterator
wenzelm@55432
   714
                st = state.command_state(version, thy_load_command)
wenzelm@55432
   715
                res = result(st)
wenzelm@55650
   716
                Text.Info(r0, a) <- st.markup(markup_index).cumulate[A](
wenzelm@55432
   717
                  former_range.restrict(chunk.range), info, elements,
wenzelm@55432
   718
                  { case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0), b)) }
wenzelm@55432
   719
                ).iterator
wenzelm@55432
   720
              } yield Text.Info(convert(r0), a)).toList
wenzelm@55432
   721
wenzelm@55432
   722
            case _ =>
wenzelm@55649
   723
              val markup_index = Command.Markup_Index(status, "")
wenzelm@55432
   724
              (for {
wenzelm@55432
   725
                (command, command_start) <- node.command_range(former_range)
wenzelm@55432
   726
                st = state.command_state(version, command)
wenzelm@55432
   727
                res = result(st)
wenzelm@55650
   728
                Text.Info(r0, a) <- st.markup(markup_index).cumulate[A](
wenzelm@55432
   729
                  (former_range - command_start).restrict(command.range), info, elements,
wenzelm@55649
   730
                  {
wenzelm@55649
   731
                    case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b))
wenzelm@55649
   732
                  }).iterator
wenzelm@55432
   733
              } yield Text.Info(convert(r0 + command_start), a)).toList
wenzelm@55432
   734
          }
wenzelm@45459
   735
        }
wenzelm@45459
   736
wenzelm@55651
   737
        def select[A](
wenzelm@55651
   738
          range: Text.Range,
wenzelm@55820
   739
          elements: Elements,
wenzelm@55651
   740
          result: Command.State => Text.Markup => Option[A],
wenzelm@55651
   741
          status: Boolean = false): List[Text.Info[A]] =
wenzelm@38845
   742
        {
wenzelm@52889
   743
          def result1(st: Command.State): (Option[A], Text.Markup) => Option[Option[A]] =
wenzelm@50500
   744
          {
wenzelm@50500
   745
            val res = result(st)
wenzelm@52889
   746
            (_: Option[A], x: Text.Markup) =>
wenzelm@52889
   747
              res(x) match {
wenzelm@52889
   748
                case None => None
wenzelm@52889
   749
                case some => Some(some)
wenzelm@52889
   750
              }
wenzelm@50500
   751
          }
wenzelm@55651
   752
          for (Text.Info(r, Some(x)) <- cumulate(range, None, elements, result1 _, status))
wenzelm@46198
   753
            yield Text.Info(r, x)
wenzelm@38845
   754
        }
wenzelm@55800
   755
wenzelm@55800
   756
wenzelm@55800
   757
        /* output */
wenzelm@55800
   758
wenzelm@55800
   759
        override def toString: String =
wenzelm@55800
   760
          "Snapshot(node = " + node_name.node + ", version = " + version.id +
wenzelm@55800
   761
            (if (is_outdated) ", outdated" else "") + ")"
wenzelm@38841
   762
      }
wenzelm@38150
   763
    }
wenzelm@34485
   764
  }
wenzelm@34840
   765
}
wenzelm@34840
   766