1use std::collections::BTreeMap;
13use std::fmt::Write as _;
14use std::path::Path;
15
16use crate::direct_specs::MODULES_DIR;
17use crate::error::CodegenError;
18use crate::schema::export::GeneratedFile;
19
20pub const CMAKE_CATALOG_PATH: &str = "cxx/cmake/NvModuleCatalog.generated.cmake";
22
23const OS_KEYS: &[&str] = &["apple", "linux", "windows"];
24const BACKEND_KEYS: &[&str] = &["apple", "gtk", "qt", "windows"];
25const DIRECT_HOST_KEYS: &[&str] = &[
26 "snake", "os_spec", "routing", "default_os_link", "apple_os_target", "apple_ios",
27 "apple_extra_subdir", "apple_extra_guard", "optional", "core_accessor_name",
28 "apple", "linux", "windows",
29];
30const DIRECT_HOST_OS_KEYS: &[&str] = &[
31 "subdir", "guard_target", "target", "raw_targets", "include", "members", "set_sink",
32 "register", "activate", "unregister", "core_accessor_type", "core_accessor_expr",
33 "apple_host_only",
34];
35const COMPONENT_KEYS: &[&str] = &["snake", "optional", "apple", "gtk", "qt", "windows"];
36const COMPONENT_BACKEND_KEYS: &[&str] = &[
37 "subdir", "target", "raw_targets", "header", "objc", "factory", "direct_host_arg",
38];
39const ROUTING_KINDS: &[&str] = &[
40 "pure_os", "header_fallback_non_apple", "linux_toolkit_exception",
41 "window_toolkit_exception", "os_only",
42];
43
44#[derive(Clone, Debug, Default, PartialEq, Eq)]
45pub struct DirectHostOsBinding {
46 pub subdir: String,
47 pub guard_target: String,
48 pub target: String,
49 pub raw_targets: Vec<String>,
50 pub include: String,
51 pub members: String,
52 pub set_sink: String,
53 pub register: String,
54 pub activate: String,
55 pub unregister: String,
56 pub core_accessor_type: String,
57 pub core_accessor_expr: String,
58 pub apple_host_only: bool,
59}
60
61#[derive(Clone, Debug, Default, PartialEq, Eq)]
62pub struct DirectHostEntry {
63 pub cap_dir: String,
64 pub snake: String,
65 pub os_spec: bool,
66 pub routing: Option<String>,
67 pub default_os_link: bool,
68 pub apple_os_target: bool,
69 pub apple_ios: bool,
70 pub apple_extra_subdir: bool,
71 pub apple_extra_guard: Option<String>,
72 pub optional: bool,
73 pub core_accessor_name: Option<String>,
74 pub os_bindings: BTreeMap<String, DirectHostOsBinding>,
75}
76
77#[derive(Clone, Debug, Default, PartialEq, Eq)]
78pub struct ComponentBackendBinding {
79 pub subdir: String,
80 pub target: String,
81 pub raw_targets: Vec<String>,
82 pub header: String,
83 pub objc: bool,
84 pub factory: String,
85 pub direct_host_arg: Option<String>,
86}
87
88#[derive(Clone, Debug, Default, PartialEq, Eq)]
89pub struct ComponentPluginEntry {
90 pub cap_dir: String,
91 pub snake: String,
92 pub optional: bool,
93 pub backends: BTreeMap<String, ComponentBackendBinding>,
94}
95
96#[derive(Clone, Debug, Default, PartialEq, Eq)]
97pub struct ModuleCatalog {
98 pub direct_hosts: Vec<DirectHostEntry>,
99 pub component_plugins: Vec<ComponentPluginEntry>,
100}
101
102
103fn reject_unknown_keys(tbl: &toml::Table, allowed: &[&str], ctx: &str) -> Result<(), CodegenError> {
104 for key in tbl.keys() {
105 if !allowed.contains(&key.as_str()) {
106 return Err(CodegenError::validation(format!(
107 "{ctx}: unknown key `{key}` (allowed: {})",
108 allowed.join(", ")
109 )));
110 }
111 }
112 Ok(())
113}
114
115fn opt_bool(tbl: &toml::Table, key: &str, default: bool, ctx: &str) -> Result<bool, CodegenError> {
116 match tbl.get(key) {
117 None => Ok(default),
118 Some(v) => v
119 .as_bool()
120 .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` must be a boolean"))),
121 }
122}
123
124fn opt_str(tbl: &toml::Table, key: &str, ctx: &str) -> Result<Option<String>, CodegenError> {
125 match tbl.get(key) {
126 None => Ok(None),
127 Some(v) => v
128 .as_str()
129 .map(|s| Some(s.to_owned()))
130 .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` must be a string"))),
131 }
132}
133
134fn req_str(tbl: &toml::Table, key: &str, ctx: &str) -> Result<String, CodegenError> {
135 match opt_str(tbl, key, ctx)? {
136 Some(s) if !s.is_empty() => Ok(s),
137 Some(_) => Err(CodegenError::validation(format!("{ctx}: `{key}` must not be empty"))),
138 None => Err(CodegenError::validation(format!("{ctx}: missing string key `{key}`"))),
139 }
140}
141
142fn opt_table<'a>(tbl: &'a toml::Table, key: &str, ctx: &str) -> Result<Option<&'a toml::Table>, CodegenError> {
143 match tbl.get(key) {
144 None => Ok(None),
145 Some(v) => v
146 .as_table()
147 .map(Some)
148 .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` must be a TOML table"))),
149 }
150}
151
152fn get_str_list(tbl: &toml::Table, key: &str, ctx: &str) -> Result<Vec<String>, CodegenError> {
153 let Some(val) = tbl.get(key) else {
154 return Ok(Vec::new());
155 };
156 let arr = val
157 .as_array()
158 .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` must be an array of strings")))?;
159 arr.iter()
160 .map(|v| {
161 v.as_str()
162 .map(str::to_owned)
163 .ok_or_else(|| CodegenError::validation(format!("{ctx}: `{key}` entries must be strings")))
164 })
165 .collect()
166}
167
168fn validate_cap_dir(val: &str, ctx: &str) -> Result<(), CodegenError> {
169 let valid = !val.is_empty()
170 && val.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
171 && val
172 .bytes()
173 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_');
174 if !valid {
175 return Err(CodegenError::validation(format!(
176 "{ctx}: invalid module directory name `{val}` for CMake catalog"
177 )));
178 }
179 Ok(())
180}
181
182fn validate_ident(val: &str, key: &str, ctx: &str) -> Result<(), CodegenError> {
183 let valid = !val.is_empty()
184 && val.bytes().next().is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
185 && val.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
186 if !valid {
187 return Err(CodegenError::validation(format!(
188 "{ctx}: `{key}` value `{val}` must be a valid ASCII identifier"
189 )));
190 }
191 Ok(())
192}
193
194fn validate_cmake_target(val: &str, key: &str, ctx: &str) -> Result<(), CodegenError> {
195 let valid = !val.is_empty()
196 && val
197 .bytes()
198 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b':' | b'.' | b'+'));
199 if !valid {
200 return Err(CodegenError::validation(format!(
201 "{ctx}: `{key}` value `{val}` contains characters unsafe for CMake target tokens"
202 )));
203 }
204 Ok(())
205}
206
207fn validate_rel_subdir(val: &str, key: &str, ctx: &str) -> Result<(), CodegenError> {
208 let valid = !val.is_empty()
209 && !val.starts_with('/')
210 && val.split('/').all(|seg| !seg.is_empty() && seg != "..")
211 && val
212 .bytes()
213 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b'/'));
214 if !valid {
215 return Err(CodegenError::validation(format!(
216 "{ctx}: `{key}` value `{val}` must be a safe relative path"
217 )));
218 }
219 Ok(())
220}
221
222fn validate_single_line(val: &str, key: &str, ctx: &str) -> Result<(), CodegenError> {
223 if val.contains('\n') || val.contains('\r') {
224 return Err(CodegenError::validation(format!("{ctx}: `{key}` must be single-line")));
225 }
226 Ok(())
227}
228
229fn parse_direct_host_os(tbl: &toml::Table, ctx: &str) -> Result<DirectHostOsBinding, CodegenError> {
230 reject_unknown_keys(tbl, DIRECT_HOST_OS_KEYS, ctx)?;
231 let subdir = req_str(tbl, "subdir", ctx)?;
232 let guard_target = req_str(tbl, "guard_target", ctx)?;
233 let target = req_str(tbl, "target", ctx)?;
234 let raw_targets = get_str_list(tbl, "raw_targets", ctx)?;
235 let include = req_str(tbl, "include", ctx)?;
236 let core_accessor_type = opt_str(tbl, "core_accessor_type", ctx)?.unwrap_or_default();
237 let core_accessor_expr = opt_str(tbl, "core_accessor_expr", ctx)?.unwrap_or_default();
238 validate_rel_subdir(&subdir, "subdir", ctx)?;
239 validate_cmake_target(&guard_target, "guard_target", ctx)?;
240 validate_cmake_target(&target, "target", ctx)?;
241 for raw in &raw_targets {
242 validate_cmake_target(raw, "raw_targets", ctx)?;
243 }
244 validate_single_line(&include, "include", ctx)?;
245 validate_single_line(&core_accessor_type, "core_accessor_type", ctx)?;
246 validate_single_line(&core_accessor_expr, "core_accessor_expr", ctx)?;
247 Ok(DirectHostOsBinding {
248 subdir,
249 guard_target,
250 target,
251 raw_targets,
252 include,
253 members: opt_str(tbl, "members", ctx)?.unwrap_or_default(),
254 set_sink: opt_str(tbl, "set_sink", ctx)?.unwrap_or_default(),
255 register: opt_str(tbl, "register", ctx)?.unwrap_or_default(),
256 activate: opt_str(tbl, "activate", ctx)?.unwrap_or_default(),
257 unregister: opt_str(tbl, "unregister", ctx)?.unwrap_or_default(),
258 core_accessor_type,
259 core_accessor_expr,
260 apple_host_only: opt_bool(tbl, "apple_host_only", false, ctx)?,
261 })
262}
263
264fn parse_component_backend(tbl: &toml::Table, ctx: &str) -> Result<ComponentBackendBinding, CodegenError> {
265 reject_unknown_keys(tbl, COMPONENT_BACKEND_KEYS, ctx)?;
266 let subdir = req_str(tbl, "subdir", ctx)?;
267 let target = req_str(tbl, "target", ctx)?;
268 let raw_targets = get_str_list(tbl, "raw_targets", ctx)?;
269 let header = req_str(tbl, "header", ctx)?;
270 let factory = req_str(tbl, "factory", ctx)?;
271 let direct_host_arg = opt_str(tbl, "direct_host_arg", ctx)?;
272 validate_rel_subdir(&subdir, "subdir", ctx)?;
273 validate_cmake_target(&target, "target", ctx)?;
274 for raw in &raw_targets {
275 validate_cmake_target(raw, "raw_targets", ctx)?;
276 }
277 validate_single_line(&header, "header", ctx)?;
278 validate_single_line(&factory, "factory", ctx)?;
279 if let Some(ref arg) = direct_host_arg {
280 validate_ident(arg, "direct_host_arg", ctx)?;
281 }
282 Ok(ComponentBackendBinding {
283 subdir,
284 target,
285 raw_targets,
286 header,
287 objc: opt_bool(tbl, "objc", false, ctx)?,
288 factory,
289 direct_host_arg,
290 })
291}
292
293fn parse_module_manifest(
294 cap_dir: &str,
295 manifest: &Path,
296) -> Result<(Option<DirectHostEntry>, Option<ComponentPluginEntry>), CodegenError> {
297 let text = std::fs::read_to_string(manifest).map_err(|e| CodegenError::io_path(manifest, e))?;
298 let root: toml::Table = text.parse().map_err(|e| CodegenError::io_path(manifest, e))?;
299 let ctx_base = format!("{MODULES_DIR}/{cap_dir}/Cargo.toml");
300 let Some(nv_val) = root
301 .get("package")
302 .and_then(|p| p.get("metadata"))
303 .and_then(|m| m.get("nativeview"))
304 else {
305 return Ok((None, None));
306 };
307 let nv = nv_val
308 .as_table()
309 .ok_or_else(|| CodegenError::validation(format!("{ctx_base}: `[package.metadata.nativeview]` must be a table")))?;
310
311 let default_snake = cap_dir.replace('-', "_");
312
313 let direct_host = if let Some(dh) = opt_table(nv, "direct_host", &ctx_base)? {
314 let dh_ctx = format!("{ctx_base} [package.metadata.nativeview.direct_host]");
315 validate_cap_dir(cap_dir, &dh_ctx)?;
316 reject_unknown_keys(dh, DIRECT_HOST_KEYS, &dh_ctx)?;
317 let snake = opt_str(dh, "snake", &dh_ctx)?.unwrap_or_else(|| default_snake.clone());
318 validate_ident(&snake, "snake", &dh_ctx)?;
319 let routing = opt_str(dh, "routing", &dh_ctx)?;
320 if let Some(ref r) = routing
321 && !ROUTING_KINDS.contains(&r.as_str())
322 {
323 return Err(CodegenError::validation(format!(
324 "{dh_ctx}: unknown direct_host.routing `{r}` (expected one of {})",
325 ROUTING_KINDS.join(", ")
326 )));
327 }
328 let apple_extra_guard = opt_str(dh, "apple_extra_guard", &dh_ctx)?;
329 if let Some(ref g) = apple_extra_guard {
330 validate_cmake_target(g, "apple_extra_guard", &dh_ctx)?;
331 }
332 let core_accessor_name = opt_str(dh, "core_accessor_name", &dh_ctx)?;
333 if let Some(ref acc) = core_accessor_name {
334 validate_ident(acc, "core_accessor_name", &dh_ctx)?;
335 }
336 let optional = opt_bool(dh, "optional", false, &dh_ctx)?;
337 let mut os_bindings = BTreeMap::new();
338 for &os in OS_KEYS {
339 if let Some(sub) = opt_table(dh, os, &dh_ctx)? {
340 let ctx = format!("{ctx_base} [package.metadata.nativeview.direct_host.{os}]");
341 os_bindings.insert(os.to_owned(), parse_direct_host_os(sub, &ctx)?);
342 }
343 }
344 if !os_bindings.is_empty() && !optional {
345 return Err(CodegenError::validation(format!(
346 "{dh_ctx}: per-OS direct_host bindings require `optional = true` (non-optional OS modules use `os_spec` + `default_os_link` + `routing`)"
347 )));
348 }
349 Some(DirectHostEntry {
350 cap_dir: cap_dir.to_owned(),
351 snake,
352 os_spec: opt_bool(dh, "os_spec", false, &dh_ctx)?,
353 routing,
354 default_os_link: opt_bool(dh, "default_os_link", false, &dh_ctx)?,
355 apple_os_target: opt_bool(dh, "apple_os_target", false, &dh_ctx)?,
356 apple_ios: opt_bool(dh, "apple_ios", true, &dh_ctx)?,
357 apple_extra_subdir: opt_bool(dh, "apple_extra_subdir", false, &dh_ctx)?,
358 apple_extra_guard,
359 optional,
360 core_accessor_name,
361 os_bindings,
362 })
363 } else {
364 None
365 };
366
367 let component = if let Some(comp) = opt_table(nv, "component", &ctx_base)? {
368 let comp_ctx = format!("{ctx_base} [package.metadata.nativeview.component]");
369 validate_cap_dir(cap_dir, &comp_ctx)?;
370 reject_unknown_keys(comp, COMPONENT_KEYS, &comp_ctx)?;
371 let snake = opt_str(comp, "snake", &comp_ctx)?.unwrap_or_else(|| default_snake.clone());
372 validate_ident(&snake, "snake", &comp_ctx)?;
373 let optional = opt_bool(comp, "optional", true, &comp_ctx)?;
374 if !optional {
375 return Err(CodegenError::validation(format!(
376 "{comp_ctx}: `optional = false` is unsupported (component plugins must set `optional = true` so hosts link them via `-DNV_MODULES=...`)"
377 )));
378 }
379 let mut backends = BTreeMap::new();
380 for &backend in BACKEND_KEYS {
381 if let Some(sub) = opt_table(comp, backend, &comp_ctx)? {
382 let ctx = format!("{ctx_base} [package.metadata.nativeview.component.{backend}]");
383 backends.insert(backend.to_owned(), parse_component_backend(sub, &ctx)?);
384 }
385 }
386 Some(ComponentPluginEntry {
387 cap_dir: cap_dir.to_owned(),
388 snake,
389 optional,
390 backends,
391 })
392 } else {
393 None
394 };
395
396 Ok((direct_host, component))
397}
398
399pub fn discover_module_catalog_in(roots: &[&Path]) -> Result<ModuleCatalog, CodegenError> {
401 let mut direct_by_cap: BTreeMap<String, DirectHostEntry> = BTreeMap::new();
402 let mut comp_by_cap: BTreeMap<String, ComponentPluginEntry> = BTreeMap::new();
403 let mut seen_caps = std::collections::BTreeSet::new();
404
405 for root in roots {
406 let dir = root.join(MODULES_DIR);
407 if !dir.is_dir() {
408 continue;
409 }
410 let mut entries: Vec<_> = std::fs::read_dir(&dir)
411 .map_err(|e| CodegenError::io_path(&dir, e))?
412 .map(|e| e.map(|x| x.path()).map_err(|err| CodegenError::io_path(&dir, err)))
413 .collect::<Result<Vec<_>, _>>()?;
414 entries.sort();
415 for mod_dir in entries {
416 let Some(cap_dir) = mod_dir.file_name().and_then(|n| n.to_str()) else { continue };
417 let manifest = mod_dir.join("Cargo.toml");
418 if !manifest.is_file() || !seen_caps.insert(cap_dir.to_owned()) {
419 continue;
420 }
421 let (dh, comp) = parse_module_manifest(cap_dir, &manifest)?;
422 if let Some(entry) = dh {
423 direct_by_cap.insert(cap_dir.to_owned(), entry);
424 }
425 if let Some(entry) = comp {
426 comp_by_cap.insert(cap_dir.to_owned(), entry);
427 }
428 }
429 }
430
431 Ok(ModuleCatalog {
432 direct_hosts: direct_by_cap.into_values().collect(),
433 component_plugins: comp_by_cap.into_values().collect(),
434 })
435}
436
437fn cmake_escape(s: &str) -> String {
438 let mut out = String::with_capacity(s.len() + 8);
439 for ch in s.chars() {
440 match ch {
441 '\\' => out.push_str("\\\\"),
442 '"' => out.push_str("\\\""),
443 '\n' => out.push_str("\\n"),
444 '\r' => {}
445 '$' => out.push_str("\\$"),
446 _ => out.push(ch),
447 }
448 }
449 out
450}
451
452fn push_set_list(out: &mut String, var: &str, items: &[String]) -> Result<(), CodegenError> {
453 validate_ident(var, "cmake_var", CMAKE_CATALOG_PATH)?;
454 if items.is_empty() {
455 let _ = writeln!(out, "set({var} \"\")");
456 return Ok(());
457 }
458 for tok in items {
459 validate_cmake_target(tok, var, CMAKE_CATALOG_PATH)?;
460 }
461 let _ = writeln!(out, "set({var} {})", items.join(" "));
462 Ok(())
463}
464
465pub fn generate_cmake_module_catalog(catalog: &ModuleCatalog) -> Result<GeneratedFile, CodegenError> {
467 let mut out = String::with_capacity(8192);
468 out.push_str("# @generated by nativeview-codegen (module_catalog.rs) from packages/modules/*/Cargo.toml. DO NOT EDIT.\n");
469 out.push_str("# Two-part CMake catalog consumed by cxx/cmake/NvOsModules.cmake:\n");
470 out.push_str("# 1. direct_host — OS spec modules, OS-first leaf routing, and optional per-OS Direct-FFI hosts.\n");
471 out.push_str("# 2. component_plugin — Per-backend native component plugins (header, target, factory, direct_host arg).\n\n");
472 out.push_str("include_guard(GLOBAL)\n\n");
473
474 out.push_str("# =============================================================================\n");
476 out.push_str("# Section 1: direct_host\n");
477 out.push_str("# =============================================================================\n\n");
478
479 let os_spec_caps: Vec<String> = catalog.direct_hosts.iter().filter(|d| d.os_spec).map(|d| d.cap_dir.clone()).collect();
480 let os_spec_snakes: Vec<String> = catalog.direct_hosts.iter().filter(|d| d.os_spec).map(|d| d.snake.clone()).collect();
481 let default_os_links: Vec<String> = catalog.direct_hosts.iter().filter(|d| d.default_os_link).map(|d| d.snake.clone()).collect();
482 let apple_os_always: Vec<String> = catalog
483 .direct_hosts
484 .iter()
485 .filter(|d| d.apple_os_target && d.apple_ios)
486 .map(|d| format!("nv::{}_apple", d.snake))
487 .collect();
488 let apple_os_macos_only: Vec<String> = catalog
489 .direct_hosts
490 .iter()
491 .filter(|d| d.apple_os_target && !d.apple_ios)
492 .map(|d| format!("nv::{}_apple", d.snake))
493 .collect();
494 let apple_extra_caps: Vec<String> = catalog
495 .direct_hosts
496 .iter()
497 .filter(|d| d.apple_extra_subdir)
498 .map(|d| d.cap_dir.clone())
499 .collect();
500 let apple_extra_guards: Vec<String> = catalog
501 .direct_hosts
502 .iter()
503 .filter(|d| d.apple_extra_subdir)
504 .map(|d| d.apple_extra_guard.clone().unwrap_or_else(|| format!("nv_{}_cxx", d.snake)))
505 .collect();
506
507 push_set_list(&mut out, "NV_CATALOG_OS_SPEC_CAPS", &os_spec_caps)?;
508 push_set_list(&mut out, "NV_CATALOG_OS_SPEC_SNAKES", &os_spec_snakes)?;
509 push_set_list(&mut out, "NV_CATALOG_DEFAULT_OS_LINK_SNAKES", &default_os_links)?;
510 push_set_list(&mut out, "NV_CATALOG_APPLE_OS_TARGETS", &apple_os_always)?;
511 push_set_list(&mut out, "NV_CATALOG_APPLE_MACOS_ONLY_OS_TARGETS", &apple_os_macos_only)?;
512 push_set_list(&mut out, "NV_CATALOG_APPLE_EXTRA_SPEC_CAPS", &apple_extra_caps)?;
513 push_set_list(&mut out, "NV_CATALOG_APPLE_EXTRA_SPEC_GUARDS", &apple_extra_guards)?;
514
515 for &(routing_kind, var) in &[
516 ("pure_os", "NV_CATALOG_ROUTING_PURE_OS"),
517 ("header_fallback_non_apple", "NV_CATALOG_ROUTING_HEADER_FALLBACK_NON_APPLE"),
518 ("linux_toolkit_exception", "NV_CATALOG_ROUTING_LINUX_TOOLKIT_EXCEPTIONS"),
519 ("window_toolkit_exception", "NV_CATALOG_ROUTING_WINDOW_TOOLKIT_EXCEPTIONS"),
520 ] {
521 let mods: Vec<String> = catalog
522 .direct_hosts
523 .iter()
524 .filter(|d| d.routing.as_deref() == Some(routing_kind))
525 .map(|d| d.snake.clone())
526 .collect();
527 push_set_list(&mut out, var, &mods)?;
528 }
529
530 let opt_direct: Vec<String> = catalog
531 .direct_hosts
532 .iter()
533 .filter(|d| d.optional && !d.os_bindings.is_empty())
534 .map(|d| d.snake.clone())
535 .collect();
536 push_set_list(&mut out, "NV_CATALOG_OPTIONAL_DIRECT_HOSTS", &opt_direct)?;
537
538 let core_accessors: Vec<String> = catalog
539 .direct_hosts
540 .iter()
541 .filter_map(|d| d.core_accessor_name.clone())
542 .collect();
543 push_set_list(&mut out, "NV_CATALOG_CORE_ACCESSORS", &core_accessors)?;
544
545 for dh in catalog.direct_hosts.iter().filter(|d| d.optional && !d.os_bindings.is_empty()) {
546 validate_ident(&dh.snake, "snake", CMAKE_CATALOG_PATH)?;
547 let up = dh.snake.to_ascii_uppercase();
548 out.push('\n');
549 let _ = writeln!(out, "# direct_host: {} ({})", dh.snake, dh.cap_dir);
550 if let Some(ref acc) = dh.core_accessor_name {
551 validate_ident(acc, "core_accessor_name", CMAKE_CATALOG_PATH)?;
552 let _ = writeln!(out, "set(NV_CATALOG_DIRECT_HOST_{up}_CORE_ACCESSOR \"{acc}\")");
553 }
554 let os_list: Vec<String> = dh.os_bindings.keys().cloned().collect();
555 push_set_list(&mut out, &format!("NV_CATALOG_DIRECT_HOST_{up}_OS_LIST"), &os_list)?;
556 for (os, b) in &dh.os_bindings {
557 let os_up = os.to_ascii_uppercase();
558 let p = format!("NV_CATALOG_DIRECT_HOST_{up}_{os_up}");
559 let _ = writeln!(out, "set({p}_SUBDIR \"{}\")", cmake_escape(&b.subdir));
560 let _ = writeln!(out, "set({p}_GUARD_TARGET \"{}\")", cmake_escape(&b.guard_target));
561 let _ = writeln!(out, "set({p}_TARGET \"{}\")", cmake_escape(&b.target));
562 push_set_list(&mut out, &format!("{p}_RAW_TARGETS"), &b.raw_targets)?;
563 let _ = writeln!(out, "set({p}_INCLUDE \"{}\")", cmake_escape(&b.include));
564 let _ = writeln!(out, "set({p}_MEMBERS \"{}\")", cmake_escape(&b.members));
565 let _ = writeln!(out, "set({p}_SET_SINK \"{}\")", cmake_escape(&b.set_sink));
566 let _ = writeln!(out, "set({p}_REGISTER \"{}\")", cmake_escape(&b.register));
567 let _ = writeln!(out, "set({p}_ACTIVATE \"{}\")", cmake_escape(&b.activate));
568 let _ = writeln!(out, "set({p}_UNREGISTER \"{}\")", cmake_escape(&b.unregister));
569 let _ = writeln!(out, "set({p}_CORE_ACCESSOR_TYPE \"{}\")", cmake_escape(&b.core_accessor_type));
570 let _ = writeln!(out, "set({p}_CORE_ACCESSOR_EXPR \"{}\")", cmake_escape(&b.core_accessor_expr));
571 let _ = writeln!(out, "set({p}_APPLE_HOST_ONLY {})", if b.apple_host_only { 1 } else { 0 });
572 }
573 }
574
575 out.push_str("\n# =============================================================================\n");
577 out.push_str("# Section 2: component_plugin\n");
578 out.push_str("# =============================================================================\n\n");
579
580 let comp_mods: Vec<String> = catalog.component_plugins.iter().map(|c| c.snake.clone()).collect();
581 push_set_list(&mut out, "NV_CATALOG_COMPONENT_PLUGINS", &comp_mods)?;
582
583 let mut all_optional: Vec<String> = Vec::new();
584 for m in opt_direct.iter().chain(
585 catalog
586 .component_plugins
587 .iter()
588 .filter(|c| c.optional)
589 .map(|c| &c.snake),
590 ) {
591 if !all_optional.contains(m) {
592 all_optional.push(m.clone());
593 }
594 }
595 all_optional.sort();
596 push_set_list(&mut out, "NV_CATALOG_OPTIONAL_MODULES", &all_optional)?;
597
598 for comp in &catalog.component_plugins {
599 validate_ident(&comp.snake, "snake", CMAKE_CATALOG_PATH)?;
600 let up = comp.snake.to_ascii_uppercase();
601 out.push('\n');
602 let _ = writeln!(out, "# component_plugin: {} ({})", comp.snake, comp.cap_dir);
603 let backend_list: Vec<String> = comp.backends.keys().cloned().collect();
604 push_set_list(&mut out, &format!("NV_CATALOG_COMPONENT_{up}_BACKENDS"), &backend_list)?;
605 for (backend, b) in &comp.backends {
606 let b_up = backend.to_ascii_uppercase();
607 let p = format!("NV_CATALOG_COMPONENT_{up}_{b_up}");
608 let _ = writeln!(out, "set({p}_SUBDIR \"{}\")", cmake_escape(&b.subdir));
609 let _ = writeln!(out, "set({p}_TARGET \"{}\")", cmake_escape(&b.target));
610 push_set_list(&mut out, &format!("{p}_RAW_TARGETS"), &b.raw_targets)?;
611 let _ = writeln!(out, "set({p}_HEADER \"{}\")", cmake_escape(&b.header));
612 let _ = writeln!(out, "set({p}_OBJC {})", if b.objc { 1 } else { 0 });
613 let _ = writeln!(out, "set({p}_FACTORY \"{}\")", cmake_escape(&b.factory));
614 let _ = writeln!(
615 out,
616 "set({p}_DIRECT_HOST_ARG \"{}\")",
617 cmake_escape(b.direct_host_arg.as_deref().unwrap_or(""))
618 );
619 }
620 }
621
622 Ok(GeneratedFile {
623 relative_path: CMAKE_CATALOG_PATH.to_owned(),
624 content: out,
625 })
626}
627
628#[cfg(test)]
629#[path = "module_catalog_tests.rs"]
630mod tests;