SAFETY comments - nomicon

This, in an ongoing discussion on URLO, really hit home for me too.

I've also noticed that there are some excellent examples of SAFETY comments and many, very many, examples of unsafe with no comments.

While agreeing with the OP, I thought "I'll refer to the nomicon, that will contain great guidelines on how to add SAFETY comments to code ..." - oops!

  • The nomicon doesn't mention SAFETY comments once, nor safety-related lints
  • While it does include inline comments in the "implementing Vec" example - they don't match today's expectations for format or content

I'd like to suggest raising a PR to the nomicon to:

  1. add a dedicated section 1.4 "Documenting & auditing unsafe code" covering how to write safety comments as well as the fundamental rustc & clippy lints
  2. update the implementing Vec example to include exemplary safety documentation

Given that we should expect a significant increase in the amount of unsafe being written in the next year, I'd consider now to be the right time to get ahead of this and hopefully push towards a positive feedback loop with more of that code including good comments.

I'd be happy to work on this, but only if it has a chance of landing :wink:

4 Likes

As a passive observer (generally in favor of documenting this if not available elsewhere), I am curious:
Is this more a "more code in general, some of which is unsafe" or specifically "unsafe"?

2 Likes

My hypothesis is that we will see a larger proportion of unsafe in the next 1-2 years than usual up to now.

2 technical reasons & 1 human one:

  1. migrating large code bases from C/C++ needs to happen incrementally, so there will be an unusually high need to cross ffi-boundaries while this happens.
  2. codebases targeted for migration will somewhat disproportionately weigh towards including low-level elements which require unsafe (that's why they were in C and not something else)
  3. mimicking the old c-style is only natural - there will be unsafe which could be idiomatically avoided (and the more effort goes into safety-commenting, the more this will be noticed and avoided)

But whatever anyone's views on the above, which is just a personal guess from my side, there is a lot of value to providing guidance on how to document unsafe.

1 Like

I guess how to write SAFETY documentation is still an ongoing topic, as listed in the Rust project goal Improving Unsafe Code Documentation in the Rust Standard Library and safer-rust/rust-safety-standard, where both the goal and the repo is maintained by @hxuhack

4 Likes