swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.27k stars 10.33k forks source link

Freestanding Declaration Macro Expanding Defer Block Causes Compiler Error starting with Swift 5.10 #72307

Open i2h3 opened 5 months ago

i2h3 commented 5 months ago

Description

With Swift 5.9, I implemented a Swift package which provides a freestanding declaration macro. That macro expands to two variable declarations and a defer block to start a signpost and define its end in the defer block immediately. It always compiled and worked fine. After updating to Swift 5.10, the expansion causes a compiler error.

Reproduction

I have set up an example Swift macro package which implements the minimal example.

✅ It builds and works fine in Swift 5.9 (Xcode 15.2). 💥 It results in a compiler error in Swift 5.10 (Xcode 15.3) at the defer block of the macro expansion.

$ swift build            
Building for debugging...
/var/folders/5h/qlnrjvt16p31yv1ndyt_sll00000gn/T/swift-generated-sources/@__swiftmacro_14SignpostClient7ExampleC8sayHelloyyF8signpostfMf0_.swift:4:1: error: expected macro expansion to produce a declaration
defer {
^
/Users/redacted/Temporary/Signpost/Sources/SignpostClient/main.swift:9:9: note: in expansion of macro 'signpost' here
        #signpost
        ^~~~~~~~~
/var/folders/5h/qlnrjvt16p31yv1ndyt_sll00000gn/T/swift-generated-sources/@__swiftmacro_14SignpostClient7ExampleC8sayHelloyyF8signpostfMf0_.swift:2:5: warning: initialization of immutable value 'signpostIntervalState' was never used; consider replacing with assignment to '_' or removing it
let signpostIntervalState = signposter.beginInterval(#function, id: signpostID)
    ^
/Users/redacted/Temporary/Signpost/Sources/SignpostClient/main.swift:9:9: note: in expansion of macro 'signpost' here
        #signpost
        ^~~~~~~~~
error: fatalError
Screenshot

Expected behavior

The macro expansion is accepted and does not cause a compiler error as before.

Environment

$ swiftc -version
swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0

Additional information

I asked about this issue already in the Swift forums.

shimastripe commented 5 months ago

It looks like it was intentional changes. https://github.com/apple/swift/pull/69106

And, I think it seems appropriate to use CodeItem freestanding macro for your case. But CodeItem macro is experimental feature yet... https://github.com/apple/swift/pull/65427 Just sharing 🙏

i2h3 commented 4 months ago

Thank you for point out, I considered it being intentional. Ok, then I will have to wait for the CodeItem macro, I guess.