| 1 |
// SPDX-License-Identifier: Apache-2.0 OR MIT |
| 2 |
|
| 3 |
use proc_macro2::{Span, TokenStream}; |
| 4 |
use quote::{format_ident, quote, quote_spanned}; |
| 5 |
use 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 |
|
| 14 |
use crate::diagnostics::{DiagCtxt, ErrorGuaranteed}; |
| 15 |
|
| 16 |
pub(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 |
|
| 26 |
struct This { |
| 27 |
_and_token: Token![&], |
| 28 |
ident: Ident, |
| 29 |
_in_token: Token![in], |
| 30 |
} |
| 31 |
|
| 32 |
struct InitializerField { |
| 33 |
attrs: Vec<Attribute>, |
| 34 |
kind: InitializerKind, |
| 35 |
} |
| 36 |
|
| 37 |
enum 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 |
|
| 54 |
impl 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 |
|
| 63 |
enum InitializerAttribute { |
| 64 |
DefaultError(DefaultErrorAttribute), |
| 65 |
} |
| 66 |
|
| 67 |
struct DefaultErrorAttribute { |
| 68 |
ty: Box<Type>, |
| 69 |
} |
| 70 |
|
| 71 |
pub(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 |
// The user specified `..Zeroable::zeroed()` at the end of the list of fields. |
| 126 |
// Therefore we check if the struct implements `Zeroable` and then zero the memory. |
| 127 |
// This allows us to also remove the check that all fields are present (since we |
| 128 |
// already set the memory to zero and that is a valid bit pattern). |
| 129 |
fn assert_zeroable<T: ?::core::marker::Sized>(_: *mut T) |
| 130 |
where T: ::pin_init::Zeroable |
| 131 |
{} |
| 132 |
// Ensure that the struct is indeed `Zeroable`. |
| 133 |
assert_zeroable(#slot); |
| 134 |
// SAFETY: The type implements `Zeroable` by the check above. |
| 135 |
unsafe { ::core::ptr::write_bytes(#slot, 0, 1) }; |
| 136 |
}, |
| 137 |
}; |
| 138 |
let this = match this { |
| 139 |
None => quote!(), |
| 140 |
Some(This { ident, .. }) => quote! { |
| 141 |
// Create the `this` so it can be referenced by the user inside of the |
| 142 |
// expressions creating the individual fields. |
| 143 |
let #ident = unsafe { ::core::ptr::NonNull::new_unchecked(slot) }; |
| 144 |
}, |
| 145 |
}; |
| 146 |
// `mixed_site` ensures that the data is not accessible to the user-controlled code. |
| 147 |
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 |
// Get the data about fields from the supplied type. |
| 152 |
// SAFETY: TODO |
| 153 |
let #data = unsafe { |
| 154 |
use ::pin_init::__internal::#has_data_trait; |
| 155 |
// Can't use `<#path as #has_data_trait>::#get_data`, since the user is able to omit |
| 156 |
// generics (which need to be present with that syntax). |
| 157 |
#path::#get_data() |
| 158 |
}; |
| 159 |
// Ensure that `#data` really is of type `#data` and help with type inference: |
| 160 |
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 |
// SAFETY: we are the `init!` macro that is allowed to call this. |
| 168 |
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 |
// SAFETY: TODO |
| 175 |
let init = unsafe { ::pin_init::#init_from_closure::<_, #error>(init) }; |
| 176 |
init |
| 177 |
}}) |
| 178 |
} |
| 179 |
|
| 180 |
enum InitKind { |
| 181 |
Normal, |
| 182 |
Zeroing, |
| 183 |
} |
| 184 |
|
| 185 |
fn get_init_kind(rest: Option<(Token![..], Expr)>, dcx: &mut DiagCtxt) -> InitKind { |
| 186 |
let Some((dotdot, expr)) = rest else { |
| 187 |
return InitKind::Normal; |
| 188 |
}; |
| 189 |
match &expr { |
| 190 |
Expr::Call(ExprCall { func, args, .. }) if args.is_empty() => match &**func { |
| 191 |
Expr::Path(ExprPath { |
| 192 |
attrs, |
| 193 |
qself: None, |
| 194 |
path: |
| 195 |
Path { |
| 196 |
leading_colon: None, |
| 197 |
segments, |
| 198 |
}, |
| 199 |
}) if attrs.is_empty() |
| 200 |
&& segments.len() == 2 |
| 201 |
&& segments[0].ident == "Zeroable" |
| 202 |
&& segments[0].arguments.is_none() |
| 203 |
&& segments[1].ident == "init_zeroed" |
| 204 |
&& segments[1].arguments.is_none() => |
| 205 |
{ |
| 206 |
return InitKind::Zeroing; |
| 207 |
} |
| 208 |
_ => {} |
| 209 |
}, |
| 210 |
_ => {} |
| 211 |
} |
| 212 |
dcx.error( |
| 213 |
dotdot.span().join(expr.span()).unwrap_or(expr.span()), |
| 214 |
"expected nothing or `..Zeroable::init_zeroed()`.", |
| 215 |
); |
| 216 |
InitKind::Normal |
| 217 |
} |
| 218 |
|
| 219 |
/// Generate the code that initializes the fields of the struct using the initializers in `field`. |
| 220 |
fn init_fields( |
| 221 |
fields: &Punctuated<InitializerField, Token![,]>, |
| 222 |
pinned: bool, |
| 223 |
data: &Ident, |
| 224 |
slot: &Ident, |
| 225 |
) -> TokenStream { |
| 226 |
let mut guards = vec![]; |
| 227 |
let mut guard_attrs = vec![]; |
| 228 |
let mut res = TokenStream::new(); |
| 229 |
for InitializerField { attrs, kind } in fields { |
| 230 |
let cfgs = { |
| 231 |
let mut cfgs = attrs.clone(); |
| 232 |
cfgs.retain(|attr| attr.path().is_ident("cfg")); |
| 233 |
cfgs |
| 234 |
}; |
| 235 |
let init = match kind { |
| 236 |
InitializerKind::Value { ident, value } => { |
| 237 |
let mut value_ident = ident.clone(); |
| 238 |
let value_prep = value.as_ref().map(|value| &value.1).map(|value| { |
| 239 |
// Setting the span of `value_ident` to `value`'s span improves error messages |
| 240 |
// when the type of `value` is wrong. |
| 241 |
value_ident.set_span(value.span()); |
| 242 |
quote!(let #value_ident = #value;) |
| 243 |
}); |
| 244 |
// Again span for better diagnostics |
| 245 |
let write = quote_spanned!(ident.span()=> ::core::ptr::write); |
| 246 |
quote! { |
| 247 |
#(#attrs)* |
| 248 |
{ |
| 249 |
#value_prep |
| 250 |
// SAFETY: TODO |
| 251 |
unsafe { #write(::core::ptr::addr_of_mut!((*#slot).#ident), #value_ident) }; |
| 252 |
} |
| 253 |
} |
| 254 |
} |
| 255 |
InitializerKind::Init { ident, value, .. } => { |
| 256 |
// Again span for better diagnostics |
| 257 |
let init = format_ident!("init", span = value.span()); |
| 258 |
let value_init = if pinned { |
| 259 |
quote! { |
| 260 |
// SAFETY: |
| 261 |
// - `slot` is valid, because we are inside of an initializer closure, we |
| 262 |
// return when an error/panic occurs. |
| 263 |
// - We also use `#data` to require the correct trait (`Init` or `PinInit`) |
| 264 |
// for `#ident`. |
| 265 |
unsafe { #data.#ident(::core::ptr::addr_of_mut!((*#slot).#ident), #init)? }; |
| 266 |
} |
| 267 |
} else { |
| 268 |
quote! { |
| 269 |
// SAFETY: `slot` is valid, because we are inside of an initializer |
| 270 |
// closure, we return when an error/panic occurs. |
| 271 |
unsafe { |
| 272 |
::pin_init::Init::__init( |
| 273 |
#init, |
| 274 |
::core::ptr::addr_of_mut!((*#slot).#ident), |
| 275 |
)? |
| 276 |
}; |
| 277 |
} |
| 278 |
}; |
| 279 |
quote! { |
| 280 |
#(#attrs)* |
| 281 |
{ |
| 282 |
let #init = #value; |
| 283 |
#value_init |
| 284 |
} |
| 285 |
} |
| 286 |
} |
| 287 |
InitializerKind::Code { block: value, .. } => quote! { |
| 288 |
#(#attrs)* |
| 289 |
#[allow(unused_braces)] |
| 290 |
#value |
| 291 |
}, |
| 292 |
}; |
| 293 |
res.extend(init); |
| 294 |
if let Some(ident) = kind.ident() { |
| 295 |
// `mixed_site` ensures that the guard is not accessible to the user-controlled code. |
| 296 |
let guard = format_ident!("__{ident}_guard", span = Span::mixed_site()); |
| 297 |
|
| 298 |
// NOTE: The reference is derived from the guard so that it only lives as long as the |
| 299 |
// guard does and cannot escape the scope. If it's created via `&mut (*#slot).#ident` |
| 300 |
// like the unaligned field guard, it will become effectively `'static`. |
| 301 |
let accessor = if pinned { |
| 302 |
let project_ident = format_ident!("__project_{ident}"); |
| 303 |
quote! { |
| 304 |
// SAFETY: the initialization is pinned. |
| 305 |
unsafe { #data.#project_ident(#guard.let_binding()) } |
| 306 |
} |
| 307 |
} else { |
| 308 |
quote! { |
| 309 |
#guard.let_binding() |
| 310 |
} |
| 311 |
}; |
| 312 |
|
| 313 |
res.extend(quote! { |
| 314 |
#(#cfgs)* |
| 315 |
// Create the drop guard. |
| 316 |
// |
| 317 |
// SAFETY: |
| 318 |
// - `&raw mut (*slot).#ident` is valid. |
| 319 |
// - `make_field_check` checks that `&raw mut (*slot).#ident` is properly aligned. |
| 320 |
// - `(*slot).#ident` has been initialized above. |
| 321 |
// - We only need the ownership to the pointee back when initialization has |
| 322 |
// succeeded, where we `forget` the guard. |
| 323 |
let mut #guard = unsafe { |
| 324 |
::pin_init::__internal::DropGuard::new( |
| 325 |
::core::ptr::addr_of_mut!((*slot).#ident) |
| 326 |
) |
| 327 |
}; |
| 328 |
|
| 329 |
#(#cfgs)* |
| 330 |
#[allow(unused_variables)] |
| 331 |
let #ident = #accessor; |
| 332 |
}); |
| 333 |
guards.push(guard); |
| 334 |
guard_attrs.push(cfgs); |
| 335 |
} |
| 336 |
} |
| 337 |
quote! { |
| 338 |
#res |
| 339 |
// If execution reaches this point, all fields have been initialized. Therefore we can now |
| 340 |
// dismiss the guards by forgetting them. |
| 341 |
#( |
| 342 |
#(#guard_attrs)* |
| 343 |
::core::mem::forget(#guards); |
| 344 |
)* |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
/// Generate the check for ensuring that every field has been initialized and aligned. |
| 349 |
fn make_field_check( |
| 350 |
fields: &Punctuated<InitializerField, Token![,]>, |
| 351 |
init_kind: InitKind, |
| 352 |
path: &Path, |
| 353 |
) -> TokenStream { |
| 354 |
let field_attrs: Vec<_> = fields |
| 355 |
.iter() |
| 356 |
.filter_map(|f| f.kind.ident().map(|_| &f.attrs)) |
| 357 |
.collect(); |
| 358 |
let field_name: Vec<_> = fields.iter().filter_map(|f| f.kind.ident()).collect(); |
| 359 |
let zeroing_trailer = match init_kind { |
| 360 |
InitKind::Normal => None, |
| 361 |
InitKind::Zeroing => Some(quote! { |
| 362 |
..::core::mem::zeroed() |
| 363 |
}), |
| 364 |
}; |
| 365 |
quote! { |
| 366 |
#[allow(unreachable_code, clippy::diverging_sub_expression)] |
| 367 |
// We use unreachable code to perform field checks. They're still checked by the compiler. |
| 368 |
// SAFETY: this code is never executed. |
| 369 |
let _ = || unsafe { |
| 370 |
// Create references to ensure that the initialized field is properly aligned. |
| 371 |
// Unaligned fields will cause the compiler to emit E0793. We do not support |
| 372 |
// unaligned fields since `Init::__init` requires an aligned pointer; the call to |
| 373 |
// `ptr::write` for value-initialization case has the same requirement. |
| 374 |
#( |
| 375 |
#(#field_attrs)* |
| 376 |
let _ = &(*slot).#field_name; |
| 377 |
)* |
| 378 |
|
| 379 |
// If the zeroing trailer is not present, this checks that all fields have been |
| 380 |
// mentioned exactly once. If the zeroing trailer is present, all missing fields will be |
| 381 |
// zeroed, so this checks that all fields have been mentioned at most once. The use of |
| 382 |
// struct initializer will still generate very natural error messages for any misuse. |
| 383 |
::core::ptr::write(slot, #path { |
| 384 |
#( |
| 385 |
#(#field_attrs)* |
| 386 |
#field_name: ::core::panic!(), |
| 387 |
)* |
| 388 |
#zeroing_trailer |
| 389 |
}) |
| 390 |
}; |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
impl Parse for Initializer { |
| 395 |
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { |
| 396 |
let attrs = input.call(Attribute::parse_outer)?; |
| 397 |
let this = input.peek(Token![&]).then(|| input.parse()).transpose()?; |
| 398 |
let path = input.parse()?; |
| 399 |
let content; |
| 400 |
let brace_token = braced!(content in input); |
| 401 |
let mut fields = Punctuated::new(); |
| 402 |
loop { |
| 403 |
let lh = content.lookahead1(); |
| 404 |
if lh.peek(End) || lh.peek(Token![..]) { |
| 405 |
break; |
| 406 |
} else if lh.peek(Ident) || lh.peek(Token![_]) || lh.peek(Token![#]) { |
| 407 |
fields.push_value(content.parse()?); |
| 408 |
let lh = content.lookahead1(); |
| 409 |
if lh.peek(End) { |
| 410 |
break; |
| 411 |
} else if lh.peek(Token![,]) { |
| 412 |
fields.push_punct(content.parse()?); |
| 413 |
} else { |
| 414 |
return Err(lh.error()); |
| 415 |
} |
| 416 |
} else { |
| 417 |
return Err(lh.error()); |
| 418 |
} |
| 419 |
} |
| 420 |
let rest = content |
| 421 |
.peek(Token![..]) |
| 422 |
.then(|| Ok::<_, syn::Error>((content.parse()?, content.parse()?))) |
| 423 |
.transpose()?; |
| 424 |
let error = input |
| 425 |
.peek(Token![?]) |
| 426 |
.then(|| Ok::<_, syn::Error>((input.parse()?, input.parse()?))) |
| 427 |
.transpose()?; |
| 428 |
let attrs = attrs |
| 429 |
.into_iter() |
| 430 |
.map(|a| { |
| 431 |
if a.path().is_ident("default_error") { |
| 432 |
a.parse_args::<DefaultErrorAttribute>() |
| 433 |
.map(InitializerAttribute::DefaultError) |
| 434 |
} else { |
| 435 |
Err(syn::Error::new_spanned(a, "unknown initializer attribute")) |
| 436 |
} |
| 437 |
}) |
| 438 |
.collect::<Result<Vec<_>, _>>()?; |
| 439 |
Ok(Self { |
| 440 |
attrs, |
| 441 |
this, |
| 442 |
path, |
| 443 |
brace_token, |
| 444 |
fields, |
| 445 |
rest, |
| 446 |
error, |
| 447 |
}) |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
impl Parse for DefaultErrorAttribute { |
| 452 |
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { |
| 453 |
Ok(Self { ty: input.parse()? }) |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
impl Parse for This { |
| 458 |
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { |
| 459 |
Ok(Self { |
| 460 |
_and_token: input.parse()?, |
| 461 |
ident: input.parse()?, |
| 462 |
_in_token: input.parse()?, |
| 463 |
}) |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
impl Parse for InitializerField { |
| 468 |
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { |
| 469 |
let attrs = input.call(Attribute::parse_outer)?; |
| 470 |
Ok(Self { |
| 471 |
attrs, |
| 472 |
kind: input.parse()?, |
| 473 |
}) |
| 474 |
} |
| 475 |
} |
| 476 |
|
| 477 |
impl Parse for InitializerKind { |
| 478 |
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { |
| 479 |
let lh = input.lookahead1(); |
| 480 |
if lh.peek(Token![_]) { |
| 481 |
Ok(Self::Code { |
| 482 |
_underscore_token: input.parse()?, |
| 483 |
_colon_token: input.parse()?, |
| 484 |
block: input.parse()?, |
| 485 |
}) |
| 486 |
} else if lh.peek(Ident) { |
| 487 |
let ident = input.parse()?; |
| 488 |
let lh = input.lookahead1(); |
| 489 |
if lh.peek(Token![<-]) { |
| 490 |
Ok(Self::Init { |
| 491 |
ident, |
| 492 |
_left_arrow_token: input.parse()?, |
| 493 |
value: input.parse()?, |
| 494 |
}) |
| 495 |
} else if lh.peek(Token![:]) { |
| 496 |
Ok(Self::Value { |
| 497 |
ident, |
| 498 |
value: Some((input.parse()?, input.parse()?)), |
| 499 |
}) |
| 500 |
} else if lh.peek(Token![,]) || lh.peek(End) { |
| 501 |
Ok(Self::Value { ident, value: None }) |
| 502 |
} else { |
| 503 |
Err(lh.error()) |
| 504 |
} |
| 505 |
} else { |
| 506 |
Err(lh.error()) |
| 507 |
} |
| 508 |
} |
| 509 |
} |