// SPDX-License-Identifier: GPL-3.0-or-later import Foundation enum AssemblyCPU: String, CaseIterable, Codable, Sendable { case mc6809 = "6809" case hd6309 = "6309" } struct AssemblyProjectSnapshot: Equatable, Sendable { static let configurationFilename = "vccplus-assembly.json" struct Settings: Codable, Equatable, Sendable { var main: String? var modules: [String]? var linkScript: String? var makefile: String? var target: String? var binary: String? } let mainPath: String let files: [String: Data] let cpu: AssemblyCPU let settings: Settings static func single(source: String, path: String = "main.asm", cpu: AssemblyCPU = .mc6809) -> Self { Self(mainPath: path, files: [path: Data(source.utf8)], cpu: cpu, settings: Settings()) } static func read(directory: URL, mainPath: String = "main.asm", overlays: [String: String] = [:], cpu: AssemblyCPU = .mc6809) throws -> Self { var files = try CMOCProject.files(in: directory) for (path, text) in overlays { try CMOCProject.validateRelativePath(path) files[path] = try CMOCProject.sourceBytes(text) } let settings = try files[configurationFilename].map { try JSONDecoder().decode(Settings.self, from: $0) } ?? Settings() let entry = settings.main ?? mainPath if let binary = settings.binary { files.removeValue(forKey: binary) } let snapshot = Self(mainPath: entry, files: files, cpu: cpu, settings: settings) try snapshot.validate() return snapshot } /// A loose source may live in Documents or Downloads. Only follow its literal /// include chain; never enumerate or copy unrelated neighboring files. static func readSource(at url: URL, overlays: [String: String] = [:], cpu: AssemblyCPU = .mc6809) throws -> Self { let root = try CMOCProject.physicalURL(url.deletingLastPathComponent()).standardizedFileURL let main = url.lastPathComponent var files: [String: Data] = [:], scanned = Set(), total = 0 var pending = [(path: main, binary: false)] let directive = try NSRegularExpression(pattern: #"(?i)^(?:[^\s*;]+\s+|\s+)(include|incl|use|lib|includebin)\s+(?:"([^"]+)"|'([^']+)'|([^\s,;]+))"#) while let input = pending.popLast() { try Task.checkCancellation() try CMOCProject.validateRelativePath(input.path) let file = root.appendingPathComponent(input.path) if files[input.path] == nil { let data: Data if let overlay = overlays[input.path] { data = try CMOCProject.sourceBytes(overlay) } else { guard file.standardizedFileURL.path == file.resolvingSymlinksInPath().standardizedFileURL.path else { throw AssemblyBuildFailure("Copy linked inputs into the source folder before assembling.") } guard FileManager.default.fileExists(atPath: file.path) || input.path == main else { continue } data = try DevelopmentBuildTools.readFile(file, limit: CMOCProject.maximumFileBytes) } total += data.count guard total <= CMOCProject.maximumProjectBytes, files.count < 20_000 else { throw AssemblyBuildFailure("The included source files exceed the project snapshot limit.") } files[input.path] = data } guard !input.binary, scanned.insert(input.path).inserted, let data = files[input.path] else { continue } guard data.count <= CMOCProject.maximumSourceBytes, let source = String(data: data, encoding: .utf8) else { throw AssemblyBuildFailure("Choose UTF-8 source files of at most 1 MB.") } for line in source.components(separatedBy: .newlines) { let ns = line as NSString guard let match = directive.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)), let index = (2...4).first(where: { match.range(at: $0).location != NSNotFound }) else { continue } let operand = ns.substring(with: match.range(at: index)) let included = file.deletingLastPathComponent().appendingPathComponent(operand).standardizedFileURL guard !operand.hasPrefix("/"), included.path.hasPrefix(root.path + "/") else { throw AssemblyBuildFailure("Keep assembly includes inside the source folder: " + operand) } var relative = String(included.path.dropFirst(root.path.count + 1)) // Match LWASM's search order: the including file's folder first, // then the root supplied by -I. A buffer may exist before saving. if overlays[relative] == nil && !FileManager.default.fileExists(atPath: included.path) { let fallback = root.appendingPathComponent(operand).standardizedFileURL if fallback.path.hasPrefix(root.path + "/") { relative = String(fallback.path.dropFirst(root.path.count + 1)) } } pending.append((relative, ns.substring(with: match.range(at: 1)).lowercased() == "includebin")) } } let snapshot = Self(mainPath: main, files: files, cpu: cpu, settings: Settings()) try snapshot.validate() return snapshot } func validate() throws { let modules = [mainPath] + (settings.modules ?? []) guard modules.count <= 128, Set(modules).count == modules.count else { throw AssemblyBuildFailure("Use up to 128 distinct assembly modules.") } for path in files.keys { try CMOCProject.validateRelativePath(path) } for path in modules + [settings.makefile, settings.linkScript].compactMap({ $0 }) { try CMOCProject.validateRelativePath(path) guard files[path] != nil else { throw AssemblyBuildFailure("The project is missing " + path) } } for module in modules { guard let data = files[module], data.count <= CMOCProject.maximumSourceBytes, !data.contains(0), String(data: data, encoding: .utf8) != nil else { throw AssemblyBuildFailure("Choose UTF-8 assembly modules of at most 1 MB without NUL characters.") } } if let makefile = settings.makefile { guard settings.modules == nil, settings.linkScript == nil, let binary = settings.binary, binary.lowercased().hasSuffix(".bin"), ![mainPath, makefile].contains(binary) else { throw AssemblyBuildFailure("For custom Make, set makefile, target and binary. Use modules and linkScript for native linked builds.") } try CMOCProject.validateRelativePath(binary) try CMOCProjectConfiguration.validateTarget(settings.target ?? "all") } else if settings.binary != nil || settings.target != nil { throw AssemblyBuildFailure("A custom binary path or target requires a Makefile.") } if !(settings.modules ?? []).isEmpty, settings.linkScript == nil { throw AssemblyBuildFailure("Set linkScript to a project-relative LWLINK script with a load address and entry.") } } }