Skip to main content

azul_css/codegen/
rust.rs

1//! Rust source-code emitter for parsed CSS.
2//!
3//! Produces a `const CSS: Css = ...;` literal plus a minimal `Cargo.toml` and
4//! `src/main.rs` skeleton suitable for `cargo build` against `azul`.
5
6use alloc::{format, string::String, string::ToString, vec, vec::Vec};
7use core::fmt::Write;
8
9use super::{CodegenBackend, GeneratedFile};
10use crate::{
11    css::{
12        AttributeMatchOp, Css, CssAttributeSelector, CssDeclaration, CssNthChildPattern,
13        CssNthChildSelector, CssPath, CssPathPseudoSelector, CssPathSelector, DynamicCssProperty,
14        NodeTypeTag,
15    },
16    props::property::format_static_css_prop,
17};
18
19/// Emits Rust source code for a parsed CSS stylesheet.
20#[derive(Copy, Clone, Debug)]
21pub struct RustBackend;
22
23impl CodegenBackend for RustBackend {
24    fn lang(&self) -> &'static str {
25        "rust"
26    }
27
28    fn emit_css(&self, css: &Css) -> String {
29        css_to_rust_code(css)
30    }
31
32    fn emit_project(&self, css: &Css) -> Vec<GeneratedFile> {
33        let css_literal = css_to_rust_code(css);
34        let main_rs = format!(
35            "use azul::prelude::*;\r\n\r\n{css_literal}\r\n\r\nfn main() {{\r\n    \
36             println!(\"Generated stylesheet contains {{}} rule(s)\", \
37             CSS.rules.as_ref().len());\r\n}}\r\n",
38        );
39        let cargo_toml = "[package]\r\n\
40            name = \"azul-generated-app\"\r\n\
41            version = \"0.1.0\"\r\n\
42            edition = \"2021\"\r\n\
43            \r\n\
44            [dependencies]\r\n\
45            azul = \"0.0.7\"\r\n"
46            .to_string();
47        vec![
48            GeneratedFile {
49                path: "Cargo.toml".to_string(),
50                contents: cargo_toml,
51            },
52            GeneratedFile {
53                path: "src/main.rs".to_string(),
54                contents: main_rs,
55            },
56        ]
57    }
58}
59
60/// Render a parsed [`Css`] as Rust source code (a `const CSS: Css = ...;`).
61#[must_use]
62pub fn css_to_rust_code(css: &Css) -> String {
63    let mut output = String::new();
64
65    output.push_str("const CSS: Css = Css {\r\n");
66    output.push_str("\trules: [\r\n");
67
68    for block in &css.rules {
69        output.push_str("\t\tCssRuleBlock {\r\n");
70        let _ = write!(
71            output,
72            "\t\t\tpath: {},\r\n",
73            print_block_path(&block.path, 3)
74        );
75        let _ = write!(output, "\t\t\tpriority: {},\r\n", block.priority,);
76
77        output.push_str("\t\t\tdeclarations: [\r\n");
78        for declaration in &block.declarations {
79            let _ = write!(output, "\t\t\t\t{},\r\n", print_declaration(declaration, 4));
80        }
81        output.push_str("\t\t\t]\r\n");
82
83        output.push_str("\t\t},\r\n");
84    }
85
86    output.push_str("\t]\r\n");
87    output.push_str("};");
88
89    output.replace('\t', "    ")
90}
91
92#[allow(clippy::too_many_lines)]
93// large but cohesive: single-purpose CSS parser/formatter/dispatch table (one branch per property/variant)
94#[must_use]
95pub const fn format_node_type(n: &NodeTypeTag) -> &'static str {
96    match n {
97        // Document structure
98        NodeTypeTag::Html => "NodeTypeTag::Html",
99        NodeTypeTag::Head => "NodeTypeTag::Head",
100        NodeTypeTag::Body => "NodeTypeTag::Body",
101
102        // Block elements
103        NodeTypeTag::Div => "NodeTypeTag::Div",
104        NodeTypeTag::P => "NodeTypeTag::P",
105        NodeTypeTag::Article => "NodeTypeTag::Article",
106        NodeTypeTag::Section => "NodeTypeTag::Section",
107        NodeTypeTag::Nav => "NodeTypeTag::Nav",
108        NodeTypeTag::Aside => "NodeTypeTag::Aside",
109        NodeTypeTag::Header => "NodeTypeTag::Header",
110        NodeTypeTag::Footer => "NodeTypeTag::Footer",
111        NodeTypeTag::Main => "NodeTypeTag::Main",
112        NodeTypeTag::Figure => "NodeTypeTag::Figure",
113        NodeTypeTag::FigCaption => "NodeTypeTag::FigCaption",
114
115        // Headings
116        NodeTypeTag::H1 => "NodeTypeTag::H1",
117        NodeTypeTag::H2 => "NodeTypeTag::H2",
118        NodeTypeTag::H3 => "NodeTypeTag::H3",
119        NodeTypeTag::H4 => "NodeTypeTag::H4",
120        NodeTypeTag::H5 => "NodeTypeTag::H5",
121        NodeTypeTag::H6 => "NodeTypeTag::H6",
122
123        // Text formatting
124        NodeTypeTag::Br => "NodeTypeTag::Br",
125        NodeTypeTag::Hr => "NodeTypeTag::Hr",
126        NodeTypeTag::Pre => "NodeTypeTag::Pre",
127        NodeTypeTag::BlockQuote => "NodeTypeTag::BlockQuote",
128        NodeTypeTag::Address => "NodeTypeTag::Address",
129        NodeTypeTag::Details => "NodeTypeTag::Details",
130        NodeTypeTag::Summary => "NodeTypeTag::Summary",
131        NodeTypeTag::Dialog => "NodeTypeTag::Dialog",
132
133        // List elements
134        NodeTypeTag::Ul => "NodeTypeTag::Ul",
135        NodeTypeTag::Ol => "NodeTypeTag::Ol",
136        NodeTypeTag::Li => "NodeTypeTag::Li",
137        NodeTypeTag::Dl => "NodeTypeTag::Dl",
138        NodeTypeTag::Dt => "NodeTypeTag::Dt",
139        NodeTypeTag::Dd => "NodeTypeTag::Dd",
140        NodeTypeTag::Menu => "NodeTypeTag::Menu",
141        NodeTypeTag::MenuItem => "NodeTypeTag::MenuItem",
142        NodeTypeTag::Dir => "NodeTypeTag::Dir",
143
144        // Table elements
145        NodeTypeTag::Table => "NodeTypeTag::Table",
146        NodeTypeTag::Caption => "NodeTypeTag::Caption",
147        NodeTypeTag::THead => "NodeTypeTag::THead",
148        NodeTypeTag::TBody => "NodeTypeTag::TBody",
149        NodeTypeTag::TFoot => "NodeTypeTag::TFoot",
150        NodeTypeTag::Tr => "NodeTypeTag::Tr",
151        NodeTypeTag::Th => "NodeTypeTag::Th",
152        NodeTypeTag::Td => "NodeTypeTag::Td",
153        NodeTypeTag::ColGroup => "NodeTypeTag::ColGroup",
154        NodeTypeTag::Col => "NodeTypeTag::Col",
155
156        // Form elements
157        NodeTypeTag::Form => "NodeTypeTag::Form",
158        NodeTypeTag::FieldSet => "NodeTypeTag::FieldSet",
159        NodeTypeTag::Legend => "NodeTypeTag::Legend",
160        NodeTypeTag::Label => "NodeTypeTag::Label",
161        NodeTypeTag::Input => "NodeTypeTag::Input",
162        NodeTypeTag::Button => "NodeTypeTag::Button",
163        NodeTypeTag::Select => "NodeTypeTag::Select",
164        NodeTypeTag::OptGroup => "NodeTypeTag::OptGroup",
165        NodeTypeTag::SelectOption => "NodeTypeTag::SelectOption",
166        NodeTypeTag::TextArea => "NodeTypeTag::TextArea",
167        NodeTypeTag::Output => "NodeTypeTag::Output",
168        NodeTypeTag::Progress => "NodeTypeTag::Progress",
169        NodeTypeTag::Meter => "NodeTypeTag::Meter",
170        NodeTypeTag::DataList => "NodeTypeTag::DataList",
171
172        // Inline elements
173        NodeTypeTag::Span => "NodeTypeTag::Span",
174        NodeTypeTag::A => "NodeTypeTag::A",
175        NodeTypeTag::Em => "NodeTypeTag::Em",
176        NodeTypeTag::Strong => "NodeTypeTag::Strong",
177        NodeTypeTag::B => "NodeTypeTag::B",
178        NodeTypeTag::I => "NodeTypeTag::I",
179        NodeTypeTag::U => "NodeTypeTag::U",
180        NodeTypeTag::S => "NodeTypeTag::S",
181        NodeTypeTag::Mark => "NodeTypeTag::Mark",
182        NodeTypeTag::Del => "NodeTypeTag::Del",
183        NodeTypeTag::Ins => "NodeTypeTag::Ins",
184        NodeTypeTag::Code => "NodeTypeTag::Code",
185        NodeTypeTag::Samp => "NodeTypeTag::Samp",
186        NodeTypeTag::Kbd => "NodeTypeTag::Kbd",
187        NodeTypeTag::Var => "NodeTypeTag::Var",
188        NodeTypeTag::Cite => "NodeTypeTag::Cite",
189        NodeTypeTag::Dfn => "NodeTypeTag::Dfn",
190        NodeTypeTag::Abbr => "NodeTypeTag::Abbr",
191        NodeTypeTag::Acronym => "NodeTypeTag::Acronym",
192        NodeTypeTag::Q => "NodeTypeTag::Q",
193        NodeTypeTag::Time => "NodeTypeTag::Time",
194        NodeTypeTag::Sub => "NodeTypeTag::Sub",
195        NodeTypeTag::Sup => "NodeTypeTag::Sup",
196        NodeTypeTag::Small => "NodeTypeTag::Small",
197        NodeTypeTag::Big => "NodeTypeTag::Big",
198        NodeTypeTag::Bdo => "NodeTypeTag::Bdo",
199        NodeTypeTag::Bdi => "NodeTypeTag::Bdi",
200        NodeTypeTag::Wbr => "NodeTypeTag::Wbr",
201        NodeTypeTag::Ruby => "NodeTypeTag::Ruby",
202        NodeTypeTag::Rt => "NodeTypeTag::Rt",
203        NodeTypeTag::Rtc => "NodeTypeTag::Rtc",
204        NodeTypeTag::Rp => "NodeTypeTag::Rp",
205        NodeTypeTag::Data => "NodeTypeTag::Data",
206
207        // Embedded content
208        NodeTypeTag::Canvas => "NodeTypeTag::Canvas",
209        NodeTypeTag::Object => "NodeTypeTag::Object",
210        NodeTypeTag::Param => "NodeTypeTag::Param",
211        NodeTypeTag::Embed => "NodeTypeTag::Embed",
212        NodeTypeTag::Audio => "NodeTypeTag::Audio",
213        NodeTypeTag::Video => "NodeTypeTag::Video",
214        NodeTypeTag::Source => "NodeTypeTag::Source",
215        NodeTypeTag::Track => "NodeTypeTag::Track",
216        NodeTypeTag::Map => "NodeTypeTag::Map",
217        NodeTypeTag::Area => "NodeTypeTag::Area",
218        NodeTypeTag::Svg => "NodeTypeTag::Svg",
219        NodeTypeTag::SvgPath => "NodeTypeTag::SvgPath",
220        NodeTypeTag::SvgCircle => "NodeTypeTag::SvgCircle",
221        NodeTypeTag::SvgRect => "NodeTypeTag::SvgRect",
222        NodeTypeTag::SvgEllipse => "NodeTypeTag::SvgEllipse",
223        NodeTypeTag::SvgLine => "NodeTypeTag::SvgLine",
224        NodeTypeTag::SvgPolygon => "NodeTypeTag::SvgPolygon",
225        NodeTypeTag::SvgPolyline => "NodeTypeTag::SvgPolyline",
226        NodeTypeTag::SvgG => "NodeTypeTag::SvgG",
227
228        // SVG container elements
229        NodeTypeTag::SvgDefs => "NodeTypeTag::SvgDefs",
230        NodeTypeTag::SvgSymbol => "NodeTypeTag::SvgSymbol",
231        NodeTypeTag::SvgUse => "NodeTypeTag::SvgUse",
232        NodeTypeTag::SvgSwitch => "NodeTypeTag::SvgSwitch",
233
234        // SVG text elements
235        NodeTypeTag::SvgText => "NodeTypeTag::SvgText",
236        NodeTypeTag::SvgTspan => "NodeTypeTag::SvgTspan",
237        NodeTypeTag::SvgTextPath => "NodeTypeTag::SvgTextPath",
238
239        // SVG paint server elements
240        NodeTypeTag::SvgLinearGradient => "NodeTypeTag::SvgLinearGradient",
241        NodeTypeTag::SvgRadialGradient => "NodeTypeTag::SvgRadialGradient",
242        NodeTypeTag::SvgStop => "NodeTypeTag::SvgStop",
243        NodeTypeTag::SvgPattern => "NodeTypeTag::SvgPattern",
244
245        // SVG clipping/masking elements
246        NodeTypeTag::SvgClipPathElement => "NodeTypeTag::SvgClipPathElement",
247        NodeTypeTag::SvgMask => "NodeTypeTag::SvgMask",
248
249        // SVG filter elements
250        NodeTypeTag::SvgFilter => "NodeTypeTag::SvgFilter",
251        NodeTypeTag::SvgFeBlend => "NodeTypeTag::SvgFeBlend",
252        NodeTypeTag::SvgFeColorMatrix => "NodeTypeTag::SvgFeColorMatrix",
253        NodeTypeTag::SvgFeComponentTransfer => "NodeTypeTag::SvgFeComponentTransfer",
254        NodeTypeTag::SvgFeComposite => "NodeTypeTag::SvgFeComposite",
255        NodeTypeTag::SvgFeConvolveMatrix => "NodeTypeTag::SvgFeConvolveMatrix",
256        NodeTypeTag::SvgFeDiffuseLighting => "NodeTypeTag::SvgFeDiffuseLighting",
257        NodeTypeTag::SvgFeDisplacementMap => "NodeTypeTag::SvgFeDisplacementMap",
258        NodeTypeTag::SvgFeDistantLight => "NodeTypeTag::SvgFeDistantLight",
259        NodeTypeTag::SvgFeDropShadow => "NodeTypeTag::SvgFeDropShadow",
260        NodeTypeTag::SvgFeFlood => "NodeTypeTag::SvgFeFlood",
261        NodeTypeTag::SvgFeFuncR => "NodeTypeTag::SvgFeFuncR",
262        NodeTypeTag::SvgFeFuncG => "NodeTypeTag::SvgFeFuncG",
263        NodeTypeTag::SvgFeFuncB => "NodeTypeTag::SvgFeFuncB",
264        NodeTypeTag::SvgFeFuncA => "NodeTypeTag::SvgFeFuncA",
265        NodeTypeTag::SvgFeGaussianBlur => "NodeTypeTag::SvgFeGaussianBlur",
266        NodeTypeTag::SvgFeImage => "NodeTypeTag::SvgFeImage",
267        NodeTypeTag::SvgFeMerge => "NodeTypeTag::SvgFeMerge",
268        NodeTypeTag::SvgFeMergeNode => "NodeTypeTag::SvgFeMergeNode",
269        NodeTypeTag::SvgFeMorphology => "NodeTypeTag::SvgFeMorphology",
270        NodeTypeTag::SvgFeOffset => "NodeTypeTag::SvgFeOffset",
271        NodeTypeTag::SvgFePointLight => "NodeTypeTag::SvgFePointLight",
272        NodeTypeTag::SvgFeSpecularLighting => "NodeTypeTag::SvgFeSpecularLighting",
273        NodeTypeTag::SvgFeSpotLight => "NodeTypeTag::SvgFeSpotLight",
274        NodeTypeTag::SvgFeTile => "NodeTypeTag::SvgFeTile",
275        NodeTypeTag::SvgFeTurbulence => "NodeTypeTag::SvgFeTurbulence",
276
277        // SVG marker/image elements
278        NodeTypeTag::SvgMarker => "NodeTypeTag::SvgMarker",
279        NodeTypeTag::SvgImage => "NodeTypeTag::SvgImage",
280        NodeTypeTag::SvgForeignObject => "NodeTypeTag::SvgForeignObject",
281
282        // SVG descriptive elements
283        NodeTypeTag::SvgTitle => "NodeTypeTag::SvgTitle",
284        NodeTypeTag::SvgDesc => "NodeTypeTag::SvgDesc",
285        NodeTypeTag::SvgMetadata => "NodeTypeTag::SvgMetadata",
286        NodeTypeTag::SvgA => "NodeTypeTag::SvgA",
287        NodeTypeTag::SvgView => "NodeTypeTag::SvgView",
288        NodeTypeTag::SvgStyle => "NodeTypeTag::SvgStyle",
289        NodeTypeTag::SvgScript => "NodeTypeTag::SvgScript",
290
291        // SVG animation elements
292        NodeTypeTag::SvgAnimate => "NodeTypeTag::SvgAnimate",
293        NodeTypeTag::SvgAnimateMotion => "NodeTypeTag::SvgAnimateMotion",
294        NodeTypeTag::SvgAnimateTransform => "NodeTypeTag::SvgAnimateTransform",
295        NodeTypeTag::SvgSet => "NodeTypeTag::SvgSet",
296        NodeTypeTag::SvgMpath => "NodeTypeTag::SvgMpath",
297
298        // Metadata
299        NodeTypeTag::Title => "NodeTypeTag::Title",
300        NodeTypeTag::Meta => "NodeTypeTag::Meta",
301        NodeTypeTag::Link => "NodeTypeTag::Link",
302        NodeTypeTag::Script => "NodeTypeTag::Script",
303        NodeTypeTag::Style => "NodeTypeTag::Style",
304        NodeTypeTag::Base => "NodeTypeTag::Base",
305
306        // Content elements
307        NodeTypeTag::Text => "NodeTypeTag::Text",
308        NodeTypeTag::Img => "NodeTypeTag::Img",
309        NodeTypeTag::VirtualView => "NodeTypeTag::VirtualView",
310        NodeTypeTag::TransientWindow => "NodeTypeTag::TransientWindow",
311        NodeTypeTag::Icon => "NodeTypeTag::Icon",
312        NodeTypeTag::GeolocationProbe => "NodeTypeTag::GeolocationProbe",
313        NodeTypeTag::PageBreak => "NodeTypeTag::PageBreak",
314
315        // Pseudo-elements
316        NodeTypeTag::Before => "NodeTypeTag::Before",
317        NodeTypeTag::After => "NodeTypeTag::After",
318        NodeTypeTag::Marker => "NodeTypeTag::Marker",
319        NodeTypeTag::Placeholder => "NodeTypeTag::Placeholder",
320    }
321}
322
323#[must_use]
324pub fn print_block_path(path: &CssPath, tabs: usize) -> String {
325    let t = String::from("    ").repeat(tabs);
326    let t1 = String::from("    ").repeat(tabs + 1);
327
328    format!(
329        "CssPath {{\r\n{}selectors: {}\r\n{}}}",
330        t1,
331        format_selectors(path.selectors.as_ref(), tabs + 1),
332        t
333    )
334}
335
336#[must_use]
337pub fn format_selectors(selectors: &[CssPathSelector], tabs: usize) -> String {
338    let t = String::from("    ").repeat(tabs);
339    let t1 = String::from("    ").repeat(tabs + 1);
340
341    let selectors_formatted = selectors
342        .iter()
343        .map(|s| format!("{}{},", t1, format_single_selector(s, tabs + 1)))
344        .collect::<Vec<String>>()
345        .join("\r\n");
346
347    format!("vec![\r\n{selectors_formatted}\r\n{t}].into()")
348}
349
350#[must_use]
351pub fn format_single_selector(p: &CssPathSelector, _tabs: usize) -> String {
352    match p {
353        CssPathSelector::Global => "CssPathSelector::Global".to_string(),
354        CssPathSelector::Root(r) => format!(
355            "CssPathSelector::Root(CssScopeRange {{ start: {}, end: {} }})",
356            r.start, r.end
357        ),
358        CssPathSelector::Type(ntp) => format!("CssPathSelector::Type({})", format_node_type(ntp)),
359        CssPathSelector::Class(class) => {
360            format!("CssPathSelector::Class(String::from({class:?}))")
361        }
362        CssPathSelector::Id(id) => format!("CssPathSelector::Id(String::from({id:?}))"),
363        CssPathSelector::PseudoSelector(cps) => format!(
364            "CssPathSelector::PseudoSelector({})",
365            format_pseudo_selector_type(cps)
366        ),
367        CssPathSelector::Attribute(a) => format!(
368            "CssPathSelector::Attribute({})",
369            format_attribute_selector(a)
370        ),
371        CssPathSelector::DirectChildren => "CssPathSelector::DirectChildren".to_string(),
372        CssPathSelector::Children => "CssPathSelector::Children".to_string(),
373        CssPathSelector::AdjacentSibling => "CssPathSelector::AdjacentSibling".to_string(),
374        CssPathSelector::GeneralSibling => "CssPathSelector::GeneralSibling".to_string(),
375    }
376}
377
378#[must_use]
379pub fn format_pseudo_selector_type(p: &CssPathPseudoSelector) -> String {
380    match p {
381        CssPathPseudoSelector::First => "CssPathPseudoSelector::First".to_string(),
382        CssPathPseudoSelector::Last => "CssPathPseudoSelector::Last".to_string(),
383        CssPathPseudoSelector::NthChild(n) => format!(
384            "CssPathPseudoSelector::NthChild({})",
385            format_nth_child_selector(n)
386        ),
387        CssPathPseudoSelector::Placeholder => "CssPathPseudoSelector::Placeholder".to_string(),
388        CssPathPseudoSelector::Hover => "CssPathPseudoSelector::Hover".to_string(),
389        CssPathPseudoSelector::Active => "CssPathPseudoSelector::Active".to_string(),
390        CssPathPseudoSelector::Focus => "CssPathPseudoSelector::Focus".to_string(),
391        CssPathPseudoSelector::SeatFocus => "CssPathPseudoSelector::SeatFocus".to_string(),
392        CssPathPseudoSelector::Backdrop => "CssPathPseudoSelector::Backdrop".to_string(),
393        CssPathPseudoSelector::Lang(lang) => format!(
394            "CssPathPseudoSelector::Lang(AzString::from_const_str(\"{}\"))",
395            lang.as_str()
396        ),
397        CssPathPseudoSelector::Dragging => "CssPathPseudoSelector::Dragging".to_string(),
398        CssPathPseudoSelector::DragOver => "CssPathPseudoSelector::DragOver".to_string(),
399        CssPathPseudoSelector::Root => "CssPathPseudoSelector::Root".to_string(),
400    }
401}
402
403#[must_use]
404pub fn format_attribute_selector(a: &CssAttributeSelector) -> String {
405    let value = a.value.as_ref().map_or_else(
406        || "OptionString::None".to_string(),
407        |v| {
408            format!(
409                "OptionString::Some(AzString::from_const_str({:?}))",
410                v.as_str()
411            )
412        },
413    );
414    format!(
415        "CssAttributeSelector {{ name: AzString::from_const_str({:?}), op: {}, value: {} }}",
416        a.name.as_str(),
417        format_attribute_match_op(&a.op),
418        value
419    )
420}
421
422#[must_use]
423pub fn format_attribute_match_op(op: &AttributeMatchOp) -> String {
424    match op {
425        AttributeMatchOp::Exists => "AttributeMatchOp::Exists".to_string(),
426        AttributeMatchOp::Eq => "AttributeMatchOp::Eq".to_string(),
427        AttributeMatchOp::Includes => "AttributeMatchOp::Includes".to_string(),
428        AttributeMatchOp::DashMatch => "AttributeMatchOp::DashMatch".to_string(),
429        AttributeMatchOp::Prefix => "AttributeMatchOp::Prefix".to_string(),
430        AttributeMatchOp::Suffix => "AttributeMatchOp::Suffix".to_string(),
431        AttributeMatchOp::Substring => "AttributeMatchOp::Substring".to_string(),
432    }
433}
434
435#[must_use]
436pub fn format_nth_child_selector(n: &CssNthChildSelector) -> String {
437    match n {
438        CssNthChildSelector::Number(num) => format!("CssNthChildSelector::Number({num})"),
439        CssNthChildSelector::Even => "CssNthChildSelector::Even".to_string(),
440        CssNthChildSelector::Odd => "CssNthChildSelector::Odd".to_string(),
441        CssNthChildSelector::Pattern(CssNthChildPattern {
442            pattern_repeat,
443            offset,
444        }) => format!(
445            "CssNthChildSelector::Pattern(CssNthChildPattern {{ pattern_repeat: {pattern_repeat}, offset: {offset} }})"
446        ),
447    }
448}
449
450#[must_use]
451pub fn print_declaration(decl: &CssDeclaration, tabs: usize) -> String {
452    match decl {
453        CssDeclaration::Static(s) => format!(
454            "CssDeclaration::Static({})",
455            format_static_css_prop(s, tabs)
456        ),
457        CssDeclaration::Dynamic(d) => format!(
458            "CssDeclaration::Dynamic({})",
459            format_dynamic_css_prop(d, tabs)
460        ),
461    }
462}
463
464#[must_use]
465pub fn format_dynamic_css_prop(decl: &DynamicCssProperty, tabs: usize) -> String {
466    let t = String::from("    ").repeat(tabs);
467    format!(
468        "DynamicCssProperty {{\r\n{}    dynamic_id: {:?},\r\n{}    default_value: {},\r\n{}}}",
469        t,
470        decl.dynamic_id,
471        t,
472        format_static_css_prop(&decl.default_value, tabs + 1),
473        t
474    )
475}
476
477#[cfg(test)]
478mod tests {
479    use alloc::vec;
480
481    use super::*;
482    use crate::css::CssRuleBlock;
483
484    fn sample_css() -> Css {
485        let path = CssPath::new(vec![CssPathSelector::Type(NodeTypeTag::Div)]);
486        let block = CssRuleBlock::new(path, vec![]);
487        Css {
488            rules: vec![block].into(),
489            keyframes: crate::css::KeyframesVec::from_const_slice(&[]),
490        }
491    }
492
493    #[test]
494    fn rust_backend_emits_const_literal() {
495        let css = sample_css();
496        let rust = RustBackend.emit_css(&css);
497        assert!(rust.contains("const CSS: Css"));
498        assert!(rust.contains("NodeTypeTag::Div"));
499    }
500
501    #[test]
502    fn rust_backend_emits_project_files() {
503        let css = sample_css();
504        let files = RustBackend.emit_project(&css);
505        let paths: Vec<_> = files.iter().map(|f| f.path.as_str()).collect();
506        assert!(paths.contains(&"Cargo.toml"));
507        assert!(paths.contains(&"src/main.rs"));
508        let main_rs = files
509            .iter()
510            .find(|f| f.path == "src/main.rs")
511            .expect("main.rs missing");
512        assert!(main_rs.contains_const_literal());
513    }
514
515    impl GeneratedFile {
516        fn contains_const_literal(&self) -> bool {
517            self.contents.contains("const CSS: Css")
518        }
519    }
520}