File: Diagnostic.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 (428 lines) | stat: -rw-r--r-- 13,862 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 LSPLogging
import LanguageServerProtocol
import SKSupport
import SourceKitD
import SwiftDiagnostics

extension CodeAction {

  /// Creates a CodeAction from a list for sourcekit fixits.
  ///
  /// If this is from a note, the note's description should be passed as `fromNote`.
  init?(fixits: SKDResponseArray, in snapshot: DocumentSnapshot, fromNote: String?) {
    var edits: [TextEdit] = []
    let editsMapped = fixits.forEach { (_, skfixit) -> Bool in
      if let edit = TextEdit(fixit: skfixit, in: snapshot) {
        edits.append(edit)
        return true
      }
      return false
    }

    if !editsMapped {
      logger.fault("Failed to construct TextEdits from response \(fixits)")
      return nil
    }

    if edits.isEmpty {
      return nil
    }

    let title: String
    if let fromNote = fromNote {
      title = fromNote
    } else {
      guard let generatedTitle = Self.title(for: edits, in: snapshot) else {
        return nil
      }
      title = generatedTitle
    }

    self.init(
      title: title,
      kind: .quickFix,
      diagnostics: nil,
      edit: WorkspaceEdit(changes: [snapshot.uri: edits])
    )
  }

  init?(_ fixIt: FixIt, in snapshot: DocumentSnapshot) {
    var textEdits = [TextEdit]()
    for edit in fixIt.edits {
      textEdits.append(TextEdit(range: snapshot.range(of: edit.range), newText: edit.replacement))
    }

    self.init(
      title: fixIt.message.message.withFirstLetterUppercased(),
      kind: .quickFix,
      diagnostics: nil,
      edit: WorkspaceEdit(changes: [snapshot.uri: textEdits])
    )
  }

  private static func title(for edits: [TextEdit], in snapshot: DocumentSnapshot) -> String? {
    if edits.isEmpty {
      return nil
    }
    let startIndex = snapshot.index(of: edits[0].range.lowerBound)
    let endIndex = snapshot.index(of: edits[0].range.upperBound)
    guard startIndex <= endIndex,
      snapshot.text.indices.contains(startIndex),
      endIndex <= snapshot.text.endIndex
    else {
      return nil
    }
    let oldText = String(snapshot.text[startIndex..<endIndex])
    let description = Self.fixitTitle(replace: oldText, with: edits[0].newText)
    if edits.count == 1 {
      return description
    }
    return description + "..."
  }

  /// Describe a fixit's edit briefly.
  ///
  /// For example, "Replace 'x' with 'y'", or "Remove 'z'".
  public static func fixitTitle(replace oldText: String, with newText: String) -> String {
    switch (oldText.isEmpty, newText.isEmpty) {
    case (false, false):
      return "Replace '\(oldText)' with '\(newText)'"
    case (false, true):
      return "Remove '\(oldText)'"
    case (true, false):
      return "Insert '\(newText)'"
    case (true, true):
      logger.fault("Both oldText and newText of FixIt are empty")
      return "Fix"
    }
  }
}

extension TextEdit {

  /// Creates a TextEdit from a sourcekitd fixit response dictionary.
  init?(fixit: SKDResponseDictionary, in snapshot: DocumentSnapshot) {
    let keys = fixit.sourcekitd.keys
    if let utf8Offset: Int = fixit[keys.offset],
      let length: Int = fixit[keys.length],
      let replacement: String = fixit[keys.sourceText],
      length > 0 || !replacement.isEmpty
    {
      // Snippets are only suppored in code completion.
      // Remove SourceKit placeholders from Fix-Its because they can't be represented in the editor properly.
      let replacementWithoutPlaceholders = rewriteSourceKitPlaceholders(in: replacement, clientSupportsSnippets: false)

      // If both the replacement without placeholders and the fixit are empty, no TextEdit should be created.
      if (replacementWithoutPlaceholders.isEmpty && length == 0) {
        return nil
      }

      let position = snapshot.positionOf(utf8Offset: utf8Offset)
      let endPosition = snapshot.positionOf(utf8Offset: utf8Offset + length)
      self.init(range: position..<endPosition, newText: replacementWithoutPlaceholders)
    } else {
      return nil
    }
  }
}

fileprivate extension String {
  /// Returns this string with the first letter uppercased.
  ///
  /// If the string does not start with a letter, no change is made to it.
  func withFirstLetterUppercased() -> String {
    if let firstLetter = self.first {
      return firstLetter.uppercased() + self.dropFirst()
    } else {
      return self
    }
  }
}

extension Diagnostic {

  /// Creates a diagnostic from a sourcekitd response dictionary.
  ///
  /// `snapshot` is the snapshot of the document for which the diagnostics are generated.
  /// `documentManager` is used to resolve positions of notes in secondary files.
  init?(
    _ diag: SKDResponseDictionary,
    in snapshot: DocumentSnapshot,
    documentManager: DocumentManager,
    useEducationalNoteAsCode: Bool
  ) {
    let keys = diag.sourcekitd.keys
    let values = diag.sourcekitd.values

    guard let filePath: String = diag[keys.filePath] else {
      logger.fault("Missing file path in diagnostic")
      return nil
    }
    guard filePath == snapshot.uri.pseudoPath else {
      logger.error("Ignoring diagnostic from a different file: \(filePath)")
      return nil
    }

    guard let message: String = diag[keys.description]?.withFirstLetterUppercased() else { return nil }

    var range: Range<Position>? = nil
    if let line: Int = diag[keys.line],
      let utf8Column: Int = diag[keys.column],
      line > 0, utf8Column > 0
    {
      range = Range(snapshot.positionOf(zeroBasedLine: line - 1, utf8Column: utf8Column - 1))
    } else if let utf8Offset: Int = diag[keys.offset] {
      range = Range(snapshot.positionOf(utf8Offset: utf8Offset))
    }

    // If the diagnostic has a range associated with it that starts at the same location as the diagnostics position, use it to retrieve a proper range for the diagnostic, instead of just reporting a zero-length range.
    (diag[keys.ranges] as SKDResponseArray?)?.forEach { index, skRange in
      guard let utf8Offset: Int = skRange[keys.offset],
        let length: Int = skRange[keys.length]
      else {
        return true  // continue
      }
      let start = snapshot.positionOf(utf8Offset: utf8Offset)
      let end = snapshot.positionOf(utf8Offset: utf8Offset + length)
      guard start == range?.lowerBound else {
        return true
      }

      range = start..<end
      return false  // terminate forEach
    }

    guard let range = range else {
      return nil
    }

    var severity: LanguageServerProtocol.DiagnosticSeverity? = nil
    if let uid: sourcekitd_api_uid_t = diag[keys.severity] {
      switch uid {
      case values.diagError:
        severity = .error
      case values.diagWarning:
        severity = .warning
      default:
        break
      }
    }

    var code: DiagnosticCode? = nil
    var codeDescription: CodeDescription? = nil
    // If this diagnostic has one or more educational notes, the first one is
    // treated as primary and used to fill in the diagnostic code and
    // description. `useEducationalNoteAsCode` ensures a note name is only used
    // as a code if the cline supports an extended code description.
    if useEducationalNoteAsCode,
      let educationalNotePaths: SKDResponseArray = diag[keys.educationalNotePaths],
      educationalNotePaths.count > 0,
      let primaryPath = educationalNotePaths[0]
    {
      let url = URL(fileURLWithPath: primaryPath)
      let name = url.deletingPathExtension().lastPathComponent
      code = .string(name)
      codeDescription = .init(href: DocumentURI(url))
    }

    var actions: [CodeAction]? = nil
    if let skfixits: SKDResponseArray = diag[keys.fixits],
      let action = CodeAction(fixits: skfixits, in: snapshot, fromNote: nil)
    {
      actions = [action]
    }

    var notes: [DiagnosticRelatedInformation]? = nil
    if let sknotes: SKDResponseArray = diag[keys.diagnostics] {
      notes = []
      sknotes.forEach { (_, sknote) -> Bool in
        guard
          let note = DiagnosticRelatedInformation(
            sknote,
            primaryDocumentSnapshot: snapshot,
            documentManager: documentManager
          )
        else { return true }
        notes?.append(note)
        return true
      }
    }

    var tags: [DiagnosticTag] = []
    if let categories: SKDResponseArray = diag[keys.categories] {
      categories.forEachUID { (_, category) in
        switch category {
        case values.diagDeprecation:
          tags.append(.deprecated)
        case values.diagNoUsage:
          tags.append(.unnecessary)
        default:
          break
        }
        return true
      }
    }

    self.init(
      range: range,
      severity: severity,
      code: code,
      codeDescription: codeDescription,
      source: "SourceKit",
      message: message,
      tags: tags,
      relatedInformation: notes,
      codeActions: actions
    )
  }

  init(
    _ diag: SwiftDiagnostics.Diagnostic,
    in snapshot: DocumentSnapshot
  ) {
    // Start with a zero-length range based on the position.
    // If the diagnostic has highlights associated with it that start at the
    // position, use that as the diagnostic's range.
    var range = Range(snapshot.position(of: diag.position))
    for highlight in diag.highlights {
      let swiftSyntaxRange = highlight.positionAfterSkippingLeadingTrivia..<highlight.endPositionBeforeTrailingTrivia
      let highlightRange = snapshot.range(of: swiftSyntaxRange)
      if range.upperBound == highlightRange.lowerBound {
        range = range.lowerBound..<highlightRange.upperBound
      } else {
        break
      }
    }

    let relatedInformation = diag.notes.compactMap { DiagnosticRelatedInformation($0, in: snapshot) }
    let codeActions = diag.fixIts.compactMap { CodeAction($0, in: snapshot) }

    self.init(
      range: range,
      severity: diag.diagMessage.severity.lspSeverity,
      code: nil,
      codeDescription: nil,
      source: "SourceKit",
      message: diag.message,
      tags: nil,
      relatedInformation: relatedInformation,
      codeActions: codeActions
    )
  }
}

extension DiagnosticRelatedInformation {

  /// Creates related information from a sourcekitd note response dictionary.
  ///
  /// `primaryDocumentSnapshot` is the snapshot of the document for which the diagnostics are generated.
  /// `documentManager` is used to resolve positions of notes in secondary files.
  init?(_ diag: SKDResponseDictionary, primaryDocumentSnapshot: DocumentSnapshot, documentManager: DocumentManager) {
    let keys = diag.sourcekitd.keys

    guard let filePath: String = diag[keys.filePath] else {
      logger.fault("Missing file path in related diagnostic information")
      return nil
    }
    let uri = DocumentURI(filePath: filePath, isDirectory: false)
    let snapshot: DocumentSnapshot
    if filePath == primaryDocumentSnapshot.uri.pseudoPath {
      snapshot = primaryDocumentSnapshot
    } else if let inMemorySnapshot = try? documentManager.latestSnapshot(uri) {
      snapshot = inMemorySnapshot
    } else if let snapshotFromDisk = try? DocumentSnapshot(withContentsFromDisk: uri, language: .swift) {
      snapshot = snapshotFromDisk
    } else {
      return nil
    }

    var position: Position? = nil
    if let line: Int = diag[keys.line],
      let utf8Column: Int = diag[keys.column],
      line > 0, utf8Column > 0
    {
      position = snapshot.positionOf(zeroBasedLine: line - 1, utf8Column: utf8Column - 1)
    } else if let utf8Offset: Int = diag[keys.offset] {
      position = snapshot.positionOf(utf8Offset: utf8Offset)
    }

    if position == nil {
      return nil
    }

    guard let message: String = diag[keys.description]?.withFirstLetterUppercased() else { return nil }

    var actions: [CodeAction]? = nil
    if let skfixits: SKDResponseArray = diag[keys.fixits],
      let action = CodeAction(fixits: skfixits, in: snapshot, fromNote: message)
    {
      actions = [action]
    }

    self.init(
      location: Location(uri: snapshot.uri, range: Range(position!)),
      message: message,
      codeActions: actions
    )
  }

  init(_ note: Note, in snapshot: DocumentSnapshot) {
    let nodeRange = note.node.positionAfterSkippingLeadingTrivia..<note.node.endPositionBeforeTrailingTrivia
    self.init(
      location: Location(uri: snapshot.uri, range: snapshot.range(of: nodeRange)),
      message: note.message
    )
  }
}

extension Diagnostic {
  func withRange(_ newRange: Range<Position>) -> Diagnostic {
    var updated = self
    updated.range = newRange
    return updated
  }
}

/// Whether a diagostic is semantic or syntatic (parse).
enum DiagnosticStage: Hashable {
  case parse
  case sema
}

extension DiagnosticStage {
  init?(_ uid: sourcekitd_api_uid_t, sourcekitd: SourceKitD) {
    switch uid {
    case sourcekitd.values.parseDiagStage:
      self = .parse
    case sourcekitd.values.semaDiagStage:
      self = .sema
    default:
      let desc = sourcekitd.api.uid_get_string_ptr(uid).map { String(cString: $0) }
      logger.fault("Unknown diagnostic stage \(desc ?? "nil", privacy: .public)")
      return nil
    }
  }
}

fileprivate extension SwiftDiagnostics.DiagnosticSeverity {
  var lspSeverity: LanguageServerProtocol.DiagnosticSeverity {
    switch self {
    case .error: return .error
    case .warning: return .warning
    case .note: return .information
    case .remark: return .hint
    }
  }
}