Skip to content

Commit d72b229

Browse files
committed
rust: pin-init: rewrite the #[pinned_drop] attribute macro using syn
Rewrite the attribute macro for implementing `PinnedDrop` using `syn`. Otherwise no functional changes intended aside from improved error messages on syntactic and semantical errors. For example: When missing the `drop` function in the implementation, the old error was: error: no rules expected `)` --> tests/ui/compile-fail/pinned_drop/no_fn.rs:6:1 | 6 | #[pinned_drop] | ^^^^^^^^^^^^^^ no rules expected this token in macro call | note: while trying to match keyword `fn` --> src/macros.rs | | fn drop($($sig:tt)*) { | ^^ = note: this error originates in the attribute macro `pinned_drop` (in Nightly builds, run with -Z macro-backtrace for more info) And the new one is: error[E0046]: not all trait items implemented, missing: `drop` --> tests/ui/compile-fail/pinned_drop/no_fn.rs:7:1 | 7 | impl PinnedDrop for Foo {} | ^^^^^^^^^^^^^^^^^^^^^^^ missing `drop` in implementation | = help: implement the missing item: `fn drop(self: Pin<&mut Self>, _: OnlyCallFromDrop) { todo!() }` Signed-off-by: Benno Lossin <lossin@kernel.org>
1 parent 7304864 commit d72b229

3 files changed

Lines changed: 52 additions & 69 deletions

File tree

rust/pin-init/internal/src/lib.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
2525

2626
#[proc_macro_attribute]
2727
pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {
28-
pinned_drop::pinned_drop(args.into(), input.into()).into()
28+
pinned_drop::pinned_drop(parse_macro_input!(args), parse_macro_input!(input)).into()
2929
}
3030

3131
#[proc_macro_derive(Zeroable)]
@@ -55,12 +55,10 @@ impl From<syn::Error> for Error {
5555
}
5656

5757
impl Error {
58-
#[expect(dead_code)]
5958
pub(crate) fn none() -> Self {
6059
Self(None)
6160
}
6261

63-
#[expect(dead_code)]
6462
pub(crate) fn combine(&mut self, error: impl Into<Self>) {
6563
let error = error.into();
6664
if let Some(this) = self.0.as_mut() {
Lines changed: 51 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,62 @@
11
// SPDX-License-Identifier: Apache-2.0 OR MIT
22

3-
use proc_macro2::{TokenStream, TokenTree};
3+
use proc_macro2::TokenStream;
44
use quote::quote;
5+
use syn::{parse::Nothing, parse_quote, spanned::Spanned, Error, ImplItem, ItemImpl, Token};
56

6-
pub(crate) fn pinned_drop(_args: TokenStream, input: TokenStream) -> TokenStream {
7-
let mut toks = input.into_iter().collect::<Vec<_>>();
8-
assert!(!toks.is_empty());
9-
// Ensure that we have an `impl` item.
10-
assert!(matches!(&toks[0], TokenTree::Ident(i) if i == "impl"));
11-
// Ensure that we are implementing `PinnedDrop`.
12-
let mut nesting: usize = 0;
13-
let mut pinned_drop_idx = None;
14-
for (i, tt) in toks.iter().enumerate() {
15-
match tt {
16-
TokenTree::Punct(p) if p.as_char() == '<' => {
17-
nesting += 1;
7+
pub(crate) fn pinned_drop(_args: Nothing, mut input: ItemImpl) -> TokenStream {
8+
let mut error = crate::Error::none();
9+
if let Some(unsafety) = input.unsafety {
10+
error.combine(Error::new_spanned(
11+
unsafety,
12+
"implementing `PinnedDrop` is safe",
13+
));
14+
}
15+
input.unsafety = Some(Token![unsafe](input.impl_token.span));
16+
match &mut input.trait_ {
17+
Some((not, path, _for)) => {
18+
if let Some(not) = not {
19+
error.combine(Error::new_spanned(not, "cannot implement `!PinnedDrop`"));
1820
}
19-
TokenTree::Punct(p) if p.as_char() == '>' => {
20-
nesting = nesting.checked_sub(1).unwrap();
21-
continue;
21+
for (seg, expected) in path
22+
.segments
23+
.iter()
24+
.rev()
25+
.zip(["PinnedDrop", "pin_init", ""])
26+
{
27+
if expected.is_empty() || seg.ident != expected {
28+
error.combine(Error::new_spanned(seg, "bad import path for `PinnedDrop`"));
29+
}
30+
if !seg.arguments.is_none() {
31+
error.combine(Error::new_spanned(
32+
&seg.arguments,
33+
"unexpected arguments for `PinnedDrop` path",
34+
));
35+
}
2236
}
23-
_ => {}
37+
*path = parse_quote!(::pin_init::PinnedDrop);
2438
}
25-
if i >= 1 && nesting == 0 {
26-
// Found the end of the generics, this should be `PinnedDrop`.
27-
assert!(
28-
matches!(tt, TokenTree::Ident(i) if i == "PinnedDrop"),
29-
"expected 'PinnedDrop', found: '{tt:?}'"
30-
);
31-
pinned_drop_idx = Some(i);
32-
break;
39+
None => {
40+
let span = input
41+
.impl_token
42+
.span
43+
.join(input.self_ty.span())
44+
.unwrap_or(input.impl_token.span);
45+
error.combine(Error::new(
46+
span,
47+
"expected `impl ... PinnedDrop for ...`, got inherent impl",
48+
));
3349
}
3450
}
35-
let idx = pinned_drop_idx
36-
.unwrap_or_else(|| panic!("Expected an `impl` block implementing `PinnedDrop`."));
37-
// Fully qualify the `PinnedDrop`, as to avoid any tampering.
38-
toks.splice(idx..idx, quote!(::pin_init::));
39-
// Take the `{}` body and call the declarative macro.
40-
if let Some(TokenTree::Group(last)) = toks.pop() {
41-
let last = last.stream();
42-
quote!(::pin_init::__pinned_drop! {
43-
@impl_sig(#(#toks)*),
44-
@impl_body(#last),
45-
})
46-
} else {
47-
TokenStream::from_iter(toks)
51+
for item in &mut input.items {
52+
if let ImplItem::Fn(fn_item) = item {
53+
if fn_item.sig.ident == "drop" {
54+
fn_item
55+
.sig
56+
.inputs
57+
.push(parse_quote!(_: ::pin_init::__internal::OnlyCallFromDrop));
58+
}
59+
}
4860
}
61+
quote!(#error #input)
4962
}

rust/pin-init/src/macros.rs

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -503,34 +503,6 @@ pub use ::macros::paste;
503503
#[cfg(not(kernel))]
504504
pub use ::paste::paste;
505505

506-
/// Creates a `unsafe impl<...> PinnedDrop for $type` block.
507-
///
508-
/// See [`PinnedDrop`] for more information.
509-
///
510-
/// [`PinnedDrop`]: crate::PinnedDrop
511-
#[doc(hidden)]
512-
#[macro_export]
513-
macro_rules! __pinned_drop {
514-
(
515-
@impl_sig($($impl_sig:tt)*),
516-
@impl_body(
517-
$(#[$($attr:tt)*])*
518-
fn drop($($sig:tt)*) {
519-
$($inner:tt)*
520-
}
521-
),
522-
) => {
523-
// SAFETY: TODO.
524-
unsafe $($impl_sig)* {
525-
// Inherit all attributes and the type/ident tokens for the signature.
526-
$(#[$($attr)*])*
527-
fn drop($($sig)*, _: $crate::__internal::OnlyCallFromDrop) {
528-
$($inner)*
529-
}
530-
}
531-
}
532-
}
533-
534506
/// This macro first parses the struct definition such that it separates pinned and not pinned
535507
/// fields. Afterwards it declares the struct and implement the `PinData` trait safely.
536508
#[doc(hidden)]

0 commit comments

Comments
 (0)