rules.md

June 23, 2026 ยท View on GitHub

Bazel rules to define Swift libraries and executable binaries.

Users should load these rules from .bzl files under the swift and proto directories. Do not import definitions from the internal subdirectory directly.

For example:

load("@rules_swift//swift:swift_library.bzl", "swift_library")
load("@rules_swift//proto:swift_proto_library.bzl", "swift_proto_library")

On this page:

swift_binary

swift_binary(name, deps, srcs, data, additional_linker_inputs, copts, defines, env, linkopts,
             linkshared, malloc, module_name, package_name, plugins, stamp, swiftc_inputs)

Compiles and links Swift code into an executable binary.

On Linux, this rule produces an executable binary for the desired target architecture.

On Apple platforms, this rule produces a single-architecture binary; it does not produce universal binaries. As such, this rule is mainly useful for creating Swift tools intended to run on the local build machine.

If you want to create a multi-architecture binary or a bundled application, please use one of the platform-specific application rules in rules_apple instead of swift_binary.

Setting linkshared = True links a shared library instead of an executable; see the linkshared attribute.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of targets that are dependencies of the target being built, which will be linked into that target.

If the Swift toolchain supports implementation-only imports (private_deps on swift_library), then targets in deps are treated as regular (non-implementation-only) imports that are propagated both to their direct and indirect (transitive) dependents.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
srcsA list of .swift source files that will be compiled into the library.

Except in very rare circumstances, a Swift source file should only appear in a single swift_* target. Adding the same source file to multiple swift_* targets can lead to binary bloat and/or symbol collisions. If specific sources need to be shared by multiple targets, consider factoring them out into their own swift_library instead.
List of labelsoptional[]
dataThe list of files needed by this target at runtime.

Files and targets named in the data attribute will appear in the *.runfiles area of this target, if it has one. This may include data files needed by a binary or library, or other programs needed by it.
List of labelsoptional[]
additional_linker_inputsList of additional files needed by the linker.

These files will be passed to the linker when linking the binary target. Typically, these are linker scripts or other files referenced by linkopts.
List of labelsoptional[]
coptsAdditional compiler options that should be passed to swiftc. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
definesA list of defines to add to the compilation command line.

Note that unlike C-family languages, Swift defines do not have values; they are simply identifiers that are either defined or undefined. So strings in this list should be simple identifiers, not name=value pairs.

Each string is prepended with -D and added to the command line. Unlike copts, these flags are added for the target and every target that depends on it, so use this attribute with caution. It is preferred that you add defines directly to copts, only using this feature in the rare case that a library needs to propagate a symbol up to those that depend on it.
List of stringsoptional[]
envSpecifies additional environment variables to set when the test is executed by bazel run or bazel test.

The values of these environment variables are subject to $(location) and "Make variable" substitution.

NOTE: The environment variables are not set when you run the target outside of Bazel (for example, by manually executing the binary in bazel-bin/).
Dictionary: String -> Stringoptional{}
linkoptsAdditional linker options that should be passed to clang. These strings are subject to $(location ...) expansion.List of stringsoptional[]
linksharedIf True, link the target as a shared library / loadable module instead of an executable, similar to cc_binary's linkshared. The binary has no main entry point and the renamed-entry-point machinery is disabled.

This produces a dynamic library named lib<name>.so (.dylib on Apple platforms) suitable for loading with dlopen / System.loadLibrary (e.g. an Android JNI library; export functions with @_cdecl).
BooleanoptionalFalse
mallocOverride the default dependency on malloc.

By default, Swift binaries are linked against @bazel_tools//tools/cpp:malloc", which is an empty library and the resulting binary will use libc's malloc. This label must refer to a cc_library rule.
Labeloptional"@bazel_tools//tools/cpp:malloc"
module_nameThe name of the Swift module being built.

If left unspecified, the module name will be computed based on the target's build label, by stripping the leading // and replacing /, :, and other non-identifier characters with underscores.
Stringoptional""
package_nameThe semantic package of the Swift target being built. Targets with the same package_name can access APIs using the 'package' access control modifier in Swift 5.9+.Stringoptional""
pluginsA list of swift_compiler_plugin targets that should be loaded by the compiler when compiling this module and any modules that directly depend on it.List of labelsoptional[]
stampEnable or disable link stamping; that is, whether to encode build information into the binary. Possible values are:

* stamp = 1: Stamp the build information into the binary. Stamped binaries are only rebuilt when their dependencies change. Use this if there are tests that depend on the build information.

* stamp = 0: Always replace build information by constant values. This gives good build result caching.

* stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.
Integeroptional-1
swiftc_inputsAdditional files that are referenced using $(location ...) in attributes that support location expansion.List of labelsoptional[]

swift_compiler_plugin

swift_compiler_plugin(name, deps, srcs, data, additional_linker_inputs, copts, defines, linkopts,
                      malloc, module_name, package_name, plugins, stamp, swiftc_inputs)

Compiles and links a Swift compiler plugin (for example, a macro).

A compiler plugin is a standalone executable that minimally implements the CompilerPlugin protocol from the SwiftCompilerPlugin module in swift-syntax. As of the time of this writing (Xcode 15.0), a compiler plugin can contain one or more macros, which can be associated with other Swift targets to perform syntax-tree-based expansions.

When a swift_compiler_plugin target is listed in the plugins attribute of a swift_library, it will be loaded by that library and any targets that directly depend on it. (The plugins attribute also exists on swift_binary, swift_test, and swift_compiler_plugin itself, to support plugins that are only used within those targets.)

Compiler plugins also support being built as a library so that they can be tested. The swift_test rule can contain swift_compiler_plugin targets in its deps, and the plugin's module can be imported by the test's sources so that unit tests can be written against the plugin.

Example:

# The actual macro code, using SwiftSyntax
swift_compiler_plugin(
    name = "Macros",
    srcs = glob(["Macros/*.swift"]),
    deps = [
        "@swift-syntax//:SwiftSyntax",
        "@swift-syntax//:SwiftCompilerPlugin",
        "@swift-syntax//:SwiftSyntaxMacros",
    ],
)

# A target testing the macro itself
swift_test(
    name = "MacrosTests",
    srcs = glob(["MacrosTests/*.swift"]),
    deps = [
        ":Macros",
        "@swift-syntax//:SwiftSyntaxMacrosTestSupport",
    ],
)

# The library that defines the macro hook for use in your project
swift_library(
    name = "MacroLibrary",
    srcs = glob(["MacroLibrary/*.swift"]),
    plugins = [":Macros"],
)

# A consumer of the macro library. This doesn't have to be separate from the
# MacroLibrary depending on what makes sense for your project's organization
swift_library(
    name = "MacroConsumer",
    srcs = glob(["Sources/*.swift"]),
    deps = [":MacroLibrary"],
)

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of targets that are dependencies of the target being built, which will be linked into that target.

If the Swift toolchain supports implementation-only imports (private_deps on swift_library), then targets in deps are treated as regular (non-implementation-only) imports that are propagated both to their direct and indirect (transitive) dependents.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
srcsA list of .swift source files that will be compiled into the library.

Except in very rare circumstances, a Swift source file should only appear in a single swift_* target. Adding the same source file to multiple swift_* targets can lead to binary bloat and/or symbol collisions. If specific sources need to be shared by multiple targets, consider factoring them out into their own swift_library instead.
List of labelsoptional[]
dataThe list of files needed by this target at runtime.

Files and targets named in the data attribute will appear in the *.runfiles area of this target, if it has one. This may include data files needed by a binary or library, or other programs needed by it.
List of labelsoptional[]
additional_linker_inputsList of additional files needed by the linker.

These files will be passed to the linker when linking the binary target. Typically, these are linker scripts or other files referenced by linkopts.
List of labelsoptional[]
coptsAdditional compiler options that should be passed to swiftc. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
definesA list of defines to add to the compilation command line.

Note that unlike C-family languages, Swift defines do not have values; they are simply identifiers that are either defined or undefined. So strings in this list should be simple identifiers, not name=value pairs.

Each string is prepended with -D and added to the command line. Unlike copts, these flags are added for the target and every target that depends on it, so use this attribute with caution. It is preferred that you add defines directly to copts, only using this feature in the rare case that a library needs to propagate a symbol up to those that depend on it.
List of stringsoptional[]
linkoptsAdditional linker options that should be passed to clang. These strings are subject to $(location ...) expansion.List of stringsoptional[]
mallocOverride the default dependency on malloc.

By default, Swift binaries are linked against @bazel_tools//tools/cpp:malloc", which is an empty library and the resulting binary will use libc's malloc. This label must refer to a cc_library rule.
Labeloptional"@bazel_tools//tools/cpp:malloc"
module_nameThe name of the Swift module being built.

If left unspecified, the module name will be computed based on the target's build label, by stripping the leading // and replacing /, :, and other non-identifier characters with underscores.
Stringoptional""
package_nameThe semantic package of the Swift target being built. Targets with the same package_name can access APIs using the 'package' access control modifier in Swift 5.9+.Stringoptional""
pluginsA list of swift_compiler_plugin targets that should be loaded by the compiler when compiling this module and any modules that directly depend on it.List of labelsoptional[]
stampEnable or disable link stamping; that is, whether to encode build information into the binary. Possible values are:

* stamp = 1: Stamp the build information into the binary. Stamped binaries are only rebuilt when their dependencies change. Use this if there are tests that depend on the build information.

* stamp = 0: Always replace build information by constant values. This gives good build result caching.

* stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.
Integeroptional0
swiftc_inputsAdditional files that are referenced using $(location ...) in attributes that support location expansion.List of labelsoptional[]

swift_compiler_plugin_import

swift_compiler_plugin_import(name, executable, module_names)

Allows for a Swift compiler plugin to be loaded from a prebuilt executable or some other binary-propagating rule, instead of building the plugin from source using swift_compiler_plugin.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
executableThe compiler plugin executable that will be passed to the Swift compiler when compiling any modules that depend on the plugin. This attribute may refer directly to an executable binary or to another rule that produces an executable binary.Labelrequired
module_namesThe list of names of Swift modules in the plugin executable that provide implementations of plugin types, which the compiler uses to look up their implementations.List of stringsrequired

swift_cross_import_overlay

swift_cross_import_overlay(name, deps, bystanding_module, bystanding_module_name, declaring_module,
                           declaring_module_name, swiftoverlay)

Declares a cross-import overlay that will be automatically added as a dependency by the toolchain if its declaring and bystanding modules are both imported.

Since Bazel requires the dependency graph to be explicit, cross-import overlays do not work correctly when the Swift compiler attempts to import them automatically when they aren't represented in the graph. Users can explicitly depend on the cross-import overlay module, but this is unsatisfying because there is no single import declaration in the source code that indicates what needs to be depended on.

To address this, the toolchain owner can define a swift_cross_import_overlay target for each cross-import overlay that they wish to support and set them as cross_import_overlays on the toolchain. During Swift compilation analysis, the direct dependencies will be scanned and if any pair of dependencies matches a cross-import overlay defined by the toolchain, the overlay module will be automatically injected as a dependency as well.

NOTE: This rule and its associated APIs only exists to support cross-import overlays already defined by Apple's SDKs. Since cross-import overlays are not a public feature of the compiler and its design and implementation may change in the future, this rule is not recommended for other widespread use.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA non-empty list of targets representing modules that should be passed as dependencies when a target depends on both declaring_module and bystanding_module.List of labelsrequired
bystanding_moduleA label for the target representing the second of the two modules (the other being declaring_module) that must be imported for the cross-import overlay modules to be imported. It is completely passive in the cross-import process, having no definition with or other association to either the declaring module or the cross-import modules.Labelrequired
bystanding_module_nameThe name of the bystanding module from the target specified by the bystanding_module attribute. This is inferred if bystanding_module only exports a single direct module; this name must be specified if bystanding_module exports more than one.Stringoptional""
declaring_moduleA label for the target representing the first of the two modules (the other being bystanding_module) that must be imported for the cross-import overlay modules to be imported. This is the module that contains the .swiftcrossimport overlay definition that connects it to the bystander and to the overlay modules.Labelrequired
declaring_module_nameThe name of the declaring module from the target specified by the declaring_module attribute. This is inferred if declaring_module only exports a single direct module; this name must be specified if declaring_module exports more than one.Stringoptional""
swiftoverlayThe path to the SDK .swiftoverlay file that declares this cross-import.Stringrequired

swift_feature_allowlist

swift_feature_allowlist(name, aspect_ids, managed_features, packages)

Limits the ability to request or disable certain features to a set of packages (and possibly subpackages) in the workspace.

A Swift toolchain target can reference any number (zero or more) of swift_feature_allowlist targets. The features managed by these allowlists may overlap. For some package P, a feature is allowed to be used by targets in that package if P matches the packages patterns in all of the allowlists that manage that feature.

A feature that is not managed by any allowlist is allowed to be used by any package.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
aspect_idsA list of strings representing the identifiers of aspects that are allowed to enable/disable the features in managed_features, even when the aspect is applied to packages not covered by the packages attribute.

Aspect identifiers are each expected to be of the form <.bzl file label>%<aspect top-level name> (i.e., the form one would use if invoking it from the command line, as described at https://bazel.build/extending/aspects#invoking_the_aspect_using_the_command_line).
List of stringsoptional[]
managed_featuresA list of feature strings that are permitted to be specified by the targets in the packages matched by the packages attribute or an aspect whose name matches the aspect_ids attribute (in any package). This list may include both feature names and/or negations (a name with a leading -); a regular feature name means that the matching targets/aspects may explicitly request that the feature be enabled, and a negated feature means that the target may explicitly request that the feature be disabled.

For example, managed_features = ["foo", "-bar"] means that targets in the allowlist's packages/aspects may request that feature "foo" be enabled and that feature "bar" be disabled.
List of stringsoptional[]
packagesA list of strings representing packages (possibly recursive) whose targets are allowed to enable/disable the features in managed_features. Each package pattern is written in the syntax used by the package_group function:

* //foo/bar: Targets in the package //foo/bar but not in subpackages.

* //foo/bar/...: Targets in the package //foo/bar and any of its subpackages.

* A leading - excludes packages that would otherwise have been included by the patterns in the list.

Exclusions always take priority over inclusions; order in the list is irrelevant.
List of stringsrequired

swift_import

swift_import(name, deps, data, archives, module_name, plugins, swiftdoc, swiftinterface,
             swiftmodule)

Allows for the use of Swift textual module interfaces and/or precompiled Swift modules as dependencies in other swift_library and swift_binary targets.

To use swift_import targets across Xcode versions and/or OS versions, it is required to use .swiftinterface files. These can be produced by the pre-built target if built with:

  • --features=swift.enable_library_evolution
  • --features=swift.emit_swiftinterface

If the pre-built target supports .private.swiftinterface files, these can be used instead of .swiftinterface files in the swiftinterface attribute.

To import pre-built Swift modules that use @_spi when using swiftinterface, the .private.swiftinterface files are required in order to build any code that uses the API marked with @_spi.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of targets that are dependencies of the target being built, which will be linked into that target.

If the Swift toolchain supports implementation-only imports (private_deps on swift_library), then targets in deps are treated as regular (non-implementation-only) imports that are propagated both to their direct and indirect (transitive) dependents.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
dataThe list of files needed by this target at runtime.

Files and targets named in the data attribute will appear in the *.runfiles area of this target, if it has one. This may include data files needed by a binary or library, or other programs needed by it.
List of labelsoptional[]
archivesThe list of .a or .lo files provided to Swift targets that depend on this target.List of labelsoptional[]
module_nameThe name of the module represented by this target.Stringrequired
pluginsA list of swift_compiler_plugin targets that should be loaded by the compiler when compiling any modules that directly depend on this target.List of labelsoptional[]
swiftdocThe .swiftdoc file provided to Swift targets that depend on this target.LabeloptionalNone
swiftinterfaceThe .swiftinterface file that defines the module interface for this target. May not be specified if swiftmodule is specified.LabeloptionalNone
swiftmoduleThe .swiftmodule file provided to Swift targets that depend on this target. May not be specified if swiftinterface is specified.LabeloptionalNone

swift_interop_hint

swift_interop_hint(name, exclude_hdrs, module_map, module_name, suppressed)

Defines an aspect hint that associates non-Swift BUILD targets with additional information required for them to be imported by Swift.

Some build rules, such as objc_library, support interoperability with Swift simply by depending on them; a module map is generated automatically. This is for convenience, because the common case is that most objc_library targets contain code that is compatible (i.e., capable of being imported) by Swift.

For other rules, like cc_library, additional information must be provided to indicate that a particular target is compatible with Swift. This is done using the aspect_hints attribute and the swift_interop_hint rule.

If you want to import a non-Swift, non-Objective-C target into Swift using the module name that is automatically derived from the BUILD label, there is no need to declare an instance of swift_interop_hint. A canonical one that requests module name derivation has been provided in @rules_swift//swift:auto_module. Simply add it to the aspect_hints of the target you wish to import:

# //my/project/BUILD
cc_library(
    name = "somelib",
    srcs = ["somelib.c"],
    hdrs = ["somelib.h"],
    aspect_hints = ["@rules_swift//swift:auto_module"],
)

When this cc_library is a dependency of a Swift target, a module map will be generated for it. In this case, the module's name would be my_project_somelib.

Using an explicit module name

If you need to provide an explicit name for the module (for example, if it is part of a third-party library that expects to be imported with a specific name), then you can declare your own swift_interop_hint target to define the name:

# //my/project/BUILD
cc_library(
    name = "somelib",
    srcs = ["somelib.c"],
    hdrs = ["somelib.h"],
    aspect_hints = [":somelib_swift_interop"],
)

swift_interop_hint(
    name = "somelib_swift_interop",
    module_name = "CSomeLib",
)

When this cc_library is a dependency of a Swift target, a module map will be generated for it with the module name CSomeLib.

Using a custom module map

In rare cases, the automatically generated module map may not be suitable. For example, a Swift module may depend on a C module that defines specific submodules, and this is not handled by the Swift build rules. In this case, you can provide the module map file using the module_map attribute.

When setting the module_map attribute, module_name must also be set to the name of the desired top-level module; it cannot be omitted.

# //my/project/BUILD
cc_library(
    name = "somelib",
    srcs = ["somelib.c"],
    hdrs = ["somelib.h"],
    aspect_hints = [":somelib_swift_interop"],
)

swift_interop_hint(
    name = "somelib_swift_interop",
    module_map = "module.modulemap",
    module_name = "CSomeLib",
)

Suppressing a module

As mentioned above, objc_library and other Objective-C targets generate modules by default, without an explicit hint, for convenience. In some situations, this behavior may not be desirable. For example, an objc_library might contain only Objective-C++ code in its headers that would not be possible to import into Swift at all.

When building with implicit modules, this is not typically an issue because the module map would only be used if Swift code tried to import it (although it does create useless actions and compiler inputs during the build). When building with explicit modules, however, Bazel needs to know which targets represent modules that it can compile and which do not.

In these cases, there is no need to declare an instance of swift_interop_hint. A canonical one that suppresses module generation has been provided in @rules_swift//swift:no_module. Simply add it to the aspect_hints of the target whose module you wish to suppress:

# //my/project/BUILD
objc_library(
    name = "somelib",
    srcs = ["somelib.mm"],
    hdrs = ["somelib.h"],
    aspect_hints = ["@rules_swift//swift:no_module"],
)

When this objc_library is a dependency of a Swift target, no module map or explicit module will be generated for it, nor will any Swift information from its transitive dependencies be propagated.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
exclude_hdrsA list of header files that should be excluded from the Clang module generated for the target to which this hint is applied. This allows a target to exclude a subset of a library's headers specifically from the Swift module map without removing them from the library completely, which can be useful if some headers are not Swift-compatible but are still needed by other sources in the library or by non-Swift dependents.

This attribute may only be specified if a custom module_map is not provided. Setting both attributes is an error.
List of labelsoptional[]
module_mapAn optional custom .modulemap file that defines the Clang module for the headers in the target to which this hint is applied.

If this attribute is omitted, a module map will be automatically generated based on the headers in the hinted target.

If this attribute is provided, then module_name must also be provided and match the name of the desired top-level module in the .modulemap file. (A single .modulemap file may define multiple top-level modules.)
LabeloptionalNone
module_nameThe name that will be used to import the hinted module into Swift.

If left unspecified, the module name will be computed based on the hinted target's build label, by stripping the leading // and replacing /, :, and other non-identifier characters with underscores.
Stringoptional""
suppressedIf True, the hinted target should suppress any module that it would otherwise generate.BooleanoptionalFalse

swift_library

swift_library(name, deps, srcs, data, always_include_developer_search_paths, alwayslink, copts,
              defines, generated_header_name, generates_header, library_evolution, linkopts,
              linkstatic, module_name, package_name, plugins, private_deps, swiftc_inputs)

Compiles and links Swift code into a static library and Swift module.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of targets that are dependencies of the target being built, which will be linked into that target.

If the Swift toolchain supports implementation-only imports (private_deps on swift_library), then targets in deps are treated as regular (non-implementation-only) imports that are propagated both to their direct and indirect (transitive) dependents.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
srcsA list of .swift source files that will be compiled into the library.

Except in very rare circumstances, a Swift source file should only appear in a single swift_* target. Adding the same source file to multiple swift_* targets can lead to binary bloat and/or symbol collisions. If specific sources need to be shared by multiple targets, consider factoring them out into their own swift_library instead.
List of labelsrequired
dataThe list of files needed by this target at runtime.

Files and targets named in the data attribute will appear in the *.runfiles area of this target, if it has one. This may include data files needed by a binary or library, or other programs needed by it.
List of labelsoptional[]
always_include_developer_search_pathsIf True, the developer framework search paths will be added to the compilation command. This enables a Swift module to access XCTest without having to mark the target as testonly = True.BooleanoptionalFalse
alwayslinkIf False, any binary that depends (directly or indirectly) on this Swift module will only link in all the object files for the files listed in srcs when there is a direct symbol reference.

Swift protocol conformances don't create linker references. Likewise, if the Swift code has Objective-C classes/methods, their usage does not always result in linker references.

"All the object files" for this module is also somewhat fuzzy. Unlike C, C++, and Objective-C, where each source file results in a .o file; for Swift the number of .o files depends on the compiler options (-wmo/-whole-module-optimization, -num-threads). That makes relying on linker reference more fragile, and any individual .swift file in srcs may/may not get picked up based on the linker references to other files that happen to get batched into a single .o by the compiler options used.

Swift Package Manager always passes the individual .o files to the linker instead of using intermediate static libraries, so it effectively is the same as alwayslink = True.

Note that by default, this value will default to True. But if the swift.enable_embedded feature is on, this value will be automatically overridden to False, as the swift features that cause -force_load to be required (such as reflection) are not available in that mode.
BooleanoptionalTrue
coptsAdditional compiler options that should be passed to swiftc. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
definesA list of defines to add to the compilation command line.

Note that unlike C-family languages, Swift defines do not have values; they are simply identifiers that are either defined or undefined. So strings in this list should be simple identifiers, not name=value pairs.

Each string is prepended with -D and added to the command line. Unlike copts, these flags are added for the target and every target that depends on it, so use this attribute with caution. It is preferred that you add defines directly to copts, only using this feature in the rare case that a library needs to propagate a symbol up to those that depend on it.
List of stringsoptional[]
generated_header_nameThe name of the generated Objective-C interface header. This name must end with a .h extension and cannot contain any path separators.

If this attribute is not specified, then the default behavior is to name the header ${target_name}-Swift.h.

This attribute is ignored if the toolchain does not support generating headers.
Stringoptional""
generates_headerIf True, an Objective-C header will be generated for this target, in the same build package where the target is defined. By default, the name of the header is ${target_name}-Swift.h; this can be changed using the generated_header_name attribute.

Targets should only set this attribute to True if they export Objective-C APIs. A header generated for a target that does not export Objective-C APIs will be effectively empty (except for a large amount of prologue and epilogue code) and this is generally wasteful because the extra file needs to be propagated in the build graph and, when explicit modules are enabled, extra actions must be executed to compile the Objective-C module for the generated header.
BooleanoptionalFalse
library_evolutionIndicates whether the Swift code should be compiled with library evolution mode enabled.

This attribute should be used to compile a module that will be distributed as part of a client-facing (non-implementation-only) module in a library or framework that will be distributed for use outside of the Bazel build graph. Setting this to true will compile the module with the -library-evolution flag and emit a .swiftinterface file as one of the compilation outputs.
BooleanoptionalFalse
linkoptsAdditional linker options that should be passed to the linker for the binary that depends on this target. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
linkstaticIf True, the Swift module will be built for static linking. This will make all interfaces internal to the module that is being linked against and will inform the consuming module that the objects will be locally available (which may potentially avoid a PLT relocation). Set to False to build a .so or .dll.BooleanoptionalTrue
module_nameThe name of the Swift module being built.

If left unspecified, the module name will be computed based on the target's build label, by stripping the leading // and replacing /, :, and other non-identifier characters with underscores.
Stringoptional""
package_nameThe semantic package of the Swift target being built. Targets with the same package_name can access APIs using the 'package' access control modifier in Swift 5.9+.Stringoptional""
pluginsA list of swift_compiler_plugin targets that should be loaded by the compiler when compiling this module and any modules that directly depend on it.List of labelsoptional[]
private_depsA list of targets that are implementation-only dependencies of the target being built. Libraries/linker flags from these dependencies will be propagated to dependent for linking, but artifacts/flags required for compilation (such as .swiftmodule files, C headers, and search paths) will not be propagated.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
swiftc_inputsAdditional files that are referenced using $(location ...) in attributes that support location expansion.List of labelsoptional[]

swift_library_group

swift_library_group(name, deps)

Groups Swift compatible libraries (e.g. swift_library and objc_library). The target can be used anywhere a swift_library can be used. It behaves similar to source-less {cc,obj}_library targets.

A new module isn't created for this target, you need to import the grouped libraries directly.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of targets that should be included in the group. Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]

swift_module_mapping

swift_module_mapping(name, aliases)

Defines a set of module aliases that will be passed to the Swift compiler.

This rule defines a mapping from original module names to aliased names. This is useful if you are building a library or framework for external use and want to ensure that dependencies do not conflict with other versions of the same library that another framework or the client may use.

To use this feature, first define a swift_module_mapping target that lists the aliases you need:

# //some/package/BUILD

swift_library(
    name = "Utils",
    srcs = [...],
    module_name = "Utils",
)

swift_library(
    name = "Framework",
    srcs = [...],
    module_name = "Framework",
    deps = [":Utils"],
)

swift_module_mapping(
    name = "mapping",
    aliases = {
        "Utils": "GameUtils",
    },
)

Then, pass the label of that target to Bazel using the --@rules_swift//swift:module_mapping build flag:

bazel build //some/package:Framework \
    --@rules_swift//swift:module_mapping=//some/package:mapping

When Utils is compiled, it will be given the module name GameUtils instead. Then, when Framework is compiled, it will import GameUtils anywhere that the source asked to import Utils.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
aliasesA dictionary that remaps the names of Swift modules.

Each key in the dictionary is the name of a module as it is written in source code. The corresponding value is the replacement module name to use when compiling it and/or any modules that depend on it.
Dictionary: String -> Stringrequired

swift_module_mapping_test

swift_module_mapping_test(name, deps, exclude, mapping)

Validates that a swift_module_mapping target covers all the modules in the transitive closure of a list of dependencies.

If you are building a static library or framework for external distribution and you are using swift_module_mapping to rename some of the modules used by your implementation, this rule will detect if any of your dependencies have taken on a new dependency that you need to add to the mapping (otherwise, its symbols would leak into your library with their original names).

When executed, this test will collect the names of all Swift modules in the transitive closure of deps. System modules and modules whose names are listed in the exclude attribute are omitted. Then, the test will fail if any of the remaining modules collected are not present in the aliases of the swift_module_mapping target specified by the mapping attribute.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of Swift targets whose transitive closure will be validated against the swift_module_mapping target specified by mapping.List of labelsrequired
excludeA list of module names that may be in the transitive closure of deps but are not required to be covered by mapping.List of stringsoptional[]
mappingThe label of a swift_module_mapping target against which the transitive closure of deps will be validated.Labelrequired

swift_overlay

swift_overlay(name, deps, srcs, always_include_developer_search_paths, alwayslink, copts, defines,
              library_evolution, linkopts, linkstatic, package_name, plugins, private_deps,
              swiftc_inputs)

A Swift overlay that sits on top of a C/Objective-C library, allowing an author of a C/Objective-C library to create additional Swift-specific APIs that are automatically available when a Swift target depends on their C/Objective-C library.

The Swift overlay will only be compiled when other Swift targets depend on the original library that uses the overlay; non-Swift clients depending on the original library will not cause the Swift overlay code to be built or linked. This is done to retain optimium build performance and binary size for non-Swift clients. For this reason, swift_overlay is not a general purpose mechanism for creating mixed-language modules; swift_overlay does not support generation of an Objective-C header.

The swift_overlay rule does not perform any compilation of its own. Instead, it must be placed in the aspect_hints attribute of another rule such as objc_library or cc_library. For example,

objc_library(
    name = "MyModule",
    srcs = ["MyModule.m"],
    hdrs = ["MyModule.h"],
    aspect_hints = [":MyModule_overlay"],
    deps = [...],
)

swift_overlay(
    name = "MyModule_overlay",
    srcs = ["MyModule.swift"],
    deps = [...],
)

When some other Swift target, such as a swift_library, depends on MyModule, the Swift code in MyModule_overlay will be compiled into the same module. Therefore, when that library imports MyModule, it will see the APIs from the objc_library and the swift_overlay as a single combined module.

When writing a Swift overlay, the Swift code must do a re-exporting import of its own module in order to access the C/Objective-C APIs; they are not available automatically. Continuing the example above, any Swift sources that want to use or extend the API from the C/Objective-C side of the module would need to write the following:

@_exported import MyModule

The swift_overlay rule supports all the same attributes as swift_library, except for the following:

  • module_name is not supported because the overlay inherits the same module name as the target it is attached to.
  • generates_header and generated_header_name are not supported because it is assumed that the overlay is pure Swift code that does not export any APIs that would be of interest to C/Objective-C clients.

Aside from its module name and its underlying C/Objective-C module dependency, swift_overlay does not inherit anything else from its associated target. If the swift_overlay imports any modules other than its C/Objective-C side, the overlay target must explicitly depend on them as well. This means that an overlay can have a different set of dependencies than the underlying module, if desired.

There is a tight coupling between a Swift overlay and the C/Objective-C module to which it is being applied, so a specific swift_overlay target should only be referenced by the aspect_hints of a single objc_library or cc_library target. Referencing a swift_overlay from multiple targets' aspect_hints is almost always an anti-pattern.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of targets that are dependencies of the target being built, which will be linked into that target.

If the Swift toolchain supports implementation-only imports (private_deps on swift_library), then targets in deps are treated as regular (non-implementation-only) imports that are propagated both to their direct and indirect (transitive) dependents.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
srcsA list of .swift source files that will be compiled into the library.

Except in very rare circumstances, a Swift source file should only appear in a single swift_* target. Adding the same source file to multiple swift_* targets can lead to binary bloat and/or symbol collisions. If specific sources need to be shared by multiple targets, consider factoring them out into their own swift_library instead.
List of labelsrequired
always_include_developer_search_pathsIf True, the developer framework search paths will be added to the compilation command. This enables a Swift module to access XCTest without having to mark the target as testonly = True.BooleanoptionalFalse
alwayslinkIf False, any binary that depends (directly or indirectly) on this Swift module will only link in all the object files for the files listed in srcs when there is a direct symbol reference.

Swift protocol conformances don't create linker references. Likewise, if the Swift code has Objective-C classes/methods, their usage does not always result in linker references.

"All the object files" for this module is also somewhat fuzzy. Unlike C, C++, and Objective-C, where each source file results in a .o file; for Swift the number of .o files depends on the compiler options (-wmo/-whole-module-optimization, -num-threads). That makes relying on linker reference more fragile, and any individual .swift file in srcs may/may not get picked up based on the linker references to other files that happen to get batched into a single .o by the compiler options used.

Swift Package Manager always passes the individual .o files to the linker instead of using intermediate static libraries, so it effectively is the same as alwayslink = True.

Note that by default, this value will default to True. But if the swift.enable_embedded feature is on, this value will be automatically overridden to False, as the swift features that cause -force_load to be required (such as reflection) are not available in that mode.
BooleanoptionalTrue
coptsAdditional compiler options that should be passed to swiftc. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
definesA list of defines to add to the compilation command line.

Note that unlike C-family languages, Swift defines do not have values; they are simply identifiers that are either defined or undefined. So strings in this list should be simple identifiers, not name=value pairs.

Each string is prepended with -D and added to the command line. Unlike copts, these flags are added for the target and every target that depends on it, so use this attribute with caution. It is preferred that you add defines directly to copts, only using this feature in the rare case that a library needs to propagate a symbol up to those that depend on it.
List of stringsoptional[]
library_evolutionIndicates whether the Swift code should be compiled with library evolution mode enabled.

This attribute should be used to compile a module that will be distributed as part of a client-facing (non-implementation-only) module in a library or framework that will be distributed for use outside of the Bazel build graph. Setting this to true will compile the module with the -library-evolution flag and emit a .swiftinterface file as one of the compilation outputs.
BooleanoptionalFalse
linkoptsAdditional linker options that should be passed to the linker for the binary that depends on this target. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
linkstaticIf True, the Swift module will be built for static linking. This will make all interfaces internal to the module that is being linked against and will inform the consuming module that the objects will be locally available (which may potentially avoid a PLT relocation). Set to False to build a .so or .dll.BooleanoptionalTrue
package_nameThe semantic package of the Swift target being built. Targets with the same package_name can access APIs using the 'package' access control modifier in Swift 5.9+.Stringoptional""
pluginsA list of swift_compiler_plugin targets that should be loaded by the compiler when compiling this module and any modules that directly depend on it.List of labelsoptional[]
private_depsA list of targets that are implementation-only dependencies of the target being built. Libraries/linker flags from these dependencies will be propagated to dependent for linking, but artifacts/flags required for compilation (such as .swiftmodule files, C headers, and search paths) will not be propagated.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
swiftc_inputsAdditional files that are referenced using $(location ...) in attributes that support location expansion.List of labelsoptional[]

swift_package_configuration

swift_package_configuration(name, configured_features, packages)

A compilation configuration to apply to the Swift targets in a set of packages.

A Swift toolchain target can reference any number (zero or more) of swift_package_configuration targets. When the compilation action for a target is being configured, those package configurations will be applied if the target's label is included by the package specifications in the configuration.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
configured_featuresA list of feature strings that will be applied by default to targets in the packages matched by the packages attribute, as if they had been specified by the package(features = ...) rule in the BUILD file.

This list may include both feature names and/or negations (a name with a leading -); a regular feature name means that the targets in the matching packages will have the feature enabled, and a negated feature means that the target will have the feature disabled.

For example, configured_features = ["foo", "-bar"] means that targets in the configuration's packages will have the feature "foo" enabled by default and the feature "bar" disabled by default.
List of stringsoptional[]
packagesA list of strings representing packages (possibly recursive) whose targets will have this package configuration applied. Each package pattern is written in the syntax used by the package_group function:

* //foo/bar: Targets in the package //foo/bar but not in subpackages.

* //foo/bar/...: Targets in the package //foo/bar and any of its subpackages.

* A leading - excludes packages that would otherwise have been included by the patterns in the list.

Exclusions always take priority over inclusions; order in the list is irrelevant.
List of stringsrequired

swift_proto_compiler

swift_proto_compiler(name, deps, bundled_proto_paths, plugin, plugin_name, plugin_option_allowlist,
                     plugin_options, protoc, suffixes)

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList of targets providing SwiftInfo and CcInfo. Added as implicit dependencies for any swift_proto_library using this compiler. Typically, these are Well Known Types and proto runtime libraries.List of labelsoptional[]
bundled_proto_pathsList of proto paths for which to skip generation because they're built into the modules imported by the generated Swift proto code, e.g., SwiftProtobuf.List of stringsoptional["google/protobuf/any.proto", "google/protobuf/api.proto", "google/protobuf/descriptor.proto", "google/protobuf/duration.proto", "google/protobuf/empty.proto", "google/protobuf/field_mask.proto", "google/protobuf/source_context.proto", "google/protobuf/struct.proto", "google/protobuf/timestamp.proto", "google/protobuf/type.proto", "google/protobuf/wrappers.proto"]
pluginA proto compiler plugin executable binary.

For example: "//tools/protoc_wrapper:protoc-gen-grpc-swift" "//tools/protoc_wrapper:ProtoCompilerPlugin"
Labelrequired
plugin_nameName of the proto compiler plugin passed to protoc.

For example:

protoc     --plugin=protoc-gen-NAME=path/to/plugin/binary


This name will be used to prefix the option and output directory arguments. E.g.:

protoc     --plugin=protoc-gen-NAME=path/to/mybinary     --NAME_out=OUT_DIR     --NAME_opt=Visibility=Public


See the protobuf API reference for more information.
Stringrequired
plugin_option_allowlistAllowlist of options allowed by the plugin. This is used to filter out any irrelevant plugin options passed down to the compiler from the library, which is especially useful when using multiple plugins in combination like GRPC and SwiftProtobuf.List of stringsrequired
plugin_optionsDictionary of plugin options passed to the plugin.

These are prefixed with the plugin_name + "_opt". E.g.:

plugin_name = "swift"
plugin_options = {
"Visibility": "Public",
"FileNaming": "FullPath",
}


Would be passed to protoc as:

protoc     --plugin=protoc-gen-NAME=path/to/plugin/binary     --NAME_opt=Visibility=Public     --NAME_opt=FileNaming=FullPath
Dictionary: String -> Stringrequired
protoc-LabeloptionalNone
suffixesSuffix used for Swift files generated by the plugin from protos.

E.g.

foo.proto => foo.pb.swift
foo_service.proto => foo.grpc.swift


Each compiler target should configure this based on the suffix applied to the generated files.
List of stringsrequired

swift_proto_library

swift_proto_library(name, deps, srcs, data, additional_compiler_deps, additional_compiler_info,
                    always_include_developer_search_paths, alwayslink, compilers, copts, defines,
                    generated_header_name, generates_header, library_evolution, linkopts, linkstatic,
                    module_name, package_name, plugins, protos, swiftc_inputs)

Generates a Swift static library from one or more targets producing ProtoInfo.

load("@protobuf//bazel:proto_library.bzl", "proto_library")
load("//proto:swift_proto_library.bzl", "swift_proto_library")

proto_library(
    name = "foo",
    srcs = ["foo.proto"],
)

swift_proto_library(
    name = "foo_swift",
    protos = [":foo"],
)

If your protos depend on protos from other targets, add dependencies between the swift_proto_library targets which mirror the dependencies between the proto targets.

load("@protobuf//bazel:proto_library.bzl", "proto_library")
load("//proto:swift_proto_library.bzl", "swift_proto_library")

proto_library(
    name = "bar",
    srcs = ["bar.proto"],
    deps = [":foo"],
)

swift_proto_library(
    name = "bar_swift",
    protos = [":bar"],
    deps = [":foo_swift"],
)

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of targets that are dependencies of the target being built, which will be linked into that target.

If the Swift toolchain supports implementation-only imports (private_deps on swift_library), then targets in deps are treated as regular (non-implementation-only) imports that are propagated both to their direct and indirect (transitive) dependents.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
srcsA list of .swift source files that will be compiled into the library.

Except in very rare circumstances, a Swift source file should only appear in a single swift_* target. Adding the same source file to multiple swift_* targets can lead to binary bloat and/or symbol collisions. If specific sources need to be shared by multiple targets, consider factoring them out into their own swift_library instead.
List of labelsoptional[]
dataThe list of files needed by this target at runtime.

Files and targets named in the data attribute will appear in the *.runfiles area of this target, if it has one. This may include data files needed by a binary or library, or other programs needed by it.
List of labelsoptional[]
additional_compiler_depsList of additional dependencies required by the generated Swift code at compile time, whose SwiftProtoInfo will be ignored.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
additional_compiler_infoDictionary of additional information passed to the compiler targets. See the documentation of the respective compiler rules for more information on which fields are accepted and how they are used.Dictionary: String -> Stringoptional{}
always_include_developer_search_pathsIf True, the developer framework search paths will be added to the compilation command. This enables a Swift module to access XCTest without having to mark the target as testonly = True.BooleanoptionalFalse
alwayslinkIf False, any binary that depends (directly or indirectly) on this Swift module will only link in all the object files for the files listed in srcs when there is a direct symbol reference.

Swift protocol conformances don't create linker references. Likewise, if the Swift code has Objective-C classes/methods, their usage does not always result in linker references.

"All the object files" for this module is also somewhat fuzzy. Unlike C, C++, and Objective-C, where each source file results in a .o file; for Swift the number of .o files depends on the compiler options (-wmo/-whole-module-optimization, -num-threads). That makes relying on linker reference more fragile, and any individual .swift file in srcs may/may not get picked up based on the linker references to other files that happen to get batched into a single .o by the compiler options used.

Swift Package Manager always passes the individual .o files to the linker instead of using intermediate static libraries, so it effectively is the same as alwayslink = True.

Note that by default, this value will default to True. But if the swift.enable_embedded feature is on, this value will be automatically overridden to False, as the swift features that cause -force_load to be required (such as reflection) are not available in that mode.
BooleanoptionalTrue
compilersOne or more swift_proto_compiler targets (or targets producing SwiftProtoCompilerInfo), from which the Swift protos will be generated.List of labelsoptional["@rules_swift//proto/compilers:swift_proto"]
coptsAdditional compiler options that should be passed to swiftc. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
definesA list of defines to add to the compilation command line.

Note that unlike C-family languages, Swift defines do not have values; they are simply identifiers that are either defined or undefined. So strings in this list should be simple identifiers, not name=value pairs.

Each string is prepended with -D and added to the command line. Unlike copts, these flags are added for the target and every target that depends on it, so use this attribute with caution. It is preferred that you add defines directly to copts, only using this feature in the rare case that a library needs to propagate a symbol up to those that depend on it.
List of stringsoptional[]
generated_header_nameThe name of the generated Objective-C interface header. This name must end with a .h extension and cannot contain any path separators.

If this attribute is not specified, then the default behavior is to name the header ${target_name}-Swift.h.

This attribute is ignored if the toolchain does not support generating headers.
Stringoptional""
generates_headerIf True, an Objective-C header will be generated for this target, in the same build package where the target is defined. By default, the name of the header is ${target_name}-Swift.h; this can be changed using the generated_header_name attribute.

Targets should only set this attribute to True if they export Objective-C APIs. A header generated for a target that does not export Objective-C APIs will be effectively empty (except for a large amount of prologue and epilogue code) and this is generally wasteful because the extra file needs to be propagated in the build graph and, when explicit modules are enabled, extra actions must be executed to compile the Objective-C module for the generated header.
BooleanoptionalFalse
library_evolutionIndicates whether the Swift code should be compiled with library evolution mode enabled.

This attribute should be used to compile a module that will be distributed as part of a client-facing (non-implementation-only) module in a library or framework that will be distributed for use outside of the Bazel build graph. Setting this to true will compile the module with the -library-evolution flag and emit a .swiftinterface file as one of the compilation outputs.
BooleanoptionalFalse
linkoptsAdditional linker options that should be passed to the linker for the binary that depends on this target. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
linkstaticIf True, the Swift module will be built for static linking. This will make all interfaces internal to the module that is being linked against and will inform the consuming module that the objects will be locally available (which may potentially avoid a PLT relocation). Set to False to build a .so or .dll.BooleanoptionalTrue
module_nameThe name of the Swift module being built.

If left unspecified, the module name will be computed based on the target's build label, by stripping the leading // and replacing /, :, and other non-identifier characters with underscores.
Stringoptional""
package_nameThe semantic package of the Swift target being built. Targets with the same package_name can access APIs using the 'package' access control modifier in Swift 5.9+.Stringoptional""
pluginsA list of swift_compiler_plugin targets that should be loaded by the compiler when compiling this module and any modules that directly depend on it.List of labelsoptional[]
protosA list of proto_library targets (or targets producing ProtoInfo), from which the Swift source files should be generated.List of labelsoptional[]
swiftc_inputsAdditional files that are referenced using $(location ...) in attributes that support location expansion.List of labelsoptional[]

swift_proto_library_group

swift_proto_library_group(name, compiler, proto)

Generates a collection of Swift static library from a target producing ProtoInfo and its dependencies.

This rule is intended to facilitate migration from the deprecated swift proto library rules to the new ones. Unlike swift_proto_library which is a drop-in-replacement for swift_library, this rule uses an aspect over the direct proto library dependency and its transitive dependencies, compiling each into a swift static library.

For example, in the following targets, the proto_library_group_swift_proto target only depends on package_2_proto target, and this transitively depends on package_1_proto.

When used as a dependency from a swift_library or swift_binary target, two modules generated from these proto library targets are visible.

Because these are derived from the proto library targets via an aspect, though, you cannot customize many of the attributes including the swift proto compiler targets or the module names. The module names are derived from the proto library names.

In this case, the module names are:

import examples_xplatform_proto_library_group_package_1_package_1_proto
import examples_xplatform_proto_library_group_package_2_package_2_proto

For this reason, we would encourage new consumers of the proto rules to use swift_proto_library when possible.

proto_library(
    name = "package_1_proto",
    srcs = glob(["*.proto"]),
    visibility = ["//visibility:public"],
)

...

proto_library(
    name = "package_2_proto",
    srcs = glob(["*.proto"]),
    visibility = ["//visibility:public"],
    deps = ["//examples/xplatform/proto_library_group/package_1:package_1_proto"],
)

...

swift_proto_library_group(
    name = "proto_library_group_swift_proto",
    proto = "//examples/xplatform/proto_library_group/package_2:package_2_proto",
)

...

swift_binary(
    name = "proto_library_group_example",
    srcs = ["main.swift"],
    deps = [
        ":proto_library_group_swift_proto",
    ],
)

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
compilerA swift_proto_compiler target (or target producing SwiftProtoCompilerInfo), from which the Swift protos will be generated.Labeloptional"@rules_swift//proto/compilers:swift_proto"
protoExactly one proto_library target (or target producing ProtoInfo), from which the Swift source files should be generated.Labelrequired

swift_test

swift_test(name, deps, srcs, data, additional_linker_inputs, copts, defines, discover_tests, env,
           env_inherit, linkopts, malloc, module_name, package_name, plugins, stamp, swiftc_inputs)

Compiles and links Swift code into an executable test target.

XCTest Test Discovery

By default, this rule performs test discovery that finds tests written with the XCTest framework and executes them automatically, without the user providing their own main entry point.

On Apple platforms, XCTest-style tests are automatically discovered and executed using the Objective-C runtime. To provide the same behavior on Linux, the swift_test rule performs its own scan for XCTest-style tests. In other words, you can write a single swift_test target that executes the same tests on either Linux or Apple platforms.

There are two approaches that one can take to write a swift_test that supports test discovery:

  1. Preferred approach: Write a swift_test target whose srcs contain your tests. In this mode, only these sources will be scanned for tests; direct dependencies will not be scanned.

  2. Write a swift_test target with no srcs. In this mode, all direct dependencies of the target will be scanned for tests; indirect dependencies will not be scanned. This approach is useful if you want to share tests with an Apple-specific test target like ios_unit_test.

See the documentation of the discover_tests attribute for more information about how this behavior affects the rule's outputs.

Test Bundles

The swift_test rule always produces a standard executable binary. This is true even when targeting macOS, where the typical practice is to use a Mach-O bundle binary. However, when targeting macOS, the executable binary is still generated inside a bundle-like directory structure: {name}.xctest/Contents/MacOS/{name}. This allows tests to still work if they contain logic that looks for the path to their bundle.

Test Filtering

swift_test supports Bazel's --test_filter flag on all platforms (i.e., Apple and Linux), which can be used to run only a subset of tests. The test filter can be a test name of the form ClassName/MethodName or a regular expression that matches names of that form.

For example,

  • --test_filter='ArrayTests/testAppend' would only run the test method testAppend in the ArrayTests class.

  • --test_filter='ArrayTests/test(App.*|Ins.*)' would run all test methods starting with testApp or testIns in the ArrayTests class.

Xcode Integration

If integrating with Xcode, the relative paths in test binaries can prevent the Issue navigator from working for test failures. To work around this, you can have the paths made absolute via swizzling by enabling the "apple.swizzle_absolute_xcttestsourcelocation" feature. You'll also need to set the BUILD_WORKSPACE_DIRECTORY environment variable in your scheme to the root of your workspace (i.e. $(SRCROOT)).

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsA list of targets that are dependencies of the target being built, which will be linked into that target.

If the Swift toolchain supports implementation-only imports (private_deps on swift_library), then targets in deps are treated as regular (non-implementation-only) imports that are propagated both to their direct and indirect (transitive) dependents.

Allowed kinds of dependencies are:

* swift_library (or anything propagating SwiftInfo)

* cc_library and objc_library (or anything propagating CcInfo)
List of labelsoptional[]
srcsA list of .swift source files that will be compiled into the library.

Except in very rare circumstances, a Swift source file should only appear in a single swift_* target. Adding the same source file to multiple swift_* targets can lead to binary bloat and/or symbol collisions. If specific sources need to be shared by multiple targets, consider factoring them out into their own swift_library instead.
List of labelsoptional[]
dataThe list of files needed by this target at runtime.

Files and targets named in the data attribute will appear in the *.runfiles area of this target, if it has one. This may include data files needed by a binary or library, or other programs needed by it.
List of labelsoptional[]
additional_linker_inputsList of additional files needed by the linker.

These files will be passed to the linker when linking the binary target. Typically, these are linker scripts or other files referenced by linkopts.
List of labelsoptional[]
coptsAdditional compiler options that should be passed to swiftc. These strings are subject to $(location ...) and "Make" variable expansion.List of stringsoptional[]
definesA list of defines to add to the compilation command line.

Note that unlike C-family languages, Swift defines do not have values; they are simply identifiers that are either defined or undefined. So strings in this list should be simple identifiers, not name=value pairs.

Each string is prepended with -D and added to the command line. Unlike copts, these flags are added for the target and every target that depends on it, so use this attribute with caution. It is preferred that you add defines directly to copts, only using this feature in the rare case that a library needs to propagate a symbol up to those that depend on it.
List of stringsoptional[]
discover_testsDetermines whether or not tests are automatically discovered in the binary. The default value is True.

Tests are discovered in a platform-specific manner. On Apple platforms, they are found using the XCTest framework's XCTestSuite.default accessor, which uses the Objective-C runtime to dynamically discover tests. On non-Apple platforms, discovery uses symbol graphs generated from dependencies to find classes and methods written in XCTest's style.

If tests are discovered, then you should not provide your own main entry point in the swift_test binary; the test runtime provides the entry point for you. If you set this attribute to False, then you are responsible for providing your own main. This allows you to write tests that use a framework other than Apple's XCTest. The only requirement of such a test is that it terminate with a zero exit code for success or a non-zero exit code for failure.
BooleanoptionalTrue
envDictionary of environment variables that should be set during the test execution.Dictionary: String -> Stringoptional{}
env_inheritSpecifies additional environment variables to inherit from the external environment when the test is executed by bazel test.List of stringsoptional[]
linkoptsAdditional linker options that should be passed to clang. These strings are subject to $(location ...) expansion.List of stringsoptional[]
mallocOverride the default dependency on malloc.

By default, Swift binaries are linked against @bazel_tools//tools/cpp:malloc", which is an empty library and the resulting binary will use libc's malloc. This label must refer to a cc_library rule.
Labeloptional"@bazel_tools//tools/cpp:malloc"
module_nameThe name of the Swift module being built.

If left unspecified, the module name will be computed based on the target's build label, by stripping the leading // and replacing /, :, and other non-identifier characters with underscores.
Stringoptional""
package_nameThe semantic package of the Swift target being built. Targets with the same package_name can access APIs using the 'package' access control modifier in Swift 5.9+.Stringoptional""
pluginsA list of swift_compiler_plugin targets that should be loaded by the compiler when compiling this module and any modules that directly depend on it.List of labelsoptional[]
stampEnable or disable link stamping; that is, whether to encode build information into the binary. Possible values are:

* stamp = 1: Stamp the build information into the binary. Stamped binaries are only rebuilt when their dependencies change. Use this if there are tests that depend on the build information.

* stamp = 0: Always replace build information by constant values. This gives good build result caching.

* stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.
Integeroptional0
swiftc_inputsAdditional files that are referenced using $(location ...) in attributes that support location expansion.List of labelsoptional[]

universal_swift_compiler_plugin

universal_swift_compiler_plugin(name, plugin)

Wraps an existing swift_compiler_plugin target to produce a universal binary.

This is useful to allow sharing of caches between Intel and Apple Silicon Macs at the cost of building everything twice.

Example:

# The actual macro code, using SwiftSyntax, as usual.
swift_compiler_plugin(
    name = "Macros",
    srcs = glob(["Macros/*.swift"]),
    deps = [
        "@swift-syntax//:SwiftSyntax",
        "@swift-syntax//:SwiftCompilerPlugin",
        "@swift-syntax//:SwiftSyntaxMacros",
    ],
)

# Wrap your compiler plugin in this universal shim.
universal_swift_compiler_plugin(
    name = "Macros.universal",
    plugin = ":Macros",
)

# The library that defines the macro hook for use in your project, this
# references the universal_swift_compiler_plugin.
swift_library(
    name = "MacroLibrary",
    srcs = glob(["MacroLibrary/*.swift"]),
    plugins = [":Macros.universal"],
)

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
pluginTarget to generate a 'fat' binary from.Labelrequired

mixed_language_library

mixed_language_library(*, name, additional_objc_compiler_inputs,
                       always_include_developer_search_paths, alwayslink, clang_copts, clang_defines,
                       clang_deps, clang_srcs, data, enable_modules, hdrs, includes, linkopts,
                       module_map, module_name, non_arc_srcs, package_name, private_deps, sdk_dylibs,
                       sdk_frameworks, swift_copts, swift_defines, swift_plugins, swift_srcs,
                       swiftc_inputs, textual_hdrs, umbrella_header, weak_sdk_frameworks, deps,
                       **kwargs)

Creates a mixed language library from a Clang and Swift library target pair.

Note: In the future swift_library will support mixed-language libraries. Once that is the case, this macro will be deprecated.

PARAMETERS

NameDescriptionDefault Value
nameThe name of the target.none
additional_objc_compiler_inputsAdditional files that are referenced using $(location ...) in attributes that support location expansion.[]
always_include_developer_search_pathsIf True, the developer framework search paths will be added to the swift compilation command. This enables a Swift module to access XCTest without having to mark the target as testonly = True.False
alwayslinkIf true, any binary that depends (directly or indirectly) on this library will link in all the object files for the files listed in clang_srcs and swift_srcs, even if some contain no symbols referenced by the binary. This is useful if your code isn't explicitly called by code in the binary; for example, if you rely on runtime checks for protocol conformances added in extensions in the library but do not directly reference any other symbols in the object file that adds that conformance.False
clang_coptsThe compiler flags for the clang library. These will only be used for the clang library. If you want them to affect the swift library as well, you need to pass them with -Xcc in swift_copts.[]
clang_definesExtra clang -D flags to pass to the compiler. They should be in the form KEY=VALUE or simply KEY and are passed not only to the compiler for this target (as clang_copts are) but also to all dependers of this target. Subject to "Make variable" substitution and Bourne shell tokenization.[]
clang_depsA list of targets that are dependencies of only the clang library.[]
clang_srcsThe list of C, C++, Objective-C, or Objective-C++ sources for the clang library.none
dataThe list of files needed by this target at runtime.

Files and targets named in the data attribute will appear in the *.runfiles area of this target, if it has one. This may include data files needed by a binary or library, or other programs needed by it.
[]
enable_modulesEnables clang module support (via -fmodules). Setting this to True will allow you to @import system headers and other targets: @import UIKit; @import path_to_package_target;.False
hdrsThe list of C, C++, Objective-C, or Objective-C++ header files published by this library to be included by sources in dependent rules. This can't include umbrella_header.[]
includesList of #include/#import search paths to add to this target and all depending targets.[]
linkoptsExtra flags to pass to the linker.[]
module_mapA File representing an existing module map that should be used to represent the module, or None (the default) if the module map should be generated based on hdrs. If this argument is provided, then module_name must also be provided.

Warning: If a module map (whether provided here or not) is able to be found via an include path, it will result in duplicate module definition errors for downstream targets unless sandboxing or remote execution is used.
None
module_nameThe name of the Swift module being built.

If left unspecified, the module name will be computed based on the target's build label, by stripping the leading // and replacing /, :, and other non-identifier characters with underscores.
None
non_arc_srcsThe list of Objective-C files that are processed to create the library target that DO NOT use ARC. The files in this attribute are treated very similar to those in the clang_srcs attribute, but are compiled without ARC enabled.[]
package_nameThe semantic package of the Swift target being built. Targets with the same package_name can access APIs using the 'package' access control modifier in Swift 5.9+.None
private_depsA list of targets that are implementation-only dependencies of the target being built. Libraries/linker flags from these dependencies will be propagated to dependent for linking, but artifacts/flags required for compilation (such as .swiftmodule files, C headers, and search paths) will not be propagated.[]
sdk_dylibsA list of of SDK .dylib libraries to link with. For instance, "libz" or "libarchive". "libc++" is included automatically if the binary has any C++ or Objective-C++ sources in its dependency tree. When linking a binary, all libraries named in that binary's transitive dependency graph are used.[]
sdk_frameworksA list of SDK frameworks to link with (e.g. "AddressBook", "QuartzCore").

When linking a top level Apple binary, all SDK frameworks listed in that binary's transitive dependency graph are linked.
[]
swift_coptsThe compiler flags for the swift library.[]
swift_definesA list of Swift defines to add to the compilation command line.

Note that unlike C-family languages, Swift defines do not have values; they are simply identifiers that are either defined or undefined. So strings in this list should be simple identifiers, not name=value pairs.

Each string is prepended with -D and added to the command line. Unlike swift_copts, these flags are added for the target and every target that depends on it, so use this attribute with caution. It is preferred that you add defines directly to swift_copts, only using this feature in the rare case that a library needs to propagate a symbol up to those that depend on it.
[]
swift_pluginsA list of Swift plugins for the swift library.[]
swift_srcsThe sources for the swift library.none
swiftc_inputsAdditional files that are referenced using $(location ...) in attributes that support location expansion.[]
textual_hdrsThe list of C, C++, Objective-C, or Objective-C++ files that are included as headers by source files in this rule or by users of this library. Unlike hdrs, these will not be compiled separately from the sources.[]
umbrella_headerA File representing an existing umbrella header that should be used in the generated module map or is used in the custom module map, or None (the default) if the umbrella header should be generated based on hdrs. A symlink to this header is added to an include path such that #import <ModuleName/ModuleName.h> works for this and downstream targets.None
weak_sdk_frameworksA list of SDK frameworks to weakly link with. For instance, "MediaAccessibility". In difference to regularly linked SDK frameworks, symbols from weakly linked frameworks do not cause an error if they are not present at runtime.[]
depsA list of targets that are dependencies of the target being built.[]
kwargsAdditional arguments to pass to the underlying clang and swift library targets.none