扩展 #[diagnostic] 工具属性命名空间

  • Recap of #[diagnostic] namespace stabilization: The #[diagnostic] namespace is for attributes influencing Rust compiler diagnostic output. Stabilized in Rust 1.78 in May 2024 with #[diagnostic::on_unimplemented] allowing custom messages. Crates like axum, bevy, diesel, and serde started using it, reducing support questions. The Rust standard library also replaced some internal unstable #[rustc_on_unimplemented] with the new stable version.
  • Adding #[diagnostic::do_not_recommend] attribute: Based on the original Rust Foundation Project Grant proposal from 2022, this attribute aims to solve problems with error messages. In Diesel's example, the compiler is too helpful and hides important information. RFC 2397 proposed this attribute in 2018 but wasn't implemented due to concerns. Implementing it in the #[diagnostic] namespace softens guarantees. With the implementation, error messages improved, directly mentioning relevant bounds and implementations. It was also used in the Rust Standard library to hide certain nightly only types.
  • Implementation of the new attribute: To implement the #[diagnostic::do_not_recommend] attribute, tests were written in the [tests/ui/diagnostic_namespace/do_not_recommend] folder. The compiler needed to accept and handle the attribute. By searching for relevant code locations based on error messages and similar tasks (like registering #[diagnostic::on_unimplemented]), the necessary changes were made. The right locations for modifying the emitted error message were found, and dbg! calls were used to understand the structure. Implementing the functionality was not complicated by walking up the trait bound tree. The work was then submitted as a PR with some back-and-forth during code review.
  • Conclusion: Contributing to the compiler is like working on any other Rust project. You don't need to know everything, and targeted searching and debug printing can help. There are also people to assist if needed. Improving compiler diagnostics has a broad impact and is relatively straightforward to implement and test. Sponsoring the work on GitHub is also appreciated.
阅读 3
0 条评论