skip to content

In a Package.swift manifest, how do you wire a Swift macro so app code can use it, and why must app targets import a library target rather than the `.macro` target?

level: seniorimportance: should knowfreq 28%

answer

  1. a separate import in the manifest
  2. implementation versus interface module
  3. the compiler runs one of them
  4. swift-syntax stays behind the macro

basics

~20 s

Import CompilerPluginSupport, declare a .macro target depending on swift-syntax's SwiftSyntaxMacros and SwiftCompilerPlugin, plus a regular target that depends on it and declares the macros. Clients import that library target; the macro target is a compiler plugin.

solid answer

~40 s

Macro targets arrived with tools version 5.9 in the `CompilerPluginSupport` module, so the manifest needs `import CompilerPluginSupport`; without it, `.macro(...)` fails with `has no member 'macro'`. The `.macro` target holds the implementation and depends on swift-syntax's `SwiftSyntaxMacros` and `SwiftCompilerPlugin`; the compiler loads it while compiling client code, so it is built for the host, never linked into the app. A regular `.target` depends on it and declares the public macros with `#externalMacro(module:type:)`; that interface target is what a library product vends and what app code imports. SwiftPM 6.0's changelog notes that modules importing a macro module directly, instead of its interface module, no longer build with `swift build`. A `.testTarget` depends on the macro target to test expansions, and `swift package init --type macro` generates this layout.

code

swift · 25 lines
swift
// swift-tools-version: 6.1
import PackageDescription
import CompilerPluginSupport          // where .macro is declared

let package = Package(
    name: "ClientKit",
    platforms: [.iOS(.v17), .macOS(.v14)],
    products: [
        .library(name: "DesignSystem", targets: ["DesignSystem"]),
    ],
    dependencies: [
        .package(url: "https://github.com/swiftlang/swift-syntax", from: "509.0.0"),
    ],
    targets: [
        .macro(
            name: "DesignSystemMacros",            // implementation, run by the compiler
            dependencies: [
                .product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
                .product(name: "SwiftCompilerPlugin", package: "swift-syntax"),
            ]
        ),
        .target(name: "DesignSystem", dependencies: ["DesignSystemMacros"]),  // interface
        .testTarget(name: "DesignSystemMacrosTests", dependencies: ["DesignSystemMacros"]),
    ]
)

go deeper

for a junior

Recall that a macro package needs import CompilerPluginSupport, a .macro target and a library target that apps import.

for a middle

Explain why the implementation and the interface are separate modules and which one a library product should list.

for a senior

Diagnose macro wiring failures, from the missing import to direct imports of macro modules, and keep swift-syntax away from shipping targets.

for a principal

Weigh where macro packages sit in the module graph so their swift-syntax build cost lands on as few teams and targets as possible.

## The pieces a macro needs A Swift macro is split across modules because the code that **expands** it and the code that **uses** it run in different places. SwiftPM models that with a dedicated target type, added in tools version 5.9: - **The `.macro` target is the implementation.** It depends on swift-syntax's `SwiftSyntaxMacros` and `SwiftCompilerPlugin` products, and the compiler loads it as a plugin while it compiles client code. The factory lives in the `CompilerPluginSupport` module, so the manifest needs `import CompilerPluginSupport`; without it the manifest fails with `type 'Array<Target>.ArrayLiteralElement' (aka 'Target') has no member 'macro'`. - **A regular `.target` is the interface.** It depends on the macro target and declares the macros clients write, for example `@freestanding(expression) public macro hexColor(_ value: String) -> UInt32 = #externalMacro(module: "DesignSystemMacros", type: "HexColorMacro")`. This is the module a library product vends and app code imports. - **A `.testTarget` exercises the expansions.** It depends on the macro target directly, because it tests the implementation types. How a macro declaration and its SwiftSyntax implementation work is covered with the Swift language's macros; this question is about the manifest that wires them together. ## Why app code imports the interface | Target | Built for | Linked into the app | Imported by app code | |---|---|---|---| | `.macro` (`DesignSystemMacros`) | the machine running the compiler | no | no | | interface `.target` (`DesignSystem`) | the app's platform | yes | yes | | `.testTarget` | the platform running the tests | no | no | The macro target is a program the compiler runs, built for the host even when the app targets iOS. App code reaches the macros only through the declarations in the interface module. SwiftPM 6.0 tightened this: its changelog records that packages with modules that imported macro modules directly, instead of the macro interface modules, no longer build with `swift build`. In practice: - the library product lists the interface target, `DesignSystem`, and never `DesignSystemMacros`; - app targets depend on that product and write `import DesignSystem`; - only the interface target and the macro tests depend on the macro target. ## swift-syntax is a cost to manage The macro target pulls in swift-syntax, a large package, so the wiring decides how much of the graph pays for it: - Keep swift-syntax behind the macro target. A regular app-facing target that imports swift-syntax drags it into code that ships. - Helper code shared by two macro targets can go in a library that only macro targets depend on. SwiftPM 6.3's release notes describe improved use of prebuilt swift-syntax for such macro-only libraries, and say SwiftPM turns prebuilts off when it detects that such a library may be used by non-macro targets, because mixing prebuilt and source-built swift-syntax at link time caused problems. - The version of swift-syntax the package accepts is a dependency requirement like any other, and resolution rules are a separate lesson. ## Names that must line up The wiring crosses three places, and each one names the macro target by the same string: - the `.macro(name: "DesignSystemMacros")` declaration in the manifest; - the interface target's dependency, `dependencies: ["DesignSystemMacros"]`; - the `module:` argument of every `#externalMacro(module: "DesignSystemMacros", type: ...)` in the interface module. Rename the target without updating the declarations and the macro declaration still compiles, but the compiler warns that the external macro implementation type could not be found, and any use of the macro fails. A rename of a macro target is therefore a manifest change and a source change in one commit. ## What a `.macro` target can declare The `.macro` factory takes `name`, `dependencies`, `path`, `exclude`, `sources`, `packageAccess`, `swiftSettings`, `linkerSettings` and `plugins`. It has no `resources:` parameter and no C or C++ settings: the target model rejects resources and public headers on a macro target. A macro that needs data has to carry it in code. ## Starting from the template 1. Run `swift package init --type macro`: it generates a `.macro` target with its swift-syntax dependencies, a library `.target` with the macro declarations, an `.executableTarget` that uses the macro, and a `.testTarget`. 2. Rename the targets to your feature, for example `DesignSystemMacros` and `DesignSystem`, and keep the split. 3. Vend only the interface target in a library product. 4. Keep the manifest at tools version 5.9 or later, since `.macro` does not exist before it. 5. Remember that a `.testTarget` cannot depend on another `.testTarget`; shared test helpers go in a regular target.

  • What error do you get if the manifest uses `.macro` without importing CompilerPluginSupport?
    The manifest does not compile: `type 'Array<Target>.ArrayLiteralElement' (aka 'Target') has no member 'macro'`. The `.macro` factory is an extension on `Target` declared in `CompilerPluginSupport`, not in `PackageDescription`, so the second import is required.
  • Why can a macro target not declare `resources:`?
    The macro target is a compiler plugin built for the host, not a module shipped with the app, and the target model rejects resources and public headers for the macro type. The `.macro` factory has no `resources:` parameter at all, so data the macro needs lives in its code.

  • App targets should depend on the .macro target directly to use its macros.
  • The .macro factory is part of PackageDescription, so no extra import is needed.
  • A macro target is linked into the app like any other library target.
  • Putting swift-syntax in a shared app-facing target is free because the macro needs it anyway.
  • A macro target can bundle JSON resources for its expansion logic.

Assumes tools version 5.9 or later, which added CompilerPluginSupport and .macro targets; the Swift 6.0 import rule and the 6.3 prebuilt note come from SwiftPM's changelog and release notes, checked against SwiftPM 6.4.