Skip to content

Add support for body macros on variables and accessors#3298

Merged
rintaro merged 7 commits intoswiftlang:mainfrom
calda:cal--computed-var-body-macro
Mar 20, 2026
Merged

Add support for body macros on variables and accessors#3298
rintaro merged 7 commits intoswiftlang:mainfrom
calda:cal--computed-var-body-macro

Conversation

@calda
Copy link
Copy Markdown
Contributor

@calda calda commented Mar 14, 2026

Corresponding compiler PR: swiftlang/swift#87869


According to SE-0415, body macros should be supported on variables and accessors:

Function body macros can be applied to accessors as well, in which case they go on the accessor itself, e.g.,

var area: Double {
  @Logged get {
    return length * width
  }
}

When using the shorthand syntax for get-only properties, a function body macro can be applied to the property itself:

@Logged var area: Double {
  return length * width
}

However, both forms are currently unsupported with errors like error: 'body' macro cannot be attached to var ('area') or error: Declaration is not a type with an optional code block.

This PR adds implements supports for both of these use cases.

  • To support body macros on accessors, we only have to fix an issue where the SwiftSyntax plugin did not properly parse the AccessorDeclSyntax received via a plugin message.
  • To support body macros on computed property declarations, we have to update the compiler to pass through the VariableDeclSyntax, and then within Swift Syntax synthesize an implicit AccessorDeclSyntax to use in the expansion(of:providingBodyFor:in:) call (which needs a WithOptionalCodeBlockSyntax).

At Airbnb, we'd like to use this functionality to enable adding instrumentation to SwiftUI view bodies, like:

struct MyView: View {
  @Instrumented // Enabled by this fix :)
  var body: some View {
    Text("Hello world!")
  }
}

Fixes swiftlang/swift#75715.

Please review: @ahoppen @DougGregor

@calda calda requested a review from DougGregor as a code owner March 17, 2026 03:02
@rintaro
Copy link
Copy Markdown
Member

rintaro commented Mar 18, 2026

@swift-ci Please test

@rintaro
Copy link
Copy Markdown
Member

rintaro commented Mar 20, 2026

@swift-ci Please test

@rintaro
Copy link
Copy Markdown
Member

rintaro commented Mar 20, 2026

@swift-ci Please test Windows

@rintaro rintaro merged commit 901f1c9 into swiftlang:main Mar 20, 2026
38 checks passed
@rintaro
Copy link
Copy Markdown
Member

rintaro commented Mar 20, 2026

Thank you Cal!

@calda
Copy link
Copy Markdown
Contributor Author

calda commented Mar 20, 2026

Thanks for the review and support 🙇🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Body macro can’t be attached to variables

2 participants