File: DocCReferenceResolutionService.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (233 lines) | stat: -rw-r--r-- 8,444 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 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 Foundation
import IndexStoreDB
import LanguageServerProtocol
import SKLogging
import SemanticIndex
@_spi(Linkcompletion) @preconcurrency import SwiftDocC
import SwiftExtensions

final class DocCReferenceResolutionService: DocumentationService, Sendable {
  /// The message type that this service accepts.
  static let symbolResolutionMessageType: DocumentationServer.MessageType = "resolve-reference"

  /// The message type that this service responds with when the requested symbol resolution was successful.
  static let symbolResolutionResponseMessageType: DocumentationServer.MessageType = "resolve-reference-response"

  static let handlingTypes = [symbolResolutionMessageType]

  private let contextMap = ThreadSafeBox<[String: DocCReferenceResolutionContext]>(initialValue: [:])

  init() {}

  func addContext(_ context: DocCReferenceResolutionContext, withKey key: String) {
    contextMap.value[key] = context
  }

  @discardableResult func removeContext(forKey key: String) -> DocCReferenceResolutionContext? {
    contextMap.value.removeValue(forKey: key)
  }

  func context(forKey key: String) -> DocCReferenceResolutionContext? {
    contextMap.value[key]
  }

  func process(
    _ message: DocumentationServer.Message,
    completion: @escaping (DocumentationServer.Message) -> ()
  ) {
    do {
      let response = try process(message)
      completion(response)
    } catch {
      completion(createResponseWithErrorMessage(error.localizedDescription))
    }
  }

  private func process(
    _ message: DocumentationServer.Message
  ) throws(ReferenceResolutionError) -> DocumentationServer.Message {
    // Decode the message payload
    guard let payload = message.payload else {
      throw ReferenceResolutionError.nilMessagePayload
    }
    let request = try decode(ConvertRequestContextWrapper<OutOfProcessReferenceResolver.Request>.self, from: payload)
    // Attempt to resolve the reference in the request
    let resolvedReference = try resolveReference(request: request);
    // Encode the response payload
    let encodedResolvedReference = try encode(resolvedReference)
    return createResponse(payload: encodedResolvedReference)
  }

  private func resolveReference(
    request: ConvertRequestContextWrapper<OutOfProcessReferenceResolver.Request>
  ) throws(ReferenceResolutionError) -> OutOfProcessReferenceResolver.Response {
    guard let convertRequestIdentifier = request.convertRequestIdentifier else {
      throw .missingConvertRequestIdentifier
    }
    guard let context = context(forKey: convertRequestIdentifier) else {
      throw .missingContext
    }
    switch request.payload {
    case .symbol(let symbolUSR):
      throw .symbolNotFound(symbolUSR)
    case .asset(let assetReference):
      guard let catalog = context.catalogIndex else {
        throw .indexNotAvailable
      }
      guard let dataAsset = catalog.assets[assetReference.assetName] else {
        throw .assetNotFound
      }
      return .asset(dataAsset)
    case .topic(let topicURL):
      // Check if this is a link to another documentation article
      let relevantPathComponents = topicURL.pathComponents.filter { $0 != "/" }
      let resolvedReference: TopicRenderReference? =
        switch relevantPathComponents.first {
        case NodeURLGenerator.Path.documentationFolderName:
          context.catalogIndex?.articles[topicURL.lastPathComponent]
        case NodeURLGenerator.Path.tutorialsFolderName:
          context.catalogIndex?.tutorials[topicURL.lastPathComponent]
        default:
          nil
        }
      if let resolvedReference {
        return .resolvedInformation(OutOfProcessReferenceResolver.ResolvedInformation(resolvedReference, url: topicURL))
      }
      // Otherwise this must be a link to a symbol
      let urlString = topicURL.absoluteString
      guard let doccSymbolLink = DocCSymbolLink(linkString: urlString) else {
        throw .invalidURLInRequest
      }
      // Don't bother checking to see if the symbol actually exists in the index. This can be time consuming and
      // it would be better to report errors/warnings for unresolved symbols directly within the document, anyway.
      return .resolvedInformation(
        OutOfProcessReferenceResolver.ResolvedInformation(
          symbolURL: topicURL,
          symbolName: doccSymbolLink.symbolName
        )
      )
    }
  }

  private func decode<T: Decodable>(_ type: T.Type, from data: Data) throws(ReferenceResolutionError) -> T {
    do {
      return try JSONDecoder().decode(T.self, from: data)
    } catch {
      throw .decodingFailure(error.localizedDescription)
    }
  }

  private func encode<T: Encodable>(_ value: T) throws(ReferenceResolutionError) -> Data {
    do {
      return try JSONEncoder().encode(value)
    } catch {
      throw .decodingFailure(error.localizedDescription)
    }
  }

  private func createResponseWithErrorMessage(_ message: String) -> DocumentationServer.Message {
    let errorMessage = OutOfProcessReferenceResolver.Response.errorMessage(message)
    let encodedErrorMessage = orLog("Encoding error message for OutOfProcessReferenceResolver.Response") {
      try JSONEncoder().encode(errorMessage)
    }
    return createResponse(payload: encodedErrorMessage)
  }

  private func createResponse(payload: Data?) -> DocumentationServer.Message {
    DocumentationServer.Message(
      type: DocCReferenceResolutionService.symbolResolutionResponseMessageType,
      payload: payload
    )
  }
}

struct DocCReferenceResolutionContext {
  let catalogURL: URL?
  let catalogIndex: DocCCatalogIndex?
}

fileprivate extension OutOfProcessReferenceResolver.ResolvedInformation {
  init(symbolURL: URL, symbolName: String) {
    self = OutOfProcessReferenceResolver.ResolvedInformation(
      kind: .unknownSymbol,
      url: symbolURL,
      title: symbolName,
      abstract: "",
      language: .swift,
      availableLanguages: [.swift],
      platforms: [],
      declarationFragments: nil
    )
  }

  init(_ renderReference: TopicRenderReference, url: URL) {
    let kind: DocumentationNode.Kind
    switch renderReference.kind {
    case .article:
      kind = .article
    case .tutorial, .overview:
      kind = .tutorial
    case .symbol:
      kind = .unknownSymbol
    case .section:
      kind = .unknown
    }

    self.init(
      kind: kind,
      url: url,
      title: renderReference.title,
      abstract: renderReference.abstract.map(\.plainText).joined(),
      language: .swift,
      availableLanguages: [.swift, .objectiveC],
      topicImages: renderReference.images
    )
  }
}

enum ReferenceResolutionError: LocalizedError {
  case nilMessagePayload
  case invalidURLInRequest
  case decodingFailure(String)
  case encodingFailure(String)
  case missingConvertRequestIdentifier
  case missingContext
  case indexNotAvailable
  case symbolNotFound(String)
  case assetNotFound

  var errorDescription: String? {
    switch self {
    case .nilMessagePayload:
      return "Nil message payload provided."
    case .decodingFailure(let error):
      return "The service was unable to decode the given symbol resolution request: '\(error)'."
    case .encodingFailure(let error):
      return "The service failed to encode the result after resolving the symbol: \(error)"
    case .invalidURLInRequest:
      return "Failed to initialize an 'AbsoluteSymbolLink' from the given URL."
    case .missingConvertRequestIdentifier:
      return "The given request was missing a convert request identifier."
    case .missingContext:
      return "The given convert request identifier is not associated with any symbol resolution context."
    case .indexNotAvailable:
      return "An index was not available to complete this request."
    case .symbolNotFound(let symbol):
      return "Unable to find symbol '\(symbol)' in the index."
    case .assetNotFound:
      return "The requested asset could not be found."
    }
  }
}