Getting started with macros?

Hi all. TIL Swift has macros per the newsletter I got. Are these C-style macros or something more Swift-y? Is there a page I can check out for getting started; my searches all come up with random SO pages that don’t seem a great way to get one’s feet wet with them.

1 Like

Some light reading for you. :stuck_out_tongue_winking_eye:

Hello!

We're working on a macros feature for Swift. It's still experimental and going through a bunch of design evolution. Since it can be hard to track what's going on with the development of major features. I'm writing up a gist to help give an overview.

Here is a Swift Macros Dashboard.

Doug

10 Likes

I know it would be more work for you :sweat_smile: but I would love it if the dashboard had more info about what's actually implemented so far. For example, swift-DEVELOPMENT-SNAPSHOT-2023-02-02-a.xctoolchain (the latest atm) doesn't appear to support @attached(peer).

I believe peer macros are the last major part of the attached macro proposal that is not implemented. I'm working on that, and I expect to have an initial implementation landed under the Macros experimental feature flag early next week!

I added some details to the gist about what's expected to work (or not).

Doug

2 Likes

is there a centralized guide for how to use the feature flags in SPM projects, and which ones are available for which nightly toolchain?

1 Like

SE-0362 describes the -enable-experimental-feature mechanism and how to use it with SPM. You can also find the SwiftSetting.enableExperimentalFeature documentation in the SPM repository: swift-package-manager/BuildSettings.swift at main · apple/swift-package-manager · GitHub

I believe the only source of this information today is in the Swift repository for the tag of a given development snapshot in the Features.def file that declares these experimental features. For example, here's the Features.def file in the source code for the February 4th snapshot: swift/Features.def at swift-DEVELOPMENT-SNAPSHOT-2023-02-04-a · apple/swift · GitHub. Everything declared with EXPERIMENTAL_FEATURE is available to use via -enable-experimental-feature in this snapshot.

2 Likes

I think @Douglas_Gregor’s macro example repository also requires another flag (to dynamically load the plugins, IIRC?). Is that also required as an unsafe flag or can we just use the experimental feature flag for macros?

Yeah, there are other flags to load the compiler "plugin". I wasn't able to express all of the right flags and dependencies in SwiftPM, so the sample project is using Xcode's project model for the moment. It should be straightforward to implement the same set of dependencies in CMake, for example, but for SwiftPM we need an actual implementation of the manifest changes.

Doug

2 Likes