lotsoftools

Understanding Rust Error E0773: Builtin Macro Defined More Than Once

Introduction to Rust Error E0773

Rust Error E0773 occurs when a built-in macro in a Rust program is defined multiple times, either within the same module or across different modules. This causes ambiguity for the compiler, which could potentially produce unexpected results or runtime errors.

Example of Erroneous Code

#![allow(unused)]
#![feature(decl_macro)]
#![feature(rustc_attrs)]

fn main() {
#[rustc_builtin_macro]
pub macro test($item:item) {
    /* compiler built-in */
}

mod inner {
    #[rustc_builtin_macro]
    pub macro test($item:item) {
        /* compiler built-in */
    }
}
}

Explanation of the Erroneous Code

In this example, the built-in macro 'test' is defined twice; once inside the 'main' function and once inside the nested 'inner' module. The 'rustc_builtin_macro' attribute informs the compiler that this is a compiler built-in macro, which results in the E0773 error due to the duplicate declaration.

Fixing the E0773 Error

To resolve Rust Error E0773, you need to remove one of the duplicate built-in macro declarations. This ensures the compiler has a single definition to work with. Here's a corrected version of the example:

#![allow(unused)]
#![feature(decl_macro)]
#![feature(rustc_attrs)]

fn main() {
#[rustc_builtin_macro]
pub macro test($item:item) {
    /* compiler built-in */
}
}

Rare Edge Cases

In very rare cases, Rust Error E0773 may also occur when loading the 'core' or 'std' libraries twice – once with check metadata and once with build metadata. For more detailed information on this particular scenario, refer to GitHub issue #75176.