Skip to main content

cranpose_macros/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4use callback_param::CallbackParam;
5use held_callback::{HeldCallback, borrows};
6use packed_params::PackedParams;
7use proc_macro::TokenStream;
8use proc_macro_crate::{FoundCrate, crate_name};
9use proc_macro2::{Span, TokenStream as TokenStream2};
10use quote::quote;
11use returning_call::ReturningCall;
12use syn::{FnArg, Ident, ItemFn, Pat, PatType, ReturnType, Type, parse_macro_input};
13
14mod branch_groups;
15mod callback_param;
16mod composable_marker;
17mod constant_modifiers;
18mod held_callback;
19mod include_wgsl;
20#[cfg(feature = "localization")]
21mod localization;
22mod packed_params;
23mod preview;
24mod returning_call;
25mod worker_job;
26
27/// Localizes readable source text using the nearest localization provider.
28/// Named arguments use `name = expression`; optional literal metadata is
29/// `id`, `context`, `comment`, and `source_locale` (default `en`).
30///
31/// `tr!` compiles only inside a `#[composable]` function or a closure written
32/// in one. Elsewhere the build fails with "cannot find value
33/// `tr_runs_only_in_composables`": use [`message!`] there.
34#[cfg(feature = "localization")]
35#[proc_macro]
36pub fn tr(input: TokenStream) -> TokenStream {
37    localization::translate(input.into())
38        .unwrap_or_else(|error| error.to_compile_error())
39        .into()
40}
41
42/// Embeds WGSL files as one `&'static str`, joined in order, without their
43/// `//` comments or the whitespace round each line. Paths are relative to
44/// the calling file, as `include_str!` takes them, and a file with a `/*`
45/// block comment fails the build. Each line of a file stays a line, so a
46/// shader compiler's line numbers still point into a file included alone.
47///
48/// ```ignore
49/// const SURFACE_WGSL: &str = include_wgsl!("noise.wgsl", "surface.wgsl");
50/// ```
51#[proc_macro]
52pub fn include_wgsl(input: TokenStream) -> TokenStream {
53    let caller = proc_macro::Span::call_site().local_file();
54    include_wgsl::include_wgsl(input.into(), caller.as_deref())
55        .unwrap_or_else(|error| error.to_compile_error())
56        .into()
57}
58
59/// Embeds `<directory>/<locale>/<namespace>.ftl` catalogs and checks them at compile time.
60/// Syntax: `translations!("locales", fallback = "en")`.
61#[cfg(feature = "localization")]
62#[proc_macro]
63pub fn translations(input: TokenStream) -> TokenStream {
64    localization::catalogs(input.into())
65        .unwrap_or_else(|error| error.to_compile_error())
66        .into()
67}
68
69/// Captures readable source text and arguments for translation when displayed.
70/// Accepts the same syntax as `tr!`, but works outside composition.
71#[cfg(feature = "localization")]
72#[proc_macro]
73pub fn message(input: TokenStream) -> TokenStream {
74    localization::message(input.into())
75        .unwrap_or_else(|error| error.to_compile_error())
76        .into()
77}
78
79/// Generates a module of named message accessors from a source-language Fluent file.
80/// Syntax: `translation_messages!(pub mod messages, "locales/en/app.ftl")`.
81#[cfg(feature = "localization")]
82#[proc_macro]
83pub fn translation_messages(input: TokenStream) -> TokenStream {
84    localization::bindings(input.into())
85        .unwrap_or_else(|error| error.to_compile_error())
86        .into()
87}
88#[cfg(test)]
89#[path = "tests/preview_tests.rs"]
90mod preview_tests;
91
92/// Makes a function a job that `LaunchedEffectScope::launch_worker` runs off
93/// the UI thread: on a thread where the platform has threads, in a Web Worker
94/// in a browser.
95///
96/// The function takes one parameter and returns a value. Both types implement
97/// `WorkerData`. The function's name is the job's name, one of a kind in the
98/// app. The attribute replaces the function with a unit type of the same
99/// name, which is what `launch_worker` takes.
100#[proc_macro_attribute]
101pub fn worker_job(_args: TokenStream, item: TokenStream) -> TokenStream {
102    let item = syn::parse_macro_input!(item as ItemFn);
103    worker_job::expand(&item)
104        .unwrap_or_else(|error| error.to_compile_error())
105        .into()
106}
107
108/// Registers a parameterless component fixture for IDE previews.
109///
110/// Enable Cranpose's `preview` feature. Options are `name`, `group`, `width`,
111/// `height`, and `dark`. Combine this attribute with `#[composable]`.
112#[proc_macro_attribute]
113pub fn preview(args: TokenStream, item: TokenStream) -> TokenStream {
114    let function = parse_macro_input!(item as ItemFn);
115    preview::expand(args.into(), function)
116        .unwrap_or_else(|error| error.to_compile_error())
117        .into()
118}
119
120fn is_fn_like_type(ty: &Type) -> bool {
121    match ty {
122        Type::ImplTrait(impl_trait) => impl_trait.bounds.iter().any(|bound| {
123            if let syn::TypeParamBound::Trait(trait_bound) = bound {
124                let path = &trait_bound.path;
125                if let Some(segment) = path.segments.last() {
126                    let ident_str = segment.ident.to_string();
127                    return ident_str == "FnMut" || ident_str == "Fn" || ident_str == "FnOnce";
128                }
129            }
130            false
131        }),
132        Type::Path(type_path) => {
133            if let Some(segment) = type_path.path.segments.last()
134                && segment.ident == "Box"
135                && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
136                && let Some(syn::GenericArgument::Type(Type::TraitObject(trait_obj))) =
137                    args.args.first()
138            {
139                return trait_obj.bounds.iter().any(|bound| {
140                    if let syn::TypeParamBound::Trait(trait_bound) = bound {
141                        let path = &trait_bound.path;
142                        if let Some(segment) = path.segments.last() {
143                            let ident_str = segment.ident.to_string();
144                            return ident_str == "FnMut"
145                                || ident_str == "Fn"
146                                || ident_str == "FnOnce";
147                        }
148                    }
149                    false
150                });
151            }
152            false
153        }
154        Type::FnPtr(_) => true,
155        _ => false,
156    }
157}
158
159fn is_generic_fn_like(ty: &Type, generics: &syn::Generics) -> bool {
160    let type_ident = match ty {
161        Type::Path(type_path) if type_path.path.segments.len() == 1 => {
162            &type_path.path.segments[0].ident
163        }
164        _ => return false,
165    };
166
167    for param in &generics.params {
168        if let syn::GenericParam::Type(type_param) = param
169            && type_param.ident == *type_ident
170        {
171            for bound in &type_param.bounds {
172                if let syn::TypeParamBound::Trait(trait_bound) = bound
173                    && let Some(segment) = trait_bound.path.segments.last()
174                {
175                    let ident_str = segment.ident.to_string();
176                    if ident_str == "FnMut" || ident_str == "Fn" || ident_str == "FnOnce" {
177                        return true;
178                    }
179                }
180            }
181        }
182    }
183
184    if let Some(where_clause) = &generics.where_clause {
185        for predicate in &where_clause.predicates {
186            if let syn::WherePredicate::Type(pred) = predicate
187                && let Type::Path(bounded_type) = &pred.bounded_ty
188                && bounded_type.path.segments.len() == 1
189                && bounded_type.path.segments[0].ident == *type_ident
190            {
191                for bound in &pred.bounds {
192                    if let syn::TypeParamBound::Trait(trait_bound) = bound
193                        && let Some(segment) = trait_bound.path.segments.last()
194                    {
195                        let ident_str = segment.ident.to_string();
196                        if ident_str == "FnMut" || ident_str == "Fn" || ident_str == "FnOnce" {
197                            return true;
198                        }
199                    }
200                }
201            }
202        }
203    }
204
205    false
206}
207
208/// A parameter of a `#[composable]` function.
209struct ParamInfo {
210    ident: Ident,
211    pat: Box<Pat>,
212    ty: Type,
213    pat_is_mut: bool,
214    is_impl_trait: bool,
215}
216
217fn is_fn_param(ty: &Type, generics: &syn::Generics) -> bool {
218    is_fn_like_type(ty) || is_generic_fn_like(ty, generics)
219}
220
221fn type_bare_generic_ident(ty: &Type) -> Option<&Ident> {
222    match ty {
223        Type::Path(type_path)
224            if type_path.qself.is_none()
225                && type_path.path.segments.len() == 1
226                && type_path.path.segments[0].arguments.is_none() =>
227        {
228            Some(&type_path.path.segments[0].ident)
229        }
230        _ => None,
231    }
232}
233
234fn stream_mentions_ident(tokens: &TokenStream2, name: &str) -> bool {
235    tokens.clone().into_iter().any(|tt| match tt {
236        proc_macro2::TokenTree::Ident(ident) => ident == name,
237        proc_macro2::TokenTree::Group(group) => stream_mentions_ident(&group.stream(), name),
238        _ => false,
239    })
240}
241
242fn filter_generics(
243    generics: &syn::Generics,
244    strip: &std::collections::BTreeSet<String>,
245) -> syn::Generics {
246    let mut filtered = generics.clone();
247    filtered.params = filtered
248        .params
249        .into_iter()
250        .filter(|param| match param {
251            syn::GenericParam::Type(type_param) => !strip.contains(&type_param.ident.to_string()),
252            _ => true,
253        })
254        .collect();
255    if let Some(where_clause) = &mut filtered.where_clause {
256        where_clause.predicates = where_clause
257            .predicates
258            .clone()
259            .into_iter()
260            .filter(|predicate| {
261                if let syn::WherePredicate::Type(pred) = predicate
262                    && let Some(ident) = type_bare_generic_ident(&pred.bounded_ty)
263                {
264                    return !strip.contains(&ident.to_string());
265                }
266                true
267            })
268            .collect();
269        if where_clause.predicates.is_empty() {
270            filtered.where_clause = None;
271        }
272    }
273    filtered
274}
275
276fn is_node_id_return(ty: &Type) -> bool {
277    matches!(
278        ty,
279        Type::Path(type_path)
280            if type_path
281                .path
282                .segments
283                .last()
284                .is_some_and(|segment| segment.ident == "NodeId")
285    )
286}
287
288fn core_crate_path() -> TokenStream2 {
289    let crate_name = crate_name("cranpose")
290        .ok()
291        .or_else(|| crate_name("cranpose-core").ok());
292
293    match crate_name {
294        Some(FoundCrate::Itself) => quote!(crate),
295        Some(FoundCrate::Name(name)) => {
296            let ident = Ident::new(&name, Span::call_site());
297            quote!(#ident)
298        }
299        None => quote!(cranpose_core),
300    }
301}
302
303/// The path of the crate that holds `Modifier`: the facade, which re-exports
304/// it, or cranpose-ui. `None` in a crate that has neither, where no chain is
305/// kept.
306fn ui_crate_path() -> Option<TokenStream2> {
307    let (package, found) = ["cranpose", "cranpose-ui"]
308        .into_iter()
309        .find_map(|package| crate_name(package).ok().map(|found| (package, found)))?;
310    // Both libraries take their own name with `extern crate self`, so the
311    // name serves in the library, its examples and its doctests alike.
312    let name = match found {
313        FoundCrate::Itself => package.replace('-', "_"),
314        FoundCrate::Name(name) => name,
315    };
316    let ident = Ident::new(&name, Span::call_site());
317    Some(quote!(#ident))
318}
319
320/// The key of a slot the expansion takes: a constant of the call site, or
321/// under hot reload, where a patch moves call sites, the caller's location
322/// as a call computes it.
323fn slot_key(core_path: &TokenStream2) -> TokenStream2 {
324    if cfg!(feature = "hot-reload") {
325        return quote! { #core_path::caller_location_key() };
326    }
327    quote! {{
328        const __CRANPOSE_SLOT_KEY: #core_path::Key =
329            #core_path::const_location_key(file!(), line!(), column!());
330        #core_path::noted_location_key(__CRANPOSE_SLOT_KEY, file!(), line!(), column!())
331    }}
332}
333
334fn definition_key_stmt(
335    core_path: &TokenStream2,
336    caller_key_ident: &Ident,
337    name: &Ident,
338) -> TokenStream2 {
339    if cfg!(feature = "hot-reload") {
340        // A hot patch moves definitions and may reuse a static cache for a
341        // different item. Development keys name the definition instead.
342        let name = name.to_string();
343        return quote! {
344            let #caller_key_ident = #core_path::composable_identity_key({
345                const __CRANPOSE_DEFINITION_KEY: #core_path::Key =
346                    #core_path::hot_definition_key(file!(), module_path!(), #name);
347                __CRANPOSE_DEFINITION_KEY
348            });
349        };
350    }
351    quote! {
352        let #caller_key_ident = #core_path::composable_identity_key({
353            struct __CranposeDefinitionMarker;
354            static __CRANPOSE_DEFINITION_KEY: ::std::sync::OnceLock<#core_path::Key> =
355                ::std::sync::OnceLock::new();
356            #core_path::cached_composable_definition_key(
357                &__CRANPOSE_DEFINITION_KEY,
358                file!(),
359                line!(),
360                column!(),
361                ::std::any::TypeId::of::<__CranposeDefinitionMarker>(),
362            )
363        });
364    }
365}
366
367/// Turns a function into a composable: its body runs inside a group keyed by
368/// the call site, and recomposition skips it while its arguments are
369/// unchanged. `#[composable(no_skip)]` always re-runs the body and stores no
370/// parameters: as Compose's inline composables, it composes in its caller's
371/// group, where what it composes is matched by position, as a loop's items
372/// are, so a state it or its content reads recomposes the composable that
373/// called it.
374///
375/// Composables are named in CamelCase, as in Jetpack Compose, so the
376/// generated function carries `#[allow(non_snake_case)]` and callers need no
377/// lint allowance of their own.
378#[proc_macro_attribute]
379pub fn composable(attr: TokenStream, item: TokenStream) -> TokenStream {
380    let attr_tokens = TokenStream2::from(attr);
381    let mut enable_skip = true;
382    let core_path = core_crate_path();
383    if !attr_tokens.is_empty() {
384        match syn::parse2::<Ident>(attr_tokens) {
385            Ok(ident) if ident == "no_skip" => enable_skip = false,
386            Ok(other) => {
387                return syn::Error::new_spanned(other, "unsupported composable attribute")
388                    .to_compile_error()
389                    .into();
390            }
391            Err(err) => {
392                return err.to_compile_error().into();
393            }
394        }
395    }
396
397    let mut func = parse_macro_input!(item as ItemFn);
398
399    let mut param_info: Vec<ParamInfo> = Vec::new();
400
401    for (index, arg) in func.sig.inputs.iter_mut().enumerate() {
402        if let FnArg::Typed(PatType { pat, ty, .. }) = arg {
403            if let Some(reserved) = find_reserved_pattern_ident(pat) {
404                let name = reserved.to_string();
405                return syn::Error::new(
406                    reserved.span(),
407                    format!("`{name}` is reserved by #[composable]"),
408                )
409                .to_compile_error()
410                .into();
411            }
412            let pat_is_mut = matches!(
413                pat.as_ref(),
414                Pat::Ident(pat_ident) if pat_ident.mutability.is_some()
415            );
416            let is_impl_trait = matches!(**ty, Type::ImplTrait(_));
417
418            if is_impl_trait {
419                let ident = if let Pat::Ident(pat_ident) = &**pat {
420                    pat_ident.ident.clone()
421                } else {
422                    Ident::new(&format!("__arg{index}"), Span::mixed_site())
423                };
424                param_info.push(ParamInfo {
425                    ident,
426                    pat: pat.clone(),
427                    ty: ty.as_ref().clone(),
428                    pat_is_mut,
429                    is_impl_trait: true,
430                });
431            } else {
432                let ident = Ident::new(&format!("__arg{index}"), Span::mixed_site());
433                let original_pat: Box<Pat> = pat.clone();
434                **pat = syn::parse_quote! { #ident };
435                param_info.push(ParamInfo {
436                    ident,
437                    pat: original_pat,
438                    ty: ty.as_ref().clone(),
439                    pat_is_mut,
440                    is_impl_trait: false,
441                });
442            }
443        }
444    }
445
446    inject_groups(&core_path, &mut func);
447    let has_rust_abi = match &func.sig.abi {
448        None => true,
449        Some(abi) => abi.name.as_ref().is_some_and(|name| name.value() == "Rust"),
450    };
451    if has_rust_abi {
452        func.attrs.push(syn::parse_quote!(#[track_caller]));
453    }
454    func.attrs.push(syn::parse_quote!(
455        #[allow(non_snake_case, reason = "names follow Compose's casing")]
456    ));
457
458    let scope_label_ident = func.sig.ident.clone();
459    let original_block = composable_marker::declared(&func.block);
460    let body_end = func.block.brace_token.span.close();
461    let composer_ident = Ident::new("__composer", Span::mixed_site());
462    let slot_key = slot_key(&core_path);
463    let caller_key_ident = Ident::new("__cranpose_caller_key", Span::mixed_site());
464    let result_ident = Ident::new("__result", Span::mixed_site());
465    let group_ident = Ident::new("__cranpose_group", Span::mixed_site());
466    let key_expr = quote! { #caller_key_ident };
467    let caller_key_stmt = definition_key_stmt(&core_path, &caller_key_ident, &scope_label_ident);
468
469    let rebinds_for_no_skip: Vec<_> = param_info
470        .iter()
471        .map(|info| {
472            let ident = &info.ident;
473            let pat = &info.pat;
474            quote! { let #pat = #ident; }
475        })
476        .collect();
477
478    let return_ty: Type = match &func.sig.output {
479        ReturnType::Default => syn::parse_quote! { () },
480        ReturnType::Type(_, ty) => ty.as_ref().clone(),
481    };
482    let returns_unit = returns_unit(&func.sig.output);
483    let invalidate_return_consumer = if returns_unit || is_node_id_return(&return_ty) {
484        quote! {}
485    } else {
486        quote! { #composer_ident.__invalidate_return_consumer_scope(); }
487    };
488    let _helper_ident = Ident::new(
489        &format!("__cranpose_impl_{}", func.sig.ident),
490        Span::mixed_site(),
491    );
492    let generics = func.sig.generics.clone();
493    let (_impl_generics, _ty_generics, _where_clause) = generics.split_for_impl();
494
495    let _helper_inputs: Vec<TokenStream2> = param_info
496        .iter()
497        .map(|info| {
498            let ident = &info.ident;
499            let ty = &info.ty;
500            quote! { #ident: #ty }
501        })
502        .collect();
503
504    let held: Vec<Option<HeldCallback>> = param_info
505        .iter()
506        .map(|info| HeldCallback::of(&info.ty, &func.sig.generics))
507        .collect();
508    // A borrowed parameter cannot be kept for a later comparison either.
509    let has_unhandled_impl_trait = param_info
510        .iter()
511        .zip(&held)
512        .any(|(info, held)| (info.is_impl_trait && held.is_none()) || borrows(&info.ty));
513
514    if enable_skip && !has_unhandled_impl_trait {
515        let helper_ident = Ident::new(
516            &format!("__cranpose_impl_{}", func.sig.ident),
517            Span::mixed_site(),
518        );
519        let generics = func.sig.generics.clone();
520
521        let param_state_slots: Vec<Ident> = (0..param_info.len())
522            .map(|index| Ident::new(&format!("__param_state_slot{index}"), Span::mixed_site()))
523            .collect();
524        let callbacks: Vec<Option<CallbackParam>> = param_info
525            .iter()
526            .zip(&param_state_slots)
527            .zip(&held)
528            .map(|((info, slot), held)| {
529                CallbackParam::of(&core_path, info, slot, held.as_ref(), &generics)
530            })
531            .collect();
532        let param_erased: Vec<bool> = callbacks
533            .iter()
534            .map(|callback| callback.as_ref().is_some_and(CallbackParam::boxes))
535            .collect();
536
537        let mut strippable: std::collections::BTreeSet<String> = param_info
538            .iter()
539            .zip(&param_erased)
540            .filter(|(info, erased)| **erased && !info.is_impl_trait)
541            .filter_map(|(info, _)| type_bare_generic_ident(&info.ty))
542            .map(Ident::to_string)
543            .collect();
544        loop {
545            use quote::ToTokens;
546            let mut used_elsewhere: Vec<TokenStream2> = Vec::new();
547            for (info, erased) in param_info.iter().zip(&param_erased) {
548                if !*erased {
549                    used_elsewhere.push(info.ty.to_token_stream());
550                }
551            }
552            used_elsewhere.push(return_ty.to_token_stream());
553            for param in &generics.params {
554                match param {
555                    syn::GenericParam::Type(type_param) => {
556                        if !strippable.contains(&type_param.ident.to_string()) {
557                            used_elsewhere.push(type_param.bounds.to_token_stream());
558                            if let Some((_, default)) = &type_param.default {
559                                used_elsewhere.push(default.to_token_stream());
560                            }
561                        }
562                    }
563                    syn::GenericParam::Const(const_param) => {
564                        used_elsewhere.push(const_param.ty.to_token_stream());
565                    }
566                    syn::GenericParam::Lifetime(_) => {}
567                }
568            }
569            if let Some(where_clause) = &generics.where_clause {
570                for predicate in &where_clause.predicates {
571                    if let syn::WherePredicate::Type(pred) = predicate
572                        && let Some(ident) = type_bare_generic_ident(&pred.bounded_ty)
573                        && strippable.contains(&ident.to_string())
574                    {
575                        continue;
576                    }
577                    used_elsewhere.push(predicate.to_token_stream());
578                }
579            }
580            let before = strippable.len();
581            strippable.retain(|name| {
582                !used_elsewhere
583                    .iter()
584                    .any(|tokens| stream_mentions_ident(tokens, name))
585            });
586            if strippable.len() == before {
587                break;
588            }
589        }
590
591        let helper_generics = filter_generics(&generics, &strippable);
592        let (impl_generics, ty_generics, where_clause) = helper_generics.split_for_impl();
593        let ty_generics_turbofish = ty_generics.as_turbofish();
594
595        let helper_inputs: Vec<TokenStream2> = param_info
596            .iter()
597            .zip(&callbacks)
598            .map(|(info, callback)| {
599                let ident = &info.ident;
600                match callback.as_ref().and_then(CallbackParam::boxed_type) {
601                    Some(boxed) => quote! { #ident: ::std::boxed::Box<#boxed> },
602                    None => {
603                        let ty = &info.ty;
604                        quote! { #ident: #ty }
605                    }
606                }
607            })
608            .collect();
609
610        let param_setup: Vec<TokenStream2> = callbacks
611            .iter()
612            .flatten()
613            .map(|callback| callback.setup(&core_path, &composer_ident))
614            .collect();
615        let param_setup_recompose: Vec<TokenStream2> = callbacks
616            .iter()
617            .flatten()
618            .map(|callback| callback.recompose_setup(&core_path, &composer_ident))
619            .collect();
620        let callback_rebinds: Vec<TokenStream2> = callbacks
621            .iter()
622            .flatten()
623            .map(|callback| callback.rebind(&core_path, &composer_ident))
624            .collect();
625
626        let body_inputs: Vec<TokenStream2> = param_info
627            .iter()
628            .zip(&callbacks)
629            .map(|(info, callback)| match callback {
630                Some(callback) => callback.body_input(&core_path),
631                None => {
632                    let pat = &info.pat;
633                    let ty = &info.ty;
634                    quote! { #pat: #ty }
635                }
636            })
637            .collect();
638        let body_args: Vec<&Ident> = param_info
639            .iter()
640            .zip(&callbacks)
641            .map(|(info, callback)| {
642                callback
643                    .as_ref()
644                    .map_or(&info.ident, |callback| callback.slot)
645            })
646            .collect();
647
648        let packed = PackedParams {
649            params: param_info
650                .iter()
651                .zip(&callbacks)
652                .filter(|(info, callback)| callback.is_none() && !info.is_impl_trait)
653                .map(|(info, _)| (&info.ident, &info.ty))
654                .collect(),
655            returns: (!returns_unit).then_some(&return_ty),
656        };
657        // Every parameter here is compared or is a held callback.
658        let skippable = true;
659        let param_setup = packed.with_setup(
660            &core_path,
661            &composer_ident,
662            (&ReturningCall::previous(), skippable),
663            param_setup,
664        );
665        let param_setup_recompose =
666            packed.with_slot(&core_path, &composer_ident, param_setup_recompose);
667        let reads_for_recompose = packed.reads(&core_path, &composer_ident);
668
669        let body_ident = Ident::new(
670            &format!("__cranpose_body_{}", func.sig.ident),
671            Span::mixed_site(),
672        );
673        let body_call = quote! {
674            #body_ident #ty_generics_turbofish (#composer_ident #(, #body_args)*)
675        };
676
677        let recompose_fn_ident = Ident::new(
678            &format!("__cranpose_recompose_{}", func.sig.ident),
679            Span::mixed_site(),
680        );
681
682        let recompose_fn = quote! { #recompose_fn_ident #ty_generics_turbofish };
683
684        let returning = ReturningCall {
685            core_path: &core_path,
686            composer: &composer_ident,
687            group: &group_ident,
688            scope_label: &scope_label_ident,
689            return_ty: &return_ty,
690            slot_key: &slot_key,
691            packed: &packed,
692            skippable,
693            body_call: &body_call,
694        };
695        let helper_body = if returns_unit {
696            unit_helper_body(&returning, &param_setup, &recompose_fn)
697        } else {
698            let setter =
699                recompose_setter(&group_ident, &recompose_fn, (&core_path, &composer_ident));
700            returning.helper_body(&param_setup, &setter)
701        };
702
703        let recompose_fn_body = if returns_unit {
704            quote! {
705                #(#param_setup_recompose)*
706                #(#reads_for_recompose)*
707                #body_call;
708            }
709        } else {
710            returning.recompose_body(
711                &param_setup_recompose,
712                &reads_for_recompose,
713                &invalidate_return_consumer,
714            )
715        };
716
717        let slot_origin = hot_slot_origin(&core_path, &func.sig.ident, body_end);
718        let recompose_fn = quote! {
719            #[allow(non_snake_case, reason = "names follow Compose's casing")]
720            fn #recompose_fn_ident #impl_generics (
721                #composer_ident: &#core_path::Composer
722            ) -> #return_ty #where_clause {
723                #slot_origin
724                #recompose_fn_body
725            }
726        };
727
728        let helper_fn = quote! {
729            #[allow(non_snake_case, clippy::too_many_arguments, reason = "the helper takes the composable's own parameters")]
730            fn #helper_ident #impl_generics (
731                #composer_ident: &#core_path::Composer,
732                #group_ident: &#core_path::ComposableGroup<'_>
733                #(, #helper_inputs)*
734            ) -> #return_ty #where_clause {
735                #slot_origin
736                #helper_body
737            }
738        };
739
740        let body_fn = quote! {
741            #[allow(non_snake_case, clippy::too_many_arguments, reason = "the helper takes the composable's own parameters")]
742            fn #body_ident #impl_generics (
743                #composer_ident: &#core_path::Composer
744                #(, #body_inputs)*
745            ) -> #return_ty #where_clause {
746                #(#callback_rebinds)*
747                let _cranpose_source_scope = #core_path::__source_scope(
748                    stringify!(#scope_label_ident), file!(), line!(), env!("CARGO_MANIFEST_DIR"),
749                );
750                #original_block
751            }
752        };
753
754        let wrapper_args: Vec<TokenStream2> = param_info
755            .iter()
756            .zip(&param_erased)
757            .map(|(info, erased)| {
758                let ident = &info.ident;
759                if *erased {
760                    quote! { ::std::boxed::Box::new(#ident) }
761                } else {
762                    quote! { #ident }
763                }
764            })
765            .collect();
766
767        let open_group = open_group_fn(returns_unit);
768        let wrapped = quote!({
769            #caller_key_stmt
770            let #composer_ident = #core_path::__current_composer();
771            let #group_ident = #composer_ident.#open_group(#key_expr);
772            let #result_ident = #helper_ident(
773                &#composer_ident,
774                &#group_ident
775                #(, #wrapper_args)*
776            );
777            #group_ident.close();
778            #result_ident
779        });
780        *func.block = syn::parse2(wrapped).expect("failed to build block");
781        TokenStream::from(quote! {
782            #body_fn
783            #recompose_fn
784            #helper_fn
785            #func
786        })
787    } else {
788        let wrapped = quote!({
789            #core_path::with_current_composer(|#composer_ident: &#core_path::Composer| {
790                #(#rebinds_for_no_skip)*
791                let _cranpose_source_scope = #core_path::__inline_source_scope(
792                    stringify!(#scope_label_ident), file!(), line!(), env!("CARGO_MANIFEST_DIR"),
793                );
794                #original_block
795            })
796        });
797        *func.block = syn::parse2(wrapped).expect("failed to build block");
798        TokenStream::from(quote! { #func })
799    }
800}
801
802/// Adds branch groups; with the development-only `hot-reload` feature the
803/// body also marks its definition as the origin for call-site keys.
804fn inject_groups(core_path: &TokenStream2, func: &mut ItemFn) {
805    let hot_reload = cfg!(feature = "hot-reload");
806    branch_groups::inject_branch_groups_with(
807        core_path,
808        &mut func.block,
809        &func.sig.ident,
810        hot_reload,
811    );
812    // A hot patch keeps the slots of unchanged code, so a kept chain whose
813    // constants it edits would stay as it was.
814    if !hot_reload && let Some(ui_path) = ui_crate_path() {
815        constant_modifiers::keep_constant_modifiers(core_path, &ui_path, &mut func.block);
816    }
817    if hot_reload {
818        let end = func.block.brace_token.span.close();
819        let origin = branch_groups::hot_origin_stmt(core_path, &func.sig.ident, end);
820        func.block
821            .stmts
822            .insert(0, syn::parse2(origin).expect("hot origin statement"));
823    }
824}
825
826// Whether a function returns `()`.
827fn returns_unit(output: &ReturnType) -> bool {
828    match output {
829        ReturnType::Default => true,
830        ReturnType::Type(_, ty) => {
831            matches!(ty.as_ref(), Type::Tuple(tuple) if tuple.elems.is_empty())
832        }
833    }
834}
835
836// The statement that gives the group of a composable that returns a value
837// its recompose function: a wrapper that drops the value.
838fn recompose_setter(
839    group: &Ident,
840    recompose_fn: &TokenStream2,
841    (core_path, composer): (&TokenStream2, &Ident),
842) -> TokenStream2 {
843    quote! {
844        #group.set_recompose_fn(|#composer: &#core_path::Composer| {
845            let _ = #recompose_fn(#composer);
846        });
847    }
848}
849
850// The helper body of a composable that returns nothing: one call gives the
851// group its recompose function, a plain function with no box, vtable or call
852// shim per composable, and says whether the body runs. It skips the body
853// when no parameter changed, and leaves it for a later frame when the group
854// opened in pausable content past the frame's budget.
855fn unit_helper_body(
856    call: &ReturningCall<'_>,
857    param_setup: &[TokenStream2],
858    recompose_fn: &TokenStream2,
859) -> TokenStream2 {
860    let (core_path, group) = (call.core_path, call.group);
861    let (scope_label, body_call) = (call.scope_label, call.body_call);
862    quote! {
863        #core_path::debug_label_current_scope(stringify!(#scope_label));
864        let mut __changed = #group.should_recompose();
865        #(#param_setup)*
866        if !#group.should_execute(__changed.into(), #recompose_fn) {
867            return;
868        }
869        #body_call
870    }
871}
872
873// The composer method that opens a composable's group: only a composable that
874// returns nothing may leave its first body for a later frame.
875fn open_group_fn(returns_unit: bool) -> Ident {
876    let name = if returns_unit {
877        "__open_pausable_group"
878    } else {
879        "__open_composable_group"
880    };
881    Ident::new(name, Span::call_site())
882}
883
884/// Parameter and return slots are keyed by call sites in generated code. With
885/// hot reload those keys follow the current origin, so the first composition
886/// and an independent recomposition both set the composable's own origin.
887fn hot_slot_origin(core_path: &TokenStream2, name: &Ident, end: Span) -> TokenStream2 {
888    if cfg!(feature = "hot-reload") {
889        branch_groups::hot_origin_stmt(core_path, name, end)
890    } else {
891        TokenStream2::new()
892    }
893}
894
895fn find_reserved_pattern_ident(pat: &Pat) -> Option<&Ident> {
896    use syn::visit::Visit;
897
898    struct Scan<'ast> {
899        found: Option<&'ast Ident>,
900    }
901    impl<'ast> Visit<'ast> for Scan<'ast> {
902        fn visit_pat_ident(&mut self, node: &'ast syn::PatIdent) {
903            if self.found.is_none() {
904                let name = node.ident.to_string();
905                if name == "__composer" || name.starts_with("__cranpose") {
906                    self.found = Some(&node.ident);
907                }
908            }
909            syn::visit::visit_pat_ident(self, node);
910        }
911    }
912    let mut scan = Scan { found: None };
913    scan.visit_pat(pat);
914    scan.found
915}
916
917#[cfg(test)]
918#[path = "tests/macros_tests.rs"]
919mod tests;