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
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import Foundation
import os
import TableProSQLGrammar
import TableProSQLQuoting

public final class SQLCompletionProvider {
// Sendable so a request runs off the caller's actor: an editor asks on the main thread, and analysis, the catalog
// reads and ranking would otherwise all run there, re-entering it after every catalog read.
public final class SQLCompletionProvider: Sendable {
private struct State {
var functionItems: [SQLCompletionItem]?
var favoriteKeywords: [String: (name: String, query: String)] = [:]
}

private let contextAnalyzer = SQLContextAnalyzer()
private let catalog: (any SQLCompletionCatalog)?
public private(set) var grammar: SQLLexicalGrammar
private var vocabulary: SQLCompletionVocabulary
private var cachedFunctionItems: [SQLCompletionItem]?
private var favoriteKeywords: [String: (name: String, query: String)] = [:]
public let grammar: SQLLexicalGrammar
private let vocabulary: SQLCompletionVocabulary
private let state = OSAllocatedUnfairLock(initialState: State())

private var favoriteKeywords: [String: (name: String, query: String)] {
state.withLock { $0.favoriteKeywords }
}

private let defaultMaxSuggestions = 20

Expand All @@ -32,14 +43,8 @@ public final class SQLCompletionProvider {
self.vocabulary = vocabulary
}

public func update(grammar: SQLLexicalGrammar, vocabulary: SQLCompletionVocabulary) {
self.grammar = grammar
self.vocabulary = vocabulary
self.cachedFunctionItems = nil
}

public func updateFavoriteKeywords(_ keywords: [String: (name: String, query: String)]) {
self.favoriteKeywords = keywords
state.withLock { $0.favoriteKeywords = keywords }
}

// `forcedTableReferences` stands in for the FROM clause when the caller already knows the table, as a
Expand All @@ -57,6 +62,9 @@ public final class SQLCompletionProvider {
return (session.items, session.context)
}

// Off the caller's actor from start to end, so a catalog read returns to this request, not to the caller.
// A request a newer one replaced stops between the steps that cost.
@concurrent
public func completionSession(
text: String,
cursorPosition: Int,
Expand All @@ -67,13 +75,17 @@ public final class SQLCompletionProvider {
context = context.replacingTableReferences(forcedTableReferences)
}

if context.isInsideString || context.isInsideComment {
if context.isInsideString || context.isInsideComment || Task.isCancelled {
return SQLCompletionSession(items: [], candidates: [], context: context, candidatesTruncated: false)
}

let limit = maxSuggestions(for: context.clauseType)
let candidates = await getCandidates(for: context)
guard !Task.isCancelled else {
return SQLCompletionSession(items: [], candidates: [], context: context, candidatesTruncated: false)
}
return await Self.rankedSession(
await getCandidates(for: context),
candidates,
context: context,
limit: limit,
pool: sessionPool(for: limit)
Expand Down Expand Up @@ -121,7 +133,7 @@ public final class SQLCompletionProvider {
private func sessionPool(for limit: Int) -> Int { limit * 10 }

private func functionItems() -> [SQLCompletionItem] {
if let cachedFunctionItems { return cachedFunctionItems }
if let cached = state.withLock({ $0.functionItems }) { return cached }
// The generic list writes SYSDATE() and CURRENT_DATE() too, which the engine may reject.
var items = SQLKeywords.functionItems().map { item in
guard vocabulary.bareFunctions.contains(item.label.uppercased()) else { return item }
Expand All @@ -136,8 +148,9 @@ public final class SQLCompletionProvider {
items.append(SQLCompletionItem.function(name, signature: signature, caseFolding: folding))
}
}
cachedFunctionItems = items
return items
let built = items
state.withLock { $0.functionItems = built }
return built
}

// MARK: - Candidate Generation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,13 @@ public enum SQLCompletionTriggerPolicy {
let semicolon = UInt16(UnicodeScalar(";").value)
let newline = UInt16(UnicodeScalar("\n").value)
guard previous == semicolon || previous == newline else { return false }
guard offset < text.length else { return true }

return text.substring(from: offset).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
// Stops at the first character that is not blank instead of copying the rest of the document.
var index = offset
while index < text.length {
guard let scalar = Unicode.Scalar(text.character(at: index)),
CharacterSet.whitespacesAndNewlines.contains(scalar) else { return false }
index += 1
}
return true
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ public struct SQLContext: Sendable {
)
}

public final class SQLContextAnalyzer {
public final class SQLContextAnalyzer: Sendable {
private static let newline = UInt16(UnicodeScalar("\n").value)
private static let openParen = UInt16(UnicodeScalar("(").value)
private static let closeParen = UInt16(UnicodeScalar(")").value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ struct StubCatalog: SQLCompletionCatalog {
var qualifiesInScope = false
// Like the iOS catalog, which quotes a mixed-case name itself because nothing spells it later.
var writesNames = false
// Runs where the provider reads the table list, which is where the request runs.
var onTableRead: (@Sendable () -> Void)?
let keyReads = KeyReads()

final class KeyReads: @unchecked Sendable {
Expand Down Expand Up @@ -61,7 +63,8 @@ struct StubCatalog: SQLCompletionCatalog {
}

func tableCompletionItems() -> [SQLCompletionItem] {
tables.map { SQLCompletionItem.table($0) }
onTableRead?()
return tables.map { SQLCompletionItem.table($0) }
}

func tableCompletionItems(inSchema schema: String) -> [SQLCompletionItem] {
Expand Down Expand Up @@ -505,6 +508,34 @@ struct SQLCompletionProviderIsolationTests {
#expect(session.items.first?.label == "orders")
#expect(executor.enqueuedJobs > 0)
}

// An editor asks on the main actor; analysis and the catalog reads must not run there, or each read re-enters
// the main queue behind the keystroke's own layout and drawing.
@Test("a request made on the main actor reads the catalog off the main thread")
func catalogReadsLeaveTheMainThread() async {
let reads = StubCatalog.KeyReads()
var catalog = StubCatalog(tables: ["orders"], columns: [:])
catalog.onTableRead = { reads.record(Thread.isMainThread ? "main" : "background") }
let provider = SQLCompletionProvider(catalog: catalog, grammar: .ansi, vocabulary: .generic)

let session = await provider.completionSession(text: "SELECT * FROM o", cursorPosition: 15)

#expect(session.items.contains { $0.label == "orders" })
#expect(reads.all == ["background"])
}

@Test("a cancelled request stops before it ranks")
func cancelledRequestStops() async {
let provider = SQLCompletionProvider(
catalog: StubCatalog(tables: ["orders"], columns: [:]), grammar: .ansi, vocabulary: .generic
)
let request = Task {
withUnsafeCurrentTask { $0?.cancel() }
return await provider.completionSession(text: "SELECT * FROM o", cursorPosition: 15)
}

#expect(await request.value.items.isEmpty)
}
}

// The caller's own actor never reaches it, so a job here is work that left the caller.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
public protocol CodeSuggestionDelegate: AnyObject {
func completionTriggerCharacters() -> Set<String>

// Optional. In the turn of the key or command that asks, before the request starts; a request that only
// refreshes an open window, or asks again after one ends, does not call it.
func completionRequestDidBegin(textView: TextViewController)

func completionSuggestionsRequested(
textView: TextViewController,
cursorPosition: CursorPosition,
Expand Down Expand Up @@ -42,6 +46,7 @@ public protocol CodeSuggestionDelegate: AnyObject {

public extension CodeSuggestionDelegate {
func completionTriggerCharacters() -> Set<String> { [] }
func completionRequestDidBegin(textView: TextViewController) { }
func completionNeedsFreshItems(textView: TextViewController, cursorPosition: CursorPosition) -> Bool { false }
func completionWindowDidShow(textView: TextViewController, itemCount: Int) { }
func completionWindowDidClose() { }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ final class SuggestionViewModel: ObservableObject {

private var lastDroppedMovePresents = false

private var refresh: (generation: Int, position: CursorPosition)?
private var isRefreshingItems: Bool { itemsRequestTask != nil && refresh?.generation == requestGeneration }
private var refreshGeneration: Int?
private var isRefreshingItems: Bool { itemsRequestTask != nil && refreshGeneration == requestGeneration }

weak var delegate: CodeSuggestionDelegate?

Expand Down Expand Up @@ -272,9 +272,9 @@ final class SuggestionViewModel: ObservableObject {
resetSelection()
syntaxHighlightedCache = [:]
notifySelection()
// A deletion arrives here as a plain move, so the delegate, not the trigger, decides.
let isRefreshingHere = isRefreshingItems && refresh?.position == position
if !isRefreshingHere, delegate.completionNeedsFreshItems(textView: textView, cursorPosition: position) {
// A deletion arrives here as a plain move, so the delegate, not the trigger, decides. One refresh runs at
// a time: when it lands it asks again for the caret as it is then, so typing never stacks requests.
if !isRefreshingItems, delegate.completionNeedsFreshItems(textView: textView, cursorPosition: position) {
refreshItems(textView: textView, delegate: delegate, cursorPosition: position)
}
return
Expand All @@ -298,7 +298,7 @@ final class SuggestionViewModel: ObservableObject {
itemsRequestTask?.cancel()
requestGeneration &+= 1
let generation = requestGeneration
refresh = (generation, cursorPosition)
refreshGeneration = generation
itemsRequestTask = Task {
defer {
if self.requestGeneration == generation {
Expand All @@ -315,7 +315,14 @@ final class SuggestionViewModel: ObservableObject {
self.isPresented, self.activeTextView === textView else { return }

guard let response else {
self.onRequestClose?()
// Nothing for the prefix it ran on; a key typed meanwhile may still have answers. Only the range says
// the caret moved: a typed key reports no line or column, and the editor's own position has both.
if let liveCursor = textView.cursorPositions.first, liveCursor.range != cursorPosition.range,
delegate.completionNeedsFreshItems(textView: textView, cursorPosition: liveCursor) {
self.refreshItems(textView: textView, delegate: delegate, cursorPosition: liveCursor)
} else {
self.onRequestClose?()
}
return
}
guard let items = self.itemsForLiveEditor(response, textView: textView, delegate: delegate),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ public final class SuggestionController: NSWindowController {
isManualTrigger: Bool = false,
asPopover: Bool = false
) {
delegate.completionRequestDidBegin(textView: textView)
model.showCompletions(
textView: textView,
delegate: delegate,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,124 @@ final class SuggestionLiveCursorTests: XCTestCase {
XCTAssertEqual(model.items.map(\.label), ["ab_target"])
}

// With no wait before a request, a refresh per key would stack work on prefixes already typed past.
@MainActor
func test_refresh_typingDuringItStartsNoSecondRequestAndThenAsksOnceForTheNewestCaret() async throws {
let editor = FocusedEditor(text: "ab x")
defer { editor.close() }
editor.controller.setCursorPositions([CursorPosition(range: NSRange(location: 2, length: 0))])
let delegate = ParkingDelegate(
answers: ["ab": ["ab1"], "a": ["a1", "ab1"]],
reranked: ["a": ["a1", "ab1"], "ab": ["ab1"]],
needsFresh: ["a"]
)
let model = SuggestionViewModel()

model.showCompletions(textView: editor.controller, delegate: delegate, cursorPosition: editor.cursor) { _, _ in }
let first = try XCTUnwrap(model.itemsRequestTask)
await delegate.readTheEditor()
delegate.answer()
await first.value

editor.deleteBackward(reportingTo: model, delegate: delegate)
let refresh = try XCTUnwrap(model.itemsRequestTask)
await delegate.readTheEditor()
delegate.needsFresh = ["a", "ab"]
editor.type("b", reportingTo: model, delegate: delegate) {}

XCTAssertEqual(model.itemsRequestTask, refresh)
delegate.answer()
await refresh.value
let again = try XCTUnwrap(model.itemsRequestTask)
XCTAssertNotEqual(again, refresh)
await delegate.readTheEditor()
delegate.answer()
await again.value

XCTAssertTrue(model.isPresented)
XCTAssertEqual(model.items.map(\.label), ["ab1"])
XCTAssertEqual(delegate.askedAt, [2, 1, 2])
}

// The refresh found nothing for `a`, but `ac` was typed while it ran and still has answers.
@MainActor
func test_refresh_answeringNothingAsksAgainForAKeyTypedWhileItRan() async throws {
let editor = FocusedEditor(text: "ab x")
defer { editor.close() }
editor.controller.setCursorPositions([CursorPosition(range: NSRange(location: 2, length: 0))])
let delegate = ParkingDelegate(
answers: ["ab": ["ab1"], "ac": ["ac1"]],
reranked: ["a": ["a1"], "ac": ["ac0"]],
needsFresh: ["a", "ac"]
)
let model = SuggestionViewModel()
var closeRequests = 0
model.onRequestClose = { closeRequests += 1 }

model.showCompletions(textView: editor.controller, delegate: delegate, cursorPosition: editor.cursor) { _, _ in }
let first = try XCTUnwrap(model.itemsRequestTask)
await delegate.readTheEditor()
delegate.answer()
await first.value

editor.deleteBackward(reportingTo: model, delegate: delegate)
let refresh = try XCTUnwrap(model.itemsRequestTask)
await delegate.readTheEditor()
editor.type("c", reportingTo: model, delegate: delegate) {}
delegate.answer()
await refresh.value

let again = try XCTUnwrap(model.itemsRequestTask)
XCTAssertNotEqual(again, refresh)
await delegate.readTheEditor()
delegate.answer()
await again.value

XCTAssertEqual(closeRequests, 0)
XCTAssertTrue(model.isPresented)
XCTAssertEqual(model.items.map(\.label), ["ac1"])
XCTAssertEqual(delegate.askedAt, [2, 1, 2])
}

// A typed key reports its caret with no line or column, so only the range can say the caret has not moved.
@MainActor
func test_refresh_answeringNothingWithTheCaretUnmovedClosesWithoutAskingAgain() async throws {
let editor = FocusedEditor(text: "ab x")
defer { editor.close() }
editor.controller.setCursorPositions([CursorPosition(range: NSRange(location: 2, length: 0))])
let delegate = ParkingDelegate(
answers: ["ab": ["ab1"]],
reranked: ["ab": ["ab1"], "abc": ["abc0"]],
needsFresh: ["abc"]
)
let model = SuggestionViewModel()
var closeRequests = 0
model.onRequestClose = { closeRequests += 1 }

model.showCompletions(textView: editor.controller, delegate: delegate, cursorPosition: editor.cursor) { _, _ in }
let first = try XCTUnwrap(model.itemsRequestTask)
await delegate.readTheEditor()
delegate.answer()
await first.value

editor.controller.textView.replaceCharacters(in: NSRange(location: 2, length: 0), with: "c")
editor.controller.setCursorPositions([CursorPosition(range: NSRange(location: 3, length: 0))])
model.cursorsUpdated(
textView: editor.controller,
delegate: delegate,
position: CursorPosition(range: NSRange(location: 3, length: 0)),
presentIfNot: true
) {}
let refresh = try XCTUnwrap(model.itemsRequestTask)
await delegate.readTheEditor()
delegate.answer()
await refresh.value

XCTAssertEqual(closeRequests, 1)
XCTAssertNil(model.itemsRequestTask)
XCTAssertEqual(delegate.askedAt, [2, 3])
}

@MainActor
func test_refresh_asksAgainInsteadOfClosingWhenItsAnswerCannotRankARetypedPrefix() async throws {
let editor = FocusedEditor(text: "ab x")
Expand Down
Loading
Loading