euv-macros 0.48.6

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::*;

/// Classifies the return type of an `#[euv]` annotated function into unit, `Result<App, ...>`, or `NodeId`.
///
/// # Arguments
///
/// - `&ReturnType` - Parsed function return type annotation.
///
/// # Returns
///
/// - `EntryReturnKind` - Detected entry-point launch mode.
fn classify_entry_return(output: &ReturnType) -> EntryReturnKind {
    let ReturnType::Type(_, ret_ty) = output else {
        return EntryReturnKind::Unit;
    };
    match ret_ty.as_ref() {
        Type::Tuple(tup) if tup.elems.is_empty() => EntryReturnKind::Unit,
        Type::Path(type_path) => {
            let is_result: bool = type_path
                .path
                .segments
                .last()
                .map(|seg: &PathSegment| seg.ident == ENTRY_TYPE_RESULT)
                .unwrap_or(false);
            if is_result {
                EntryReturnKind::AppResult
            } else {
                EntryReturnKind::NodeId
            }
        }
        _ => EntryReturnKind::NodeId,
    }
}

/// Expands `#[euv]` on a root view, `App` builder, or `main` function into unified cross-platform entry points.
///
/// # Arguments
///
/// - `EuvAttrArgs` - Parsed attribute options.
/// - `ItemFn` - Annotated entry function item.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - Preserved entry function plus platform bootstrap entry points.
pub(crate) fn expand_euv_attr(args: EuvAttrArgs, mut func: ItemFn) -> proc_macro2::TokenStream {
    if func.sig.asyncness.is_some() {
        return Error::new(func.sig.fn_token.span(), ERR_EUV_NO_ASYNC).to_compile_error();
    }
    if !func.sig.inputs.is_empty() {
        return Error::new(func.sig.inputs.span(), ERR_EUV_NO_PARAMS).to_compile_error();
    }
    let ret_kind: EntryReturnKind = classify_entry_return(&func.sig.output);
    if !matches!(ret_kind, EntryReturnKind::NodeId)
        && let Some(opt_span) = args.first_opt_span
    {
        return Error::new(opt_span, ERR_EUV_WINDOW_OPTS_NODE_ONLY).to_compile_error();
    }
    let orig_name: String = func.sig.ident.to_string();
    let call_ident: Ident = if orig_name == ENTRY_FN_MAIN {
        let inner: Ident = Ident::new(ENTRY_FN_INNER, func.sig.ident.span());
        func.sig.ident = inner.clone();
        func.vis = Visibility::Inherited;
        inner
    } else {
        func.sig.ident.clone()
    };
    let launch_body: proc_macro2::TokenStream = match ret_kind {
        EntryReturnKind::Unit => quote! {
            #call_ident();
        },
        EntryReturnKind::AppResult => quote! {
            if let ::core::result::Result::Ok(mut __euv_app) = #call_ident() {
                let _ = __euv_app.step_frame();
            }
        },
        EntryReturnKind::NodeId => {
            let mut win_stmts: Vec<proc_macro2::TokenStream> = Vec::new();
            if let Some(title) = args.title {
                win_stmts.push(quote_spanned! {title.span()=>
                    __euv_win.set_title(::std::string::String::from(#title));
                });
            }
            if let Some(width) = args.width {
                win_stmts.push(quote_spanned! {width.span()=>
                    __euv_win.set_width(#width);
                });
            }
            if let Some(height) = args.height {
                win_stmts.push(quote_spanned! {height.span()=>
                    __euv_win.set_height(#height);
                });
            }
            if let Some(mode) = args.render {
                let render_expr: proc_macro2::TokenStream = match mode {
                    EntryRenderMode::Auto => quote! { ::euv::RenderConfig::default() },
                    EntryRenderMode::Software => quote! { ::euv::RenderConfig::software() },
                    EntryRenderMode::Hardware => quote! { ::euv::RenderConfig::hardware() },
                    EntryRenderMode::Hybrid => quote! { ::euv::RenderConfig::hybrid() },
                };
                win_stmts.push(quote! {
                    __euv_win.set_render(#render_expr);
                });
            }
            if let Some(fs_lit) = args.fullscreen {
                if fs_lit.value() {
                    win_stmts.push(quote_spanned! {fs_lit.span()=>
                        __euv_win.set_fullscreen(::euv::FullscreenMode::Borderless);
                    });
                } else {
                    win_stmts.push(quote_spanned! {fs_lit.span()=>
                        __euv_win.set_fullscreen(::euv::FullscreenMode::Windowed);
                    });
                }
            }
            let use_headless: bool = args
                .headless
                .map(|lit: LitBool| lit.value())
                .unwrap_or(false);
            let app_ctor: proc_macro2::TokenStream = if use_headless {
                quote! { ::euv::App::headless }
            } else {
                quote! { ::euv::App::new }
            };
            let win_init: proc_macro2::TokenStream = if win_stmts.is_empty() {
                quote! {
                    let __euv_win: ::euv::WindowConfig = ::euv::WindowConfig::default();
                }
            } else {
                quote! {
                    let mut __euv_win: ::euv::WindowConfig = ::euv::WindowConfig::default();
                    #(#win_stmts)*
                }
            };
            quote! {
                #win_init
                let mut __euv_cfg: ::euv::AppConfig = ::euv::AppConfig::default();
                __euv_cfg.set_window(__euv_win);
                if let ::core::result::Result::Ok(mut __euv_app) = #app_ctor(__euv_cfg) {
                    let _: ::euv::NodeId = __euv_app.mount(#call_ident);
                    let _ = __euv_app.step_frame();
                }
            }
        }
    };
    let arch_wasm32: &str = CFG_ARCH_WASM32;
    let os_wasi: &str = CFG_OS_WASI;
    let os_android: &str = CFG_OS_ANDROID;
    let os_ios: &str = CFG_OS_IOS;
    let os_watchos: &str = CFG_OS_WATCHOS;
    let os_tvos: &str = CFG_OS_TVOS;
    let os_visionos: &str = CFG_OS_VISIONOS;
    let os_nuttx: &str = CFG_OS_NUTTX;
    let env_ohos: &str = CFG_ENV_OHOS;
    quote! {
        #func
        /// Launches the `#[euv]` application across the active platform runtime.
        fn __euv_launch() {
            #launch_body
        }
        /// Native desktop and TUI/CLI entry point.
        #[cfg(not(any(
            target_arch = #arch_wasm32,
            target_os = #os_android,
            target_os = #os_ios,
            target_os = #os_watchos,
            target_os = #os_tvos,
            target_os = #os_visionos,
            target_os = #os_nuttx,
            target_env = #env_ohos
        )))]
        fn main() {
            __euv_launch();
        }
        /// WebAssembly browser application entry point.
        #[cfg(all(target_arch = #arch_wasm32, not(target_os = #os_wasi)))]
        #[::wasm_bindgen::prelude::wasm_bindgen(start)]
        pub fn euv_web_start() {
            __euv_launch();
        }
        /// WebAssembly MiniApp and QuickApp host entry point.
        #[cfg(target_arch = #arch_wasm32)]
        #[unsafe(no_mangle)]
        pub extern "C" fn euv_miniapp_entry() {
            __euv_launch();
        }
        /// WebAssembly vivo BlueOS Watch host entry point.
        #[cfg(target_arch = #arch_wasm32)]
        #[unsafe(no_mangle)]
        pub extern "C" fn euv_blueos_entry() {
            __euv_launch();
        }
        /// WebAssembly WASI CLI/TUI entry point.
        #[cfg(all(target_arch = #arch_wasm32, target_os = #os_wasi))]
        fn main() {
            __euv_launch();
        }
        /// Android and WearOS native entry point.
        #[cfg(target_os = #os_android)]
        #[unsafe(no_mangle)]
        pub extern "C" fn euv_android_entry() {
            __euv_launch();
        }
        /// iOS and iPadOS native entry point.
        #[cfg(target_os = #os_ios)]
        #[unsafe(no_mangle)]
        pub extern "C" fn euv_ios_entry() {
            __euv_launch();
        }
        /// HarmonyOS native entry point across phone, tablet, PC, foldable, TV, car, and wearable devices.
        #[cfg(target_env = #env_ohos)]
        #[unsafe(no_mangle)]
        pub extern "C" fn euv_harmony_entry() {
            __euv_launch();
        }
        /// Wearable and spatial native entry point (watchOS, NuttX/Vela, tvOS, visionOS).
        #[cfg(any(
            target_os = #os_watchos,
            target_os = #os_nuttx,
            target_os = #os_tvos,
            target_os = #os_visionos
        ))]
        #[unsafe(no_mangle)]
        pub extern "C" fn euv_wearable_entry() {
            __euv_launch();
        }
    }
}