165 lines
12 KiB
Swift
165 lines
12 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import Foundation
|
|
|
|
/// Read-only inputs for browsing. Never invokes Make or a compiler to discover
|
|
/// flags, and never follows project links into unrelated folders.
|
|
struct CMOCIndexInputs: Sendable {
|
|
static let libraryPrefix = "@toolchain/include/"
|
|
static let maximumBytes = 16 * 1024 * 1024
|
|
static let maximumFiles = 1024
|
|
var documents: [String: String] = [:]
|
|
var referencePaths: Set<String> = []
|
|
var generatedPaths: Set<String> = []
|
|
var issues: [String] = []
|
|
var defines: [String] = []
|
|
var includePaths: [String] = []
|
|
var configurationUncertain = true
|
|
|
|
static func load(project: CMOCProject, toolchain: URL, configurationName: String,
|
|
overlays: [String: String], generated: [String: Data]) throws -> Self {
|
|
var result = Self(), total = 0
|
|
func issue(_ message: String) { if result.issues.count < 16 { result.issues.append(message) } }
|
|
func accept(_ text: String, path: String) {
|
|
guard !text.contains("\0"), text.utf8.count <= CMOCProject.maximumSourceBytes else {
|
|
issue("Skipped oversized or non-text file: \(path)"); return
|
|
}
|
|
let oldSize = result.documents[path]?.utf8.count ?? 0
|
|
guard (result.documents[path] != nil || result.documents.count < maximumFiles),
|
|
total - oldSize + text.utf8.count <= maximumBytes else {
|
|
issue("Index limited to \(maximumFiles) files and 16 MB of text."); return
|
|
}
|
|
total += text.utf8.count - oldSize; result.documents[path] = text
|
|
}
|
|
// An edited configuration is a browsing hint only, never a build command.
|
|
var configuration = project.configuration
|
|
if let text = overlays[CMOCProject.configurationFilename] ?? (try? project.readText(relativePath: CMOCProject.configurationFilename)) {
|
|
do { configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data(text.utf8)).validated() }
|
|
catch { issue("Project settings contain errors; using the last accepted browsing settings.") }
|
|
}
|
|
let generatedOutputs = Set(configuration.makefileSettings?.generatedResources.flatMap(\.outputs) ?? [])
|
|
let root = try CMOCProject.physicalURL(project.directory)
|
|
var readError: Error?
|
|
let keys: Set<URLResourceKey> = [.isRegularFileKey, .isSymbolicLinkKey, .isDirectoryKey, .fileSizeKey]
|
|
let excluded: Set<String> = [".git", ".svn", ".build", ".vccplus-build", ".DS_Store"]
|
|
guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: Array(keys),
|
|
errorHandler: { _, error in readError = error; return false }) else {
|
|
throw CMOCBuildError.message("The project could not be read for navigation.")
|
|
}
|
|
var urls: [(String, URL)] = []
|
|
var visited = 0
|
|
while let url = enumerator.nextObject() as? URL {
|
|
try Task.checkCancellation(); visited += 1
|
|
guard visited <= 20_000 else { issue("Project navigation stopped after 20,000 entries."); break }
|
|
if excluded.contains(url.lastPathComponent) { enumerator.skipDescendants(); continue }
|
|
let path = String(url.path.dropFirst(root.path.count + 1))
|
|
if path.hasPrefix(libraryPrefix) { enumerator.skipDescendants(); issue("Reserved library-reference path omitted from project: \(path)"); continue }
|
|
let values = try url.resourceValues(forKeys: keys)
|
|
if values.isSymbolicLink == true { enumerator.skipDescendants(); issue("Linked file or folder omitted: \(path)"); continue }
|
|
if values.isDirectory == true { continue }
|
|
guard values.isRegularFile == true, CMOCProject.isEditable(path), !generatedOutputs.contains(path) else { continue }
|
|
guard let size = values.fileSize, size <= CMOCProject.maximumSourceBytes else { issue("Oversized text file omitted: \(path)"); continue }
|
|
urls.append((path, url))
|
|
}
|
|
if let readError { issue("Some project files could not be read: " + readError.localizedDescription) }
|
|
for (path, _) in urls.sorted(by: { $0.0 < $1.0 }) {
|
|
try Task.checkCancellation()
|
|
if let overlay = overlays[path] { accept(overlay, path: path); continue }
|
|
do { accept(try project.readText(relativePath: path), path: path) }
|
|
catch { issue("Unreadable text file omitted: \(path)") }
|
|
if result.documents.count >= maximumFiles || total >= maximumBytes { issue("Project text limit reached; some files are not indexed."); break }
|
|
}
|
|
for (path, text) in overlays.sorted(by: { $0.key < $1.key }) {
|
|
try Task.checkCancellation()
|
|
guard !path.hasPrefix(libraryPrefix), CMOCProject.isEditable(path) else { continue }
|
|
_ = try project.fileURL(relativePath: path)
|
|
accept(text, path: path)
|
|
}
|
|
for (path, data) in generated.sorted(by: { $0.key < $1.key }) where result.documents[path] == nil && ["c", "h"].contains((path as NSString).pathExtension.lowercased()) {
|
|
try Task.checkCancellation()
|
|
try CMOCProject.validateRelativePath(path)
|
|
guard data.count <= CMOCProject.maximumSourceBytes, let text = String(data: data, encoding: .utf8) else { continue }
|
|
accept(text, path: path); if result.documents[path] != nil { result.generatedPaths.insert(path) }
|
|
}
|
|
if !result.generatedPaths.isEmpty { issue("Generated sources are read-only snapshots from the last successful build.") }
|
|
|
|
if let recipe = configuration.makefileSettings {
|
|
result.includePaths = recipe.includePaths
|
|
result.defines = recipe.defines
|
|
// Trust flags only when the current Makefile exactly matches the
|
|
// generated recipe, and selected Make assignments cannot alter it.
|
|
let expected = try? recipe.generateMakefile(makefileName: configuration.makefile)
|
|
let current = result.documents[configuration.makefile]
|
|
let assignments = configuration.configurations.first(where: { $0.name == configurationName })?.makeArguments ?? []
|
|
result.configurationUncertain = expected == nil || current != expected || assignments.contains { !$0.hasPrefix("VCC_CONFIGURATION=") }
|
|
var coco = true, unsignedChar = false, noRelocate = false
|
|
var floatingPointMacro: String?
|
|
var undefined: Set<String> = []
|
|
for option in recipe.compilerOptions {
|
|
if option.hasPrefix("-D"), option.count > 2 { result.defines.append(String(option.dropFirst(2))) }
|
|
else if option.hasPrefix("-I"), option.count > 2 {
|
|
let path = String(option.dropFirst(2))
|
|
if (try? project.fileURL(relativePath: path)) != nil { result.includePaths.append(path) }
|
|
else { issue("External include path is not browsed: \(path)"); result.configurationUncertain = true }
|
|
} else if option == "-funsigned-char" { unsignedChar = true }
|
|
else if option == "-fsigned-char" { unsignedChar = false }
|
|
else if option == "--native-float" { floatingPointMacro = "_CMOC_NATIVE_FLOAT_=1" }
|
|
else if option == "--mc6839" { floatingPointMacro = "_CMOC_MC6839_=1" }
|
|
else if option == "--no-relocate" { noRelocate = true }
|
|
else if option.hasPrefix("-U"), option.count > 2 { undefined.insert(String(option.dropFirst(2))); result.configurationUncertain = true }
|
|
else if option == "--coco" { coco = true }
|
|
else if ["--os9", "--vectrex", "--dragon", "--usim", "--thommo", "--void-target"].contains(option) { coco = false; result.configurationUncertain = true }
|
|
else if !["-O0", "-O1", "-O2", "-fno-omit-frame-pointer", "--intermediate", "--deps"].contains(option) { result.configurationUncertain = true }
|
|
}
|
|
// CMOC resolves mode switches in argument order, then emits its
|
|
// builtin definitions before all user -D arguments. Preserve that
|
|
// order so explicit user values can override a builtin value.
|
|
var builtins: [String] = []
|
|
if coco { builtins.append("_COCO_BASIC_=1") }
|
|
if unsignedChar { builtins.append("_CMOC_unsigned_char_=1") }
|
|
if noRelocate { builtins.append("_CMOC_NO_RELOCATE_=1") }
|
|
if let floatingPointMacro { builtins.append(floatingPointMacro) }
|
|
result.defines.insert(contentsOf: builtins, at: 0)
|
|
result.defines.removeAll { undefined.contains(String($0.prefix { $0 != "=" })) }
|
|
}
|
|
if result.configurationUncertain { issue("Custom Make flags are not evaluated; conditional definitions are browsing candidates, not compiler-verified bindings.") }
|
|
if let data = try? Data(contentsOf: toolchain.appendingPathComponent("manifest.json")),
|
|
let manifest = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let version = manifest["cmoc"] as? String {
|
|
let components = version.split(separator: ".").compactMap { Int($0) }
|
|
if components.count == 3 { result.defines.insert("_CMOC_VERSION_=\(components[0] * 1000000 + components[1] * 1000 + components[2])", at: 0) }
|
|
}
|
|
let undefined = Set((configuration.makefileSettings?.compilerOptions ?? []).filter { $0.hasPrefix("-U") && $0.count > 2 }.map { String($0.dropFirst(2)) })
|
|
result.defines.removeAll { undefined.contains(String($0.prefix { $0 != "=" })) }
|
|
let requestedHeaders = toolchain.appendingPathComponent("share/cmoc/include")
|
|
if (try? requestedHeaders.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true {
|
|
issue("Linked library include folder is not browsed."); return result
|
|
}
|
|
guard let headers = try? CMOCProject.physicalURL(requestedHeaders) else {
|
|
issue("Bundled library headers are unavailable; project navigation remains available."); return result
|
|
}
|
|
let compatibility = configuration.makefileSettings?.libraries.contains("vcccompat") == true ||
|
|
configuration.bundledLibraries.contains { $0.library == "vcccompat" }
|
|
if compatibility { result.includePaths.append("@toolchain/include/vcc/compat") }
|
|
result.includePaths.append("@toolchain/include")
|
|
if let libraryFiles = FileManager.default.enumerator(at: headers, includingPropertiesForKeys: Array(keys), errorHandler: { _, _ in false }) {
|
|
var count = 0
|
|
while let url = libraryFiles.nextObject() as? URL {
|
|
try Task.checkCancellation(); count += 1
|
|
guard count <= 4096 else { issue("Library header scan reached its limit."); break }
|
|
let values = try url.resourceValues(forKeys: keys)
|
|
if values.isSymbolicLink == true { libraryFiles.skipDescendants(); continue }
|
|
if !compatibility, url == headers.appendingPathComponent("vcc/compat", isDirectory: true) {
|
|
libraryFiles.skipDescendants(); continue
|
|
}
|
|
guard values.isRegularFile == true, url.pathExtension.lowercased() == "h" else { continue }
|
|
let path = libraryPrefix + String(url.path.dropFirst(headers.path.count + 1))
|
|
guard (values.fileSize ?? Int.max) <= CMOCProject.maximumSourceBytes,
|
|
let text = try? CMOCProject.readText(url, maximumBytes: CMOCProject.maximumSourceBytes) else { issue("Library header omitted: \(path)"); continue }
|
|
accept(text, path: path)
|
|
if result.documents[path] != nil { result.referencePaths.insert(path) }
|
|
}
|
|
} else { issue("Bundled library headers are unavailable; project navigation remains available.") }
|
|
return result
|
|
}
|
|
}
|