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
Expand Up @@ -17,12 +17,17 @@ public enum KeywordUppercaseHelper {
(ch >= 0x30 && ch <= 0x39) || ch == 0x5F
}

// Read from the start of the text with the session's grammar: a literal can open any distance back, and where it
// ends is the engine's rule.
static func isInsideProtectedContext(_ text: NSString, at position: Int, grammar: SQLLexicalGrammar) -> Bool {
// Read with the session's grammar from `codeStart`, a point known to sit in code such as the start of the statement:
// a literal can open any distance back, and where it ends is the engine's rule.
static func isInsideProtectedContext(
_ text: NSString,
at position: Int,
from codeStart: Int = 0,
grammar: SQLLexicalGrammar
) -> Bool {
let length = text.length
let runsExecutableComments = grammar.contains(.executableComments)
var index = 0
var index = min(max(0, codeStart), position)
while index < position {
// The server runs the body of `/*! ... */`, so it is code.
if runsExecutableComments, let opener = SqlLexer.executableCommentOpenerLength(text, at: index, length: length) {
Expand All @@ -40,10 +45,13 @@ public enum KeywordUppercaseHelper {
}

// Nil when the word is not a keyword, sits in a comment, a literal or a quoted name, or is already in the target case.
// `codeStart` is where reading for a literal or comment may begin: a statement start the scanner found, or the top.
// Finding it can cost a scan, so it is asked for only once the word is a keyword that would change.
public static func keywordBeforePosition(
_ text: NSString,
at position: Int,
uppercase: Bool = true,
codeStart: @autoclosure () -> Int = 0,
grammar: SQLLexicalGrammar
) -> (word: String, folded: String, range: NSRange)? {
var wordStart = position
Expand All @@ -58,10 +66,10 @@ public enum KeywordUppercaseHelper {

let word = text.substring(with: NSRange(location: wordStart, length: wordLength))
guard SQLKeywords.keywordSet.contains(word.lowercased()) else { return nil }
guard !isInsideProtectedContext(text, at: wordStart, grammar: grammar) else { return nil }

let folded = uppercase ? word.uppercased() : word.lowercased()
guard folded != word else { return nil }
guard !isInsideProtectedContext(text, at: wordStart, from: codeStart(), grammar: grammar) else { return nil }

return (word: word, folded: folded, range: NSRange(location: wordStart, length: wordLength))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -348,4 +348,19 @@ struct KeywordUppercaseHelperTests {
#expect(folds("/*!50001 select", mySQL))
#expect(!folds("/* select", mySQL))
}

@Test("Reading from a statement start finds the same answer as reading from the top")
func codeStartMatchesReadingFromTheTop() {
let head = "SELECT 'it''s';\n-- a note; with a quote '\n"
let start = (head as NSString).length
let text = (head + "SELECT 'from' from") as NSString
let literal = start + 9
let keyword = text.length

#expect(KeywordUppercaseHelper.isInsideProtectedContext(text, at: literal, from: start, grammar: .ansi))
#expect(KeywordUppercaseHelper.isInsideProtectedContext(text, at: literal, grammar: .ansi))
#expect(!KeywordUppercaseHelper.isInsideProtectedContext(text, at: keyword - 4, from: start, grammar: .ansi))
#expect(!KeywordUppercaseHelper.isInsideProtectedContext(text, at: keyword - 4, grammar: .ansi))
#expect(KeywordUppercaseHelper.keywordBeforePosition(text, at: keyword, codeStart: start, grammar: .ansi)?.word == "from")
}
}
7 changes: 5 additions & 2 deletions apple/TablePro/Views/Editor/SQLEditorCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -855,13 +855,16 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie
keywordCase.rewritesTypedText,
KeywordUppercaseHelper.isWordBoundary(string),
PluginManager.shared.editorLanguage(for: databaseType ?? .mysql) == .sql,
(textView.textStorage.string as NSString).length < 500_000 else { return }
textView.textStorage.length < 500_000 else { return }

let nsText = textView.textStorage.string as NSString
let nsText = textView.string as NSString
guard let match = KeywordUppercaseHelper.keywordBeforePosition(
nsText,
at: range.location,
uppercase: keywordCase.prefersUppercase,
codeStart: statementRunController.statementStart(
containing: range.location, in: textView, grammar: lexicalGrammar
),
grammar: lexicalGrammar
) else { return }

Expand Down
83 changes: 74 additions & 9 deletions apple/TablePro/Views/Editor/StatementRunController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ enum StatementNavigationDirection {
// never offers to run something other than what it is drawn beside. The band runs on every caret move, so a SQL
// document resolves it through `SQLStatementCursorIndex`, which rescans only from the last boundary before the caret,
// and a JavaScript or Redis document through a `QueryStatementCaretTable` read once per text.
// The controls need every statement, a full pass of 31ms at the size limit, so that refresh is debounced.
// The controls need every statement, a full pass of 31ms at the size limit, so on a large document that refresh is
// debounced and scanned off the main thread.
@MainActor
final class StatementRunController {
/// The largest document decorations are computed for, in UTF-16 units.
Expand Down Expand Up @@ -136,9 +137,9 @@ final class StatementRunController {
/// every keystroke rather than for everything but the last 150ms of typing.
func scheduleControlsRefresh(in controller: TextViewController?) {
pendingRefresh?.cancel()
guard let controller else { return }
guard let controller, let textView = controller.textView else { return }

if controller.textView?.textStorage.length ?? 0 <= Self.synchronousRefreshLimit {
if textView.textStorage.length <= Self.synchronousRefreshLimit {
refreshControls(in: controller)
return
}
Expand All @@ -150,18 +151,61 @@ final class StatementRunController {
}
}

/// Recomputes the run controls now, without waiting out the debounce.
/// Recomputes the run controls without waiting out the debounce.
///
/// A small document is scanned here, so its controls are in step when this returns. A larger one is scanned off
/// the main thread on a snapshot of the text, and its controls are replaced only if no edit landed meanwhile:
/// the edit schedules a scan of its own.
func refreshControls(in controller: TextViewController?) {
guard let controller, let textView = controller.textView else { return }
let text = textView.string
pendingRefresh?.cancel()
pendingRefresh = nil
guard let controller, let textView = controller.textView, let storage = textView.textStorage else { return }

guard (text as NSString).length <= sizeLimit else {
guard storage.length <= sizeLimit else {
controller.runnableStatements = []
return
}

controller.runnableStatements = QueryStatementScanner
.navigableStatements(in: text, model: statementModel, grammar: grammar)
guard storage.length > Self.synchronousRefreshLimit else {
controller.runnableStatements = Self.statementRuns(in: textView.string, model: statementModel, grammar: grammar)
return
}

if caretIndexStorage !== storage {
observeEdits(on: storage)
}
// Started on the next turn of the main actor, so a call made inside an editing batch reads the text, and
// counts the edit, after the storage has finished processing it.
pendingRefresh = Task { [weak self, weak controller, weak storage] in
guard let self, let controller, let storage, controller.textView?.textStorage === storage else { return }
// Bridging the storage shares its buffer, so the snapshot costs nothing until an edit touches a block.
let text = controller.textView.string
let serial = self.editSerial
let model = self.statementModel
let grammar = self.grammar
let runs = await Self.scanStatementRuns(in: text, model: model, grammar: grammar)
guard !Task.isCancelled, controller.textView?.textStorage === storage,
self.editSerial == serial, self.statementModel == model, self.grammar == grammar else { return }
controller.runnableStatements = runs
}
}

@concurrent
nonisolated private static func scanStatementRuns(
in text: String,
model: QueryStatementModel,
grammar: SQLLexicalGrammar
) async -> [StatementRun] {
statementRuns(in: text, model: model, grammar: grammar)
}

nonisolated private static func statementRuns(
in text: String,
model: QueryStatementModel,
grammar: SQLLexicalGrammar
) -> [StatementRun] {
QueryStatementScanner
.navigableStatements(in: text, model: model, grammar: grammar)
.map { StatementRun(range: $0.contentRange) }
}

Expand Down Expand Up @@ -231,6 +275,27 @@ final class StatementRunController {
return indexedStatement(at: cursor, in: text, storage: storage)
}

/// Where the statement holding `offset` starts, or 0 where the index does not answer for this document or grammar.
///
/// A statement never starts inside a literal or a comment, so a reader that has to know whether `offset` is in one
/// can begin here rather than at the top of the document. Not remembered as the caret's statement: `offset` is
/// rarely the caret.
func statementStart(containing offset: Int, in textView: TextView, grammar requested: SQLLexicalGrammar) -> Int {
guard statementModel == .sql, grammar == requested,
let storage = textView.textStorage, storage.length <= sizeLimit else { return 0 }
if caretIndexStorage !== storage {
observeEdits(on: storage)
}
if storage.editedMask.contains(.editedCharacters) {
textDidChange(at: storage.editedRange.location)
}
if caretIndex == nil {
caretIndex = SQLStatementCursorIndex(grammar: grammar)
}
let start = caretIndex?.statementAtCursor(offset, in: textView.string).offset ?? 0
return min(start, offset)
}

// Only where the band keeps the index warm at the caret. `text` is the storage's text as it is now.
func maintainedStatement(
at cursor: Int,
Expand Down
58 changes: 58 additions & 0 deletions apple/TableProTests/Views/Editor/StatementRunControllerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import TableProEditorKit
import TableProGrammars
import TableProPluginKit
import TableProSQLGrammar
import TableProTestSupport
import TableProTextEngine
import Testing

Expand Down Expand Up @@ -249,6 +250,63 @@ struct StatementRunControllerTests {
#expect(subject.caretIndexUnitsScanned - warmed <= moves * (SQLStatementCursorIndex.defaultCheckpointSpacing + 20))
}

// A document past the synchronous limit: a full pass of it on the keystroke's turn is what stalled typing.
private var largeScript: String {
String(repeating: "SELECT id, name FROM users WHERE id = 1;\n", count: 2_000)
}

private func freshControls(in controller: TextViewController) -> [NSRange] {
SQLStatementScanner.navigableStatements(in: controller.textView.string, grammar: TestGrammar.standard)
.map(\.contentRange)
}

@Test("A large document's controls are scanned off the main thread and then equal a fresh scan")
func largeDocumentControlsArriveFromABackgroundScan() async throws {
let controller = makeController(text: largeScript)
try #require(controller.textView.textStorage.length > StatementRunController.synchronousRefreshLimit)
let subject = makeSubject()

subject.install(on: controller)
#expect(controller.runnableStatements.isEmpty)

try await waitUntil { !controller.runnableStatements.isEmpty }
#expect(controller.runnableStatements.map(\.range) == freshControls(in: controller))
}

@Test("A large document's refresh asked for before an edit reads the edited text")
func largeRefreshReadsTheTextAfterTheEdit() async throws {
let controller = makeController(text: largeScript)
let subject = makeSubject()
subject.install(on: controller)
try await waitUntil { !controller.runnableStatements.isEmpty }

subject.refreshControls(in: controller)
controller.textView.replaceCharacters(in: NSRange(location: 0, length: 0), with: "SELECT 0;\n")

try await waitUntil { controller.runnableStatements.count == 2_001 }
#expect(controller.runnableStatements.map(\.range) == freshControls(in: controller))
}

@Test("The statement start keyword case reads from is the statement's own, and costs one statement's scan")
func statementStartForKeywordCaseIsBounded() {
let script = String(repeating: "SELECT 1;\n", count: 40_000)
let controller = makeController(text: script)
let subject = makeSubject()
subject.install(on: controller)
let textView = controller.textView!
let end = textView.textStorage.length
_ = subject.statementStart(containing: end, in: textView, grammar: TestGrammar.standard)
let warmed = subject.caretIndexUnitsScanned

textView.replaceCharacters(in: NSRange(location: end, length: 0), with: "select")
let start = subject.statementStart(containing: end + 6, in: textView, grammar: TestGrammar.standard)

let fresh = SQLStatementScanner.locatedStatementAtCursor(in: textView.string, cursorPosition: end + 6)
#expect(start == fresh.offset)
#expect(subject.caretIndexUnitsScanned - warmed <= SQLStatementCursorIndex.defaultCheckpointSpacing + 20)
#expect(subject.statementStart(containing: end, in: textView, grammar: TestGrammar.mysql) == 0)
}

// MARK: - Callback

@Test("Pressing a control reports that control's own statement, not the caret's")
Expand Down
1 change: 1 addition & 0 deletions apple/changelog.d/4571.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Typing in a large SQL script no longer pauses while the run buttons in the gutter update.
Loading