ferroui-view-macros 0.4.0-preview.1

The rsx! and #[component] macros of ferroui-view, the declarative Rust API of FerroUI
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
489
490
491
492
493
494
495
496
//! ferroui-view-macros
//!
//! The macros of `ferroui-view`: [`rsx!`] writes an element tree in a form
//! close to XAML and expands to the builders, and [`#[component]`](component)
//! turns a function into a component with a builder of its parameters.
//! Errors point at the user's code: an attribute that a class has no setter
//! for is a missing method of its builder.

use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{format_ident, quote, quote_spanned, ToTokens};
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::{braced, token, Expr, FnArg, Ident, ItemFn, LitStr, Pat, Path, Token, Type};

/// An element tree, expanded to the builders of `ferroui-view`.
///
/// ```ignore
/// rsx! {
///     StackPanel { spacing: 8.0,
///         TextBlock { text: move || format!("Count: {}", count.get()) }
///         Button { on_click: move |_| count.update(|c| *c += 1), "Increment" }
///     }
/// }
/// ```
///
/// - `Name { ... }` is an element of the control class or component `Name`
///   in scope (`<Name as Builder>::builder()`): `StackPanel` is
///   `stack_panel()`, `todo::Row` the component `Row` of the module `todo`.
/// - `name` alone gives the setter `name` the variable `name`, as a field of
///   a struct is given (`TextBlock { text }`).
/// - `name: value` calls the setter `.name(value)`: a property
///   (`spacing: 8.0`), a handler (`on_click: ...`), `key`, `name`, `class`.
/// - `Owner.name: value` sets an attached property: `Grid.row: 1` calls
///   `.grid_row(1)`.
/// - `name(a, b)` calls a method of the builder with several arguments:
///   `on_changed(TextBox::text_property(), handler)`,
///   `set(Grid::row_property(), 1)` (the indexer `control[Property] = 1`
///   upstream), `bind(TextBlock::text_property(), binding)`.
/// - `"text"` is a text child, `{expr}` any child (an element, a builder, a
///   list, `for_each(..)`, `show(..)`), and a nested element a child.
/// - `if cond { .. } else { .. }` and `for x in items { .. }` choose and
///   repeat children when the tree is built (for children that follow state,
///   use `{for_each(..)}`, `{show(..)}` or `{dynamic(..)}`).
///
/// Several nodes at the root make a fragment.
#[proc_macro]
pub fn rsx(input: TokenStream) -> TokenStream {
    let nodes = syn::parse_macro_input!(input as Nodes);
    let elements: Vec<TokenStream2> = nodes.0.iter().map(Node::to_element).collect();
    let tokens = if elements.len() == 1 {
        elements.into_iter().next().unwrap_or_default()
    } else {
        quote! { ::ferroui_view::Element::Fragment(::std::vec![#(#elements),*]) }
    };
    tokens.into()
}

struct Nodes(Vec<Node>);

impl Parse for Nodes {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut nodes = Vec::new();
        while !input.is_empty() {
            nodes.push(input.parse()?);
            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }
        Ok(Nodes(nodes))
    }
}

enum Node {
    Element(ElementNode),
    Text(LitStr),
    Expr(Expr, Span),
    If(Box<Expr>, Vec<Node>, Option<Vec<Node>>, Span),
    For(Box<Pat>, Box<Expr>, Vec<Node>, Span),
}

struct ElementNode {
    path: Path,
    attributes: Vec<Attribute>,
    children: Vec<Node>,
}

enum Attribute {
    /// `name: value` or `Owner.name: value`.
    Value {
        /// `Owner` of `Owner.name`.
        owner: Option<Ident>,
        name: Ident,
        value: Expr,
    },
    /// `name(arguments)`: a method of the builder with several arguments.
    Call { name: Ident, arguments: syn::punctuated::Punctuated<Expr, Token![,]> },
}

fn parse_children(input: ParseStream) -> syn::Result<Vec<Node>> {
    let content;
    braced!(content in input);
    Ok(content.parse::<Nodes>()?.0)
}

impl Parse for Node {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        if input.peek(LitStr) {
            return Ok(Node::Text(input.parse()?));
        }
        if input.peek(token::Brace) {
            let span = input.span();
            let content;
            braced!(content in input);
            return Ok(Node::Expr(content.parse()?, span));
        }
        if input.peek(Token![if]) {
            let span = input.span();
            input.parse::<Token![if]>()?;
            let condition = Expr::parse_without_eager_brace(input)?;
            let then = parse_children(input)?;
            let otherwise = if input.peek(Token![else]) {
                input.parse::<Token![else]>()?;
                if input.peek(Token![if]) {
                    Some(vec![input.parse::<Node>()?])
                } else {
                    Some(parse_children(input)?)
                }
            } else {
                None
            };
            return Ok(Node::If(Box::new(condition), then, otherwise, span));
        }
        if input.peek(Token![for]) {
            let span = input.span();
            input.parse::<Token![for]>()?;
            let pattern = Pat::parse_single(input)?;
            input.parse::<Token![in]>()?;
            let items = Expr::parse_without_eager_brace(input)?;
            let body = parse_children(input)?;
            return Ok(Node::For(Box::new(pattern), Box::new(items), body, span));
        }
        let path: Path = input.call(Path::parse_mod_style)?;
        let content;
        braced!(content in input);
        let mut attributes = Vec::new();
        let mut children = Vec::new();
        while !content.is_empty() {
            if content.peek(Ident::peek_any) && content.peek2(token::Paren) {
                let name = content.call(Ident::parse_any)?;
                let arguments;
                syn::parenthesized!(arguments in content);
                let arguments = arguments.parse_terminated(Expr::parse, Token![,])?;
                attributes.push(Attribute::Call { name, arguments });
            } else if content.peek(Ident::peek_any) && (content.peek2(Token![,]) || is_last_token(&content)) {
                // `name` alone: the setter of the name with the variable of
                // the name, as a field of a struct is given.
                let name = content.call(Ident::parse_any)?;
                let value: Expr = syn::parse_quote!(#name);
                attributes.push(Attribute::Value { owner: None, name, value });
            } else if is_attribute(&content) {
                let owner = if content.peek2(Token![.]) {
                    let owner = content.call(Ident::parse_any)?;
                    content.parse::<Token![.]>()?;
                    Some(owner)
                } else {
                    None
                };
                let name = content.call(Ident::parse_any)?;
                content.parse::<Token![:]>()?;
                let value: Expr = content.parse()?;
                attributes.push(Attribute::Value { owner, name, value });
            } else {
                children.push(content.parse()?);
            }
            if content.peek(Token![,]) {
                content.parse::<Token![,]>()?;
            }
        }
        Ok(Node::Element(ElementNode { path, attributes, children }))
    }
}

/// Whether the next token is the last one of the stream.
fn is_last_token(input: ParseStream) -> bool {
    let fork = input.fork();
    fork.parse::<proc_macro2::TokenTree>().is_ok() && fork.is_empty()
}

/// `name: ...` or `Owner.name: ...`, as opposed to a child element
/// (`Name { ... }`, `module::Name { ... }`).
fn is_attribute(input: ParseStream) -> bool {
    let fork = input.fork();
    if fork.call(Ident::parse_any).is_err() {
        return false;
    }
    if fork.peek(Token![.]) {
        let _ = fork.parse::<Token![.]>();
        if fork.call(Ident::parse_any).is_err() {
            return false;
        }
    }
    fork.peek(Token![:]) && !fork.peek(Token![::])
}

/// `StackPanel` as `stack_panel`.
fn snake_case(name: &str) -> String {
    let mut out = String::new();
    let chars: Vec<char> = name.chars().collect();
    for (index, &char) in chars.iter().enumerate() {
        if char.is_uppercase() {
            let previous_lower = index > 0 && (chars[index - 1].is_lowercase() || chars[index - 1].is_ascii_digit());
            let next_lower = chars.get(index + 1).is_some_and(|next| next.is_lowercase());
            let previous_upper = index > 0 && chars[index - 1].is_uppercase();
            if index > 0 && (previous_lower || (previous_upper && next_lower)) {
                out.push('_');
            }
            out.extend(char.to_lowercase());
        } else {
            out.push(char);
        }
    }
    out
}

impl Node {
    /// The node as a child expression (what `.child(..)` takes).
    fn to_child(&self) -> TokenStream2 {
        match self {
            Node::Element(element) => element.to_builder(),
            Node::Text(text) => text.to_token_stream(),
            Node::Expr(expr, span) => quote_spanned! {*span=> #expr },
            Node::If(..) | Node::For(..) => self.to_element(),
        }
    }

    /// The node as an `Element`.
    fn to_element(&self) -> TokenStream2 {
        match self {
            Node::Element(element) => {
                let builder = element.to_builder();
                quote! { ::ferroui_view::IntoElement::into_element(#builder) }
            }
            Node::Text(text) => quote! { ::ferroui_view::IntoChild::into_child(#text) },
            Node::Expr(expr, span) => quote_spanned! {*span=> ::ferroui_view::IntoChild::into_child(#expr) },
            Node::If(condition, then, otherwise, span) => {
                let then = fragment(then);
                let otherwise = otherwise.as_ref().map_or_else(|| quote! { ::ferroui_view::Element::Empty }, |nodes| fragment(nodes));
                quote_spanned! {*span=> if #condition { #then } else { #otherwise } }
            }
            Node::For(pattern, items, body, span) => {
                let body = fragment(body);
                quote_spanned! {*span=>
                    ::ferroui_view::Element::Fragment(
                        ::std::iter::IntoIterator::into_iter(#items).map(|#pattern| #body).collect::<::std::vec::Vec<_>>()
                    )
                }
            }
        }
    }
}

fn fragment(nodes: &[Node]) -> TokenStream2 {
    let elements: Vec<TokenStream2> = nodes.iter().map(Node::to_element).collect();
    match elements.len() {
        0 => quote! { ::ferroui_view::Element::Empty },
        1 => elements.into_iter().next().unwrap_or_default(),
        _ => quote! { ::ferroui_view::Element::Fragment(::std::vec![#(#elements),*]) },
    }
}

impl ElementNode {
    fn to_builder(&self) -> TokenStream2 {
        let path = &self.path;
        let span = self.path.span();
        let mut tokens = quote_spanned! {span=> <#path as ::ferroui_view::Builder>::builder() };
        for attribute in &self.attributes {
            match attribute {
                Attribute::Value { owner, name, value } => {
                    let method = match owner {
                        Some(owner) => {
                            format_ident!("{}_{}", snake_case(&owner.unraw().to_string()), name.unraw(), span = name.span())
                        }
                        None => name.clone(),
                    };
                    tokens = quote_spanned! {method.span()=> #tokens.#method(#value) };
                }
                Attribute::Call { name, arguments } => {
                    tokens = quote_spanned! {name.span()=> #tokens.#name(#arguments) };
                }
            }
        }
        for child in &self.children {
            let child = child.to_child();
            tokens = quote! { #tokens.child(#child) };
        }
        tokens
    }
}

/// A component: a function whose parameters are its properties, with a
/// builder so that `rsx!` and the builders use it like a control.
///
/// ```ignore
/// #[component]
/// fn Counter(initial: i32, #[prop(default = 1)] step: i32) -> Element {
///     let count = signal(initial);
///     rsx! { Button { on_click: move |_| count.update(|c| *c += step), {move || count.get()} } }
/// }
///
/// rsx! { Counter { initial: 5 } }        // or counter().initial(5)
/// ```
///
/// The name is in upper camel case. Besides the function, the macro declares
/// a type of the name (what `rsx!` names: `Counter { .. }`) and a builder
/// function of the name in snake case (`counter()`), with a setter per parameter that takes what
/// converts into its type (`IntoValue`: the conversions of the setters of
/// controls). A parameter is required unless it has
/// `#[prop(default)]` (the default of its type), `#[prop(default = expr)]`,
/// or an `Option` type. A parameter named `children` of type `Element` takes
/// the children of the element (`.child(..)`). The function runs once, when
/// the element is built.
#[proc_macro_attribute]
pub fn component(attribute: TokenStream, item: TokenStream) -> TokenStream {
    if !attribute.is_empty() {
        return syn::Error::new(Span::call_site(), "#[component] takes no arguments").to_compile_error().into();
    }
    let function = syn::parse_macro_input!(item as ItemFn);
    match expand_component(function) {
        Ok(tokens) => tokens.into(),
        Err(error) => error.to_compile_error().into(),
    }
}

struct Param {
    name: Ident,
    ty: Type,
    default: Option<TokenStream2>,
    attrs: Vec<syn::Attribute>,
}

fn is_option(ty: &Type) -> bool {
    matches!(ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "Option"))
}

fn expand_component(mut function: ItemFn) -> syn::Result<TokenStream2> {
    let name = function.sig.ident.clone();
    let name_text = name.to_string();
    if !name_text.chars().next().is_some_and(char::is_uppercase) {
        return Err(syn::Error::new(name.span(), "a component is named in upper camel case (`TodoList`)"));
    }
    let builder_function = Ident::new(&snake_case(&name_text), name.span());
    let builder_type = format_ident!("{}Builder", name);
    let visibility = function.vis.clone();

    let mut params = Vec::new();
    for input in function.sig.inputs.iter_mut() {
        let FnArg::Typed(typed) = input else {
            return Err(syn::Error::new(input.span(), "a component is a free function"));
        };
        let Pat::Ident(pattern) = &*typed.pat else {
            return Err(syn::Error::new(typed.pat.span(), "a parameter of a component is a name"));
        };
        let mut default = None;
        let mut kept = Vec::new();
        for attr in typed.attrs.drain(..) {
            if attr.path().is_ident("prop") {
                attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("default") {
                        if meta.input.peek(Token![=]) {
                            let value: Expr = meta.value()?.parse()?;
                            default = Some(value.to_token_stream());
                        } else {
                            default = Some(quote! { ::std::default::Default::default() });
                        }
                        Ok(())
                    } else {
                        Err(meta.error("expected `default` or `default = ...`"))
                    }
                })?;
            } else {
                kept.push(attr);
            }
        }
        typed.attrs = kept.clone();
        let ty = (*typed.ty).clone();
        if default.is_none() && is_option(&ty) {
            default = Some(quote! { ::std::option::Option::None });
        }
        params.push(Param { name: pattern.ident.clone(), ty, default, attrs: kept });
    }

    let fields = params.iter().map(|param| {
        let (name, ty) = (&param.name, &param.ty);
        quote! { #name: ::std::option::Option<#ty> }
    });
    let setters = params.iter().map(|param| {
        let (name, ty) = (&param.name, &param.ty);
        let docs = param.attrs.iter().filter(|attr| attr.path().is_ident("doc"));
        if name == "children" {
            quote! {
                #(#docs)*
                pub fn children(mut self, children: impl ::ferroui_view::IntoChildren) -> Self {
                    let mut items = match self.children.take() {
                        ::std::option::Option::Some(::ferroui_view::Element::Fragment(items)) => items,
                        _ => ::std::vec::Vec::new(),
                    };
                    items.extend(::ferroui_view::IntoChildren::into_children(children));
                    self.children = ::std::option::Option::Some(::ferroui_view::Element::Fragment(items));
                    self
                }

                /// Adds a child.
                pub fn child(mut self, child: impl ::ferroui_view::IntoChild) -> Self {
                    let mut items = match self.children.take() {
                        ::std::option::Option::Some(::ferroui_view::Element::Fragment(items)) => items,
                        _ => ::std::vec::Vec::new(),
                    };
                    items.push(::ferroui_view::IntoChild::into_child(child));
                    self.children = ::std::option::Option::Some(::ferroui_view::Element::Fragment(items));
                    self
                }
            }
        } else {
            quote! {
                #(#docs)*
                pub fn #name(mut self, value: impl ::ferroui_view::IntoValue<#ty>) -> Self {
                    self.#name = ::std::option::Option::Some(::ferroui_view::IntoValue::into_value(value));
                    self
                }
            }
        }
    });
    let arguments = params.iter().map(|param| {
        let name = &param.name;
        let message = format!("`{}` is a required property of `{}`", name, name_text);
        match &param.default {
            Some(default) => quote! { self.#name.unwrap_or_else(|| #default) },
            None if name == "children" => quote! { self.#name.unwrap_or_default() },
            None => quote! { self.#name.unwrap_or_else(|| panic!(#message)) },
        }
    });
    let field_names: Vec<&Ident> = params.iter().map(|param| &param.name).collect();
    let doc = format!("The builder of the component [`{name_text}`].");
    let start_doc = format!("Starts an element of the component [`{name_text}`].");
    let type_doc = format!("The component [`{name_text}`] as the name of an element of `rsx!`.");

    function.attrs.push(syn::parse_quote!(#[allow(non_snake_case)]));
    Ok(quote! {
        #function

        #[doc = #doc]
        #[allow(non_camel_case_types)]
        #visibility struct #builder_type {
            #(#fields,)*
            key: ::std::option::Option<::ferroui_view::Key>,
        }

        #[doc = #type_doc]
        #[allow(non_camel_case_types)]
        #visibility struct #name {}

        impl ::ferroui_view::Builder for #name {
            type Output = #builder_type;
            fn builder() -> #builder_type {
                #builder_function()
            }
        }

        #[doc = #start_doc]
        #visibility fn #builder_function() -> #builder_type {
            #builder_type { #(#field_names: ::std::option::Option::None,)* key: ::std::option::Option::None }
        }

        impl #builder_type {
            #(#setters)*

            /// The key of the element among its siblings.
            pub fn key(mut self, key: impl ::std::convert::Into<::ferroui_view::Key>) -> Self {
                self.key = ::std::option::Option::Some(key.into());
                self
            }
        }

        impl ::ferroui_view::IntoElement for #builder_type {
            fn into_element(self) -> ::ferroui_view::Element {
                let element = #name(#(#arguments),*);
                match self.key {
                    ::std::option::Option::Some(key) => ::ferroui_view::element::with_key(element, key),
                    ::std::option::Option::None => element,
                }
            }
        }
    })
}