[Coding Guideline] Revise guideline on unsafe code in macros#368
[Coding Guideline] Revise guideline on unsafe code in macros#368rcseacord wants to merge 2 commits intorustfoundation:mainfrom
Conversation
✅ Deploy Preview for scrc-coding-guidelines ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
I opened a Zulip thread to ask about this: How should one combine I wanted to know how useful this pattern (of having an And it seems like it is quite useful, and necessary in some cases: A very simple example by scottmcm: let slice = $crate::MyUnsafeTrait::get_me_the_thing($e);
// SAFETY: `MyUnsafeTrait` promises that `get_me_the_thing` returns a non-empty slice
unsafe { slice.get_unchecked(0) }Another example, this time from
|
|
@felix91gr I think we can both seen the value or need for this rule? maybe we can make some adjustments around valid use cases. Something like: You can have an unsafe macro with an arbitrary identifier like the pin! macro if the macro provided the macro upholds the safety contract and there is no way to misuse the macro to introduce undefined behavior. If you have an unsafe macro that exposes unsafe behavior you must prefix the macro name with the string "unsafe_" Unsafe macros without a prefix are not allowed. Or you could break this up into a strict advisory rule and a less strict required rule. It's not great when the language / library violates your rule. MISRA does this with rules like don't use restrict which is used throughout the C library, but it's mostly because they don't know what they are talking about. |
I agree. This seems very reasonable: we would be classifying those, so-to-say, as "safe macros which internally have In Rust, for safe APIs that contain So, this idea would be following the same kind of standard, only for macros instead of functions. The burden of proof is higher (one must prove that any use of the macro cannot introduce UB), but if done properly (like we believe to be the case for the It would also only require local reasoning about safety which is good. It would be much like how properly encapsulating
Continuing with the theme above, this seems very reasonable as well. It would be the macro equivalent of an Which are themselves the rules for
That's another parallel to
🤣 it makes me smile to see you dunk on MISRA, dunno why In their defense: does gcc have full and sound Given that history (and how hard a time LLVM at least has had trying to fully implement it), I would not be surprised if a broad ban on |
Updated guideline on unsafe code in macros to clarify the importance of preserving 'unsafe' token visibility. Added examples of compliant and non-compliant macro implementations.
Updated guideline on unsafe code in macros to clarify the importance of preserving 'unsafe' token visibility. Added examples of compliant and non-compliant macro implementations.