In Swift, how is a macro declared with `#externalMacro(module:type:)` and implemented with SwiftSyntax, and where does its implementation actually run?
answer
- declaration apart from implementation
- macro keyword plus a role attribute
- #externalMacro names module and type
- role protocol's static expansion method
- host plug-in, launched by the compiler
basics
~20 sA macro declaration gives the name, signature and role, and #externalMacro(module:type:) points at a type in a separate macro target. That type conforms to a SwiftSyntax protocol such as ExpressionMacro, and the compiler runs it as a plug-in while building callers.
solid answer
~40 sA macro has two halves. The declaration lives in a library clients import: `@freestanding(expression) public macro checkedURL(_ string: String) -> URL = #externalMacro(module: "URLMacros", type: "CheckedURLMacro")`. The implementation lives in a separate macro target built for the host, the machine running the compiler: a type conforming to the role's SwiftSyntax protocol (`ExpressionMacro` requires a static `expansion(of:in:)` that takes the call's syntax and a `MacroExpansionContext` and returns `ExprSyntax`), plus an `@main` type conforming to `CompilerPlugin` that lists it in `providingMacros`. The compiler launches that plug-in during the build, and the book says it runs sandboxed, without file-system or network access. If the plug-in cannot be found, the declaration only warns, but every use fails with `external macro implementation type … could not be found`.
code
swift · 21 linesimport Foundation
import SwiftSyntax
import SwiftSyntaxMacros
public struct CheckedURLMacro: ExpressionMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> ExprSyntax {
guard let literal = node.arguments.first?.expression
.as(StringLiteralExprSyntax.self),
let text = literal.representedLiteralValue
else {
throw MacroExpansionErrorMessage("#checkedURL needs a string literal")
}
guard let url = URL(string: text), url.scheme == "https", url.host != nil else {
throw MacroExpansionErrorMessage("'\(text)' is not a valid https URL")
}
return "URL(string: \(literal))!"
}
}go deeper
Recall that a macro has a declaration you import and an implementation the compiler runs, and that the # call names the declaration.
Explain how #externalMacro links the two, which protocol each role implements, and what expansion(of:in:) receives and returns.
Diagnose a broken setup from its messages: a warning on the declaration plus errors at uses means the client's build never loaded the plug-in.
Treat macro targets as host tools in your build graph: they need the same review, pinning and CI caching as any build-time dependency.
## Two halves, two targets Most Swift declarations are their own implementation. A **macro** is not: its **declaration** and its **implementation** are separate, and they live in different modules built for different machines. - The **declaration** sits in an ordinary library module that clients import. It gives the name, parameters, result type and roles. - The **implementation** sits in a **macro target**, a separate program that the build system compiles for the **host**, the machine running the compiler, not for the device the app ships to. It is built on the **SwiftSyntax** library. Packaging the two targets is the Swift Package Manager's business; the manifest side is covered with SwiftPM. What follows is the language side. ## The declaration ```swift @freestanding(expression) public macro checkedURL(_ string: String) -> URL = #externalMacro(module: "URLMacros", type: "CheckedURLMacro") ``` - `macro` introduces the declaration; it must be at **file scope**, or Swift reports `macro 'checkedURL' can only be declared at file scope`. - The role attribute, here `@freestanding(expression)`, is required: without one you get `macro '…' must declare its applicable roles via '@freestanding' or '@attached'`. - The right-hand side is `#externalMacro(module:type:)`, a standard-library macro that may only define another macro (`macro 'externalMacro' can only be used to define another macro`). Its two string literals name the **plug-in module** and the **implementation type**. - The book notes that macros are declared `public`, because the code that uses them lives in another module. ## The implementation 1. A type conforms to the **SwiftSyntax protocol for its role**: `ExpressionMacro`, `DeclarationMacro`, `PeerMacro`, `MemberMacro`, `MemberAttributeMacro`, `AccessorMacro`, `ExtensionMacro` or `BodyMacro`. 2. It implements the role's static `expansion` method. For `ExpressionMacro` that is `expansion(of:in:)`, taking a `some FreestandingMacroExpansionSyntax` node and a `some MacroExpansionContext` and returning `ExprSyntax`. 3. It reads the arguments as syntax nodes, for example `StringLiteralExprSyntax`, and builds its result from a string literal, since SwiftSyntax node types can be created from string literals. 4. To reject bad input it **throws**, for example `MacroExpansionErrorMessage("…")`, or calls `context.diagnose(_:)` for a diagnostic placed on a specific node, with fix-its if it has them. 5. An `@main` type conforming to `CompilerPlugin` lists the macro types in `providingMacros`; its `main()` connects to the compiler over standard input and output. `MacroExpansionContext` is the implementation's only window on the outside world: - `makeUniqueName(_:)` returns an identifier that, in its doc comment's words, will not conflict with any other name in a well-formed program; - `diagnose(_:)` emits warnings and errors; - `location(of:at:filePathMode:)` turns a node into a file, line and column; - `lexicalContext` lists the enclosing declarations, with their bodies and member lists stripped out. ## Where it runs The build system tells the compiler where each plug-in is; SwiftPM passes `-load-plugin-executable path#ModuleName`, and the compiler launches that executable on demand and exchanges syntax with it. The Swift Programming Language describes two safeguards: - the implementation receives only the syntax of the macro use, not the code before or after it; - it runs in a **sandbox** that prevents file-system and network access. The macro's author still has to keep it deterministic. A macro whose expansion depended on the time of day would defeat the build system's ability to skip expansions that have not changed. ## What the compiler reports when a piece is missing | Situation | Swift 6.4 diagnostic | |---|---| | Plug-in not found, declaration only | warning: `external macro implementation type 'URLMacros.CheckedURLMacro' could not be found for macro 'checkedURL'; …` | | Plug-in not found, at each use | the same text as an **error** | | Called without `#` | `expansion of macro 'checkedURL' requires leading '#'` | | Implementation type lacks the role's protocol | `macro implementation type '…' doesn't conform to required protocol '…'` | The first two rows explain a common surprise: a library that declares macros builds, and its clients fail, when the plug-in is not wired into the client's build. ## Checklist for a new macro - The declaration's role matches the protocol the implementation adopts, and the declaration names every role the implementation serves. - The `#externalMacro` strings match the plug-in's module name and the implementation type's name exactly. - The `@main` `CompilerPlugin` type lists the implementation in `providingMacros`; a type missing there cannot be resolved. - Misuse produces a clear thrown message or diagnostic, not generated code that fails to type-check somewhere the user never wrote.
- What is `MacroExpansionContext` for?It is the implementation's only access to the compiler. `makeUniqueName(_:)` returns an identifier that cannot clash with names in the program, `diagnose(_:)` emits warnings or errors on a chosen node, `location(of:at:filePathMode:)` gives a node's source position, and `lexicalContext` lists the enclosing declarations with their bodies stripped. Anything beyond the macro's own syntax has to come through it.
- Why does a library that declares a macro build while its clients fail?A declaration whose plug-in cannot be loaded only produces a warning, `external macro implementation type '…' could not be found`. The same message becomes an error at every place the macro is used, so the failure shows up in the client that expands it. The fix is in the build setup: the client must load the macro target's plug-in.
- Can a macro be declared inside a type or a function?No. Swift requires macro declarations at file scope and reports `macro '…' can only be declared at file scope` otherwise. They are usually `public` in a library because their callers live in other modules.
- The macro implementation is compiled into the app and runs on the device.
- #externalMacro can be used anywhere to expand another macro.
- The implementation receives the whole source file to inspect.
- A macro plug-in can read project files or call a server during the build.
- A missing plug-in is reported only at the macro declaration.