oxiforge 0.4.0

YAML-to-Rust code generator for oxivgl LVGL UIs
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::{HashMap, HashSet};

use crate::{error::OxiforgeError, model::*};

fn is_valid_rust_ident(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        None => false,
        Some(c) => (c.is_ascii_alphabetic() || c == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_'),
    }
}

/// Validate a parsed UiDoc. Returns list of errors (empty = valid).
pub fn validate(doc: &UiDoc) -> Vec<OxiforgeError> {
    let mut errors = Vec::new();
    let mut page_ids = HashSet::new();
    let mut widget_ids = HashSet::new();

    // Collect defined style IDs
    let style_ids: HashSet<&str> = doc
        .lvgl
        .style_definitions
        .as_ref()
        .map(|defs| defs.iter().map(|d| d.id.as_str()).collect())
        .unwrap_or_default();

    // Collect defined gradient IDs
    let gradient_ids: HashSet<&str> =
        doc.lvgl.gradients.as_ref().map(|gs| gs.iter().map(|g| g.id.as_str()).collect()).unwrap_or_default();

    // Toast id → declared param count (presets already expanded into `toasts`),
    // for validating `on: { ...: { show_toast } }` references and arg counts.
    let toast_params: HashMap<&str, usize> = doc
        .lvgl
        .toasts
        .iter()
        .flatten()
        .map(|t| (t.id.as_str(), t.params.as_deref().map_or(0, <[String]>::len)))
        .collect();

    // Style definitions carry full StyleProps — check their gradient refs and
    // bg_image_src symbols too.
    if let Some(defs) = &doc.lvgl.style_definitions {
        for def in defs {
            check_style_props(&def.style, &gradient_ids, &mut errors);
        }
    }

    // Check page IDs unique
    for page in &doc.lvgl.pages {
        if !page_ids.insert(page.id.as_str()) {
            errors.push(OxiforgeError::Other(format!("duplicate page id '{}'", page.id)));
        }
        check_style_refs(&page.common, &style_ids, &mut errors);
        check_style_props(&page.common.style, &gradient_ids, &mut errors);
        check_input_group(page, &mut errors);
        check_budget(&page.budget, &page.id, &mut errors);
        if let Some(widgets) = &page.common.widgets {
            validate_widgets(widgets, &style_ids, &gradient_ids, &mut widget_ids, &mut errors);
            reject_page_bind_text(widgets, &page.id, &mut errors);
            check_show_toast_refs(widgets, &toast_params, &mut errors);
        }
    }

    // Toasts: ids unique (and distinct from pages), timing fields exclusive,
    // non-empty content. Each toast is its own scope for widget-id checks.
    let mut toast_ids = HashSet::new();
    for toast in doc.lvgl.toasts.iter().flatten() {
        if page_ids.contains(toast.id.as_str()) {
            errors.push(OxiforgeError::Other(format!(
                "toast id '{}' collides with a page id — both emit create_{}",
                toast.id, toast.id
            )));
        }
        if !toast_ids.insert(toast.id.as_str()) {
            errors.push(OxiforgeError::Other(format!("duplicate toast id '{}'", toast.id)));
        }
        if toast.duration_ms.is_some() && toast.persistent == Some(true) {
            errors.push(OxiforgeError::Other(format!(
                "toast '{}' sets both 'duration_ms' and 'persistent' — they are mutually exclusive",
                toast.id
            )));
        }
        if toast.common.widgets.as_deref().is_none_or(<[WidgetKind]>::is_empty) {
            errors.push(OxiforgeError::Other(format!("toast '{}' has no widgets", toast.id)));
        }
        check_style_refs(&toast.common, &style_ids, &mut errors);
        check_style_props(&toast.common.style, &gradient_ids, &mut errors);
        check_budget(&toast.budget, &toast.id, &mut errors);
        if let Some(widgets) = &toast.common.widgets {
            let mut toast_widget_ids = HashSet::new();
            validate_widgets(widgets, &style_ids, &gradient_ids, &mut toast_widget_ids, &mut errors);
        }
        check_toast_bindings(toast, &mut errors);
    }

    errors
}

/// Validate a toast's `params` and the `bind_text:` references in its tree:
/// params are valid unique identifiers and each is used by some `bind_text`;
/// every `bind_text` names a declared param and the label has no static `text`.
fn check_toast_bindings(toast: &ToastDef, errors: &mut Vec<OxiforgeError>) {
    let params: Vec<&str> = toast.params.as_deref().unwrap_or_default().iter().map(String::as_str).collect();
    let param_set: HashSet<&str> = params.iter().copied().collect();

    let mut seen = HashSet::new();
    for p in &params {
        if !is_valid_rust_ident(p) {
            errors
                .push(OxiforgeError::Other(format!("toast '{}' param '{p}' is not a valid Rust identifier", toast.id)));
        }
        if !seen.insert(*p) {
            errors.push(OxiforgeError::Other(format!("toast '{}' declares duplicate param '{p}'", toast.id)));
        }
    }

    let mut used = HashSet::new();
    if let Some(widgets) = &toast.common.widgets {
        check_bind_text_tree(widgets, &toast.id, &param_set, &mut used, errors);
    }

    for p in &params {
        if !used.contains(*p) {
            errors.push(OxiforgeError::Other(format!(
                "toast '{}' declares param '{p}' but no bind_text uses it",
                toast.id
            )));
        }
    }
}

/// Recursively check `bind_text` labels against a toast's declared params.
fn check_bind_text_tree<'a>(
    widgets: &'a [WidgetKind],
    toast_id: &str,
    params: &HashSet<&'a str>,
    used: &mut HashSet<&'a str>,
    errors: &mut Vec<OxiforgeError>,
) {
    for w in widgets {
        if let WidgetKind::Label(p) = w
            && let Some(bind) = &p.bind_text
        {
            if p.text.is_some() {
                errors.push(OxiforgeError::Other(format!(
                    "toast '{toast_id}' label sets both 'text' and 'bind_text' — use one"
                )));
            }
            match params.get(bind.as_str()) {
                Some(name) => {
                    used.insert(*name);
                }
                None => {
                    let candidates: Vec<&str> = params.iter().copied().collect();
                    let msg = match crate::hints::closest_match(bind, &candidates, 5) {
                        Some(s) => {
                            format!(
                                "toast '{toast_id}' bind_text '{bind}' is not a declared param, did you mean '{s}'?"
                            )
                        }
                        None => format!("toast '{toast_id}' bind_text '{bind}' is not a declared param"),
                    };
                    errors.push(OxiforgeError::Other(msg));
                }
            }
        }
        if let Some(children) = w.common().widgets.as_deref() {
            check_bind_text_tree(children, toast_id, params, used, errors);
        }
    }
}

/// `bind_text` is toast-only — reject it anywhere in a page tree.
fn reject_page_bind_text(widgets: &[WidgetKind], page_id: &str, errors: &mut Vec<OxiforgeError>) {
    for w in widgets {
        if let WidgetKind::Label(p) = w
            && p.bind_text.is_some()
        {
            errors.push(OxiforgeError::Other(format!(
                "page '{page_id}' label uses 'bind_text', which is only valid inside a toast"
            )));
        }
        if let Some(children) = w.common().widgets.as_deref() {
            reject_page_bind_text(children, page_id, errors);
        }
    }
}

fn validate_widgets(
    widgets: &[WidgetKind],
    style_ids: &HashSet<&str>,
    gradient_ids: &HashSet<&str>,
    widget_ids: &mut HashSet<String>,
    errors: &mut Vec<OxiforgeError>,
) {
    for widget in widgets {
        let common = widget.common();

        // Check widget id uniqueness
        if let Some(id) = &common.id
            && !widget_ids.insert(id.clone())
        {
            errors.push(OxiforgeError::Other(format!("duplicate widget id '{id}'")));
        }

        check_style_refs(common, style_ids, errors);
        check_style_props(&common.style, gradient_ids, errors);
        check_event_bindings(common, errors);

        // Recurse into children
        if let Some(children) = &common.widgets {
            validate_widgets(children, style_ids, gradient_ids, widget_ids, errors);
        }

        // Recurse into Tabview tab contents
        #[cfg(feature = "widget-tabview")]
        if let WidgetKind::Tabview(p) = widget
            && let Some(tabs) = &p.tabs
        {
            for tab in tabs {
                check_style_refs(&tab.common, style_ids, errors);
                check_style_props(&tab.common.style, gradient_ids, errors);
                if let Some(children) = &tab.common.widgets {
                    validate_widgets(children, style_ids, gradient_ids, widget_ids, errors);
                }
            }
        }
        // Recurse into Tileview tile contents
        #[cfg(feature = "widget-tileview")]
        if let WidgetKind::Tileview(p) = widget
            && let Some(tiles) = &p.tiles
        {
            for tile in tiles {
                check_style_refs(&tile.common, style_ids, errors);
                check_style_props(&tile.common.style, gradient_ids, errors);
                if let Some(children) = &tile.common.widgets {
                    validate_widgets(children, style_ids, gradient_ids, widget_ids, errors);
                }
            }
        }
    }
}

/// Validate a page's `input_group` / `input_group_fn`: they are mutually
/// exclusive, the hook name must be a valid identifier, and every declarative
/// member must reference an id-tagged widget on the same page.
fn check_input_group(page: &Page, errors: &mut Vec<OxiforgeError>) {
    if page.input_group.is_some() && page.input_group_fn.is_some() {
        errors.push(OxiforgeError::Other(format!(
            "page '{}' sets both 'input_group' and 'input_group_fn' — they are mutually exclusive",
            page.id
        )));
    }

    if let Some(f) = &page.input_group_fn
        && !is_valid_rust_ident(f)
    {
        errors.push(OxiforgeError::Other(format!("input_group_fn {f:?} is not a valid Rust identifier")));
    }

    let Some(group) = &page.input_group else { return };

    if group.members.is_empty() {
        errors.push(OxiforgeError::Other(format!("page '{}' input_group has no members", page.id)));
        return;
    }

    // Id-tagged widgets on this page are the only valid focus-group members.
    let ids: Vec<String> = page
        .common
        .widgets
        .as_deref()
        .map(crate::codegen::collect_id_widgets)
        .unwrap_or_default()
        .into_iter()
        .map(|(id, _)| id)
        .collect();
    let candidates: Vec<&str> = ids.iter().map(String::as_str).collect();
    let id_set: HashSet<&str> = candidates.iter().copied().collect();

    for member in &group.members {
        if !id_set.contains(member.as_str()) {
            let msg = match crate::hints::closest_match(member, &candidates, 5) {
                Some(suggestion) => format!(
                    "page '{}' input_group member '{member}' is not a widget id on this page, did you mean '{suggestion}'?",
                    page.id
                ),
                None => {
                    format!("page '{}' input_group member '{member}' is not a widget id on this page", page.id)
                }
            };
            errors.push(OxiforgeError::Other(msg));
        }
    }
}

fn check_event_bindings(common: &CommonProps, errors: &mut Vec<OxiforgeError>) {
    let Some(on_map) = &common.on else { return };

    // Collect widget IDs in scope for collision detection
    let widget_id = common.id.as_deref();

    // Handler-name checks only; `show_toast` actions are validated against the
    // toast table in `check_show_toast_refs`.
    for handler_name in on_map.values().filter_map(|a| match a {
        EventAction::Handler(h) => Some(h),
        EventAction::ShowToast(_) => None,
    }) {
        if !is_valid_rust_ident(handler_name) {
            errors.push(OxiforgeError::Other(format!(
                "event handler name {:?} is not a valid Rust identifier",
                handler_name
            )));
        } else if Some(handler_name.as_str()) == widget_id {
            errors.push(OxiforgeError::Other(format!(
                "event handler name {:?} collides with widget id — the local variable would shadow the function",
                handler_name
            )));
        }
    }
}

/// Recursively validate `on: { ...: { show_toast: <id>, args: [...] } }`
/// bindings: the toast must exist and the arg count must match its params.
fn check_show_toast_refs(widgets: &[WidgetKind], toast_params: &HashMap<&str, usize>, errors: &mut Vec<OxiforgeError>) {
    for w in widgets {
        if let Some(on_map) = &w.common().on {
            for st in on_map.values().filter_map(|a| match a {
                EventAction::ShowToast(st) => Some(st),
                EventAction::Handler(_) => None,
            }) {
                match toast_params.get(st.show_toast.as_str()) {
                    None => errors.push(OxiforgeError::Other(format!(
                        "on show_toast '{}' is not a defined toast or preset",
                        st.show_toast
                    ))),
                    Some(&n) if st.args.len() != n => errors.push(OxiforgeError::Other(format!(
                        "on show_toast '{}' takes {n} arg(s) but {} given",
                        st.show_toast,
                        st.args.len()
                    ))),
                    Some(_) => {}
                }
            }
        }
        if let Some(children) = w.common().widgets.as_deref() {
            check_show_toast_refs(children, toast_params, errors);
        }
    }
}

fn check_style_refs(common: &CommonProps, style_ids: &HashSet<&str>, errors: &mut Vec<OxiforgeError>) {
    if let Some(style_ref) = &common.styles {
        for name in style_ref.names() {
            if !style_ids.contains(name) {
                errors.push(OxiforgeError::Other(format!("undefined style reference '{name}'")));
            }
        }
    }
}

fn check_budget(budget: &Option<BudgetDef>, owner: &str, errors: &mut Vec<OxiforgeError>) {
    if let Some(b) = budget
        && b.max_objects == 0
    {
        errors.push(OxiforgeError::Other(format!(
            "'{owner}' budget.max_objects must be at least 1 (the container itself counts)"
        )));
    }
}

fn check_style_props(style: &StyleProps, gradient_ids: &HashSet<&str>, errors: &mut Vec<OxiforgeError>) {
    if let Some(grad) = &style.bg_grad
        && !gradient_ids.contains(grad.as_str())
    {
        errors.push(OxiforgeError::Other(format!("undefined gradient reference '{grad}'")));
    }
    // bg_image_src is emitted verbatim into an `unsafe extern "C"` block — a
    // non-identifier would generate uncompilable code.
    if let Some(sym) = &style.bg_image_src
        && !is_valid_rust_ident(sym)
    {
        errors.push(OxiforgeError::Other(format!("bg_image_src '{sym}' is not a valid Rust identifier")));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::parse_str;

    #[test]
    fn rejects_duplicate_page_ids() {
        let yaml = "lvgl:\n  pages:\n    - id: main\n    - id: main\n";
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(!errs.is_empty());
        assert!(errs[0].to_string().contains("duplicate page id"));
    }

    #[test]
    fn rejects_zero_object_budget() {
        let yaml = r#"
lvgl:
  pages:
    - id: main
      budget:
        max_objects: 0
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(errs.iter().any(|e| e.to_string().contains("budget.max_objects")));
    }

    #[test]
    fn rejects_invalid_bg_image_src_ident() {
        let yaml = r#"
lvgl:
  style_definitions:
    - id: backdrop
      bg_image_src: "bad-symbol-name"
  pages:
    - id: main
      styles: backdrop
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(errs.iter().any(|e| e.to_string().contains("not a valid Rust identifier")));
    }

    #[test]
    fn rejects_duplicate_widget_ids() {
        let yaml = r#"
lvgl:
  pages:
    - id: main
      widgets:
        - label:
            id: lbl
            text: "a"
        - label:
            id: lbl
            text: "b"
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(!errs.is_empty());
        assert!(errs[0].to_string().contains("duplicate widget id"));
    }

    #[test]
    fn rejects_undefined_style_ref() {
        let yaml = r#"
lvgl:
  pages:
    - id: main
      widgets:
        - label:
            styles: nonexistent
            text: "hi"
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(!errs.is_empty());
        assert!(errs[0].to_string().contains("nonexistent"));
    }

    #[test]
    fn rejects_undefined_gradient_ref() {
        let yaml = r#"
lvgl:
  pages:
    - id: main
      widgets:
        - obj:
            bg_grad: missing_grad
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(!errs.is_empty());
        assert!(errs[0].to_string().contains("missing_grad"));
    }

    #[test]
    fn rejects_invalid_handler_name_with_hyphen() {
        let yaml = r#"
lvgl:
  pages:
    - id: main
      widgets:
        - button:
            on:
              clicked: "my-handler"
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(!errs.is_empty());
        assert!(errs[0].to_string().contains("my-handler"));
    }

    #[test]
    fn rejects_empty_handler_name() {
        let yaml = "lvgl:\n  pages:\n    - id: main\n      widgets:\n        - button:\n            on:\n              clicked: \"\"\n";
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(!errs.is_empty());
    }

    #[test]
    fn accepts_underscore_prefixed_handler() {
        let yaml = r#"
lvgl:
  pages:
    - id: main
      widgets:
        - button:
            on:
              clicked: _on_btn
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(errs.is_empty());
    }

    #[test]
    fn accepts_same_handler_on_two_widgets() {
        let yaml = r#"
lvgl:
  pages:
    - id: main
      widgets:
        - button:
            on:
              clicked: on_btn_clicked
        - button:
            on:
              clicked: on_btn_clicked
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(errs.is_empty());
    }

    #[test]
    fn rejects_handler_name_colliding_with_widget_id() {
        let yaml = r#"
lvgl:
  pages:
    - id: main
      widgets:
        - button:
            id: on_clicked
            on:
              clicked: on_clicked
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(!errs.is_empty());
        assert!(errs[0].to_string().contains("on_clicked"));
    }

    #[test]
    fn accepts_valid_document() {
        let yaml = r#"
lvgl:
  style_definitions:
    - id: card
      bg_color: 0x1E1E1E
  pages:
    - id: main
      widgets:
        - obj:
            styles: card
"#;
        let doc = parse_str(yaml).unwrap();
        let errs = validate(&doc);
        assert!(errs.is_empty());
    }
}