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