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.
302 lines
22 KiB
Swift
302 lines
22 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import XCTest
|
|
|
|
final class CMOCNavigationTests: XCTestCase {
|
|
private struct Deadline: Error {}
|
|
private struct Fixture {
|
|
let root: URL
|
|
let project: CMOCProject
|
|
let model: CMOCDevelopmentModel
|
|
let machine: MachineModel
|
|
let defaults: UserDefaults
|
|
let suite: String
|
|
}
|
|
@MainActor private func waitUntil(_ description: String, _ predicate: () -> Bool) async throws {
|
|
for _ in 0..<800 {
|
|
if predicate() { return }
|
|
try await Task.sleep(nanoseconds: 10_000_000)
|
|
}
|
|
XCTFail("Timed out waiting for " + description); throw Deadline()
|
|
}
|
|
@MainActor private func withFixture(_ body: (Fixture) async throws -> Void) async throws {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCNavigation-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
let suite = "CMOCNavigation." + UUID().uuidString, defaults = UserDefaults(suiteName: suite)!
|
|
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) }
|
|
var project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
|
|
var recipe = CMOCMakefileSettings(); recipe.sources = ["main.c", "helper.c"]; recipe.libraries = []
|
|
recipe.includePaths = ["include"]
|
|
project.configuration.makefileSettings = recipe
|
|
try JSONEncoder().encode(project.configuration).write(to: project.directory.appendingPathComponent(CMOCProject.configurationFilename))
|
|
try FileManager.default.createDirectory(at: project.directory.appendingPathComponent("include"), withIntermediateDirectories: true)
|
|
try Data("int helper(void);\n".utf8).write(to: project.directory.appendingPathComponent("include/api.h"))
|
|
let main = "#include \"api.h\"\nint globalValue;\nint main(void) { /* 🙂 */ return helper(); }\n"
|
|
try Data(main.utf8).write(to: project.sourceURL)
|
|
try Data("/* helper implementation */\nint helper(void) { return 42; }\n".utf8).write(to: project.directory.appendingPathComponent("helper.c"))
|
|
try Data((try recipe.generateMakefile() + "\nNAVIGATION_SENTINEL := $(shell touch navigation-must-not-run)\n").utf8).write(to: project.makefileURL)
|
|
let toolchain = root.appendingPathComponent("Toolchain"), includes = toolchain.appendingPathComponent("share/cmoc/include")
|
|
try FileManager.default.createDirectory(at: includes, withIntermediateDirectories: true)
|
|
try Data("int library_only_marker(void);\n".utf8).write(to: includes.appendingPathComponent("cmoc.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, toolchain: toolchain, defaults: defaults,
|
|
buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery"))
|
|
do {
|
|
try model.adopt(project)
|
|
try await body(.init(root: root, project: project, model: model, machine: machine, defaults: defaults, suite: suite))
|
|
await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } }
|
|
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
|
|
} catch {
|
|
model.cancelBuild()
|
|
await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } }
|
|
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
|
|
throw error
|
|
}
|
|
}
|
|
@MainActor func testParameterHintsFollowCurrentDraftAndRejectDelayedResults() async throws {
|
|
try await withFixture { f in
|
|
let draft = "int sum(int left, int right);\nint main(void) { return sum(1, 2); }\n"
|
|
f.model.source = draft
|
|
f.model.refreshProjectIndex()
|
|
try await waitUntil("hint declarations") { !f.model.indexing && f.model.projectIndex?.documents["main.c"] == draft }
|
|
let caret = (draft as NSString).range(of: "2);").location
|
|
f.model.updateCursor(offset: caret)
|
|
f.model.refreshParameterHints()
|
|
try await waitUntil("second parameter") { f.model.parameterHints.first?.activeParameter == 1 }
|
|
XCTAssertEqual(f.model.parameterHints.first?.name, "sum")
|
|
XCTAssertEqual(f.model.source, draft)
|
|
let originalRequest = f.model.completionRequest
|
|
f.model.requestCompletion()
|
|
XCTAssertNotEqual(originalRequest, f.model.completionRequest)
|
|
XCTAssertEqual(f.model.source, draft, "Requesting completion must not edit the draft")
|
|
|
|
f.model.updateCursor(offset: caret)
|
|
f.model.source = "int main(void) { return 0; }\n"
|
|
f.model.updateCursor(offset: 0)
|
|
try await Task.sleep(nanoseconds: 250_000_000)
|
|
XCTAssertTrue(f.model.parameterHints.isEmpty, "An older scan must not show a call removed from the draft")
|
|
f.model.openFile("helper.c")
|
|
f.model.refreshParameterHints()
|
|
try await Task.sleep(nanoseconds: 150_000_000)
|
|
XCTAssertTrue(f.model.parameterHints.isEmpty, "Switching documents invalidates the old call context")
|
|
|
|
f.model.refreshProjectIndex()
|
|
try await waitUntil("reference index") { !f.model.indexing && f.model.projectIndex?.documents["@toolchain/include/cmoc.h"] != nil }
|
|
f.model.openFile("@toolchain/include/cmoc.h")
|
|
let referenceRequest = f.model.completionRequest
|
|
f.model.requestCompletion()
|
|
XCTAssertEqual(referenceRequest, f.model.completionRequest, "Read-only references cannot request an edit")
|
|
XCTAssertTrue(f.model.parameterHints.isEmpty)
|
|
}
|
|
}
|
|
@MainActor func testUnsavedSearchOutlineAndDefinitionHistoryPreserveExactCursorAndText() async throws {
|
|
try await withFixture { f in
|
|
let original = f.model.source
|
|
f.model.source += "\nint unsavedFunction(void) { return 7; } /* navigation_needle */\n"
|
|
let edited = f.model.source
|
|
f.model.refreshProjectIndex()
|
|
try await waitUntil("unsaved index") { !f.model.indexing && f.model.projectIndex?.documents["main.c"] == edited }
|
|
XCTAssertTrue(f.model.currentOutline.contains { $0.name == "unsavedFunction" && $0.isDefinition })
|
|
XCTAssertEqual(try String(contentsOf: f.project.sourceURL, encoding: .utf8), original)
|
|
XCTAssertFalse(FileManager.default.fileExists(atPath: f.project.directory.appendingPathComponent("navigation-must-not-run").path))
|
|
|
|
let callOffset = (edited as NSString).range(of: "helper()", options: .backwards).location + 2
|
|
f.model.updateCursor(offset: callOffset)
|
|
f.model.goToDefinition()
|
|
XCTAssertEqual(f.model.selectedFile, "helper.c")
|
|
XCTAssertEqual(f.model.navigationLine, 2)
|
|
XCTAssertTrue(f.model.canNavigateBack)
|
|
f.model.navigateBack()
|
|
XCTAssertEqual(f.model.selectedFile, "main.c")
|
|
XCTAssertEqual(f.model.cursorOffset, callOffset, "Back restores the actual UTF-16 caret, including text after emoji")
|
|
XCTAssertEqual(f.model.source, edited, "Navigation must preserve unsaved editor contents")
|
|
XCTAssertTrue(f.model.canNavigateForward)
|
|
f.model.navigateForward()
|
|
XCTAssertEqual(f.model.selectedFile, "helper.c")
|
|
XCTAssertEqual(f.model.navigationLine, 2)
|
|
f.model.navigateBack()
|
|
|
|
f.model.searchQuery = "NAVIGATION_NEEDLE"; f.model.searchCaseSensitive = false
|
|
try await waitUntil("case-insensitive search") { f.model.searchMatches.contains { $0.path == "main.c" } }
|
|
let match = try XCTUnwrap(f.model.searchMatches.first { $0.path == "main.c" })
|
|
f.model.openSearchMatch(match)
|
|
XCTAssertEqual(f.model.selectedFile, "main.c")
|
|
XCTAssertEqual(f.model.navigationColumn, match.column)
|
|
XCTAssertEqual(f.model.navigationLength, match.lengthUTF16)
|
|
XCTAssertEqual(f.model.source, edited)
|
|
f.model.searchCaseSensitive = true
|
|
try await waitUntil("case-sensitive search") { f.model.searchMatches.isEmpty }
|
|
XCTAssertNil(f.model.artifact, "Indexing and navigation do not build or load the guest")
|
|
}
|
|
}
|
|
@MainActor func testBundledHeadersAreReadOnlyAndExcludedFromProjectSearchAndOverlays() async throws {
|
|
try await withFixture { f in
|
|
f.model.refreshProjectIndex()
|
|
let path = "@toolchain/include/cmoc.h"
|
|
try await waitUntil("bundled header index") { !f.model.indexing && f.model.projectIndex?.documents[path] != nil }
|
|
let symbol = try XCTUnwrap(f.model.projectIndex?.symbols.first { $0.path == path && $0.name == "library_only_marker" })
|
|
f.model.openSymbol(symbol)
|
|
XCTAssertEqual(f.model.selectedFile, path)
|
|
XCTAssertTrue(f.model.selectedFileIsGenerated, "Reference headers use the read-only editor path")
|
|
XCTAssertFalse(f.model.overlays.keys.contains(path), "Toolchain references must never enter a project build snapshot")
|
|
XCTAssertFalse(f.model.saveFile(path), "Reference headers cannot overwrite the bundled library")
|
|
XCTAssertTrue(f.model.documents.first { $0.id == path }?.reference == true)
|
|
f.model.checkExternalFiles()
|
|
XCTAssertFalse(f.model.documents.first { $0.id == path }?.missing == true, "Project scanning must not mistake a library header for a missing project file")
|
|
f.model.searchQuery = "library_only_marker"
|
|
try await Task.sleep(nanoseconds: 250_000_000)
|
|
XCTAssertTrue(f.model.searchMatches.isEmpty, "Find in Project excludes toolchain reference files")
|
|
f.model.openFile("main.c")
|
|
XCTAssertFalse(f.model.selectedFileIsGenerated)
|
|
XCTAssertFalse(f.model.unsaved)
|
|
}
|
|
}
|
|
@MainActor func testProjectSwitchRejectsStaleIndexAndNavigationHistory() async throws {
|
|
try await withFixture { f in
|
|
f.model.source += "\nint old_project_only;\n"
|
|
f.model.refreshProjectIndex()
|
|
let other = try CMOCProject.create(at: f.root.appendingPathComponent("OtherProject"))
|
|
try Data("int new_project_only;\nint main(void) { return 0; }\n".utf8).write(to: other.sourceURL)
|
|
try f.model.adopt(other)
|
|
f.model.refreshProjectIndex()
|
|
try await waitUntil("new project index") { !f.model.indexing && f.model.projectIndex?.documents["main.c"]?.contains("new_project_only") == true }
|
|
XCTAssertFalse(f.model.projectIndex?.symbols.contains { $0.name == "old_project_only" } == true)
|
|
XCTAssertFalse(f.model.canNavigateBack)
|
|
XCTAssertFalse(f.model.canNavigateForward)
|
|
f.model.searchQuery = "old_project_only"
|
|
try await Task.sleep(nanoseconds: 250_000_000)
|
|
XCTAssertTrue(f.model.searchMatches.isEmpty)
|
|
XCTAssertEqual(f.model.project?.directory, other.directory)
|
|
XCTAssertNil(f.model.artifact)
|
|
}
|
|
}
|
|
@MainActor func testOutdatedSearchHitDoesNotNavigateToDifferentDiskText() async throws {
|
|
try await withFixture { f in
|
|
let path = f.project.directory.appendingPathComponent("notes.txt")
|
|
try Data("before\nunique old match\nafter\n".utf8).write(to: path)
|
|
f.model.refreshProjectIndex()
|
|
try await waitUntil("text-resource index") { !f.model.indexing && f.model.projectIndex?.documents["notes.txt"] != nil }
|
|
f.model.searchQuery = "unique old match"
|
|
try await waitUntil("old text match") { f.model.searchMatches.contains { $0.path == "notes.txt" } }
|
|
let match = try XCTUnwrap(f.model.searchMatches.first { $0.path == "notes.txt" })
|
|
try Data("completely different source\n".utf8).write(to: path)
|
|
f.model.openSearchMatch(match)
|
|
XCTAssertNotEqual(f.model.selectedFile, "notes.txt", "A stale hit must not select unrelated new disk text")
|
|
XCTAssertNotNil(f.model.message)
|
|
XCTAssertEqual(try String(contentsOf: path, encoding: .utf8), "completely different source\n")
|
|
try await waitUntil("refreshed changed source") { !f.model.indexing && f.model.projectIndex?.documents["notes.txt"] == "completely different source\n" }
|
|
f.model.openSearchMatch(match)
|
|
XCTAssertNotEqual(f.model.selectedFile, "notes.txt", "An old result also stays rejected after a replacement index has completed")
|
|
}
|
|
}
|
|
@MainActor func testReferenceNavigationKeepsSuccessfulBuildIdentity() async throws {
|
|
let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources")
|
|
let toolchain = vccQualificationToolchain(resources.appendingPathComponent("ToolchainBundle"))
|
|
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged toolchain required")
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCNavigationBuild-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
let suite = "CMOCNavigationBuild." + UUID().uuidString, defaults = UserDefaults(suiteName: suite)!
|
|
defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) }
|
|
let project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
|
|
let retired = project.directory.appendingPathComponent("retired.h")
|
|
try Data("int retired_project_symbol;\n".utf8).write(to: retired)
|
|
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,
|
|
buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery"))
|
|
do {
|
|
try model.adopt(project)
|
|
model.build(); try await waitUntil("compiler build") { !model.building }
|
|
let artifact = try XCTUnwrap(model.artifact, model.message ?? model.log)
|
|
XCTAssertTrue(model.buildMatchesEditor)
|
|
model.refreshProjectIndex()
|
|
try await waitUntil("built index") { !model.indexing && model.projectIndex?.documents["@toolchain/include/cmoc.h"] != nil }
|
|
let symbol = try XCTUnwrap(model.projectIndex?.symbols.first { $0.path == "@toolchain/include/cmoc.h" && $0.name == "printf" })
|
|
model.openSymbol(symbol)
|
|
XCTAssertTrue(model.selectedFileIsGenerated)
|
|
XCTAssertEqual(model.artifact?.id, artifact.id)
|
|
XCTAssertTrue(model.buildMatchesEditor, "Reading a library declaration must not make an otherwise current build stale")
|
|
model.checkExternalFiles()
|
|
XCTAssertTrue(model.buildMatchesEditor)
|
|
XCTAssertFalse(model.overlays.keys.contains { $0.hasPrefix("@toolchain/") })
|
|
XCTAssertNil(model.launchedBuildID, "Navigation must never run a successful build")
|
|
XCTAssertNotNil(artifact.sources["retired.h"])
|
|
try FileManager.default.removeItem(at: retired)
|
|
model.refreshProjectIndex()
|
|
try await waitUntil("index after deleted ordinary source") { !model.indexing && model.projectIndex != nil }
|
|
XCTAssertNil(model.projectIndex?.documents["retired.h"], "A deleted ordinary source must not reappear as a generated build snapshot")
|
|
XCTAssertFalse(model.projectIndex?.symbols.contains { $0.name == "retired_project_symbol" } == true)
|
|
await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } }
|
|
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
|
|
} catch {
|
|
model.cancelBuild()
|
|
await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } }
|
|
await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } }
|
|
throw error
|
|
}
|
|
}
|
|
func testIndexInputsHonorManagedFlagsAndBoundariesWithoutExecutingRecipes() throws {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCIndexInputs-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
var project = try CMOCProject.create(at: root.appendingPathComponent("Project"))
|
|
var recipe = CMOCMakefileSettings(); recipe.libraries = []; recipe.includePaths = ["include"]
|
|
recipe.defines = ["FEATURE=1"]; recipe.compilerOptions = ["-DOPTION=2", "-Iextra"]
|
|
recipe.generatedResources = [.init(outputs: ["generated/schema.h"], inputs: ["main.c"], command: "touch must-not-run")]
|
|
project.configuration.makefileSettings = recipe
|
|
project.configuration.configurations.append(.init(name: "Custom", makeArguments: ["CPPFLAGS=-DOTHER=1"]))
|
|
try JSONEncoder().encode(project.configuration).write(to: project.directory.appendingPathComponent(CMOCProject.configurationFilename))
|
|
try Data(recipe.generateMakefile().utf8).write(to: project.makefileURL)
|
|
let generated = project.directory.appendingPathComponent("generated/schema.h")
|
|
try FileManager.default.createDirectory(at: generated.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
try Data("#define STALE_GENERATED 1\n".utf8).write(to: generated)
|
|
let outside = root.appendingPathComponent("outside.h")
|
|
try Data("int should_not_be_indexed;\n".utf8).write(to: outside)
|
|
try FileManager.default.createSymbolicLink(at: project.directory.appendingPathComponent("escaped.h"), withDestinationURL: outside)
|
|
let toolchain = root.appendingPathComponent("Toolchain"), headers = toolchain.appendingPathComponent("share/cmoc/include")
|
|
try FileManager.default.createDirectory(at: headers, withIntermediateDirectories: true)
|
|
try Data("int library_function(void);\n".utf8).write(to: headers.appendingPathComponent("cmoc.h"))
|
|
try Data("{\"cmoc\":\"0.1.100\"}".utf8).write(to: toolchain.appendingPathComponent("manifest.json"))
|
|
let expected = "#define CURRENT_GENERATED 1\n"
|
|
let input = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug",
|
|
overlays: ["main.c": "int unsaved_input;\n"], generated: ["generated/schema.h": Data(expected.utf8)])
|
|
XCTAssertFalse(input.configurationUncertain)
|
|
XCTAssertTrue(input.defines.contains("FEATURE=1")); XCTAssertTrue(input.defines.contains("OPTION=2"))
|
|
XCTAssertTrue(input.defines.contains("_CMOC_VERSION_=1100")); XCTAssertTrue(input.defines.contains("_COCO_BASIC_=1"))
|
|
XCTAssertTrue(input.includePaths.contains("include")); XCTAssertTrue(input.includePaths.contains("extra"))
|
|
XCTAssertEqual(input.documents["main.c"], "int unsaved_input;\n")
|
|
XCTAssertEqual(input.documents["generated/schema.h"], expected)
|
|
XCTAssertTrue(input.generatedPaths.contains("generated/schema.h"))
|
|
XCTAssertTrue(input.referencePaths.contains("@toolchain/include/cmoc.h"), "Header paths: \(input.referencePaths.sorted()); issues: \(input.issues)")
|
|
XCTAssertNil(input.documents["escaped.h"])
|
|
XCTAssertTrue(input.issues.contains { $0.contains("Linked") })
|
|
XCTAssertFalse(FileManager.default.fileExists(atPath: project.directory.appendingPathComponent("must-not-run").path))
|
|
let custom = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Custom", overlays: [:], generated: [:])
|
|
XCTAssertTrue(custom.configurationUncertain, "Arbitrary selected Make assignments cannot be treated as compiler-verified flags")
|
|
XCTAssertFalse(custom.defines.contains("OTHER=1"), "Navigation must not execute or guess arbitrary Make variables")
|
|
let missingLibrary = try CMOCIndexInputs.load(project: project, toolchain: root.appendingPathComponent("NoToolchain"), configurationName: "Debug", overlays: [:], generated: [:])
|
|
XCTAssertNotNil(missingLibrary.documents["main.c"], "Missing optional bundled headers must not disable project navigation")
|
|
XCTAssertTrue(missingLibrary.referencePaths.isEmpty)
|
|
XCTAssertTrue(missingLibrary.issues.contains { $0.contains("headers") && $0.contains("unavailable") })
|
|
// These switches set compiler mode first; CMOC emits all user -D
|
|
// values after its builtins, even when the mode switch occurs later.
|
|
recipe.defines = ["_CMOC_NATIVE_FLOAT_=0"]
|
|
recipe.compilerOptions = ["--mc6839", "--native-float", "-funsigned-char", "-fsigned-char", "--no-relocate"]
|
|
project.configuration.makefileSettings = recipe
|
|
try JSONEncoder().encode(project.configuration).write(to: project.directory.appendingPathComponent(CMOCProject.configurationFilename))
|
|
try Data(recipe.generateMakefile().utf8).write(to: project.makefileURL)
|
|
let modes = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug", overlays: [:], generated: [:])
|
|
XCTAssertFalse(modes.configurationUncertain)
|
|
XCTAssertFalse(modes.defines.contains("_CMOC_MC6839_=1"), "Only the final floating-point mode may be predefined")
|
|
XCTAssertFalse(modes.defines.contains("_CMOC_unsigned_char_=1"), "The final signed-char switch restores CMOC's default")
|
|
XCTAssertTrue(modes.defines.contains("_CMOC_NO_RELOCATE_=1"))
|
|
let branches = "#if _CMOC_NATIVE_FLOAT_\nint wrong_builtin_override;\n#else\nint correct_user_override;\n#endif\n"
|
|
let modeIndex = CMOCProjectIndex(documents: ["modes.c": branches], defines: modes.defines,
|
|
configurationUncertain: modes.configurationUncertain)
|
|
XCTAssertTrue(modeIndex.symbols.contains { $0.name == "correct_user_override" })
|
|
XCTAssertFalse(modeIndex.symbols.contains { $0.name == "wrong_builtin_override" })
|
|
|
|
}
|
|
|
|
}
|