Summary

This RFC adds three new attributes:

Note that this does not add any new functionality into the compiler; it only relaxes the current restrictions. While rustc verifies that tool attributes and lints are syntactically valid and do not cause ambiguity during name resolution, it does no extra processing.

Motivation

There are several tools predefined in the tool namespace. These tools are hard-coded, and cannot be extended with user-defined tools. There are many external programs that would benefit from being able to annotate specific portions of a crate or register custom lints without the compiler raising an error.

Here is a short summary of the built-in tools:

Tool Lints Attributes
clippy ✅ ✅
rustfmt ❌ ✅
miri ❌ ✅
rust_analyzer ❌ ✅
rustdoc ✅ ❌
rustc ✅ (with -Z unstable-options) ❌
diagnostic ❌ ✅

Why support custom lints?

There are several crates, such as bevy and regex, that would benefit from API-specific lints that encourage specific styles or warn against potential footguns. While it is possible to create a custom rustc driver that registers these lints, any reference to them in code would cause the default compiler to raise an error.

// While `bevy_lint` will recognize this, the default `rustc` will not, raising a compile error.
#![warn(bevy::style)]

There are currently two solutions to this: upstream lints directly to Clippy or use #[cfg_attr(my_tool, warn(...))]. The prior solution increases the maintenance burden for Clippy developers, and thus will rarely be accepted. The latter is very verbose and requires adding unexpected_cfgs = { level = "warn", check-cfg = ["cfg(my_tool)"] } in Cargo.toml.

There are also several linting tools that don’t make sense to upstream to Clippy:

Why support custom attributes?

There are also some tools that would benefit from using developer-added metadata on portions of source code:

Guide-level explanation

For users of external tools

Several official tools let you configure their behavior on specific parts of your code. For example, Clippy lets you use #[warn(clippy::as_ptr_cast_mut)] to warn on that lint for a single item, and Rustfmt lets you use #[rustfmt::skip] to avoid formatting a single item. You can also do this for external tools that are not provided in the Rust toolchain. See the documentation of those tools for the lints and attributes they support.

To tell the compiler about an external tool, add #![register_tool(some_tool)] to your crate root.

Crate-level lints for external tools can use #![warn(some_tool::lint_name)], like any lint. Tools may also support a custom configuration format that allows you to control lints for your whole workspace at once. Consult the documentation of the tool you use.

Fixing name resolution errors

Note that register_tool changes name resolution, and may give errors if you have a crate named some_tool. The compiler will suggest ways to fix the new errors.

If a tool name conflicts with a crate name, you can disambiguate the crate with ::some_tool:

#![register_tool(some_tool)]
extern crate some_tool;

#[some_tool::attribute] //~ ERROR: is this the tool or a proc-macro?
fn bar() {
    // ...
}

#[::some_tool::attribute] // OK: This is the proc-macro defined in the crate.
fn foo() {
    // ...
}

However, if you want to go on to use a tool attribute, you must rename the crate so it doesn’t conflict:

#![register_tool(some_tool)]
extern crate some_tool as my_library;

#[some_tool::attribute] // OK: This is the attribute specified by the tool.
fn bar() {
    // ...
}

Alternatively, if you only want to use lints, you can use register_lint_tool instead of register_tool, which will avoid resolution errors.

Overlaps like this are expected to be rare in practice.

For authors of external tools

The Rust language can be extended and analyzed using external tools. If your tool can parse Rust, you may wish to allow configuring it at sub-crate levels (e.g. individual functions, types, and modules). To reuse the same syntax as the official tools, like Clippy and Rustfmt, instruct your users to add #![register_lint_tool(your_tool)] (if your tool only adds new lints) or #![register_attribute_tool(your_tool)] (if your tool only adds new attributes). If your tool supports both lints and attributes, use #![register_tool(your_tool]. Then, instruct your users to add either #[warn(your_tool::your_lint)] or #[your_tool::your_attribute(your_tokens)] as appropriate.

We do not specify a syntax for package-level configuration. We suggest using [package.metadata.your_tool] in Cargo.toml.

The syntax for external attributes is carefully designed such that you do not need to do name resolution in order to recognize the attributes. As long as register_attribute_tool(your_tool) is present at the crate root, #[your_tool::your_attribute] will always be an inert attribute you can parse directly; it can never be a re-export of a different item, nor a reference to a local item.

Please do verify that register_attribute_tool is present, and either warn or error otherwise. If you do not do so, you may accidentally interpret a crate or local module as your tool. We will ensure that rustdoc --output-format json includes register_attribute_tool so that users of rustdoc json are not required to reimplement a rust parser.

Please do not suggest using #[cfg_attr(your_tool, your_attribute)]. Doing so runs the risk that the language will add that lint or attribute in a future version. Use tool namespaces instead, as that’s what they’re for! It’s ok to pass a custom cfg when your tool runs, but avoid using it to guard tool lints and attributes unless it would break your MSRV (minimum supported Rust version).

Please do not use tool attributes for metadata that changes the meaning of the code. At that point you are parsing a dialect of Rust, and there is no indication for your users that their code will be interpreted differently by your tool than by the compiler. For example, #[must_use] and #[automatically_derived] would be suitable for tool attributes, but #[repr] and #[panic_handler] are not, because they change the meaning of the code. For that use case, use proc-macros, generated code, or bare (un-namespaced) attributes instead, all of which will give a hard error if they cannot be understood by the compiler. If absolutely necessary to use bare attributes, use a C-style namespace like #[rustc_const_stable].

Reference-level explanation

Language

Background: name resolution of preludes

Currently, names in the type namespace are resolved in the following order:

  1. Explicit definitions (including imports)
  2. Extern prelude (crates injected using either extern crate or --extern)
  3. Tool prelude
  4. Standard library prelude
  5. Language prelude

Note that currently, loading a crate completely prevents using a tool attribute with that name. Consider this program:

extern crate rustfmt; // or --extern rustfmt

#[rustfmt::skip]  // ERROR could not find `skip` in `rustfmt`
fn foo ( ) { }

Semantics

The tool prelude is separated into the tool attribute prelude (which is in the type namespace) and the lint prelude (which is only active inside lint controls).

The #![register_attribute_tool(ident)] crate-level attribute adds a new tool to the tool attribute prelude. The #![register_lint_tool(ident)] crate-level attribute adds a new tool to the lint prelude. For both attributes, tools must be a single ident, not a nested path.

register_attribute_tool and register_lint_tool are idempotent; duplicating the attribute has no effect.

Crate-level macros such as #![cfg_attr(...)] may expand to register_*_tool, subject to all existing rules for macro expansion.

Like today, attributes and lints in a tool namespace are always considered used by the compiler. The compiler does not verify the contents of any tool attribute, except to verify that all attributes are syntactically valid tool attributes.

Registering a predefined tool (clippy, miri, etc.) using #![register_*_tool(...)] is an error.

The rustc tool namespace is currently reserved and will continue to be reserved after this RFC, i.e, register_*_tool(rustc) is an error.

Note that the compiler currently reserves all attributes starting with rustc (such as #[rustcat]), even if they do not have a trailing _. That continues to be the case after this RFC, but tool names starting with rustc are not explicitly prohibited in register_*_tool attributes.

Ambiguity between a tool name and any other name in the type namespace is always a hard error. For example, this code would error:

#![register_tool(name)]

extern crate name;
#[name::skip] // ERROR: ambiguous
#[::name::skip] // OK
fn foo() {}

mod inner {
    mod name {
        // Import the derive macro.
        use Clone as x;
    }

    #[name::x]       // ERROR: ambiguous
    #[name::y]       // ERROR: ambiguous (even though y is not present)
    #[self::name::x] // OK
    fn f() {}
}

This is in order to not require external tools to perform name resolution. This restriction may be relaxed in the future to favor tool names.

To disambiguate a local item, developers may use self:: to force resolution in the current module. To disambiguate a crate, developers may write #[::rustfmt::skip], which forces resolution in the Extern prelude. To disambiguate an item in the standard prelude (e.g. Clone), developers may use std::prelude::v1::Clone. There is no way to disambiguate the tool; developers must use extern crate rustfmt as my_rustfmt (or the equivalent in Cargo.toml) to avoid the ambiguity. As a quality of implementation issue, errors should mention one of the above workarounds.

Modules in the first path of an attribute (e.g. #[unregistered::name]) are assumed to be a crate if they cannot be resolved, and therefore give a hard error if not registered.

Unknown tool names in lints remain a hard error until the story for proc-macro lints is resolved (see Future possibilities).

Inner attributes for tools remain a hard error. Tool names are not affected by the current scope, but we need to know the current scope in order to give an ambiguity error.

Today, #![no_implicit_prelude] suppresses the tool attribute prelude but does not suppress the lint prelude (e.g., #[allow(clippy::foo)] continues to work). Under this RFC, neither prelude is suppressed by #![no_implicit_prelude]. This is technically a breaking change since it can produce new ambiguity errors in stable code.

Drawbacks

This makes the rules for name resolution even more complicated.

This runs the risk that external tools will add attributes that change the meaning of the code, such that the behavior is different when the tool is present. There is not much we can do about this other than to ask tool authors not to do that.

This introduces a new “meta-breaking” concern: once this is stabilized, adding a new tool namespace, like we did for diagnostic and rust_analyzer, becomes a breaking change. That said, this is what editions are for; I think adding a new namespace is rare enough that waiting for an edition isn’t a big deal in practice.

The lang team expressed a concern in 2022 that the name register_*_tool would mislead users into thinking that this automatically runs the tool. I do not think this is likely in practice; if someone adds this attribute, it’s because the docs for the external tool told them to do so, and those docs should also say how to run the tool.

Rationale and alternatives

Prior art

Unresolved questions

How does this interact with proc-macro lints?

Future possibilities