nativeview-codegen 0.1.0-rc.1

Multi-language ABI, policy, flat-op codec, and hybrid Direct-FFI code generator for Native View Engine.
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
//! Discovery and emission of `cxx/cmake/NvModuleCatalog.generated.cmake` from
//! `packages/modules/*/Cargo.toml` (`[package.metadata.nativeview.direct_host]` and
//! `[package.metadata.nativeview.component]`).
//!
//! Two-part catalog consumed by `cxx/cmake/NvOsModules.cmake`:
//!   1. `direct_host`: OS-module spec subdirectories, OS-first leaf routing categories, default
//!      OS-linked leaves, Apple OS target lists, and optional per-OS Direct-FFI host bindings
//!      (target, include, sinks, registration, core accessor).
//!   2. `component_plugin`: per-backend (`apple`, `gtk`, `qt`, `windows`) native component plugin
//!      targets, headers, factories, and optional `direct_host_arg` accessors.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::Path;

use crate::direct_specs::MODULES_DIR;
use crate::error::CodegenError;
use crate::schema::export::GeneratedFile;

/// Output path relative to the workspace root.
pub const CMAKE_CATALOG_PATH: &str = "cxx/cmake/NvModuleCatalog.generated.cmake";

const OS_KEYS: &[&str] = &["apple", "linux", "windows"];
const BACKEND_KEYS: &[&str] = &["apple", "gtk", "qt", "windows"];
const DIRECT_HOST_KEYS: &[&str] = &[
    "snake", "os_spec", "routing", "default_os_link", "apple_os_target", "apple_ios",
    "apple_extra_subdir", "apple_extra_guard", "optional", "core_accessor_name",
    "apple", "linux", "windows",
];
const DIRECT_HOST_OS_KEYS: &[&str] = &[
    "subdir", "guard_target", "target", "raw_targets", "include", "members", "set_sink",
    "register", "activate", "unregister", "core_accessor_type", "core_accessor_expr",
    "apple_host_only",
];
const COMPONENT_KEYS: &[&str] = &["snake", "optional", "apple", "gtk", "qt", "windows"];
const COMPONENT_BACKEND_KEYS: &[&str] = &[
    "subdir", "target", "raw_targets", "header", "objc", "factory", "direct_host_arg",
];
const ROUTING_KINDS: &[&str] = &[
    "pure_os", "header_fallback_non_apple", "linux_toolkit_exception",
    "window_toolkit_exception", "os_only",
];

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DirectHostOsBinding {
    pub subdir: String,
    pub guard_target: String,
    pub target: String,
    pub raw_targets: Vec<String>,
    pub include: String,
    pub members: String,
    pub set_sink: String,
    pub register: String,
    pub activate: String,
    pub unregister: String,
    pub core_accessor_type: String,
    pub core_accessor_expr: String,
    pub apple_host_only: bool,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DirectHostEntry {
    pub cap_dir: String,
    pub snake: String,
    pub os_spec: bool,
    pub routing: Option<String>,
    pub default_os_link: bool,
    pub apple_os_target: bool,
    pub apple_ios: bool,
    pub apple_extra_subdir: bool,
    pub apple_extra_guard: Option<String>,
    pub optional: bool,
    pub core_accessor_name: Option<String>,
    pub os_bindings: BTreeMap<String, DirectHostOsBinding>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ComponentBackendBinding {
    pub subdir: String,
    pub target: String,
    pub raw_targets: Vec<String>,
    pub header: String,
    pub objc: bool,
    pub factory: String,
    pub direct_host_arg: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ComponentPluginEntry {
    pub cap_dir: String,
    pub snake: String,
    pub optional: bool,
    pub backends: BTreeMap<String, ComponentBackendBinding>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ModuleCatalog {
    pub direct_hosts: Vec<DirectHostEntry>,
    pub component_plugins: Vec<ComponentPluginEntry>,
}


fn reject_unknown_keys(tbl: &toml::Table, allowed: &[&str], ctx: &str) -> Result<(), CodegenError> {
    for key in tbl.keys() {
        if !allowed.contains(&key.as_str()) {
            return Err(CodegenError::validation(format!(
                "{ctx}: unknown key `{key}` (allowed: {})",
                allowed.join(", ")
            )));
        }
    }
    Ok(())
}

fn opt_bool(tbl: &toml::Table, key: &str, default: bool, ctx: &str) -> Result<bool, CodegenError> {
    match tbl.get(key) {
        None => Ok(default),
        Some(v) => v
            .as_bool()
            .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` must be a boolean"))),
    }
}

fn opt_str(tbl: &toml::Table, key: &str, ctx: &str) -> Result<Option<String>, CodegenError> {
    match tbl.get(key) {
        None => Ok(None),
        Some(v) => v
            .as_str()
            .map(|s| Some(s.to_owned()))
            .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` must be a string"))),
    }
}

fn req_str(tbl: &toml::Table, key: &str, ctx: &str) -> Result<String, CodegenError> {
    match opt_str(tbl, key, ctx)? {
        Some(s) if !s.is_empty() => Ok(s),
        Some(_) => Err(CodegenError::validation(format!("{ctx}: `{key}` must not be empty"))),
        None => Err(CodegenError::validation(format!("{ctx}: missing string key `{key}`"))),
    }
}

fn opt_table<'a>(tbl: &'a toml::Table, key: &str, ctx: &str) -> Result<Option<&'a toml::Table>, CodegenError> {
    match tbl.get(key) {
        None => Ok(None),
        Some(v) => v
            .as_table()
            .map(Some)
            .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` must be a TOML table"))),
    }
}

fn get_str_list(tbl: &toml::Table, key: &str, ctx: &str) -> Result<Vec<String>, CodegenError> {
    let Some(val) = tbl.get(key) else {
        return Ok(Vec::new());
    };
    let arr = val
        .as_array()
        .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` must be an array of strings")))?;
    arr.iter()
        .map(|v| {
            v.as_str()
                .map(str::to_owned)
                .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` entries must be strings")))
        })
        .collect()
}

fn validate_cap_dir(val: &str, ctx: &str) -> Result<(), CodegenError> {
    let valid = !val.is_empty()
        && val.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
        && val
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_');
    if !valid {
        return Err(CodegenError::validation(format!(
            "{ctx}: invalid module directory name `{val}` for CMake catalog"
        )));
    }
    Ok(())
}

fn validate_ident(val: &str, key: &str, ctx: &str) -> Result<(), CodegenError> {
    let valid = !val.is_empty()
        && val.bytes().next().is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
        && val.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
    if !valid {
        return Err(CodegenError::validation(format!(
            "{ctx}: `{key}` value `{val}` must be a valid ASCII identifier"
        )));
    }
    Ok(())
}

fn validate_cmake_target(val: &str, key: &str, ctx: &str) -> Result<(), CodegenError> {
    let valid = !val.is_empty()
        && val
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b':' | b'.' | b'+'));
    if !valid {
        return Err(CodegenError::validation(format!(
            "{ctx}: `{key}` value `{val}` contains characters unsafe for CMake target tokens"
        )));
    }
    Ok(())
}

fn validate_rel_subdir(val: &str, key: &str, ctx: &str) -> Result<(), CodegenError> {
    let valid = !val.is_empty()
        && !val.starts_with('/')
        && val.split('/').all(|seg| !seg.is_empty() && seg != "..")
        && val
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b'/'));
    if !valid {
        return Err(CodegenError::validation(format!(
            "{ctx}: `{key}` value `{val}` must be a safe relative path"
        )));
    }
    Ok(())
}

fn validate_single_line(val: &str, key: &str, ctx: &str) -> Result<(), CodegenError> {
    if val.contains('\n') || val.contains('\r') {
        return Err(CodegenError::validation(format!("{ctx}: `{key}` must be single-line")));
    }
    Ok(())
}

fn parse_direct_host_os(tbl: &toml::Table, ctx: &str) -> Result<DirectHostOsBinding, CodegenError> {
    reject_unknown_keys(tbl, DIRECT_HOST_OS_KEYS, ctx)?;
    let subdir = req_str(tbl, "subdir", ctx)?;
    let guard_target = req_str(tbl, "guard_target", ctx)?;
    let target = req_str(tbl, "target", ctx)?;
    let raw_targets = get_str_list(tbl, "raw_targets", ctx)?;
    let include = req_str(tbl, "include", ctx)?;
    let core_accessor_type = opt_str(tbl, "core_accessor_type", ctx)?.unwrap_or_default();
    let core_accessor_expr = opt_str(tbl, "core_accessor_expr", ctx)?.unwrap_or_default();
    validate_rel_subdir(&subdir, "subdir", ctx)?;
    validate_cmake_target(&guard_target, "guard_target", ctx)?;
    validate_cmake_target(&target, "target", ctx)?;
    for raw in &raw_targets {
        validate_cmake_target(raw, "raw_targets", ctx)?;
    }
    validate_single_line(&include, "include", ctx)?;
    validate_single_line(&core_accessor_type, "core_accessor_type", ctx)?;
    validate_single_line(&core_accessor_expr, "core_accessor_expr", ctx)?;
    Ok(DirectHostOsBinding {
        subdir,
        guard_target,
        target,
        raw_targets,
        include,
        members: opt_str(tbl, "members", ctx)?.unwrap_or_default(),
        set_sink: opt_str(tbl, "set_sink", ctx)?.unwrap_or_default(),
        register: opt_str(tbl, "register", ctx)?.unwrap_or_default(),
        activate: opt_str(tbl, "activate", ctx)?.unwrap_or_default(),
        unregister: opt_str(tbl, "unregister", ctx)?.unwrap_or_default(),
        core_accessor_type,
        core_accessor_expr,
        apple_host_only: opt_bool(tbl, "apple_host_only", false, ctx)?,
    })
}

fn parse_component_backend(tbl: &toml::Table, ctx: &str) -> Result<ComponentBackendBinding, CodegenError> {
    reject_unknown_keys(tbl, COMPONENT_BACKEND_KEYS, ctx)?;
    let subdir = req_str(tbl, "subdir", ctx)?;
    let target = req_str(tbl, "target", ctx)?;
    let raw_targets = get_str_list(tbl, "raw_targets", ctx)?;
    let header = req_str(tbl, "header", ctx)?;
    let factory = req_str(tbl, "factory", ctx)?;
    let direct_host_arg = opt_str(tbl, "direct_host_arg", ctx)?;
    validate_rel_subdir(&subdir, "subdir", ctx)?;
    validate_cmake_target(&target, "target", ctx)?;
    for raw in &raw_targets {
        validate_cmake_target(raw, "raw_targets", ctx)?;
    }
    validate_single_line(&header, "header", ctx)?;
    validate_single_line(&factory, "factory", ctx)?;
    if let Some(ref arg) = direct_host_arg {
        validate_ident(arg, "direct_host_arg", ctx)?;
    }
    Ok(ComponentBackendBinding {
        subdir,
        target,
        raw_targets,
        header,
        objc: opt_bool(tbl, "objc", false, ctx)?,
        factory,
        direct_host_arg,
    })
}

fn parse_module_manifest(
    cap_dir: &str,
    manifest: &Path,
) -> Result<(Option<DirectHostEntry>, Option<ComponentPluginEntry>), CodegenError> {
    let text = std::fs::read_to_string(manifest).map_err(|e| CodegenError::io_path(manifest, e))?;
    let root: toml::Table = text.parse().map_err(|e| CodegenError::io_path(manifest, e))?;
    let ctx_base = format!("{MODULES_DIR}/{cap_dir}/Cargo.toml");
    let Some(nv_val) = root
        .get("package")
        .and_then(|p| p.get("metadata"))
        .and_then(|m| m.get("nativeview"))
    else {
        return Ok((None, None));
    };
    let nv = nv_val
        .as_table()
        .ok_or_else(|| CodegenError::validation(format!("{ctx_base}: `[package.metadata.nativeview]` must be a table")))?;

    let default_snake = cap_dir.replace('-', "_");

    let direct_host = if let Some(dh) = opt_table(nv, "direct_host", &ctx_base)? {
        let dh_ctx = format!("{ctx_base} [package.metadata.nativeview.direct_host]");
        validate_cap_dir(cap_dir, &dh_ctx)?;
        reject_unknown_keys(dh, DIRECT_HOST_KEYS, &dh_ctx)?;
        let snake = opt_str(dh, "snake", &dh_ctx)?.unwrap_or_else(|| default_snake.clone());
        validate_ident(&snake, "snake", &dh_ctx)?;
        let routing = opt_str(dh, "routing", &dh_ctx)?;
        if let Some(ref r) = routing
            && !ROUTING_KINDS.contains(&r.as_str())
        {
            return Err(CodegenError::validation(format!(
                "{dh_ctx}: unknown direct_host.routing `{r}` (expected one of {})",
                ROUTING_KINDS.join(", ")
            )));
        }
        let apple_extra_guard = opt_str(dh, "apple_extra_guard", &dh_ctx)?;
        if let Some(ref g) = apple_extra_guard {
            validate_cmake_target(g, "apple_extra_guard", &dh_ctx)?;
        }
        let core_accessor_name = opt_str(dh, "core_accessor_name", &dh_ctx)?;
        if let Some(ref acc) = core_accessor_name {
            validate_ident(acc, "core_accessor_name", &dh_ctx)?;
        }
        let optional = opt_bool(dh, "optional", false, &dh_ctx)?;
        let mut os_bindings = BTreeMap::new();
        for &os in OS_KEYS {
            if let Some(sub) = opt_table(dh, os, &dh_ctx)? {
                let ctx = format!("{ctx_base} [package.metadata.nativeview.direct_host.{os}]");
                os_bindings.insert(os.to_owned(), parse_direct_host_os(sub, &ctx)?);
            }
        }
        if !os_bindings.is_empty() && !optional {
            return Err(CodegenError::validation(format!(
                "{dh_ctx}: per-OS direct_host bindings require `optional = true` (non-optional OS modules use `os_spec` + `default_os_link` + `routing`)"
            )));
        }
        Some(DirectHostEntry {
            cap_dir: cap_dir.to_owned(),
            snake,
            os_spec: opt_bool(dh, "os_spec", false, &dh_ctx)?,
            routing,
            default_os_link: opt_bool(dh, "default_os_link", false, &dh_ctx)?,
            apple_os_target: opt_bool(dh, "apple_os_target", false, &dh_ctx)?,
            apple_ios: opt_bool(dh, "apple_ios", true, &dh_ctx)?,
            apple_extra_subdir: opt_bool(dh, "apple_extra_subdir", false, &dh_ctx)?,
            apple_extra_guard,
            optional,
            core_accessor_name,
            os_bindings,
        })
    } else {
        None
    };

    let component = if let Some(comp) = opt_table(nv, "component", &ctx_base)? {
        let comp_ctx = format!("{ctx_base} [package.metadata.nativeview.component]");
        validate_cap_dir(cap_dir, &comp_ctx)?;
        reject_unknown_keys(comp, COMPONENT_KEYS, &comp_ctx)?;
        let snake = opt_str(comp, "snake", &comp_ctx)?.unwrap_or_else(|| default_snake.clone());
        validate_ident(&snake, "snake", &comp_ctx)?;
        let optional = opt_bool(comp, "optional", true, &comp_ctx)?;
        if !optional {
            return Err(CodegenError::validation(format!(
                "{comp_ctx}: `optional = false` is unsupported (component plugins must set `optional = true` so hosts link them via `-DNV_MODULES=...`)"
            )));
        }
        let mut backends = BTreeMap::new();
        for &backend in BACKEND_KEYS {
            if let Some(sub) = opt_table(comp, backend, &comp_ctx)? {
                let ctx = format!("{ctx_base} [package.metadata.nativeview.component.{backend}]");
                backends.insert(backend.to_owned(), parse_component_backend(sub, &ctx)?);
            }
        }
        Some(ComponentPluginEntry {
            cap_dir: cap_dir.to_owned(),
            snake,
            optional,
            backends,
        })
    } else {
        None
    };

    Ok((direct_host, component))
}

/// Discovers catalog metadata across `roots` (earlier roots win per `cap_dir` for `--out` overlay).
pub fn discover_module_catalog_in(roots: &[&Path]) -> Result<ModuleCatalog, CodegenError> {
    let mut direct_by_cap: BTreeMap<String, DirectHostEntry> = BTreeMap::new();
    let mut comp_by_cap: BTreeMap<String, ComponentPluginEntry> = BTreeMap::new();
    let mut seen_caps = std::collections::BTreeSet::new();

    for root in roots {
        let dir = root.join(MODULES_DIR);
        if !dir.is_dir() {
            continue;
        }
        let mut entries: Vec<_> = std::fs::read_dir(&dir)
            .map_err(|e| CodegenError::io_path(&dir, e))?
            .map(|e| e.map(|x| x.path()).map_err(|err| CodegenError::io_path(&dir, err)))
            .collect::<Result<Vec<_>, _>>()?;
        entries.sort();
        for mod_dir in entries {
            let Some(cap_dir) = mod_dir.file_name().and_then(|n| n.to_str()) else { continue };
            let manifest = mod_dir.join("Cargo.toml");
            if !manifest.is_file() || !seen_caps.insert(cap_dir.to_owned()) {
                continue;
            }
            let (dh, comp) = parse_module_manifest(cap_dir, &manifest)?;
            if let Some(entry) = dh {
                direct_by_cap.insert(cap_dir.to_owned(), entry);
            }
            if let Some(entry) = comp {
                comp_by_cap.insert(cap_dir.to_owned(), entry);
            }
        }
    }

    Ok(ModuleCatalog {
        direct_hosts: direct_by_cap.into_values().collect(),
        component_plugins: comp_by_cap.into_values().collect(),
    })
}

fn cmake_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 8);
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => {}
            '$' => out.push_str("\\$"),
            _ => out.push(ch),
        }
    }
    out
}

fn push_set_list(out: &mut String, var: &str, items: &[String]) -> Result<(), CodegenError> {
    validate_ident(var, "cmake_var", CMAKE_CATALOG_PATH)?;
    if items.is_empty() {
        let _ = writeln!(out, "set({var} \"\")");
        return Ok(());
    }
    for tok in items {
        validate_cmake_target(tok, var, CMAKE_CATALOG_PATH)?;
    }
    let _ = writeln!(out, "set({var} {})", items.join(" "));
    Ok(())
}

/// Renders the two-part `cxx/cmake/NvModuleCatalog.generated.cmake` from `catalog`.
pub fn generate_cmake_module_catalog(catalog: &ModuleCatalog) -> Result<GeneratedFile, CodegenError> {
    let mut out = String::with_capacity(8192);
    out.push_str("# @generated by nativeview-codegen (module_catalog.rs) from packages/modules/*/Cargo.toml. DO NOT EDIT.\n");
    out.push_str("# Two-part CMake catalog consumed by cxx/cmake/NvOsModules.cmake:\n");
    out.push_str("#   1. direct_host      — OS spec modules, OS-first leaf routing, and optional per-OS Direct-FFI hosts.\n");
    out.push_str("#   2. component_plugin — Per-backend native component plugins (header, target, factory, direct_host arg).\n\n");
    out.push_str("include_guard(GLOBAL)\n\n");

    // === Section 1: direct_host ===
    out.push_str("# =============================================================================\n");
    out.push_str("# Section 1: direct_host\n");
    out.push_str("# =============================================================================\n\n");

    let os_spec_caps: Vec<String> = catalog.direct_hosts.iter().filter(|d| d.os_spec).map(|d| d.cap_dir.clone()).collect();
    let os_spec_snakes: Vec<String> = catalog.direct_hosts.iter().filter(|d| d.os_spec).map(|d| d.snake.clone()).collect();
    let default_os_links: Vec<String> = catalog.direct_hosts.iter().filter(|d| d.default_os_link).map(|d| d.snake.clone()).collect();
    let apple_os_always: Vec<String> = catalog
        .direct_hosts
        .iter()
        .filter(|d| d.apple_os_target && d.apple_ios)
        .map(|d| format!("nv::{}_apple", d.snake))
        .collect();
    let apple_os_macos_only: Vec<String> = catalog
        .direct_hosts
        .iter()
        .filter(|d| d.apple_os_target && !d.apple_ios)
        .map(|d| format!("nv::{}_apple", d.snake))
        .collect();
    let apple_extra_caps: Vec<String> = catalog
        .direct_hosts
        .iter()
        .filter(|d| d.apple_extra_subdir)
        .map(|d| d.cap_dir.clone())
        .collect();
    let apple_extra_guards: Vec<String> = catalog
        .direct_hosts
        .iter()
        .filter(|d| d.apple_extra_subdir)
        .map(|d| d.apple_extra_guard.clone().unwrap_or_else(|| format!("nv_{}_cxx", d.snake)))
        .collect();

    push_set_list(&mut out, "NV_CATALOG_OS_SPEC_CAPS", &os_spec_caps)?;
    push_set_list(&mut out, "NV_CATALOG_OS_SPEC_SNAKES", &os_spec_snakes)?;
    push_set_list(&mut out, "NV_CATALOG_DEFAULT_OS_LINK_SNAKES", &default_os_links)?;
    push_set_list(&mut out, "NV_CATALOG_APPLE_OS_TARGETS", &apple_os_always)?;
    push_set_list(&mut out, "NV_CATALOG_APPLE_MACOS_ONLY_OS_TARGETS", &apple_os_macos_only)?;
    push_set_list(&mut out, "NV_CATALOG_APPLE_EXTRA_SPEC_CAPS", &apple_extra_caps)?;
    push_set_list(&mut out, "NV_CATALOG_APPLE_EXTRA_SPEC_GUARDS", &apple_extra_guards)?;

    for &(routing_kind, var) in &[
        ("pure_os", "NV_CATALOG_ROUTING_PURE_OS"),
        ("header_fallback_non_apple", "NV_CATALOG_ROUTING_HEADER_FALLBACK_NON_APPLE"),
        ("linux_toolkit_exception", "NV_CATALOG_ROUTING_LINUX_TOOLKIT_EXCEPTIONS"),
        ("window_toolkit_exception", "NV_CATALOG_ROUTING_WINDOW_TOOLKIT_EXCEPTIONS"),
    ] {
        let mods: Vec<String> = catalog
            .direct_hosts
            .iter()
            .filter(|d| d.routing.as_deref() == Some(routing_kind))
            .map(|d| d.snake.clone())
            .collect();
        push_set_list(&mut out, var, &mods)?;
    }

    let opt_direct: Vec<String> = catalog
        .direct_hosts
        .iter()
        .filter(|d| d.optional && !d.os_bindings.is_empty())
        .map(|d| d.snake.clone())
        .collect();
    push_set_list(&mut out, "NV_CATALOG_OPTIONAL_DIRECT_HOSTS", &opt_direct)?;

    let core_accessors: Vec<String> = catalog
        .direct_hosts
        .iter()
        .filter_map(|d| d.core_accessor_name.clone())
        .collect();
    push_set_list(&mut out, "NV_CATALOG_CORE_ACCESSORS", &core_accessors)?;

    for dh in catalog.direct_hosts.iter().filter(|d| d.optional && !d.os_bindings.is_empty()) {
        validate_ident(&dh.snake, "snake", CMAKE_CATALOG_PATH)?;
        let up = dh.snake.to_ascii_uppercase();
        out.push('\n');
        let _ = writeln!(out, "# direct_host: {} ({})", dh.snake, dh.cap_dir);
        if let Some(ref acc) = dh.core_accessor_name {
            validate_ident(acc, "core_accessor_name", CMAKE_CATALOG_PATH)?;
            let _ = writeln!(out, "set(NV_CATALOG_DIRECT_HOST_{up}_CORE_ACCESSOR \"{acc}\")");
        }
        let os_list: Vec<String> = dh.os_bindings.keys().cloned().collect();
        push_set_list(&mut out, &format!("NV_CATALOG_DIRECT_HOST_{up}_OS_LIST"), &os_list)?;
        for (os, b) in &dh.os_bindings {
            let os_up = os.to_ascii_uppercase();
            let p = format!("NV_CATALOG_DIRECT_HOST_{up}_{os_up}");
            let _ = writeln!(out, "set({p}_SUBDIR \"{}\")", cmake_escape(&b.subdir));
            let _ = writeln!(out, "set({p}_GUARD_TARGET \"{}\")", cmake_escape(&b.guard_target));
            let _ = writeln!(out, "set({p}_TARGET \"{}\")", cmake_escape(&b.target));
            push_set_list(&mut out, &format!("{p}_RAW_TARGETS"), &b.raw_targets)?;
            let _ = writeln!(out, "set({p}_INCLUDE \"{}\")", cmake_escape(&b.include));
            let _ = writeln!(out, "set({p}_MEMBERS \"{}\")", cmake_escape(&b.members));
            let _ = writeln!(out, "set({p}_SET_SINK \"{}\")", cmake_escape(&b.set_sink));
            let _ = writeln!(out, "set({p}_REGISTER \"{}\")", cmake_escape(&b.register));
            let _ = writeln!(out, "set({p}_ACTIVATE \"{}\")", cmake_escape(&b.activate));
            let _ = writeln!(out, "set({p}_UNREGISTER \"{}\")", cmake_escape(&b.unregister));
            let _ = writeln!(out, "set({p}_CORE_ACCESSOR_TYPE \"{}\")", cmake_escape(&b.core_accessor_type));
            let _ = writeln!(out, "set({p}_CORE_ACCESSOR_EXPR \"{}\")", cmake_escape(&b.core_accessor_expr));
            let _ = writeln!(out, "set({p}_APPLE_HOST_ONLY {})", if b.apple_host_only { 1 } else { 0 });
        }
    }

    // === Section 2: component_plugin ===
    out.push_str("\n# =============================================================================\n");
    out.push_str("# Section 2: component_plugin\n");
    out.push_str("# =============================================================================\n\n");

    let comp_mods: Vec<String> = catalog.component_plugins.iter().map(|c| c.snake.clone()).collect();
    push_set_list(&mut out, "NV_CATALOG_COMPONENT_PLUGINS", &comp_mods)?;

    let mut all_optional: Vec<String> = Vec::new();
    for m in opt_direct.iter().chain(
        catalog
            .component_plugins
            .iter()
            .filter(|c| c.optional)
            .map(|c| &c.snake),
    ) {
        if !all_optional.contains(m) {
            all_optional.push(m.clone());
        }
    }
    all_optional.sort();
    push_set_list(&mut out, "NV_CATALOG_OPTIONAL_MODULES", &all_optional)?;

    for comp in &catalog.component_plugins {
        validate_ident(&comp.snake, "snake", CMAKE_CATALOG_PATH)?;
        let up = comp.snake.to_ascii_uppercase();
        out.push('\n');
        let _ = writeln!(out, "# component_plugin: {} ({})", comp.snake, comp.cap_dir);
        let backend_list: Vec<String> = comp.backends.keys().cloned().collect();
        push_set_list(&mut out, &format!("NV_CATALOG_COMPONENT_{up}_BACKENDS"), &backend_list)?;
        for (backend, b) in &comp.backends {
            let b_up = backend.to_ascii_uppercase();
            let p = format!("NV_CATALOG_COMPONENT_{up}_{b_up}");
            let _ = writeln!(out, "set({p}_SUBDIR \"{}\")", cmake_escape(&b.subdir));
            let _ = writeln!(out, "set({p}_TARGET \"{}\")", cmake_escape(&b.target));
            push_set_list(&mut out, &format!("{p}_RAW_TARGETS"), &b.raw_targets)?;
            let _ = writeln!(out, "set({p}_HEADER \"{}\")", cmake_escape(&b.header));
            let _ = writeln!(out, "set({p}_OBJC {})", if b.objc { 1 } else { 0 });
            let _ = writeln!(out, "set({p}_FACTORY \"{}\")", cmake_escape(&b.factory));
            let _ = writeln!(
                out,
                "set({p}_DIRECT_HOST_ARG \"{}\")",
                cmake_escape(b.direct_host_arg.as_deref().unwrap_or(""))
            );
        }
    }

    Ok(GeneratedFile {
        relative_path: CMAKE_CATALOG_PATH.to_owned(),
        content: out,
    })
}

#[cfg(test)]
#[path = "module_catalog_tests.rs"]
mod tests;