Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

@@ -0,0 +1,479 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import AppKit
import SwiftUI
final class BASICWorkspaceTests: XCTestCase {
@MainActor func testBlankAndReopenedDevelopmentEditorsLayOutWholeLinesAndRevealTheApprovedChange() async throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: directory) }
let suite = UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")),
displayDefaults: defaults, inputStore: .init(url: directory.appendingPathComponent("input.json")))
let source = (1...60).map { "\($0 * 10) PRINT \"LINE \($0)\"" }.joined(separator: "\n")
let model = BASICDevelopmentModel(machine: machine, directory: directory, initialSource: "")
for (size, appearance) in [(NSSize(width: 1050, height: 760), NSAppearance.Name.aqua),
(NSSize(width: 850, height: 560), .darkAqua)] {
let host = NSHostingView(rootView: BASICDevelopmentView(model: model))
let window = NSWindow(contentRect: NSRect(origin: .zero, size: size),
styleMask: [.titled, .resizable], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
defer { window.close() }
window.appearance = NSAppearance(named: appearance)
window.contentView = host
host.layoutSubtreeIfNeeded()
let editor = try XCTUnwrap(model.assistantEditor)
let scroll = try XCTUnwrap(editor.enclosingScrollView)
let ruler = try XCTUnwrap(scroll.verticalRulerView as? BASICBreakpointRuler)
model.source = source
for _ in 0..<100 where editor.string != source {
try await Task.sleep(for: .milliseconds(10))
host.layoutSubtreeIfNeeded()
}
XCTAssertEqual(editor.string, source)
let layout = try XCTUnwrap(editor.layoutManager)
let container = try XCTUnwrap(editor.textContainer)
func verifyFirstLineFits(_ text: String, file: StaticString = #filePath, line: UInt = #line) {
layout.ensureLayout(for: container)
let end = (text as NSString).range(of: "\n").location - 1
let lastGlyph = layout.glyphIndexForCharacter(at: end)
XCTAssertEqual(layout.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil).minY,
layout.lineFragmentRect(forGlyphAt: lastGlyph, effectiveRange: nil).minY,
"An empty editor must grow past a single character column.", file: file, line: line)
}
// Ordinary source updates and subsequently approved replacements both
// use the same editor. A wide final line must remain horizontally scrollable.
verifyFirstLineFits(source)
let revised = "5 REM NEW TITLE\n" + source + "\n610 REM " + String(repeating: "W", count: 192)
let change = BASICEditorAction(expectedSource: source, operation: .replace(source: revised, undoName: "Approve Title"))
XCTAssertTrue(editor.applyEditorAction(change, revealReplacementAt: 0))
host.layoutSubtreeIfNeeded()
verifyFirstLineFits(revised)
XCTAssertGreaterThan(layout.usedRect(for: container).width, scroll.contentView.bounds.width)
XCTAssertGreaterThan(scroll.contentView.bounds.width, size.width * 0.90)
XCTAssertEqual(editor.selectedRange(), NSRange(location: 0, length: 0))
XCTAssertTrue(ruler.visibleRows().contains { $0.number == 5 })
XCTAssertLessThanOrEqual(scroll.contentView.bounds.origin.x, 1)
}
}
/// Exercise native buttons and their real hit regions without moving the desktop pointer.
@MainActor func testBreakpointGutterHitTargetsTrackLineStateAndScrolling() throws {
for basic in [true, false] {
let size = NSSize(width: 450, height: 170)
let host = NSView(frame: NSRect(origin: .zero, size: size))
let scroll = NSScrollView(frame: host.bounds)
host.addSubview(scroll)
let editor = BASICTextView(frame: NSRect(x: 0, y: 0, width: 400, height: 1400))
editor.font = .monospacedSystemFont(ofSize: 14, weight: .regular)
editor.string = (1...64).map { basic ? "\($0 * 10) PRINT \($0)" : "print(\($0));" }.joined(separator: "\n")
scroll.documentView = editor
let ruler: BreakpointRuler = basic
? BASICBreakpointRuler(textView: editor)
: CLineRuler(scrollView: scroll, orientation: .verticalRuler)
scroll.verticalRulerView = ruler
scroll.hasVerticalRuler = true; scroll.rulersVisible = true
scroll.tile()
var pressed: [Int] = []
ruler.onClick = { pressed.append($0) }
if basic {
editor.configureDebug(points: [], stoppedLine: nil, toggle: { pressed.append($0) })
}
ruler.layoutSubtreeIfNeeded()
func marker(_ line: Int) -> NSButton? {
ruler.subviews.compactMap { $0 as? NSButton }.first { $0.tag == line }
}
let first = basic ? 10 : 1
let second = first * 2
let button = try XCTUnwrap(marker(second))
XCTAssertEqual(button.toolTip, "Set breakpoint on line \(second)")
XCTAssertEqual(button.accessibilityLabel(), button.toolTip)
XCTAssertTrue(ruler.isAccessibilityElement())
XCTAssertTrue(ruler.accessibilityChildren()?.contains { ($0 as? NSButton) === button } == true)
XCTAssertEqual(button.accessibilityIdentifier(), "breakpoint.gutter.line.\(second)")
let center = ruler.convert(NSPoint(x: button.bounds.midX, y: button.bounds.midY), from: button)
XCTAssertIdentical(ruler.hitTest(ruler.convert(center, to: ruler.superview)), button)
button.performClick(nil)
XCTAssertEqual(pressed, [second])
ruler.points = [second]
ruler.layoutSubtreeIfNeeded()
XCTAssertEqual(button.toolTip, "Remove breakpoint on line \(second)")
XCTAssertEqual(marker(first)?.toolTip, "Set breakpoint on line \(first)")
XCTAssertEqual(button.accessibilityLabel(), button.toolTip)
ruler.active = false
ruler.layoutSubtreeIfNeeded()
XCTAssertFalse(button.isEnabled)
ruler.active = true
scroll.contentView.scroll(to: NSPoint(x: 0, y: 520))
scroll.reflectScrolledClipView(scroll.contentView)
ruler.layoutSubtreeIfNeeded()
XCTAssertNil(marker(first))
let scrolled = try XCTUnwrap(ruler.subviews.compactMap { $0 as? NSButton }.first)
XCTAssertGreaterThan(scrolled.tag, second)
XCTAssertEqual(scrolled.toolTip, "Set breakpoint on line \(scrolled.tag)")
}
}
@MainActor func testToolbarBreakpointHelpMatchesTheActiveBASICLine() throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: directory) }
let suite = UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")),
displayDefaults: defaults, inputStore: .init(url: directory.appendingPathComponent("input.json")))
let model = BASICDevelopmentModel(machine: machine, directory: directory)
model.source = " 10 PRINT 1\r\n40 PRINT 2\r\n"
model.cursorChanged((model.source as NSString).range(of: "PRINT 2").location)
XCTAssertEqual(model.cursorBreakpointHelp, "Set breakpoint on line 40")
model.toggleBreakpointAtCursor()
XCTAssertEqual(model.cursorBreakpointHelp, "Remove breakpoint on line 40")
model.cursorChanged(0)
XCTAssertEqual(model.cursorBreakpointHelp, "Set breakpoint on line 10")
model.cursorChanged((model.source as NSString).length)
XCTAssertTrue(model.cursorBreakpointHelp.contains("numbered BASIC statement"))
XCTAssertEqual(model.breakpoints, [40])
}
func testBASICWatchSyntaxAndCanonicalNames() throws {
XCTAssertEqual(BASICWatch("longname$")?.canonical, "LO$")
XCTAssertEqual(BASICWatch(" a(1, 2) ")?.canonical, "A(1,2)")
XCTAssertEqual(BASICWatch("A0")?.canonical, "A0")
for invalid in ["", "A+1", "PEEK(1024)", "RND(1)", "FN F(2)", "A(-1)", "A(1.5)", "A()", "A(32768)", "A(1):PRINT 1", "A=1", "1A", "A(9999999999999999999999999)"] {
// Keyword names are rejected by the parser, even when shaped like an array.
XCTAssertNil(BASICWatch(invalid), invalid)
}
}
@MainActor private final class UndoDelegate: NSObject, NSTextViewDelegate {
let manager=UndoManager()
func undoManager(for view:NSTextView) -> UndoManager? { manager }
}
@MainActor func testUntouchedSampleDoesNotPromptAndRecoveryPreservesEdits() async throws {
let directory=FileManager.default.temporaryDirectory.appendingPathComponent("BASICWorkspace-"+UUID().uuidString)
let suite="BASICWorkspace-"+UUID().uuidString
let defaults=UserDefaults(suiteName:suite)!
defer { defaults.removePersistentDomain(forName:suite); try? FileManager.default.removeItem(at:directory) }
let machine=MachineModel(diskStore:.init(url:directory.appendingPathComponent("disks.json")), displayDefaults:defaults, inputStore:.init(url:directory.appendingPathComponent("input.json")))
let model=BASICDevelopmentModel(machine:machine,directory:directory.appendingPathComponent("draft"))
XCTAssertFalse(model.dirty)
XCTAssertTrue(model.confirmDiscard())
model.source="10 PRINT 42\n"
model.watchEntry = "name$"; model.addWatch()
model.watchEntry = "NAME$"; model.addWatch()
model.watchEntry = "A(2, 1)"; model.addWatch()
model.persistDraft()
let restored=BASICDevelopmentModel(machine:machine,directory:directory.appendingPathComponent("draft"))
XCTAssertEqual(restored.source,"10 PRINT 42\n")
XCTAssertEqual(restored.watches, ["NA$", "A(2,1)"])
XCTAssertTrue(restored.dirty)
XCTAssertNil(restored.fileURL)
// Undoing to the saved source and quitting before the debounce fires
// must not bring back an older dirty recovery copy next launch.
model.source = BASICLanguage.sample
XCTAssertTrue(model.confirmDiscard())
let clean=BASICDevelopmentModel(machine:machine,directory:directory.appendingPathComponent("draft"))
XCTAssertFalse(clean.dirty)
XCTAssertEqual(clean.source,BASICLanguage.sample)
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
}
@MainActor func testStatementHighlightMovesWithinOneLineWithoutEditingOrMovingSelection() {
let view = BASICTextView(frame: NSRect(x: 0, y: 0, width: 600, height: 200))
let source = "10 GOSUB 100:PRINT A\n100 RETURN\n"
view.string = source; view.setSelectedRange(NSRange(location: 0, length: 0))
let first = (source as NSString).range(of: "GOSUB"), second = (source as NSString).range(of: "PRINT")
view.configureDebug(points: [10], stoppedLine: 10, token: first, toggle: { _ in })
let firstColor = view.layoutManager?.temporaryAttribute(.backgroundColor, atCharacterIndex: first.location, effectiveRange: nil) as? NSColor
view.configureDebug(points: [10], stoppedLine: 10, token: second, toggle: { _ in })
let secondColor = view.layoutManager?.temporaryAttribute(.backgroundColor, atCharacterIndex: second.location, effectiveRange: nil) as? NSColor
XCTAssertEqual(firstColor, secondColor)
XCTAssertNotEqual(view.layoutManager?.temporaryAttribute(.backgroundColor, atCharacterIndex: first.location, effectiveRange: nil) as? NSColor, secondColor)
XCTAssertEqual(view.string, source); XCTAssertEqual(view.selectedRange(), NSRange(location: 0, length: 0))
view.configureDebug(points: [10], stoppedLine: nil, toggle: { _ in })
XCTAssertNil(view.layoutManager?.temporaryAttribute(.backgroundColor, atCharacterIndex: second.location, effectiveRange: nil))
}
func testExportNamesUseSafeCoCoDirectoryAndCassetteNames() {
XCTAssertEqual(BASICExportName.normalized(" hello2 "), "HELLO2")
XCTAssertEqual(BASICExportName.normalized("ABCDEFG8"), "ABCDEFG8")
for invalid in ["", " ", "ABCDEFGHI", "HELLO.BAS", "../FOO", "A/B", "A B", "é", "ß", "😀"] {
XCTAssertNil(BASICExportName.normalized(invalid), invalid)
}
XCTAssertEqual(BASICExportName.suggestion(for: nil), "HELLO")
XCTAssertEqual(BASICExportName.suggestion(for: URL(fileURLWithPath: "/tmp/My Game 2026.bas")), "MYGAME20")
XCTAssertEqual(BASICExportName.suggestion(for: URL(fileURLWithPath: "/tmp/😀.bas")), "HELLO")
}
@MainActor func testRejectedExportPreservesSourceBindingAndExistingDestination() async throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("BASICExport-" + UUID().uuidString)
let draftDirectory = directory.appendingPathComponent("draft")
let suite = "BASICExport-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: directory) }
try FileManager.default.createDirectory(at: draftDirectory, withIntermediateDirectories: true)
let sourceURL = directory.appendingPathComponent("Working.bas")
try Data("10 PRINT 1\n".utf8).write(to: sourceURL)
let source = "10 PRINT 42\n"
let draft = BASICDevelopmentModel.Draft(source: source, savedSource: "10 PRINT 1\n", filePath: sourceURL.path, fingerprint: nil)
try JSONEncoder().encode(draft).write(to: draftDirectory.appendingPathComponent("Draft.json"))
let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")), displayDefaults: defaults,
inputStore: .init(url: directory.appendingPathComponent("input.json")))
let model = BASICDevelopmentModel(machine: machine, directory: draftDirectory)
func settled() async throws {
for _ in 0..<1000 {
if !machine.busy { return }
try await Task.sleep(nanoseconds: 10_000_000)
}
throw NSError(domain: "BASICExportTimeout", code: 1)
}
do {
try await settled(); machine.loadDiagnostic(); try await settled()
let destination = directory.appendingPathComponent("Existing.dsk")
let untouched = Data("Existing destination must survive a rejected export".utf8)
try untouched.write(to: destination)
// A diagnostic machine is valid/runnable but has no recognized BASIC
// ROM dictionary. The actual core must reject this before any write.
let result = await model.exportImage(.disk, name: "HELLO", to: destination)
XCTAssertFalse(result)
XCTAssertNotNil(model.message)
XCTAssertEqual(try Data(contentsOf: destination), untouched)
XCTAssertEqual(model.source, source)
XCTAssertEqual(model.fileURL, sourceURL)
XCTAssertTrue(model.dirty)
XCTAssertFalse(model.busy)
XCTAssertEqual(machine.state, .paused)
XCTAssertEqual(try String(contentsOf: sourceURL, encoding: .utf8), "10 PRINT 1\n")
} catch {
await withCheckedContinuation { done in machine.shutdown { done.resume() } }; throw error
}
await withCheckedContinuation { done in machine.shutdown { done.resume() } }
}
func testInlineSuggestionRequiresUniquePartialKeywordAndSafeContext() {
XCTAssertEqual(BASICLanguage.inlineCompletion("10 PRI", at: 6)?.suffix, "NT")
XCTAssertEqual(BASICLanguage.inlineCompletion("10 pri", at: 6)?.word, "PRINT")
for text in ["10 P", "10 GO", "10 PRINT", "10 REM PRI", "10 DATA PRI", "10 PRINT \"PRI", "10 A1PRI"] {
XCTAssertNil(BASICLanguage.inlineCompletion(text, at: (text as NSString).length), text)
}
XCTAssertNil(BASICLanguage.inlineCompletion("10 PRI X", at: 6))
XCTAssertNil(BASICLanguage.inlineCompletion("10 PRINT", at: 6))
XCTAssertEqual(BASICLanguage.inlineCompletion("10PRI", at: 5)?.word, "PRINT")
XCTAssertEqual(BASICLanguage.inlineCompletion("10 PRI\n20 END", at: 6)?.suffix, "NT")
}
func testReturnNumberingFollowsIncrementAndFitsWithoutCollisions() {
func next(_ source: String, _ caret: Int? = nil) -> String? {
BASICLanguage.nextLineInsertion(source, at: caret ?? (source as NSString).length)
}
XCTAssertEqual(next("10 PRINT 1"), "\n20 ")
XCTAssertEqual(next("100 CLS\n125 END"), "\n150 ")
XCTAssertEqual(next("10 CLS\n20 END", 6), "\n15 ")
XCTAssertEqual(next("10 CLS\n12 END", 6), "\n11 ")
XCTAssertNil(next("10 CLS\n11 END", 6))
XCTAssertNil(next("10 CLS\n5 END", 6))
XCTAssertNil(next("10 "))
XCTAssertNil(next("PRINT 1"))
XCTAssertNil(next("10 PRINT 1", 5))
XCTAssertNil(next("63999 END"))
XCTAssertEqual(next("63998 END"), "\n63999 ")
XCTAssertEqual(next("10 CLS\r\n20 END"), "\r\n30 ")
// Out-of-order earlier rows must not cause a duplicate label.
XCTAssertEqual(next("30 END\n10 CLS\n20 PRINT 1"), "\n31 ")
}
@MainActor func testInlinePreviewAcceptanceDismissalSelectionAndUndo() throws {
let delegate = UndoDelegate()
let editor = BASICTextView(frame: NSRect(x: 0, y: 0, width: 400, height: 200))
editor.delegate = delegate; editor.allowsUndo = true; editor.string = "10 PRI"
editor.setSelectedRange(NSRange(location: 6, length: 0)); editor.refreshInlineSuggestion()
XCTAssertEqual(editor.inlineSuggestion?.suffix, "NT")
XCTAssertEqual(editor.string, "10 PRI"); XCTAssertFalse(delegate.manager.canUndo)
editor.cancelOperation(nil); editor.refreshInlineSuggestion()
XCTAssertNil(editor.inlineSuggestion)
editor.setSelectedRange(NSRange(location: 5, length: 0))
editor.setSelectedRange(NSRange(location: 6, length: 0)); editor.refreshInlineSuggestion()
editor.insertTab(nil)
XCTAssertEqual(editor.string, "10 PRINT")
delegate.manager.undo(); XCTAssertEqual(editor.string, "10 PRI")
XCTAssertFalse(delegate.manager.canUndo)
editor.setSelectedRange(NSRange(location: 3, length: 3)); editor.refreshInlineSuggestion()
XCTAssertNil(editor.inlineSuggestion)
editor.setSelectedRange(NSRange(location: 6, length: 0)); editor.isEditable = false; editor.refreshInlineSuggestion()
XCTAssertNil(editor.inlineSuggestion)
}
@MainActor func testAutomaticNumberAndNewlineAreOneUndoableEditAndPasteIsUntouched() {
let delegate = UndoDelegate()
let editor = BASICTextView(frame: NSRect(x: 0, y: 0, width: 400, height: 200))
editor.delegate = delegate; editor.allowsUndo = true; editor.string = "10 PRINT 1"
editor.setSelectedRange(NSRange(location: 10, length: 0))
editor.insertNewline(nil)
XCTAssertEqual(editor.string, "10 PRINT 1\n20 ")
delegate.manager.undo(); XCTAssertEqual(editor.string, "10 PRINT 1")
XCTAssertFalse(delegate.manager.canUndo)
editor.insertText("10 PRINT 1\n20 END\n", replacementRange: NSRange(location: 0, length: 10))
XCTAssertEqual(editor.string, "10 PRINT 1\n20 END\n")
}
func testHighlightingKeepsStringsCommentsAndDataOpaque() {
let source = "10 PRINT \"FOR REM DATA\":REM PRINT\n20 DATA PRINT,\"A:B\",12:PRINT 3\n30 'PRINT"
let spans = BASICLanguage.spans(source)
XCTAssertEqual(spans.filter { $0.kind == .keyword }.map(\.word), ["PRINT", "REM", "DATA", "PRINT"])
XCTAssertTrue(spans.contains { $0.kind == .string && (source as NSString).substring(with: $0.range) == "\"FOR REM DATA\"" })
XCTAssertTrue(spans.contains { $0.kind == .data && (source as NSString).substring(with: $0.range).contains("A:B") })
XCTAssertEqual(spans.filter { $0.kind == .comment }.count, 2)
XCTAssertEqual(BASICLanguage.spans("10 FORI=1TO5:NEXTI").filter { $0.kind == .keyword }.map(\.word), ["FOR", "TO", "NEXT"])
}
func testCompletionUsesCaretRangeAndSkipsLiteralContexts() throws {
let text = "10 priZZ\n20 END"
let suggestion = try XCTUnwrap(BASICLanguage.completion(text, at: 6))
XCTAssertEqual(suggestion.range, NSRange(location: 3, length: 5))
XCTAssertEqual(suggestion.words, ["PRINT"])
XCTAssertNil(BASICLanguage.completion("10 REM PRI", at: 10))
XCTAssertNil(BASICLanguage.completion("10 PRINT \"PRI", at: 13))
XCTAssertNil(BASICLanguage.completion("10 DATA PRI", at: 11))
XCTAssertEqual(BASICLanguage.completion("10 DATA \"A:B\":PRI", at: 17)?.words, ["PRINT"])
XCTAssertTrue(try XCTUnwrap(BASICLanguage.completion("10 GO", at: 5)).words.contains("GOSUB"))
XCTAssertNil(BASICLanguage.completion("10 PRINT", at: -1))
}
func testParameterHintsFollowCurrentStatementAndFunctions() {
XCTAssertEqual(BASICLanguage.hint("10 PRINT MID$(A$,", at: 17), BASICLanguage.signatures["MID$"])
XCTAssertEqual(BASICLanguage.hint("10 FOR I=1 TO ", at: 14), BASICLanguage.signatures["FOR"])
XCTAssertNil(BASICLanguage.hint("10 PRINT 1\n20 ", at: 14))
}
@MainActor func testFileReaderRejectsBinaryAndNormalizesLineEndings() throws {
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".bas")
defer { try? FileManager.default.removeItem(at: url) }
try Data("10 PRINT 1\r\n20 END\r".utf8).write(to:url)
XCTAssertEqual(try BASICDevelopmentModel.readText(url).0, "10 PRINT 1\n20 END\n")
try Data([0xff,0,0]).write(to:url)
XCTAssertThrowsError(try BASICDevelopmentModel.readText(url))
}
@MainActor func testNativeCompletionAcceptanceIsOneUndoableEdit() throws {
let delegate = UndoDelegate()
let editor = BASICTextView(frame:NSRect(x:0,y:0,width:400,height:200))
editor.delegate=delegate; editor.allowsUndo=true; editor.string="10 PRI"; editor.setSelectedRange(NSRange(location:6,length:0))
// Preparing the menu off-window does not change the source. A final
// choice uses NSTextView's normal insertion and Undo machinery.
XCTAssertTrue(editor.prepareCompletion())
let range=editor.rangeForUserCompletion
XCTAssertEqual(range,NSRange(location:3,length:3))
var selection = -1
XCTAssertEqual(editor.completions(forPartialWordRange:range,indexOfSelectedItem:&selection),["PRINT"])
XCTAssertEqual(selection,0,"Return should accept the highlighted first suggestion")
editor.insertCompletion("PRINT",forPartialWordRange:range,movement:NSTextMovement.down.rawValue,isFinal:false)
XCTAssertEqual(editor.string,"10 PRI")
editor.insertCompletion("PRINT",forPartialWordRange:range,movement:NSTextMovement.return.rawValue,isFinal:true)
XCTAssertEqual(editor.string,"10 PRINT")
XCTAssertTrue(delegate.manager.canUndo)
delegate.manager.undo()
XCTAssertEqual(editor.string,"10 PRI")
XCTAssertFalse(delegate.manager.canUndo)
}
func testSourceCheckReportsPhysicalRowsAndPreciseRanges() {
let text="10 PRINT 1\r\n\r\n010 END\r\nPRINT 2\r\n64000 END\r\n20 PRINT\"é\"\r\n30 GOTO999\r\n40\r\n"
let report=BASICLanguage.analyze(text)
XCTAssertTrue(report.hasErrors)
XCTAssertEqual(report.diagnostics.filter { $0.severity == .error }.map(\.row),[3,4,5,6])
XCTAssertTrue(report.diagnostics.contains { $0.row == 7 && $0.severity == .warning && $0.message.contains("999") })
XCTAssertTrue(report.diagnostics.contains { $0.row == 8 && $0.severity == .warning })
let duplicate=report.diagnostics.first { $0.row == 3 }!
XCTAssertEqual((text as NSString).substring(with:duplicate.range),"010")
XCTAssertNil(BASICLanguage.lineRange(for:10,in:text))
let valid="0 PRINT\"UNCLOSED\n10 REM " + String(repeating:"X",count:242)
XCTAssertFalse(BASICLanguage.analyze(valid).hasErrors,"EOL closes a BASIC string; exactly249characters are allowed")
XCTAssertTrue(BASICLanguage.analyze(valid+"X").hasErrors)
XCTAssertTrue(BASICLanguage.analyze("10 PRINT\u{01}").hasErrors)
XCTAssertFalse(BASICLanguage.analyze("\t10\tPRINT 1\n").hasErrors)
}
func testRenumberPreservesControlFlowAndOpaqueLiterals() throws {
let text="10 FORI=1TO2:ONI GOTO30,40\n20 IF A THEN30ELSE40\n30 GO SUB40:RUN10\n40 PRINT\"GOTO10\":DATA 10,\"RUN20:ELSE30\":REM GOTO20\n50 LIST1-9999:LLIST-40:DEL30-:EDIT20\n60 ON ERR GOTO0:ON BRK GO TO40\n70 XGOTO=10:PRINT20:POKE100,20\n80 'GOTO10\n"
XCTAssertTrue(BASICLanguage.analyze(text).diagnostics.isEmpty)
let result=try BASICLanguage.renumber(text,start:100,step:100)
XCTAssertEqual(result.lineCount,8)
XCTAssertEqual(result.source,"100 FORI=1TO2:ONI GOTO300,400\n200 IF A THEN300ELSE400\n300 GO SUB400:RUN100\n400 PRINT\"GOTO10\":DATA 10,\"RUN20:ELSE30\":REM GOTO20\n500 LIST100-800:LLIST-400:DEL300-:EDIT200\n600 ON ERR GOTO0:ON BRK GO TO400\n700 XGOTO=10:PRINT20:POKE100,20\n800 'GOTO10\n")
XCTAssertGreaterThan(result.changedReferences,10)
}
func testRenumberKeepsPhysicalRowsAndMapsNumericExecutionOrder() throws {
let source=" 30 END\r\n\r\n\t0 GOTO30\r\n10 PRINT 123\r\n"
let result=try BASICLanguage.renumber(source)
XCTAssertEqual(result.source," 30 END\r\n\r\n\t10 GOTO30\r\n20 PRINT 123\r\n")
let range=try XCTUnwrap(BASICLanguage.lineRange(for:0,in:source))
XCTAssertEqual((source as NSString).substring(with:range),"\t0 GOTO30")
XCTAssertNil(BASICLanguage.lineRange(for:123,in:source))
XCTAssertEqual(try BASICLanguage.renumber("\n\r\n").source,"\n\r\n")
}
func testRenumberRejectsAmbiguityOrMissingTargetsWithoutChangingSource() {
for text in ["10 GOTO999\n20 END", "10 GOTO20+1\n20 END", "10 ON X GOTO20,\n20 END",
"10 GO TOX\n20 END", "10 RUN A$\n20 END", "10 RENUM\n20 END", "10\n20 GOTO10",
"10 LIST11-19\n20 END", "10 LIST999999999999999999999-\n20 END",
"10 LLIST-999999999999999999999\n20 END", "10 PRINT1\n010 END", "PRINT1"] {
XCTAssertThrowsError(try BASICLanguage.renumber(text),text)
}
let source="10 GOTO100\n20 END"
XCTAssertFalse(BASICLanguage.analyze(source).hasErrors,"An unresolved conditional branch is a warning, not a load blocker")
XCTAssertThrowsError(try BASICLanguage.renumber(source,start:100,step:100),"Must not accidentally capture orphan100 as new firstline")
for (start,step) in [(-1,10),(10,0),(64000,10),(63999,1),(10,Int.max)] {
XCTAssertThrowsError(try BASICLanguage.renumber("10 END\n20 END",start:start,step:step))
}
let boundary="1 REM "+String(repeating:"X",count:243)
XCTAssertFalse(BASICLanguage.analyze(boundary).hasErrors)
XCTAssertThrowsError(try BASICLanguage.renumber(boundary,start:63999),"Expanded labels must not exceed inputline limit")
}
func testRenumberRangeBoundsPreserveIncludedLinesAndTrapZero() throws {
let source="0 END\n10 LIST1-29:LLIST-29:DEL1-\n20 ONERRGOTO0:ONBRKGOTO0\n30 IF1THENPRINT20ELSE10\n"
let value=try BASICLanguage.renumber(source,start:100,step:100).source
XCTAssertEqual(value,"100 END\n200 LIST200-300:LLIST-300:DEL200-\n300 ONERRGOTO0:ONBRKGOTO0\n400 IF1THENPRINT20ELSE200\n")
let literals="10 DATA GOTO999,\"ELSE888:RUN777\":PRINT10\n20 REM RUN999\n30 PRINT\"GOTO999\"\n40 XGOTO=999:PRINT20\n"
XCTAssertTrue(BASICLanguage.analyze(literals).diagnostics.isEmpty)
XCTAssertNoThrow(try BASICLanguage.renumber(literals))
}
@MainActor func testExplicitEditorActionsUseOneUndoAndRejectStaleRequests() throws {
let delegate=UndoDelegate(), editor=BASICTextView(frame:NSRect(x:0,y:0,width:500,height:300))
editor.delegate=delegate; editor.allowsUndo=true
let original="10 GOTO20\n20 END\n", changed=try BASICLanguage.renumber(original,start:100,step:100).source
editor.string=original
let action=BASICEditorAction(expectedSource:original,operation:.replace(source:changed,undoName:"Renumber BASIC"))
XCTAssertTrue(editor.applyEditorAction(action)); XCTAssertEqual(editor.string,changed)
XCTAssertEqual(delegate.manager.undoActionName,"Renumber BASIC")
delegate.manager.undo(); XCTAssertEqual(editor.string,original); XCTAssertFalse(delegate.manager.canUndo)
delegate.manager.redo(); XCTAssertEqual(editor.string,changed)
XCTAssertFalse(editor.applyEditorAction(action)); XCTAssertEqual(editor.string,changed)
XCTAssertFalse(editor.applyEditorAction(.init(expectedSource:changed,operation:.select(NSRange(location:NSNotFound,length:2)))))
XCTAssertTrue(editor.applyEditorAction(.init(expectedSource:changed,operation:.select(NSRange(location:0,length:3)))))
XCTAssertEqual(editor.selectedRange(),NSRange(location:0,length:3))
editor.isEditable=false
XCTAssertFalse(editor.applyEditorAction(.init(expectedSource:changed,operation:.replace(source:original,undoName:"Change"))))
}
@MainActor func testModelAssistanceQueuesEditsAndNavigatesDiagnostics() async throws {
let directory=FileManager.default.temporaryDirectory.appendingPathComponent("BASICAssistance-"+UUID().uuidString)
let suite="BASICAssistance-"+UUID().uuidString, defaults=UserDefaults(suiteName:suite)!
defer { defaults.removePersistentDomain(forName:suite); try? FileManager.default.removeItem(at:directory) }
let machine=MachineModel(diskStore:.init(url:directory.appendingPathComponent("disks.json")),displayDefaults:defaults,inputStore:.init(url:directory.appendingPathComponent("input.json")))
let model=BASICDevelopmentModel(machine:machine,directory:directory.appendingPathComponent("draft"))
model.source="10 GOTO999\n20 END\n"; model.checkSource()
XCTAssertEqual(model.diagnostics.count,1)
if let diagnostic=model.diagnostics.first {
model.selectDiagnostic(diagnostic)
if let action=model.editorAction {
if case .select(let range)=action.operation { XCTAssertEqual((model.source as NSString).substring(with:range),"999") } else { XCTFail("Expected selection") }
model.editorActionHandled(id:action.id,applied:true)
} else { XCTFail("Missing diagnostic action") }
}
model.renumber(start:100,increment:100)
XCTAssertNil(model.editorAction); XCTAssertNotNil(model.message)
let source="10 GOTO20\n20 END\n"; model.source=source
model.renumber(start:100,increment:100)
XCTAssertEqual(model.source,source,"Source changes only through the native undoable edit")
if let action=model.editorAction {
if case .replace(let newSource,let name)=action.operation { XCTAssertEqual(newSource,"100 GOTO200\n200 END\n"); XCTAssertEqual(name,"Renumber BASIC") } else { XCTFail("Expected replacement") }
model.editorActionHandled(id:action.id,applied:false)
} else { XCTFail("Missing renumber action") }
model.goToLine(20)
if let action=model.editorAction {
if case .select(let range)=action.operation { XCTAssertEqual((source as NSString).substring(with:range),"20 END") } else { XCTFail("Expected line selection") }
model.editorActionHandled(id:action.id,applied:true)
} else { XCTFail("Missing navigation action") }
model.renumber(start:63999,increment:1); XCTAssertNil(model.editorAction); XCTAssertEqual(model.source,source)
await withCheckedContinuation { done in machine.shutdown { done.resume() } }
}
}