nalgebra icon indicating copy to clipboard operation
nalgebra copied to clipboard

Improve compiler warnings with #[must_use]

Open cauthmann opened this issue 6 years ago • 6 comments

Hello,

After porting my project to nalgebra, I spent way too much time debugging a black screen, which I eventually traced back to my following mistake:

view_matrix.prepend_translation(&(-camera));

This function returns a new matrix; the line is a no-op.

Enter #[must_use]:

    #[inline]
    #[must_use = "Did you mean to use prepend_translation_mut()?"]
    pub fn prepend_translation<SB>(
    ...

This turns a silent error into a helpful compiler warning:

   |     view_matrix.prepend_translation(&(-camera));
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: #[warn(unused_must_use)] on by default
   = note: Did you mean to use prepend_translation_mut()?

I propose to tag all functions that return a new object without side effects as #[must_use], optionally with a hint towards an in-place alternative.

This might also help with #534.

Is this something you'd consider an improvement? Shall I try to prepare a pull request, or would you rather go through your code yourself?

cauthmann avatar Jun 01 '19 12:06 cauthmann

Hi! This is a great idea.

Lot of nalgebra feature existed before #[must_use] was added to the language so we could not do this before. It would be a great contribution if you make a pull request for this, yes!

sebcrozet avatar Jun 04 '19 07:06 sebcrozet

I saw your request for further functions on #607, @cauthmann. Since I just found a bug in my code, I'd like to propose the cap_magnitude functions. If someone (me) assumes that they would mutate their Vector/Matrix, they'd be suprised to find some unexpected behaviour.

MalteT avatar Mar 09 '21 11:03 MalteT

@MalteT: That seems like a good candidate, but I don't have any active projects using nalgebra right now. Feel free to make your own PR.

cauthmann avatar Mar 09 '21 11:03 cauthmann

Thanks! I'll see if I can find some time soon :)

MalteT avatar Mar 09 '21 12:03 MalteT

Would it maybe make sense to mark the Matrix type itself with #[must_use]? I can't think of cases where it would be harmful per se, and it would be easier than marking individual functions that return Matrix.

RReverser avatar Apr 11 '25 22:04 RReverser

It's such a general type, I'm not sure that's always going to be desirable, for the same reason that e.g. u32 isn't marked that way.

Ralith avatar Apr 11 '25 23:04 Ralith