This commit is contained in:
Isaac 2025-12-06 01:28:06 +08:00
parent 1969b1b280
commit 1ee7268488
72 changed files with 1645 additions and 934 deletions

View file

@ -46,6 +46,8 @@ class ProjectGenerator {
"CLANG_CXX_LANGUAGE_STANDARD": "c++17",
"CLANG_ENABLE_MODULES": "YES",
"CLANG_ENABLE_OBJC_ARC": "YES",
"CLANG_ENABLE_EXPLICIT_MODULES": "NO", // Disable explicit module builds for ObjC-Swift interop
"SWIFT_ENABLE_EXPLICIT_MODULES": "NO", // Disable explicit module builds for Swift
"ENABLE_STRICT_OBJC_MSGSEND": "YES",
"GCC_NO_COMMON_BLOCKS": "YES",
"IPHONEOS_DEPLOYMENT_TARGET": "13.0",

View file

@ -21,7 +21,9 @@ class SymlinkManager {
guard path.exists else { return }
do {
for item in try path.children() {
if item.lastComponent == ".build" { continue }
let name = item.lastComponent
// Skip build artifacts and xcodeproj bundles
if name == ".build" || name.hasSuffix(".xcodeproj") { continue }
previousFiles.insert(item)
if item.isDirectory && !item.isSymlink {
scanDirectory(item)

View file

@ -20,15 +20,48 @@ class TargetBuilder {
self.symlinkManager = symlinkManager
}
// Track which modules are header-only (have no linkable code)
private var headerOnlyModules: Set<String> = []
// Track which modules are static library collections (.a files)
private var staticLibraryModules: [String: [String]] = [:] // module name -> list of .a file paths
func isHeaderOnlyModule(_ name: String) -> Bool {
return headerOnlyModules.contains(name)
}
func isStaticLibraryModule(_ name: String) -> Bool {
return staticLibraryModules[name] != nil
}
func getStaticLibraries(for name: String) -> [String] {
return staticLibraryModules[name] ?? []
}
func buildTarget(for module: ModuleDefinition, allModules: [String: ModuleDefinition]) throws -> PBXNativeTarget? {
guard let moduleType = ModuleType(from: module) else {
print("Warning: Unknown module type \(module.type) for \(module.name)")
return nil
}
// Skip empty modules
let sourceFiles = module.sources.filter { !$0.hasSuffix(".a") }
if sourceFiles.isEmpty && moduleType != .xcframework {
// Check for static library modules (only .a files)
let staticLibs = module.sources.filter { $0.hasSuffix(".a") }
let nonStaticLibs = module.sources.filter { !$0.hasSuffix(".a") }
let isStaticLibOnly = !staticLibs.isEmpty && nonStaticLibs.allSatisfy { $0.hasSuffix(".h") || $0.hasSuffix(".hpp") }
if isStaticLibOnly && moduleType != .xcframework {
// This is a static library module - track its .a files but don't create a framework
staticLibraryModules[module.name] = staticLibs
return nil // Don't create a target, just track the static libs
}
// Check if module is header-only (only header files, no real sources)
let sourceFiles = module.sources.filter { source in
!source.hasSuffix(".a") && !source.hasSuffix(".h") && !source.hasSuffix(".hpp")
}
let isHeaderOnly = sourceFiles.isEmpty && moduleType != .xcframework
// Skip modules with no sources at all
if module.sources.isEmpty && moduleType != .xcframework {
return nil
}
@ -36,7 +69,12 @@ class TargetBuilder {
case .xcframework:
return try buildXCFrameworkTarget(for: module)
case .swiftLibrary, .objcLibrary, .ccLibrary:
return try buildFrameworkTarget(for: module, moduleType: moduleType)
if isHeaderOnly {
headerOnlyModules.insert(module.name)
return try buildHeaderOnlyFrameworkTarget(for: module)
} else {
return try buildFrameworkTarget(for: module, moduleType: moduleType)
}
}
}
@ -61,7 +99,13 @@ class TargetBuilder {
// Create symlinks and file references
var sourceRefs: [PBXFileReference] = []
var headerRefs: [PBXFileReference] = []
var publicHeaderRefs: [PBXFileReference] = []
var seenPublicHeaderNames: Set<String> = [] // Track header filenames to avoid duplicates in headers build phase
// Determine public header detection:
// 1. If hdrs is provided, use those (explicit public headers)
// 2. Otherwise, headers in includes directories are public
let explicitPublicHeaders = Set(module.hdrs ?? [])
let allSourceFiles = module.sources + (module.hdrs ?? []) + (module.textualHdrs ?? [])
@ -99,11 +143,33 @@ class TargetBuilder {
fileName: fileName
)
if source.hasSuffix(".h") || source.hasSuffix(".hpp") {
headerRefs.append(fileRef)
} else if !source.hasSuffix(".inc") {
let isHeader = source.hasSuffix(".h") || source.hasSuffix(".hpp")
// Determine if this is a public header:
// 1. Explicitly in hdrs array
// 2. Located in an includes directory
let isPublicHeader: Bool
if !isHeader {
isPublicHeader = false
} else if !explicitPublicHeaders.isEmpty {
// If hdrs is provided, only those are public
isPublicHeader = explicitPublicHeaders.contains(source)
} else {
// Headers in include directories are public (handles bazel-out paths)
isPublicHeader = isInIncludesDirectory(source: source, modulePath: module.path, includes: module.includes)
}
if isPublicHeader {
// Skip duplicate header filenames to avoid "multiple commands produce" errors
if !seenPublicHeaderNames.contains(fileName) {
seenPublicHeaderNames.insert(fileName)
publicHeaderRefs.append(fileRef)
}
} else if !source.hasSuffix(".inc") && !isHeader {
// Source files (not headers)
sourceRefs.append(fileRef)
}
// Private headers are not added to any build phase
}
// Build phases
@ -120,17 +186,23 @@ class TargetBuilder {
pbxproj.add(object: sourcesBuildPhase)
buildPhases.append(sourcesBuildPhase)
// Headers build phase for ObjC/C++
// Generate modulemap for ObjC/C++ modules (SPM-style explicit headers)
var modulemapPath: Path? = nil
if moduleType == .objcLibrary || moduleType == .ccLibrary {
let headersBuildPhase = PBXHeadersBuildPhase(
files: headerRefs.map { ref in
let buildFile = PBXBuildFile(file: ref, settings: ["ATTRIBUTES": ["Public"]])
pbxproj.add(object: buildFile)
return buildFile
}
)
pbxproj.add(object: headersBuildPhase)
buildPhases.append(headersBuildPhase)
modulemapPath = try generateModulemap(for: module)
// Headers build phase with public headers - needed for ObjC #import to work
if !publicHeaderRefs.isEmpty {
let headersBuildPhase = PBXHeadersBuildPhase(
files: publicHeaderRefs.map { ref in
let buildFile = PBXBuildFile(file: ref, settings: ["ATTRIBUTES": ["Public"]])
pbxproj.add(object: buildFile)
return buildFile
}
)
pbxproj.add(object: headersBuildPhase)
buildPhases.append(headersBuildPhase)
}
}
// Frameworks build phase
@ -138,8 +210,8 @@ class TargetBuilder {
pbxproj.add(object: frameworksBuildPhase)
buildPhases.append(frameworksBuildPhase)
// Create target
let configList = createConfigurationList(for: module, isXCFramework: false)
// Create target with custom modulemap if generated
let configList = createConfigurationList(for: module, isXCFramework: false, modulemapPath: modulemapPath)
let target = PBXNativeTarget(
name: module.name,
@ -155,6 +227,110 @@ class TargetBuilder {
return target
}
/// Build a framework target for header-only modules (just headers + modulemap, no sources)
private func buildHeaderOnlyFrameworkTarget(for module: ModuleDefinition) throws -> PBXNativeTarget {
// Create group for module
let moduleGroup = try getOrCreateGroup(for: module.path)
// Symlink header files and create file references
var publicHeaderRefs: [PBXFileReference] = []
var seenPublicHeaderNames: Set<String> = [] // Track header filenames to avoid duplicates
let allHeaders = module.sources.filter { $0.hasSuffix(".h") || $0.hasSuffix(".hpp") } + (module.hdrs ?? []) + (module.textualHdrs ?? [])
for source in allHeaders {
let sourcePath = Path(source)
let fileName = sourcePath.lastComponent
let relativeToModule = relativePathInModule(source: source, modulePath: module.path)
// Create parent group
let parentPath = (Path(module.path) + Path(relativeToModule).parent()).string
let parentGroup = try getOrCreateGroup(for: parentPath)
// Create symlink
let symlinkPath = outputDir + module.path + relativeToModule
try symlinkManager.createDirectory(symlinkPath.parent())
try symlinkManager.createSymlink(from: Path(source), to: symlinkPath)
// Create file reference
let fileType = lastKnownFileType(for: fileName)
let fileRef = PBXFileReference(
sourceTree: .group,
name: fileName,
lastKnownFileType: fileType,
path: fileName
)
pbxproj.add(object: fileRef)
parentGroup.children.append(fileRef)
// Check if it's a public header (in includes directories)
// Use helper that properly handles bazel-out paths
let isPublic = isInIncludesDirectory(source: source, modulePath: module.path, includes: module.includes)
if isPublic {
// Skip duplicate header filenames to avoid "multiple commands produce" errors
if !seenPublicHeaderNames.contains(fileName) {
seenPublicHeaderNames.insert(fileName)
publicHeaderRefs.append(fileRef)
}
}
}
// Generate modulemap for this header-only module
let modulemapPath = try generateModulemap(for: module)
// Create build phases
var buildPhases: [PBXBuildPhase] = []
// Headers build phase with public headers - needed for ObjC #import to work
if !publicHeaderRefs.isEmpty {
let headersBuildPhase = PBXHeadersBuildPhase(
files: publicHeaderRefs.map { ref in
let buildFile = PBXBuildFile(file: ref, settings: ["ATTRIBUTES": ["Public"]])
pbxproj.add(object: buildFile)
return buildFile
}
)
pbxproj.add(object: headersBuildPhase)
buildPhases.append(headersBuildPhase)
}
// Empty frameworks phase (needed for Xcode, but won't link anything)
let frameworksBuildPhase = PBXFrameworksBuildPhase(files: [])
pbxproj.add(object: frameworksBuildPhase)
buildPhases.append(frameworksBuildPhase)
// Create target with custom modulemap
let configList = createConfigurationList(for: module, isXCFramework: false, modulemapPath: modulemapPath)
let target = PBXNativeTarget(
name: module.name,
buildConfigurationList: configList,
buildPhases: buildPhases,
productName: module.name,
productType: .framework
)
pbxproj.add(object: target)
project.targets.append(target)
targetsByName[module.name] = target
return target
}
/// Collect all transitive dependencies for a module
private func collectAllDependencies(for moduleName: String, modules: [String: ModuleDefinition], visited: inout Set<String>) -> Set<String> {
guard !visited.contains(moduleName) else { return [] }
visited.insert(moduleName)
guard let module = modules[moduleName], let deps = module.deps else {
return []
}
var allDeps = Set(deps)
for depName in deps {
allDeps.formUnion(collectAllDependencies(for: depName, modules: modules, visited: &visited))
}
return allDeps
}
func wireUpDependencies(modules: [String: ModuleDefinition]) throws {
for (name, module) in modules {
guard let target = targetsByName[name],
@ -165,13 +341,88 @@ class TargetBuilder {
continue
}
for depName in deps {
guard let depTarget = targetsByName[depName] else { continue }
// Track all frameworks we've added to avoid duplicates
var linkedFrameworks: Set<String> = []
// Add target dependency
let dependency = PBXTargetDependency(target: depTarget)
pbxproj.add(object: dependency)
target.dependencies.append(dependency)
// Add target dependency (only for direct deps)
for depName in deps {
if let depTarget = targetsByName[depName] {
let dependency = PBXTargetDependency(target: depTarget)
pbxproj.add(object: dependency)
target.dependencies.append(dependency)
}
}
// Collect all transitive dependencies to link
var visited = Set<String>()
let allDeps = collectAllDependencies(for: name, modules: modules, visited: &visited)
// Collect header paths from ALL dependencies (direct and transitive)
var depHeaderPaths: [String] = []
for depName in allDeps {
if let depModule = modules[depName] {
depHeaderPaths.append(contentsOf: exportedHeaderPaths(for: depModule))
}
}
// Link all dependencies (direct and transitive) that have targets
for depName in allDeps {
// Skip if already linked
guard !linkedFrameworks.contains(depName) else { continue }
// Check if this is a static library module - link .a files directly
if isStaticLibraryModule(depName) {
// Link static libraries directly
for libPath in getStaticLibraries(for: depName) {
let libName = Path(libPath).lastComponent
// Use absolute path to the static library in bazel-out
let absolutePath = "$(SRCROOT)/../\(libPath)"
let libRef = PBXFileReference(
sourceTree: .group,
name: libName,
lastKnownFileType: "archive.ar",
path: absolutePath
)
pbxproj.add(object: libRef)
let buildFile = PBXBuildFile(file: libRef)
pbxproj.add(object: buildFile)
frameworksPhase.files?.append(buildFile)
}
linkedFrameworks.insert(depName)
continue
}
// Skip header-only modules (no framework to link)
if isHeaderOnlyModule(depName) { continue }
// Regular framework dependency
guard targetsByName[depName] != nil else { continue }
linkedFrameworks.insert(depName)
let frameworkRef = PBXFileReference(
sourceTree: .buildProductsDir,
name: "\(depName).framework",
lastKnownFileType: "wrapper.framework",
path: "\(depName).framework"
)
pbxproj.add(object: frameworkRef)
let buildFile = PBXBuildFile(file: frameworkRef)
pbxproj.add(object: buildFile)
frameworksPhase.files?.append(buildFile)
}
// Update build configurations with dependency paths
if !depHeaderPaths.isEmpty || !deps.isEmpty {
for config in target.buildConfigurationList?.buildConfigurations ?? [] {
// Add header search paths
if !depHeaderPaths.isEmpty {
let existing = config.buildSettings["HEADER_SEARCH_PATHS"] as? String ?? "$(inherited)"
config.buildSettings["HEADER_SEARCH_PATHS"] = existing + " " + depHeaderPaths.joined(separator: " ")
}
// Ensure framework and module search paths include built products
config.buildSettings["FRAMEWORK_SEARCH_PATHS"] = "$(inherited) $(BUILT_PRODUCTS_DIR)"
config.buildSettings["SWIFT_INCLUDE_PATHS"] = "$(inherited) $(BUILT_PRODUCTS_DIR)"
}
}
// Add SDK frameworks
@ -192,13 +443,32 @@ class TargetBuilder {
}
}
/// Returns the header search paths that this module exports to its dependents
private func exportedHeaderPaths(for module: ModuleDefinition) -> [String] {
var paths: [String] = []
if let includes = module.includes, !includes.isEmpty {
for inc in includes {
if inc == "." {
paths.append("$(SRCROOT)/\(module.path)")
} else {
paths.append("$(SRCROOT)/\(module.path)/\(inc)")
}
}
} else {
// No includes specified, export module's own path
paths.append("$(SRCROOT)/\(module.path)")
}
return paths
}
func getTarget(named name: String) -> PBXNativeTarget? {
return targetsByName[name]
}
private func createConfigurationList(for module: ModuleDefinition, isXCFramework: Bool) -> XCConfigurationList {
let debugSettings = createBuildSettings(for: module, isDebug: true, isXCFramework: isXCFramework)
let releaseSettings = createBuildSettings(for: module, isDebug: false, isXCFramework: isXCFramework)
private func createConfigurationList(for module: ModuleDefinition, isXCFramework: Bool, modulemapPath: Path? = nil) -> XCConfigurationList {
let debugSettings = createBuildSettings(for: module, isDebug: true, isXCFramework: isXCFramework, modulemapPath: modulemapPath)
let releaseSettings = createBuildSettings(for: module, isDebug: false, isXCFramework: isXCFramework, modulemapPath: modulemapPath)
let debugConfig = XCBuildConfiguration(name: "Debug", buildSettings: debugSettings)
let releaseConfig = XCBuildConfiguration(name: "Release", buildSettings: releaseSettings)
@ -215,7 +485,7 @@ class TargetBuilder {
return configList
}
private func createBuildSettings(for module: ModuleDefinition, isDebug: Bool, isXCFramework: Bool) -> BuildSettings {
private func createBuildSettings(for module: ModuleDefinition, isDebug: Bool, isXCFramework: Bool, modulemapPath: Path? = nil) -> BuildSettings {
var settings: BuildSettings = [
"PRODUCT_NAME": "$(TARGET_NAME)",
"PRODUCT_BUNDLE_IDENTIFIER": "org.telegram.\(module.name)",
@ -229,6 +499,7 @@ class TargetBuilder {
// Swift settings
if moduleType == .swiftLibrary {
settings["SWIFT_VERSION"] = "5.0"
settings["DEFINES_MODULE"] = "YES"
if let copts = module.copts, !copts.isEmpty {
let filtered = copts.filter { !$0.hasPrefix("-warnings") }
@ -244,12 +515,14 @@ class TargetBuilder {
// C/ObjC settings
if moduleType == .objcLibrary || moduleType == .ccLibrary {
// Always suppress deprecated warnings (e.g., OSSpinLock) and don't treat warnings as errors
var cflags = ["-Wno-deprecated-declarations"]
if let copts = module.copts, !copts.isEmpty {
let filtered = copts.filter { !$0.hasPrefix("-warnings") && !$0.hasPrefix("-W") }
if !filtered.isEmpty {
settings["OTHER_CFLAGS"] = "$(inherited) " + filtered.joined(separator: " ")
}
cflags.append(contentsOf: filtered)
}
settings["OTHER_CFLAGS"] = "$(inherited) " + cflags.joined(separator: " ")
settings["GCC_TREAT_WARNINGS_AS_ERRORS"] = "NO"
if let cxxopts = module.cxxopts, !cxxopts.isEmpty {
let filtered = cxxopts.filter { !$0.hasPrefix("-std=") }
@ -262,15 +535,22 @@ class TargetBuilder {
settings["GCC_PREPROCESSOR_DEFINITIONS"] = "$(inherited) " + defines.joined(separator: " ")
}
if let includes = module.includes, !includes.isEmpty {
let paths = includes.map { inc -> String in
if inc == "." {
return "$(SRCROOT)/\(module.path)"
}
return "$(SRCROOT)/\(module.path)/\(inc)"
// Always include module's own path for header search
var headerPaths = ["$(SRCROOT)/\(module.path)"]
if let includes = module.includes {
for inc in includes where inc != "." {
headerPaths.append("$(SRCROOT)/\(module.path)/\(inc)")
}
settings["HEADER_SEARCH_PATHS"] = "$(inherited) " + paths.joined(separator: " ")
}
settings["HEADER_SEARCH_PATHS"] = "$(inherited) " + headerPaths.joined(separator: " ")
// Use custom modulemap if provided (SPM-style)
if let modmap = modulemapPath {
// Get relative path from SRCROOT
let relativePath = modmap.string.replacingOccurrences(of: outputDir.string + "/", with: "")
settings["MODULEMAP_FILE"] = "$(SRCROOT)/\(relativePath)"
}
settings["DEFINES_MODULE"] = "YES"
}
return settings
@ -352,4 +632,110 @@ class TargetBuilder {
default: return "text"
}
}
/// Extract the relative path within a module from a source path
/// Handles both regular paths (submodules/Foo/...) and bazel-out paths (bazel-out/.../bin/submodules/Foo/...)
private func relativePathInModule(source: String, modulePath: String) -> String {
if source.hasPrefix(modulePath + "/") {
return String(source.dropFirst(modulePath.count + 1))
} else if source.hasPrefix("bazel-out/") {
// Generated file - extract path after the module path portion
if let range = source.range(of: modulePath + "/") {
return String(source[range.upperBound...])
} else {
return Path(source).lastComponent
}
} else {
return Path(source).lastComponent
}
}
/// Check if a source file is in one of the includes directories
private func isInIncludesDirectory(source: String, modulePath: String, includes: [String]?) -> Bool {
guard let includes = includes, !includes.isEmpty else {
return false
}
let relative = relativePathInModule(source: source, modulePath: modulePath)
return includes.contains { inc in
if inc == "." {
return true // All files in module are public
} else {
return relative.hasPrefix(inc + "/") || relative == inc
}
}
}
/// Generates an explicit module.modulemap for ObjC/C++ modules (SPM-style)
/// Returns the path to the modulemap, or nil if no public headers
func generateModulemap(for module: ModuleDefinition) throws -> Path? {
let moduleType = ModuleType(from: module)
guard moduleType == .objcLibrary || moduleType == .ccLibrary else {
return nil
}
// Determine public header prefix from includes
let publicHeaderPrefix: String
if let includes = module.includes, !includes.isEmpty {
let firstInclude = includes[0]
publicHeaderPrefix = firstInclude == "." ? "" : firstInclude
} else {
publicHeaderPrefix = ""
}
// Determine public headers
let explicitPublicHeaders = Set(module.hdrs ?? [])
let allFiles = module.sources + (module.hdrs ?? []) + (module.textualHdrs ?? [])
let allHeaders = allFiles.filter { $0.hasSuffix(".h") || $0.hasSuffix(".hpp") }
// Determine which headers are public
let publicHeaders: [String]
if !explicitPublicHeaders.isEmpty {
publicHeaders = allHeaders.filter { explicitPublicHeaders.contains($0) }
} else if module.includes != nil && !module.includes!.isEmpty {
// Use helper that properly handles bazel-out paths
publicHeaders = allHeaders.filter { header in
isInIncludesDirectory(source: header, modulePath: module.path, includes: module.includes)
}
} else {
publicHeaders = []
}
guard !publicHeaders.isEmpty else {
return nil
}
// Generate explicit modulemap content (SPM-style)
var content = "// module.modulemap for \(module.name)\n"
content += "// Auto-generated - do not edit\n\n"
content += "module \(module.name) {\n"
for header in publicHeaders {
// Calculate the symlinked path - matches the symlink creation in buildFrameworkTarget
// The symlink is at: outputDir + module.path + relativeToModule
let relativeToModule = relativePathInModule(source: header, modulePath: module.path)
let symlinkPath = outputDir + module.path + relativeToModule
content += " header \"\(symlinkPath.string)\"\n"
}
content += " export *\n"
content += "}\n"
// Write modulemap to the public headers directory
let modulemapDir: Path
if !publicHeaderPrefix.isEmpty {
modulemapDir = outputDir + module.path + publicHeaderPrefix
} else {
modulemapDir = outputDir + module.path
}
let modulemapPath = modulemapDir + "module.modulemap"
try modulemapDir.mkpath()
try modulemapPath.write(content)
// Track this file so it doesn't get cleaned up
symlinkManager.markFile(modulemapPath)
return modulemapPath
}
}