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