File: DocumentManager.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (269 lines) | stat: -rw-r--r-- 9,245 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import Dispatch
import LSPLogging
import LanguageServerProtocol
import SKSupport
import SemanticIndex
import SwiftSyntax

/// An immutable snapshot of a document at a given time.
///
/// ``DocumentSnapshot`` is always derived from a ``Document``. That is, the
/// data structure that is stored internally by the ``DocumentManager`` is a
/// ``Document``. The purpose of a ``DocumentSnapshot`` is to be able to work
/// with one version of a document without having to think about it changing.
public struct DocumentSnapshot: Identifiable, Sendable {
  /// An ID that uniquely identifies the version of the document stored in this
  /// snapshot.
  public struct ID: Hashable, Comparable, Sendable {
    public let uri: DocumentURI
    public let version: Int

    /// Returns `true` if the snapshots reference the same document but rhs has a
    /// later version than `lhs`.
    ///
    /// Snapshot IDs of different documents are not comparable to each other and
    /// will always return `false`.
    public static func < (lhs: DocumentSnapshot.ID, rhs: DocumentSnapshot.ID) -> Bool {
      return lhs.uri == rhs.uri && lhs.version < rhs.version
    }
  }

  public let id: ID
  public let language: Language
  public let lineTable: LineTable

  public var uri: DocumentURI { id.uri }
  public var version: Int { id.version }
  public var text: String { lineTable.content }

  public init(
    uri: DocumentURI,
    language: Language,
    version: Int,
    lineTable: LineTable
  ) {
    self.id = ID(uri: uri, version: version)
    self.language = language
    self.lineTable = lineTable
  }
}

public final class Document {
  public let uri: DocumentURI
  public let language: Language
  var latestVersion: Int
  var latestLineTable: LineTable

  init(uri: DocumentURI, language: Language, version: Int, text: String) {
    self.uri = uri
    self.language = language
    self.latestVersion = version
    self.latestLineTable = LineTable(text)
  }

  /// **Not thread safe!** Use `DocumentManager.latestSnapshot` instead.
  fileprivate var latestSnapshot: DocumentSnapshot {
    DocumentSnapshot(
      uri: self.uri,
      language: self.language,
      version: latestVersion,
      lineTable: latestLineTable
    )
  }
}

public final class DocumentManager: InMemoryDocumentManager, Sendable {

  public enum Error: Swift.Error {
    case alreadyOpen(DocumentURI)
    case missingDocument(DocumentURI)
  }

  // FIXME: (async) Migrate this to be an AsyncQueue
  private let queue: DispatchQueue = DispatchQueue(label: "document-manager-queue")

  // `nonisolated(unsafe)` is fine because `documents` is guarded by queue.
  nonisolated(unsafe) var documents: [DocumentURI: Document] = [:]

  public init() {}

  /// All currently opened documents.
  public var openDocuments: Set<DocumentURI> {
    return queue.sync {
      return Set(documents.keys)
    }
  }

  /// Opens a new document with the given content and metadata.
  ///
  /// - returns: The initial contents of the file.
  /// - throws: Error.alreadyOpen if the document is already open.
  @discardableResult
  public func open(_ uri: DocumentURI, language: Language, version: Int, text: String) throws -> DocumentSnapshot {
    return try queue.sync {
      let document = Document(uri: uri, language: language, version: version, text: text)
      if nil != documents.updateValue(document, forKey: uri) {
        throw Error.alreadyOpen(uri)
      }
      return document.latestSnapshot
    }
  }

  /// Closes the given document.
  ///
  /// - returns: The initial contents of the file.
  /// - throws: Error.missingDocument if the document is not open.
  public func close(_ uri: DocumentURI) throws {
    try queue.sync {
      if nil == documents.removeValue(forKey: uri) {
        throw Error.missingDocument(uri)
      }
    }
  }

  /// Applies the given edits to the document.
  ///
  /// - Parameters:
  ///   - uri: The URI of the document to update
  ///   - newVersion: The new version of the document. Must be greater than the
  ///     latest version of the document.
  ///   - edits: The edits to apply to the document
  /// - Returns: The snapshot of the document before the edit, the snapshot
  ///   of the document after the edit, and the edits. The edits are sequential, ie.
  ///   the edits are expected to be applied in order and later values in this array
  ///   assume that previous edits are already applied.
  @discardableResult
  public func edit(
    _ uri: DocumentURI,
    newVersion: Int,
    edits: [TextDocumentContentChangeEvent]
  ) throws -> (preEditSnapshot: DocumentSnapshot, postEditSnapshot: DocumentSnapshot, edits: [SourceEdit]) {
    return try queue.sync {
      guard let document = documents[uri] else {
        throw Error.missingDocument(uri)
      }
      let preEditSnapshot = document.latestSnapshot

      var sourceEdits: [SourceEdit] = []
      for edit in edits {
        sourceEdits.append(SourceEdit(edit: edit, lineTableBeforeEdit: document.latestLineTable))

        if let range = edit.range {
          document.latestLineTable.replace(
            fromLine: range.lowerBound.line,
            utf16Offset: range.lowerBound.utf16index,
            toLine: range.upperBound.line,
            utf16Offset: range.upperBound.utf16index,
            with: edit.text
          )
        } else {
          // Full text replacement.
          document.latestLineTable = LineTable(edit.text)
        }
      }

      if newVersion <= document.latestVersion {
        logger.error("Document version did not increase on edit from \(document.latestVersion) to \(newVersion)")
      }
      document.latestVersion = newVersion
      return (preEditSnapshot, document.latestSnapshot, sourceEdits)
    }
  }

  public func latestSnapshot(_ uri: DocumentURI) throws -> DocumentSnapshot {
    return try queue.sync {
      guard let document = documents[uri] else {
        throw ResponseError.unknown("Failed to find snapshot for '\(uri)'")
      }
      return document.latestSnapshot
    }
  }

  public func fileHasInMemoryModifications(_ uri: DocumentURI) -> Bool {
    guard let document = try? latestSnapshot(uri), let fileURL = uri.fileURL else {
      return false
    }

    guard let onDiskFileContents = try? String(contentsOf: fileURL, encoding: .utf8) else {
      // If we can't read the file on disk, it can't match any on-disk state, so it's in-memory state
      return true
    }
    return onDiskFileContents != document.lineTable.content
  }
}

extension DocumentManager {

  // MARK: - LSP notification handling

  /// Convenience wrapper for `open(_:language:version:text:)` that logs on failure.
  @discardableResult
  func open(_ notification: DidOpenTextDocumentNotification) -> DocumentSnapshot? {
    let doc = notification.textDocument
    return orLog("failed to open document", level: .error) {
      try open(doc.uri, language: doc.language, version: doc.version, text: doc.text)
    }
  }

  /// Convenience wrapper for `close(_:)` that logs on failure.
  func close(_ notification: DidCloseTextDocumentNotification) {
    orLog("failed to close document", level: .error) {
      try close(notification.textDocument.uri)
    }
  }

  /// Convenience wrapper for `edit(_:newVersion:edits:updateDocumentTokens:)`
  /// that logs on failure.
  @discardableResult
  func edit(
    _ notification: DidChangeTextDocumentNotification
  ) -> (preEditSnapshot: DocumentSnapshot, postEditSnapshot: DocumentSnapshot, edits: [SourceEdit])? {
    return orLog("failed to edit document", level: .error) {
      return try edit(
        notification.textDocument.uri,
        newVersion: notification.textDocument.version,
        edits: notification.contentChanges
      )
    }
  }
}

fileprivate extension SourceEdit {
  /// Constructs a `SourceEdit` from the given `TextDocumentContentChangeEvent`.
  ///
  /// Returns `nil` if the `TextDocumentContentChangeEvent` refers to line:column positions that don't exist in
  /// `LineTable`.
  init(edit: TextDocumentContentChangeEvent, lineTableBeforeEdit: LineTable) {
    if let range = edit.range {
      let offset = lineTableBeforeEdit.utf8OffsetOf(
        line: range.lowerBound.line,
        utf16Column: range.lowerBound.utf16index
      )
      let end = lineTableBeforeEdit.utf8OffsetOf(
        line: range.upperBound.line,
        utf16Column: range.upperBound.utf16index
      )
      self.init(
        range: AbsolutePosition(utf8Offset: offset)..<AbsolutePosition(utf8Offset: end),
        replacement: edit.text
      )
    } else {
      self.init(
        range: AbsolutePosition(utf8Offset: 0)..<AbsolutePosition(utf8Offset: lineTableBeforeEdit.content.utf8.count),
        replacement: edit.text
      )
    }
  }
}