[Pitch] Expression macros

Macro definitions will need to be in a different module, but can be from the same package.

Rust has more than one kind of macro. Rust's declarative macros can be in the same file. Rust's procedural macros need to be in a separate crate (akin to a Swift package) that is specially marked as defining a procedural macro.

Access control will be based on the macro declaration, so if your macro declaration is public it can be used outside of the module, if it's internal you can only use it inside the module, etc. Package-level visibility would allow one to create a macro only visible within the package.

I don't have a specific design yet, but my thought is that it'll be a special kind of target in the manifest so that SwiftPM knows it is building a macro definition and can pass the appropriate compiler flags down.

That's how Rust's procedural macros work, but I'd rather not require that. I think we should be able to have the macro definition module be part of the same package as the macro declaration. The macro definition module will have very different dependencies (e.g., it'll depend on swift-syntax) and be built for a different platform/architecture (because it runs on the host, not the target).

These things need to be designed further and written down somewhere. I don't know if it should be this proposal, or whether it should be a separate SwiftPM proposal focused on how macro definitions are built.

Doug

10 Likes

Immensely helpful, and I like all of these design decisions very much. Thank you!

1 Like

Could macros have access to build settings and preprocess Swift source with them (e.g.: to initialise a property)?

I had a use case today where I needed the value for the DEVELOPMENT_TEAM build setting to properly access shared Keychains. I am currently relying on the Info.plist (or some other property list) to be preprocessed and reading that value from it at runtime. But it would have been simpler and easier to use to have it known at compile time and fail to build the app if a team ID couldn't be found.

Now I'm daydreaming of an alternate universe where we could replace Info.plist files with Swift files!

2 Likes

Yes, that's the eventual plan. I've added that to the proposal in Note that MacroEvaluationContext will grow to include build environmeā€¦ Ā· DougGregor/swift-evolution@d101cff Ā· GitHub

Doug

5 Likes

Folks, I've made some significant revisions to the proposal and posted a second pitch. Thank you all so much for the discussion!

Doug

5 Likes