Skip to content
Open
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
70 changes: 70 additions & 0 deletions Sources/DependenciesMacros/Macros.swift
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,76 @@ public macro _DependencyEntryDefaultValue() =
type: "DependencyEntryDefaultValueMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro IsolationCheck(_: () -> Void) =
#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyEntryIsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro IsolationCheck(_: @MainActor () -> Void) =
#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyEntryMainActorIsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro IsolationCheck<Root, Value: Sendable>(keyPath: KeyPath<Root, Value>) =
#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyEntryIsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro IsolationCheck<Root, Value>(keyPath: KeyPath<Root, Value>) =
#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyEntrySendableCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro IsolationCheck(client: () -> Void) =
#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyEntryIsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro IsolationCheck(client: @MainActor () -> Void) =
#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyClientMainActorCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro TypeCheck<Root, Value>(
_: KeyPath<Root, Value>,
liveValue: @autoclosure @MainActor () -> Value
) =
#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyEntryIsolationCheckMacro"
)

@_documentation(visibility: private)
@freestanding(declaration)
public macro TypeCheck<Root, Value>(
_: KeyPath<Root, Value>,
previewValue: @autoclosure @MainActor () -> Value
) =
#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyEntryIsolationCheckMacro"
)

/// The error thrown by "unimplemented" closures produced by ``DependencyEndpoint(method:)``
public struct Unimplemented: Error {
let endpoint: String
Expand Down
42 changes: 36 additions & 6 deletions Sources/DependenciesMacrosPlugin/DependencyClientMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -231,18 +231,48 @@ public enum DependencyClientMacro: MemberAttributeMacro, MemberMacro {
guard hasEndpoints else { return [] }
let access = accesses.min().flatMap { $0.token?.with(\.trailingTrivia, .space) }
// TODO: Don't define initializers if any single endpoint is invalid
return [properties, properties.filter { !$0.isEndpoint }].map {
$0.isEmpty
? "\(access)init() {}"
return [(properties, isolationCheck(for: node, in: context)), (properties.filter { !$0.isEndpoint }, "")].map {
(properties, check) in
properties.isEmpty
? """
\(access)init() {\(raw: check)}
"""
: """
\(access)init(
\(raw: $0.map { $0.declaration.bindings.trimmedDescription }.joined(separator: ",\n"))
) {
\(raw: $0.map { "self.\($0.identifier) = \($0.identifier)" }.joined(separator: "\n"))
\(raw: properties.map { $0.declaration.bindings.trimmedDescription }.joined(separator: ",\n"))
) {\(raw: check)
\(raw: properties.map { "self.\($0.identifier) = \($0.identifier)" }.joined(separator: "\n"))
}
"""
}
}

private static func isolationCheck(
for node: AttributeSyntax,
in context: some MacroExpansionContext
) -> String {
let probeName = "__dependencyClientIsolationProbe"
guard
let location = context.location(of: node, at: .afterLeadingTrivia, filePathMode: .filePath)
else {
return """

#if DEBUG
func \(probeName)() {}
#IsolationCheck(client: \(probeName))
#endif
"""
}
return """

#if DEBUG
func \(probeName)() {}
#sourceLocation(file: \(location.file), line: \(location.line))
#IsolationCheck(client: \(probeName))
#sourceLocation()
#endif
"""
}
}

private enum Access: Comparable {
Expand Down
172 changes: 170 additions & 2 deletions Sources/DependenciesMacrosPlugin/DependencyEntryMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ extension DependencyEntryMacro: AccessorMacro {
let keyName = keyTypeName(for: node, property: property, identifier: identifier)
return [
"""
get { self[\(keyName).self] }
get {
\(entryChecks(for: node, identifier: identifier, in: context))
return self[\(keyName).self]
}
""",
"""
set { self[\(keyName).self] = newValue }
Expand Down Expand Up @@ -136,7 +139,7 @@ extension DependencyEntryMacro: PeerMacro {
\(raw: body)
}
"""
return [keyDecl]
return sendableCheck(for: node, identifier: identifier, in: context) + [keyDecl]
}
}

Expand Down Expand Up @@ -258,6 +261,171 @@ private func isInDependencyValuesExtension(
return name == "DependencyValues"
}

private let isolationProbeName = "__dependencyEntryIsolationProbe"

private func entryValueArguments(
from node: AttributeSyntax
) -> (liveValue: ExprSyntax?, previewValue: ExprSyntax?) {
var liveValueExpr: ExprSyntax?
var previewValueExpr: ExprSyntax?
if let arguments = node.arguments?.as(LabeledExprListSyntax.self) {
for argument in arguments {
switch argument.label?.text {
case "liveValue":
liveValueExpr = argument.expression
case "previewValue":
previewValueExpr = argument.expression
default:
break
}
}
}
return (liveValueExpr, previewValueExpr)
}

private func extendedType(in context: some MacroExpansionContext) -> TypeSyntax? {
context.lexicalContext.first?.as(ExtensionDeclSyntax.self)?.extendedType.trimmed
}

private func entryChecks(
for node: AttributeSyntax,
identifier: TokenSyntax,
in context: some MacroExpansionContext
) -> CodeBlockItemListSyntax {
var checks = ["#IsolationCheck(\(isolationProbeName))"]
if let extendedType = extendedType(in: context) {
let (liveValueExpr, previewValueExpr) = entryValueArguments(from: node)
if let liveValueExpr {
checks.append(
"#TypeCheck(\\\(extendedType).\(identifier), liveValue: \(liveValueExpr.trimmed))"
)
}
if let previewValueExpr {
checks.append(
"#TypeCheck(\\\(extendedType).\(identifier), previewValue: \(previewValueExpr.trimmed))"
)
}
}
guard
let location = context.location(of: node, at: .afterLeadingTrivia, filePathMode: .filePath)
else {
return """
#if DEBUG
func \(raw: isolationProbeName)() {}
\(raw: checks.joined(separator: "\n"))
#endif
"""
}
let directive = "#sourceLocation(file: \(location.file), line: \(location.line))"
return """
#if DEBUG
func \(raw: isolationProbeName)() {}
\(raw: checks.map { "\(directive)\n\($0)" }.joined(separator: "\n"))
#sourceLocation()
#endif
"""
}

private func sendableCheck(
for node: AttributeSyntax,
identifier: TokenSyntax,
in context: some MacroExpansionContext
) -> [DeclSyntax] {
guard let extendedType = extendedType(in: context)
else {
return []
}
let check = "#IsolationCheck(keyPath: \\\(extendedType).\(identifier))"
guard
let location = context.location(of: node, at: .afterLeadingTrivia, filePathMode: .filePath)
else {
return [
"""
#if DEBUG
\(raw: check)
#endif
"""
]
}
return [
"""
#if DEBUG
#sourceLocation(file: \(location.file), line: \(location.line))
\(raw: check)
#sourceLocation()
#endif
"""
]
}

public enum DependencyEntryIsolationCheckMacro {}

extension DependencyEntryIsolationCheckMacro: DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
[]
}
}

public enum DependencyEntryMainActorIsolationCheckMacro {}

extension DependencyEntryMainActorIsolationCheckMacro: DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
context.diagnose(
Diagnostic(
node: node,
message: MacroExpansionErrorMessage(
"entry must be 'nonisolated var' when default isolation is '@MainActor'"
)
)
)
return []
}
}

public enum DependencyClientMainActorCheckMacro {}

extension DependencyClientMainActorCheckMacro: DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
context.diagnose(
Diagnostic(
node: node,
message: MacroExpansionErrorMessage(
"client must be 'nonisolated struct' when default isolation is '@MainActor'"
)
)
)
return []
}
}

public enum DependencyEntrySendableCheckMacro {}

extension DependencyEntrySendableCheckMacro: DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
context.diagnose(
Diagnostic(
node: node,
message: MacroExpansionErrorMessage(
"entry value must be 'Sendable'"
)
)
)
return []
}
}

public enum DependencyEntryDefaultValueMacro {}

extension DependencyEntryDefaultValueMacro: AccessorMacro {
Expand Down
4 changes: 4 additions & 0 deletions Sources/DependenciesMacrosPlugin/Plugins.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@ struct MacrosPlugin: CompilerPlugin {
DependencyEndpointIgnoredMacro.self,
DependencyEntryMacro.self,
DependencyEntryDefaultValueMacro.self,
DependencyEntryIsolationCheckMacro.self,
DependencyEntryMainActorIsolationCheckMacro.self,
DependencyEntrySendableCheckMacro.self,
DependencyClientMainActorCheckMacro.self,
]
}
Loading
Loading