Files
VCCPlusOSS/platforms/macos/Tests/CMOCFloatingPointIntegrationTests.swift
T
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

179 lines
11 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
/// Runs actual ROM-backed CMOC float operations before inspecting both live frames.
final class CMOCFloatingPointIntegrationTests: XCTestCase {
private struct Fixture {
let root: URL
let artifact: CMOCBuildArtifact
let metadata: CMOCVariableDebug
let rom: Data
let sources: [String: String]
func line(_ marker: String, file: String) throws -> Int {
try XCTUnwrap(sources[file]?.components(separatedBy: "\n").firstIndex { $0.contains(marker) }) + 1
}
func address(_ marker: String, file: String) throws -> UInt16 {
try XCTUnwrap(metadata.sourceMap.addresses(forLine: line(marker, file: file), in: file).first, marker)
}
}
private func fixture() async throws -> Fixture {
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
let rom = resources.appendingPathComponent("ROMs/coco3.rom")
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path)
&& FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required")
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCFloatingPoint-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
do {
let project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
let sources = ["types.h": """
struct Measurements { float x; float samples[3]; float *pointer; };
""", "main.c": """
#include <cmoc.h>
#include <coco.h>
#include "types.h"
float globalValues[6] = { 0.0f, 1.5f, -2.75f, 1.0e-20f, 1.0e20f, 0.1f };
float globalResult;
unsigned int result;
unsigned int inspect(float input, struct Measurements *parent);
int main(void)
{
float callerValue = -6.25f;
struct Measurements measurements;
initCoCoSupport();
measurements.x = 1.25f;
measurements.samples[0] = 0.5f;
measurements.samples[1] = -0.125f;
measurements.samples[2] = 8.0f;
measurements.pointer = &measurements.samples[1];
result = inspect(callerValue, &measurements); /* MAIN_CALL */
for (;;) ++result;
return 0;
}
""", "helper.c": """
#include "types.h"
extern float globalResult;
extern unsigned int result;
unsigned int inspect(float input, struct Measurements *parent)
{
float local = input + 0.5f;
float samples[2];
samples[0] = 0.25f;
samples[1] = -16.5f;
globalResult = parent->x * 3.0f;
result = 1; /* LEAF_STOP */
return result;
}
"""]
for (name, source) in sources { try Data(source.utf8).write(to: project.directory.appendingPathComponent(name)) }
let makefile = """
CMOC ?= cmoc
build: main.bin
main.bin: main.o helper.o
\t"$(CMOC)" --coco --intermediate --org=2800 -o $@ main.o helper.o
main.o: main.c
\t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $<
helper.o: helper.c
\t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $<
"""
try Data(makefile.utf8).write(to: project.makefileURL)
let service = CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds"))
let artifact = try await service.build(project: project, overlays: [:])
let map = try CMOCProjectSourceMap.parse(artifact: artifact)
let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map)
return Fixture(root: root, artifact: artifact, metadata: metadata, rom: try Data(contentsOf: rom), sources: sources)
} catch { try? FileManager.default.removeItem(at: root); throw error }
}
@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) async -> VCCDebuggerSnapshot {
await withCheckedContinuation { continuation in
controller.debuggerSnapshot(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) }
}
}
@MainActor private func withStoppedProcessors(_ fixture: Fixture,
body: (VCCMachineController, VCCDebuggerSnapshot) async throws -> Void) async throws {
for use6309 in [false, true] {
let controller = VCCMachineController()
do {
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
let loaded = await command { controller.loadROM(fixture.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 breakpoint = try fixture.address("LEAF_STOP", file: "helper.c")
var state = await command { controller.debuggerLoadBinary(fixture.artifact.binaryData, breakpoint: breakpoint, completion: $0) }
for _ in 0..<1000 where state.state == .running {
try await Task.sleep(nanoseconds: 5_000_000)
state = await command(controller.snapshot)
}
XCTAssertNil(state.errorMessage)
XCTAssertEqual(state.state, .paused)
XCTAssertEqual(state.programCounter, breakpoint)
try await body(controller, await capture(controller))
_ = await command(controller.shutdown)
} catch { _ = await command(controller.shutdown); throw error }
}
}
private func stack(_ fixture: Fixture, _ snapshot: VCCDebuggerSnapshot,
memory: Data? = nil, available: Data? = nil) throws -> CMOCCallStack {
CMOCCallStack.capture(metadata: fixture.metadata, pc: snapshot.machine.programCounter,
u: try XCTUnwrap(snapshot.registers["U"]?.uint16Value), s: try XCTUnwrap(snapshot.registers["S"]?.uint16Value),
memory: memory ?? snapshot.logicalMemory, available: available ?? snapshot.logicalMemoryAvailable)
}
@MainActor func testCompiledFloatingValuesAndCallerFramesOnBothProcessors() async throws {
let fixture = try await fixture()
defer { try? FileManager.default.removeItem(at: fixture.root) }
try await withStoppedProcessors(fixture) { controller, snapshot in
let originalMemory = Data(Array(snapshot.logicalMemory))
let frames = try stack(fixture, snapshot)
XCTAssertEqual(frames.frames.map(\.functionName), ["inspect", "main"], frames.termination)
guard frames.frames.count == 2 else { return }
func evaluator(_ frame: CMOCCallStack.Frame) -> CMOCWatchEvaluator {
CMOCWatchEvaluator(metadata: fixture.metadata,
context: .init(pc: frame.pc, u: frame.u, memory: snapshot.logicalMemory,
available: snapshot.logicalMemoryAvailable),
frameLocalsAvailable: frame.localsInspectable)
}
let current = evaluator(frames.frames[0]), caller = evaluator(frames.frames[1])
for (engine, expression, expected) in [
(current, "input", "-6.25"), (current, "local", "-5.75"),
(current, "samples[0]", "0.25"), (current, "samples[1]", "-16.5"),
(current, "globalResult", "3.75"), (current, "parent->x", "1.25"),
(current, "*parent->pointer", "-0.125"), (caller, "callerValue", "-6.25"),
(caller, "measurements.x", "1.25"), (caller, "*measurements.pointer", "-0.125")
] {
let value = engine.evaluate(expression)
XCTAssertNil(value.error, "\(expression): \(value.error ?? "")")
XCTAssertEqual(value.value, expected, expression)
}
let globals = current.children(of: .init(root: .variable("globalValues"))).nodes
XCTAssertEqual(globals.count, 6)
XCTAssertEqual(Array(globals.prefix(3).map(\.value)), ["0", "1.5", "-2.75"])
XCTAssertEqual(try XCTUnwrap(Double(globals[3].value)), 1e-20, accuracy: 1e-29)
XCTAssertEqual(try XCTUnwrap(Double(globals[4].value)), 1e20, accuracy: 1e11)
XCTAssertEqual(globals[5].value, "0.099999999977", "Preserve the compiled 32-bit significand rather than rounding through host Float")
let aggregate = caller.watchTreeRoot("measurements")
XCTAssertEqual(aggregate.childCount, 3)
let member = caller.children(of: aggregate.path).nodes
XCTAssertEqual(member[0].value, "1.25")
XCTAssertEqual(caller.children(of: member[1].path).nodes.map(\.value), ["0.5", "-0.125", "8"])
XCTAssertEqual(caller.children(of: member[2].path).nodes.first?.value, "-0.125")
XCTAssertTrue(current.visibleVariables().contains { $0.name == "local" && $0.value == "-5.75" && $0.error == nil })
// The compiler chooses a format explicitly; the app must not guess
// from a float's name, byte count or the machine's current ROM.
let inputType = try XCTUnwrap(fixture.metadata.variables.first { $0.name == "input" }?.type)
XCTAssertEqual(inputType.floatingFormat, "coco-basic-40")
XCTAssertEqual(inputType.size, 5)
let after = await capture(controller)
XCTAssertEqual(after.machine.programCounter, snapshot.machine.programCounter)
XCTAssertEqual(after.machine.cycles, snapshot.machine.cycles)
XCTAssertEqual(after.registers, snapshot.registers)
XCTAssertEqual(snapshot.logicalMemory, originalMemory)
XCTAssertEqual(after.logicalMemory, originalMemory, "Reading floats must not execute guest math routines or touch memory")
}
}
}