Skip to content

Commit f99b707

Browse files
committed
[Completion] Make adjustCompletionLocation() safe for out of range
Make it optional.
1 parent 4b0b0ec commit f99b707

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

Sources/SourceKit/sourcekitd/SwiftLanguageServer.swift

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,11 @@ extension SwiftLanguageServer {
300300
return
301301
}
302302

303-
let completionPos = adjustCompletionLocation(req.params.position, in: snapshot)
303+
guard let completionPos = adjustCompletionLocation(req.params.position, in: snapshot) else {
304+
log("invalid completion position \(req.params.position)")
305+
req.reply(CompletionList(isIncomplete: true, items: []))
306+
return
307+
}
304308

305309
guard let offset = snapshot.utf8Offset(of: completionPos) else {
306310
log("invalid completion position \(req.params.position) (adjusted: \(completionPos)")
@@ -388,13 +392,20 @@ extension SwiftLanguageServer {
388392
}
389393

390394
/// Adjust completion position to the start of identifier characters.
391-
func adjustCompletionLocation(_ pos: Position, in snapshot: DocumentSnapshot) -> Position {
395+
func adjustCompletionLocation(_ pos: Position, in snapshot: DocumentSnapshot) -> Position? {
396+
guard pos.line < snapshot.lineTable.count else {
397+
// Line out of range.
398+
return nil
399+
}
392400
let lineSlice = snapshot.lineTable[pos.line]
393401
let startIndex = lineSlice.startIndex
394402

395403
let identifierChars = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "_"))
396404

397-
var loc = lineSlice.utf16.index(startIndex, offsetBy: pos.utf16index)
405+
guard var loc = lineSlice.utf16.index(startIndex, offsetBy: pos.utf16index, limitedBy: lineSlice.endIndex) else {
406+
// Column out of range.
407+
return nil
408+
}
398409
while loc != startIndex {
399410
let prev = lineSlice.index(before: loc)
400411
if !identifierChars.contains(lineSlice.unicodeScalars[prev]) {

0 commit comments

Comments
 (0)