docs

你正在阅读 v0.1.0 的文档。Nabi 0.1.0 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#Conditional Compilation

本页内容

One source tree often has to build in several shapes: per operating system, debug against release, with or without an optional feature. Nabi decides this at compile time with #[cfg(..)]. Code whose condition is false is removed right after parsing, as if it had never been written, so it costs nothing at run time and may even refer to names that do not exist in that build.

#Conditions

A condition is a flag, a key = "value" pair, or a combination of them with all(..), any(..) and not(..).

ConditionTrue when
target_os = "linux"Building for Linux ("macos", "windows", "wasi", "unknown" for the browser, ..)
target_arch = "aarch64"Building for that CPU ("x86_64", ..)
target_family = "unix"Unix-like targets ("windows", "wasm")
target_pointer_width = "64"64-bit targets
feature = "tls"The package's feature tls is enabled (chapter 18)
debug_assertionsBuilding at -O0 (the default for nabi run)
testBuilding for nabi test

target_* follow --target, so a cross build sees the target's values, not the host's.

#Where #[cfg] goes

#[cfg] attaches to items (functions, types, mod, use, const, static, impl blocks and their members) and also to the smaller pieces inside code: statements, match arms, struct fields, fields of a struct literal, and function parameters.

Built with -O2, the same file prints release build of demo and unsupported: the checks field, its initializer and the Trace arm are all gone.

A parameter with a false condition is removed from the signature, and calls pass only the remaining arguments. This lets an optional feature add a parameter without a second copy of the function.

nabi
fn connect(host: str, #[cfg(feature = "tls")] verify: bool) -> str {
    #[cfg(feature = "tls")]
    if verify { return f"{host} (verified)"; }
    host
}

// Without the `tls` feature, `connect` takes one argument.
println(connect("example.com"));
example.com

Closure parameters take no attributes.

#Two definitions, one build

To give a function a different body per platform, write it twice with conditions that exclude each other. Only one survives in any build; if both survive, it is the ordinary duplicate-definition error.

nabi
#[cfg(target_family = "windows")]
fn path_sep() -> str { "\\" }

#[cfg(not(target_family = "windows"))]
fn path_sep() -> str { "/" }

println(["usr", "local", "bin"].join(path_sep()));

On Linux and macOS this prints usr/local/bin.

A whole module can be conditional too. #[cfg(target_os = "linux")] mod linux; does not even read linux.nabi in other builds.

The compiler remembers what a condition removed. Calling something that exists only in another build is an error that says where it exists and how to guard the call:

error[E0046]: no method `pidfd` found for type `Child`
   = note: `pidfd` is only available on linux (`#[cfg(target_os = "linux")]`)
   = help: put the code that uses it under the same `#[cfg(target_os = "linux")]`

#OS-specific parts of std

The standard library splits the same way. What only some systems have lives in std::os::unix, os::linux and os::windows, and each exists only on its targets. Their extension traits are in the prelude there, so on Linux and macOS Command::new("sh").process_group(0) needs no use. On Windows the same call is an error that says where the method exists:

error[E0046]: no method `process_group` found for type `Command`
   = note: `process_group` is only available on unix (`#[cfg(target_family = "unix")]`)
   = help: put the code that uses it under the same `#[cfg(target_family = "unix")]`

So the code that uses it goes under the same condition:

nabi
use std::process::Command;

#[cfg(target_family = "unix")]
fn detached(cmd: Command) -> Command { cmd.process_group(0) }

#[cfg(not(target_family = "unix"))]
fn detached(cmd: Command) -> Command { cmd }

Raw OS handles for C live there too. as_raw_fd() (as_raw_handle() / as_raw_socket() on Windows) borrows the descriptor of a File, a socket or a child pipe: the value still owns it and closes it. into_raw_fd() (into_raw_handle() / into_raw_socket()) hands the descriptor over: the value is consumed and no longer closes it, so closing it is now up to you. unsafe from_raw_fd(fd) makes a value that owns fd again.

#cfg!: a compile-time bool

When both branches compile everywhere and only the choice differs, cfg!(..) is shorter. It is a constant bool, so the compiler drops the dead branch; unlike #[cfg], both sides must still type-check.

nabi
const DEBUG: bool = cfg!(debug_assertions);

let level = if cfg!(feature = "verbose") { 2 } else { 1 };
println(f"debug={DEBUG} level={level}");
debug=true level=1

#[cfg_attr(cond, attr)] attaches another attribute only when the condition holds, for example #[cfg_attr(test, derive(Debug))].

#Summary

  • #[cfg(..)] keeps or removes code at compile time. Conditions are key = "value", flags (test, debug_assertions) and all / any / not.
  • It attaches to items, fields, variants, statements, match arms, struct literal fields and parameters. A removed parameter disappears from the signature.
  • Write mutually exclusive definitions for per-platform bodies.
  • cfg!(..) is a constant bool for an ordinary if.
  • OS-specific std lives in std::os::{unix, linux, windows}; its extension traits are in the prelude on their targets.
  • feature = ".." conditions are set by the package's features, the subject of the next chapter.

#Further reading

Found a mistake? Edit this page on GitHub. Last updated