Skip to content

Macros seem to be expanded in their own sub-scope #73707

Open
@tmcdonell

Description

@tmcdonell

Description

Code item macros seem to be expanded in their own scope, rather than into the surrounding scope they were called in. This means that operations such as defer will be executed immediately, rather than at the end of the enclosing scope as one would expect (and as described in the official example here).

Reproduction

Minimal reproducer is here: https://github.com/tmcdonell/swift-issue-73707-example

The macro adds a defer { print( ... ) } statement that should be printed right before the function exits.

> swift run
Building for debugging...
[7/7] Applying DeferClient
Build of product 'DeferClient' complete! (0.46s)
=== Expected ===
hello, sailor
exiting function expected()
=== Actual ===
exiting function actual()
hello, sailor

Expected behavior

The deferred print statement should be executed at the end of the function scope.

Environment

Tested with:

  • Apple Swift version 6.0-dev (LLVM cef183591317ec7, Swift 66e3110)
  • Apple Swift version 6.0-dev (LLVM 5b202efbc95a8bf, Swift a17d360)
  • Apple Swift version 5.10-dev (LLVM 57d4e30156f5d21, Swift c05dd0b)
  • Apple Swift version 5.10 (swift-5.10-RELEASE)
  • Apple Swift version 5.9 (swift-5.9-RELEASE)

Target: arm64-apple-macosx14.0

Additional information

Tangentially related: #72307 Since 5.10 it is (correctly) no longer possible to work around this using a declaration macro

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.swift macroFeature → declarations: Swift `macro` declarations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions