In Swift, what happens at compile time when code calls a freestanding macro such as `#checkedURL("https://example.com")`, and how does that differ from a function call?
answer
- runs while building, not running
- the plug-in receives the call's syntax
- expansion replaces the call
- expanded code is type-checked again
- a thrown error fails the build
basics
~20 sThe compiler expands it during the build: the macro's implementation receives the call's syntax and returns code that replaces the call, which is then type-checked. A function runs later with real values; a macro's thrown error fails the build.
solid answer
~40 sA `#` call is a freestanding macro expansion. While compiling, Swift type-checks the arguments against the macro's declaration, sends the syntax of the call to the macro's implementation (a compiler plug-in built on SwiftSyntax) and replaces `#checkedURL("https://example.com")` with the code that comes back, here `URL(string: "https://example.com")!`. The expansion is type-checked like hand-written code, and if the implementation throws, the build fails with that message at the call site. Nothing of the macro runs when the app runs. A function receives values at run time; the macro sees only what is written, so it can reject a malformed literal before the app ships but cannot know what a variable will hold. `#function` and `#line` are standard-library macros of the same kind.
code
swift · 12 linesimport Foundation
@freestanding(expression)
public macro checkedURL(_ string: String) -> URL =
#externalMacro(module: "MyMacros", type: "CheckedURLMacro")
let docs = #checkedURL("https://example.com/docs")
print(docs.host ?? "no host") // example.com
// Each line below stops the build instead of failing at run time:
// let typo = #checkedURL("htps//example.com")
// let built = #checkedURL(base + "/docs")go deeper
Recall that a # call is expanded by the compiler before the program exists, and that a bad literal becomes a build error rather than a crash.
Walk through the steps: arguments type-checked, the call's syntax sent to the plug-in, the expansion spliced in and type-checked again, thrown errors reported at the call site.
Show that you read expansions when debugging, with Expand Macro or the dump flag, and that you know a computed argument reaches the macro as syntax, not as a value.
Weigh a compile-time literal check against a plain failable initializer: the macro fails earlier but adds a plug-in dependency and clean-build time for every target that uses it.
## What a `#` call is In Swift, a name written after a number sign, such as `#checkedURL("https://example.com/docs")`, is a **freestanding macro expansion**. It looks like a function call, but nothing is called when the program runs. The **compiler** expands it while it builds the module that contains the call, and only the code the macro produced ends up in the binary. A **macro** in Swift has two parts: - a **declaration** that clients import, giving the macro's name, parameter types, result type and role, for example `@freestanding(expression) public macro checkedURL(_ string: String) -> URL`; - an **implementation**, a type built on the SwiftSyntax library that the compiler runs as a **compiler plug-in** to produce the expansion. The standard library already uses the same mechanism for `#function`, `#line`, `#column` and `#fileID`, which it declares as `@freestanding(expression)` macros implemented inside the compiler. ## The steps of one expansion For `let docs = #checkedURL("https://example.com/docs")` the compiler does this: 1. **Parses** the file and type-checks the arguments against the declaration. Passing an `Int` here is an ordinary type error. 2. **Sends the syntax of the call**, and only that piece of the syntax tree, to the macro's implementation. 3. The implementation inspects that syntax and either **returns new code**, here `URL(string: "https://example.com/docs")!`, or **throws**. 4. The compiler **replaces the call** with the returned code and **type-checks it again**, as if you had typed it yourself. If step 3 throws, the message becomes a compile error at the call site, tagged with the macro's name: `error: 'htps//example.com' is not a valid https URL (from macro 'checkedURL')`. A typo in a hard-coded URL is caught on the developer's machine instead of becoming a force-unwrap crash in production. ## What the macro sees The implementation receives **syntax, not values**: - a string literal arrives as a literal node whose text the macro can read and validate; - `#checkedURL(base + "/docs")` type-checks, because the result of `+` is a `String`, but the macro receives an infix expression, not a literal, so a well-written implementation rejects it with a clear message; - it receives only the syntax of the call, not the code before or after it, and The Swift Programming Language says the implementation runs in a sandbox without file-system or network access; not depending on anything else, such as the clock, is the macro author's job. That is the general nature of compile-time expansion, which the material on macro expansion models covers in depth; in Swift the consequence is concrete: the macro can check what is written, never what a variable will hold. ## Macro or function | | `#checkedURL("…")` macro | `URL(string:)` function call | |---|---|---| | When its logic runs | while compiling | each time the line runs | | What it receives | the syntax of the call | the run-time `String` value | | Bad input | build fails with the macro's message | returns `nil`, and a `!` traps | | Present in the binary | only the expanded code | the call itself | | Cost | build time, a plug-in dependency | a little run-time work | ## Seeing the expansion Because the expansion is ordinary Swift, you can read it: - in Xcode, the **Expand Macro** command on the call shows the generated code inline; - from the command line, `swiftc -Xfrontend -dump-macro-expansions` prints every expansion buffer; - when the generated code fails to type-check, the compiler reports the error inside a buffer named after the macro, such as `macro expansion @AddCompletionHandler`, and notes where it was expanded. ## Slips to avoid - Calling the macro without `#`: Swift answers `expansion of macro 'checkedURL' requires leading '#'`. - Expecting the expansion to adapt to run-time data: it is fixed once the build ends. - Treating a macro as free: every clean build has to build or load its plug-in, and the plug-in's dependency on SwiftSyntax comes with it. A freestanding expression macro is the right tool when the input is written in source and a mistake in it should stop the build; when the value arrives at run time, a throwing or failable initializer is still the answer.
- Why does `#checkedURL(base + "/docs")` fail when `base` holds a valid URL string?The argument type-checks as a `String`, so the call matches the declaration, but the implementation receives syntax: an infix `+` expression, not a string literal. This implementation accepts only a single literal, so it throws "#checkedURL needs a string literal" and the compiler reports that at the call site. The macro never sees what `base` holds at run time.
- Are `#function` and `#line` macros too?Yes. The standard library declares them as freestanding expression macros, for example `@freestanding(expression) public macro line<T: ExpressibleByIntegerLiteral>() -> T`, implemented inside the compiler rather than by an external plug-in. Each expands to the enclosing function's name or the line number where it is written.
- How do you see what a macro call expanded to?In Xcode, run Expand Macro on the call to show the generated code inline. From the command line, `swiftc -Xfrontend -dump-macro-expansions` prints each expansion. When generated code fails to type-check, the error is reported inside a buffer named after the macro, with a note pointing at the call.
A macro is like a clerk who checks a handwritten form before it is filed: a bad entry is sent back at the desk, a good one is typed up cleanly, and only the typed copy goes into the archive. Nobody calls the clerk when the file is read later.
- A macro call runs when the program reaches that line, like a function.
- A macro can read the run-time value of a variable passed to it.
- Macro output skips type checking because the compiler trusts the plug-in.
- An error thrown by a macro implementation crashes the app at launch.
- #checkedURL and @checkedURL are two spellings of the same call.