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
4 changes: 4 additions & 0 deletions .github/workflows/swift-benchmark-delta.yml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ jobs:
if: ${{ success() || failure() }}
run: |
#/usr/bin/ordo-performance powersave
# Repositories without benchmarks have nothing to compare.
if [ "${{ env.hasBenchmark }}" != "1" ]; then
exit 0
fi
# Treat improvement (4) and same-as-baseline (0) as success
if [ "${{ env.exitStatus }}" = "0" ] || [ "${{ env.exitStatus }}" = "4" ]; then
exit 0
Expand Down
23 changes: 14 additions & 9 deletions .github/workflows/swift-code-coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,20 @@ jobs:

- name: Export code coverage
run: |
xctest_binary=".build/debug/${{ github.event.repository.name }}PackageTests.xctest"
if [ ! -f ${xctest_binary} ]; then
xctest_binary=$(find .build/debug/ -type f -name "*.xctest" | tail -1)
echo "Will llvm-cov '${xctest_binary}'"
fi

if [ -f ${xctest_binary} ]; then
llvm-cov export -format="lcov" ${xctest_binary} -instr-profile .build/debug/codecov/default.profdata > info.lcov
fi
coverage_json=$(swift test --show-codecov-path)
coverage_dir=$(dirname "${coverage_json}")
products_dir=$(dirname "${coverage_dir}")
test_binary=$(find "${products_dir}" -maxdepth 4 -type f -perm -111 \
\( -name "*.xctest" -o -name "*Tests" -o -name "*Tests-test-runner" \) \
-print -quit)
profdata="${coverage_dir}/default.profdata"
if [ -z "${test_binary}" ] || [ ! -f "${profdata}" ]; then
echo "Unable to locate the test binary or coverage profile"
exit 1
fi
echo "Will llvm-cov '${test_binary}'"
llvm-cov export -format="lcov" "${test_binary}" \
-instr-profile "${profdata}" > info.lcov

- name: Upload codecov
uses: codecov/codecov-action@v5
Expand Down
1 change: 1 addition & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ let package = Package(
.testTarget(
name: "EquatableTests",
dependencies: [
"Equatable",
"EquatableMacros",
.product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax")
]
Expand Down
97 changes: 95 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Ideal for teams scaling SwiftUI in large apps.

## Overview

The `@Equatable` macro generates an `Equatable` implementation that compares all of the struct's stored instance properties, excluding properties with SwiftUI property wrappers like @State and @Environment that trigger view updates through other mechanisms. Properties that aren't `Equatable` and don't affect the output of the view body can be marked with `@EquatableIgnored` to exclude them from the generated implementation. Closures are not permitted by default but can be marked with `@EquatableIgnoredUnsafeClosure` to indicate that they are safe to exclude from equality checks.
The `@Equatable` macro generates an `Equatable` implementation that compares all of a struct's stored instance properties. Properties with SwiftUI property wrappers like @State and @Environment are excluded because they trigger view updates through other mechanisms. Properties that aren't `Equatable` and don't affect the output of the view body can be marked with `@EquatableIgnored` to exclude them from the generated implementation. Closures are not permitted by default but can be marked with `@EquatableIgnoredUnsafeClosure` to indicate that they are safe to exclude from equality checks.

## Installation

Expand Down Expand Up @@ -78,7 +78,100 @@ extension ProfileView: Equatable {
}
```

## Isolation
## Property-level comparison strategies

Use `@EquatableCompared` to select how an instance stored property participates in equality.
It works with stored properties in `@Equatable` structs, including properties with `willSet` or `didSet` observers.
Other properties retain their normal comparison behavior and ordering.

### Compare a projected value

A key path lets a property participate even when its type does not conform to `Equatable`:

```swift
final class Document {
let identifier: Int
let title: String

init(identifier: Int, title: String) {
self.identifier = identifier
self.title = title
}
}

@Equatable
struct DocumentState: Hashable {
@EquatableCompared(by: \Document.identifier)
var document: Document
}
```

Two `DocumentState` values compare equal when their document identifiers match, even if they
contain different document instances or titles. Hashing also uses the identifier.

Provide a key-path literal with its root type, such as `\Document.identifier`; the marker cannot
infer the root of `\.identifier` from the property it annotates. Nested paths and optional
chaining are supported, such as `\Container.document?.identifier`. An optional property needs
a key path rooted in that optional type, or a strategy that explicitly accepts an optional value.

### Compare reference identity

```swift
final class Coordinator {}

@Equatable
struct ScreenState: Hashable {
@EquatableCompared(.identity)
var coordinator: Coordinator?
}
```

Identity uses `===`: two references to the same object compare equal, and distinct objects
compare unequal even if their contents match. Optional references are supported, with two nil
values comparing equal. Hashing uses the object's `ObjectIdentifier`, or the nil representation.
Identity comparison requires a class reference; value types are rejected by the compiler.

### Reuse a normalization strategy

```swift
enum LowercasedString: EquatableComparisonStrategy {
static func comparisonValue(for value: String) -> String {
value.lowercased()
}
}

@Equatable
struct Category: Hashable {
@EquatableCompared(using: LowercasedString.self)
var name: String
}
```

`Category(name: "BOOKS")` equals `Category(name: "books")`, and both use the same normalized
value for hashing. Strategy types can be generic or namespaced. Pass an explicit metatype,
such as `LowercasedString.self`, rather than a variable holding a metatype.

A strategy implements `EquatableComparisonStrategy`, whose `Value` is the property input and
whose `ComparisonValue: Equatable` is the comparison representation. Swift can infer both
associated types from `comparisonValue(for:)`. A strategy can accept optional inputs and
normalize nil explicitly.

### Requirements and semantics

- Projected values only need `Equatable` for equality. If the containing type uses generated
hashing, the projected value must also conform to `Hashable`; the compiler enforces this.
- Projections must be deterministic and free of side effects. They run when a comparison or
hash is requested and obey the selected isolation mode. Equality still short-circuits.
- Projections read current values; they do not snapshot mutable object state. Identity does
not detect mutations within an existing object. Comparison keys must remain stable while
a value is stored in a `Set` or used as a dictionary key.
- Each property can have one comparison marker. Combining it with `@EquatableIgnored`,
`@EquatableIgnoredUnsafeClosure`, or an automatically skipped SwiftUI wrapper produces an error.
- Comparison markers require an enclosing `@Equatable` struct.
Computed properties, static/class properties, closures, and multi-property declarations
are unsupported. Write a separate declaration for each annotated property.

## Isolation
`Equatable` macro supports generating the conformance with different isolation levels by using the `isolation` parameter.
The parameter accepts three values: `.nonisolated` (default), `.isolated`, and `.main` (requires Swift 6.2 or later).
The chosen isolation level will be applied to the generated conformances for both `Equatable` and `Hashable` (if applicable).
Expand Down
58 changes: 58 additions & 0 deletions Sources/Equatable/EquatableCompared.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/// The built-in comparison modes for an `@EquatableCompared` property.
public enum EquatableComparison {
/// Compare class references using `===`, including optional references.
/// Changes inside the same object do not affect its identity.
case identity
}

/// Produces the representation used to compare a property and, when applicable, hash it.
///
/// Implementations must be deterministic, free of side effects, and accessible from
/// the isolation context selected by `@Equatable`. The representation must also
/// conform to `Hashable` when the containing type uses generated hashing.
public protocol EquatableComparisonStrategy {
/// The type of property accepted by the strategy.
associatedtype Value

/// The equatable representation produced for comparison and hashing.
associatedtype ComparisonValue: Equatable

/// Produces the representation used to compare a property value.
///
/// - Parameter value: The property's current value.
/// - Returns: A deterministic representation of `value`.
static func comparisonValue(for value: Value) -> ComparisonValue
}

/// Compares and hashes a property through a key path rooted in the property's type.
///
/// For example, `@EquatableCompared(by: \Document.identifier)` compares the identifier
/// even when `Document` itself is not `Equatable`. Use an explicit root type. Optional
/// chaining follows Swift's normal key-path rules; optional properties require an
/// optional-root key path or a strategy accepting an optional input.
///
/// The selected value must be `Hashable` if the containing type uses generated hashing.
/// The key path is evaluated at comparison time, not captured as a snapshot.
@attached(peer)
public macro EquatableCompared<Root, ComparedValue: Equatable>(by keyPath: KeyPath<Root, ComparedValue>) =
#externalMacro(module: "EquatableMacros", type: "EquatableComparedMacro")

/// Compares a class reference by identity and hashes its `ObjectIdentifier`.
///
/// Supports optional references: two nil values compare equal. Value types are not
/// supported. Use on an instance stored property inside an `@Equatable` type.
@attached(peer)
public macro EquatableCompared(_ comparison: EquatableComparison) =
#externalMacro(module: "EquatableMacros", type: "EquatableComparedMacro")

/// Compares and hashes the representation produced by a reusable strategy.
///
/// For example, `@EquatableCompared(using: LowercasedString.self)` can normalize a
/// string before comparison. The strategy's input must accept the property, and its
/// output must be `Hashable` if the containing type uses generated hashing.
///
/// Comparison markers cannot be combined with exclusion markers or automatically
/// skipped SwiftUI property wrappers. Closures and computed properties are unsupported.
@attached(peer)
public macro EquatableCompared<Strategy: EquatableComparisonStrategy>(using strategy: Strategy.Type) =
#externalMacro(module: "EquatableMacros", type: "EquatableComparedMacro")
27 changes: 27 additions & 0 deletions Sources/EquatableClient/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,33 @@ import Equatable
@EquatableIgnoredUnsafeClosure let closure: (() -> Content)?
}

@Equatable
struct EquatableComparedExample: Hashable {
let name: String
@EquatableCompared(.identity)
let foo1: Foo
@EquatableCompared(by: \Foo.id)
let foo2: Foo
@EquatableCompared(using: FooComparedByUUIDString.self)
let foo3: Foo

@EquatableIgnoredUnsafeClosure let closure: (() -> Void)?
}

class Foo {
let id: UUID

init() {
id = UUID()
}
}

enum FooComparedByUUIDString: EquatableComparisonStrategy {
static func comparisonValue(for value: Foo) -> some Hashable {
value.id.uuidString
}
}

struct CustomType: Equatable {
let name: String
let lastName: String
Expand Down
121 changes: 121 additions & 0 deletions Sources/EquatableMacros/EquatableComparedMacro.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import SwiftSyntax
import SwiftSyntaxMacros

public struct EquatableComparedMacro: PeerMacro {
public static func expansion(
of node: AttributeSyntax,
providingPeersOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard let variable = declaration.as(VariableDeclSyntax.self) else {
throw MacroExpansionErrorMessage("@EquatableCompared can only be applied to instance stored properties")
}
_ = try comparison(for: variable)

// Do not walk past functions or nested unannotated types to find an
// unrelated outer @Equatable declaration.
let parent = context.lexicalContext.first { !$0.is(VariableDeclSyntax.self) }
let parentAttributes: AttributeListSyntax?
parentAttributes = parent?.as(StructDeclSyntax.self)?.attributes
guard parentAttributes?.contains(where: { element in
guard let attribute = element.as(AttributeSyntax.self) else { return false }
return ["Equatable", "Equatable.Equatable"].contains(attribute.attributeName.trimmedDescription)
}) == true else {
throw MacroExpansionErrorMessage("@EquatableCompared requires an enclosing @Equatable struct")
}
return []
}

static func comparison(for declaration: VariableDeclSyntax) throws -> EquatableProperty.Comparison {
let markers = attributes(in: declaration)
guard markers.count == 1, let marker = markers.first else {
throw MacroExpansionErrorMessage("A property can have only one @EquatableCompared marker")
}
guard declaration.bindings.count == 1, let binding = declaration.bindings.first,
binding.pattern.is(IdentifierPatternSyntax.self) else {
throw MacroExpansionErrorMessage("@EquatableCompared requires a single named property")
}
guard !declaration.modifiers.contains(where: {
$0.name.tokenKind == .keyword(.static) || $0.name.tokenKind == .keyword(.class)
}), isStored(binding) else {
throw MacroExpansionErrorMessage("@EquatableCompared can only be applied to instance stored properties")
}
let excludedNames = [
"EquatableIgnored", "Equatable.EquatableIgnored",
"EquatableIgnoredUnsafeClosure", "Equatable.EquatableIgnoredUnsafeClosure"
]
if declaration.attributes.contains(where: { element in
element.as(AttributeSyntax.self).map { excludedNames.contains($0.attributeName.trimmedDescription) } == true
}) {
throw MacroExpansionErrorMessage("@EquatableCompared cannot be combined with an equality exclusion marker")
}
guard !EquatableMacro.shouldSkip(declaration) else {
throw MacroExpansionErrorMessage("@EquatableCompared cannot be applied to automatically skipped SwiftUI properties")
}
guard binding.typeAnnotation.map({ isClosure(type: $0.type) }) != true,
binding.initializer?.value.is(ClosureExprSyntax.self) != true else {
throw MacroExpansionErrorMessage("@EquatableCompared cannot be applied to closures")
}
return try comparison(from: marker)
}

private static func isStored(_ binding: PatternBindingSyntax) -> Bool {
guard let block = binding.accessorBlock else { return true }
guard case let .accessors(accessors) = block.accessors, !accessors.isEmpty else { return false }
return accessors.allSatisfy {
$0.accessorSpecifier.tokenKind == .keyword(.willSet) || $0.accessorSpecifier.tokenKind == .keyword(.didSet)
}
}

static func attributes(in declaration: VariableDeclSyntax) -> [AttributeSyntax] {
declaration.attributes.compactMap { element in
guard let attribute = element.as(AttributeSyntax.self),
["EquatableCompared", "Equatable.EquatableCompared"].contains(attribute.attributeName.trimmedDescription) else {
return nil
}
return attribute
}
}

static func comparison(from attribute: AttributeSyntax) throws -> EquatableProperty.Comparison {
guard let arguments = attribute.arguments?.as(LabeledExprListSyntax.self),
arguments.count == 1, let argument = arguments.first else {
throw MacroExpansionErrorMessage("@EquatableCompared requires one comparison argument")
}

switch argument.label?.text {
case "by":
guard argument.expression.is(KeyPathExprSyntax.self) else {
throw MacroExpansionErrorMessage("@EquatableCompared(by:) requires a key-path literal")
}
return .keyPath(argument.expression)
case "using":
guard let member = argument.expression.as(MemberAccessExprSyntax.self),
member.declName.baseName.text == "self", let base = member.base,
isTypeReference(base) else {
throw MacroExpansionErrorMessage("@EquatableCompared(using:) requires a strategy metatype, such as Strategy.self")
}
return .strategy(base)
case nil:
guard let member = argument.expression.as(MemberAccessExprSyntax.self),
member.declName.baseName.text == "identity",
[nil, "EquatableComparison", "Equatable.EquatableComparison"].contains(member.base?.trimmedDescription) else {
throw MacroExpansionErrorMessage("@EquatableCompared requires .identity, by: a key path, or using: a strategy")
}
return .identity
default:
throw MacroExpansionErrorMessage("@EquatableCompared requires .identity, by: a key path, or using: a strategy")
}
}

private static func isTypeReference(_ expression: ExprSyntax) -> Bool {
if expression.is(DeclReferenceExprSyntax.self) { return true }
if let member = expression.as(MemberAccessExprSyntax.self), let base = member.base {
return isTypeReference(base)
}
if let specialization = expression.as(GenericSpecializationExprSyntax.self) {
return isTypeReference(specialization.expression)
}
return false
}
}
Loading
Loading