(
ast: &syn::DeriveInput,
generate_default: bool,
)
| 341 | } |
| 342 | |
| 343 | fn generate_default_impl( |
| 344 | ast: &syn::DeriveInput, |
| 345 | generate_default: bool, |
| 346 | ) -> proc_macro2::TokenStream { |
| 347 | let name = &ast.ident; |
| 348 | let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); |
| 349 | |
| 350 | // By default, we don't generate Default impl to avoid conflicts. |
| 351 | // Only generate if generate_default is true AND there's no existing Default. |
| 352 | let should_generate_default = generate_default && !has_existing_default(ast, "Default"); |
| 353 | |
| 354 | match &ast.data { |
| 355 | Data::Struct(s) => { |
| 356 | let source_fields = source_fields(&s.fields); |
| 357 | let is_tuple_struct = source_fields |
| 358 | .first() |
| 359 | .map(|sf| sf.is_tuple_struct) |
| 360 | .unwrap_or(false); |
| 361 | |
| 362 | // Generate field initializations with original index for sorting |
| 363 | let mut indexed: Vec<_> = source_fields |
| 364 | .iter() |
| 365 | .map(|sf| { |
| 366 | let value = super::field_codec::default_expr_for_type(&sf.field.ty); |
| 367 | (sf.original_index, sf.field_init(value)) |
| 368 | }) |
| 369 | .collect(); |
| 370 | |
| 371 | // For tuple structs, sort by original index |
| 372 | if is_tuple_struct { |
| 373 | indexed.sort_by_key(|(idx, _)| *idx); |
| 374 | } |
| 375 | |
| 376 | let field_inits: Vec<_> = indexed.into_iter().map(|(_, ts)| ts).collect(); |
| 377 | let self_construction = crate::util::self_construction(is_tuple_struct, &field_inits); |
| 378 | |
| 379 | if should_generate_default { |
| 380 | // User requested Default generation via #[fory(generate_default)] |
| 381 | quote! { |
| 382 | impl #impl_generics fory_core::ForyDefault for #name #ty_generics #where_clause { |
| 383 | fn fory_default() -> Self { |
| 384 | #self_construction |
| 385 | } |
| 386 | } |
| 387 | impl #impl_generics ::std::default::Default for #name #ty_generics #where_clause { |
| 388 | fn default() -> Self { |
| 389 | Self::fory_default() |
| 390 | } |
| 391 | } |
| 392 | } |
| 393 | } else { |
| 394 | // Default case: only generate ForyDefault, not Default |
| 395 | // This avoids conflicts with existing Default implementations |
| 396 | quote! { |
| 397 | impl #impl_generics fory_core::ForyDefault for #name #ty_generics #where_clause { |
| 398 | fn fory_default() -> Self { |
| 399 | #self_construction |
| 400 | } |
no test coverage detected