euv-macros 0.52.0

Zero-overhead procedural macros for the cross-platform euv UI framework, providing view!, style!, var!, watch!, computed!, state!, #[store], #[component], #[event], emit!, on!, and #[euv].
Documentation
use super::*;

/// Expands `#[derive(Props)]` into `::euv::ComponentProps` initialization plus span-preserving fluent named-prop setters.
///
/// # Arguments
///
/// - `DeriveInput` - Parsed target struct definition.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - Generated `ComponentProps` and inherent fluent setter implementations.
pub(crate) fn expand_props_derive(input: DeriveInput) -> proc_macro2::TokenStream {
    let struct_ident: &Ident = &input.ident;
    let (impl_generics, ty_generics, where_clause): (
        ImplGenerics<'_>,
        TypeGenerics<'_>,
        Option<&WhereClause>,
    ) = input.generics.split_for_impl();
    let named_fields: &Punctuated<Field, Token![,]> = match &input.data {
        Data::Struct(data_struct) => match &data_struct.fields {
            Fields::Named(fields) => &fields.named,
            _ => {
                return Error::new(struct_ident.span(), ERR_PROPS_NAMED_STRUCT_ONLY)
                    .to_compile_error();
            }
        },
        _ => {
            return Error::new(struct_ident.span(), ERR_PROPS_NAMED_STRUCT_ONLY).to_compile_error();
        }
    };
    let mut init_fields: Vec<proc_macro2::TokenStream> = Vec::with_capacity(named_fields.len());
    let mut setters: Vec<proc_macro2::TokenStream> = Vec::with_capacity(named_fields.len());
    for field in named_fields.iter() {
        let Some(field_name) = field.ident.as_ref() else {
            continue;
        };
        let (skip_setter, default_expr): (bool, Option<Expr>) =
            match parse_prop_field_attrs(&field.attrs) {
                Ok(parsed) => parsed,
                Err(parse_error) => return parse_error.to_compile_error(),
            };
        let init_value: proc_macro2::TokenStream = match default_expr {
            Some(expr) => quote_spanned! {expr.span()=> #expr },
            None => quote_spanned! {field_name.span()=> ::core::default::Default::default() },
        };
        init_fields.push(quote_spanned! {field_name.span()=> #field_name: #init_value });
        if !skip_setter {
            let field_type: &Type = &field.ty;
            let setter_tokens: proc_macro2::TokenStream = if is_string_type(field_type) {
                quote_spanned! {field_name.span()=>
                    #[must_use]
                    #[cfg_attr(not(target_arch = "wasm32"), inline)]
                    pub fn #field_name<StringValue>(mut self, value: StringValue) -> Self
                    where
                        StringValue: ::core::convert::Into<::std::string::String>,
                    {
                        self.#field_name = ::core::convert::Into::into(value);
                        self
                    }
                }
            } else if is_option_style_type(field_type) {
                quote_spanned! {field_name.span()=>
                    #[must_use]
                    #[cfg_attr(not(target_arch = "wasm32"), inline)]
                    pub fn #field_name<StyleValue>(mut self, value: StyleValue) -> Self
                    where
                        StyleValue: ::core::convert::Into<#field_type>,
                    {
                        self.#field_name = ::core::convert::Into::into(value);
                        self
                    }
                }
            } else {
                quote_spanned! {field_name.span()=>
                    #[must_use]
                    #[cfg_attr(not(target_arch = "wasm32"), inline)]
                    pub fn #field_name(mut self, value: #field_type) -> Self {
                        self.#field_name = value;
                        self
                    }
                }
            };
            setters.push(setter_tokens);
        }
    }
    let setters_impl: proc_macro2::TokenStream = if setters.is_empty() {
        quote! {}
    } else {
        quote! {
        /// Implements `impl #impl_generics #struct_ident #ty_generics #where_clause`.
                    impl #impl_generics #struct_ident #ty_generics #where_clause {
                        #(#setters)*
                    }
                }
    };
    quote! {
    /// Implements `impl #impl_generics ::euv::ComponentProps for #struct_ident #ty_generics #where_clause`.
            impl #impl_generics ::euv::ComponentProps for #struct_ident #ty_generics #where_clause {
    /// Implements the `init_props` operation on [`Self`].
                #[cfg_attr(not(target_arch = "wasm32"), inline)]
                fn init_props() -> Self {
                    Self {
                        #(#init_fields),*
                    }
                }
            }
            #setters_impl
        }
}

/// Parses `#[prop(skip)]` and `#[prop(default = expr)]` attributes attached to a struct field.
///
/// # Arguments
///
/// - `&[Attribute]` - Field attributes slice.
///
/// # Returns
///
/// - `Result<(bool, Option<Expr>)>` - `(skip_setter, optional_default_expr)`.
fn parse_prop_field_attrs(attributes: &[Attribute]) -> Result<(bool, Option<Expr>)> {
    let mut skip_setter: bool = false;
    let mut default_expr: Option<Expr> = None;
    for attribute in attributes.iter() {
        if !attribute.path().is_ident(ATTR_PROP) {
            continue;
        }
        let nested_metas: Punctuated<Meta, Token![,]> =
            attribute.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?;
        for meta_item in nested_metas.into_iter() {
            match meta_item {
                Meta::Path(path) if path.is_ident(PROP_OPT_SKIP) => {
                    skip_setter = true;
                }
                Meta::NameValue(name_value) if name_value.path.is_ident(PROP_OPT_DEFAULT) => {
                    default_expr = Some(name_value.value);
                }
                other_meta => {
                    return Err(Error::new(other_meta.span(), ERR_PROPS_UNKNOWN_OPTION));
                }
            }
        }
    }
    Ok((skip_setter, default_expr))
}

/// Returns `true` when `field_type` is an unqualified or qualified `String` type without generic arguments.
///
/// # Arguments
///
/// - `&Type` - Field type AST to inspect.
///
/// # Returns
///
/// - `bool` - Whether `field_type` is `String`.
fn is_string_type(field_type: &Type) -> bool {
    let Type::Path(type_path) = field_type else {
        return false;
    };
    if type_path.qself.is_some() {
        return false;
    }
    let Some(last_segment) = type_path.path.segments.last() else {
        return false;
    };
    last_segment.ident == TYPE_NAME_STRING && matches!(last_segment.arguments, PathArguments::None)
}

/// Returns `true` when `field_type` is `Option<Style>` so `#[derive(Props)]` accepts `Style` or `Option<Style>` uniformly.
///
/// # Arguments
///
/// - `&Type` - Field type AST to inspect.
///
/// # Returns
///
/// - `bool` - Whether `field_type` is `Option<Style>`.
fn is_option_style_type(field_type: &Type) -> bool {
    let Type::Path(type_path) = field_type else {
        return false;
    };
    if type_path.qself.is_some() {
        return false;
    }
    let Some(last_segment) = type_path.path.segments.last() else {
        return false;
    };
    if last_segment.ident != TYPE_NAME_OPTION {
        return false;
    }
    let PathArguments::AngleBracketed(ref angle_args) = last_segment.arguments else {
        return false;
    };
    if angle_args.args.len() != 1 {
        return false;
    }
    let Some(GenericArgument::Type(Type::Path(inner_path))) = angle_args.args.first() else {
        return false;
    };
    if inner_path.qself.is_some() {
        return false;
    }
    let Some(inner_last) = inner_path.path.segments.last() else {
        return false;
    };
    inner_last.ident == TYPE_NAME_STYLE && matches!(inner_last.arguments, PathArguments::None)
}