skip to content

A Swift peer macro `@AddCompletionHandler` fails with "declaration name 'fetchAvatarWithCompletion' is not covered by macro"; why, and why can it not rewrite the async method itself instead?

level: seniorimportance: nice to knowfreq 18%

answer

  1. the names: list in @attached
  2. overloaded vs suffixed
  3. peers are added beside, never in place
  4. same signature means redeclaration
  5. read the expansion, then pin it in tests

basics

~20 s

Its declaration says names: overloaded, which covers only declarations named fetchAvatar, so fetchAvatarWithCompletion is rejected. Emit an overload of fetchAvatar or declare suffixed(WithCompletion). A peer macro only adds declarations beside the method; it cannot change it.

solid answer

~40 s

Swift checks every name an attached macro introduces against the `names:` list in its declaration. `@attached(peer, names: overloaded)` promises only overloads of the attached declaration's own name, so `fetchAvatar(id:completionHandler:)` passes but `fetchAvatarWithCompletion(_:)` fails with `declaration name 'fetchAvatarWithCompletion' is not covered by macro 'AddCompletionHandler'`. Fix the expansion or widen the list with `suffixed(WithCompletion)`. Rewriting the async method is out of reach: a peer macro returns new declarations placed beside the original, and emitting a copy with the same signature is an `invalid redeclaration`. Only a `body` macro, added in Swift 6.0, may supply or replace the attached function's body. To work on it, read the expansion with Xcode's Expand Macro or `-Xfrontend -dump-macro-expansions`, and pin it with `assertMacroExpansion` tests.

code

swift · 18 lines
swift
import Foundation

@attached(peer, names: overloaded)
public macro AddCompletionHandler() =
    #externalMacro(module: "MyMacros", type: "AddCompletionHandlerMacro")

struct AvatarService {
    @AddCompletionHandler
    func fetchAvatar(id: Int) async -> String {
        "avatar-\(id)"
    }
}

// Generated beside fetchAvatar(id:), callable from completion-handler code:
AvatarService().fetchAvatar(id: 7) { name in
    print(name)   // avatar-7
}
Thread.sleep(forTimeInterval: 0.2)

go deeper

for a junior

Recall that an attached macro adds code next to or inside a declaration and that its declaration lists the names it may add.

for a middle

Explain how named, overloaded, prefixed, suffixed and arbitrary each constrain an expansion, and what the not-covered error checks.

for a senior

Fix the expansion or the names list, say why a peer cannot replace the method, and show the debugging loop: expansion buffer, Expand Macro, expansion tests.

for a principal

Decide which macros may change behaviour, such as body macros, and require their expansions to be visible in review and pinned by tests.

## The scenario A team is moving a networking layer to `async` methods but still has callers written with completion handlers. Instead of hand-writing a wrapper for every method, they write an attached **peer macro**, `@AddCompletionHandler`, declared as `@attached(peer, names: overloaded)`. Attached to `func fetchAvatar(id: Int) async -> String`, it should add a companion that takes a `completionHandler` and calls the async method from a `Task`. The first version of the implementation names the companion `fetchAvatarWithCompletion(_:)`, and the build fails inside the expansion: ```plaintext macro expansion @AddCompletionHandler:1:6: error: declaration name 'fetchAvatarWithCompletion' is not covered by macro 'AddCompletionHandler' ``` ## Why the name is rejected Swift checks every declaration an attached macro introduces against the `names:` list in the macro's declaration. The list is a promise the compiler relies on during name lookup: when it looks up `fetchAvatarWithCompletion`, it can skip any macro that cannot produce that name. | Name specifier | Covers, for `fetchAvatar(id:)` | |---|---| | `overloaded` | other declarations named `fetchAvatar`, such as `fetchAvatar(id:completionHandler:)` | | `suffixed(WithCompletion)` | `fetchAvatarWithCompletion` | | `prefixed(legacy_)` | `legacy_fetchAvatar` | | `named(fetchAll)` | exactly `fetchAll` | | `arbitrary` | any name, at the cost of always expanding during lookup | So there are two fixes: 1. emit an **overload** that keeps the base name, `fetchAvatar(id:completionHandler:)`, which `overloaded` covers; or 2. keep the new name and declare `@attached(peer, names: suffixed(WithCompletion))`. Avoid reaching for `arbitrary`: it makes every lookup in that scope expand the macro, and on a top-level function Swift rejects it outright with `'peer' macros are not allowed to introduce arbitrary names at global scope`. ## Macros add; they do not edit A second request usually follows: "make the macro turn the async method itself into a completion-handler method". A peer macro cannot. The book is explicit that macro expansion is additive. A peer implementation returns `[DeclSyntax]`, new declarations placed **beside** the original, and the original stays exactly as written. - Emitting a copy of the method with the same signature does not replace it; Swift reports `invalid redeclaration of 'fetchAvatar(id:)'`. - Copying the attribute along with the declaration makes the copy expand the macro again, and Swift stops with `recursive expansion of macro`. - A member macro adds members and an extension macro adds an extension. Even an accessor macro, which turns a stored property into a computed one, does it by adding accessors; none of these roles deletes code that was written. The one exception is the **body** role, added in Swift 6.0. A `BodyMacro` receives the function as written and returns the statements of its body; a body that was written must still parse but is not type-checked, and the macro's result replaces it. That is how a logging or tracing wrapper is built. It is also exactly the kind of invisible change reviewers should insist on seeing expanded. ## Debugging the expansion 1. **Read the error in place.** Errors in generated code are reported inside a buffer named `macro expansion @AddCompletionHandler`, with a note pointing at the attribute that produced it. 2. **Look at the whole expansion.** Xcode's Expand Macro shows it inline at the attribute; `swiftc -Xfrontend -dump-macro-expansions` prints every buffer. 3. **Diagnose misuse early.** If the macro is attached to a non-`async` function, throw a clear message, or call `context.diagnose(_:)`, instead of emitting code that fails later with a confusing type error. 4. **Generate helper names safely.** A temporary variable in the expansion should come from `context.makeUniqueName(_:)`, never a fixed identifier that could shadow one of the caller's. ## Testing it Expansion is a pure syntax-to-syntax function, so it tests well without a compiler in the loop. In the macro target's test target, `assertMacroExpansion` from SwiftSyntaxMacrosTestSupport takes the source that uses the macro, the expanded source you expect, and a dictionary from macro name to implementation type, plus any diagnostics you expect for misuse. Pin at least: - the expansion for a method with labelled, unlabelled and `_` parameters; - a `throws` method, if the macro supports one, mapped to a `Result`; - the diagnostic for a non-async function. ## Generated code still obeys the language mode The generated overload is checked where it lands, like hand-written code, including data-race checking. In Swift 6 language mode, a version of the macro that declared the handler as `@escaping (String) -> Void`, without `@Sendable`, fails inside the expansion: ```plaintext macro expansion @AddHandler:2:5: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure ``` So the macro has to generate code that is correct in the strictest language mode its users build with; the expansion hides nothing from the checker.

  • When is `names: arbitrary` the right list, and what does it cost?
    When names depend on the input, such as one constant per enum case. The compiler then has to expand the macro for every name lookup in that scope, which costs build time, and a peer macro on a top-level declaration may not use it: `'peer' macros are not allowed to introduce arbitrary names at global scope`.
  • The team now wants the macro to wrap the async method's body in logging. Which role, and what changes?
    The `body` role, added in Swift 6.0, implemented with `BodyMacro`. It receives the function as written and returns the statements of its body; a written body must parse but is not type-checked, and only one body macro may sit on a function. Unlike a peer, it changes what the method does, so reviewers need to see the expansion.
  • How do you test the macro?
    In the macro target's test target, call `assertMacroExpansion` from SwiftSyntaxMacrosTestSupport with the source using the macro, the expanded source you expect and a map from macro name to implementation type, plus expected diagnostics for misuse such as a non-async function. The test runs the implementation directly, so it is fast and needs no app build.

  • names: overloaded lets a peer macro introduce any name it likes.
  • A peer macro can replace the method it is attached to by emitting a new version.
  • A names-not-covered error means the macro plug-in crashed.
  • Macro-generated code is exempt from Swift 6 Sendable checking.
  • names: arbitrary is the safe default for every peer macro.