compose-rust-macros 0.0.10

The #[Composable] attribute for compose-rust's slot table runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! `#[Composable]`: what the Compose compiler plugin does to a function, done from outside
//! the compiler.
//!
//! The plugin does three things to a `@Composable` function, and this does the same three
//! to a Rust one:
//!
//! 1. **It gives the call a group**, keyed by where the function is declared. A slot table
//!    stores what a call site remembered at a position, and the group is what turns a
//!    position into an identity: two calls of the same function in one parent are told
//!    apart by order, and everything the function remembers belongs to its group alone.
//! 2. **It gives every branch a group of its own**: each arm of an `if`, an `else` and a
//!    `match`. Without one, the state a branch remembered is handed to whichever call
//!    occupies its position after the branch stops being taken. Both values are often the
//!    same type, so nothing complains, and the screen silently shows one widget's state in
//!    another.
//!
//!    Loop bodies get no group, as in Compose. Each pass of a loop calls the same call
//!    sites again, and the runtime tells the passes apart by order, which is what a list
//!    that only grows and shrinks at the end needs. A list whose items move needs to say
//!    which item is which, and that is `key(id, || ..)`: a group per iteration here would
//!    sit between the loop and the key and pin every item to its position.
//! 3. **It makes the function skippable and restartable.** The parameters are compared
//!    with the ones the group was last run with, and when they are all equal and nothing
//!    the function read has changed, its body is not run at all. When a state it read
//!    changes, the runtime runs this function again on its own, with the parameters it
//!    last had, without running whatever called it.
//!
//! A group closes when a guard bound at the top of its block is dropped, not when a
//! closure wrapping the block returns. A local with a destructor is dropped after the
//! block's tail expression has been evaluated, so the group closes in the right place on
//! an ordinary exit, and closes anyway on `continue`, `break`, `return`, `?` and an
//! unwind. Wrapping the body in a closure would make the first two compile errors and give
//! `return` a different meaning.
//!
//! What can be compared and stored is decided from the parameter's type as written. A
//! parameter whose type borrows (other than `&'static`), names a generic parameter, or is
//! `impl Trait` cannot be kept past the call, so a function with one is never skipped and
//! is re-run by its caller rather than on its own. A parameter that can be kept but is not
//! `Clone + PartialEq` is found out at compile time by method resolution and treated the
//! same way. Nothing here needs the function's author to say which is which.

mod call_macro;

use call_macro::{CallParam, implicit_default, normalise_default};
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{format_ident, quote};
use syn::visit::{self, Visit};
use syn::visit_mut::{self, VisitMut};
use syn::{
    Block, Expr, FnArg, GenericParam, Ident, ItemFn, Pat, ReturnType, Type, parse_macro_input,
    parse_quote,
};

/// Turns a function into a composable.
///
/// ```ignore
/// #[Composable]
/// fn Greeting(name: String) {
///     let clicks = remember(|| mutable_state_of(0));
///     Text(format!("Hello, {name}: {}", clicks.get()));
///     Button("Again").on_click(move || clicks.update(|count| *count += 1));
/// }
/// ```
///
/// `#[Composable(nonrestartable)]` keeps the groups and the skipping but never re-runs the
/// function on its own: a state it reads re-runs its caller instead. That is what an
/// associated function needs, because the runtime re-runs a function by calling it by its
/// bare name.
#[proc_macro_attribute]
#[allow(non_snake_case)]
pub fn Composable(attribute: TokenStream, item: TokenStream) -> TokenStream {
    let options = match parse_options(attribute.into()) {
        Ok(options) => options,
        Err(error) => return error.to_compile_error().into(),
    };
    let mut function = parse_macro_input!(item as ItemFn);
    let defaults = match take_defaults(&mut function) {
        Ok(defaults) => defaults,
        Err(error) => return error.to_compile_error().into(),
    };
    // A function that re-runs itself by bare name is an associated function, and a method
    // has no name of its own to share with a macro, so only the restartable form gets one.
    let call_params = options
        .restartable
        .then(|| call_params(&function, defaults))
        .flatten();
    match expand(&mut function, &options) {
        Ok(()) => {
            let call_macro = call_params.map(|params| call_macro::generate(&function, &params));
            quote!(#function #call_macro).into()
        }
        Err(error) => error.to_compile_error().into(),
    }
}

/// The expansion of every generated call macro. Hidden: it is the generated
/// `macro_rules!`'s way of reading its arguments with the caller's spans, not an API.
#[doc(hidden)]
#[proc_macro]
pub fn __compose_call_check(input: TokenStream) -> TokenStream {
    match call_macro::check(input.into()) {
        Ok(tokens) => tokens.into(),
        Err(error) => error.to_compile_error().into(),
    }
}

/// Removes the `#[default(expr)]` attributes from the parameters and returns the
/// expressions, one entry per parameter.
fn take_defaults(function: &mut ItemFn) -> syn::Result<Vec<Option<Expr>>> {
    let mut defaults = Vec::new();
    for input in &mut function.sig.inputs {
        let attrs = match input {
            FnArg::Receiver(receiver) => &mut receiver.attrs,
            FnArg::Typed(typed) => &mut typed.attrs,
        };
        let mut default = None;
        let mut kept = Vec::new();
        for attribute in attrs.drain(..) {
            if !attribute.path().is_ident("default") {
                kept.push(attribute);
                continue;
            }
            if default.is_some() {
                return Err(syn::Error::new_spanned(
                    attribute,
                    "a parameter takes one #[default(..)]",
                ));
            }
            default = Some(attribute.parse_args::<Expr>().map_err(|error| {
                syn::Error::new(
                    error.span(),
                    "#[default(..)] takes the default value as an expression, \
                     like #[default(false)]",
                )
            })?);
        }
        *attrs = kept;
        if default.is_some() && matches!(input, FnArg::Receiver(_)) {
            return Err(syn::Error::new_spanned(input, "self has no default"));
        }
        defaults.push(default);
    }
    Ok(defaults)
}

/// The parameters as the call macro needs them, or `None` for a function the macro cannot
/// name: one with a receiver, a pattern instead of a name, or `Self` in a type.
fn call_params(function: &ItemFn, defaults: Vec<Option<Expr>>) -> Option<Vec<CallParam>> {
    let mut params = Vec::new();
    for (input, default) in function.sig.inputs.iter().zip(defaults) {
        let FnArg::Typed(typed) = input else {
            return None;
        };
        let Pat::Ident(pattern) = &*typed.pat else {
            return None;
        };
        if pattern.by_ref.is_some() || pattern.subpat.is_some() || mentions_self(&typed.ty) {
            return None;
        }
        let ident = pattern.ident.clone();
        let ty = (*typed.ty).clone();
        let default = match default {
            Some(expr) => Some(normalise_default(quote!(#expr))),
            None => implicit_default(&ident, &ty),
        };
        params.push(CallParam { ident, ty, default });
    }
    Some(params)
}

fn mentions_self(ty: &Type) -> bool {
    struct Find(bool);
    impl<'ast> Visit<'ast> for Find {
        fn visit_path(&mut self, path: &'ast syn::Path) {
            if path
                .segments
                .first()
                .is_some_and(|first| first.ident == "Self")
            {
                self.0 = true;
            }
            visit::visit_path(self, path);
        }
    }
    let mut find = Find(false);
    find.visit_type(ty);
    find.0
}

struct Options {
    restartable: bool,
}

fn parse_options(attribute: proc_macro2::TokenStream) -> syn::Result<Options> {
    let mut options = Options { restartable: true };
    if attribute.is_empty() {
        return Ok(options);
    }
    let ident: Ident = syn::parse2(attribute)?;
    if ident == "nonrestartable" {
        options.restartable = false;
        Ok(options)
    } else {
        Err(syn::Error::new(
            ident.span(),
            "#[Composable] takes no argument except `nonrestartable`",
        ))
    }
}

/// One parameter the runtime may compare and keep.
struct Param {
    ident: Ident,
    storable: bool,
}

fn expand(function: &mut ItemFn, options: &Options) -> syn::Result<()> {
    if let Some(asyncness) = function.sig.asyncness {
        return Err(syn::Error::new(
            asyncness.span,
            "a composable cannot be async: it runs to completion inside one composition. \
             Start asynchronous work with LaunchedEffect or remember_coroutine_scope",
        ));
    }
    let name = function.sig.ident.clone();
    let path = name.to_string();

    // Branch groups first, so the function's own group wraps them.
    let mut inserter = Inserter {
        path: path.clone(),
        ordinal: 0,
    };
    inserter.visit_block_mut(&mut function.block);

    let generic_types: Vec<Ident> = function
        .sig
        .generics
        .params
        .iter()
        .filter_map(|param| match param {
            GenericParam::Type(param) => Some(param.ident.clone()),
            _ => None,
        })
        .collect();
    let has_generics = !function.sig.generics.params.is_empty();

    let mut params = Vec::new();
    let mut params_ok = true;
    for input in &function.sig.inputs {
        match input {
            FnArg::Receiver(_) => params_ok = false,
            FnArg::Typed(typed) => match &*typed.pat {
                Pat::Ident(pattern) if pattern.by_ref.is_none() && pattern.subpat.is_none() => {
                    params.push(Param {
                        ident: pattern.ident.clone(),
                        storable: storable(&typed.ty, &generic_types),
                    });
                }
                _ => params_ok = false,
            },
        }
    }

    let unit_return = match &function.sig.output {
        ReturnType::Default => true,
        ReturnType::Type(_, ty) => matches!(&**ty, Type::Tuple(tuple) if tuple.elems.is_empty()),
    };
    // A parameter that cannot be kept cannot be compared next time, so a function with
    // one runs whenever its caller does, as an unstable parameter makes a Compose function
    // run.
    let skippable = unit_return && params_ok && params.iter().all(|param| param.storable);
    let restartable = skippable && options.restartable && !has_generics;

    let private = quote!(::compose_rust::runtime::__private);
    let key = key_expression(&path, u32::MAX);
    let body = &function.block;

    let skip = if skippable {
        let comparisons = params.iter().enumerate().map(|(index, param)| {
            let ident = &param.ident;
            quote! {
                __compose_changed |= (&#private::Param(&#ident))
                    .__compose_changed(&__compose_scope, #index);
            }
        });
        let restart = if restartable && params.is_empty() {
            quote! {
                if __compose_scope.wants_restart() {
                    __compose_scope.set_restart(move || {
                        #name();
                    });
                }
            }
        } else if restartable {
            let captured: Vec<Ident> = (0..params.len())
                .map(|index| format_ident!("__compose_param_{}", index))
                .collect();
            let idents = params.iter().map(|param| &param.ident);
            let clones = captured.iter().map(|captured| {
                quote! {
                    (&#private::Param(&#captured))
                        .__compose_clone()
                        .expect("a parameter that was cloned once clones again")
                }
            });
            quote! {
                if __compose_scope.wants_restart() {
                    if let (#(::core::option::Option::Some(#captured),)*) =
                        (#((&#private::Param(&#idents)).__compose_clone(),)*)
                    {
                        __compose_scope.set_restart(move || {
                            #name(#(#clones),*);
                        });
                    }
                }
            }
        } else {
            quote! {}
        };
        quote! {
            {
                #[allow(unused_mut)]
                let mut __compose_changed = __compose_scope.must_run();
                #(#comparisons)*
                if !__compose_changed {
                    __compose_scope.skip();
                    return;
                }
                #restart
            }
        }
    } else {
        quote! {}
    };

    function.block = parse_quote!({
        #[allow(unused_imports)]
        use #private::{StableParam as _, UnstableParam as _};
        let __compose_scope = #private::start_restart_group(#key);
        #skip
        #body
    });
    function.attrs.push(parse_quote!(#[allow(non_snake_case)]));
    Ok(())
}

/// Whether a parameter of this type, as written, can be kept after the call returns.
///
/// Only the syntax is available here, so the answer is conservative: anything that could
/// borrow, anything generic and anything opaque is treated as not storable, and the
/// function is then run every time its caller runs rather than wrongly skipped.
fn storable(ty: &Type, generics: &[Ident]) -> bool {
    struct Check<'a> {
        generics: &'a [Ident],
        ok: bool,
    }
    impl<'ast> Visit<'ast> for Check<'_> {
        fn visit_type_reference(&mut self, reference: &'ast syn::TypeReference) {
            match &reference.lifetime {
                Some(lifetime) if lifetime.ident == "static" => {}
                _ => self.ok = false,
            }
            visit::visit_type_reference(self, reference);
        }
        fn visit_lifetime(&mut self, lifetime: &'ast syn::Lifetime) {
            if lifetime.ident != "static" {
                self.ok = false;
            }
        }
        fn visit_type_impl_trait(&mut self, _: &'ast syn::TypeImplTrait) {
            self.ok = false;
        }
        fn visit_type_infer(&mut self, _: &'ast syn::TypeInfer) {
            self.ok = false;
        }
        fn visit_type_path(&mut self, path: &'ast syn::TypePath) {
            if path.qself.is_some() {
                self.ok = false;
            }
            if let Some(first) = path.path.segments.first() {
                if first.ident == "Self" || self.generics.contains(&first.ident) {
                    self.ok = false;
                }
            }
            visit::visit_type_path(self, path);
        }
        fn visit_type_ptr(&mut self, _: &'ast syn::TypePtr) {
            self.ok = false;
        }
    }
    let mut check = Check { generics, ok: true };
    check.visit_type(ty);
    check.ok
}

struct Inserter {
    path: String,
    ordinal: u32,
}

impl Inserter {
    fn next(&mut self) -> (proc_macro2::TokenStream, Ident) {
        let key = key_expression(&self.path, self.ordinal);
        self.ordinal += 1;
        (key, guard_name(self.ordinal))
    }

    /// Wraps a block so that what it remembers belongs to this branch and no other.
    fn wrap(&mut self, block: &mut Block) {
        let (key, guard) = self.next();
        // The branch's own statements, spliced in after the guard rather than nested as a
        // block of their own: a nested block around a tail value is braces the compiler
        // warns about, and the warning would point at the user's code.
        let statements = &block.stmts;
        *block = parse_quote!({
            let #guard = ::compose_rust::runtime::__private::group(#key);
            #(#statements)*
        });
    }
}

impl VisitMut for Inserter {
    fn visit_expr_mut(&mut self, expr: &mut Expr) {
        // Descend first, so an inner branch is numbered and wrapped before the outer one
        // closes over it.
        visit_mut::visit_expr_mut(self, expr);

        match expr {
            Expr::If(conditional) => {
                self.wrap(&mut conditional.then_branch);
                if let Some((_, otherwise)) = conditional.else_branch.as_mut() {
                    // An `else if` is another `Expr::If`, already wrapped by the descent
                    // above. Only a plain `else` block needs one here.
                    if let Expr::Block(block) = otherwise.as_mut() {
                        self.wrap(&mut block.block);
                    }
                }
            }
            Expr::Match(matched) => {
                for arm in &mut matched.arms {
                    let (key, guard) = self.next();
                    let body = arm.body.clone();
                    arm.body = match *body {
                        // A block arm's statements go after the guard, for the reason
                        // `wrap` gives.
                        Expr::Block(syn::ExprBlock {
                            ref attrs,
                            label: None,
                            ref block,
                        }) if attrs.is_empty() => {
                            let statements = &block.stmts;
                            parse_quote!({
                                let #guard = ::compose_rust::runtime::__private::group(#key);
                                #(#statements)*
                            })
                        }
                        body => parse_quote!({
                            let #guard = ::compose_rust::runtime::__private::group(#key);
                            #body
                        }),
                    };
                }
            }
            _ => {}
        }
    }

    /// Bodies of nested items are somebody else's composition, or not a composition at all.
    fn visit_item_mut(&mut self, _item: &mut syn::Item) {}
}

/// A distinct name per group, so nesting does not shadow an outer guard and drop it early.
fn guard_name(ordinal: u32) -> Ident {
    Ident::new(&format!("__compose_group_{ordinal}"), Span::call_site())
}

/// A call site's key, computed at compile time from the function's path and the macro's
/// own counter within its body.
fn key_expression(path: &str, ordinal: u32) -> proc_macro2::TokenStream {
    quote!({
        const __COMPOSE_KEY: u64 = ::compose_rust::runtime::__private::call_site(
            concat!(module_path!(), "::", #path),
            #ordinal,
        );
        __COMPOSE_KEY
    })
}