1use proc_macro2::{Span, TokenStream};
4use quote::{format_ident, quote, quote_spanned};
5use syn::{
6 braced,
7 parse::{End, Parse},
8 parse_quote,
9 punctuated::Punctuated,
10 spanned::Spanned,
11 token, Attribute, Block, Expr, ExprCall, ExprPath, Ident, Path, Token, Type,
12};
13
14use crate::diagnostics::{DiagCtxt, ErrorGuaranteed};
15
16pub(crate) struct Initializer {
17 attrs: Vec<InitializerAttribute>,
18 this: Option<This>,
19 path: Path,
20 brace_token: token::Brace,
21 fields: Punctuated<InitializerField, Token![,]>,
22 rest: Option<(Token![..], Expr)>,
23 error: Option<(Token![?], Type)>,
24}
25
26struct This {
27 _and_token: Token![&],
28 ident: Ident,
29 _in_token: Token![in],
30}
31
32struct InitializerField {
33 attrs: Vec<Attribute>,
34 kind: InitializerKind,
35}
36
37enum InitializerKind {
38 Value {
39 ident: Ident,
40 value: Option<(Token![:], Expr)>,
41 },
42 Init {
43 ident: Ident,
44 _left_arrow_token: Token![<-],
45 value: Expr,
46 },
47 Code {
48 _underscore_token: Token![_],
49 _colon_token: Token![:],
50 block: Block,
51 },
52}
53
54impl InitializerKind {
55 fn ident(&self) -> Option<&Ident> {
56 match self {
57 Self::Value { ident, .. } | Self::Init { ident, .. } => Some(ident),
58 Self::Code { .. } => None,
59 }
60 }
61}
62
63enum InitializerAttribute {
64 DefaultError(DefaultErrorAttribute),
65}
66
67struct DefaultErrorAttribute {
68 ty: Box<Type>,
69}
70
71pub(crate) fn expand(
72 Initializer {
73 attrs,
74 this,
75 path,
76 brace_token,
77 fields,
78 rest,
79 error,
80 }: Initializer,
81 default_error: Option<&'static str>,
82 pinned: bool,
83 dcx: &mut DiagCtxt,
84) -> Result<TokenStream, ErrorGuaranteed> {
85 let error = error.map_or_else(
86 || {
87 if let Some(default_error) = attrs.iter().fold(None, |acc, attr| {
88 #[expect(irrefutable_let_patterns)]
89 if let InitializerAttribute::DefaultError(DefaultErrorAttribute { ty }) = attr {
90 Some(ty.clone())
91 } else {
92 acc
93 }
94 }) {
95 default_error
96 } else if let Some(default_error) = default_error {
97 syn::parse_str(default_error).unwrap()
98 } else {
99 dcx.error(brace_token.span.close(), "expected `? <type>` after `}`");
100 parse_quote!(::core::convert::Infallible)
101 }
102 },
103 |(_, err)| Box::new(err),
104 );
105 let slot = format_ident!("slot");
106 let (has_data_trait, data_trait, get_data, init_from_closure) = if pinned {
107 (
108 format_ident!("HasPinData"),
109 format_ident!("PinData"),
110 format_ident!("__pin_data"),
111 format_ident!("pin_init_from_closure"),
112 )
113 } else {
114 (
115 format_ident!("HasInitData"),
116 format_ident!("InitData"),
117 format_ident!("__init_data"),
118 format_ident!("init_from_closure"),
119 )
120 };
121 let init_kind = get_init_kind(rest, dcx);
122 let zeroable_check = match init_kind {
123 InitKind::Normal => quote!(),
124 InitKind::Zeroing => quote! {
125 fn assert_zeroable<T: ?::core::marker::Sized>(_: *mut T)
130 where T: ::pin_init::Zeroable
131 {}
132 assert_zeroable(#slot);
134 unsafe { ::core::ptr::write_bytes(#slot, 0, 1) };
136 },
137 };
138 let this = match this {
139 None => quote!(),
140 Some(This { ident, .. }) => quote! {
141 let #ident = unsafe { ::core::ptr::NonNull::new_unchecked(slot) };
144 },
145 };
146 let data = Ident::new("__data", Span::mixed_site());
148 let init_fields = init_fields(&fields, pinned, &data, &slot);
149 let field_check = make_field_check(&fields, init_kind, &path);
150 Ok(quote! {{
151 let #data = unsafe {
154 use ::pin_init::__internal::#has_data_trait;
155 #path::#get_data()
158 };
159 let init = ::pin_init::__internal::#data_trait::make_closure::<_, #error>(
161 #data,
162 move |slot| {
163 #zeroable_check
164 #this
165 #init_fields
166 #field_check
167 Ok(unsafe { ::pin_init::__internal::InitOk::new() })
169 }
170 );
171 let init = move |slot| -> ::core::result::Result<(), #error> {
172 init(slot).map(|__InitOk| ())
173 };
174 unsafe { ::pin_init::#init_from_closure::<_, #error>(init) }
176 }})
177}
178
179enum InitKind {
180 Normal,
181 Zeroing,
182}
183
184fn get_init_kind(rest: Option<(Token![..], Expr)>, dcx: &mut DiagCtxt) -> InitKind {
185 let Some((dotdot, expr)) = rest else {
186 return InitKind::Normal;
187 };
188 match &expr {
189 Expr::Call(ExprCall { func, args, .. }) if args.is_empty() => match &**func {
190 Expr::Path(ExprPath {
191 attrs,
192 qself: None,
193 path:
194 Path {
195 leading_colon: None,
196 segments,
197 },
198 }) if attrs.is_empty()
199 && segments.len() == 2
200 && segments[0].ident == "Zeroable"
201 && segments[0].arguments.is_none()
202 && segments[1].ident == "init_zeroed"
203 && segments[1].arguments.is_none() =>
204 {
205 return InitKind::Zeroing;
206 }
207 _ => {}
208 },
209 _ => {}
210 }
211 dcx.error(
212 dotdot.span().join(expr.span()).unwrap_or(expr.span()),
213 "expected nothing or `..Zeroable::init_zeroed()`.",
214 );
215 InitKind::Normal
216}
217
218fn init_fields(
220 fields: &Punctuated<InitializerField, Token![,]>,
221 pinned: bool,
222 data: &Ident,
223 slot: &Ident,
224) -> TokenStream {
225 let mut guards = vec![];
226 let mut guard_attrs = vec![];
227 let mut res = TokenStream::new();
228 for InitializerField { attrs, kind } in fields {
229 let cfgs = {
230 let mut cfgs = attrs.clone();
231 cfgs.retain(|attr| attr.path().is_ident("cfg"));
232 cfgs
233 };
234 let init = match kind {
235 InitializerKind::Value { ident, value } => {
236 let mut value_ident = ident.clone();
237 let value_prep = value.as_ref().map(|value| &value.1).map(|value| {
238 value_ident.set_span(value.span());
241 quote!(let #value_ident = #value;)
242 });
243 let write = quote_spanned!(ident.span()=> ::core::ptr::write);
245 quote! {
246 #(#attrs)*
247 {
248 #value_prep
249 unsafe { #write(&raw mut (*#slot).#ident, #value_ident) };
251 }
252 }
253 }
254 InitializerKind::Init { ident, value, .. } => {
255 let init = format_ident!("init", span = value.span());
257 let value_init = if pinned {
258 quote! {
259 unsafe { #data.#ident(&raw mut (*#slot).#ident, #init)? };
265 }
266 } else {
267 quote! {
268 unsafe {
271 ::pin_init::Init::__init(
272 #init,
273 &raw mut (*#slot).#ident,
274 )?
275 };
276 }
277 };
278 quote! {
279 #(#attrs)*
280 {
281 let #init = #value;
282 #value_init
283 }
284 }
285 }
286 InitializerKind::Code { block: value, .. } => quote! {
287 #(#attrs)*
288 #[allow(unused_braces)]
289 #value
290 },
291 };
292 res.extend(init);
293 if let Some(ident) = kind.ident() {
294 let guard = format_ident!("__{ident}_guard", span = Span::mixed_site());
296
297 let accessor = if pinned {
301 let project_ident = format_ident!("__project_{ident}");
302 quote! {
303 unsafe { #data.#project_ident(#guard.let_binding()) }
305 }
306 } else {
307 quote! {
308 #guard.let_binding()
309 }
310 };
311
312 res.extend(quote! {
313 #(#cfgs)*
314 let mut #guard = unsafe {
323 ::pin_init::__internal::DropGuard::new(
324 &raw mut (*slot).#ident
325 )
326 };
327
328 #(#cfgs)*
329 #[allow(unused_variables)]
330 let #ident = #accessor;
331 });
332 guards.push(guard);
333 guard_attrs.push(cfgs);
334 }
335 }
336 quote! {
337 #res
338 #(
341 #(#guard_attrs)*
342 ::core::mem::forget(#guards);
343 )*
344 }
345}
346
347fn make_field_check(
349 fields: &Punctuated<InitializerField, Token![,]>,
350 init_kind: InitKind,
351 path: &Path,
352) -> TokenStream {
353 let field_attrs: Vec<_> = fields
354 .iter()
355 .filter_map(|f| f.kind.ident().map(|_| &f.attrs))
356 .collect();
357 let field_name: Vec<_> = fields.iter().filter_map(|f| f.kind.ident()).collect();
358 let zeroing_trailer = match init_kind {
359 InitKind::Normal => None,
360 InitKind::Zeroing => Some(quote! {
361 ..::core::mem::zeroed()
362 }),
363 };
364 quote! {
365 #[allow(unreachable_code, clippy::diverging_sub_expression)]
366 let _ = || unsafe {
369 #(
374 #(#field_attrs)*
375 let _ = &(*slot).#field_name;
376 )*
377
378 ::core::ptr::write(slot, #path {
383 #(
384 #(#field_attrs)*
385 #field_name: ::core::panic!(),
386 )*
387 #zeroing_trailer
388 })
389 };
390 }
391}
392
393impl Parse for Initializer {
394 fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
395 let attrs = input.call(Attribute::parse_outer)?;
396 let this = input.peek(Token![&]).then(|| input.parse()).transpose()?;
397 let path = input.parse()?;
398 let content;
399 let brace_token = braced!(content in input);
400 let mut fields = Punctuated::new();
401 loop {
402 let lh = content.lookahead1();
403 if lh.peek(End) || lh.peek(Token![..]) {
404 break;
405 } else if lh.peek(Ident) || lh.peek(Token![_]) || lh.peek(Token![#]) {
406 fields.push_value(content.parse()?);
407 let lh = content.lookahead1();
408 if lh.peek(End) {
409 break;
410 } else if lh.peek(Token![,]) {
411 fields.push_punct(content.parse()?);
412 } else {
413 return Err(lh.error());
414 }
415 } else {
416 return Err(lh.error());
417 }
418 }
419 let rest = content
420 .peek(Token![..])
421 .then(|| Ok::<_, syn::Error>((content.parse()?, content.parse()?)))
422 .transpose()?;
423 let error = input
424 .peek(Token![?])
425 .then(|| Ok::<_, syn::Error>((input.parse()?, input.parse()?)))
426 .transpose()?;
427 let attrs = attrs
428 .into_iter()
429 .map(|a| {
430 if a.path().is_ident("default_error") {
431 a.parse_args::<DefaultErrorAttribute>()
432 .map(InitializerAttribute::DefaultError)
433 } else {
434 Err(syn::Error::new_spanned(a, "unknown initializer attribute"))
435 }
436 })
437 .collect::<Result<Vec<_>, _>>()?;
438 Ok(Self {
439 attrs,
440 this,
441 path,
442 brace_token,
443 fields,
444 rest,
445 error,
446 })
447 }
448}
449
450impl Parse for DefaultErrorAttribute {
451 fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
452 Ok(Self { ty: input.parse()? })
453 }
454}
455
456impl Parse for This {
457 fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
458 Ok(Self {
459 _and_token: input.parse()?,
460 ident: input.parse()?,
461 _in_token: input.parse()?,
462 })
463 }
464}
465
466impl Parse for InitializerField {
467 fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
468 let attrs = input.call(Attribute::parse_outer)?;
469 Ok(Self {
470 attrs,
471 kind: input.parse()?,
472 })
473 }
474}
475
476impl Parse for InitializerKind {
477 fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
478 let lh = input.lookahead1();
479 if lh.peek(Token![_]) {
480 Ok(Self::Code {
481 _underscore_token: input.parse()?,
482 _colon_token: input.parse()?,
483 block: input.parse()?,
484 })
485 } else if lh.peek(Ident) {
486 let ident = input.parse()?;
487 let lh = input.lookahead1();
488 if lh.peek(Token![<-]) {
489 Ok(Self::Init {
490 ident,
491 _left_arrow_token: input.parse()?,
492 value: input.parse()?,
493 })
494 } else if lh.peek(Token![:]) {
495 Ok(Self::Value {
496 ident,
497 value: Some((input.parse()?, input.parse()?)),
498 })
499 } else if lh.peek(Token![,]) || lh.peek(End) {
500 Ok(Self::Value { ident, value: None })
501 } else {
502 Err(lh.error())
503 }
504 } else {
505 Err(lh.error())
506 }
507 }
508}