Skip to content

#[rustc_inherit_overflow_checks] should be documented instead of replaced with e.g. Add::add calls. #81721

Open
@eddyb

Description

@eddyb

(Note: this was originally posted as a comment on #62429 - also cc #35310 but not sure how relevant)

In #62429 (comment) @scottmcm said:

Might be worth double-checking there's a test for overflow checks here? I'm never confident in what rustc_inherit_overflow_checks does. (And I hear that one can use Add::add(count, 1) instead of using the attribute.)

While adding more tests is better, I don't agree with removing the attribute. If anything the attribute should be better documented, but relying on more implicit mechanisms that internally use the attribute obscures the fact that something unusual is happening.
(i.e. that some of the behavior isn't decided by the crate being compiled, but by a downstream using crate)

The reason Add::add works at all is because the attribute is used in the impls` for the integer types, e.g.:

macro_rules! add_impl {
($($t:ty)*) => ($(
#[stable(feature = "rust1", since = "1.0.0")]
impl Add for $t {
type Output = $t;
#[inline]
#[rustc_inherit_overflow_checks]
fn add(self, other: $t) -> $t { self + other }
}
forward_ref_binop! { impl Add, add for $t, $t }
)*)
}
add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }

There's nothing magical about it being a trait call, you're just calling another function with #[rustc_inherit_overflow_checks] on it, instead of using #[rustc_inherit_overflow_checks] yourself, and relying on generic/#[inline] instantiation to get the behavior.

The only reason the trait impls have the attribute is because of things generic over those traits, not to call directly.

EDIT: see also documentation issue by @m-ou-se at rust-lang/std-dev-guide#13

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsT-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions