active-core 1.1.0

Core implementation of the Active configuration and data language: lexer, parser, IR, dependency graph, evaluator, type system and diagnostics
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Typed code generation from Active schemas (C-047,
//! spec/converters.md §7). Reads the module's schema tree and emits
//! JSON Schema, an OpenAPI fragment, TypeScript interfaces, Go
//! structs, and Rust serde types. Only static literal constraints
//! render — dynamic bounds still validate at runtime but have no
//! static form (documented, never guessed).

use crate::ir::{Module, Node, NodeId, SchemaField};
use crate::types::ActiveType;
use serde_json::{json, Value as JsonValue};
use std::collections::{HashMap, HashSet};

fn no_schema() -> String {
    "document has no schema block".to_string()
}

fn schema_root(module: &Module) -> Result<NodeId, String> {
    module.schema.ok_or_else(no_schema)
}

// ------------------------------------------------------------------
// Shared shape helpers.
// ------------------------------------------------------------------

/// Static literal integer bound (dynamic expressions skipped).
fn literal_int(module: &Module, id: Option<NodeId>) -> Option<i64> {
    match id.and_then(|node| module.get(node)) {
        Some(Node::Literal(crate::ir::Value::Int(i))) => Some(*i),
        _ => None,
    }
}

/// Static literal float bound (plain integers widen).
fn literal_float(module: &Module, id: Option<NodeId>) -> Option<f64> {
    match id.and_then(|node| module.get(node)) {
        Some(Node::Literal(crate::ir::Value::Float(f))) => Some(*f),
        Some(Node::Literal(crate::ir::Value::Int(i))) => Some(*i as f64),
        _ => None,
    }
}

/// Static literal string bound.
fn literal_string(module: &Module, id: Option<NodeId>) -> Option<String> {
    match id.and_then(|node| module.get(node)) {
        Some(Node::Literal(crate::ir::Value::String(s))) => Some(s.clone()),
        _ => None,
    }
}

/// Static literal default as JSON (any literal kind, redacted like
/// every export — secrets never leak through generated defaults).
fn literal_default(module: &Module, field: &SchemaField) -> Option<JsonValue> {
    match field.default.and_then(|node| module.get(node)) {
        Some(Node::Literal(value)) => Some(super::value_to_json(value)),
        _ => None,
    }
}

/// Required unless a static default exists or the field is Null
/// (absent Null keys validate clean — C-032). Tables and arrays are
/// always required: they carry no default slot.
fn is_required(module: &Module, id: NodeId) -> bool {
    match module.get(id) {
        Some(Node::SchemaField { field }) => {
            !matches!(field.typ, ActiveType::Null) && literal_default(module, field).is_none()
        }
        _ => true,
    }
}

fn pascal_case(s: &str) -> String {
    let mut out = String::new();
    for part in s.split(['_', '-']) {
        let mut chars = part.chars();
        match chars.next() {
            None => out.push('_'),
            Some(first) => {
                out.extend(first.to_uppercase());
                out.push_str(chars.as_str());
            }
        }
    }
    if out.is_empty() {
        return "Type".to_string();
    }
    if out.starts_with(|c: char| c.is_ascii_digit()) {
        out.insert(0, '_');
    }
    out
}

fn sanitize_ident(s: &str, fallback: &str) -> String {
    let clean: String = s
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if clean.is_empty()
        || clean.starts_with(|c: char| c.is_ascii_digit())
        || !clean
            .chars()
            .all(|c: char| c.is_ascii_alphanumeric() || c == '_')
    {
        return fallback.to_string();
    }
    clean
}

/// Innermost nominal node through array wrappers: arrays are
/// transparent for naming (the element table/enum owns the name).
fn nominal_id(module: &Module, mut id: NodeId) -> NodeId {
    while let Some(Node::SchemaArray { element }) = module.get(id) {
        id = *element;
    }
    id
}

// ------------------------------------------------------------------
// JSON Schema (Draft 2020-12 compatible subset).
// ------------------------------------------------------------------

/// The schema tree as JSON Schema: objects for tables (closed →
/// `additionalProperties: false`), enums, arrays, constraints from
/// static literals, static defaults, and `deprecated` flags.
pub fn schema_to_json_schema(module: &Module) -> Result<JsonValue, String> {
    let root = schema_root(module)?;
    Ok(json_schema_node(module, root))
}

fn json_schema_node(module: &Module, id: NodeId) -> JsonValue {
    match module.get(id) {
        Some(Node::SchemaTable { fields, closed }) => {
            let mut properties = serde_json::Map::new();
            let mut required = Vec::new();
            for (name, field) in fields {
                properties.insert(name.clone(), json_schema_node(module, *field));
                if is_required(module, *field) {
                    required.push(JsonValue::String(name.clone()));
                }
            }
            let mut obj = serde_json::Map::new();
            obj.insert("type".to_string(), JsonValue::String("object".to_string()));
            obj.insert("properties".to_string(), JsonValue::Object(properties));
            if !required.is_empty() {
                obj.insert("required".to_string(), JsonValue::Array(required));
            }
            if *closed {
                obj.insert("additionalProperties".to_string(), JsonValue::Bool(false));
            }
            JsonValue::Object(obj)
        }
        Some(Node::SchemaArray { element }) => {
            json!({"type": "array", "items": json_schema_node(module, *element)})
        }
        Some(Node::SchemaField { field }) => json_schema_field(module, field),
        _ => JsonValue::Bool(true),
    }
}

fn json_schema_field(module: &Module, field: &SchemaField) -> JsonValue {
    let mut obj = serde_json::Map::new();
    match &field.typ {
        ActiveType::Null => {
            obj.insert("type".to_string(), JsonValue::String("null".to_string()));
        }
        ActiveType::Bool => {
            obj.insert("type".to_string(), JsonValue::String("boolean".to_string()));
        }
        ActiveType::Int => {
            obj.insert("type".to_string(), JsonValue::String("integer".to_string()));
            if let Some(min) = literal_int(module, field.min) {
                obj.insert("minimum".to_string(), JsonValue::from(min));
            }
            if let Some(max) = literal_int(module, field.max) {
                obj.insert("maximum".to_string(), JsonValue::from(max));
            }
        }
        ActiveType::Float => {
            obj.insert("type".to_string(), JsonValue::String("number".to_string()));
            if let Some(min) = literal_float(module, field.min) {
                obj.insert("minimum".to_string(), JsonValue::from(min));
            }
            if let Some(max) = literal_float(module, field.max) {
                obj.insert("maximum".to_string(), JsonValue::from(max));
            }
        }
        ActiveType::String => {
            obj.insert("type".to_string(), JsonValue::String("string".to_string()));
            if let Some(min) = literal_int(module, field.min_len) {
                obj.insert("minLength".to_string(), JsonValue::from(min));
            }
            if let Some(max) = literal_int(module, field.max_len) {
                obj.insert("maxLength".to_string(), JsonValue::from(max));
            }
            if let Some(pattern) = literal_string(module, field.pattern) {
                obj.insert("pattern".to_string(), JsonValue::String(pattern));
            }
        }
        // Matches the §1 export shape: durations serialize as
        // `{"ms": n}` objects.
        ActiveType::Duration => {
            obj.insert("type".to_string(), JsonValue::String("object".to_string()));
            obj.insert("properties".to_string(), json!({"ms": {"type": "integer"}}));
            obj.insert("required".to_string(), json!(["ms"]));
            obj.insert("additionalProperties".to_string(), JsonValue::Bool(false));
        }
        // Bytes normalize to integers on export.
        ActiveType::Bytes => {
            obj.insert("type".to_string(), JsonValue::String("integer".to_string()));
        }
        ActiveType::Table { closed } => {
            obj.insert("type".to_string(), JsonValue::String("object".to_string()));
            if *closed {
                obj.insert("additionalProperties".to_string(), JsonValue::Bool(false));
            }
        }
        ActiveType::Enum(members) => {
            obj.insert(
                "enum".to_string(),
                JsonValue::Array(members.iter().cloned().map(JsonValue::String).collect()),
            );
        }
        // Secrets export as redacted strings.
        ActiveType::Secret => {
            obj.insert("type".to_string(), JsonValue::String("string".to_string()));
            obj.insert(
                "description".to_string(),
                JsonValue::String("secret value, redacted as ***SECRET*** on export".to_string()),
            );
        }
        ActiveType::Any => return JsonValue::Bool(true),
    }
    if let Some(default) = literal_default(module, field) {
        obj.insert("default".to_string(), default);
    }
    if let Some(reason) = field.deprecated.as_deref() {
        obj.insert("deprecated".to_string(), JsonValue::Bool(true));
        if !reason.is_empty() {
            obj.insert(
                "description".to_string(),
                JsonValue::String(reason.to_string()),
            );
        }
    }
    JsonValue::Object(obj)
}

// ------------------------------------------------------------------
// OpenAPI fragment (3.1: plain JSON Schema under components).
// ------------------------------------------------------------------

/// The JSON Schema wrapped as an OpenAPI 3.1
/// `components.schemas.<name>` fragment.
pub fn schema_to_openapi(module: &Module, name: &str) -> Result<JsonValue, String> {
    let schema = schema_to_json_schema(module)?;
    let mut schemas = serde_json::Map::new();
    schemas.insert(sanitize_ident(name, "Config"), schema);
    let mut components = serde_json::Map::new();
    components.insert("schemas".to_string(), JsonValue::Object(schemas));
    let mut out = serde_json::Map::new();
    out.insert(
        "openapi".to_string(),
        JsonValue::String("3.1.0".to_string()),
    );
    out.insert("components".to_string(), JsonValue::Object(components));
    Ok(JsonValue::Object(out))
}

// ------------------------------------------------------------------
// TypeScript interfaces.
// ------------------------------------------------------------------

/// The schema tree as TypeScript `export interface` declarations
/// (nested tables become PascalCase interfaces; `?` marks
/// defaulted/Null fields).
pub fn schema_to_typescript(module: &Module, root_name: &str) -> Result<String, String> {
    let root = schema_root(module)?;
    if !matches!(module.get(root), Some(Node::SchemaTable { .. })) {
        return Err("schema block must be a table for code generation".to_string());
    }
    let mut gen = TsGen {
        module,
        out: String::new(),
        names: HashMap::new(),
        taken: HashSet::new(),
    };
    let root_name = gen.type_name(root, pascal_case(&sanitize_ident(root_name, "Config")));
    gen.emit_table(&root_name, root);
    Ok(gen.out)
}

struct TsGen<'a> {
    module: &'a Module,
    out: String,
    /// Type name per node plus every assigned name: same-derived
    /// names for different nodes (`port` vs `Port` tables) gain
    /// suffixes deterministically instead of colliding.
    names: HashMap<NodeId, String>,
    taken: HashSet<String>,
}

impl TsGen<'_> {
    /// Canonical type name for a node under a derived base: stable
    /// across the reference and declaration passes, which compute
    /// the same base independently.
    fn type_name(&mut self, id: NodeId, base: String) -> String {
        if let Some(name) = self.names.get(&id) {
            return name.clone();
        }
        let mut name = base;
        while !self.taken.insert(name.clone()) {
            name.push('_');
        }
        self.names.insert(id, name.clone());
        name
    }

    fn emit_table(&mut self, name: &str, id: NodeId) {
        let Some(Node::SchemaTable { fields, .. }) = self.module.get(id) else {
            return;
        };
        let fields: Vec<(String, NodeId)> = fields.iter().map(|(k, v)| (k.clone(), *v)).collect();
        self.out.push_str(&format!("export interface {name} {{\n"));
        for (key, field) in &fields {
            let optional = !is_required(self.module, *field);
            let nominal = nominal_id(self.module, *field);
            let tname = self.type_name(nominal, format!("{name}{}", pascal_case(key)));
            let typ = self.ts_type(&tname, *field);
            let mark = if optional { "?" } else { "" };
            if let Some(reason) = self.deprecated(*field) {
                if reason.is_empty() {
                    self.out.push_str("  /** @deprecated */\n");
                } else {
                    self.out
                        .push_str(&format!("  /** @deprecated {reason} */\n"));
                }
            }
            self.out.push_str(&format!("  {key}{mark}: {typ};\n"));
        }
        self.out.push_str("}\n");
        for (key, field) in &fields {
            let nominal = nominal_id(self.module, *field);
            let tname = self.type_name(nominal, format!("{name}{}", pascal_case(key)));
            self.emit_nested(&tname, *field);
        }
    }

    fn emit_nested(&mut self, name: &str, id: NodeId) {
        match self.module.get(id) {
            Some(Node::SchemaTable { .. }) => self.emit_table(name, id),
            Some(Node::SchemaArray { element }) => self.emit_nested(name, *element),
            _ => {}
        }
    }

    fn ts_type(&mut self, hint: &str, id: NodeId) -> String {
        match self.module.get(id) {
            // Named by the caller: emit_table/emit_nested declares
            // the same hint, so references always resolve.
            Some(Node::SchemaTable { .. }) => hint.to_string(),
            Some(Node::SchemaArray { element }) => {
                format!("{}[]", self.ts_inline(hint, *element))
            }
            Some(Node::SchemaField { field }) => self.ts_field(field),
            _ => "unknown".to_string(),
        }
    }

    /// Inline type for array elements, threaded with the same naming
    /// hint the declaration pass uses — element tables resolve to
    /// the named interface, never to anonymous duplicates.
    fn ts_inline(&mut self, hint: &str, id: NodeId) -> String {
        match self.module.get(id) {
            Some(Node::SchemaTable { .. }) => hint.to_string(),
            Some(Node::SchemaArray { element }) => {
                format!("{}[]", self.ts_inline(hint, *element))
            }
            Some(Node::SchemaField { field }) => self.ts_field(field),
            _ => "unknown".to_string(),
        }
    }

    fn ts_field(&self, field: &SchemaField) -> String {
        match &field.typ {
            ActiveType::Null => "null".to_string(),
            ActiveType::Bool => "boolean".to_string(),
            ActiveType::Int | ActiveType::Float | ActiveType::Duration | ActiveType::Bytes => {
                "number".to_string()
            }
            ActiveType::String | ActiveType::Secret => "string".to_string(),
            ActiveType::Table { .. } => "Record<string, unknown>".to_string(),
            ActiveType::Enum(members) => members
                .iter()
                .map(|m| format!("{m:?}"))
                .collect::<Vec<_>>()
                .join(" | "),
            ActiveType::Any => "unknown".to_string(),
        }
    }

    fn deprecated(&self, id: NodeId) -> Option<String> {
        match self.module.get(id) {
            Some(Node::SchemaField { field }) => field.deprecated.clone(),
            _ => None,
        }
    }
}

// ------------------------------------------------------------------
// Go structs.
// ------------------------------------------------------------------

/// The schema tree as Go structs with `json` tags (nested tables
/// become PascalCase structs; enums stay strings with their members
/// documented).
pub fn schema_to_go(module: &Module, root_name: &str) -> Result<String, String> {
    let root = schema_root(module)?;
    if !matches!(module.get(root), Some(Node::SchemaTable { .. })) {
        return Err("schema block must be a table for code generation".to_string());
    }
    let mut gen = GoGen {
        module,
        out: String::new(),
        names: HashMap::new(),
        taken: HashSet::new(),
    };
    let root_name = gen.type_name(root, pascal_case(&sanitize_ident(root_name, "Config")));
    gen.emit_table(&root_name, root);
    Ok(gen.out)
}

struct GoGen<'a> {
    module: &'a Module,
    out: String,
    names: HashMap<NodeId, String>,
    taken: HashSet<String>,
}

impl GoGen<'_> {
    fn type_name(&mut self, id: NodeId, base: String) -> String {
        if let Some(name) = self.names.get(&id) {
            return name.clone();
        }
        let mut name = base;
        while !self.taken.insert(name.clone()) {
            name.push('_');
        }
        self.names.insert(id, name.clone());
        name
    }

    fn emit_table(&mut self, name: &str, id: NodeId) {
        let Some(Node::SchemaTable { fields, .. }) = self.module.get(id) else {
            return;
        };
        let fields: Vec<(String, NodeId)> = fields.iter().map(|(k, v)| (k.clone(), *v)).collect();
        self.out.push_str(&format!("type {name} struct {{\n"));
        let mut taken = HashSet::new();
        for (key, field) in &fields {
            let mut field_name = pascal_case(key);
            while !taken.insert(field_name.clone()) {
                field_name.push('_');
            }
            let nominal = nominal_id(self.module, *field);
            let tname = self.type_name(nominal, format!("{name}{}", pascal_case(key)));
            let typ = self.go_type(&tname, *field);
            if let Some(reason) = self.deprecated(*field) {
                if reason.is_empty() {
                    self.out.push_str("\t// Deprecated: no reason given.\n");
                } else {
                    self.out.push_str(&format!("\t// Deprecated: {reason}\n"));
                }
            }
            if let Some(doc) = self.doc(*field) {
                self.out.push_str(&format!("\t// {doc}\n"));
            }
            self.out
                .push_str(&format!("\t{field_name} {typ} `json:\"{key}\"`\n"));
        }
        self.out.push_str("}\n");
        for (key, field) in &fields {
            let nominal = nominal_id(self.module, *field);
            let tname = self.type_name(nominal, format!("{name}{}", pascal_case(key)));
            self.emit_nested(&tname, *field);
        }
    }

    fn emit_nested(&mut self, name: &str, id: NodeId) {
        match self.module.get(id) {
            Some(Node::SchemaTable { .. }) => self.emit_table(name, id),
            Some(Node::SchemaArray { element }) => self.emit_nested(name, *element),
            _ => {}
        }
    }

    fn go_type(&mut self, hint: &str, id: NodeId) -> String {
        match self.module.get(id) {
            Some(Node::SchemaTable { .. }) => hint.to_string(),
            Some(Node::SchemaArray { element }) => {
                format!("[]{}", self.go_inline(hint, *element))
            }
            Some(Node::SchemaField { field }) => self.go_field(field),
            _ => "interface{}".to_string(),
        }
    }

    fn go_inline(&mut self, hint: &str, id: NodeId) -> String {
        match self.module.get(id) {
            // Element tables resolve to the named struct the
            // declaration pass emits under the same hint.
            Some(Node::SchemaTable { .. }) => hint.to_string(),
            Some(Node::SchemaArray { element }) => {
                format!("[]{}", self.go_inline(hint, *element))
            }
            Some(Node::SchemaField { field }) => self.go_field(field),
            _ => "interface{}".to_string(),
        }
    }

    fn go_field(&self, field: &SchemaField) -> String {
        match &field.typ {
            ActiveType::Null | ActiveType::Any => "interface{}".to_string(),
            ActiveType::Bool => "bool".to_string(),
            ActiveType::Int | ActiveType::Duration | ActiveType::Bytes => "int64".to_string(),
            ActiveType::Float => "float64".to_string(),
            ActiveType::String | ActiveType::Secret | ActiveType::Enum(_) => "string".to_string(),
            ActiveType::Table { .. } => "map[string]interface{}".to_string(),
        }
    }

    fn doc(&self, id: NodeId) -> Option<String> {
        match self.module.get(id) {
            Some(Node::SchemaField { field }) => match &field.typ {
                ActiveType::Duration => Some("milliseconds".to_string()),
                ActiveType::Enum(members) => Some(format!("one of: {}", members.join(", "))),
                ActiveType::Secret => {
                    Some("secret value, redacted as ***SECRET*** on export".to_string())
                }
                _ => None,
            },
            _ => None,
        }
    }

    fn deprecated(&self, id: NodeId) -> Option<String> {
        match self.module.get(id) {
            Some(Node::SchemaField { field }) => field.deprecated.clone(),
            _ => None,
        }
    }
}

// ------------------------------------------------------------------
// Rust serde types.
// ------------------------------------------------------------------

const RUST_KEYWORDS: &[&str] = &[
    "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
    "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
    "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where",
    "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "macro",
    "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
];

/// The schema tree as Rust serde types: structs with `rename` tags,
/// real enums for `Enum`, `Option` for defaulted/Null fields.
pub fn schema_to_rust(module: &Module, root_name: &str) -> Result<String, String> {
    let root = schema_root(module)?;
    if !matches!(module.get(root), Some(Node::SchemaTable { .. })) {
        return Err("schema block must be a table for code generation".to_string());
    }
    let mut gen = RustGen {
        module,
        out: String::from(
            "// Requires: serde = { version = \"1\", features = [\"derive\"] }, serde_json = \"1\"\nuse serde::{Deserialize, Serialize};\n\n",
        ),
        names: HashMap::new(),
        taken: HashSet::new(),
    };
    let root_name = gen.type_name(root, pascal_case(&sanitize_ident(root_name, "Config")));
    gen.emit_table(&root_name, root);
    Ok(gen.out)
}

struct RustGen<'a> {
    module: &'a Module,
    out: String,
    names: HashMap<NodeId, String>,
    taken: HashSet<String>,
}

impl RustGen<'_> {
    fn type_name(&mut self, id: NodeId, base: String) -> String {
        if let Some(name) = self.names.get(&id) {
            return name.clone();
        }
        let mut name = base;
        while !self.taken.insert(name.clone()) {
            name.push('_');
        }
        self.names.insert(id, name.clone());
        name
    }

    fn emit_table(&mut self, name: &str, id: NodeId) {
        let Some(Node::SchemaTable { fields, .. }) = self.module.get(id) else {
            return;
        };
        let fields: Vec<(String, NodeId)> = fields.iter().map(|(k, v)| (k.clone(), *v)).collect();
        self.out
            .push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ");
        self.out.push_str(name);
        self.out.push_str(" {\n");
        let mut taken = HashSet::new();
        for (key, field) in &fields {
            let optional = !is_required(self.module, *field);
            let raw = sanitize_ident(key, "field");
            let (field_name, mut renamed) = if RUST_KEYWORDS.contains(&raw.as_str()) {
                (format!("r#{raw}"), true)
            } else {
                (raw.clone(), raw != *key)
            };
            let mut field_name = field_name;
            while !taken.insert(field_name.clone()) {
                field_name.push('_');
                renamed = true;
            }
            let inner = {
                let nominal = nominal_id(self.module, *field);
                let tname = self.type_name(nominal, format!("{name}{}", pascal_case(key)));
                self.rust_type(&tname, *field)
            };
            let typ = if optional {
                format!("Option<{inner}>")
            } else {
                inner
            };
            if let Some(reason) = self.deprecated(*field) {
                if reason.is_empty() {
                    self.out.push_str("\t#[deprecated]\n");
                } else {
                    self.out
                        .push_str(&format!("\t#[deprecated(note = {reason:?})]\n"));
                }
            }
            // Raw identifiers (`r#type`) never match their key
            // textually; serde_derive strips the prefix, so an
            // explicit rename keeps the mapping exact either way.
            if renamed {
                self.out
                    .push_str(&format!("\t#[serde(rename = {key:?})]\n"));
            }
            self.out.push_str(&format!("\tpub {field_name}: {typ},\n"));
        }
        self.out.push_str("}\n");
        for (key, field) in &fields {
            let nominal = nominal_id(self.module, *field);
            let tname = self.type_name(nominal, format!("{name}{}", pascal_case(key)));
            self.emit_nested(&tname, *field);
        }
    }

    fn emit_nested(&mut self, name: &str, id: NodeId) {
        match self.module.get(id) {
            Some(Node::SchemaTable { .. }) => self.emit_table(name, id),
            Some(Node::SchemaArray { element }) => self.emit_nested(name, *element),
            Some(Node::SchemaField { field }) => {
                if let ActiveType::Enum(members) = &field.typ {
                    self.emit_enum(name, members);
                }
            }
            _ => {}
        }
    }

    fn emit_enum(&mut self, name: &str, members: &[String]) {
        self.out
            .push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum ");
        self.out.push_str(name);
        self.out.push_str(" {\n");
        let mut taken = HashSet::new();
        for member in members {
            let mut variant = pascal_case(&sanitize_ident(member, "Value"));
            while !taken.insert(variant.clone()) {
                variant.push('_');
            }
            if &variant != member {
                self.out
                    .push_str(&format!("\t#[serde(rename = {member:?})]\n"));
            }
            self.out.push_str(&format!("\t{variant},\n"));
        }
        self.out.push_str("}\n");
    }

    fn rust_type(&mut self, hint: &str, id: NodeId) -> String {
        match self.module.get(id) {
            Some(Node::SchemaTable { .. }) => hint.to_string(),
            Some(Node::SchemaArray { element }) => {
                format!("Vec<{}>", self.rust_inline(hint, *element))
            }
            Some(Node::SchemaField { field }) => match &field.typ {
                ActiveType::Null => "()".to_string(),
                ActiveType::Bool => "bool".to_string(),
                ActiveType::Int => "i64".to_string(),
                ActiveType::Float => "f64".to_string(),
                ActiveType::String | ActiveType::Secret => "String".to_string(),
                ActiveType::Duration | ActiveType::Bytes => "u64".to_string(),
                ActiveType::Table { .. } => {
                    "std::collections::HashMap<String, serde_json::Value>".to_string()
                }
                ActiveType::Enum(_) => hint.to_string(),
                ActiveType::Any => "serde_json::Value".to_string(),
            },
            _ => "serde_json::Value".to_string(),
        }
    }

    /// Element types under the declaration hint: element tables and
    /// enums resolve to the named items `emit_nested` declares.
    fn rust_inline(&mut self, hint: &str, id: NodeId) -> String {
        match self.module.get(id) {
            Some(Node::SchemaTable { .. }) => hint.to_string(),
            Some(Node::SchemaArray { element }) => {
                format!("Vec<{}>", self.rust_inline(hint, *element))
            }
            Some(Node::SchemaField { field }) => match &field.typ {
                ActiveType::Enum(_) => hint.to_string(),
                _ => self.rust_type(hint, id),
            },
            _ => "serde_json::Value".to_string(),
        }
    }

    fn deprecated(&self, id: NodeId) -> Option<String> {
        match self.module.get(id) {
            Some(Node::SchemaField { field }) => field.deprecated.clone(),
            _ => None,
        }
    }
}