#![restrict(unsafe, modules = "platform::win")] (bikesheddable)

I've recently found myself creating a library which includes some platform-specific ffi usage as well as some much higher-level functionality, which I'd really rather not split into 2 crates.

This means I cannot #![forbid(unsafe)] at the top level, only #![deny(unsafe)] and that allows #[expect(unsafe)] anywhere.

Ideally, I would like to forbid unsafe except for a pre-determined set of modules, where it was simply deny-ed. I would see 2 advantages for this:

  1. added safety for anyone reviewing / auditing the crate - they know where to look for unsafe, can reason about whether there is a need and be confident that no other unsafe exists.
  2. deterministic verification via a lint or test is always[1] better than non-deterministic via a human reviewer, however trustworthy that human is.

Does anything like this already exist? I couldn't find any historical proposals for something along the lines of #![restrict(unsafe, modules = "platform::win")] (bikesheddable).


  1. for a given definition of "always" :wink: ↩︎

2 Likes
#[deny(unsafe_code)]
pub mod m {

    #[allow(unsafe_code)]
    pub mod ffi {
        pub unsafe fn f() {}        
    }
    
    #[forbid(unsafe_code)]
    mod wrapper {
        // this won't compile
        // #[allow(unsafe_code)]
        // pub unsafe fn f() {}        
    }
}
2 Likes

I don't think that exists, because people typically split the ffi into a separate crate.

3 Likes

Yeah, I specifically don't want to do that, as I have no interest in maintaining a set of bindings for general use with the additional documentation and completeness expectations that would bring.

I've gone this route, for now, with #![deny(unsafe_code)] and #[forbid(unsafe_code)] as high up the module tree as possible.

But I still feel that this is something where I would rather reason and explicitly communicate once, in the place where people look first, rather than needing to maintain at multiple points, with the risk of missing a forbid.

3 Likes