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;
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))
}
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(())
}
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");
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 });
}
}
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;