Skip to content

Commit ccad218

Browse files
committed
Auto merge of rust-lang#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 (rust-lang#82525), it would make sense for this lint to be triggered for external macros as well. See taiki-e/pin-project-lite#55 (comment) and taiki-e/pin-project-lite#55 (comment) for more. r? `@RalfJung`
2 parents 5233edc + 62b4b8d commit ccad218

File tree

4 files changed

+69
-0
lines changed

4 files changed

+69
-0
lines changed

compiler/rustc_lint_defs/src/builtin.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1080,6 +1080,7 @@ declare_lint! {
10801080
pub UNALIGNED_REFERENCES,
10811081
Allow,
10821082
"detects unaligned references to fields of packed structs",
1083+
report_in_external_macro
10831084
}
10841085

10851086
declare_lint! {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#[macro_export]
2+
macro_rules! mac {
3+
(
4+
$(#[$attrs:meta])*
5+
pub struct $ident:ident {
6+
$(
7+
$(#[$pin:ident])?
8+
$field_vis:vis $field:ident: $field_ty:ty
9+
),+ $(,)?
10+
}
11+
) => {
12+
$(#[$attrs])*
13+
pub struct $ident {
14+
$(
15+
$field_vis $field: $field_ty
16+
),+
17+
}
18+
19+
const _: () = {
20+
#[deny(unaligned_references)]
21+
fn __f(this: &$ident) {
22+
$(
23+
let _ = &this.$field;
24+
)+
25+
}
26+
};
27+
};
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// aux-build:unaligned_references_external_crate.rs
2+
3+
#![allow(safe_packed_borrows)]
4+
5+
extern crate unaligned_references_external_crate;
6+
7+
unaligned_references_external_crate::mac! { //~ERROR reference to packed field is unaligned
8+
#[repr(packed)]
9+
pub struct X {
10+
pub field: u16
11+
}
12+
}
13+
14+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
error: reference to packed field is unaligned
2+
--> $DIR/unaligned_references_external_macro.rs:7:1
3+
|
4+
LL | / unaligned_references_external_crate::mac! {
5+
LL | | #[repr(packed)]
6+
LL | | pub struct X {
7+
LL | | pub field: u16
8+
LL | | }
9+
LL | | }
10+
| |_^
11+
|
12+
note: the lint level is defined here
13+
--> $DIR/unaligned_references_external_macro.rs:7:1
14+
|
15+
LL | / unaligned_references_external_crate::mac! {
16+
LL | | #[repr(packed)]
17+
LL | | pub struct X {
18+
LL | | pub field: u16
19+
LL | | }
20+
LL | | }
21+
| |_^
22+
= note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)
23+
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
24+
25+
error: aborting due to previous error
26+

0 commit comments

Comments
 (0)