Skip to content

Commit a92f5fd

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!() }` Tested-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Signed-off-by: Benno Lossin <lossin@kernel.org>
1 parent 50426bd commit a92f5fd

3 files changed

Lines changed: 52 additions & 66 deletions

File tree

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
2828

2929
#[proc_macro_attribute]
3030
pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {
31-
pinned_drop::pinned_drop(args.into(), input.into()).into()
31+
let args = parse_macro_input!(args);
32+
let input = parse_macro_input!(input);
33+
DiagCtxt::with(|dcx| pinned_drop::pinned_drop(args, input, dcx)).into()
3234
}
3335

3436
#[proc_macro_derive(Zeroable)]
Lines changed: 49 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,61 @@
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, 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+
use crate::diagnostics::{DiagCtxt, ErrorGuaranteed};
8+
9+
pub(crate) fn pinned_drop(
10+
_args: Nothing,
11+
mut input: ItemImpl,
12+
dcx: &mut DiagCtxt,
13+
) -> Result<TokenStream, ErrorGuaranteed> {
14+
if let Some(unsafety) = input.unsafety {
15+
dcx.error(unsafety, "implementing `PinnedDrop` is safe");
16+
}
17+
input.unsafety = Some(Token![unsafe](input.impl_token.span));
18+
match &mut input.trait_ {
19+
Some((not, path, _for)) => {
20+
if let Some(not) = not {
21+
dcx.error(not, "cannot implement `!PinnedDrop`");
1822
}
19-
TokenTree::Punct(p) if p.as_char() == '>' => {
20-
nesting = nesting.checked_sub(1).unwrap();
21-
continue;
23+
for (seg, expected) in path
24+
.segments
25+
.iter()
26+
.rev()
27+
.zip(["PinnedDrop", "pin_init", ""])
28+
{
29+
if expected.is_empty() || seg.ident != expected {
30+
dcx.error(seg, "bad import path for `PinnedDrop`");
31+
}
32+
if !seg.arguments.is_none() {
33+
dcx.error(&seg.arguments, "unexpected arguments for `PinnedDrop` path");
34+
}
2235
}
23-
_ => {}
36+
*path = parse_quote!(::pin_init::PinnedDrop);
2437
}
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:?}'"
38+
None => {
39+
let span = input
40+
.impl_token
41+
.span
42+
.join(input.self_ty.span())
43+
.unwrap_or(input.impl_token.span);
44+
dcx.error(
45+
span,
46+
"expected `impl ... PinnedDrop for ...`, got inherent impl",
3047
);
31-
pinned_drop_idx = Some(i);
32-
break;
3348
}
3449
}
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)
50+
for item in &mut input.items {
51+
if let ImplItem::Fn(fn_item) = item {
52+
if fn_item.sig.ident == "drop" {
53+
fn_item
54+
.sig
55+
.inputs
56+
.push(parse_quote!(_: ::pin_init::__internal::OnlyCallFromDrop));
57+
}
58+
}
4859
}
60+
Ok(quote!(#input))
4961
}

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)