Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 79 additions & 59 deletions Sources/SWBCore/Dependencies.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import SWBMacro
public struct ModuleDependency: Hashable, Sendable, SerializableCodable {
public let name: String
public let accessLevel: AccessLevel
public let optional: Bool

public enum AccessLevel: String, Hashable, Sendable, CaseIterable, Codable, Serializable, Comparable {
case Private = "private"
Expand Down Expand Up @@ -43,29 +44,25 @@ public struct ModuleDependency: Hashable, Sendable, SerializableCodable {
}
}

public init(name: String, accessLevel: AccessLevel) {
public init(name: String, accessLevel: AccessLevel, optional: Bool) {
self.name = name
self.accessLevel = accessLevel
self.optional = optional
}

public init(entry: String) throws {
var it = entry.split(separator: " ").makeIterator()
switch (it.next(), it.next(), it.next()) {
case (let .some(name), nil, nil):
self.name = String(name)
self.accessLevel = .Private

case (let .some(accessLevel), let .some(name), nil):
self.name = String(name)
self.accessLevel = try AccessLevel(String(accessLevel))

default:
throw StubError.error("expected 1 or 2 space-separated components in: \(entry)")
let re = #/((?<accessLevel>private|package|public)\s+)?(?<name>\w+)(?<optional>\?)?/#
guard let match = entry.wholeMatch(of: re) else {
throw StubError.error("Invalid module dependency format: \(entry), expected [private|package|public] <name>[?]")
}

self.name = String(match.output.name)
self.accessLevel = try match.output.accessLevel.map { try AccessLevel(String($0)) } ?? .Private
self.optional = match.output.optional != nil
}

public var asBuildSettingEntry: String {
"\(accessLevel == .Private ? "" : "\(accessLevel.rawValue) ")\(name)"
"\(accessLevel == .Private ? "" : "\(accessLevel.rawValue) ")\(name)\(optional ? "?" : "")"
}

public var asBuildSettingEntryQuotedIfNeeded: String {
Expand All @@ -76,35 +73,39 @@ public struct ModuleDependency: Hashable, Sendable, SerializableCodable {

public struct ModuleDependenciesContext: Sendable, SerializableCodable {
public var validate: BooleanWarningLevel
public var validateUnused: BooleanWarningLevel
var moduleDependencies: [ModuleDependency]
var fixItContext: FixItContext?

init(validate: BooleanWarningLevel, moduleDependencies: [ModuleDependency], fixItContext: FixItContext? = nil) {
init(validate: BooleanWarningLevel, validateUnused: BooleanWarningLevel, moduleDependencies: [ModuleDependency], fixItContext: FixItContext? = nil) {
self.validate = validate
self.validateUnused = validateUnused
self.moduleDependencies = moduleDependencies
self.fixItContext = fixItContext
}

public init?(settings: Settings) {
let validate = settings.globalScope.evaluate(BuiltinMacros.VALIDATE_MODULE_DEPENDENCIES)
guard validate != .no else { return nil }
let validateUnused = settings.globalScope.evaluate(BuiltinMacros.VALIDATE_UNUSED_MODULE_DEPENDENCIES)
guard validate != .no || validateUnused != .no else { return nil }
let downgrade = settings.globalScope.evaluate(BuiltinMacros.VALIDATE_DEPENDENCIES_DOWNGRADE_ERRORS)
let fixItContext = ModuleDependenciesContext.FixItContext(settings: settings)
self.init(validate: downgrade ? .yes : validate, moduleDependencies: settings.moduleDependencies, fixItContext: fixItContext)
let fixItContext = validate != .no ? ModuleDependenciesContext.FixItContext(settings: settings) : nil
self.init(validate: downgrade ? .yes : validate, validateUnused: validateUnused, moduleDependencies: settings.moduleDependencies, fixItContext: fixItContext)
}

public func makeUnsupportedToolchainDiagnostic() -> Diagnostic {
Diagnostic(
behavior: .warning,
location: .unknown,
data: DiagnosticData("The current toolchain does not support \(BuiltinMacros.VALIDATE_MODULE_DEPENDENCIES.name)"))
}

/// Compute missing module dependencies.
///
/// If `imports` is nil, the current toolchain does not support the features to gather imports.
public func computeMissingDependencies(
imports: [(ModuleDependency, importLocations: [Diagnostic.Location])]?,
imports: [(ModuleDependency, importLocations: [Diagnostic.Location])],
fromSwift: Bool
) -> [(ModuleDependency, importLocations: [Diagnostic.Location])]? {
) -> [(ModuleDependency, importLocations: [Diagnostic.Location])] {
guard validate != .no else { return [] }
guard let imports else {
return nil
}

return imports.filter {
// ignore module deps without source locations, these are inserted by swift / swift-build and we should treat them as implementation details which we can track without needing the user to declare them
if fromSwift && $0.importLocations.isEmpty { return false }
Expand All @@ -115,45 +116,63 @@ public struct ModuleDependenciesContext: Sendable, SerializableCodable {
}
}

/// Make diagnostics for missing module dependencies.
public func makeDiagnostics(missingDependencies: [(ModuleDependency, importLocations: [Diagnostic.Location])]?) -> [Diagnostic] {
guard let missingDependencies else {
return [Diagnostic(
behavior: .warning,
location: .unknown,
data: DiagnosticData("The current toolchain does not support \(BuiltinMacros.VALIDATE_MODULE_DEPENDENCIES.name)"))]
}

guard !missingDependencies.isEmpty else { return [] }
public func computeUnusedDependencies(usedModuleNames: Set<String>) -> [ModuleDependency] {
guard validateUnused != .no else { return [] }
return moduleDependencies.filter { !$0.optional && !usedModuleNames.contains($0.name) }
}

let behavior: Diagnostic.Behavior = validate == .yesError ? .error : .warning
/// Make diagnostics for missing module dependencies.
public func makeDiagnostics(missingDependencies: [(ModuleDependency, importLocations: [Diagnostic.Location])], unusedDependencies: [ModuleDependency]) -> [Diagnostic] {
let missingDiagnostics: [Diagnostic]
if !missingDependencies.isEmpty {
let behavior: Diagnostic.Behavior = validate == .yesError ? .error : .warning

let fixIt = fixItContext?.makeFixIt(newModules: missingDependencies.map { $0.0 })
let fixIts = fixIt.map { [$0] } ?? []

let importDiags: [Diagnostic] = missingDependencies
.flatMap { dep in
dep.1.map {
return Diagnostic(
behavior: behavior,
location: $0,
data: DiagnosticData("Missing entry in \(BuiltinMacros.MODULE_DEPENDENCIES.name): \(dep.0.asBuildSettingEntryQuotedIfNeeded)"),
fixIts: fixIts)
}
}

let fixIt = fixItContext?.makeFixIt(newModules: missingDependencies.map { $0.0 })
let fixIts = fixIt.map { [$0] } ?? []
let message = "Missing entries in \(BuiltinMacros.MODULE_DEPENDENCIES.name): \(missingDependencies.map { $0.0.asBuildSettingEntryQuotedIfNeeded }.sorted().joined(separator: " "))"

let importDiags: [Diagnostic] = missingDependencies
.flatMap { dep in
dep.1.map {
return Diagnostic(
behavior: behavior,
location: $0,
data: DiagnosticData("Missing entry in \(BuiltinMacros.MODULE_DEPENDENCIES.name): \(dep.0.asBuildSettingEntryQuotedIfNeeded)"),
fixIts: fixIts)
}
}
let location: Diagnostic.Location = fixIt.map {
Diagnostic.Location.path($0.sourceRange.path, line: $0.sourceRange.endLine, column: $0.sourceRange.endColumn)
} ?? Diagnostic.Location.buildSetting(BuiltinMacros.MODULE_DEPENDENCIES)

let message = "Missing entries in \(BuiltinMacros.MODULE_DEPENDENCIES.name): \(missingDependencies.map { $0.0.asBuildSettingEntryQuotedIfNeeded }.sorted().joined(separator: " "))"
missingDiagnostics = [Diagnostic(
behavior: behavior,
location: location,
data: DiagnosticData(message),
fixIts: fixIts,
childDiagnostics: importDiags)]
}
else {
missingDiagnostics = []
}

let location: Diagnostic.Location = fixIt.map {
Diagnostic.Location.path($0.sourceRange.path, line: $0.sourceRange.endLine, column: $0.sourceRange.endColumn)
} ?? Diagnostic.Location.buildSetting(BuiltinMacros.MODULE_DEPENDENCIES)
let unusedDiagnostics: [Diagnostic]
if !unusedDependencies.isEmpty {
let message = "Unused entries in \(BuiltinMacros.MODULE_DEPENDENCIES.name): \(unusedDependencies.map { $0.name }.sorted().joined(separator: " "))"
// TODO location & fixit
unusedDiagnostics = [Diagnostic(
behavior: validateUnused == .yesError ? .error : .warning,
location: .unknown,
data: DiagnosticData(message),
fixIts: [])]
}
else {
unusedDiagnostics = []
}

return [Diagnostic(
behavior: behavior,
location: location,
data: DiagnosticData(message),
fixIts: fixIts,
childDiagnostics: importDiags)]
return missingDiagnostics + unusedDiagnostics
}

struct FixItContext: Sendable, SerializableCodable {
Expand All @@ -169,6 +188,7 @@ public struct ModuleDependenciesContext: Sendable, SerializableCodable {
guard let target = settings.target else { return nil }
let thisTargetCondition = MacroCondition(parameter: BuiltinMacros.targetNameCondition, valuePattern: target.name)

// TODO: if you have an assignment in a project-xcconfig and another assignment in target-settings, this would find the project-xcconfig assignment, but updating that might have no effect depending on the target-settings assignment
if let assignment = (settings.globalScope.table.lookupMacro(BuiltinMacros.MODULE_DEPENDENCIES)?.sequence.first {
$0.location != nil && ($0.conditions?.conditions == [thisTargetCondition] || ($0.conditions?.conditions.isEmpty ?? true))
}),
Expand Down
1 change: 1 addition & 0 deletions Sources/SWBCore/LibSwiftDriver/LibSwiftDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -891,5 +891,6 @@ extension ModuleDependency {
init(_ importInfo: ImportInfo) {
self.name = importInfo.importIdentifier
self.accessLevel = .init(importInfo.accessLevel)
self.optional = false
}
}
2 changes: 2 additions & 0 deletions Sources/SWBCore/Settings/BuiltinMacros.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,7 @@ public final class BuiltinMacros {
public static let VALIDATE_DEVELOPMENT_ASSET_PATHS = BuiltinMacros.declareEnumMacro("VALIDATE_DEVELOPMENT_ASSET_PATHS") as EnumMacroDeclaration<BooleanWarningLevel>
public static let VALIDATE_HEADER_DEPENDENCIES = BuiltinMacros.declareEnumMacro("VALIDATE_HEADER_DEPENDENCIES") as EnumMacroDeclaration<BooleanWarningLevel>
public static let VALIDATE_MODULE_DEPENDENCIES = BuiltinMacros.declareEnumMacro("VALIDATE_MODULE_DEPENDENCIES") as EnumMacroDeclaration<BooleanWarningLevel>
public static let VALIDATE_UNUSED_MODULE_DEPENDENCIES = BuiltinMacros.declareEnumMacro("VALIDATE_UNUSED_MODULE_DEPENDENCIES") as EnumMacroDeclaration<BooleanWarningLevel>
public static let VECTOR_SUFFIX = BuiltinMacros.declareStringMacro("VECTOR_SUFFIX")
public static let VERBOSE_PBXCP = BuiltinMacros.declareBooleanMacro("VERBOSE_PBXCP")
public static let VERSIONING_STUB = BuiltinMacros.declareStringMacro("VERSIONING_STUB")
Expand Down Expand Up @@ -2382,6 +2383,7 @@ public final class BuiltinMacros {
VALIDATE_DEVELOPMENT_ASSET_PATHS,
VALIDATE_HEADER_DEPENDENCIES,
VALIDATE_MODULE_DEPENDENCIES,
VALIDATE_UNUSED_MODULE_DEPENDENCIES,
VALID_ARCHS,
VECTOR_SUFFIX,
VERBOSE_PBXCP,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ public final class ClangCompileTaskAction: TaskAction, BuildValueValidatingTaskA
includeFiles.append(file)
}
}
let moduleDependencies = moduleNames.map { ModuleDependency(name: $0, accessLevel: .Private) }
let moduleDependencies = moduleNames.map { ModuleDependency(name: $0, accessLevel: .Private, optional: false) }
let moduleImports = moduleDependencies.map { DependencyValidationInfo.Import(dependency: $0, importLocations: []) }
return (moduleImports, includeFiles)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,32 +66,34 @@ public final class ValidateDependenciesTaskAction: TaskAction {

if let moduleContext = payload.moduleDependenciesContext {
if unsupported {
diagnostics.append(contentsOf: moduleContext.makeDiagnostics(missingDependencies: nil))
diagnostics.append(moduleContext.makeUnsupportedToolchainDiagnostic())
} else {
let clangMissingDeps = moduleContext.computeMissingDependencies(imports: allClangImports.map { ($0.dependency, $0.importLocations) }, fromSwift: false)
let swiftMissingDeps = moduleContext.computeMissingDependencies(imports: allSwiftImports.map { ($0.dependency, $0.importLocations) }, fromSwift: true)

// Update Swift dependencies with information from Clang dependencies on the same module.
var clangMissingDepsByName = [String: (ModuleDependency, importLocations: [Diagnostic.Location])]()
clangMissingDeps?.forEach {
clangMissingDeps.forEach {
clangMissingDepsByName[$0.0.name] = $0
}
let updatedSwiftMissingDeps: [(ModuleDependency, importLocations: [Diagnostic.Location])] = swiftMissingDeps?.map {
let updatedSwiftMissingDeps: [(ModuleDependency, importLocations: [Diagnostic.Location])] = swiftMissingDeps.map {
if let clangMissingDep = clangMissingDepsByName[$0.0.name] {
return (
ModuleDependency(name: $0.0.name, accessLevel: max($0.0.accessLevel, clangMissingDep.0.accessLevel)),
ModuleDependency(name: $0.0.name, accessLevel: max($0.0.accessLevel, clangMissingDep.0.accessLevel), optional: $0.0.optional),
$0.importLocations + clangMissingDep.importLocations
)
} else {
return $0
}
} ?? []
}

// Filter missing C dependencies by known Swift dependencies to avoid duplicate diagnostics.
let swiftImports = Set(allSwiftImports.map { $0.dependency.name })
let uniqueClangMissingDeps = clangMissingDeps?.filter { !swiftImports.contains($0.0.name) } ?? []
let uniqueClangMissingDeps = clangMissingDeps.filter { !swiftImports.contains($0.0.name) }

let unusedDeps = moduleContext.computeUnusedDependencies(usedModuleNames: Set(allClangImports.map { $0.dependency.name } + allSwiftImports.map { $0.dependency.name }))

diagnostics.append(contentsOf: moduleContext.makeDiagnostics(missingDependencies: uniqueClangMissingDeps + updatedSwiftMissingDeps))
diagnostics.append(contentsOf: moduleContext.makeDiagnostics(missingDependencies: uniqueClangMissingDeps + updatedSwiftMissingDeps, unusedDependencies: unusedDeps))
}
}
if let headerContext = payload.headerDependenciesContext {
Expand Down
Loading
Loading