Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 42 additions & 4 deletions Sources/AnyLanguageModel/Shared/JSONCompleter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,9 @@ struct JSONCompleter: Sendable {

/// Completes a string that starts at the given index.
///
/// If the text ends inside an escape sequence, the completion keeps only the
/// text before the backslash so that the result is valid JSON.
/// If the text ends inside an escape sequence or an incomplete UTF-16
/// surrogate pair, the completion cuts back to the start of the incomplete
/// sequence so that the result is valid JSON.
private func completeString(_ json: String, from startIndex: String.Index) -> Completion? {
guard startIndex < json.endIndex, json[startIndex] == "\"" else { return nil }

Expand All @@ -134,14 +135,51 @@ struct JSONCompleter: Sendable {
return (string: "\"", endIndex: escapeStart)
}
if json[current] == "u" {
let hexStart = json.index(after: current)
current = hexStart
var remaining = 4
current = json.index(after: current)
while remaining > 0 && current < json.endIndex && json[current].isHexDigit {
current = json.index(after: current)
remaining -= 1
}
if remaining > 0 {
return (string: "\"", endIndex: escapeStart)
if current == json.endIndex {
return (string: "\"", endIndex: escapeStart)
}
continue
}
if let codeUnit = UInt16(json[hexStart ..< current], radix: 16),
(0xD800 ... 0xDBFF).contains(codeUnit)
{
guard current < json.endIndex else {
return (string: "\"", endIndex: escapeStart)
}
if json[current] == "\\" {
let lowAfterSlash = json.index(after: current)
guard lowAfterSlash < json.endIndex else {
return (string: "\"", endIndex: escapeStart)
}
if json[lowAfterSlash] == "u" {
let lowHexStart = json.index(after: lowAfterSlash)
var lowCurrent = lowHexStart
var lowRemaining = 4
while lowRemaining > 0 && lowCurrent < json.endIndex && json[lowCurrent].isHexDigit {
lowCurrent = json.index(after: lowCurrent)
lowRemaining -= 1
}
if lowRemaining > 0 {
if lowCurrent == json.endIndex {
return (string: "\"", endIndex: escapeStart)
}
continue
}
if let lowCodeUnit = UInt16(json[lowHexStart ..< lowCurrent], radix: 16),
(0xDC00 ... 0xDFFF).contains(lowCodeUnit)
{
current = lowCurrent
}
}
}
}
continue
}
Expand Down
39 changes: 39 additions & 0 deletions Tests/AnyLanguageModelTests/JSONCompleterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,45 @@ struct JSONCompleterTests {
#expect(isValidJSON(try completer.complete(#"{"a": "x\\"#)))
}

@Test func handlesPartialSurrogatePairs() throws {
// Every prefix of a surrogate-pair escape (\uD83D\uDE00 = 😀) must complete to valid JSON.
#expect(try completer.complete(#""Hi \uD83D"#) == #""Hi ""#)
#expect(try completer.complete(#""Hi \uD83D\"#) == #""Hi ""#)
#expect(try completer.complete(#""Hi \uD83D\u"#) == #""Hi ""#)
#expect(try completer.complete(#""Hi \uD83D\uDE"#) == #""Hi ""#)
#expect(try completer.complete(#""Hi \uD83D\uDE0"#) == #""Hi ""#)
#expect(try completer.complete(#""Hi \uD83D\uDE00"#) == #""Hi \uD83D\uDE00""#)

// Works with lowercase hex and inside object values and keys too.
#expect(try completer.complete(#"{"emoji": "Hi \ud83d"#) == #"{"emoji": "Hi "}"#)
#expect(try completer.complete(#"{"emoji": "Hi \ud83d\ude"#) == #"{"emoji": "Hi "}"#)
#expect(try completer.complete(#"{"\uD83D"#) == #"{"": null}"#)

// Every character-by-character prefix of a JSON object with surrogate pairs decodes as JSON.
let full = #"{"emoji": "Hi \uD83D\uDE00 and \ud83c\udf89"}"#
var index = full.index(after: full.startIndex)
while index <= full.endIndex {
let prefix = String(full[..<index])
let completed = try completer.complete(prefix)
#expect(isValidJSON(completed), "Invalid JSON for prefix: \(prefix) -> \(completed)")
if index == full.endIndex { break }
index = full.index(after: index)
}

// GeneratedContent(json:) keeps structured object kind across partial surrogate pairs.
let partial = try GeneratedContent(json: #"{"emoji": "Hi \uD83D\uDE"#)
#expect(try partial.value(String.self, forProperty: "emoji") == "Hi ")

// Malformed escapes before the end of input must not cut back and drop trailing properties.
let malformedSurrogate = #"{"a":"\uD83D\uDE","b":1}"#
#expect(try completer.complete(malformedSurrogate) == malformedSurrogate)
#expect(try GeneratedContent(json: malformedSurrogate).kind == .string(malformedSurrogate))

let malformedEscape = #"{"a":"\u12","b":1}"#
#expect(try completer.complete(malformedEscape) == malformedEscape)
#expect(try GeneratedContent(json: malformedEscape).kind == .string(malformedEscape))
}

@Test func handlesEmptyAndWhitespaceInput() throws {
#expect(try completer.complete("") == "")
#expect(try completer.complete(" ") == " ")
Expand Down
Loading