Files
VCCPlusOSS/platforms/macos/Tests/AssemblyDevelopmentTests.swift
T

293 lines
20 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import AppKit
final class AssemblyDevelopmentTests: XCTestCase {
override func setUp() async throws {
try await super.setUp()
// InputHub reads the host application's activation state. Initialize
// AppKit explicitly so this class also runs without earlier suites.
await MainActor.run { _ = NSApplication.shared }
}
private func temporaryFolder() throws -> URL {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)
return root
}
#if DEBUG
@MainActor func testCompiledInputEndsAtBASICReturnAndPinsMediaIdentity() async throws {
let roms = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
.appendingPathComponent("LocalResources/ROMs")
try XCTSkipUnless(["coco3.rom", "disk11.rom"].allSatisfy { FileManager.default.fileExists(atPath: roms.appendingPathComponent($0).path) },
"Requires the private CoCo BASIC ROMs.")
for enhanced in [false, true] {
let dir = try temporaryFolder(), suite = "CompiledRun." + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) }
let controller = VCCMachineController()
let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("disks.json")),
controller: controller, displayDefaults: defaults,
inputStore: .init(url: dir.appendingPathComponent("input.json")))
let end = ContinuousClock.now.advanced(by: .seconds(5))
while machine.busy && ContinuousClock.now < end { try await Task.sleep(for: .milliseconds(20)) }
try await MCPBASICRun.bootFixture(machine, romDirectory: roms, use6309: enhanced)
// Poll the real ROM keyboard, echo a key, then RTS into genuine BASIC direct mode.
let romCalls = Data([0,0,12,0x3f,0,0xad,0x9f,0xa0,0,0x4d,0x27,0xf9,0xad,0x9f,0xa0,2,0x39,0xff,0,0,0x3f,0])
let disk = Data(repeating: 0xff, count: 35 * 18 * 256)
func mount(_ image: Data) async -> VCCMachineSnapshot {
await withCheckedContinuation { c in controller.mountDisk(image, drive: 1, name: "Same.dsk", readOnly: true) { c.resume(returning: $0) } }
}
func launch(_ image: Data) async throws -> MCPCompiledRunIO {
let before = await machine.mcpMachineSnapshot()
let launched: VCCMachineSnapshot? = await withCheckedContinuation { c in
machine.launchAssembly(image, breakpoints: [], guards: [:], pauseAtEntry: false, requires6309: enhanced,
expectedGeneration: before.generation, expectedRevision: before.debuggerProgramRevision,
expectedMapping: before.debuggerMappingFingerprint, shared: true) { c.resume(returning: $0) }
}
let state = try XCTUnwrap(launched)
XCTAssertNil(state.errorMessage)
return MCPCompiledRunIO(machine: machine, runID: "quiz", expected: state, assembly: true)
}
let media = await mount(disk)
XCTAssertNil(media.errorMessage)
let io = try await launch(romCalls)
let observed = try await io.reply("read_screen_text", arguments: ["run_id":"quiz"])
XCTAssertNotNil(observed["text"] as? String)
let key = ["run_id":"quiz", "keys":"1", "request_id":"one"]
let accepted = try await io.reply("send_keys", arguments: key)
XCTAssertEqual(accepted["accepted"] as? Bool, true)
var now = await machine.mcpMachineSnapshot()
for _ in 0..<100 where !now.assistantCompiledReturned {
try await Task.sleep(for: .milliseconds(25))
now = await machine.mcpMachineSnapshot()
}
XCTAssertTrue(now.assistantCompiledReturned)
XCTAssertEqual(now.pasteRemaining, 0)
for (tool, args) in [("read_screen_text", ["run_id":"quiz"]), ("send_keys", key)] {
do { _ = try await io.reply(tool, arguments: args); XCTFail("Live access survived RTS") }
catch { XCTAssertEqual(error.localizedDescription, "run_finished") }
}
io.invalidate()
// A program can print and return between any two client polls. Preserve the
// terminal screen at RTS, even if the operator later uses the BASIC prompt.
let printX = Data([0,0,7,0x3f,0,0x86,0x58,0xad,0x9f,0xa0,2,0x39,0xff,0,0,0x3f,0])
try await machine.waitForMCPFixturePrompt()
let quick = try await launch(printX)
for _ in 0..<100 {
if await machine.mcpMachineSnapshot().assistantCompiledReturned { break }
try await Task.sleep(for: .milliseconds(25))
}
let captured = try await quick.finalScreenText()
XCTAssertTrue(captured?.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix("X") == true, captured ?? "(unavailable)")
try await machine.waitForMCPFixturePrompt()
let type = try CocoPaste("CLS:PRINT 4242\n", mode: .text).chords.map { NSNumber(value: $0) }
let queued = await controller.pasteChords(type)
XCTAssertNil(queued.errorMessage)
for _ in 0..<200 {
if await machine.mcpMachineSnapshot().pasteRemaining == 0 { break }
try await Task.sleep(for: .milliseconds(15))
}
let later = try await quick.finalScreenText()
XCTAssertEqual(later, captured)
let (actual, _) = await machine.reviewedCOutput()
XCTAssertTrue(actual?.contains("4242") == true)
quick.invalidate()
let next = try await launch(romCalls)
var otherDisk = disk; otherDisk[0] = 0
let replaced = await mount(otherDisk)
XCTAssertNil(replaced.errorMessage)
do { _ = try await next.reply("read_screen_text", arguments: ["run_id":"quiz"]); XCTFail("Accepted a replacement with the original name") }
catch { XCTAssertEqual(error.localizedDescription, "media_changed") }
next.invalidate()
do { _ = try await next.reply("send_keys", arguments: key); XCTFail("Accepted a revoked lease") }
catch { XCTAssertEqual(error.localizedDescription, "stale_run") }
await withCheckedContinuation { c in machine.shutdown { c.resume() } }
}
}
#endif
@MainActor func testReviewedAssemblyFilesApplyAndUndoAcrossUnopenedInclude() async throws {
let dir = try temporaryFolder(), project = dir.appendingPathComponent("Assembly")
let suite = "ReviewedAssembly." + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) }
try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false)
let original = " include \"value.inc\"\nstart lda #VALUE\n rts\n"
try Data(original.utf8).write(to: project.appendingPathComponent("main.asm"))
try Data("VALUE equ 1\n".utf8).write(to: project.appendingPathComponent("value.inc"))
let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("disks.json")), displayDefaults: defaults,
inputStore: .init(url: dir.appendingPathComponent("input.json")))
let model = AssemblyDevelopmentModel(machine: machine, recoveryURL: dir.appendingPathComponent("drafts.json"))
model.open(project, folder: true)
for _ in 0..<200 where !model.document.isProject { try await Task.sleep(for: .milliseconds(10)) }
let draft = original + "* unsaved native text\n"
model.edit(draft)
let input = try model.document.snapshot()
let files = Set(input.files.keys)
let rows = [["path": "value.inc", "source": "VALUE equ 21\n"],
["path": "main.asm", "source": " include \"value.inc\"\nstart ldb #VALUE\n rts ; café\n"]]
let edits = try MCPAssembly.projectEdits(rows, snapshot: input, shared: files)
XCTAssertEqual(edits.map(\.path), ["main.asm", "value.inc"])
let staleLast = AssemblyProjectEdit(path: "value.inc", before: "VALUE equ 2\n", after: "VALUE equ 42\n")
let epoch = model.sourceRevision
XCTAssertThrowsError(try model.replaceReviewedFiles([edits[0], staleLast], snapshot: input))
XCTAssertEqual(model.sourceRevision, epoch)
XCTAssertEqual(model.document.buffers.count, 1)
XCTAssertEqual(model.buffer.text, draft)
let removed = try model.replaceReviewedFiles(edits, snapshot: input)
XCTAssertEqual(model.document.buffers.filter(\.dirty).count, 2)
XCTAssertEqual(model.buffer.text, rows[1]["source"])
XCTAssertEqual(try String(contentsOf: project.appendingPathComponent("value.inc"), encoding: .utf8), "VALUE equ 1\n")
let applied = try model.document.snapshot()
_ = try model.replaceReviewedFiles(edits, snapshot: applied, undo: true, restoreStops: removed)
XCTAssertEqual(try model.document.snapshot(), input)
XCTAssertEqual(model.buffer.text, draft)
XCTAssertEqual(model.document.buffers.filter(\.dirty).map(\.path), ["main.asm"])
XCTAssertEqual(try String(contentsOf: project.appendingPathComponent("main.asm"), encoding: .utf8), original)
XCTAssertThrowsError(try MCPAssembly.projectEdits([rows[0], rows[0]], snapshot: input, shared: files))
XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "main.asm", "source": draft]], snapshot: input, shared: files))
XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "../outside.asm", "source": "rts"]], snapshot: input, shared: files))
XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "main.asm", "source": "\0"]], snapshot: input, shared: files))
XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "main.asm", "source": "a", "unrecognized": "b"]], snapshot: input, shared: files))
let limit = String(repeating: "é", count: 8192)
XCTAssertNoThrow(try MCPAssembly.projectEdits([["path": "main.asm", "source": limit]], snapshot: input, shared: files))
XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "main.asm", "source": limit], rows[0]], snapshot: input, shared: files))
}
@MainActor func testSwitchingDocumentsDuringBuildRetainsDraftAndRejectsLateResult() async throws {
let dir = try temporaryFolder()
let suite = "AssemblyWorkspaceTests." + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) }
let tools = dir.appendingPathComponent("Toolchain")
let bin = tools.appendingPathComponent("bin"), assembler = bin.appendingPathComponent("lwasm")
try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true)
let script = "#!/bin/sh\n: > \"$VCC_TOOLCHAIN/started\"\nexec /bin/sleep 10\n"
try Data(script.utf8).write(to: assembler)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: assembler.path)
let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("disks.json")), displayDefaults: defaults,
inputStore: .init(url: dir.appendingPathComponent("input.json")))
let recovery = dir.appendingPathComponent("Drafts.json")
let model = AssemblyDevelopmentModel(machine: machine, service: .init(toolchain: tools), recoveryURL: recovery)
let original = model.activeID
model.edit("; My unsaved revision\n" + model.buffer.text)
model.moveCursor(12)
model.perform(.assemble)
let marker = tools.appendingPathComponent("started")
for _ in 0..<300 where !FileManager.default.fileExists(atPath: marker.path) {
try await Task.sleep(nanoseconds: 10_000_000)
}
XCTAssertTrue(FileManager.default.fileExists(atPath: marker.path))
model.openExample(title: "Second", source: "Second LDW #$1234", target6309: true)
try await Task.sleep(nanoseconds: 200_000_000)
XCTAssertFalse(model.working); XCTAssertNil(model.artifact)
XCTAssertEqual(model.cpu, .hd6309)
XCTAssertEqual(model.buffer.text, "Second LDW #$1234")
model.select(original)
XCTAssertEqual(model.cursor, 12, "Reference lookup and Set Stop must follow the restored document caret")
XCTAssertTrue(model.buffer.text.hasPrefix("; My unsaved revision"))
XCTAssertTrue(model.prepareToQuit())
XCTAssertEqual(try AssemblyRecovery.read(from: recovery).documents.count, 2)
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
}
@MainActor func testSaveCopyProtectsAnotherDocumentsIncludeAndCanSaveEmptySource() async throws {
let dir = try temporaryFolder(), suite = "AssemblySaveTests." + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) }
let sub = dir.appendingPathComponent("Shared.inc"), entry = dir.appendingPathComponent("Main.asm")
let initial = Data("start lda #1\n".utf8)
try initial.write(to: sub)
try Data(" include \"Shared.inc\"\n".utf8).write(to: entry)
let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("disks.json")), displayDefaults: defaults,
inputStore: .init(url: dir.appendingPathComponent("input.json")))
let model = AssemblyDevelopmentModel(machine: machine, recoveryURL: dir.appendingPathComponent("Drafts.json"))
model.open(entry, folder: false)
for _ in 0..<200 where model.document.title != "Main.asm" { try await Task.sleep(nanoseconds: 10_000_000) }
XCTAssertEqual(model.document.title, "Main.asm")
model.openExample(title: "Untitled", source: "", target6309: false)
let alias = dir.appendingPathComponent("alias.asm")
try FileManager.default.linkItem(at: sub, to: alias)
model.save(to: alias)
for _ in 0..<200 where !model.message.contains("separate") { try await Task.sleep(nanoseconds: 10_000_000) }
XCTAssertTrue(model.message.contains("separate"), model.message)
XCTAssertEqual(try Data(contentsOf: sub), initial)
XCTAssertEqual(try Data(contentsOf: alias), initial)
let empty = dir.appendingPathComponent("Empty.asm")
model.save(to: empty)
for _ in 0..<200 where model.document.title != "Empty.asm" { try await Task.sleep(nanoseconds: 10_000_000) }
XCTAssertEqual(try Data(contentsOf: empty), Data())
XCTAssertEqual(model.document.title, "Empty.asm")
XCTAssertTrue(model.prepareToQuit())
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
}
func testLooseSourceIncludesPreserveCaseAndOverlayWithoutWriting() throws {
let dir = try temporaryFolder(); defer { try? FileManager.default.removeItem(at: dir) }
let entry = dir.appendingPathComponent("Game.asm"), include = dir.appendingPathComponent("Data.inc")
let main = " ORG $3f00\n INCLUDE \"Data.inc\"\n END Start\n"
let saved = "Start LDA #1\n"
try Data(main.utf8).write(to: entry); try Data(saved.utf8).write(to: include)
try Data("private".utf8).write(to: dir.appendingPathComponent("Other.inc"))
var doc = try AssemblyWorkspaceDocument.open(entry, folder: false)
XCTAssertEqual(doc.mainPath, "Game.asm")
XCTAssertEqual(Set(doc.paths), ["Game.asm", "Data.inc"])
doc.buffers.append(.init(path: "Data.inc", text: "Start LDA #2\n", saved: saved))
let snap = try doc.snapshot()
XCTAssertEqual(snap.files["Data.inc"], Data("Start LDA #2\n".utf8))
XCTAssertEqual(try String(contentsOf: include, encoding: .utf8), saved)
try Data("external edit".utf8).write(to: include)
XCTAssertThrowsError(try doc.snapshot())
// An alias inside the selected folder must still be refused.
let alias = dir.appendingPathComponent("Linked.inc")
try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: include)
XCTAssertThrowsError(try doc.checkedURL("Linked.inc"))
}
func testRecoveryPreservesTwoIndependentUnsavedExamplesAndTheirTargets() throws {
let dir = try temporaryFolder(); defer { try? FileManager.default.removeItem(at: dir) }
let one = AssemblyWorkspaceDocument.example(title: "First", source: "Start LDA #1", cpu: .mc6809)
var two = AssemblyWorkspaceDocument.example(title: "Wide", source: "Start LDW #$1234", cpu: .hd6309)
two.breakpoints.insert(.init(path: "main.asm", line: 1))
let url = dir.appendingPathComponent("Recovery.json")
try AssemblyRecovery(documents: [one, two], active: two.id).write(to: url)
let restored = try AssemblyRecovery.read(from: url)
XCTAssertEqual(restored.active, two.id)
XCTAssertEqual(restored.documents.map(\.cpu), [.mc6809, .hd6309])
XCTAssertEqual(restored.documents.map { $0.buffers[0].text }, ["Start LDA #1", "Start LDW #$1234"])
XCTAssertNotEqual(restored.documents[0].buffers[0].id, restored.documents[1].buffers[0].id)
XCTAssertEqual(restored.documents[1].breakpoints, two.breakpoints)
}
@MainActor func testLineNavigationAndTokenizationPreserveUTF16AndCase() throws {
let source = "; é🖥\nEntry lda #$8f ; start here\n fcc \";Label\"\n"
let words: Set<String> = ["LDA", "FCC"]
let range = try XCTUnwrap(AssemblyDevelopmentModel.lineRange(2, text: source))
XCTAssertEqual((source as NSString).substring(with: range), "Entry lda #$8f ; start here\n")
XCTAssertEqual(AssemblyEditorSyntax.labels(in: source, vocabulary: words).map(\.0), ["Entry"])
XCTAssertEqual(AssemblyEditorSyntax.token(in: source, offset: range.location + 2, vocabulary: words), "Entry")
let literal = (source as NSString).range(of: ";Label")
XCTAssertNil(AssemblyEditorSyntax.token(in: source, offset: literal.location + 2, vocabulary: words))
}
@MainActor func testAmbiguousSourceAndAddressCannotArmStops() {
let source = " org $3f00\nstart lda #$8f\n sta $0400\n"
let snapshot = AssemblyProjectSnapshot.single(source: source)
let instructions: [AssemblyInstructionLocation] = [
.init(path: "main.asm", line: 2, address: 0x3f00, bytes: [0x86, 0x8f]),
.init(path: "main.asm", line: 3, address: 0x3f02, bytes: [0xb7, 4, 0]),
.init(path: "main.asm", line: 3, address: 0x3f05, bytes: [0x20, 0xfe]),
.init(path: "other.inc", line: 1, address: 0x3f05, bytes: [0x20, 0xfe])]
let artifact = AssemblyBuildArtifact(id: UUID(), snapshot: snapshot, binaryData: Data(), entry: 0x3f00, ranges: [],
listing: "", symbols: "", buildLog: "", instructions: instructions)
XCTAssertNil(AssemblyDevelopmentModel.location(.init(path: "main.asm", line: 1), in: artifact))
XCTAssertEqual(AssemblyDevelopmentModel.location(.init(path: "main.asm", line: 2), in: artifact)?.address, 0x3f00)
XCTAssertNil(AssemblyDevelopmentModel.location(.init(path: "main.asm", line: 3), in: artifact))
XCTAssertNil(AssemblyDevelopmentModel.location(.init(path: "other.inc", line: 1), in: artifact))
XCTAssertNil(AssemblyDevelopmentModel.codeGuards(instructions)[0x3f05])
}
}