诊断属性
以下属性用于在编译期间控制或生成诊断消息。
Lint 检查属性
Lint 检查命名潜在不需要的编码模式,例如不可达代码或省略的文档。
Lint 属性 allow、expect、warn、deny 和 forbid 使用 MetaListPaths 语法指定 lint 名称列表,以更改属性应用到的实体的 lint 级别。
对于任何 lint 检查 C:
#[allow(C)]覆盖对C的检查,使违规行为不会被报告。
#[expect(C)]表示预期会发出 lintC。如果预期未满足,该属性将抑制C的发出或发出警告。
#[warn(C)]对C的违规发出警告,但继续编译。
#[deny(C)]在遇到C的违规后发出错误信号,
#[forbid(C)]与deny(C)相同,但也禁止之后更改 lint 级别,
Note
rustc支持的 lint 检查可以通过rustc -W help找到,以及它们的默认设置,并在 rustc 之书中记录。
#![allow(unused)]
fn main() {
pub mod m1 {
// Missing documentation is ignored here
#[allow(missing_docs)]
pub fn undocumented_one() -> i32 { 1 }
// Missing documentation signals a warning here
#[warn(missing_docs)]
pub fn undocumented_too() -> i32 { 2 }
// Missing documentation signals an error here
#[deny(missing_docs)]
pub fn undocumented_end() -> i32 { 3 }
}
}
Lint 属性可以覆盖先前属性指定的级别,只要该级别不尝试更改被禁止的 lint(deny 除外,它在 forbid 上下文中是允许的,但被忽略)。先前的属性是来自语法树中更高级别的属性,或来自与左到右源顺序中列出的同一实体上的先前属性。
此示例显示如何使用 allow 和 warn 来切换特定检查的开启和关闭:
#![allow(unused)]
fn main() {
#[warn(missing_docs)]
pub mod m2 {
#[allow(missing_docs)]
pub mod nested {
// Missing documentation is ignored here
pub fn undocumented_one() -> i32 { 1 }
// Missing documentation signals a warning here,
// despite the allow above.
#[warn(missing_docs)]
pub fn undocumented_two() -> i32 { 2 }
}
// Missing documentation signals a warning here
pub fn undocumented_too() -> i32 { 3 }
}
}
此示例显示如何使用 forbid 来禁止对该 lint 检查使用 allow 或 expect:
#![allow(unused)]
fn main() {
#[forbid(missing_docs)]
pub mod m3 {
// Attempting to toggle warning signals an error here
#[allow(missing_docs)]
/// Returns 2.
pub fn undocumented_too() -> i32 { 2 }
}
}
Lint 原因
所有 lint 属性都支持额外的 reason 参数,以提供添加特定属性的原因。如果 lint 在定义的级别发出,此原因将作为 lint 消息的一部分显示。
#![allow(unused)]
fn main() {
// `keyword_idents` is allowed by default. Here we deny it to
// avoid migration of identifiers when we update the edition.
#![deny(
keyword_idents,
reason = "we want to avoid these idents to be future compatible"
)]
// This name was allowed in Rust's 2015 edition. We still aim to avoid
// this to be future compatible and not confuse end users.
fn dyn() {}
}
这是另一个示例,其中 lint 被允许并带有原因:
#![allow(unused)]
fn main() {
use std::path::PathBuf;
pub fn get_path() -> PathBuf {
// The `reason` parameter on `allow` attributes acts as documentation for the reader.
#[allow(unused_mut, reason = "this is only modified on some platforms")]
let mut file_name = PathBuf::from("git");
#[cfg(target_os = "windows")]
file_name.set_extension("exe");
file_name
}
}
#[expect] 属性
#[expect(C)] 属性为 lint C 创建 lint 预期。如果在同一位置的 #[warn(C)] 属性会导致 lint 发出,则预期将被满足。如果预期未满足,因为 lint C 不会被发出,则 unfulfilled_lint_expectations lint 将在属性处发出。
fn main() {
// This `#[expect]` attribute creates a lint expectation, that the `unused_variables`
// lint would be emitted by the following statement. This expectation is
// unfulfilled, since the `question` variable is used by the `println!` macro.
// Therefore, the `unfulfilled_lint_expectations` lint will be emitted at the
// attribute.
#[expect(unused_variables)]
let question = "who lives in a pineapple under the sea?";
println!("{question}");
// This `#[expect]` attribute creates a lint expectation that will be fulfilled, since
// the `answer` variable is never used. The `unused_variables` lint, that would usually
// be emitted, is suppressed. No warning will be issued for the statement or attribute.
#[expect(unused_variables)]
let answer = "SpongeBob SquarePants!";
}
Lint 预期仅由被 expect 属性抑制的 lint 发出满足。如果 lint 级别在作用域中被其他级别属性(如 allow 或 warn)修改,lint 发出将相应处理,预期将保持未满足。
#![allow(unused)]
fn main() {
#[expect(unused_variables)]
fn select_song() {
// This will emit the `unused_variables` lint at the warn level
// as defined by the `warn` attribute. This will not fulfill the
// expectation above the function.
#[warn(unused_variables)]
let song_name = "Crab Rave";
// The `allow` attribute suppresses the lint emission. This will not
// fulfill the expectation as it has been suppressed by the `allow`
// attribute and not the `expect` attribute above the function.
#[allow(unused_variables)]
let song_creator = "Noisestorm";
// This `expect` attribute will suppress the `unused_variables` lint emission
// at the variable. The `expect` attribute above the function will still not
// be fulfilled, since this lint emission has been suppressed by the local
// expect attribute.
#[expect(unused_variables)]
let song_version = "Monstercat Release";
}
}
如果 expect 属性包含多个 lint,则每个 lint 单独预期。对于 lint 组,如果组内的一个 lint 已被发出就足够了:
#![allow(unused)]
fn main() {
// This expectation will be fulfilled by the unused value inside the function
// since the emitted `unused_variables` lint is inside the `unused` lint group.
#[expect(unused)]
pub fn thoughts() {
let unused = "I'm running out of examples";
}
pub fn another_example() {
// This attribute creates two lint expectations. The `unused_mut` lint will be
// suppressed and with that fulfill the first expectation. The `unused_variables`
// wouldn't be emitted, since the variable is used. That expectation will therefore
// be unsatisfied, and a warning will be emitted.
#[expect(unused_mut, unused_variables)]
let mut link = "https://www.rust-lang.org/";
println!("Welcome to our community: {link}");
}
}
Note
#[expect(unfulfilled_lint_expectations)]的行为目前定义为始终生成unfulfilled_lint_expectationslint。
Lint 组
Lint 可以组织成命名组,以便可以一起调整相关 lint 的级别。使用命名组等同于列出该组内的 lint。
#![allow(unused)]
fn main() {
// This allows all lints in the "unused" group.
#[allow(unused)]
// This overrides the "unused_must_use" lint from the "unused"
// group to deny.
#[deny(unused_must_use)]
fn example() {
// This does not generate a warning because the "unused_variables"
// lint is in the "unused" group.
let x = 1;
// This generates an error because the result is unused and
// "unused_must_use" is marked as "deny".
std::fs::remove_file("some_file"); // ERROR: unused `Result` that must be used
}
}
有一个名为 “warnings” 的特殊组,包含 “warn” 级别的所有 lint。“warnings” 组忽略属性顺序,并适用于实体内所有其他会发出警告的 lint。
#![allow(unused)]
fn main() {
unsafe fn an_unsafe_fn() {}
// The order of these two attributes does not matter.
#[deny(warnings)]
// The unsafe_code lint is normally "allow" by default.
#[warn(unsafe_code)]
fn example_err() {
// This is an error because the `unsafe_code` warning has
// been lifted to "deny".
unsafe { an_unsafe_fn() } // ERROR: use of `unsafe` block
}
}
工具 lint 属性
工具 lint 允许使用作用域 lint,以 allow、warn、deny 或 forbid 特定工具的 lint。
工具 lint 仅在关联工具处于活动状态时才被检查。如果 lint 属性(如 allow)引用了不存在的工具 lint,编译器在您使用该工具之前不会对不存在的 lint 发出警告。
否则,它们的工作方式与常规 lint 属性相同:
// set the entire `pedantic` clippy lint group to warn
#![warn(clippy::pedantic)]
// silence warnings from the `filter_map` clippy lint
#![allow(clippy::filter_map)]
fn main() {
// ...
}
// silence the `cmp_nan` clippy lint just for this function
#[allow(clippy::cmp_nan)]
fn foo() {
// ...
}
deprecated 属性
deprecated 属性将项标记为已弃用。rustc 将对使用 #[deprecated] 项发出警告。rustdoc 将显示项弃用,包括 since 版本和 note(如果可用)。
deprecated 属性有几种形式:
deprecated— 发出通用消息。deprecated = "message"— 在弃用消息中包含给定字符串。- MetaListNameValueStr 语法,有两个可选字段:
since— 指定项被弃用时的版本号。rustc目前不解释该字符串,但 Clippy 等外部工具可能会检查值的有效性。note— 指定应包含在弃用消息中的字符串。这通常用于提供关于弃用和首选替代方案的解释。
deprecated 属性可应用于任何项、trait 项、枚举变体、结构体字段、外部块项或宏定义。它不能应用于 trait 实现项。当应用于包含其他项的项(如模块或实现)时,所有子项继承弃用属性。
这是一个示例:
#![allow(unused)]
fn main() {
#[deprecated(since = "5.2.0", note = "foo was rarely used. Users should instead use bar")]
pub fn foo() {}
pub fn bar() {}
}
RFC 包含动机和更多详细信息。
must_use 属性
*must_use [属性]*标记应该被使用的值。
must_use 属性使用 MetaWord 和 MetaNameValueStr 语法。
Example
#![allow(unused)] fn main() { #[must_use] fn use_me1() -> u8 { 0 } #[must_use = "explanation of why it should be used"] fn use_me2() -> u8 { 0 } }
must_use 属性可应用于:
Note
rustc会忽略在其他位置的使用,但会发出 lint 警告。这可能在未来成为错误。
must_use 属性只能在项上使用一次。
Note
rustc会对第一次之后的任何使用发出 lint 警告。这可能在未来成为错误。
must_use 属性可以使用 MetaNameValueStr 语法包含消息,例如 #[must_use = "example message"]。该消息可能作为 lint 的一部分发出。
当属性应用于结构体、枚举或联合体时,如果表达式语句的表达式具有该类型,则使用会触发 unused_must_use lint。
#![allow(unused)]
#![deny(unused_must_use)]
fn main() {
#[must_use]
struct MustUse();
MustUse(); // ERROR: Unused value that must be used.
}
作为 attributes.diagnostics.must_use.type 的例外,当 E 是无人居住的时,Result<(), E> 不会触发 lint,当 B 是无人居住的时,ControlFlow<B, ()> 也不会触发。来自外部 crate 的 #[non_exhaustive] 类型不被视为无人居住,因为它将来可能会获得构造函数。
#![allow(unused)]
#![deny(unused_must_use)]
fn main() {
use core::ops::ControlFlow;
enum Empty {}
fn f1() -> Result<(), Empty> { Ok(()) }
f1(); // OK: `Empty` is uninhabited.
fn f2() -> ControlFlow<Empty, ()> { ControlFlow::Continue(()) }
f2(); // OK: `Empty` is uninhabited.
}
如果表达式语句的表达式是调用表达式或方法调用表达式,其函数操作数是应用了属性的函数,则使用会触发 unused_must_use lint。
#![allow(unused)]
#![deny(unused_must_use)]
fn main() {
#[must_use]
fn f() {}
f(); // ERROR: Unused return value that must be used.
}
如果表达式语句的表达式是调用表达式或方法调用表达式,其函数操作数是返回 impl trait 或 dyn trait 类型的函数,其中约束中的一个或多个 trait 被标记了该属性,则使用会触发 unused_must_use lint。
#![allow(unused)]
#![deny(unused_must_use)]
fn main() {
#[must_use]
trait Tr {}
impl Tr for () {}
fn f() -> impl Tr {}
f(); // ERROR: Unused implementor that must be used.
}
当属性应用于 trait 声明中的函数时,attributes.diagnostics.must_use.fn 中描述的规则也适用于调用表达式或方法调用表达式的函数操作数是该函数的实现时。
#![allow(unused)]
#![deny(unused_must_use)]
fn main() {
trait Tr {
#[must_use]
fn use_me(&self);
}
impl Tr for () {
fn use_me(&self) {}
}
().use_me(); // ERROR: Unused return value that must be used.
}
#![allow(unused)]
fn main() {
#![deny(unused_must_use)]
trait Tr {
#[must_use]
fn use_me(&self);
}
impl Tr for () {
fn use_me(&self) {}
}
<() as Tr>::use_me(&());
// ^^^^^^^^^^^ ERROR: Unused return value that must be used.
}
在检查表达式语句的表达式是否符合 attributes.diagnostics.must_use.type、attributes.diagnostics.must_use.fn、attributes.diagnostics.must_use.trait 和 attributes.diagnostics.must_use.trait-function 时,lint 会透视块表达式(包括 [unsafe 块]和标记块表达式)到每个块的尾部表达式。这适用于嵌套块表达式的递归。
#![allow(unused)]
#![deny(unused_must_use)]
fn main() {
#[must_use]
fn f() {}
{ f() }; // ERROR: The lint looks through block expressions.
unsafe { f() }; // ERROR: The lint looks through `unsafe` blocks.
{ { f() } }; // ERROR: The lint looks through nested blocks.
}
在 trait 实现中的函数上使用时,该属性不起作用。
#![allow(unused)]
#![deny(unused_must_use)]
fn main() {
trait Tr {
fn f(&self);
}
impl Tr for () {
#[must_use] // This has no effect.
fn f(&self) {}
}
().f(); // OK.
}
Note
rustc会对 trait 实现中的函数上的使用发出 lint 警告。这可能在未来成为错误。
Note
在某些表达式中包装
#[must_use]函数的结果可以抑制基于 fn 的检查,因为表达式语句的表达式不是对#[must_use函数的调用表达式或方法调用表达式。如果整体表达式的类型是#[must_use],则基于类型的检查仍然适用。#![allow(unused)] #![deny(unused_must_use)] fn main() { #[must_use] fn f() {} // The fn-based check does not fire for any of these, because the // expression of the expression statement is not a call to a // `#[must_use]` function. (f(),); // Expression is a tuple, not a call. Some(f()); // Callee `Some` is not `#[must_use]`. if true { f() } else {}; // Expression is an `if`, not a call. match true { // Expression is a `match`, not a call. _ => f() }; }#![allow(unused)] #![deny(unused_must_use)] fn main() { #[must_use] struct MustUse; fn g() -> MustUse { MustUse } // Despite the `if` expression not being a call, the type-based check // fires because the type of the expression is `MustUse`, which has // the `#[must_use]` attribute. if true { g() } else { MustUse }; // ERROR: Must be used. }
Note
当故意丢弃必须使用的值时,使用带有
_模式的 let 语句或解构赋值是惯用做法。#![allow(unused)] #![deny(unused_must_use)] fn main() { #[must_use] fn f() {} let _ = f(); // OK. _ = f(); // OK. }
diagnostic 工具属性命名空间
#[diagnostic] 属性命名空间是用于影响编译时错误消息的属性的家园。
这些属性提供的提示不保证会被使用。
此命名空间中的未知属性被接受,尽管它们可能会对未使用的属性发出警告。 此外,已知属性的无效输入通常是警告(有关详细信息,请参阅属性定义)。 这是为了允许将来添加或丢弃属性和更改输入,而无需保持无意义的属性或选项工作。
diagnostic::on_unimplemented 属性
#[diagnostic::on_unimplemented] 属性是对编译器的提示,用于补充在需要 trait 但类型未实现 trait 的场景中通常生成的错误消息。
该属性应放在 trait 声明上,但位于其他位置不是错误。
该属性使用 MetaListNameValueStr 语法指定其输入,但属性的任何格式错误的输入都不被视为错误,以提供向前和向后兼容性。
以下键具有给定含义:
message— 顶级错误消息的文本。label— 错误消息中损坏代码内联显示的标签的文本。note— 提供额外的注释。
note 选项可以出现多次,这会导致发出多个注释消息。
如果任何其他选项出现多次,相关选项的第一次出现指定实际使用的值。后续出现会生成警告。
对任何未知键会生成警告。
所有三个选项都接受字符串作为参数,使用与 std::fmt 字符串相同的格式进行解释。
具有给定命名参数的格式参数将被替换为以下文本:
{Self}— 实现 trait 的类型的名称。{GenericParameterName}— 给定泛型参数的泛型参数类型的名称。
任何其他格式参数将生成警告,但会按原样包含在字符串中。
无效的格式字符串可能会生成警告,但否则是允许的,但可能不会按预期显示。 格式说明符可能会生成警告,但否则会被忽略。
在此示例中:
#[diagnostic::on_unimplemented(
message = "My Message for `ImportantTrait<{A}>` implemented for `{Self}`",
label = "My Label",
note = "Note 1",
note = "Note 2"
)]
trait ImportantTrait<A> {}
fn use_my_trait(_: impl ImportantTrait<i32>) {}
fn main() {
use_my_trait(String::new());
}
编译器可能生成如下所示的错误消息:
error[E0277]: My Message for `ImportantTrait<i32>` implemented for `String`
--> src/main.rs:14:18
|
14 | use_my_trait(String::new());
| ------------ ^^^^^^^^^^^^^ My Label
| |
| required by a bound introduced by this call
|
= help: the trait `ImportantTrait<i32>` is not implemented for `String`
= note: Note 1
= note: Note 2
diagnostic::do_not_recommend 属性
#[diagnostic::do_not_recommend] 属性是对编译器的提示,不要将注释的 trait 实现显示为诊断消息的一部分。
Note
如果您知道该建议通常对程序员没有用处,则抑制该建议可能很有用。这通常发生在广泛的、全面的 impl 中。该建议可能会将程序员引向错误的道路,或者 trait 实现可能是您不想暴露的内部细节,或者约束可能无法由程序员满足。
例如,在关于类型未实现所需 trait 的错误消息中,编译器可能会找到一个 trait 实现,如果不是 trait 实现中的特定约束,该实现将满足要求。编译器可能会告诉用户有一个 impl,但问题是 trait 实现中的约束。
#[diagnostic::do_not_recommend]属性可用于告诉编译器不要告诉用户有关 trait 实现的信息,而是简单地告诉用户该类型未实现所需的 trait。
该属性应放在 trait 实现项上,但位于其他位置不是错误。
该属性不接受任何参数,但意外参数不被视为错误。
在以下示例中,有一个名为 AsExpression 的 trait,用于将任意类型转换为 SQL 库中使用的 Expression 类型。有一个名为 check 的方法,它接受一个 AsExpression。
pub trait Expression {
type SqlType;
}
pub trait AsExpression<ST> {
type Expression: Expression<SqlType = ST>;
}
pub struct Text;
pub struct Integer;
pub struct Bound<T>(T);
pub struct SelectInt;
impl Expression for SelectInt {
type SqlType = Integer;
}
impl<T> Expression for Bound<T> {
type SqlType = T;
}
impl AsExpression<Integer> for i32 {
type Expression = Bound<Integer>;
}
impl AsExpression<Text> for &'_ str {
type Expression = Bound<Text>;
}
impl<T> Foo for T where T: Expression {}
// Uncomment this line to change the recommendation.
// #[diagnostic::do_not_recommend]
impl<T, ST> AsExpression<ST> for T
where
T: Expression<SqlType = ST>,
{
type Expression = T;
}
trait Foo: Expression + Sized {
fn check<T>(&self, _: T) -> <T as AsExpression<<Self as Expression>::SqlType>>::Expression
where
T: AsExpression<Self::SqlType>,
{
todo!()
}
}
fn main() {
SelectInt.check("bar");
}
SelectInt 类型的 check 方法期望一个 Integer 类型。用 i32 类型调用它可以工作,因为它通过 AsExpression trait 转换为 Integer。但是,用字符串调用它不行,并生成如下所示的错误:
error[E0277]: the trait bound `&str: Expression` is not satisfied
--> src/main.rs:53:15
|
53 | SelectInt.check("bar");
| ^^^^^ the trait `Expression` is not implemented for `&str`
|
= help: the following other types implement trait `Expression`:
Bound<T>
SelectInt
note: required for `&str` to implement `AsExpression<Integer>`
--> src/main.rs:45:13
|
45 | impl<T, ST> AsExpression<ST> for T
| ^^^^^^^^^^^^^^^^ ^
46 | where
47 | T: Expression<SqlType = ST>,
| ------------------------ unsatisfied trait bound introduced here
通过将 #[diagnostic::do_not_recommend] 属性添加到 AsExpression 的全面实现 impl,消息更改为:
error[E0277]: the trait bound `&str: AsExpression<Integer>` is not satisfied
--> src/main.rs:53:15
|
53 | SelectInt.check("bar");
| ^^^^^ the trait `AsExpression<Integer>` is not implemented for `&str`
|
= help: the trait `AsExpression<Integer>` is not implemented for `&str`
but trait `AsExpression<Text>` is implemented for it
= help: for that trait implementation, expected `Text`, found `Integer`
第一个错误消息包含关于 &str 和 Expression 关系的令人困惑的错误消息,以及全面实现中未满足的 trait 约束。添加 #[diagnostic::do_not_recommend] 后,它不再考虑全面实现作为建议。消息应该更清晰一些,指示字符串无法转换为 Integer。