macro-schema-core 0.1.3

The implementation of macro-schema over proc_macro2, testable without the compiler's macro expander.
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! The `generate { ... }` template language.
//!
//! A template is ordinary Rust tokens plus five structural constructs, all introduced
//! by `$`:
//!
//! - `$decl.value`, `$member.field`: substitute a resolved value. Every declaration
//!   value is reached through `$decl`; every member value through its loop variable.
//! - `$for member in $decl.members { ... }`: repeat once per member.
//! - `$if let Some(x) = $decl.optional { ... } else { ... }`: branch on an optional field.
//! - `$ident(...)`, `$snake(...)`, `$upper(...)`: build an identifier.
//! - `$const_arg(...)`: write a const generic argument, braced only when it must be.
//!
//! `$crate` passes through unchanged. Templates are parsed and type-checked against the
//! schema when `define!` runs, so a typo in a template is reported at the library's
//! `generate` block, not at some later caller.

use std::iter::Peekable;

use proc_macro2::{
    Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree, token_stream,
};
use syn::{Error, Result};

use crate::schema::{BodySpec, Shape};

/// The sigil `define!` sees. Embedded in the generated `macro_rules!` wrapper, the
/// template's own `$` would read as `macro_rules!` variables, so the wrapper carries
/// `#` instead; `$crate` stays `$crate`, which `macro_rules!` resolves for us.
pub(crate) const AUTHOR_SIGIL: char = '$';
pub(crate) const EMBEDDED_SIGIL: char = '#';

type Tokens = Peekable<token_stream::IntoIter>;

/// Re-marks template constructs from `$` to `#` for embedding in the wrapper.
pub(crate) fn embed(tokens: TokenStream) -> TokenStream {
    let mut output = Vec::new();
    let mut tokens = tokens.into_iter().peekable();
    while let Some(token) = tokens.next() {
        match token {
            TokenTree::Punct(punct)
                if punct.as_char() == AUTHOR_SIGIL
                    && matches!(tokens.peek(), Some(TokenTree::Ident(ident)) if ident != "crate") =>
            {
                let mut sigil = Punct::new(EMBEDDED_SIGIL, Spacing::Alone);
                sigil.set_span(punct.span());
                output.push(TokenTree::Punct(sigil));
            }
            TokenTree::Group(group) => {
                let mut new_group = Group::new(group.delimiter(), embed(group.stream()));
                new_group.set_span(group.span());
                output.push(TokenTree::Group(new_group));
            }
            other => output.push(other),
        }
    }
    output.into_iter().collect()
}

pub(crate) struct Template {
    nodes: Vec<Node>,
}

enum Node {
    Token(TokenTree),
    Group(Delimiter, Span, Vec<Node>),
    Value(Path),
    For {
        var: String,
        path: Path,
        body: Vec<Node>,
    },
    IfLet {
        var: String,
        path: Path,
        then: Vec<Node>,
        otherwise: Vec<Node>,
    },
    Ident {
        case: Case,
        span: Span,
        parts: Vec<Part>,
    },
    ConstArg {
        span: Span,
        inner: Vec<Node>,
    },
}

#[derive(Clone, Copy)]
enum Case {
    Exact,
    Snake,
    Upper,
}

enum Part {
    Text(String),
    Value(Path),
}

/// `$root.field.field`, resolved against the schema while parsing.
struct Path {
    root: Ident,
    fields: Vec<Ident>,
}

/// What a template expression refers to.
#[derive(Clone, Copy)]
enum Ty<'a> {
    /// A substitutable value; `ident_like` if it is always one identifier (or an index).
    Leaf {
        ident_like: bool,
    },
    Optional(&'a Shape),
    /// `$decl`: the declaration's built-ins, its fields, and `members`.
    Decl(&'a BodySpec),
    Block(&'a BodySpec),
    /// A loop variable: the member's built-ins and its fields.
    Member(&'a BodySpec),
    Members,
}

/// Built-in values of a namespace, which its schema fields may not shadow.
const DECL_BUILTINS: [&str; 5] = ["name", "vis", "doc", "attrs", "members"];
const MEMBER_BUILTINS: [&str; 5] = ["name", "vis", "doc", "attrs", "index"];

/// Names a loop or `$if let` variable may not take. (`$ident(...)` and its kin are
/// constructs only when called, so `ident` remains a usable variable name.)
const NOT_VARIABLES: [&str; 2] = ["decl", "crate"];

impl Ty<'_> {
    fn builtins(self) -> &'static [&'static str] {
        match self {
            Ty::Decl(_) => &DECL_BUILTINS,
            Ty::Member(_) => &MEMBER_BUILTINS,
            _ => &[],
        }
    }
}

struct Scope<'a> {
    name: String,
    ty: Ty<'a>,
}

struct Parser<'a> {
    sigil: char,
    body: &'a BodySpec,
    scopes: Vec<Scope<'a>>,
}

impl Template {
    pub(crate) fn parse(tokens: TokenStream, body: &BodySpec, sigil: char) -> Result<Self> {
        let member_fields = body
            .members
            .iter()
            .flat_map(|members| members.body.fields.iter().map(|field| (field, "member")));
        for (field, namespace) in body
            .fields
            .iter()
            .map(|field| (field, "decl"))
            .chain(member_fields)
        {
            let word = field.name.to_string();
            let builtins: &[&str] = if namespace == "decl" {
                &DECL_BUILTINS
            } else {
                &MEMBER_BUILTINS
            };
            if builtins.contains(&word.as_str()) {
                return Err(Error::new(
                    field.name.span(),
                    format!(
                        "field `{word}` collides with the template's built-in `${namespace}.{word}`; rename the field"
                    ),
                ));
            }
        }
        let mut parser = Parser {
            sigil,
            body,
            scopes: Vec::new(),
        };
        let nodes = parser.nodes(tokens)?;
        Ok(Self { nodes })
    }

    pub(crate) fn render(&self, data: &Data) -> TokenStream {
        let mut env: Vec<(String, &Data)> = Vec::new();
        let mut output = TokenStream::new();
        render_nodes(&self.nodes, data, &mut env, &mut output);
        output
    }
}

impl<'a> Parser<'a> {
    fn nodes(&mut self, tokens: TokenStream) -> Result<Vec<Node>> {
        let mut nodes = Vec::new();
        let mut tokens = tokens.into_iter().peekable();
        while let Some(token) = tokens.next() {
            match token {
                TokenTree::Punct(punct)
                    if punct.as_char() == self.sigil
                        && matches!(tokens.peek(), Some(TokenTree::Ident(ident)) if ident != "crate") =>
                {
                    let keyword = expect_ident(&mut tokens, punct.span(), "a template construct")?;
                    nodes.push(self.construct(punct.span(), keyword, &mut tokens)?);
                }
                TokenTree::Punct(punct)
                    if punct.as_char() == AUTHOR_SIGIL && self.sigil == AUTHOR_SIGIL =>
                {
                    let is_crate =
                        matches!(tokens.peek(), Some(TokenTree::Ident(ident)) if ident == "crate");
                    if !is_crate {
                        return Err(Error::new(
                            punct.span(),
                            "`$` must start a template construct (`$value`, `$for`, `$if`, `$ident(...)`, `$const_arg(...)`) or `$crate`",
                        ));
                    }
                    nodes.push(Node::Token(TokenTree::Punct(punct)));
                }
                TokenTree::Group(group) => {
                    let inner = self.nodes(group.stream())?;
                    nodes.push(Node::Group(group.delimiter(), group.span(), inner));
                }
                other => nodes.push(Node::Token(other)),
            }
        }
        Ok(nodes)
    }

    fn construct(&mut self, sigil_span: Span, keyword: Ident, tokens: &mut Tokens) -> Result<Node> {
        let word = keyword.to_string();
        let is_call = matches!(
            tokens.peek(),
            Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Parenthesis
        );
        match word.as_str() {
            "for" => self.for_node(&keyword, tokens),
            "if" => self.if_node(&keyword, tokens),
            "const_arg" if is_call => {
                let args = expect_group(tokens, keyword.span(), Delimiter::Parenthesis, "`(...)`")?;
                Ok(Node::ConstArg {
                    span: args.span(),
                    inner: self.nodes(args.stream())?,
                })
            }
            "ident" | "snake" | "upper" if is_call => {
                let args = expect_group(tokens, keyword.span(), Delimiter::Parenthesis, "`(...)`")?;
                let case = match word.as_str() {
                    "ident" => Case::Exact,
                    "snake" => Case::Snake,
                    _ => Case::Upper,
                };
                Ok(Node::Ident {
                    case,
                    span: sigil_span,
                    parts: self.parts(args.stream(), args.span())?,
                })
            }
            _ => {
                let (path, ty) = self.path(keyword, tokens)?;
                match ty {
                    Ty::Leaf { .. } => Ok(Node::Value(path)),
                    Ty::Optional(_) => Err(path_error(
                        &path,
                        "is optional; read it with `$if let Some(x) = ... { ... }`",
                    )),
                    Ty::Members => Err(path_error(
                        &path,
                        "is the member list; loop over it with `$for member in $decl.members { ... }`",
                    )),
                    Ty::Decl(body) => Err(path_error(
                        &path,
                        &format!(
                            "is the declaration, not a value; name one of {}",
                            field_list(ty.builtins(), body)
                        ),
                    )),
                    Ty::Block(_) | Ty::Member(_) => Err(path_error(
                        &path,
                        "is a block, not a value; name one of its fields",
                    )),
                }
            }
        }
    }

    /// `$for VAR in $decl.members { BODY }`.
    fn for_node(&mut self, keyword: &Ident, tokens: &mut Tokens) -> Result<Node> {
        let var = expect_ident(tokens, keyword.span(), "a loop variable after `$for`")?;
        expect_word(tokens, var.span(), "in")?;
        expect_sigil(tokens, self.sigil, var.span())?;
        let root = expect_ident(tokens, var.span(), "`$decl.members` after `in`")?;
        let (path, ty) = self.path(root, tokens)?;
        let (Ty::Members, Some(members)) = (ty, &self.body.members) else {
            return Err(path_error(
                &path,
                "is not the member list; loop over `$decl.members`",
            ));
        };
        let body = expect_group(tokens, var.span(), Delimiter::Brace, "`{ ... }`")?;
        self.check_new_name(&var)?;
        self.scopes.push(Scope {
            name: var.to_string(),
            ty: Ty::Member(&members.body),
        });
        let body = self.nodes(body.stream());
        self.scopes.pop();
        Ok(Node::For {
            var: var.to_string(),
            path,
            body: body?,
        })
    }

    /// `$if let Some(VAR) = $path { THEN } [else { OTHERWISE }]`.
    fn if_node(&mut self, keyword: &Ident, tokens: &mut Tokens) -> Result<Node> {
        expect_word(tokens, keyword.span(), "let")?;
        expect_word(tokens, keyword.span(), "Some")?;
        let binding = expect_group(tokens, keyword.span(), Delimiter::Parenthesis, "`Some(x)`")?;
        let var: Ident = syn::parse2(binding.stream())
            .map_err(|_| Error::new(binding.span(), "expected one variable name in `Some(...)`"))?;
        match tokens.next() {
            Some(TokenTree::Punct(punct)) if punct.as_char() == '=' => {}
            _ => return Err(Error::new(var.span(), "expected `=` after `Some(...)`")),
        }
        expect_sigil(tokens, self.sigil, var.span())?;
        let root = expect_ident(tokens, var.span(), "an optional value after `=`")?;
        let (path, ty) = self.path(root, tokens)?;
        let Ty::Optional(shape) = ty else {
            return Err(path_error(
                &path,
                "is not optional; `$if let` needs an optional field",
            ));
        };
        let then_tokens = expect_group(tokens, var.span(), Delimiter::Brace, "`{ ... }`")?;
        let otherwise_tokens = if matches!(tokens.peek(), Some(TokenTree::Ident(ident)) if ident == "else")
        {
            tokens.next();
            Some(expect_group(
                tokens,
                var.span(),
                Delimiter::Brace,
                "`{ ... }` after `else`",
            )?)
        } else {
            None
        };
        self.check_new_name(&var)?;
        self.scopes.push(Scope {
            name: var.to_string(),
            ty: shape_ty(false, shape),
        });
        let then = self.nodes(then_tokens.stream());
        self.scopes.pop();
        let otherwise = match otherwise_tokens {
            Some(group) => self.nodes(group.stream())?,
            None => Vec::new(),
        };
        Ok(Node::IfLet {
            var: var.to_string(),
            path,
            then: then?,
            otherwise,
        })
    }

    /// Comma-separated identifier parts: identifiers, integers, or `$` values.
    fn parts(&mut self, tokens: TokenStream, span: Span) -> Result<Vec<Part>> {
        let mut parts = Vec::new();
        let mut tokens = tokens.into_iter().peekable();
        while let Some(token) = tokens.next() {
            match token {
                TokenTree::Punct(punct) if punct.as_char() == self.sigil => {
                    let root = expect_ident(&mut tokens, punct.span(), "a value after `$`")?;
                    let (path, ty) = self.path(root, &mut tokens)?;
                    let Ty::Leaf { ident_like: true } = ty else {
                        return Err(path_error(
                            &path,
                            "is not an identifier; identifier parts must be `ident` fields, `$decl.name`, `$member.name`, or `$member.index`",
                        ));
                    };
                    parts.push(Part::Value(path));
                }
                TokenTree::Ident(ident) => parts.push(Part::Text(ident.to_string())),
                TokenTree::Literal(literal)
                    if literal
                        .to_string()
                        .bytes()
                        .all(|byte| byte.is_ascii_digit()) =>
                {
                    parts.push(Part::Text(literal.to_string()));
                }
                other => {
                    return Err(Error::new(
                        other.span(),
                        "identifier parts must be identifiers, integers, or `$` values",
                    ));
                }
            }
            match tokens.next() {
                None => break,
                Some(TokenTree::Punct(punct)) if punct.as_char() == ',' => {}
                Some(other) => {
                    return Err(Error::new(
                        other.span(),
                        "expected `,` between identifier parts",
                    ));
                }
            }
        }
        if parts.is_empty() {
            return Err(Error::new(span, "an identifier needs at least one part"));
        }
        Ok(parts)
    }

    /// Resolves `ROOT{.field}`, consuming `.field` only while the current value has fields,
    /// so `$panel.led_layout.width()` stops before `.width()`.
    fn path(&self, root: Ident, tokens: &mut Tokens) -> Result<(Path, Ty<'a>)> {
        let mut ty = self.root_ty(&root)?;
        let mut fields = Vec::new();
        while let Ty::Decl(body) | Ty::Block(body) | Ty::Member(body) = ty {
            let mut lookahead = tokens.clone();
            let (Some(TokenTree::Punct(dot)), Some(TokenTree::Ident(field))) =
                (lookahead.next(), lookahead.next())
            else {
                break;
            };
            if dot.as_char() != '.' {
                break;
            }
            tokens.next();
            tokens.next();
            let word = field.to_string();
            ty = match word.as_str() {
                builtin if !ty.builtins().contains(&builtin) => match body.field(&field) {
                    Some(spec) => shape_ty(spec.optional, &spec.shape),
                    None => {
                        return Err(Error::new(
                            field.span(),
                            format!(
                                "no value `{field}` here; expected one of {}",
                                field_list(ty.builtins(), body)
                            ),
                        ));
                    }
                },
                "name" | "index" => Ty::Leaf { ident_like: true },
                "members" => Ty::Members,
                _ => Ty::Leaf { ident_like: false },
            };
            fields.push(field);
        }
        Ok((Path { root, fields }, ty))
    }

    /// A path starts at `$decl` or at a `$for` / `$if let` variable in scope.
    fn root_ty(&self, root: &Ident) -> Result<Ty<'a>> {
        let word = root.to_string();
        if let Some(scope) = self.scopes.iter().rev().find(|scope| scope.name == word) {
            return Ok(scope.ty);
        }
        if word == "decl" {
            return Ok(Ty::Decl(self.body));
        }
        let decl = Ty::Decl(self.body);
        let hint = if decl.builtins().contains(&word.as_str()) || self.body.field(root).is_some() {
            format!("write `$decl.{word}`")
        } else {
            let mut names = vec!["`$decl`".to_owned()];
            names.extend(self.scopes.iter().map(|scope| format!("`${}`", scope.name)));
            format!("expected {}", names.join(", "))
        };
        Err(Error::new(
            root.span(),
            format!("unknown template value `${word}`; {hint}"),
        ))
    }

    fn check_new_name(&self, var: &Ident) -> Result<()> {
        let word = var.to_string();
        if NOT_VARIABLES.contains(&word.as_str()) {
            return Err(Error::new(
                var.span(),
                format!("`{word}` is reserved in templates; choose another variable name"),
            ));
        }
        if self.scopes.iter().any(|scope| scope.name == word) {
            return Err(Error::new(
                var.span(),
                format!("`${word}` is already in scope; choose another variable name"),
            ));
        }
        Ok(())
    }
}

fn shape_ty(optional: bool, shape: &Shape) -> Ty<'_> {
    match (optional, shape) {
        (true, shape) => Ty::Optional(shape),
        (false, Shape::Leaf { kind, .. }) => Ty::Leaf {
            ident_like: kind.name() == "ident",
        },
        (false, Shape::Block(block)) => Ty::Block(block),
    }
}

fn field_list(builtins: &[&str], body: &BodySpec) -> String {
    builtins
        .iter()
        .filter(|&&name| name != "members" || body.members.is_some())
        .map(|name| format!("`{name}`"))
        .chain(body.fields.iter().map(|field| format!("`{}`", field.name)))
        .collect::<Vec<_>>()
        .join(", ")
}

fn path_error(path: &Path, message: &str) -> Error {
    let text = std::iter::once(path.root.to_string())
        .chain(path.fields.iter().map(Ident::to_string))
        .collect::<Vec<_>>()
        .join(".");
    let span = path.fields.last().unwrap_or(&path.root).span();
    Error::new(span, format!("`${text}` {message}"))
}

fn expect_ident(tokens: &mut Tokens, after: Span, what: &str) -> Result<Ident> {
    match tokens.next() {
        Some(TokenTree::Ident(ident)) => Ok(ident),
        Some(other) => Err(Error::new(other.span(), format!("expected {what}"))),
        None => Err(Error::new(after, format!("expected {what}"))),
    }
}

fn expect_word(tokens: &mut Tokens, after: Span, word: &str) -> Result<()> {
    match tokens.next() {
        Some(TokenTree::Ident(ident)) if ident == word => Ok(()),
        Some(other) => Err(Error::new(other.span(), format!("expected `{word}`"))),
        None => Err(Error::new(after, format!("expected `{word}`"))),
    }
}

fn expect_sigil(tokens: &mut Tokens, sigil: char, after: Span) -> Result<()> {
    match tokens.next() {
        Some(TokenTree::Punct(punct)) if punct.as_char() == sigil => Ok(()),
        Some(other) => Err(Error::new(other.span(), "expected a `$` value")),
        None => Err(Error::new(after, "expected a `$` value")),
    }
}

fn expect_group(
    tokens: &mut Tokens,
    after: Span,
    delimiter: Delimiter,
    what: &str,
) -> Result<Group> {
    match tokens.next() {
        Some(TokenTree::Group(group)) if group.delimiter() == delimiter => Ok(group),
        Some(other) => Err(Error::new(other.span(), format!("expected {what}"))),
        None => Err(Error::new(after, format!("expected {what}"))),
    }
}

/// Resolved values a template renders from.
pub(crate) enum Data {
    Leaf(TokenStream),
    Absent,
    /// A declaration, member, or block: its named values.
    Fields(Vec<(String, Data)>),
    Members(Vec<Data>),
}

impl Data {
    /// Templates are type-checked against the same schema the data comes from, so a
    /// missing name means no output rather than an error.
    fn get(&self, name: &str) -> Option<&Data> {
        match self {
            Data::Fields(fields) => fields
                .iter()
                .find(|(field, _)| field == name)
                .map(|(_, data)| data),
            _ => None,
        }
    }
}

fn lookup<'d>(root: &'d Data, env: &[(String, &'d Data)], path: &Path) -> Option<&'d Data> {
    let name = path.root.to_string();
    let mut data = match env.iter().rev().find(|(scope, _)| *scope == name) {
        Some((_, data)) => *data,
        None => root,
    };
    for field in &path.fields {
        data = data.get(&field.to_string())?;
    }
    Some(data)
}

/// A const generic argument: one literal or one identifier stays bare, anything else is
/// braced. Rust requires the braces only for other expressions, and rustdoc prints a
/// braced argument as its source text, which for generated code is the template.
fn const_arg(tokens: TokenStream, span: Span) -> TokenStream {
    let mut trees = tokens.clone().into_iter();
    match (trees.next(), trees.next()) {
        (Some(TokenTree::Literal(_) | TokenTree::Ident(_)), None) => tokens,
        _ => {
            let mut group = Group::new(Delimiter::Brace, tokens);
            group.set_span(span);
            TokenTree::Group(group).into()
        }
    }
}

fn render_nodes<'d>(
    nodes: &[Node],
    root: &'d Data,
    env: &mut Vec<(String, &'d Data)>,
    output: &mut TokenStream,
) {
    for node in nodes {
        match node {
            Node::Token(token) => output.extend([token.clone()]),
            Node::Group(delimiter, span, inner) => {
                let mut stream = TokenStream::new();
                render_nodes(inner, root, env, &mut stream);
                let mut group = Group::new(*delimiter, stream);
                group.set_span(*span);
                output.extend([TokenTree::Group(group)]);
            }
            Node::Value(path) => {
                if let Some(Data::Leaf(tokens)) = lookup(root, env, path) {
                    output.extend(tokens.clone());
                }
            }
            Node::For { var, path, body } => {
                if let Some(Data::Members(members)) = lookup(root, env, path) {
                    for member in members {
                        env.push((var.clone(), member));
                        render_nodes(body, root, env, output);
                        env.pop();
                    }
                }
            }
            Node::IfLet {
                var,
                path,
                then,
                otherwise,
            } => match lookup(root, env, path) {
                Some(Data::Absent) | None => render_nodes(otherwise, root, env, output),
                Some(data) => {
                    env.push((var.clone(), data));
                    render_nodes(then, root, env, output);
                    env.pop();
                }
            },
            Node::ConstArg { span, inner } => {
                let mut stream = TokenStream::new();
                render_nodes(inner, root, env, &mut stream);
                output.extend(const_arg(stream, *span));
            }
            Node::Ident { case, span, parts } => {
                let mut text = String::new();
                let mut ident_span = None;
                for part in parts {
                    match part {
                        Part::Text(part_text) => text.push_str(part_text),
                        Part::Value(path) => {
                            if let Some(Data::Leaf(tokens)) = lookup(root, env, path) {
                                for token in tokens.clone() {
                                    ident_span.get_or_insert(token.span());
                                    text.push_str(&token.to_string());
                                }
                            }
                        }
                    }
                }
                let text = match case {
                    Case::Exact => text,
                    Case::Snake => to_snake_case(&text),
                    Case::Upper => to_snake_case(&text).to_uppercase(),
                };
                output.extend([TokenTree::Ident(Ident::new(
                    &text,
                    ident_span.unwrap_or(*span),
                ))]);
            }
        }
    }
}

/// `Gpio0LedStrip_pin` → `gpio0_led_strip_pin`; `PIO0_BUS` → `pio0_bus`. An underscore
/// starts a word before an uppercase letter that follows a lowercase letter, or digits
/// that follow a lowercase letter, and before the last capital of an acronym
/// (`HTTPServer` → `http_server`). All-caps text keeps its words (`LED2D` → `led2d`).
pub(crate) fn to_snake_case(text: &str) -> String {
    let chars: Vec<char> = text.chars().collect();
    let mut output = String::new();
    for (index, &character) in chars.iter().enumerate() {
        if character.is_uppercase() && index > 0 {
            let previous = chars[index - 1];
            let next_is_lower = chars.get(index + 1).is_some_and(|next| next.is_lowercase());
            let after_lowercase_digits = previous.is_ascii_digit()
                && chars[..index]
                    .iter()
                    .rev()
                    .find(|earlier| !earlier.is_ascii_digit())
                    .is_some_and(|earlier| earlier.is_lowercase());
            let starts_word = previous.is_lowercase()
                || after_lowercase_digits
                || (previous.is_uppercase() && next_is_lower);
            if starts_word && !output.ends_with('_') {
                output.push('_');
            }
        }
        output.extend(character.to_lowercase());
    }
    output
}