//! From trait implementation generation for struct errors

use proc_macro2::TokenStream;
use quote::quote;

use crate::ir::StructDefinition;

/// Generate From<T> implementation for struct with #[from] field
pub fn generate_from_impl(ir: &StructDefinition) -> TokenStream {
    let name = &ir.name;
    let (impl_generics, ty_generics, where_clause) = ir.generics.split_for_impl();

    // Find field with #[from] attribute
    let Some(from_field) = ir.fields.iter().find(|f| f.is_from) else {
        return quote! {};
    };

    let field_type = &from_field.ty;
    let field_name = &from_field.rust_name;

    quote! {
        #[automatically_derived]
        impl #impl_generics ::std::convert::From<#field_type> for #name #ty_generics #where_clause {
            fn from(source: #field_type) -> Self {
                Self { #field_name: source }
            }
        }
    }
}
