Skip to contentSkip to conversation

rust: pin-init: upstream synchronization for 7.4

PATCH Applied Gary Guo 3 participants 7 messages Sep 28 – Sep 30

Subsystems (2)
lore
Share & tools
lore

Gary Guo

author maintainer
#0 lore raw

cover rust: pin-init: upstream synchronization for 7.4

This sync series contain two upstream PRs:

- Several additional diagnostics improvements
https://github.com/Rust-for-Linux/pin-init/pull/179

- internal: init: allow reborrow of Pin<&mut T> bindings
https://github.com/Rust-for-Linux/pin-init/pull/180

The upstream PRs have test suites coverage which is not part of the kernel tree. Reviews/testings are welcome from either GitHub or the mailing list.

---
Gary Guo (3):
rust: pin-init: internal: init: allow reborrow of Pin<&mut T> bindings
rust: pin-init: internal: init: improve diagnostics from field checks
rust: pin-init: internal: init: use span of <- or : for the init/write call.

 rust/pin-init/internal/src/init.rs | 106 +++++++++++++++++++++++++------------
 1 file changed, 71 insertions(+), 35 deletions(-)

---
base-commit: 95593ed3616194c9498cc190cd1a3693ff4bca37
change-id: 20260928-dev-pin-init-sync-93e81b019c3c

Best regards,

Signature · 1 line
Gary Guo <[email protected]>
author maintainer
#1 lore raw

PATCH 1/3 rust: pin-init: internal: init: allow reborrow of `Pin<&mut T>` bindings

Use let mut for created bindings of initialized field, so Pin<&mut T> bindings may be reborrowed in subsequent initializers or code blocks.

Without let mut, attempt to reborrow can produce error (and also a confusing fix):

    error[E0596]: cannot borrow `gpu` as mutable, as it is not declared as mutable
       --> drivers/gpu/nova-core/driver.rs:129:17
        |
    129 |                 gpu.as_mut().run_selftests(pdev);
        |                 ^^^ cannot borrow as mutable
        |
    help: consider changing this to be mutable                                                                                                                                                                                  |
    119 |             mut gpu <- Gpu::new(
        |             +++

    error: aborting due to 1 previous error
---
 rust/pin-init/internal/src/init.rs | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
rust/pin-init/internal/src/init.rs +2 -1
index c5b5a0ce5c4e..4e77c7af86f9 100644
@@ -446,7 +446,8 @@ fn init_fields(fields: &Punctuated<InitializerField, Token![,]>, pinned: bool) -
                 // Allow `non_snake_case` since the same warning is going to be reported for the
                 // struct field.
                 #[allow(unused_variables, non_snake_case)]
-                let #ident = #guard.let_binding();
+                // Include `mut` so that `Pin<&mut T>` bindings can be reborrowed via `.as_mut()`.
+                let mut #ident = #guard.let_binding();
             },
             Member::Unnamed(_) => quote!(),
         };
Signature · 1 line
2.54.0
reviewer Tested-by Reviewed-by on v1 1/3
#2 lore raw

Re: [PATCH 1/3] rust: pin-init: internal: init: allow reborrow of `Pin<&mut T>` bindings

Quoted 18 lines · Gary Guo

Use let mut for created bindings of initialized field, so Pin<&mut T> bindings may be reborrowed in subsequent initializers or code blocks.

Without let mut, attempt to reborrow can produce error (and also a confusing fix):

    error[E0596]: cannot borrow `gpu` as mutable, as it is not declared as mutable
       --> drivers/gpu/nova-core/driver.rs:129:17
        |
    129 |                 gpu.as_mut().run_selftests(pdev);
        |                 ^^^ cannot borrow as mutable
        |
    help: consider changing this to be mutable                                                                                                                                                                                  |
    119 |             mut gpu <- Gpu::new(
        |             +++

    error: aborting due to 1 previous error
Quoted 3 lines
reviewer Reviewed-by on v1 1/3
#3 lore raw

Re: [PATCH 1/3] rust: pin-init: internal: init: allow reborrow of `Pin<&mut T>` bindings

In reply to Gary Guo
Quoted 18 lines · Gary Guo

Use let mut for created bindings of initialized field, so Pin<&mut T> bindings may be reborrowed in subsequent initializers or code blocks.

Without let mut, attempt to reborrow can produce error (and also a confusing fix):

    error[E0596]: cannot borrow `gpu` as mutable, as it is not declared as mutable
       --> drivers/gpu/nova-core/driver.rs:129:17
        |
    129 |                 gpu.as_mut().run_selftests(pdev);
        |                 ^^^ cannot borrow as mutable
        |
    help: consider changing this to be mutable                                                                                                                                                                                  |
    119 |             mut gpu <- Gpu::new(
        |             +++

    error: aborting due to 1 previous error
Quoted 3 lines

I've hit this issue a couple of times already, so it's a very welcome change!

FWIW,

author maintainer
#4 lore raw

PATCH 2/3 rust: pin-init: internal: init: improve diagnostics from field checks

In reply to Gary Guo

Use span of the field name for generated alignment and field duplication checks. This avoids pointing diagnostics to the full macro invocation, but just the part of it going wrong.

Before the change:

error[E0062]: field 0 specified more than once
--> tests/ui/compile-fail/init/tuple_duplicate_field.rs:7:37
|
7 | let _ = pin_init!(Tuple { 0: 1, 0: 2, 1: 3 });
| ------------------------^------------
| | |
| | used more than once
| first use of 0

After the change:

error[E0062]: field 0 specified more than once
--> tests/ui/compile-fail/init/tuple_duplicate_field.rs:7:37
|
7 | let _ = pin_init!(Tuple { 0: 1, 0: 2, 1: 3 });
| - ^ used more than once
| |
| first use of 0

---
 rust/pin-init/internal/src/init.rs | 65 ++++++++++++++++++++++++--------------
 1 file changed, 42 insertions(+), 23 deletions(-)
rust/pin-init/internal/src/init.rs +42 -23
index 4e77c7af86f9..f6f3e2f8cda6 100644
@@ -478,42 +478,61 @@ fn make_field_check(
     init_kind: InitKind,
     path: &Path,
 ) -> TokenStream {
-    let field_attrs: Vec<_> = fields
+    let align_checks: TokenStream = fields
         .iter()
-        .filter_map(|f| f.kind.member().map(|_| &f.attrs))
+        .filter_map(|f| {
+            let member = f.kind.member()?;
+            let span = member.span().resolved_at(Span::mixed_site());
+            let attrs = &f.attrs;
+
+            Some(quote_spanned! {span =>
+                // Create references to ensure that the initialized field is properly aligned.
+                // Unaligned fields will cause the compiler to emit E0793. We do not support
+                // unaligned fields since `Init::__init` requires an aligned pointer; the call to
+                // `ptr::write` for value-initialization case has the same requirement.
+                #(#attrs)*
+                let _ = &(*slot).#member;
+            })
+        })
+        .collect();
+
+    let fake_field_init: TokenStream = fields
+        .iter()
+        .filter_map(|f| {
+            let member = f.kind.member()?;
+            let span = member.span().resolved_at(Span::mixed_site());
+            let attrs = &f.attrs;
+
+            Some(quote_spanned! {span =>
+                #(#attrs)*
+                #member: loop {},
+            })
+        })
         .collect();
-    let field_name: Vec<_> = fields.iter().filter_map(|f| f.kind.member()).collect();
     let zeroing_trailer = match init_kind {
         InitKind::Normal => None,
         InitKind::Zeroing => Some(quote! {
             ..::core::mem::zeroed()
         }),
     };
+    let field_dup_checks = quote_spanned! { Span::mixed_site() =>
+        // If the zeroing trailer is not present, this checks that all fields have been
+        // mentioned exactly once. If the zeroing trailer is present, all missing fields will be
+        // zeroed, so this checks that all fields have been mentioned at most once. The use of
+        // struct initializer will still generate very natural error messages for any misuse.
+        ::core::ptr::write(slot, #path {
+            #fake_field_init
+            #zeroing_trailer
+        })
+    };
+
     quote_spanned! { Span::mixed_site() =>
         #[allow(unreachable_code)]
         // We use unreachable code to perform field checks. They're still checked by the compiler.
         // SAFETY: this code is never executed.
         let _ = || unsafe {
-            // Create references to ensure that the initialized field is properly aligned.
-            // Unaligned fields will cause the compiler to emit E0793. We do not support
-            // unaligned fields since `Init::__init` requires an aligned pointer; the call to
-            // `ptr::write` for value-initialization case has the same requirement.
-            #(
-                #(#field_attrs)*
-                let _ = &(*slot).#field_name;
-            )*
-
-            // If the zeroing trailer is not present, this checks that all fields have been
-            // mentioned exactly once. If the zeroing trailer is present, all missing fields will be
-            // zeroed, so this checks that all fields have been mentioned at most once. The use of
-            // struct initializer will still generate very natural error messages for any misuse.
-            ::core::ptr::write(slot, #path {
-                #(
-                    #(#field_attrs)*
-                    #field_name: loop {},
-                )*
-                #zeroing_trailer
-            })
+            #align_checks
+            #field_dup_checks
         };
     }
 }
Signature · 1 line
2.54.0
author maintainer
#5 lore raw

PATCH 3/3 rust: pin-init: internal: init: use span of `<-` or `:` for the init/write call.

In reply to Gary Guo

Currently we use the full span of the field initializer as the span of the generated init call. This produces overlapping spans for type mismatch errors, which is hard to read.

Use the span of <- or : for the method name, which wll cause type mismatch errors or trait bound not implemented error to be appear from the <- or : token, which declutter the output a bit and make it easier to read.

Before the change:

error[E0277]: impl pin_init::PinInit<Bar> cannot be used to movably initialize Bar with error _
--> tests/ui/compile-fail/init/invalid_init.rs:19:16
|
19 | bar <- Bar::new(),
| -------^^^^^^^^^^
| | |
| | the trait Init<Bar, _> is not implemented for impl pin_init::PinInit<Bar>
| required by a bound introduced by this call
|
= note: if your type implements PinInit but not Init, you might be forgetting a #[pin] annotation on fields

After the change:

error[E0277]: impl pin_init::PinInit<Bar> cannot be used to movably initialize Bar with error _
--> tests/ui/compile-fail/init/invalid_init.rs:19:16
|
19 | bar <- Bar::new(),
| -- ^^^^^^^^^^ the trait Init<Bar, _> is not implemented for impl pin_init::PinInit<Bar>
| |
| required by a bound introduced by this call
|
= note: if your type implements PinInit but not Init, you might be forgetting a #[pin] annotation on fields

---
 rust/pin-init/internal/src/init.rs | 38 +++++++++++++++++++++++++++-----------
 1 file changed, 27 insertions(+), 11 deletions(-)
rust/pin-init/internal/src/init.rs +27 -11
index f6f3e2f8cda6..6605e04d49df 100644
@@ -101,7 +101,7 @@ enum InitializerKind {
     },
     Init {
         member: Member,
-        _left_arrow_token: Token![<-],
+        left_arrow_token: Token![<-],
         value: Expr,
     },
     Code {
@@ -415,24 +415,40 @@ fn init_fields(fields: &Punctuated<InitializerField, Token![,]>, pinned: bool) -
 
         // `mixed_site` ensures that the guard is not accessible to the user-controlled code.
         let guard = format_ident!("__{ident}_guard", span = Span::mixed_site());
-        let full_span = kind.span();
+        let full_span = kind.span().resolved_at(Span::mixed_site());
 
         let init = match kind {
             InitializerKind::Value { value, .. } => {
-                let value = value
+                let (colon_span, value) = value
                     .as_ref()
-                    .map(|(_, value)| quote!(#value))
-                    .unwrap_or_else(|| quote!(#member));
+                    .map(|(colon_token, value)| (colon_token.span(), quote!(#value)))
+                    .unwrap_or_else(|| (member.span(), quote!(#member)));
+
+                // Use `:` as the span of the method name, so the type requirement appears to come
+                // from `:`.
+                let write =
+                    format_ident!("write", span = colon_span.resolved_at(Span::mixed_site()));
 
                 quote_spanned! { full_span =>
                     #(#attrs)*
-                    let mut #guard = #slot.write(#value);
+                    let mut #guard = #slot.#write(#value);
                 }
             }
-            InitializerKind::Init { value, .. } => {
+            InitializerKind::Init {
+                value,
+                left_arrow_token,
+                ..
+            } => {
+                // Use `<-` as the span of the method name, so the trait bound appears to come from
+                // `<-`.
+                let init = format_ident!(
+                    "init",
+                    span = left_arrow_token.span().resolved_at(Span::mixed_site())
+                );
+
                 quote_spanned! { full_span =>
                     #(#attrs)*
-                    let mut #guard = #slot.init(#value)?;
+                    let mut #guard = #slot.#init(#value)?;
                 }
             }
             InitializerKind::Code { .. } => unreachable!(),
@@ -690,7 +706,7 @@ fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
         if lh.peek(Token![<-]) {
             Ok(Self::Init {
                 member,
-                _left_arrow_token: input.parse()?,
+                left_arrow_token: input.parse()?,
                 value: input.parse()?,
             })
         } else if lh.peek(Token![:]) {
@@ -819,11 +835,11 @@ fn to_tokens(&self, tokens: &mut TokenStream) {
             }
             Self::Init {
                 member,
-                _left_arrow_token,
+                left_arrow_token,
                 value,
             } => {
                 member.to_tokens(tokens);
-                _left_arrow_token.to_tokens(tokens);
+                left_arrow_token.to_tokens(tokens);
                 value.to_tokens(tokens);
             }
             Self::Code {
Signature · 1 line
2.54.0
author maintainer Applied
#6 lore raw
In reply to Gary Guo
Quoted 11 lines · Gary Guo

This sync series contain two upstream PRs:

- Several additional diagnostics improvements
https://github.com/Rust-for-Linux/pin-init/pull/179

- internal: init: allow reborrow of Pin<&mut T> bindings
https://github.com/Rust-for-Linux/pin-init/pull/180

The upstream PRs have test suites coverage which is not part of the kernel tree. Reviews/testings are welcome from either GitHub or the mailing list.

Quoted 6 lines

---
Gary Guo (3):
rust: pin-init: internal: init: allow reborrow of Pin<&mut T> bindings
rust: pin-init: internal: init: improve diagnostics from field checks
rust: pin-init: internal: init: use span of <- or : for the init/write call.

Applied to pin-init-next. Thanks all!

Best,
Gary

Quoted 10 lines
 rust/pin-init/internal/src/init.rs | 106 +++++++++++++++++++++++++------------
 1 file changed, 71 insertions(+), 35 deletions(-)

---
base-commit: 95593ed3616194c9498cc190cd1a3693ff4bca37
change-id: 20260928-dev-pin-init-sync-93e81b019c3c

Best regards,

Signature · 1 line
Gary Guo <[email protected]>