swift-composable-architecture icon indicating copy to clipboard operation
swift-composable-architecture copied to clipboard

Added support of ViewAction for preprocessor macros

Open jasin755 opened this issue 8 months ago • 3 comments

Fix: Ensure @ViewAction(for:) Macro Compatibility with Preprocessor Directives

Summary

This PR updates the @ViewAction(for:) macro to be compatible with preprocessor directives, such as #if canImport(AppKit). Previously, the macro did not handle conditional compilation correctly, which could lead to issues when using platform-specific attributes.

Changes

  • Improved handling of #if canImport(AppKit) to support platform-dependent attributes.
  • Ensured that attributes like @Perception.Bindable and @Bindable can be conditionally applied based on platform availability.
  • Refactored macro expansion logic to correctly resolve conditional code paths.

Example Usage

#if canImport(AppKit)  
@Perception.Bindable  
var store: StoreOf<MyReducer>  
#else  
@Bindable  
var store: StoreOf<MyReducer>  
#endif  

Impact

This change improves compatibility when using @ViewAction(for:) in cross-platform projects, ensuring that platform-specific attributes are correctly recognized and applied.

Testing

  • Verified compilation on different platforms (iOS/macOS).
  • Ensured that the correct attribute is applied depending on platform availability.

jasin755 avatar Mar 20 '25 13:03 jasin755

@jasin755 Thanks for taking the time to look into this and implement! I think one thing that still needs to be accounted for is nested #ifs, so some kind of recursion is required.

There is a SwiftIfConfig module in SwiftSyntax that provides helpers for this so that you don't need to write manual recursive code: https://github.com/swiftlang/swift-syntax/blob/main/Sources/SwiftIfConfig/SwiftIfConfig.docc/SwiftIfConfig.md

We haven't explored it yet, but do you think you can take a crack at support as well as another test with more complex nested #if statements?

stephencelis avatar Mar 26 '25 18:03 stephencelis

Thanks for pointing this out! Yes, recursion will indeed be necessary—I actually realized this myself the day after submitting the PR. I just haven't had the chance to look into it yet, and I'm still getting familiar with Swift Macros. I'll definitely explore the SwiftIfConfig module you mentioned to handle nested #ifs, and I'll prepare an additional test case with more complex nested conditions soon.

jasin755 avatar Mar 31 '25 08:03 jasin755

Hi @jasin755, do you plan on still working on this? If not, what do you think about closing it out until you are ready?

mbrandonw avatar May 07 '25 18:05 mbrandonw