Skip to content

Not using the result of offset_of should lint #111669

Closed
@est31

Description

@est31

The offset_of macro (#106655) is side effect free. For standard library functions that are side effect free, or that have side effects but there is versions of them that don't return anything, it is policy to add a must_use attribute to them so that users are warned if they invoke the function without doing anything with the result (#89692).

Ideally, the same should hold for the offset_of macro as well. One of the lints in the unused lint group should fire if you don't use the result of the offset_of!() macro:

fn foo() {
    offset_of!(F, field); // WARNING result must be used
}
struct F { field: u8, }

Ideally it would be integrated into the must_use system, say via supporting #[must_use] attributes on macros. Currently you are getting:

warning: `#[must_use]` has no effect when applied to a macro def
 --> src/main.rs:1:1
  |
1 | #[must_use = "hi"]
  | ^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_attributes)]` on by default

for

#[must_use = "hi"]
macro_rules! foo {
    () => {0};
}
fn main() {
    foo!();
}

It could e.g. expand to some AST node that is just the identity.

Alternatively, one could also just solve it for the offset_of macro via sending the result through a function:

macro_rules! offset_of_must_use {
    () => {
            #[must_use = "offset_of result must be used"]
            const fn must_use(v: usize) -> usize { v }
            must_use(0)
    };
}

fn main() {
    offset_of_must_use!();
}

Sadly this pollutes the context with a function however. If one surrounds the entire expansion with {}s, the lint is silent again.

I don't think it's worth its own lint in itself.

Metadata

Metadata

Labels

A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.F-offset_of`#![feature(offset_of)]`

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions