Files
VCCPlusOSS/platforms/macos/Tests/CMOCDevelopmentTests.swift
Brian Holman 5534005799 Sync VCC Plus 3.7.1 build 67 source
Refresh reviewed MCP output export, four-drive owned playtests, bounded BASIC readiness, and pinned CMOC 0.1.101 source/patches. Preserve independent source-edition identity, empty libraries, notices and privacy boundaries.

Validated 74 export/privacy checks, pinned dependency sources, and an independent unsigned universal Release build. A subsequent documentation-only correction removes an excluded qualification link; all build inputs remain identical.
2026-11-17 08:42:27 -07:00

754 lines
51 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
final class CMOCDevelopmentTests: XCTestCase {
@MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } }
}
@MainActor private func capture(_ controller: VCCMachineController, memory: UInt16 = 0x4000) async -> VCCDebuggerSnapshot {
await withCheckedContinuation { continuation in
controller.debuggerSnapshot(address: 0x4100, followPC: true, memoryAddress: memory) {
continuation.resume(returning: $0)
}
}
}
private func binary(address: UInt16 = 0x4100, entry: UInt16 = 0x4100,
bytes: [UInt8] = [0x86, 0x2A, 0xB7, 0x40, 0x00, 0x4C, 0xB7, 0x40, 0x01, 0x20, 0xFE]) -> Data {
Data([0, UInt8(bytes.count >> 8), UInt8(bytes.count & 255), UInt8(address >> 8), UInt8(address & 255)]
+ bytes + [255, 0, 0, UInt8(entry >> 8), UInt8(entry & 255)])
}
@MainActor private func waitForStop(_ controller: VCCMachineController) async -> VCCMachineSnapshot {
var result = await command(controller.snapshot)
for _ in 0..<200 where result.state == .running {
try? await Task.sleep(nanoseconds: 10_000_000)
result = await command(controller.snapshot)
}
XCTAssertEqual(result.state, .paused)
return result
}
@MainActor func testDevelopmentLoadArmsEntryAndLaterBreakpointsAtomicallyOnBothCPUs() async {
for use6309 in [false, true] {
let controller = VCCMachineController()
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
_ = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) }
_ = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0xA5, 0x5A]), completion: $0) }
_ = await command { controller.debuggerConfigureBreakpoints([0x4500], disabled: [0x4100, 0x4501], completion: $0) }
let before = await capture(controller)
let loaded = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4100, completion: $0) }
XCTAssertNil(loaded.errorMessage)
let entry = await waitForStop(controller)
let entryDetail = await capture(controller)
XCTAssertEqual(entry.programCounter, 0x4100)
XCTAssertEqual(entry.cycles, before.machine.cycles, "Entry breakpoint must stop before the very first instruction")
XCTAssertEqual(entry.generation, before.machine.generation, "Loading a build must preserve the machine session")
XCTAssertEqual(entryDetail.memory.prefix(2), Data([0xA5, 0x5A]))
XCTAssertEqual(Set(entryDetail.breakpoints.map(\.uint16Value)), Set([UInt16(0x4100), 0x4500]))
XCTAssertEqual(entryDetail.disabledBreakpoints, [0x4501], "Arming a disabled breakpoint must retain unrelated disabled addresses")
_ = await command { controller.debuggerConfigureBreakpoints([0x4500], disabled: [0x4501], completion: $0) }
let loadedAgain = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4105, completion: $0) }
XCTAssertNil(loadedAgain.errorMessage)
let later = await waitForStop(controller)
let laterDetail = await capture(controller)
XCTAssertEqual(later.programCounter, 0x4105)
XCTAssertGreaterThan(later.cycles, entry.cycles)
XCTAssertEqual(laterDetail.memory.prefix(2), Data([0x2A, 0x5A]), "Only instructions before the selected breakpoint should execute")
XCTAssertEqual(Set(laterDetail.breakpoints.map(\.uint16Value)), Set([UInt16(0x4105), 0x4500]))
XCTAssertEqual(laterDetail.disabledBreakpoints, [0x4501])
_ = await command(controller.shutdown)
}
}
@MainActor func testDevelopmentLoadRejectsInvalidImagesWithoutMutatingMachineOrBreakpoints() async {
for use6309 in [false, true] {
let controller = VCCMachineController()
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
_ = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) }
_ = await command { controller.debuggerConfigureBreakpoints([0x4500], disabled: [0x4501], completion: $0) }
let before = await capture(controller)
let beforeProgram = await capture(controller, memory: 0x4100)
let invalid: [(Data, UInt16)] = [
(Data(binary().dropLast(5)) + binary(address: 0xFF00, entry: 0x4100), 0x4100),
(Data([0, 0, 5, 0x41, 0, 0x86]), 0x4100),
(binary(), 0x4200),
(binary(entry: 0x4200), 0x4100),
(binary(address: 0xFF00, entry: 0xFF00), 0xFF00),
(binary(address: 0x8000, entry: 0x8000), 0x8000)
]
for (image, breakpoint) in invalid {
let result = await command { controller.debuggerLoadBinary(image, breakpoint: breakpoint, completion: $0) }
XCTAssertNotNil(result.errorMessage)
let after = await capture(controller)
XCTAssertEqual(after.machine.state, .paused)
XCTAssertEqual(after.machine.programCounter, before.machine.programCounter)
XCTAssertEqual(after.machine.cycles, before.machine.cycles)
XCTAssertEqual(after.machine.generation, before.machine.generation)
XCTAssertEqual(after.machine.debuggerProgramRevision, before.machine.debuggerProgramRevision)
XCTAssertEqual(after.machine.debuggerMappingFingerprint, before.machine.debuggerMappingFingerprint)
XCTAssertEqual(after.memory, before.memory)
XCTAssertEqual(after.breakpoints, before.breakpoints)
XCTAssertEqual(after.disabledBreakpoints, before.disabledBreakpoints)
let afterProgram = await capture(controller, memory: 0x4100)
XCTAssertEqual(afterProgram.memory, beforeProgram.memory)
}
_ = await command(controller.shutdown)
}
}
@MainActor func testDevelopmentBreakpointOwnershipAndProgramRevision() async {
for use6309 in [false, true] {
let controller = VCCMachineController()
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
_ = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) }
_ = await command { controller.debuggerConfigureBreakpoints([0x4500], disabled: [0x4100, 0x4501], completion: $0) }
let before = await capture(controller)
_ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4100, completion: $0) }
let first = await waitForStop(controller)
XCTAssertGreaterThan(first.debuggerProgramRevision, before.machine.debuggerProgramRevision)
XCTAssertEqual(first.debuggerMappingFingerprint, before.machine.debuggerMappingFingerprint)
_ = await command(controller.debuggerStep)
let stepped = await capture(controller)
XCTAssertEqual(stepped.machine.debuggerProgramRevision, first.debuggerProgramRevision, "Execution must not invalidate its own source provenance")
_ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4105, completion: $0) }
_ = await waitForStop(controller)
let second = await capture(controller)
XCTAssertEqual(Set(second.breakpoints.map(\.uint16Value)), Set([UInt16(0x4105), 0x4500]))
XCTAssertEqual(Set(second.disabledBreakpoints.map(\.uint16Value)), Set([UInt16(0x4100), 0x4501]), "Moving the development breakpoint must restore a user's disabled breakpoint")
_ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4106, completion: $0) }
_ = await waitForStop(controller)
let third = await capture(controller)
XCTAssertEqual(Set(third.breakpoints.map(\.uint16Value)), Set([UInt16(0x4106), 0x4500]), "An obsolete development breakpoint must not stop the new build")
_ = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0x55]), completion: $0) }
let edited = await capture(controller)
XCTAssertGreaterThan(edited.machine.debuggerProgramRevision, third.machine.debuggerProgramRevision)
_ = await command { controller.debuggerConfigureBreakpoints([0x4100, 0x4500], disabled: [0x4501], completion: $0) }
_ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4100, completion: $0) }
_ = await waitForStop(controller)
_ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4105, completion: $0) }
_ = await waitForStop(controller)
let existing = await capture(controller)
XCTAssertEqual(Set(existing.breakpoints.map(\.uint16Value)), Set([UInt16(0x4100), 0x4105, 0x4500]), "The feature must not claim or remove a preexisting enabled breakpoint")
_ = await command(controller.shutdown)
}
}
@MainActor func testCompiledEditedProgramStopsAtVerifiedCLineOnBothCPUs() async throws {
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
let romURL = resources.appendingPathComponent("ROMs/coco3.rom")
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
&& FileManager.default.fileExists(atPath: romURL.path), "Local licensed CoCo ROM and staged toolchain are required")
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCExecutionTests-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
defer { try? FileManager.default.removeItem(at: folder) }
let project = try CMOCProject.create(at: folder.appendingPathComponent("Project"))
let source = CMOCProject.starterSource.replacingOccurrences(of: "What planet do you live on?", with: "Which planet is yours?")
let artifact = try await CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")).build(project: project, source: source)
let mapping = try CMOCSourceMap.parse(source: artifact.sourceData, sourceName: artifact.sourceURL.path,
listing: Data(contentsOf: artifact.listingURL), object: Data(contentsOf: artifact.objectURL), objectName: "main.o",
linkMap: Data(contentsOf: artifact.mapURL), binary: artifact.binaryData)
let promptLine = try XCTUnwrap(source.components(separatedBy: "\n").firstIndex { $0.contains("Which planet is yours?") }) + 1
let instruction = try XCTUnwrap(mapping.instructions.first { $0.sourceLine == promptLine })
let rom = try Data(contentsOf: romURL)
for use6309 in [false, true] {
let controller = VCCMachineController()
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
let loaded = await command { controller.loadROM(rom, use6309: use6309, completion: $0) }
XCTAssertNil(loaded.errorMessage)
_ = await command(controller.resume)
try await Task.sleep(nanoseconds: 1_500_000_000)
_ = await command(controller.pause)
let before = await capture(controller)
let result = await command { controller.debuggerLoadBinary(artifact.binaryData, breakpoint: instruction.address, completion: $0) }
XCTAssertNil(result.errorMessage)
let stopped = await waitForStop(controller)
let snapshot = await capture(controller)
XCTAssertEqual(stopped.programCounter, instruction.address)
XCTAssertEqual(mapping.line(at: stopped.programCounter), promptLine)
XCTAssertEqual(snapshot.instructions.first?.address, instruction.address)
XCTAssertEqual(snapshot.instructions.first?.bytes, Data(instruction.bytes), "The live machine must contain the exact relocated instruction verified by the C map")
XCTAssertEqual(stopped.generation, before.machine.generation)
XCTAssertGreaterThan(stopped.cycles, before.machine.cycles)
_ = await command(controller.shutdown)
}
}
@MainActor func testBundledDiskAPIWritesClosesReopensAndReadsAnIsolatedFloppyOnBothCPUs() async throws {
try await checkDiskAPIRoundTrip(standalone: false)
}
@MainActor func testStandaloneDiskAPIReadsAndWritesWithBASICBankedOutOnBothCPUs() async throws {
try await checkDiskAPIRoundTrip(standalone: true)
}
@MainActor private func checkDiskAPIRoundTrip(standalone: Bool) async throws {
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let resources = mac.appendingPathComponent("LocalResources")
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
let romURL = resources.appendingPathComponent("ROMs/coco3.rom")
let diskROMURL = resources.appendingPathComponent("ROMs/disk11.rom")
try XCTSkipUnless(FileManager.default.fileExists(atPath: toolchain.appendingPathComponent("share/cmoc/lib/libdecbfile.a").path)
&& FileManager.default.fileExists(atPath: romURL.path)
&& FileManager.default.fileExists(atPath: diskROMURL.path), "The local ROMs and bundled DECB file library are required")
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCDiskAPITests-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
defer { try? FileManager.default.removeItem(at: folder) }
let project = try CMOCProject.create(at: folder.appendingPathComponent("Project"))
// Authored fixture: use the public file API through the running Disk
// BASIC ROM. No host-side disk writer substitutes for guest file I/O.
var source = """
#include <cmoc.h>
#include <decbfile.h>
DECBDrive drives[1];
DECBFile file;
byte written[256], readBack[256];
byte testResult;
byte roundTrip(void)
{
word i;
if (decb_init(drives, 1) != DECB_OK) return 1;
if (decb_registerDrive(0) != DECB_OK) return 2;
if (decb_createSectorFile(&file, 0, "ROUND.DAT", DECB_TYPE_BASIC_DATA, DECB_FORMAT_BINARY) != DECB_OK) return 3;
for (i = 0; i < 256; ++i) written[i] = (byte) (i ^ 0x5A);
if (decb_writeSector(&file, written, 0) != DECB_OK) return 4;
decb_setNumBytesUsedInLastSector(&file, 256);
if (decb_closeSectorFile(&file) != DECB_OK) return 5;
if (decb_openSectorFile(&file, 0, "ROUND.DAT") != DECB_OK) return 6;
if (decb_readSector(&file, readBack, 0) != DECB_OK) return 7;
if (memcmp(written, readBack, 256) != 0) return 8;
if (decb_closeSectorFile(&file) != DECB_OK) return 9;
return DECB_OK;
}
int main(void)
{
initCoCoSupport();
setHighSpeed(FALSE);
testResult = roundTrip();
if (decb_shutdown() != DECB_OK) testResult = 10;
printf("DISK ROUND TRIP RESULT: %u\\n", testResult);
return testResult;
}
"""
if standalone {
try XCTSkipUnless(FileManager.default.fileExists(atPath: toolchain.appendingPathComponent("share/cmoc/lib/libdskcon-standalone.a").path), "Stage the separately supplied standalone disk driver")
var makefile = try String(contentsOf: project.makefileURL)
makefile = makefile.replacingOccurrences(of: "LIBS ?= -ldecbfile", with: "LIBS ?= -ldecbfile -ldskcon-standalone")
try makefile.write(to: project.makefileURL, atomically: true, encoding: .utf8)
source = source.replacingOccurrences(of: "#include <decbfile.h>", with: """
#include <decbfile.h>
#include <dskcon-standalone.h>
interrupt asm void diskIRQ(void)
{
asm
{
_dskcon_irqService IMPORT
ldb $FF03
bpl @done
ldb $FF02
lbsr _dskcon_irqService
@done
}
}
""")
source = source.replacingOccurrences(of: "if (decb_registerDrive(0) != DECB_OK) return 2;", with: """
if (*(volatile word *)0xC004 != 0x5A5A) return 11;
decb_setDskConAddresses(dskcon_processSector, (DECBDskConVariables *)&DCOPC);
if (decb_registerDrive(0) != DECB_OK) return 2;
""")
source = source.replacingOccurrences(of: "testResult = roundTrip();", with: """
disableInterrupts();
asm("CLR", "$FFDF");
*(volatile word *)0xC004 = 0x5A5A;
{
byte *irq = *(byte **)0xFFF8;
*irq = 0x7E;
*(word *)(irq + 1) = (word)diskIRQ;
}
dskcon_init(dskcon_nmiService);
enableInterrupts();
testResult = roundTrip();
""")
}
let line = try XCTUnwrap(source.components(separatedBy: "\n").firstIndex { $0.contains("printf(") }) + 1
let artifact = try await CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")).build(project: project, source: source)
let mapData = try Data(contentsOf: artifact.mapURL)
let mapping = try CMOCSourceMap.parse(source: artifact.sourceData, sourceName: artifact.sourceURL.path,
listing: Data(contentsOf: artifact.listingURL), object: Data(contentsOf: artifact.objectURL), objectName: "main.o",
linkMap: mapData, binary: artifact.binaryData)
let instruction = try XCTUnwrap(mapping.instructions.first { $0.sourceLine == line })
let symbol = try XCTUnwrap(String(decoding: mapData, as: UTF8.self).components(separatedBy: "\n")
.first { $0.hasPrefix("Symbol: _testResult (main.o) = ") })
let resultAddress = try XCTUnwrap(UInt16(try XCTUnwrap(symbol.split(separator: " ").last), radix: 16))
let rom = try Data(contentsOf: romURL), diskROM = try Data(contentsOf: diskROMURL)
let blankURL = mac.appendingPathComponent("Resources/StarterMedia/Blank Disk.dsk")
let blank = try Data(contentsOf: blankURL)
for use6309 in [false, true] {
let localDisk = folder.appendingPathComponent(use6309 ? "6309.dsk" : "6809.dsk")
try blank.write(to: localDisk)
let controller = VCCMachineController()
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
let configured = await command { controller.loadDiskROM(diskROM, name: "Disk BASIC", completion: $0) }
XCTAssertNil(configured.errorMessage)
let layout = await command { controller.configureCartridges([2,0,0,0,2], roms: Array(repeating: Data(), count: 5),
names: Array(repeating: "", count: 5), multiPak: true, physicalSlot: 4, completion: $0) }
XCTAssertNil(layout.errorMessage)
let mounted = await command { controller.mountDisk(blank, drive: 0, name: localDisk.lastPathComponent, readOnly: false, completion: $0) }
XCTAssertNil(mounted.errorMessage)
_ = await command { controller.loadROM(rom, use6309: use6309, completion: $0) }
_ = await command(controller.resume)
try await Task.sleep(nanoseconds: 1_500_000_000)
_ = await command(controller.pause)
let loaded = await command { controller.debuggerLoadBinary(artifact.binaryData, breakpoint: instruction.address, completion: $0) }
XCTAssertNil(loaded.errorMessage)
var stopped = loaded
for _ in 0..<1000 where stopped.state == .running {
try await Task.sleep(nanoseconds: 10_000_000)
stopped = await command(controller.snapshot)
}
XCTAssertEqual(stopped.state, .paused)
XCTAssertEqual(stopped.programCounter, instruction.address)
let snapshot = await capture(controller, memory: resultAddress)
XCTAssertEqual(snapshot.memory.first, 0, "Nonzero value identifies the failing guest disk API step")
XCTAssertEqual(snapshot.instructions.first?.bytes, Data(instruction.bytes))
XCTAssertGreaterThan(stopped.disks[0].readEvents, 0)
XCTAssertGreaterThan(stopped.disks[0].writeEvents, 0)
let exported: Data? = await withCheckedContinuation { continuation in
controller.exportDisk(inDrive: 0) { bytes, _, _ in continuation.resume(returning: bytes) }
}
XCTAssertNotNil(exported)
if let exported {
XCTAssertNotEqual(exported, blank)
XCTAssertNotNil(exported.range(of: Data("ROUND DAT".utf8)), "The file must have a real DECB directory entry")
try exported.write(to: localDisk)
}
_ = await command(controller.shutdown)
}
XCTAssertEqual(try Data(contentsOf: blankURL), blank, "The repository's starter disk must remain pristine")
}
@MainActor func testCallerSelectionPreservesExecutionAndResetsOnStepOrStaleSource() async throws {
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let staged = vccQualificationToolchain(mac.appendingPathComponent("LocalResources/ToolchainBundle"))
let bundled = Bundle.main.resourceURL!.appendingPathComponent("Toolchain")
let toolchain = vccQualificationToolchain(FileManager.default.isExecutableFile(atPath: bundled.appendingPathComponent("bin/cmoc").path) ? bundled : staged)
let romURL = mac.appendingPathComponent("LocalResources/ROMs/coco3.rom")
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
&& FileManager.default.fileExists(atPath: romURL.path), "Stage the local compiler and CoCo ROM")
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCCallerSelection-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
let suite = "CMOCCallerSelection.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) }
let pageGlobals = (0..<40).map { String(format: "unsigned int page%02d;", $0) }.joined(separator: "\n")
let source = """
#include <cmoc.h>
unsigned int score;
unsigned int grid[12][40];
struct Info { unsigned int marker; unsigned int samples[2]; };
\(pageGlobals)
unsigned int recurse(unsigned int n)
{
unsigned int local = n + 10;
unsigned int items[40];
struct Info info;
items[0] = n + 20;
items[35] = n + 55;
info.marker = n + 30;
if (n == 0) {
score = local; /* LEAF_STOP */
return local; /* NEXT_LEAF_LINE */
}
local += recurse(n - 1); /* CALLER_SITE */
return local;
}
int main(void)
{
score = recurse(2);
for (;;) ++score;
return 0;
}
"""
let lines = source.components(separatedBy: "\n")
let leafLine = try XCTUnwrap(lines.firstIndex { $0.contains("LEAF_STOP") }) + 1
let nextLine = try XCTUnwrap(lines.firstIndex { $0.contains("NEXT_LEAF_LINE") }) + 1
let callerLine = try XCTUnwrap(lines.firstIndex { $0.contains("CALLER_SITE") }) + 1
let project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
try Data(source.utf8).write(to: project.sourceURL)
let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults,
inputStore: .init(url: root.appendingPathComponent("input.json")))
let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, defaults: defaults)
func snapshot() async throws -> VCCDebuggerSnapshot {
let result: VCCDebuggerSnapshot? = await withCheckedContinuation { continuation in
machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) }
}
return try XCTUnwrap(result)
}
func nodes(_ listing: CMOCVariableTreeListing) -> [CMOCWatchEvaluator.TreeNode] {
listing.rows.compactMap { row in if case .node(let node) = row.content { return node }; return nil }
}
let itemsPath = CMOCWatchEvaluator.TreePath(root: .variable("items"))
let infoPath = CMOCWatchEvaluator.TreePath(root: .variable("info"))
func expandedValues(offset: Int = 0) -> [CMOCWatchEvaluator.TreeNode] {
nodes(model.variableTree(watches: false, expanded: [itemsPath, infoPath], offsets: [itemsPath: offset], rootOffset: 0))
}
do {
try model.adopt(project)
model.build()
for _ in 0..<3000 where model.building { try await Task.sleep(nanoseconds: 10_000_000) }
XCTAssertFalse(model.building)
XCTAssertNil(model.message)
XCTAssertTrue(model.buildMatchesEditor, model.log)
for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) }
machine.installROM(try Data(contentsOf: romURL), url: romURL)
for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) }
try await Task.sleep(nanoseconds: 1_500_000_000)
model.breakpointLine = leafLine
XCTAssertTrue(model.canRun)
model.run()
for _ in 0..<1000 where model.currentLine != leafLine || model.callStack == nil {
model.refresh(); try await Task.sleep(nanoseconds: 10_000_000)
}
let stack = try XCTUnwrap(model.callStack, model.message ?? model.execution)
XCTAssertEqual(stack.frames.map(\.functionName), ["recurse", "recurse", "recurse", "main"], stack.termination)
XCTAssertEqual(model.watchValue("n")?.value, "0")
XCTAssertEqual(model.watchValue("local")?.value, "10")
let initialInspection = try XCTUnwrap(model.variableInspectionIdentity)
XCTAssertEqual(expandedValues().first { $0.path == itemsPath.appending(.index(0)) }?.value, "20")
XCTAssertEqual(expandedValues(offset: 32).first { $0.path == itemsPath.appending(.index(35)) }?.value, "55")
XCTAssertEqual(expandedValues().first { $0.path == infoPath.appending(.member("marker")) }?.value, "30")
let firstPage = model.variableTree(watches: false, expanded: [], offsets: [:], rootOffset: 0)
let secondPage = model.variableTree(watches: false, expanded: [], offsets: [:], rootOffset: 32)
XCTAssertGreaterThan(firstPage.rootCount, 32)
XCTAssertEqual(nodes(firstPage).count, 32)
XCTAssertEqual(secondPage.rootOffset, 32)
XCTAssertTrue(Set(nodes(firstPage).map(\.path)).isDisjoint(with: nodes(secondPage).map(\.path)))
let gridPath = CMOCWatchEvaluator.TreePath(root: .variable("grid"))
let expandedGrid = Set([gridPath] + (0..<12).map { gridPath.appending(.index($0)) })
let bounded = model.variableTree(watches: false, expanded: expandedGrid, offsets: [:], rootOffset: 0)
XCTAssertLessThanOrEqual(bounded.rows.count, 256)
XCTAssertTrue(bounded.rows.contains { $0.id == .limit }, "Broad trees must report the visible-row limit")
model.watchExpression = "items"; model.addWatch()
let watchPath = CMOCWatchEvaluator.TreePath(root: .watch("items"))
let executionPC = model.pc, executionLine = model.currentLine
let navigation = model.navigationRequest
let before = try await snapshot()
model.selectFrame(1)
XCTAssertEqual(model.selectedFrameIndex, 1)
XCTAssertNotEqual(model.variableInspectionIdentity, initialInspection)
let callerInspection = model.variableInspectionIdentity
XCTAssertEqual(expandedValues().first { $0.path == itemsPath.appending(.index(0)) }?.value, "21")
XCTAssertEqual(expandedValues().first { $0.path == infoPath.appending(.member("marker")) }?.value, "31")
let callerWatch = model.variableTree(watches: true, expanded: [watchPath], offsets: [:], rootOffset: 0)
XCTAssertEqual(nodes(callerWatch).first { $0.path == watchPath.appending(.index(0)) }?.value, "21")
XCTAssertTrue(model.inspectingCaller)
XCTAssertEqual(model.navigationLine, callerLine)
XCTAssertNotEqual(model.navigationRequest, navigation)
XCTAssertEqual(model.selectedFile, "main.c")
XCTAssertEqual(model.watchValue("n")?.value, "1")
XCTAssertEqual(model.visibleVariables.first { $0.name == "local" }?.value, "11")
XCTAssertEqual(model.pc, executionPC, "Source navigation must not replace the paused execution PC")
XCTAssertEqual(model.currentLine, executionLine)
let after = try await snapshot()
XCTAssertEqual(after.machine.programCounter, before.machine.programCounter)
XCTAssertEqual(after.machine.cycles, before.machine.cycles)
XCTAssertEqual(after.registers, before.registers)
XCTAssertEqual(after.logicalMemory, before.logicalMemory)
let callerNavigation = model.navigationRequest
for _ in 0..<6 { model.refresh(); try await Task.sleep(nanoseconds: 20_000_000) }
XCTAssertEqual(model.selectedFrameIndex, 1, "Polling the same stop must preserve caller selection")
XCTAssertEqual(model.navigationRequest, callerNavigation, "Polling must not snap navigation back to frame zero")
XCTAssertEqual(model.watchValue("local")?.value, "11")
XCTAssertEqual(model.variableInspectionIdentity, callerInspection, "Same-stop refresh must not collapse the variable tree")
XCTAssertEqual(expandedValues().first { $0.path == itemsPath.appending(.index(0)) }?.value, "21")
model.source += "\n/* edited source invalidates frame provenance */"
XCTAssertNil(model.callStack)
XCTAssertNil(model.inspectionFrame)
XCTAssertNil(model.watchValue("local"))
XCTAssertNil(model.variableInspectionIdentity)
XCTAssertTrue(model.variableTree(watches: false, expanded: [itemsPath], offsets: [:], rootOffset: 0).rows.isEmpty)
XCTAssertTrue(model.variableTree(watches: true, expanded: [watchPath], offsets: [:], rootOffset: 0).rows.isEmpty)
XCTAssertFalse(model.canStepC)
model.source = source
XCTAssertTrue(model.canStepC)
model.stepSource(.over)
for _ in 0..<1000 where model.currentLine != nextLine || model.commanding || model.callStack == nil {
model.refresh(); try await Task.sleep(nanoseconds: 10_000_000)
}
XCTAssertEqual(model.currentLine, nextLine, model.message ?? model.execution)
XCTAssertNotEqual(model.pc, executionPC)
XCTAssertEqual(model.selectedFrameIndex, 0, "Execution invalidates the selected caller context")
XCTAssertFalse(model.inspectingCaller)
XCTAssertNotEqual(model.variableInspectionIdentity, initialInspection)
XCTAssertNotEqual(model.variableInspectionIdentity, callerInspection)
XCTAssertEqual(expandedValues().first { $0.path == itemsPath.appending(.index(0)) }?.value, "20")
XCTAssertEqual(model.watchValue("n")?.value, "0", "Step must control the innermost frame, not the selected caller")
XCTAssertEqual(model.watchValue("local")?.value, "10")
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
} catch {
model.cancelBuild()
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
throw error
}
}
@MainActor func testDefaultHelloDiskLaunchRunsWithoutImplicitBreakpointAndHonorsExplicitStops() async throws {
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let resources = mac.appendingPathComponent("LocalResources")
let tools = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
let rom = resources.appendingPathComponent("ROMs/coco3.rom"), diskROM = resources.appendingPathComponent("ROMs/disk11.rom")
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path) &&
FileManager.default.fileExists(atPath: rom.path) && FileManager.default.fileExists(atPath: diskROM.path), "Stage local tools and ROMs")
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCNormalLaunch-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
let suite = "CMOCNormalLaunch." + UUID().uuidString
// Use an isolated preferences domain and writable media directory.
let testDefaults = UserDefaults(suiteName: suite)!
defer { testDefaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) }
let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: testDefaults,
inputStore: .init(url: root.appendingPathComponent("input.json")))
let model = CMOCDevelopmentModel(machine: machine, toolchain: tools, defaults: testDefaults)
func detail() async throws -> VCCDebuggerSnapshot {
let value: VCCDebuggerSnapshot? = await withCheckedContinuation { continuation in
machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) }
}
return try XCTUnwrap(value)
}
func idle() async throws {
for _ in 0..<1000 where machine.busy || model.commanding || machine.diskSaving { try await Task.sleep(nanoseconds: 10_000_000) }
XCTAssertFalse(machine.busy); XCTAssertFalse(model.commanding)
}
func screen(_ detail: VCCDebuggerSnapshot) -> String {
// Standard 32-column BASIC text cells, read without touching the clipboard.
String(bytes: detail.logicalMemory[0x400..<0x600].map { cell in
let code = cell & 0x3f
return code < 32 ? code + 64 : code
}, encoding: .ascii) ?? ""
}
func bootReady() async throws {
if machine.state == .paused { machine.resume(); try await idle() }
for _ in 0..<500 {
let value = try await detail()
if screen(value).contains("OK") {
let frame = value.machine.frames
for _ in 0..<500 {
try await Task.sleep(nanoseconds: 20_000_000)
if try await detail().machine.frames >= frame + 30 { return }
}
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
let failed = try await detail()
throw CMOCBuildError.message("Disk BASIC not ready: state=\(failed.machine.state.rawValue) frames=\(failed.machine.frames) screen=\(screen(failed))")
}
func completed() async throws {
var text = ""
for _ in 0..<1500 {
let snapshot = try await detail(); text = screen(snapshot)
if text.contains("GENERATED WORD COUNT: 5") && machine.pasteRemaining == 0 { break }
if !model.commanding && snapshot.machine.state == .paused { XCTFail("Normal launch stopped at an unrequested breakpoint"); break }
try await Task.sleep(nanoseconds: 20_000_000)
}
XCTAssertTrue(text.contains("DISK RESULT: 0"), text)
XCTAssertTrue(text.contains("GENERATED WORD COUNT: 5"), text)
XCTAssertEqual(machine.state, .running, model.message ?? model.execution)
}
do {
let template = mac.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("examples/cmoc/HelloDisk")
try model.adopt(CMOCProject.createHelloDisk(at: root.appendingPathComponent("Hello Disk"), templateDirectory: template))
model.build()
for _ in 0..<3000 where model.building { try await Task.sleep(nanoseconds: 10_000_000) }
XCTAssertTrue(model.buildMatchesEditor, model.log)
XCTAssertTrue(model.breakpoints.isEmpty)
XCTAssertTrue(model.resolvedBreakpointAddresses.isEmpty)
XCTAssertNotNil(model.breakpointAddress)
XCTAssertEqual(model.runToBreakpointAddresses, [try XCTUnwrap(model.breakpointAddress)])
try await idle()
machine.selectDiskROM(diskROM); try await idle()
machine.installROM(try Data(contentsOf: rom), url: rom); try await idle()
try await bootReady()
XCTAssertTrue(machine.diskEnabled)
XCTAssertTrue(model.canLaunch, model.message ?? model.execution)
model.launchDisk(commands: ["DOS"])
try await idle(); try await completed()
// Reboot to a clean prompt, then prove explicit source breakpoints still work.
machine.reset(); try await idle(); try await bootReady()
model.toggleBreakpoint(13)
XCTAssertFalse(model.resolvedBreakpointAddresses.isEmpty)
model.launchDisk(commands: ["DOS"])
try await idle()
for _ in 0..<1500 where model.currentLine != 13 {
model.refresh(); try await Task.sleep(nanoseconds: 20_000_000)
}
XCTAssertEqual(model.currentLine, 13, model.message ?? model.execution)
XCTAssertEqual(machine.state, .paused)
model.toggleBreakpoint(13); try await idle()
XCTAssertTrue(model.resolvedBreakpointAddresses.isEmpty)
machine.reset(); try await idle(); try await bootReady()
XCTAssertTrue(model.canLaunch, model.message ?? model.execution)
model.launchDisk(commands: ["DOS"])
try await idle(); try await completed()
XCTAssertNil(model.currentLine)
// The same default program also quickloads without a selected-line stop.
machine.reset(); try await idle(); try await bootReady()
model.launchQuickload(); try await idle(); try await completed()
XCTAssertNil(model.currentLine)
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
} catch {
model.cancelBuild()
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
throw error
}
}
@MainActor func testRealBuildMappingBecomesStaleWhenEditorChanges() async throws {
let bundled = Bundle.main.resourceURL!.appendingPathComponent("Toolchain")
let staged = vccQualificationToolchain(URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
.appendingPathComponent("LocalResources/ToolchainBundle"))
let toolchain = vccQualificationToolchain(FileManager.default.isExecutableFile(atPath: bundled.appendingPathComponent("bin/cmoc").path) ? bundled : staged)
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path),
"This integration check requires the bundled development toolchain")
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCDevelopmentTests-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
let suite = "CMOCDevelopmentTests.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: folder) }
let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), displayDefaults: defaults,
inputStore: .init(url: folder.appendingPathComponent("input.json")))
let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain)
do {
try model.adopt(CMOCProject.create(at: folder.appendingPathComponent("Project")))
model.build()
for _ in 0..<3000 where model.building { try await Task.sleep(nanoseconds: 10_000_000) }
XCTAssertFalse(model.building)
XCTAssertNil(model.message)
XCTAssertTrue(model.buildMatchesEditor, model.log)
XCTAssertNotNil(model.breakpointAddress)
if let artifact = model.artifact { defer { try? FileManager.default.removeItem(at: artifact.directory) }
let compiled = model.source
model.source += "\n/* edit after building */\n"
XCTAssertFalse(model.buildMatchesEditor)
XCTAssertNil(model.breakpointAddress, "An old address must never masquerade as a mapping for edited source")
XCTAssertFalse(model.canRun)
model.source = compiled
XCTAssertTrue(model.buildMatchesEditor)
let romURL = staged.deletingLastPathComponent().appendingPathComponent("ROMs/coco3.rom")
if FileManager.default.fileExists(atPath: romURL.path) {
for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) }
machine.installROM(try Data(contentsOf: romURL), url: romURL)
for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) }
try await Task.sleep(nanoseconds: 1_500_000_000)
model.breakpointLine = 9
XCTAssertTrue(model.canRun)
model.run()
for _ in 0..<500 where model.currentLine != 9 {
model.refresh(); try await Task.sleep(nanoseconds: 10_000_000)
}
XCTAssertEqual(model.currentLine, 9, model.message ?? model.execution)
XCTAssertEqual(model.pc, model.breakpointAddress)
XCTAssertTrue(model.loadedMatchesEditor)
XCTAssertTrue(model.canStepC)
XCTAssertTrue(model.canInspectC, model.variableStatus)
model.watchExpression = "1 + 2"; model.addWatch()
XCTAssertEqual(model.watchValue("1 + 2")?.value, "3")
model.source += "\n/* stale debug source */"
XCTAssertFalse(model.canStepC)
XCTAssertFalse(model.canInspectC)
XCTAssertNil(model.watchValue("1 + 2"), "Stale sources must hide even previously captured values")
model.source = compiled
await withCheckedContinuation { continuation in
machine.debuggerWriteMemory(address: 0x4000, data: Data([0x55])) { continuation.resume() }
}
for _ in 0..<100 where model.loadedMatchesEditor {
model.refresh(); try await Task.sleep(nanoseconds: 10_000_000)
}
XCTAssertFalse(model.loadedMatchesEditor, "A debugger memory edit must invalidate loaded source provenance")
XCTAssertFalse(model.canStepC); XCTAssertFalse(model.canInspectC)
XCTAssertNil(model.watchValue("1 + 2"))
XCTAssertNil(model.currentLine)
model.run()
for _ in 0..<500 where model.currentLine != 9 {
model.refresh(); try await Task.sleep(nanoseconds: 10_000_000)
}
XCTAssertEqual(model.currentLine, 9)
machine.reset()
for _ in 0..<100 where model.loadedMatchesEditor {
model.refresh(); try await Task.sleep(nanoseconds: 10_000_000)
}
XCTAssertFalse(model.loadedMatchesEditor, "A machine reset must detach the previous C execution session")
XCTAssertNil(model.currentLine)
}
}
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
} catch {
model.cancelBuild()
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
throw error
}
}
}
final class CMOCWorkspaceDocumentTests: XCTestCase {
@MainActor func testTabsSaveAllOutsideConflictAndRestoration() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCWorkspaceDocs-\(UUID().uuidString)")
let defaultsName = "CMOCWorkspaceDocs.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: defaultsName)!
defer { defaults.removePersistentDomain(forName: defaultsName); try? FileManager.default.removeItem(at: root) }
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
let project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
try Data("#define ANSWER 42\n".utf8).write(to: project.directory.appendingPathComponent("shared.h"))
let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("input.json")))
let model = CMOCDevelopmentModel(machine: machine, defaults: defaults)
try model.adopt(project)
model.source += "\n/* unsaved main */"
let main = model.source
model.openFile("shared.h"); model.source = "#define ANSWER 43\n"
model.openFile("main.c")
XCTAssertEqual(model.source, main)
XCTAssertTrue(model.unsaved)
XCTAssertTrue(model.save())
XCTAssertEqual(try project.readText(relativePath: "shared.h"), "#define ANSWER 43\n")
model.openFile("shared.h"); model.source = "#define ANSWER 44\n"
try Data("#define ANSWER 99\n".utf8).write(to: project.directory.appendingPathComponent("shared.h"))
model.checkExternalFiles()
XCTAssertTrue(model.documents.first { $0.id == "shared.h" }!.conflict)
XCTAssertFalse(model.save())
XCTAssertEqual(try project.readText(relativePath: "shared.h"), "#define ANSWER 99\n", "Outside edits must survive Save All")
XCTAssertEqual(model.source, "#define ANSWER 44\n", "Editor edits remain recoverable")
let restored = CMOCDevelopmentModel(machine: machine, defaults: defaults)
restored.restoreWorkspace()
XCTAssertEqual(restored.documents.map(\.id), ["main.c", "shared.h"])
XCTAssertEqual(restored.selectedFile, "shared.h")
XCTAssertEqual(restored.source, "#define ANSWER 99\n", "Restoration reads disk without executing Make")
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
}
@MainActor func testSettingsGenerationProtectsCustomChangesAndKeepsBackup() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCWorkspaceSettings-\(UUID().uuidString)")
let defaultsName = "CMOCWorkspaceSettings.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: defaultsName)!
defer { defaults.removePersistentDomain(forName: defaultsName); try? FileManager.default.removeItem(at: root) }
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
let project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
let original = try project.readText(relativePath: "Makefile")
let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("input.json")))
let model = CMOCDevelopmentModel(machine: machine, defaults: defaults)
try model.adopt(project)
var settings = CMOCMakefileSettings(); settings.executable = "hello.bin"
var configuration = project.configuration; configuration.makefileSettings = settings; configuration.binary = "hello.bin"
let generated = try settings.generateMakefile()
let hash = CMOCProject.sha256(Data(original.utf8))
try Data((original + "\n# outside edit\n").utf8).write(to: project.makefileURL)
XCTAssertThrowsError(try model.applyProjectSettings(configuration, makefile: generated, expectedMakefileHash: hash, expectedConfigHash: nil))
XCTAssertFalse(FileManager.default.fileExists(atPath: project.directory.appendingPathComponent(CMOCProject.configurationFilename).path))
try Data(original.utf8).write(to: project.makefileURL)
try model.applyProjectSettings(configuration, makefile: generated, expectedMakefileHash: hash, expectedConfigHash: nil)
XCTAssertEqual(try String(contentsOf: project.makefileURL), generated)
let backups = try FileManager.default.contentsOfDirectory(at: project.directory.appendingPathComponent(".vccplus-build/Makefile Backups"), includingPropertiesForKeys: nil)
XCTAssertEqual(backups.count, 1)
XCTAssertEqual(try String(contentsOf: backups[0]), original)
XCTAssertEqual(try CMOCProject.open(at: project.directory).configuration.binary, "hello.bin")
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
}
@MainActor func testClickableDiagnosticRetainsNestedFileIdentity() {
let diagnostics = CMOCDevelopmentModel.parseDiagnostics("src/one/helper.c:17: error: missing value\n/private/tmp/build/src/two/helper.c:9:4: warning: unused\nmake: failed", directory: URL(fileURLWithPath: "/private/tmp/build"))
XCTAssertEqual(diagnostics.map(\.file), ["src/one/helper.c", "src/two/helper.c"])
XCTAssertEqual(diagnostics.map(\.line), [17, 9])
}
}