Rust: repr attributes can be applied at module level

Created on 24 Sep 2019  路  8Comments  路  Source: rust-lang/rust

Spot what's wrong with this code:

#![repr(C)] struct Foo(i32);

extern "C" {
    fn foo(x: Foo);
}

fn main() {}

(Playground)

For some reason, top-level #![repr(..)] attributes are allowed, so Foo isn't repr(C). Sadly,
@rust-lang/underhanded isn't a thing.

A-attributes C-bug T-compiler

Most helpful comment

If people rely on this compiling, but doing nothing, changing the repr of all types silently feels like a footgun.

All 8 comments

cc @Centril ^^^ I don't know who is familiar with libsyntax or the library that handles this.

I don't think attributes that affect codegen are checked for validity at all. The same thing happens for #[cold], #[inline], etc.

Some attributes including #[repr] and #[inline] are checked, it appears it's just not visiting the root module. Nested modules do get checked.

In case it turns out that many people rely on this, we could give reasonable (and arguably desirable) interpretation to #![inline] and #![repr(C)]: apply these recursively in the module to e.g. structs and fns (unless there is conflict, in which case the most-local attribute is chosen).

If people rely on this compiling, but doing nothing, changing the repr of all types silently feels like a footgun.

I feel the standard warn by default, deny by default, hard error approach is the easiest way to handle this.

Maybe even skip to deny by default.

Given that occurrences of #![repr(C)] currently do nothing, and it's easy to search for in a codebase (and thus remove or audit), I don't see a strong reason not to start emitting errors, rather than just linting, on these, as long as we can determine this won't break downstream code if there's a crate making this mistake.

I don't think attributes that affect codegen are checked for validity at all. The same thing happens for #[cold], #[inline], etc.

We should fix this too, in the same manner as @rkruppe pointed out. (Either as part of this issue, or in a new issue.) Lack of validity checking can cause concrete problems, as in https://github.com/rust-lang/rust/issues/64768.

Was this page helpful?
0 / 5 - 0 ratings