espforge-bindings 0.6.0

a scaffolding++ tool for creating esp32 no_std esphal without the hassle
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
582
583
584
585
586
587
588
589
590
591
//! Three generated files, all checked in and rewritten only when their inputs
//! change:
//!
//! - `src/drivers/generated_registry.rs` — the driver dispatch table, from the
//!   `src/drivers/*.rs` modules.
//! - `src/components/generated_vocab.rs` — the bus-component tags, from the one
//!   element schema (`espforge-espgenerate-template/src/espf.schema.kdl`).
//! - `src/components/generated_elements.rs` — one typed `Attrs` struct per
//!   element, from the same schema.

use std::fs;
use std::path::Path;

const SCHEMA: &str = "../espforge-espgenerate-template/src/espf.schema.kdl";

fn main() {
    drivers();
    component_vocab();
    element_attrs();
}

/// The driver registry: one dispatch arm per `src/drivers/*.rs` module.
fn drivers() {
    println!("cargo:rerun-if-changed=src/drivers");

    let drivers_dir = Path::new("src/drivers");
    let dest_path = Path::new("src/drivers/generated_registry.rs");

    let mut modules = Vec::new();
    let mut match_arms = Vec::new();
    let mut tags = Vec::new();

    if let Ok(entries) = fs::read_dir(drivers_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            println!("cargo:rerun-if-changed={}", path.display());
            if path.extension().map_or(false, |ext| ext == "rs") {
                let stem = path.file_stem().unwrap().to_str().unwrap().to_string();
                if stem != "mod" && stem != "generated_registry" {
                    // #[path] is relative to src/drivers/ (the directory containing
                    // generated_registry.rs), so "tmp102.rs" resolves to
                    // src/drivers/tmp102.rs. Do not remove.
                    modules.push(format!("#[path = \"{stem}.rs\"]\npub mod {stem};"));
                    match_arms.push(format!("        \"{stem}\" => {stem}::init(device),"));
                    tags.push(format!("\"{stem}\""));
                }
            }
        }
    }

    let generated_code = format!(
        "// AUTO-GENERATED BY BUILD.RS - DO NOT EDIT MANUALLY\n\n\
        #[allow(dead_code)]\n\
        {}\n\n\
        /// The device tags this registry routes, emitted alongside `route_driver`\n\
        /// so the `espforge espf` catalog can be drift-checked against it.\n\
        pub const TAGS: &[&str] = &[{}];\n\
        \n\
        pub fn route_driver(tag_name: &str, device: &espf::context::ParsedNode) -> Result<(), String> {{\n\
            match tag_name {{\n\
        {}\n\
                _ => Err(format!(\"No compile-time driver engine found for runtime tag <{{}}>\", tag_name)),\n\
            }}\n\
        }}",
        modules.join("\n"),
        tags.join(", "),
        match_arms.join("\n")
    );

    write_if_changed(dest_path, &generated_code);
}

/// The bus-component vocabulary, read from the single element schema.
///
/// A bus component is an element in the schema's `components` section marked
/// `bus_component=#true`. `<led>` and `<button>` are leaf components, so they
/// carry `bus_component=#false` and stay out of the list.
fn component_vocab() {
    println!("cargo:rerun-if-changed={SCHEMA}");

    let src = fs::read_to_string(SCHEMA).unwrap_or_else(|e| panic!("cannot read {SCHEMA}: {e}"));
    let doc = kdl::KdlDocument::parse_v2(&src)
        .unwrap_or_else(|e| panic!("{SCHEMA} is not valid KDL v2:\n{e}"));

    let mut components: Vec<String> = Vec::new();

    for node in doc.nodes() {
        if node.name().value() != "element" {
            continue;
        }
        let section = node.get("section").and_then(|value| value.as_string());
        if section != Some("components") {
            continue;
        }
        let tag = node
            .entries()
            .iter()
            .find(|entry| entry.name().is_none())
            .and_then(|entry| entry.value().as_string())
            .unwrap_or_else(|| panic!("an `element` in {SCHEMA} has no tag name"));

        let is_bus_component = node
            .get("bus_component")
            .and_then(|value| value.as_bool())
            .unwrap_or(false);
        if is_bus_component {
            components.push(tag.to_string());
        }
    }

    let tags: Vec<String> = components.iter().map(|tag| format!("\"{tag}\"")).collect();
    let out = format!(
        "// AUTO-GENERATED BY BUILD.RS FROM espf.schema.kdl - DO NOT EDIT MANUALLY\n\n\
        /// The bus-component tags in schema order.\n\
        ///\n\
        /// These are the `components` elements marked `bus_component=#true` in\n\
        /// `espf.schema.kdl`, so the catalog and the schema cannot disagree.\n\
        pub const TAGS: &[&str] = &[{}];\n",
        tags.join(", ")
    );

    write_if_changed(Path::new("src/components/generated_vocab.rs"), &out);
}

/// The element types: one `Attrs` struct per element in the schema.
///
/// Every declared attribute becomes a field whose type follows its `kind`, so
/// presence (`required`), the `choices` list, a `range` and defaults are read
/// from the schema rather than restated in lowering. Each value keeps the
/// byte span it was written at, which is what diagnostics need.
fn element_attrs() {
    println!("cargo:rerun-if-changed={SCHEMA}");

    let src = fs::read_to_string(SCHEMA).unwrap_or_else(|e| panic!("cannot read {SCHEMA}: {e}"));
    let doc = kdl::KdlDocument::parse_v2(&src)
        .unwrap_or_else(|e| panic!("{SCHEMA} is not valid KDL v2:\n{e}"));

    let mut out = String::from(
        "// AUTO-GENERATED BY BUILD.RS FROM espf.schema.kdl - DO NOT EDIT MANUALLY\n\
         \n\
         //! One `Attrs` struct per element in `espf.schema.kdl`: every attribute\n\
         //! coerced to its declared `kind`, with the span it was written at.\n\
         //!\n\
         //! Lowering consumes these; the coercion itself is in\n\
         //! `super::attrs`.\n",
    );

    for node in doc.nodes() {
        if node.name().value() != "element" {
            continue;
        }
        out.push('\n');
        out.push_str(&element_module(node));
    }

    write_if_changed(Path::new("src/components/generated_elements.rs"), &out);
}

/// One `pub mod <tag> { ... }` with the element's enums and `Attrs` struct.
fn element_module(node: &kdl::KdlNode) -> String {
    let tag = first_positional(node)
        .unwrap_or_else(|| panic!("an `element` in {SCHEMA} has no tag name"));

    let mut enums: Vec<String> = Vec::new();
    let mut fields: Vec<String> = Vec::new();
    let mut inits: Vec<String> = Vec::new();
    let mut borrowed = false;

    for attr in children(node, "attr") {
        let name =
            first_positional(&attr).unwrap_or_else(|| panic!("an `attr` of `{tag}` has no name"));
        let kind =
            prop_string(&attr, "kind").unwrap_or_else(|| panic!("`{tag}.{name}` has no kind"));
        let required = prop_bool(&attr, "required").unwrap_or(false);
        let default = prop_string(&attr, "default");
        let choices = child_strings(&attr, "choices");
        let lit = format!("{name:?}");

        let (ty, init) = match (kind.as_str(), required, default.as_deref()) {
            ("ident", _, _) => (
                "Spanned<&'a str>".to_string(),
                format!("ident(node, {lit})?"),
            ),
            ("str", true, _) => (
                "Spanned<&'a str>".to_string(),
                format!("text(node, {lit})?"),
            ),
            ("str", false, Some(d)) => (
                "Spanned<&'a str>".to_string(),
                format!("text_or(node, {lit}, {d:?})?"),
            ),
            ("str", false, None) => (
                "Option<Spanned<&'a str>>".to_string(),
                format!("opt_text(node, {lit})?"),
            ),
            ("freq", true, _) => (
                "Spanned<&'a str>".to_string(),
                format!("frequency(node, {lit})?"),
            ),
            ("freq", false, Some(d)) => (
                "Spanned<&'a str>".to_string(),
                format!("frequency_or(node, {lit}, {d:?})?"),
            ),
            ("freq", false, None) => (
                "Option<Spanned<&'a str>>".to_string(),
                format!("opt_frequency(node, {lit})?"),
            ),
            ("bool", true, _) => ("Spanned<bool>".to_string(), format!("flag(node, {lit})?")),
            ("bool", false, Some(d)) => {
                let d = match d {
                    "true" => "true",
                    "false" => "false",
                    other => panic!("`{tag}.{name}` has non-boolean default `{other}`"),
                };
                (
                    "Spanned<bool>".to_string(),
                    format!("flag_or(node, {lit}, {d})?"),
                )
            }
            ("u32", true, _) => match prop_string(&attr, "range") {
                Some(range) => {
                    let (low, high) = parse_range(&range, &tag, &name);
                    (
                        "Spanned<u32>".to_string(),
                        format!("number_in(node, {lit}, {low}, {high})?"),
                    )
                }
                None => ("Spanned<u32>".to_string(), format!("number(node, {lit})?")),
            },
            ("u32", false, Some(d)) => {
                let d: u32 = d
                    .parse()
                    .unwrap_or_else(|_| panic!("`{tag}.{name}` default `{d}` is not a u32"));
                match prop_string(&attr, "range") {
                    Some(range) => {
                        let (low, high) = parse_range(&range, &tag, &name);
                        (
                            "Spanned<u32>".to_string(),
                            format!("number_in_or(node, {lit}, {low}, {high}, {d})?"),
                        )
                    }
                    None => (
                        "Spanned<u32>".to_string(),
                        format!("number_or(node, {lit}, {d})?"),
                    ),
                }
            }
            ("pin", true, _) => ("Spanned<u8>".to_string(), format!("pin(node, {lit})?")),
            ("pin", false, None) => (
                "Option<Spanned<u8>>".to_string(),
                format!("opt_pin(node, {lit})?"),
            ),
            ("hex", true, _) => ("Spanned<u8>".to_string(), format!("hex(node, {lit})?")),
            ("hex", false, None) => (
                "Option<Spanned<u8>>".to_string(),
                format!("opt_hex(node, {lit})?"),
            ),
            ("pin_or_ref", true, _) => (
                "PinOrRef<'a>".to_string(),
                format!("pin_or_ref(node, {lit})?"),
            ),
            ("ref", true, _) => ("Ref<'a>".to_string(), format!("reference(node, {lit})?")),
            ("ref", false, None) => (
                "Option<Ref<'a>>".to_string(),
                format!("opt_reference(node, {lit})?"),
            ),
            ("list", _, _) => (
                "Vec<Spanned<&'a str>>".to_string(),
                format!("list(node, {lit})"),
            ),
            ("choice", _, _) => {
                if choices.is_empty() {
                    panic!("choice attribute `{tag}.{name}` has no `choices`");
                }
                let enum_name = camel_case(&field_name(&name));
                enums.push(choice_enum(&enum_name, &name, &choices));
                match (required, default.as_deref()) {
                    (true, _) => (
                        format!("Spanned<{enum_name}>"),
                        format!("parsed(node, {lit}, {enum_name}::parse)?"),
                    ),
                    (false, Some(d)) => (
                        format!("Spanned<{enum_name}>"),
                        format!(
                            "parsed_or(node, {lit}, {enum_name}::parse, {enum_name}::{})?",
                            variant_name(d)
                        ),
                    ),
                    (false, None) => (
                        format!("Option<Spanned<{enum_name}>>"),
                        format!("opt_parsed(node, {lit}, {enum_name}::parse)?"),
                    ),
                }
            }
            (other, required, default) => panic!(
                "unsupported attribute on `{tag}.{name}`: kind `{other}`, required {required}, default {default:?}"
            ),
        };

        let presence = match (required, default.as_deref()) {
            (true, _) => "required".to_string(),
            (false, Some(d)) => format!("optional, default {d:?}"),
            (false, None) => "optional".to_string(),
        };
        let field = field_name(&name);
        borrowed |= ty.contains("'a");
        fields.push(format!(
            "    /// `{name}` (`{kind}`, {presence})\n    pub {field}: {ty},"
        ));
        inits.push(format!("            {field}: {init},"));
    }

    // An element whose attributes are all owned values (`<runtime type=...>`)
    // borrows nothing, so it needs no lifetime parameter.
    let (struct_head, impl_head, fn_head) = if borrowed {
        (
            "pub struct Attrs<'a> {",
            "impl<'a> Attrs<'a> {",
            "pub fn from_node(node: &'a ParsedNode<'a>) -> Result<Self, Issue<'a>> {",
        )
    } else {
        (
            "pub struct Attrs {",
            "impl Attrs {",
            "pub fn from_node<'n>(node: &'n ParsedNode<'n>) -> Result<Self, Issue<'n>> {",
        )
    };

    let mut body = String::new();
    for definition in &enums {
        body.push_str(definition);
    }
    body.push_str(&format!(
        concat!(
            "/// `<{tag}>` from `espf.schema.kdl`.\n",
            "#[derive(Debug, Clone)]\n",
            "{struct_head}\n",
            "{fields}\n",
            "}}\n",
            "\n",
            "{impl_head}\n",
            "    /// Reads the attributes `espf.schema.kdl` declares for `<{tag}>`.\n",
            "    {fn_head}\n",
            "        Ok(Self {{\n",
            "{inits}\n",
            "        }})\n",
            "    }}\n",
            "}}\n",
        ),
        tag = tag,
        struct_head = struct_head,
        impl_head = impl_head,
        fn_head = fn_head,
        fields = fields.join("\n"),
        inits = inits.join("\n"),
    ));

    format!(
        concat!(
            "pub mod {tag} {{\n",
            "    use espf::context::ParsedNode;\n",
            "\n",
            "    use crate::components::attrs::*;\n",
            "\n",
            "{body}",
            "}}\n",
        ),
        tag = tag,
        body = indent(&body, 4),
    )
}

/// A generated enum for one `kind="choice"` attribute.
fn choice_enum(enum_name: &str, attr_name: &str, choices: &[String]) -> String {
    let variants: Vec<String> = choices.iter().map(|c| variant_name(c)).collect();

    let mut decls = String::new();
    let mut parses = String::new();
    let mut spellings = String::new();
    for (choice, variant) in choices.iter().zip(&variants) {
        decls.push_str(&format!("    /// `{choice}`\n    {variant},\n"));
        parses.push_str(&format!(
            "            {choice:?} => Some(Self::{variant}),\n"
        ));
        spellings.push_str(&format!("            Self::{variant} => {choice:?},\n"));
    }

    let quoted: Vec<String> = choices.iter().map(|c| format!("{c:?}")).collect();

    format!(
        concat!(
            "/// The `{attr_name}` values `espf.schema.kdl` allows.\n",
            "#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n",
            "pub enum {enum_name} {{\n",
            "{decls}",
            "}}\n",
            "\n",
            "impl {enum_name} {{\n",
            "    /// The accepted spellings, in schema order.\n",
            "    pub const CHOICES: &'static [&'static str] = &[{choices}];\n",
            "\n",
            "    /// Parses one of `CHOICES`; `None` for anything else.\n",
            "    pub fn parse(raw: &str) -> Option<Self> {{\n",
            "        match raw {{\n",
            "{parses}",
            "            _ => None,\n",
            "        }}\n",
            "    }}\n",
            "\n",
            "    /// The ESPF spelling of this value.\n",
            "    pub fn as_str(self) -> &'static str {{\n",
            "        match self {{\n",
            "{spellings}",
            "        }}\n",
            "    }}\n",
            "}}\n",
            "\n",
        ),
        attr_name = attr_name,
        enum_name = enum_name,
        decls = decls,
        parses = parses,
        spellings = spellings,
        choices = quoted.join(", "),
    )
}

/// `0..=3` → `(0, 3)`.
fn parse_range(range: &str, tag: &str, name: &str) -> (u32, u32) {
    let (low, high) = range
        .split_once("..=")
        .unwrap_or_else(|| panic!("`{tag}.{name}` range `{range}` is not `low..=high`"));
    let parse = |bound: &str| {
        bound
            .parse::<u32>()
            .unwrap_or_else(|_| panic!("`{tag}.{name}` range `{range}` is not `low..=high`"))
    };
    (parse(low), parse(high))
}

/// `"StopBits"`-style name for an attribute's generated enum.
fn camel_case(text: &str) -> String {
    let mut out = String::new();
    for part in text.split(|c: char| !c.is_ascii_alphanumeric()) {
        let mut chars = part.chars();
        if let Some(first) = chars.next() {
            out.extend(first.to_uppercase());
            out.push_str(&chars.as_str().to_lowercase());
        }
    }
    out
}

/// An enum variant for one `choices` spelling; `1` becomes `N1`, since a
/// variant cannot start with a digit.
fn variant_name(choice: &str) -> String {
    let name = camel_case(choice);
    if name.starts_with(|c: char| c.is_ascii_digit()) {
        format!("N{name}")
    } else {
        name
    }
}

/// A Rust field name for a schema attribute name (`network1.ssid` becomes
/// `network1_ssid`; keywords get a trailing `_`).
fn field_name(attr: &str) -> String {
    let name: String = attr
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect();
    if is_keyword(&name) {
        format!("{name}_")
    } else {
        name
    }
}

fn is_keyword(name: &str) -> bool {
    matches!(
        name,
        "as" | "break"
            | "const"
            | "continue"
            | "crate"
            | "dyn"
            | "else"
            | "enum"
            | "extern"
            | "false"
            | "fn"
            | "for"
            | "if"
            | "impl"
            | "in"
            | "let"
            | "loop"
            | "match"
            | "mod"
            | "move"
            | "mut"
            | "pub"
            | "ref"
            | "return"
            | "self"
            | "static"
            | "struct"
            | "super"
            | "trait"
            | "true"
            | "type"
            | "unsafe"
            | "use"
            | "where"
            | "while"
            | "async"
            | "await"
            | "try"
            | "union"
    )
}

/// Prefix every non-empty line of `text` with `spaces` spaces.
fn indent(text: &str, spaces: usize) -> String {
    let pad = " ".repeat(spaces);
    text.lines()
        .map(|line| {
            if line.is_empty() {
                String::from("\n")
            } else {
                format!("{pad}{line}\n")
            }
        })
        .collect()
}

fn first_positional(node: &kdl::KdlNode) -> Option<String> {
    node.entries()
        .iter()
        .find(|entry| entry.name().is_none())
        .and_then(|entry| entry.value().as_string())
        .map(|value| value.to_string())
}

fn prop_string(node: &kdl::KdlNode, key: &str) -> Option<String> {
    node.entries()
        .iter()
        .find(|entry| entry.name().is_some_and(|name| name.value() == key))
        .and_then(|entry| entry.value().as_string())
        .map(|value| value.to_string())
}

fn prop_bool(node: &kdl::KdlNode, key: &str) -> Option<bool> {
    node.entries()
        .iter()
        .find(|entry| entry.name().is_some_and(|name| name.value() == key))
        .and_then(|entry| entry.value().as_bool())
}

fn children<'a>(node: &'a kdl::KdlNode, name: &str) -> Vec<kdl::KdlNode> {
    node.children()
        .map(|doc| doc.nodes())
        .unwrap_or(&[])
        .iter()
        .filter(|child| child.name().value() == name)
        .cloned()
        .collect()
}

fn child_strings(node: &kdl::KdlNode, name: &str) -> Vec<String> {
    children(node, name)
        .iter()
        .flat_map(|child| {
            child
                .entries()
                .iter()
                .filter(|entry| entry.name().is_none())
        })
        .filter_map(|entry| entry.value().as_string().map(|value| value.to_string()))
        .collect()
}

/// Keep the checked-in file and the generated one identical, without touching
/// the file (and its mtime) when nothing changed.
fn write_if_changed(path: &Path, contents: &str) {
    let current = fs::read_to_string(path).unwrap_or_default();
    if current != contents {
        fs::write(path, contents)
            .unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display()));
    }
}