5.5 · How Swift macros work, and the roles they play
Macros generate Swift code at compile time. The one-line comparison with property wrappers and result builders is covered in the language section; this one is about the machinery, its limits and its price.
Mental model. A macro is a small compiler plugin that rewrites syntax into more syntax. It sees the text of what you wrote, never the types, and its output is compiled like code you typed yourself.
How a macro runs
The plugin model, its sandbox, and what it costs.
- How does a Swift macro actually run, what can it not do, and what does it cost?
A macro is implemented as a compiler plugin: a separate executable built with SwiftSyntax. When the compiler meets a macro use it launches the plugin, sends it…
What macros can add
Freestanding and attached roles.
- What are the macro roles, and which real macros use which?
A macro declares roles that say where it may appear and what it may produce. Freestanding macros are written with a # and stand alone: an expression macro…
More in Compiler & language internals
- 5.1 · From source to machine code, and how to look inside
- 5.2 · Devirtualisation, whole-module optimisation, inlining, exclusivity
- 5.3 · Specialisation, witness tables, and opaque vs existential in the compiled code
- 5.4 · Library evolution, module interfaces, and the ABI boundary
- 5.6 · Why it compiles slowly, and what rebuilds
- 5.7 · Swift 6 language mode and upcoming features
- 5.8 · Symbol names, linkage, lazy globals and reflection metadata: what is in the binary
- 5.9 · Optimisation levels, closure contexts, ownership conventions and value layout
- 5.10 · What property wrappers, result builders, async and throws compile to
- 5.11 · Package access, SPI, internal imports, strict memory safety and pre-specialisation