Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
27 changes: 0 additions & 27 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,30 +74,3 @@ jobs:
swift-configuration: ${{ matrix.config }}
run-tests: false
build-tests: false

# windows:
# name: Windows
# runs-on: windows-latest
# steps:
# - uses: compnerd/gha-setup-swift@main
# with:
# branch: swift-5.10-release
# tag: 5.10-RELEASE
#
# - uses: actions/checkout@v4
# - name: Run tests
# run: swift test
# - name: Run tests (release)
# run: swift test -c release

check-macro-compatibility:
name: Check Macro Compatibility
runs-on: macos-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run Swift Macro Compatibility Check
uses: Matejkob/swift-macro-compatibility-check@v1
with:
run-tests: false
major-versions-only: true
2 changes: 1 addition & 1 deletion Package@swift-6.0.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ let package = Package(
.package(url: "https://github.com/pointfreeco/swift-clocks", from: "1.0.4"),
.package(url: "https://github.com/pointfreeco/swift-concurrency-extras", from: "1.0.0"),
.package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.4.0"),
.package(url: "https://github.com/swiftlang/swift-syntax", "509.0.0"..<"603.0.0"),
.package(url: "https://github.com/swiftlang/swift-syntax", "600.0.0"..<"603.0.0"),
],
targets: [
.target(
Expand Down
39 changes: 39 additions & 0 deletions Sources/DependenciesMacros/Macros.swift
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,45 @@ public macro DependencyEndpoint(method: String = "") =
public macro DependencyEndpointIgnored() =
#externalMacro(module: "DependenciesMacrosPlugin", type: "DependencyEndpointIgnoredMacro")

/// Creates a dependency values entry.
///
/// Use this macro to register a custom dependency on ``DependencyValues`` without having to declare
/// a separate ``DependencyKey`` conformance:
///
/// ```swift
/// extension DependencyValues {
/// @DependencyEntry var apiClient: any APIClient = MockAPIClient()
/// }
/// ```
///
/// The macro will synthesize a private key type behind the scenes and generate the property's
/// `get`/`set` accessors. The initializer is used as the ``TestDependencyKey/testValue``. To
/// provide a live implementation:
///
/// ```swift
/// extension DependencyValues {
/// @DependencyEntry(liveValue: LiveAPIClient())
/// var apiClient: any APIClient = MockAPIClient()
/// }
/// ```
///
/// - Parameters:
/// - liveValue: A live value.
/// - previewValue: A preview value.
@attached(accessor, names: named(get), named(set))
@attached(peer, names: prefixed(__Key_))
public macro DependencyEntry<LiveValue, PreviewValue>(
liveValue: LiveValue = (),
previewValue: PreviewValue = ()
) = #externalMacro(module: "DependenciesMacrosPlugin", type: "DependencyEntryMacro")

@attached(accessor, names: named(get))
public macro _DependencyEntryDefaultValue() =

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defining this in DependenciesMacros for now, but we could probably flatten these modules soon.

#externalMacro(
module: "DependenciesMacrosPlugin",
type: "DependencyEntryDefaultValueMacro"
)

/// The error thrown by "unimplemented" closures produced by ``DependencyEndpoint(method:)``
public struct Unimplemented: Error {
let endpoint: String
Expand Down
173 changes: 173 additions & 0 deletions Sources/DependenciesMacrosPlugin/DependencyEntryMacro.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import SwiftDiagnostics
public import SwiftSyntax
import SwiftSyntaxBuilder
public import SwiftSyntaxMacros

public enum DependencyEntryMacro {}

extension DependencyEntryMacro: AccessorMacro {
public static func expansion(
of node: AttributeSyntax,
providingAccessorsOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [AccessorDeclSyntax] {
guard
isInDependencyValuesExtension(context: context),
let property = declaration.as(VariableDeclSyntax.self),
property.bindingSpecifier.tokenKind == .keyword(.var),
let identifier = property.bindings.first?.pattern
.as(IdentifierPatternSyntax.self)?.identifier.trimmed
else {
return []
}
let keyName: TokenSyntax = "__Key_\(identifier)"
return [
"""
get { self[\(keyName).self] }
""",
"""
set { self[\(keyName).self] = newValue }
""",
]
}
}

extension DependencyEntryMacro: PeerMacro {
public static func expansion(
of node: AttributeSyntax,
providingPeersOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard
let property = declaration.as(VariableDeclSyntax.self),
property.bindingSpecifier.tokenKind == .keyword(.var),
isInDependencyValuesExtension(context: context)
else {
context.diagnose(
Diagnostic(
node: node,
message: MacroExpansionErrorMessage(
"""
'@DependencyEntry' macro can only attach to 'var' declarations inside extensions of \
'DependencyValues'
"""
)
)
)
return []
}

guard
let binding = property.bindings.first,
let identifier = binding.pattern.as(IdentifierPatternSyntax.self)?.identifier.trimmed
else {
return []
}

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
}
}
}

let testValueExpr: ExprSyntax? = binding.initializer?.value
if testValueExpr == nil, liveValueExpr == nil {
context.diagnose(
Diagnostic(
node: declaration,
message: MacroExpansionErrorMessage(
"""
'@DependencyEntry' requires an initializer to define the property's test value, or a \
'liveValue' argument to fall back on
"""
)
)
)
return []
}

let conformance = liveValueExpr != nil ? "DependencyKey" : "TestDependencyKey"
let keyName: TokenSyntax = "__Key_\(identifier)"

var members: [String] = []
if let typeAnnotation = binding.typeAnnotation?.type.trimmed {
members.append("typealias Value = \(typeAnnotation)")
if let liveValueExpr {
members.append("static var liveValue: Value { \(liveValueExpr) }")
}
if let previewValueExpr {
members.append("static var previewValue: Value { \(previewValueExpr) }")
}
if let testValueExpr {
members.append("static var testValue: Value { \(testValueExpr) }")
}
} else {
let attribute = "@DependenciesMacros._DependencyEntryDefaultValue"
if let liveValueExpr {
members.append("\(attribute) static var liveValue = \(liveValueExpr)")
}
if let previewValueExpr {
members.append("\(attribute) static var previewValue = \(previewValueExpr)")
}
if let testValueExpr {
members.append("\(attribute) static var testValue = \(testValueExpr)")
}
}

let body = members.joined(separator: "\n")
let keyDecl: DeclSyntax = """
private enum \(keyName): Dependencies.\(raw: conformance) {
\(raw: body)
}
"""
return [keyDecl]
}
}

private func isInDependencyValuesExtension(
context: some MacroExpansionContext
) -> Bool {
guard
let extensionDecl = context.lexicalContext.first?.as(ExtensionDeclSyntax.self)
else {
return false
}
let extendedType = extensionDecl.extendedType
let name: String?
if let identifier = extendedType.as(IdentifierTypeSyntax.self) {
name = identifier.name.text
} else if let member = extendedType.as(MemberTypeSyntax.self) {
name = member.name.text
} else {
name = nil
}
return name == "DependencyValues"
}

public enum DependencyEntryDefaultValueMacro {}

extension DependencyEntryDefaultValueMacro: AccessorMacro {
public static func expansion(
of node: AttributeSyntax,
providingAccessorsOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [AccessorDeclSyntax] {
guard
let property = declaration.as(VariableDeclSyntax.self),
let binding = property.bindings.first,
let initializer = binding.initializer?.value
else {
return []
}
return ["get { \(initializer) }"]
}
}
2 changes: 2 additions & 0 deletions Sources/DependenciesMacrosPlugin/Plugins.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ struct MacrosPlugin: CompilerPlugin {
DependencyClientMacro.self,
DependencyEndpointMacro.self,
DependencyEndpointIgnoredMacro.self,
DependencyEntryMacro.self,
DependencyEntryDefaultValueMacro.self,
]
}
Loading
Loading