Skip to content

Unexpected warnings when capturing self in closures passed to macros #80561

@NSFatalError

Description

@NSFatalError

Description

Any closure that captures self safely (including non-escaping closures and escaping closures marked with @_implicitSelfCapture) and is passed to a macro as its argument produces unexpected warnings, like:

Reference to property '...' in closure requires explicit use of 'self' to make capture semantics explicit; this will be an error in a future Swift language mode

or:

Call to method '...' in closure requires explicit use of 'self' to make capture semantics explicit; this will be an error in a future Swift language mode

Note: I've noticed this bug with freestanding expression macros specifically, but it's possible it affects other types as well.

Reproduction

import Testing

struct MyError: Error {}

struct MyStruct {
    func perform() throws {
        throw MyError()
    }
}

final class MyTests {
    let value = MyStruct()

    @Test func example() {
        #expect(throws: MyError.self) {
            try value.perform()
            // Reference to property 'value' in closure requires explicit use of 'self' to make capture semantics explicit;
            // this will be an error in a future Swift language mode
        }
    }
}
@freestanding(expression)
macro MyMacro(
    operation: () -> Void
) = #externalMacro(...)

class MyExample {
    func first() {
        #MyMacro {
            second()
            // Call to method 'second' in closure requires explicit use of 'self' to make capture semantics explicit; 
            // this will be an error in a future Swift language mode
        }
    }
    func second() {}
}

Expected behavior

Compiler applies the same rules for self capture in closures to macros as it does to standard functions.

Environment

swift-driver version: 1.120.5 Apple Swift version 6.1 (swiftlang-6.1.0.110.21 clang-1700.0.13.3)
Target: arm64-apple-macosx15.0

Note: this bug started occurring when updating to Xcode 16.3, it did not affect earlier 16.2 release.

Additional information

No response

Metadata

Metadata

Assignees

Labels

bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfswift 6.1swift macroFeature → declarations: Swift `macro` declarationstype checkerArea → compiler: Semantic analysis

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions