Skip to main content

skia_engine_macro/
lib.rs

1//! Procedural macros for constructing `skia-engine` element trees.
2//!
3//! [`skia_ui!`] provides a brace-based syntax, while [`skia_rsx!`] accepts
4//! RSX-like tags. Both macros produce `skia_engine_core::ElementNode` values
5//! and expect the generated code's `skia_engine_core` and `skia_safe` paths to
6//! be available to the consuming crate.
7//!
8//! Supported elements are `Container`, `Rect`, `Image`, and `Text`.
9//! Containers may contain nested elements; the other elements are leaves.
10//! Element properties use Rust expressions. `Text` content can be supplied
11//! through its `content` property, or as a quoted string literal in the RSX
12//! body.
13//!
14//! # Brace syntax
15//!
16//! ```ignore
17//! skia_ui! {
18//!     Container {
19//!         width: 320.0,
20//!         height: 180.0,
21//!         background_color: skia_safe::Color::WHITE,
22//!         Rect {
23//!             width: 80.0,
24//!             height: 60.0,
25//!             color: skia_safe::Color::BLUE,
26//!         }
27//!     }
28//! }
29//! ```
30//!
31//! # RSX syntax
32//!
33//! ```ignore
34//! skia_rsx! {
35//!     <Container width={320.0} height={180.0}>
36//!         <Text font_size={24.0}>{"Hello, Skia!"}</Text>
37//!     </Container>
38//! }
39//! ```
40use proc_macro::TokenStream;
41use quote::quote;
42use syn::parse_macro_input;
43use syn_rsx::parse2;
44
45mod parser;
46
47/// A normalized element property used by both macro syntaxes.
48struct AttributeTokens {
49    /// Property identifier as written in the invocation.
50    name: String,
51    /// Rust expression to use as the property's value.
52    value: proc_macro2::TokenStream,
53}
54
55/// Builds an `ElementNode` tree using nested Rust-like brace syntax.
56///
57/// Each element is written as `Tag { ... }`. Properties use `name: expression`
58/// syntax and nested elements are written directly inside their parent's
59/// braces. Separate entries with commas. `Container` accepts children;
60/// `Rect`, `Image`, and `Text` do not. Text content is provided with the
61/// `content` property.
62///
63/// Supported tags are `Container`, `Rect`, `Image`, and `Text`. Supported
64/// properties are validated at compile time; an unknown tag or property, or an
65/// invalid element structure, produces a compile error.
66///
67/// The expansion refers to `skia_engine_core::ElementNode` and, for the
68/// default rectangle color, `skia_safe::Color::BLACK`. Those crate paths must
69/// be available in the consuming crate.
70///
71/// # Example
72///
73/// ```ignore
74/// let tree = skia_ui! {
75///     Container {
76///         width: 200.0,
77///         height: 100.0,
78///         Rect {
79///             width: 50.0,
80///             height: 50.0,
81///             color: skia_safe::Color::GREEN,
82///         }
83///     }
84/// };
85/// ```
86#[proc_macro]
87pub fn skia_ui(input: TokenStream) -> TokenStream {
88    let root = parse_macro_input!(input as parser::SkiaNodeInput);
89    expand_skia_ui_node(&root).into()
90}
91
92/// Recursively converts a parsed brace-syntax node into an element expression.
93fn expand_skia_ui_node(node: &parser::SkiaNodeInput) -> proc_macro2::TokenStream {
94    let attributes = node.attributes.iter().map(|attribute| {
95        let value = &attribute.value;
96        AttributeTokens {
97            name: attribute.key.to_string(),
98            value: quote! { #value },
99        }
100    });
101    let children = node.children.iter().map(expand_skia_ui_node).collect();
102
103    expand_element(&node.tag_name.to_string(), attributes, children, None)
104}
105
106/// Builds an `ElementNode` tree using RSX-like tag syntax.
107///
108/// Attribute values may be Rust expressions in braces, such as
109/// `width={200.0}`, or Rust paths/identifiers where accepted by the RSX parser.
110/// Container tags may nest other elements. `Rect`, `Image`, and `Text` are
111/// leaves. Text content must be a string literal body (for example,
112/// `<Text>{"Hello"}</Text>`) or supplied with the `content` property, but not
113/// both.
114///
115/// Exactly one root element is required. Unknown tags and properties,
116/// valueless attributes, invalid children, and invalid text bodies produce
117/// compile-time errors.
118///
119/// The expansion refers to `skia_engine_core::ElementNode` and, for the
120/// default rectangle color, `skia_safe::Color::BLACK`. Those crate paths must
121/// be available in the consuming crate.
122///
123/// # Example
124///
125/// ```ignore
126/// let tree = skia_rsx! {
127///     <Container width={200.0} height={100.0}>
128///         <Text font_size={20.0}>{"Hello"}</Text>
129///     </Container>
130/// };
131/// ```
132#[proc_macro]
133pub fn skia_rsx(input: TokenStream) -> TokenStream {
134    let nodes = match parse2(input.into()) {
135        Ok(nodes) => nodes,
136        Err(err) => return err.to_compile_error().into(),
137    };
138
139    match nodes.as_slice() {
140        [root] => expand_skia_rsx_node(root).into(),
141        [] => syn::Error::new(proc_macro2::Span::call_site(), "Expected a root element")
142            .to_compile_error()
143            .into(),
144        _ => syn::Error::new(
145            proc_macro2::Span::call_site(),
146            "Expected a single root element",
147        )
148        .to_compile_error()
149        .into(),
150    }
151}
152
153/// Expands a parsed RSX node, collecting its properties, element children, and
154/// (for `Text`) literal body content.
155fn expand_skia_rsx_node(node: &syn_rsx::Node) -> proc_macro2::TokenStream {
156    let syn_rsx::Node::Element(element) = node else {
157        return quote! {};
158    };
159
160    let mut attributes = Vec::new();
161    for node in &element.attributes {
162        let syn_rsx::Node::Attribute(attribute) = node else {
163            continue;
164        };
165        let Some(value) = attribute.value.as_ref() else {
166            return syn::Error::new_spanned(&attribute.key, "Element properties must have a value")
167                .to_compile_error();
168        };
169        let value = value.as_ref();
170
171        attributes.push(AttributeTokens {
172            name: attribute.key.to_string(),
173            value: quote! { #value },
174        });
175    }
176    let children = element
177        .children
178        .iter()
179        .filter(|node| matches!(node, syn_rsx::Node::Element(_)))
180        .map(expand_skia_rsx_node)
181        .collect();
182
183    let text_content = if element.name.to_string() == "Text" {
184        match extract_text_content(&element.children) {
185            Ok(content) => content,
186            Err(error) => return error.to_compile_error(),
187        }
188    } else {
189        None
190    };
191
192    expand_element(
193        &element.name.to_string(),
194        attributes,
195        children,
196        text_content,
197    )
198}
199
200/// Validates common element properties and dispatches to the tag-specific
201/// element expander.
202fn expand_element(
203    tag_name: &str,
204    attributes: impl IntoIterator<Item = AttributeTokens>,
205    children: Vec<proc_macro2::TokenStream>,
206    text_content: Option<proc_macro2::TokenStream>,
207) -> proc_macro2::TokenStream {
208    let properties = match ElementProperties::parse(attributes) {
209        Ok(properties) => properties,
210        Err(error) => return error.to_compile_error(),
211    };
212
213    match tag_name {
214        "Container" => expand_container(properties, children),
215        "Rect" => expand_rect(properties, children),
216        "Image" => expand_image(properties, children),
217        "Text" => expand_text(properties, children, text_content),
218        _ => syn::Error::new(
219            proc_macro2::Span::call_site(),
220            format!("Unknown element tag: {tag_name}"),
221        )
222        .to_compile_error(),
223    }
224}
225
226/// Concatenates literal text children for an RSX `Text` element.
227///
228/// Comments are ignored. Non-string text expressions and child elements are
229/// rejected, since this macro only supports literal text content.
230fn extract_text_content(
231    children: &[syn_rsx::Node],
232) -> syn::Result<Option<proc_macro2::TokenStream>> {
233    let mut content = String::new();
234    let mut found_text = false;
235
236    for child in children {
237        match child {
238            syn_rsx::Node::Text(text) => {
239                let value = String::try_from(&text.value).map_err(|_| {
240                    syn::Error::new(
241                        proc_macro2::Span::call_site(),
242                        "Text element content must be a string literal",
243                    )
244                })?;
245                content.push_str(&value);
246                found_text = true;
247            }
248            syn_rsx::Node::Comment(_) => {}
249            _ => {
250                return Err(syn::Error::new(
251                    proc_macro2::Span::call_site(),
252                    "Text elements may only contain string literal text",
253                ));
254            }
255        }
256    }
257
258    Ok(found_text.then(|| {
259        let literal = syn::LitStr::new(&content, proc_macro2::Span::call_site());
260        quote! { #literal }
261    }))
262}
263
264/// Parsed property values shared by the supported element expanders.
265///
266/// Values remain token streams until an expander emits them in the generated
267/// `Props` initializer, preserving Rust expression semantics.
268#[derive(Default)]
269struct ElementProperties {
270    width: Option<proc_macro2::TokenStream>,
271    height: Option<proc_macro2::TokenStream>,
272    position: Option<proc_macro2::TokenStream>,
273    x: Option<proc_macro2::TokenStream>,
274    y: Option<proc_macro2::TokenStream>,
275    vertical_alignment: Option<proc_macro2::TokenStream>,
276    horizontal_alignment: Option<proc_macro2::TokenStream>,
277    background_color: Option<proc_macro2::TokenStream>,
278    border_radius: Option<proc_macro2::TokenStream>,
279    content: Option<proc_macro2::TokenStream>,
280    font_bytes: Option<proc_macro2::TokenStream>,
281    font_size: Option<proc_macro2::TokenStream>,
282    max_width: Option<proc_macro2::TokenStream>,
283    max_height: Option<proc_macro2::TokenStream>,
284    text_wrap: Option<proc_macro2::TokenStream>,
285    text_overflow: Option<proc_macro2::TokenStream>,
286    text_alignment: Option<proc_macro2::TokenStream>,
287    image_src: Option<proc_macro2::TokenStream>,
288    image_sampling: Option<proc_macro2::TokenStream>,
289}
290
291impl ElementProperties {
292    /// Maps property names to their internal slots, rejecting unknown names.
293    fn parse(attributes: impl IntoIterator<Item = AttributeTokens>) -> syn::Result<Self> {
294        let mut properties = Self::default();
295
296        for attribute in attributes {
297            let target = match attribute.name.as_str() {
298                "width" => &mut properties.width,
299                "height" => &mut properties.height,
300                "position" => &mut properties.position,
301                "x" => &mut properties.x,
302                "y" => &mut properties.y,
303                "vertical_alignment" => &mut properties.vertical_alignment,
304                "horizontal_alignment" => &mut properties.horizontal_alignment,
305                "color" | "background_color" => &mut properties.background_color,
306                "border_radius" => &mut properties.border_radius,
307                "content" => &mut properties.content,
308                "font_bytes" => &mut properties.font_bytes,
309                "font_size" => &mut properties.font_size,
310                "max_width" => &mut properties.max_width,
311                "max_height" => &mut properties.max_height,
312                "text_wrap" => &mut properties.text_wrap,
313                "text_overflow" => &mut properties.text_overflow,
314                "text_alignment" => &mut properties.text_alignment,
315                "image_src" => &mut properties.image_src,
316                "image_sampling" => &mut properties.image_sampling,
317                other => {
318                    return Err(syn::Error::new(
319                        proc_macro2::Span::call_site(),
320                        format!("Unknown property: {other}"),
321                    ));
322                }
323            };
324            *target = Some(attribute.value);
325        }
326
327        Ok(properties)
328    }
329}
330
331/// Emits a container node with recursively expanded children.
332fn expand_container(
333    properties: ElementProperties,
334    children: Vec<proc_macro2::TokenStream>,
335) -> proc_macro2::TokenStream {
336    let mut fields = Vec::new();
337
338    if let Some(value) = properties.width {
339        fields.push(quote! { width: Some((#value) as f32) });
340    }
341    if let Some(value) = properties.height {
342        fields.push(quote! { height: Some((#value) as f32) });
343    }
344    if let Some(value) = properties.position {
345        fields.push(quote! { position: Some(#value) });
346    }
347    if let Some(value) = properties.x {
348        fields.push(quote! { x: Some((#value) as f32) });
349    }
350    if let Some(value) = properties.y {
351        fields.push(quote! { y: Some((#value) as f32) });
352    }
353    if let Some(value) = properties.vertical_alignment {
354        fields.push(quote! { vertical_alignment: Some(#value) });
355    }
356    if let Some(value) = properties.horizontal_alignment {
357        fields.push(quote! { horizontal_alignment: Some(#value) });
358    }
359    if let Some(value) = properties.background_color {
360        fields.push(quote! { background_color: Some(#value) });
361    }
362    if let Some(value) = properties.border_radius {
363        fields.push(quote! { border_radius: Some((#value) as f32) });
364    }
365
366    quote! {
367        skia_engine_core::ElementNode::Container {
368            props: skia_engine_core::nodes::container::Props {
369                #(#fields,)*
370                ..Default::default()
371            },
372            children: vec![#(#children),*],
373        }
374    }
375}
376
377/// Emits a leaf rectangle node, rejecting any element children.
378fn expand_rect(
379    properties: ElementProperties,
380    children: Vec<proc_macro2::TokenStream>,
381) -> proc_macro2::TokenStream {
382    if !children.is_empty() {
383        return syn::Error::new(
384            proc_macro2::Span::call_site(),
385            "Rect elements cannot contain children",
386        )
387        .to_compile_error();
388    }
389
390    let width = properties
391        .width
392        .map(|value| quote! { (#value) as f32 })
393        .unwrap_or_else(|| quote! { 0.0 });
394    let height = properties
395        .height
396        .map(|value| quote! { (#value) as f32 })
397        .unwrap_or_else(|| quote! { 0.0 });
398    let background_color = properties
399        .background_color
400        .unwrap_or_else(|| quote! { skia_safe::Color::BLACK });
401
402    let mut fields = Vec::new();
403    if let Some(value) = properties.position {
404        fields.push(quote! { position: Some(#value) });
405    }
406    if let Some(value) = properties.x {
407        fields.push(quote! { x: Some((#value) as f32) });
408    }
409    if let Some(value) = properties.y {
410        fields.push(quote! { y: Some((#value) as f32) });
411    }
412    if let Some(value) = properties.vertical_alignment {
413        fields.push(quote! { vertical_alignment: Some(#value) });
414    }
415    if let Some(value) = properties.horizontal_alignment {
416        fields.push(quote! { horizontal_alignment: Some(#value) });
417    }
418    if let Some(value) = properties.border_radius {
419        fields.push(quote! { border_radius: Some((#value) as f32) });
420    }
421
422    quote! {
423        skia_engine_core::ElementNode::Rect {
424            props: skia_engine_core::nodes::rect::Props {
425                width: #width,
426                height: #height,
427                background_color: #background_color,
428                #(#fields,)*
429                ..Default::default()
430            }
431        }
432    }
433}
434
435/// Emits a leaf image node, rejecting any element children.
436fn expand_image(
437    properties: ElementProperties,
438    children: Vec<proc_macro2::TokenStream>,
439) -> proc_macro2::TokenStream {
440    if !children.is_empty() {
441        return syn::Error::new(
442            proc_macro2::Span::call_site(),
443            "Image elements cannot contain children",
444        )
445        .to_compile_error();
446    }
447
448    let mut fields = Vec::new();
449    if let Some(value) = properties.width {
450        fields.push(quote! { width: (#value) as f32 });
451    }
452    if let Some(value) = properties.height {
453        fields.push(quote! { height: (#value) as f32 });
454    }
455    if let Some(value) = properties.position {
456        fields.push(quote! { position: Some(#value) });
457    }
458    if let Some(value) = properties.x {
459        fields.push(quote! { x: Some((#value) as f32) });
460    }
461    if let Some(value) = properties.y {
462        fields.push(quote! { y: Some((#value) as f32) });
463    }
464    if let Some(value) = properties.vertical_alignment {
465        fields.push(quote! { vertical_alignment: Some(#value) });
466    }
467    if let Some(value) = properties.horizontal_alignment {
468        fields.push(quote! { horizontal_alignment: Some(#value) });
469    }
470    if let Some(value) = properties.image_src {
471        fields.push(quote! { image_src: Some((#value).into()) });
472    }
473    if let Some(value) = properties.image_sampling {
474        fields.push(quote! { image_sampling: Some(#value) });
475    }
476    if let Some(value) = properties.background_color {
477        fields.push(quote! { background_color: Some(#value) });
478    }
479    if let Some(value) = properties.border_radius {
480        fields.push(quote! { border_radius: Some((#value) as f32) });
481    }
482
483    quote! {
484        skia_engine_core::ElementNode::Image {
485            props: skia_engine_core::nodes::image::Props {
486                #(#fields,)*
487                ..Default::default()
488            }
489        }
490    }
491}
492
493/// Emits a leaf text node after validating its content source and properties.
494fn expand_text(
495    properties: ElementProperties,
496    children: Vec<proc_macro2::TokenStream>,
497    text_content: Option<proc_macro2::TokenStream>,
498) -> proc_macro2::TokenStream {
499    if !children.is_empty() {
500        return syn::Error::new(
501            proc_macro2::Span::call_site(),
502            "Text elements cannot contain child elements; use the `content` property",
503        )
504        .to_compile_error();
505    }
506
507    if properties.content.is_some() && text_content.is_some() {
508        return syn::Error::new(
509            proc_macro2::Span::call_site(),
510            "Specify Text content either as a `content` property or as body text, not both",
511        )
512        .to_compile_error();
513    }
514
515    let Some(content) = properties.content.or(text_content) else {
516        return syn::Error::new(
517            proc_macro2::Span::call_site(),
518            "Text elements require a string literal body or a `content` property",
519        )
520        .to_compile_error();
521    };
522
523    let mut fields = Vec::new();
524    if let Some(value) = properties.background_color {
525        fields.push(quote! { color: Some(#value) });
526    }
527    if let Some(value) = properties.font_bytes {
528        fields.push(quote! { font_bytes: #value });
529    }
530    if let Some(value) = properties.font_size {
531        fields.push(quote! { font_size: Some((#value) as f32) });
532    }
533    if let Some(value) = properties.max_width {
534        fields.push(quote! { max_width: Some((#value) as f32) });
535    }
536    if let Some(value) = properties.max_height {
537        fields.push(quote! { max_height: Some((#value) as f32) });
538    }
539    if let Some(value) = properties.text_wrap {
540        fields.push(quote! { text_wrap: Some(#value) });
541    }
542    if let Some(value) = properties.text_overflow {
543        fields.push(quote! { text_overflow: Some(#value) });
544    }
545    if let Some(value) = properties.position {
546        fields.push(quote! { position: Some(#value) });
547    }
548    if let Some(value) = properties.x {
549        fields.push(quote! { x: Some((#value) as f32) });
550    }
551    if let Some(value) = properties.y {
552        fields.push(quote! { y: Some((#value) as f32) });
553    }
554    if let Some(value) = properties.vertical_alignment {
555        fields.push(quote! { vertical_alignment: Some(#value) });
556    }
557    if let Some(value) = properties.horizontal_alignment {
558        fields.push(quote! { horizontal_alignment: Some(#value) });
559    }
560    if let Some(value) = properties.text_alignment {
561        fields.push(quote! { text_alignment: Some(#value) });
562    }
563
564    quote! {
565        skia_engine_core::ElementNode::Text {
566            props: skia_engine_core::nodes::text::Props {
567                #(#fields,)*
568                ..Default::default()
569            },
570            content: #content,
571        }
572    }
573}