Auto merge of #82587 - taiki-e:unaligned_references, r=oli-obk

Enable report_in_external_macro in unaligned_references

Fixes an issue where `unaligned_references` is not triggered in external macros, unlike `safe_packed_borrows`.
Also, given that this lint is planned to eventually change to hard error (#82525), it would make sense for this lint to be triggered for external macros as well.

See https://github.com/taiki-e/pin-project-lite/pull/55#issuecomment-787038676 and https://github.com/taiki-e/pin-project-lite/pull/55#issuecomment-787052874 for more.

r? `@RalfJung`
This commit is contained in:
bors 2021-03-01 18:10:38 +00:00
commit ccad218e7f
4 changed files with 69 additions and 0 deletions

View File

@ -1080,6 +1080,7 @@
pub UNALIGNED_REFERENCES,
Allow,
"detects unaligned references to fields of packed structs",
report_in_external_macro
}
declare_lint! {

View File

@ -0,0 +1,28 @@
#[macro_export]
macro_rules! mac {
(
$(#[$attrs:meta])*
pub struct $ident:ident {
$(
$(#[$pin:ident])?
$field_vis:vis $field:ident: $field_ty:ty
),+ $(,)?
}
) => {
$(#[$attrs])*
pub struct $ident {
$(
$field_vis $field: $field_ty
),+
}
const _: () = {
#[deny(unaligned_references)]
fn __f(this: &$ident) {
$(
let _ = &this.$field;
)+
}
};
};
}

View File

@ -0,0 +1,14 @@
// aux-build:unaligned_references_external_crate.rs
#![allow(safe_packed_borrows)]
extern crate unaligned_references_external_crate;
unaligned_references_external_crate::mac! { //~ERROR reference to packed field is unaligned
#[repr(packed)]
pub struct X {
pub field: u16
}
}
fn main() {}

View File

@ -0,0 +1,26 @@
error: reference to packed field is unaligned
--> $DIR/unaligned_references_external_macro.rs:7:1
|
LL | / unaligned_references_external_crate::mac! {
LL | | #[repr(packed)]
LL | | pub struct X {
LL | | pub field: u16
LL | | }
LL | | }
| |_^
|
note: the lint level is defined here
--> $DIR/unaligned_references_external_macro.rs:7:1
|
LL | / unaligned_references_external_crate::mac! {
LL | | #[repr(packed)]
LL | | pub struct X {
LL | | pub field: u16
LL | | }
LL | | }
| |_^
= note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error