espforge-options 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
//! Transcribes `espf.schema.kdl` into checked-in Rust: both halves of the file.
//!
//! * `src/generated_options.rs` - the `required` list and the `option` nodes.
//! * `src/generated_catalog.rs` - the `section` and `element` nodes (the data
//!   behind `espforge espf`).
//!
//! This is a transcriber, not a validator: it copies what the file says and
//! deliberately has no rules of its own about what a valid schema is. The
//! loaders (`src/schema.rs`, `src/catalog.rs`) stay the single oracle, and one
//! test per file asserts the generated table equals what the loader parses from
//! `SCHEMA_KDL` — so anything this file gets wrong is a test failure, not a
//! silent divergence, and anything the schema gets wrong still fails there too.
//!
//! `#[rustfmt::skip]` on the generated functions keeps the checked-in files
//! byte-identical to what this build script writes; formatting long help and
//! example strings is not something a generator should try to predict.

use kdl::{KdlDocument, KdlNode};
use std::fs;
use std::path::Path;

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

fn main() {
    println!("cargo:rerun-if-changed={SCHEMA}");

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

    let mut required: Vec<String> = Vec::new();
    let mut options: Vec<String> = Vec::new();
    let mut sections: Vec<SectionDraft> = Vec::new();

    for node in doc.nodes() {
        match node.name().value() {
            "required" => required.extend(positional_strings(node)),
            "options" => {
                for child in node.children().map(|c| c.nodes()).unwrap_or(&[]) {
                    if child.name().value() == "option" {
                        options.push(option_literal(child));
                    }
                }
            }
            "section" => sections.push(section_draft(node)),
            "element" => {
                // An element belongs to the section its `section=` names, and
                // the loader orders it by its position in this file.
                let section = prop_string(node, "section").unwrap_or_default();
                let literal = element_literal(node);
                match sections.iter_mut().find(|s| s.name == section) {
                    Some(section) => section.leafs.push(literal),
                    // `load` reports this as an error, so the equality test
                    // fails; there is nothing sensible to emit.
                    None => {}
                }
            }
            // The option half is written above.
            _ => {}
        }
    }

    write_if_changed(
        Path::new("src/generated_options.rs"),
        &options_source(&required, &options),
    );
    write_if_changed(
        Path::new("src/generated_catalog.rs"),
        &catalog_source(&sections),
    );
}

// ------------------------------------------------------------------- options

fn options_source(required: &[String], options: &[String]) -> String {
    let required = if required.is_empty() {
        "Vec::new()".to_string()
    } else {
        string_vec(required)
    };

    format!(
        concat!(
            "// AUTO-GENERATED BY BUILD.RS FROM espf.schema.kdl - DO NOT EDIT MANUALLY\n",
            "\n",
            "//! The option half of `espf.schema.kdl` as Rust.\n",
            "//!\n",
            "//! `schema::embedded_schema` returns this table; a test asserts it equals\n",
            "//! what `schema::load` parses from the embedded text, so the loader stays\n",
            "//! the authority on what the schema means.\n",
            "\n",
            "use crate::schema::{{Compat, Kind, OptValue, OptionDef, Requires, Schema}};\n",
            "\n",
            "#[rustfmt::skip]\n",
            "pub(crate) fn schema() -> Schema {{\n",
            "    Schema {{\n",
            "        required: {required},\n",
            "        options: vec![\n",
            "{options}",
            "        ],\n",
            "    }}\n",
            "}}\n",
        ),
        required = required,
        options = options.join(""),
    )
}

/// One `OptionDef { .. },` line block for an `option` node.
fn option_literal(node: &kdl::KdlNode) -> String {
    let name = positional_strings(node).remove(0);

    let mut display_name = None;
    let mut selection_group = None;
    let mut kind_name = "bool".to_string();
    let mut nightly = false;
    let mut default = None;
    let mut requires: Vec<String> = Vec::new();
    let mut tools: Vec<String> = Vec::new();
    let mut chips: Option<Vec<String>> = None;
    let mut choices: Vec<String> = Vec::new();
    let mut help = None;

    for entry in node.entries().iter().filter(|e| e.name().is_some()) {
        match entry.name().map(|k| k.value()).unwrap_or("") {
            "display_name" => display_name = entry.value().as_string().map(str::to_string),
            "selection_group" => selection_group = entry.value().as_string().map(str::to_string),
            "kind" => {
                if let Some(kind) = entry.value().as_string() {
                    kind_name = kind.to_string();
                }
            }
            "requires_nightly" => nightly = entry.value().as_bool().unwrap_or(false),
            "default" => {
                default = match entry.value().as_bool() {
                    Some(value) => Some(format!("Some(OptValue::Bool({value}))")),
                    None => entry
                        .value()
                        .as_string()
                        .map(|value| format!("Some(OptValue::Str({value:?}.to_string()))")),
                }
            }
            _ => {}
        }
    }

    for child in node.children().map(|c| c.nodes()).unwrap_or(&[]) {
        match child.name().value() {
            "help" => help = positional_strings(child).into_iter().next(),
            "requires" => requires.extend(positional_strings(child)),
            "requires_tools" => tools.extend(positional_strings(child)),
            "choices" => choices.extend(positional_strings(child)),
            "compatible" => {
                chips = Some(
                    child
                        .children()
                        .map(|c| c.nodes())
                        .unwrap_or(&[])
                        .iter()
                        .filter(|c| c.name().value() == "chip")
                        .flat_map(positional_strings)
                        .collect(),
                )
            }
            _ => {}
        }
    }

    let kind = match kind_name.as_str() {
        "string" => "Kind::String".to_string(),
        "list" => "Kind::List".to_string(),
        "choice" => format!("Kind::Choice({})", string_vec(&choices)),
        _ => "Kind::Bool".to_string(),
    };
    // A bool option is off unless the schema says otherwise, and the loader
    // records that as an explicit `Some(Bool(false))`.
    if kind_name == "bool" && default.is_none() {
        default = Some("Some(OptValue::Bool(false))".to_string());
    }

    let span = node_span(node);

    format!(
        "            OptionDef {{\n\
         \x20               name: {name:?}.to_string(),\n\
         \x20               display_name: {display_name},\n\
         \x20               help: {help},\n\
         \x20               kind: {kind},\n\
         \x20               default: {default},\n\
         \x20               requires: Requires {{\n\
         \x20                   options: {requires},\n\
         \x20                   tools: {tools},\n\
         \x20                   nightly: {nightly},\n\
         \x20               }},\n\
         \x20               compat: Compat {{ chips: {chips} }},\n\
         \x20               selection_group: {selection_group},\n\
         \x20               span: {span},\n\
         \x20           }},\n",
        display_name = opt_string(display_name),
        help = opt_string(help),
        default = default.unwrap_or_else(|| "None".to_string()),
        requires = string_vec(&requires),
        tools = string_vec(&tools),
        chips = match chips {
            Some(chips) => format!("Some({})", string_vec(&chips)),
            None => "None".to_string(),
        },
        selection_group = opt_string(selection_group),
    )
}

// ------------------------------------------------------------------- catalog

/// One `section` node while its elements are being collected.
struct SectionDraft {
    name: String,
    summary: String,
    description: String,
    /// One `ElementDef { .. },` block each, in schema order.
    leafs: Vec<String>,
}

fn section_draft(node: &KdlNode) -> SectionDraft {
    let mut summary = String::new();
    let mut description = String::new();
    for child in node.children().map(|c| c.nodes()).unwrap_or(&[]) {
        let value = positional_strings(child).into_iter().next().unwrap_or_default();
        match child.name().value() {
            // The loader keeps the first of each and reports repeats.
            "summary" if summary.is_empty() => summary = value,
            "description" if description.is_empty() => description = value,
            _ => {}
        }
    }
    SectionDraft {
        name: positional_strings(node).into_iter().next().unwrap_or_default(),
        summary,
        description,
        leafs: Vec::new(),
    }
}

fn catalog_source(sections: &[SectionDraft]) -> String {
    let mut out = String::from(concat!(
        "// AUTO-GENERATED BY BUILD.RS FROM espf.schema.kdl - DO NOT EDIT MANUALLY\n",
        "\n",
        "//! The element half of `espf.schema.kdl` as Rust: the sections, elements,\n",
        "//! attributes and examples behind `espforge espf`.\n",
        "//!\n",
        "//! `catalog::embedded` returns this table; a test asserts it equals what\n",
        "//! `catalog::load` parses from the embedded text, so the loader stays the\n",
        "//! authority on what the schema means.\n",
        "\n",
        "use crate::catalog::{AttrDef, AttrKind, Catalog, ElementDef, Example, SectionDef, Status};\n",
        "use crate::schema::Compat;\n",
        "\n",
        "#[rustfmt::skip]\n",
        "pub(crate) fn catalog() -> Catalog {\n",
        "    Catalog {\n",
        "        sections: vec![\n",
    ));
    for section in sections {
        out.push_str(&format!(
            "            SectionDef {{\n\
             \x20               name: {name:?}.to_string(),\n\
             \x20               summary: {summary:?}.to_string(),\n\
             \x20               description: {description:?}.to_string(),\n\
             \x20               leafs: vec![\n\
             {leafs}\
             \x20               ],\n\
             \x20           }},\n",
            name = section.name,
            summary = section.summary,
            description = section.description,
            leafs = section.leafs.join(""),
        ));
    }
    out.push_str(concat!(
        "        ],\n",
        "        overview: espforge_espgenerate_template::OVERVIEW_TXT,\n",
        "    }\n",
        "}\n",
    ));
    out
}

/// One `ElementDef { .. },` block for an `element` node.
fn element_literal(node: &KdlNode) -> String {
    let mut summary = String::new();
    let mut description: Option<String> = None;
    let mut attrs: Vec<String> = Vec::new();
    let mut examples: Vec<String> = Vec::new();
    let mut see_also: Vec<String> = Vec::new();
    let mut chips: Option<Vec<String>> = None;

    for child in node.children().map(|c| c.nodes()).unwrap_or(&[]) {
        match child.name().value() {
            // The loader keeps the first and reports the second.
            "summary" if summary.is_empty() => {
                summary = positional_strings(child).into_iter().next().unwrap_or_default()
            }
            "description" if description.is_none() => {
                description = positional_strings(child).into_iter().next()
            }
            "attr" => attrs.push(attr_literal(child)),
            "example" => {
                let strings = positional_strings(child);
                if strings.len() == 2 {
                    examples.push(format!(
                        "                        Example {{\n\
                         \x20                           title: {:?}.to_string(),\n\
                         \x20                           fragment: {:?}.to_string(),\n\
                         \x20                       }},\n",
                        strings[0], strings[1]
                    ));
                }
                // Anything else is a loader error; the equality test fails.
            }
            "see_also" => see_also.extend(positional_strings(child)),
            "compatible" => {
                chips = Some(
                    child
                        .children()
                        .map(|c| c.nodes())
                        .unwrap_or(&[])
                        .iter()
                        .filter(|c| c.name().value() == "chip")
                        .flat_map(positional_strings)
                        .collect(),
                )
            }
            _ => {}
        }
    }

    let status = match prop_string(node, "status").as_deref() {
        Some("planned") => "Status::Planned",
        // `implemented` is the default, and the loader reports anything else.
        _ => "Status::Implemented",
    };

    format!(
        "                    ElementDef {{\n\
         \x20                       tag: {tag:?}.to_string(),\n\
         \x20                       section: {section:?}.to_string(),\n\
         \x20                       summary: {summary:?}.to_string(),\n\
         \x20                       description: {description},\n\
         \x20                       status: {status},\n\
         \x20                       attrs: vec![\n\
         {attrs}\
         \x20                       ],\n\
         \x20                       examples: vec![\n\
         {examples}\
         \x20                       ],\n\
         \x20                       see_also: {see_also},\n\
         \x20                       compat: Compat {{ chips: {chips} }},\n\
         \x20                       span: {span},\n\
         \x20                   }},\n",
        tag = positional_strings(node).into_iter().next().unwrap_or_default(),
        section = prop_string(node, "section").unwrap_or_default(),
        description = match description {
            Some(text) => format!("Some({text:?}.to_string())"),
            None => "None".to_string(),
        },
        attrs = attrs.join(""),
        examples = examples.join(""),
        see_also = string_vec(&see_also),
        chips = match chips {
            Some(chips) => format!("Some({})", string_vec(&chips)),
            None => "None".to_string(),
        },
        span = node_span(node),
    )
}

/// One `AttrDef { .. },` block for an `attr` node.
fn attr_literal(node: &KdlNode) -> String {
    let name = positional_strings(node).into_iter().next().unwrap_or_default();
    // The loader keeps the last `required=`, and repeats are an error anyway.
    let mut required = false;
    for entry in node
        .entries()
        .iter()
        .filter(|e| e.name().is_some_and(|n| n.value() == "required"))
    {
        if let Some(value) = entry.value().as_bool() {
            required = value;
        }
    }
    let choices: Vec<String> = node
        .children()
        .map(|c| c.nodes())
        .unwrap_or(&[])
        .iter()
        .filter(|c| c.name().value() == "choices")
        .flat_map(positional_strings)
        .collect();
    let help = node
        .children()
        .map(|c| c.nodes())
        .unwrap_or(&[])
        .iter()
        .find(|c| c.name().value() == "help")
        .and_then(|c| positional_strings(c).into_iter().next());

    let kind_name = prop_string(node, "kind").unwrap_or_default();
    let to: Vec<String> = props(node, "to");
    let of = prop_string(node, "of");
    let kind = kind_literal(&name, &kind_name, &choices, &to, of.as_deref());

    format!(
        "                            AttrDef {{\n\
         \x20                               name: {name:?}.to_string(),\n\
         \x20                               kind: {kind},\n\
         \x20                               required: {required},\n\
         \x20                               default: {default},\n\
         \x20                               help: {help},\n\
         \x20                               span: {span},\n\
         \x20                           }},\n",
        default = match prop_string(node, "default") {
            Some(text) => format!("Some({text:?}.to_string())"),
            None => "None".to_string(),
        },
        help = match help {
            Some(text) => format!("Some({text:?}.to_string())"),
            None => "None".to_string(),
        },
        span = node_span(node),
    )
}

/// The `AttrKind` a declared `kind=` (plus `choices`/`to`/`of`) means, exactly
/// as `catalog::load` reads it. A shape the loader rejects falls back to the
/// kind `load` itself would fall back to; the equality test then fails on the
/// loader's error rather than on this file.
fn kind_literal(
    _name: &str,
    kind_name: &str,
    choices: &[String],
    to: &[String],
    of: Option<&str>,
) -> String {
    match kind_name {
        "ident" => "AttrKind::Ident".to_string(),
        "str" => "AttrKind::Str".to_string(),
        "pin" => "AttrKind::Pin".to_string(),
        "freq" => "AttrKind::Freq".to_string(),
        "hex" => "AttrKind::Hex".to_string(),
        "u32" => "AttrKind::U32".to_string(),
        "bool" => "AttrKind::Bool".to_string(),
        "choice" => format!("AttrKind::Choice({})", string_vec(choices)),
        "ref" => format!("AttrKind::Ref {{ to: {} }}", string_vec(to)),
        "pin_or_ref" => "AttrKind::PinOrRef".to_string(),
        "list" => {
            let inner = match of {
                Some("ident") => "AttrKind::Ident",
                Some("str") => "AttrKind::Str",
                Some("pin") => "AttrKind::Pin",
                Some("freq") => "AttrKind::Freq",
                Some("hex") => "AttrKind::Hex",
                Some("u32") => "AttrKind::U32",
                Some("bool") => "AttrKind::Bool",
                // `load` reports the missing/unknown `of=` and falls back to str.
                _ => "AttrKind::Str",
            };
            format!("AttrKind::List(Box::new({inner}))")
        }
        // `load` reports the unknown kind and falls back to str.
        _ => "AttrKind::Str".to_string(),
    }
}

/// `offset..offset+len`, the same byte span `catalog::load` records.
fn node_span(node: &KdlNode) -> String {
    let span = node.span();
    format!("{}..{}", span.offset(), span.offset() + span.len())
}

/// The first `key="value"` property of a node.
fn prop_string(node: &KdlNode, key: &str) -> Option<String> {
    props(node, key).into_iter().next()
}

/// Every `key="value"` property of a node, in document order.
fn props(node: &KdlNode, key: &str) -> Vec<String> {
    node.entries()
        .iter()
        .filter(|entry| entry.name().is_some_and(|n| n.value() == key))
        .filter_map(|entry| entry.value().as_string().map(str::to_string))
        .collect()
}

// ------------------------------------------------------------------- shared

/// `Some("text".to_string())` or `None`.
fn opt_string(value: Option<String>) -> String {
    match value {
        Some(text) => format!("Some({text:?}.to_string())"),
        None => "None".to_string(),
    }
}

/// `vec!["a".to_string(), ..]` or `Vec::new()`.
fn string_vec(values: &[String]) -> String {
    if values.is_empty() {
        return "Vec::new()".to_string();
    }
    format!(
        "vec![{}]",
        values
            .iter()
            .map(|value| format!("{value:?}.to_string()"))
            .collect::<Vec<_>>()
            .join(", ")
    )
}

fn positional_strings(node: &kdl::KdlNode) -> Vec<String> {
    node.entries()
        .iter()
        .filter(|entry| entry.name().is_none())
        .filter_map(|entry| entry.value().as_string().map(str::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()));
    }
}