File: CompletionSession.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 (286 lines) | stat: -rw-r--r-- 10,302 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
//===----------------------------------------------------------------------===//
//
// 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 CompletionScoring
import Csourcekitd
import Foundation
import SKLogging
import SourceKitD

/// Represents a code completion session.
///
/// A code completion session is code completion invoked at a specific location. We might filter results as the user
/// types more characters but the fundamental set of results doesn't change during the session. Invoking code completion
/// at a different location or making an edit to the source file that doesn't filter the code completion results should
/// start a new completion session.
final class CompletionSession {
  /// The connection to sourcekitd from which we get the raw set of results.
  private let connection: Connection

  /// The location at which code completion was invoked.
  let location: Location

  /// A handle to the set of results for this session in sourcekitd. This allows us to retrieve additional information
  /// for each code completion item from sourcekitd.
  let response: swiftide_api_completion_response_t

  /// The list of code completion items available in this session, without any filters applied.
  let items: [ASTCompletionItem]

  /// The filter names for all code completion items in a `CandidateBatch`, which is used for sorting.
  let filterCandidates: CandidateBatch

  /// Information about popular symbols to influence scoring.
  private let popularityIndex: PopularityIndex?
  private let popularityTable: PopularityTable?

  /// Information about the code completion session that applies to all completion items, like what kind of completion
  /// we are performing (member completion, global completion, ...).
  private let context: CompletionContext

  /// Completion options that were set by client when the code completion session was opened.
  let options: CompletionOptions

  /// Convenience accessor to the `SourceKitD` instance.
  var sourcekitd: SourceKitD { connection.sourcekitd }

  var logger: Logger { connection.logger }

  init(
    connection: Connection,
    location: Location,
    response: swiftide_api_completion_response_t,
    options: CompletionOptions
  ) {
    let sourcekitd = connection.sourcekitd
    self.connection = connection
    self.location = location
    self.response = response
    self.options = options
    self.popularityIndex = connection.popularityIndex
    self.popularityTable = connection.popularityTable

    let completionKind = CompletionContext.Kind(connection.sourcekitd.ideApi.completion_result_get_kind(response))

    var memberAccessTypes: [String] = []
    sourcekitd.ideApi.completion_result_foreach_baseexpr_typename(response) { charPtr in
      memberAccessTypes.append(String(cString: charPtr!))
      return false
    }
    var baseExprScope: PopularityIndex.Scope? = nil
    if let popularityIndex = popularityIndex {
      // Use the first scope found in 'popularityIndex'.
      for typeName in memberAccessTypes {
        let scope = PopularityIndex.Scope(string: typeName)
        if popularityIndex.isKnownScope(scope) {
          baseExprScope = scope
          break
        }
      }
    }

    let context = CompletionContext(
      kind: completionKind,
      memberAccessTypes: memberAccessTypes,
      baseExprScope: baseExprScope
    )
    self.context = context

    var candidateStrings: [String] = []

    var items: [ASTCompletionItem] = []
    sourcekitd.ideApi.completion_result_get_completions(response) { itemsPtr, filterPtr, numItems in
      items.reserveCapacity(Int(numItems))
      candidateStrings.reserveCapacity(Int(numItems))
      let citems = UnsafeBufferPointer(start: itemsPtr, count: Int(numItems))
      let cfilters = UnsafeBufferPointer(start: filterPtr, count: Int(numItems))
      for i in 0..<Int(numItems) {
        let citem = citems[i]
        let cfilter = cfilters[i]
        let item = ASTCompletionItem(
          citem!,
          filterName: cfilter,
          completionKind: context.kind,
          index: UInt32(i),
          sourcekitd: sourcekitd
        )
        candidateStrings.append(item.filterName)
        items.append(item)
      }
    }

    self.items = items
    self.filterCandidates = CandidateBatch(candidates: candidateStrings, contentType: .codeCompletionSymbol)
    precondition(items.count == filterCandidates.count)
  }

  var totalCount: Int {
    return items.count
  }

  func completions(matchingFilterText filterText: String, maxResults: Int) -> [CompletionItem] {
    let sorting = CompletionSorting(filterText: filterText, in: self)
    let range =
      location.position..<Position(line: location.line, utf8Column: location.utf8Column + filterText.utf8.count)
    return sorting.withScoredAndFilter(maxResults: maxResults) { (matches) -> [CompletionItem] in
      var nextGroupId = 1  // NOTE: Never use zero. 0 can be considered null groupID.
      var baseNameToGroupId: [String: Int] = [:]

      return matches.map {
        CompletionItem(
          items[$0.index],
          score: $0.score,
          in: self,
          completionReplaceRange: range,
          groupID: { (baseName: String) -> Int in
            if let entry = baseNameToGroupId[baseName] {
              return entry
            } else {
              let groupId = nextGroupId
              baseNameToGroupId[baseName] = groupId
              nextGroupId += 1
              return groupId
            }
          }
        )
      }
    }
  }

  deinit {
    sourcekitd.ideApi.completion_result_dispose(response)
  }

  func popularity(ofSymbol name: String, inModule module: String?) -> Popularity? {
    guard let popularityIndex = self.popularityIndex else {
      // Fall back to deprecated 'popularityTable'.
      if let popularityTable = self.popularityTable {
        return popularityTable.popularity(symbol: name, module: module)
      }

      return nil
    }

    let shouldUseBaseExprScope: Bool
    // Use the base expression scope, for member completions.
    switch completionKind {
    case .dotExpr, .unresolvedMember, .postfixExpr, .keyPathExprSwift, .keyPathExprObjC:
      shouldUseBaseExprScope = true
    default:
      // FIXME: 'baseExprScope' might still be populated for implicit self
      // members. e.g. global expression completion in a method.
      // We might want to use `baseExprScope` if the symbol is a type member.
      shouldUseBaseExprScope = false
    }

    let scope: PopularityIndex.Scope
    // 'baseExprScope == nil' means the 'PopularityIndex' doesn't know the scope.
    // Fallback to the symbol module scope.
    if shouldUseBaseExprScope, let baseExprScope = context.baseExprScope {
      scope = baseExprScope
    } else {
      guard let module = module else {
        // Keywords, etc. don't belong to any module.
        return nil
      }
      scope = PopularityIndex.Scope(container: nil, module: module)
    }

    // Extract the base name from 'name'.
    let baseName: String
    if let parenIdx = name.firstIndex(of: "(") {
      baseName = String(name[..<parenIdx])
    } else {
      baseName = name
    }

    return popularityIndex.popularity(of: PopularityIndex.Symbol(name: baseName, scope: scope))
  }

  func extendedCompletionInfo(for id: CompletionItem.Identifier) -> ExtendedCompletionInfo? {
    return ExtendedCompletionInfo(session: self, index: Int(id.index))
  }

  var completionKind: CompletionContext.Kind { context.kind }
  var memberAccessTypes: [String] { context.memberAccessTypes }
}

/// Information about code completion items that is not returned to the client with the initial results but that the
/// client needs to request for each item with a separate request. It is intended that the client only requests this
/// information when more information about a code completion items should be displayed, eg. because the user selected
/// it.
struct ExtendedCompletionInfo {
  private let session: CompletionSession

  /// The index of the item to get extended information for in `session.items`.
  private let index: Int

  private var rawItem: swiftide_api_completion_item_t { session.items[index].impl }

  init(session: CompletionSession, index: Int) {
    self.session = session
    self.index = index
  }

  var briefDocumentation: String? {
    var result: String? = nil
    session.sourcekitd.ideApi.completion_item_get_doc_brief(session.response, rawItem) {
      if let cstr = $0 {
        result = String(cString: cstr)
      }
    }
    return result
  }

  var associatedUSRs: [String] {
    var result: [String] = []
    session.sourcekitd.ideApi.completion_item_get_associated_usrs(session.response, rawItem) { ptr, len in
      result.reserveCapacity(Int(len))
      for usr in UnsafeBufferPointer(start: ptr, count: Int(len)) {
        if let cstr = usr {
          result.append(String(cString: cstr))
        }
      }
    }
    return result
  }

  var diagnostic: CompletionItem.Diagnostic? {
    var result: CompletionItem.Diagnostic? = nil
    session.sourcekitd.ideApi.completion_item_get_diagnostic(session.response, rawItem) { severity, message in
      if let severity = CompletionItem.Diagnostic.Severity(severity) {
        result = .init(severity: severity, description: String(cString: message!))
      }
    }
    return result
  }
}

extension CompletionItem.Diagnostic.Severity {
  init?(_ ideValue: swiftide_api_completion_diagnostic_severity_t) {
    switch ideValue {
    case SWIFTIDE_COMPLETION_DIAGNOSTIC_SEVERITY_ERROR:
      self = .error
    case SWIFTIDE_COMPLETION_DIAGNOSTIC_SEVERITY_WARNING:
      self = .warning
    case SWIFTIDE_COMPLETION_DIAGNOSTIC_SEVERITY_REMARK:
      self = .remark
    case SWIFTIDE_COMPLETION_DIAGNOSTIC_SEVERITY_NOTE:
      self = .note
    case SWIFTIDE_COMPLETION_DIAGNOSTIC_SEVERITY_NONE:
      return nil
    default:
      // FIXME: Handle unknown severity?
      return nil
    }
  }
}