Skip to main content

nativeview_codegen/
direct_specs.rs

1//! Discovery of the Direct-FFI capability specs `nv codegen abi` renders, and the module-leaf
2//! layout their host bindings (and module-homed `nv_policy!` constants) land in.
3//!
4//! Every `packages/modules/<cap>/src/spec.rs` carrying a `#[nativeview_hybrid_spec]` module is a spec: no
5//! registration list exists (`[INV:direct-ffi-specs-discovered]`). `<cap>` comes from the path,
6//! `<stem>` from `parsed.stem_snake()`, and the Swift target directory from the module root crate's
7//! `packages/modules/<cap>/Cargo.toml`:
8//!
9//! ```toml
10//! [package.metadata.nativeview]
11//! swift_target = "Nv<Pascal>Apple"
12//! ```
13//!
14//! A spec whose module lacks that key fails discovery with a message naming the file, and two
15//! specs with one stem fail it too: their C/C++ headers would collide under `nv/<stem>/` on the
16//! shared include path.
17
18use std::path::{Path, PathBuf};
19
20use crate::error::CodegenError;
21use crate::schema::export::GeneratedFile;
22use crate::schema::hybrid::HybridTarget;
23
24/// Parent of every capability module.
25pub const MODULES_DIR: &str = "packages/modules";
26
27/// One discovered `src/spec.rs` Direct-FFI spec and the module it belongs to.
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct DirectSpec {
30    /// Repository-relative spec path (`packages/modules/<cap>/src/spec.rs`).
31    pub spec_rel: String,
32    /// The spec file as found on disk (`<repo root>/<spec_rel>`).
33    pub path: PathBuf,
34    /// Module directory name (`secure-store`).
35    pub cap_dir: String,
36    /// Spec namespace/stem (`secure_store`): the C/C++ include directory under `cxx/include/nv/`.
37    pub stem: String,
38    /// `[package.metadata.nativeview] swift_target`: the `apple/Sources/<target>` directory.
39    pub swift_target: String,
40    /// Optional `[package.metadata.nativeview] java_package` (e.g. `io.github.nativeview.modules.secure_store`).
41    pub java_package: Option<String>,
42}
43
44/// A module leaf directory generated host sources land in.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum ModuleLeaf {
47    CxxInclude,
48    AppleSources,
49    JavaGenerated,
50    KotlinSources,
51    Jni,
52    WebTs,
53    DartLib,
54}
55
56impl DirectSpec {
57    /// `packages/modules/<cap>/<leaf dir>`, unified with [`ModuleLayout::leaf_dir`].
58    pub fn leaf_dir(&self, leaf: ModuleLeaf) -> Result<String, CodegenError> {
59        self.layout().leaf_dir(leaf)
60    }
61
62    /// Converts this Direct-FFI spec into a generic [`ModuleLayout`].
63    pub fn layout(&self) -> ModuleLayout {
64        ModuleLayout {
65            cap_dir: self.cap_dir.clone(),
66            stem: self.stem.clone(),
67            swift_target: Some(self.swift_target.clone()),
68            java_package: self.java_package.clone(),
69            has_direct_spec: true,
70        }
71    }
72}
73
74/// Discovered leaf layout of any capability module under `packages/modules/<cap>`, whether backed
75/// by a Direct-FFI `src/spec.rs` or a table/policy-only `[package.metadata.nativeview]` manifest.
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct ModuleLayout {
78    /// Module directory name (`image`, `secure-store`).
79    pub cap_dir: String,
80    /// C/C++ include stem (`image`, `secure_store`).
81    pub stem: String,
82    /// Optional `[package.metadata.nativeview]` `swift_target` / `swift_tables_target`.
83    pub swift_target: Option<String>,
84    /// Optional `[package.metadata.nativeview]` `java_package` (e.g. `io.github.nativeview.modules.image`).
85    pub java_package: Option<String>,
86    /// `true` for Direct-FFI modules (`web/ts`), `false` for table/policy-only modules (`ts`).
87    pub has_direct_spec: bool,
88}
89
90impl ModuleLayout {
91    /// `packages/modules/<cap>/<leaf dir>`, failing clearly if `AppleSources` or `JavaGenerated`
92    /// is requested for a module without the required `[package.metadata.nativeview]` metadata.
93    pub fn leaf_dir(&self, leaf: ModuleLeaf) -> Result<String, CodegenError> {
94        let root = format!("{MODULES_DIR}/{}", self.cap_dir);
95        Ok(match leaf {
96            ModuleLeaf::CxxInclude => format!("{root}/cxx/include/nv/{}", self.stem),
97            ModuleLeaf::AppleSources => {
98                let target = self.swift_target.as_deref().ok_or_else(|| {
99                    CodegenError::validation(format!(
100                        "module `{}` has no `[package.metadata.nativeview] swift_target` for Swift output",
101                        self.cap_dir
102                    ))
103                })?;
104                format!("{root}/apple/Sources/{target}")
105            }
106            ModuleLeaf::JavaGenerated => {
107                let pkg = self.java_package.as_deref().ok_or_else(|| {
108                    CodegenError::validation(format!(
109                        "module `{}` has no `[package.metadata.nativeview] java_package` for Java output",
110                        self.cap_dir
111                    ))
112                })?;
113                format!("{root}/android/src/main/java/{}/generated", pkg.replace('.', "/"))
114            }
115            ModuleLeaf::KotlinSources => format!("{root}/android/src/main/kotlin/io/github/nativeview/hybrid"),
116            ModuleLeaf::Jni => format!("{root}/android/jni"),
117            ModuleLeaf::WebTs => {
118                if self.has_direct_spec {
119                    format!("{root}/web/ts")
120                } else {
121                    format!("{root}/ts")
122                }
123            }
124            ModuleLeaf::DartLib => format!("{root}/dart/lib/src"),
125        })
126    }
127}
128
129
130/// Sorted entries of `dir` (an absent directory has none).
131fn sorted_entries(dir: &Path) -> Result<Vec<std::path::PathBuf>, CodegenError> {
132    if !dir.is_dir() {
133        return Ok(Vec::new());
134    }
135    let mut out = std::fs::read_dir(dir)
136        .map_err(|e| CodegenError::io_path(dir, e))?
137        .map(|entry| entry.map(|e| e.path()).map_err(|e| CodegenError::io_path(dir, e)))
138        .collect::<Result<Vec<_>, _>>()?;
139    out.sort();
140    Ok(out)
141}
142
143/// `[package.metadata.nativeview]` (`swift_target`, optional `java_package`) of `manifest`.
144fn direct_spec_metadata(manifest: &Path, spec_rel: &str) -> Result<(String, Option<String>), CodegenError> {
145    let text = std::fs::read_to_string(manifest).map_err(|e| CodegenError::io_path(manifest, e))?;
146    let table: toml::Table = text.parse().map_err(|e| CodegenError::io_path(manifest, e))?;
147    let nv = table
148        .get("package")
149        .and_then(|p| p.get("metadata"))
150        .and_then(|m| m.get("nativeview"))
151        .and_then(toml::Value::as_table);
152    let target = nv
153        .and_then(|n| n.get("swift_target"))
154        .and_then(toml::Value::as_str)
155        .ok_or_else(|| {
156            CodegenError::validation(format!(
157                "{spec_rel}: its module manifest {} has no `[package.metadata.nativeview] swift_target = \"Nv<Pascal>Apple\"`",
158                manifest.display()
159            ))
160        })?;
161    let swift_target = validate_swift_target(target, manifest)?;
162    let java_package = parse_optional_java_package(nv, manifest)?;
163    Ok((swift_target, java_package))
164}
165
166fn validate_swift_target(target: &str, manifest: &Path) -> Result<String, CodegenError> {
167    let valid = target.chars().next().is_some_and(|c| c.is_ascii_uppercase())
168        && target.chars().all(|c| c.is_ascii_alphanumeric());
169    if !valid {
170        return Err(CodegenError::validation(format!(
171            "{}: swift_target `{target}` must be a PascalCase Swift target name",
172            manifest.display()
173        )));
174    }
175    Ok(target.to_owned())
176}
177
178fn validate_java_package(pkg: &str, manifest: &Path) -> Result<String, CodegenError> {
179    let valid = !pkg.is_empty()
180        && pkg.split('.').all(|seg| {
181            !seg.is_empty()
182                && seg.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
183                && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
184        });
185    if !valid {
186        return Err(CodegenError::validation(format!(
187            "{}: java_package `{pkg}` must be a dot-separated Java package identifier (e.g. `io.github.nativeview.modules.image`)",
188            manifest.display()
189        )));
190    }
191    Ok(pkg.to_owned())
192}
193
194fn parse_optional_java_package(
195    nv: Option<&toml::Table>,
196    manifest: &Path,
197) -> Result<Option<String>, CodegenError> {
198    let Some(val) = nv.and_then(|n| n.get("java_package")) else {
199        return Ok(None);
200    };
201    let pkg = val.as_str().ok_or_else(|| {
202        CodegenError::validation(format!(
203            "{}: `[package.metadata.nativeview] java_package` must be a string",
204            manifest.display()
205        ))
206    })?;
207    validate_java_package(pkg, manifest).map(Some)
208}
209
210/// Discovers [`ModuleLayout`]s for every capability module across `roots`: every discovered
211/// [`DirectSpec`] plus every table/policy-only module carrying `[package.metadata.nativeview]` in its
212/// `Cargo.toml` (earlier roots win per `cap_dir` for `--out` overlay).
213pub fn discover_module_layouts_in(
214    roots: &[&Path],
215    specs: &[DirectSpec],
216) -> Result<Vec<ModuleLayout>, CodegenError> {
217    let mut by_cap: std::collections::BTreeMap<String, ModuleLayout> = std::collections::BTreeMap::new();
218    for spec in specs {
219        by_cap.insert(spec.cap_dir.clone(), spec.layout());
220    }
221    for root in roots {
222        for module in sorted_entries(&root.join(MODULES_DIR))? {
223            let Some(cap_dir) = module.file_name().and_then(|n| n.to_str()) else { continue };
224            if by_cap.contains_key(cap_dir) {
225                continue;
226            }
227            let manifest = module.join("Cargo.toml");
228            if !manifest.is_file() {
229                continue;
230            }
231            let text = std::fs::read_to_string(&manifest).map_err(|e| CodegenError::io_path(&manifest, e))?;
232            let parsed: toml::Table = text.parse().map_err(|e| CodegenError::io_path(&manifest, e))?;
233            let Some(nv) = parsed
234                .get("package")
235                .and_then(|p| p.get("metadata"))
236                .and_then(|m| m.get("nativeview"))
237                .and_then(toml::Value::as_table)
238            else {
239                continue;
240            };
241            let swift_raw = nv
242                .get("swift_target")
243                .or_else(|| nv.get("swift_tables_target"))
244                .and_then(toml::Value::as_str);
245            let swift_target = match swift_raw {
246                Some(t) => Some(validate_swift_target(t, &manifest)?),
247                None => None,
248            };
249            let java_package = parse_optional_java_package(Some(nv), &manifest)?;
250            by_cap.insert(
251                cap_dir.to_owned(),
252                ModuleLayout {
253                    cap_dir: cap_dir.to_owned(),
254                    stem: cap_dir.replace('-', "_"),
255                    swift_target,
256                    java_package,
257                    has_direct_spec: false,
258                },
259            );
260        }
261    }
262    Ok(by_cap.into_values().collect())
263}
264
265pub use nativeview_hybrid_spec::source_has_hybrid_spec_attr;
266
267/// Every `packages/modules/*/src/spec.rs` carrying `#[...nativeview_hybrid_spec...]` under `repo_root`,
268/// sorted by path.
269pub fn discover_direct_specs(repo_root: &Path) -> Result<Vec<DirectSpec>, CodegenError> {
270    let mut out = Vec::new();
271    for module in sorted_entries(&repo_root.join(MODULES_DIR))? {
272        let Some(cap_dir) = module.file_name().and_then(|n| n.to_str()) else { continue };
273        let spec = module.join("src/spec.rs");
274        if !spec.is_file() {
275            continue;
276        }
277        let source = std::fs::read_to_string(&spec).map_err(|e| CodegenError::io_path(&spec, e))?;
278        if !source_has_hybrid_spec_attr(&source) {
279            continue;
280        }
281        let spec_rel = format!("{MODULES_DIR}/{cap_dir}/src/spec.rs");
282        let parsed = crate::parse_hybrid_rust_spec(&source)
283            .map_err(|e| CodegenError::validation(format!("{spec_rel}: {e}")))?;
284        let stem = parsed.stem_snake();
285        let (swift_target, java_package) = direct_spec_metadata(&module.join("Cargo.toml"), &spec_rel)?;
286        out.push(DirectSpec { spec_rel, path: spec, cap_dir: cap_dir.to_owned(), stem, swift_target, java_package });
287    }
288    unique_stems(out)
289}
290
291/// Rejects two specs with one stem (`nv/<stem>/` include directories would collide).
292fn unique_stems(specs: Vec<DirectSpec>) -> Result<Vec<DirectSpec>, CodegenError> {
293    for (i, spec) in specs.iter().enumerate() {
294        if let Some(first) = specs[..i].iter().find(|s| s.stem == spec.stem) {
295            return Err(CodegenError::validation(format!(
296                "{} and {} share the spec stem `{}`: their headers would collide under `nv/{}/`; rename one",
297                first.spec_rel, spec.spec_rel, spec.stem, spec.stem
298            )));
299        }
300    }
301    Ok(specs)
302}
303
304/// The host languages a Direct-FFI spec's bindings are generated for (Rust is built in-crate).
305const HOST_TARGETS: &[HybridTarget] =
306    &[HybridTarget::Cpp, HybridTarget::Swift, HybridTarget::Kotlin, HybridTarget::TypeScript, HybridTarget::Dart];
307
308/// Every spec under each of `roots`, the first root winning a `spec_rel` several hold (an
309/// out-of-tree workspace overlaying a checkout), sorted by `spec_rel`.
310pub fn discover_direct_specs_in(roots: &[&Path]) -> Result<Vec<DirectSpec>, CodegenError> {
311    let mut out: Vec<DirectSpec> = Vec::new();
312    for root in roots {
313        for spec in discover_direct_specs(root)? {
314            if !out.iter().any(|s| s.spec_rel == spec.spec_rel) {
315                out.push(spec);
316            }
317        }
318    }
319    out.sort_by(|a, b| a.spec_rel.cmp(&b.spec_rel));
320    unique_stems(out)
321}
322
323/// The C/C++, Swift, Kotlin + JNI, TypeScript and Dart bindings of every spec in `specs`, at
324/// their module-leaf paths.
325pub fn generate_direct_spec_host_files(specs: &[DirectSpec]) -> Result<Vec<GeneratedFile>, CodegenError> {
326    let mut out = Vec::with_capacity(specs.len() * 8);
327    for spec in specs {
328        let in_spec = |e: CodegenError| CodegenError::validation(format!("{}: {e}", spec.spec_rel));
329        let parsed = crate::parse_hybrid_rust_spec_file(&spec.path).map_err(in_spec)?;
330        for bundle in crate::generate_hybrid_all(&parsed, HOST_TARGETS).map_err(in_spec)? {
331            for file in bundle.files {
332                let leaf = match bundle.target {
333                    HybridTarget::Cpp => ModuleLeaf::CxxInclude,
334                    HybridTarget::Swift => ModuleLeaf::AppleSources,
335                    HybridTarget::Kotlin if file.relative_path.ends_with(".kt") => ModuleLeaf::KotlinSources,
336                    HybridTarget::Kotlin => ModuleLeaf::Jni,
337                    HybridTarget::TypeScript => ModuleLeaf::WebTs,
338                    HybridTarget::Dart => ModuleLeaf::DartLib,
339                    HybridTarget::Rust => continue,
340                };
341                out.push(GeneratedFile {
342                    relative_path: format!("{}/{}", spec.leaf_dir(leaf)?, file.relative_path),
343                    content: file.content,
344                });
345            }
346        }
347    }
348    Ok(out)
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    fn minimal_spec(ns: &str, pascal: &str, id: u16) -> String {
356        format!(
357            "#[nativeview_hybrid_macros::nativeview_hybrid_spec(namespace = \"{ns}\")]\n\
358             pub mod ffi {{\n\
359                 #[nv_hybrid_module(name = \"{pascal}\", binding = \"direct\", impl = \"host\", interface_id = 0x{id:04X})]\n\
360                 pub trait {pascal}Spec {{\n\
361                     fn ping(&self) -> Result<bool, NvModStatus>;\n\
362                 }}\n\
363             }}\n\
364             pub use ffi::*;\n"
365        )
366    }
367
368    fn fixture(name: &str, modules: &[(&str, Option<&str>, &str)]) -> std::path::PathBuf {
369        let root = std::env::temp_dir().join(format!("nv_direct_specs_{name}_{}", std::process::id()));
370        let _ = std::fs::remove_dir_all(&root);
371        for (cap, spec_src, manifest) in modules {
372            let dir = root.join(MODULES_DIR).join(cap);
373            std::fs::create_dir_all(dir.join("src")).expect("mkdir");
374            std::fs::write(dir.join("Cargo.toml"), manifest).expect("manifest");
375            if let Some(src) = spec_src {
376                std::fs::write(dir.join("src/spec.rs"), src).expect("spec");
377            }
378        }
379        root
380    }
381
382    const META: &str = "[package]\nname = \"x\"\n\n[package.metadata.nativeview]\nswift_target = \"NativeViewSecureStoreApple\"\n";
383
384    #[test]
385    fn discovers_sorted_specs_with_their_swift_target() {
386        let ss = minimal_spec("secure_store", "SecureStore", 0x2001);
387        let alpha = minimal_spec("alpha", "Alpha", 0x2002);
388        let beta = minimal_spec("beta", "Beta", 0x2003);
389        let plain = "// plain spec.rs mentioning nativeview_hybrid_spec only in a comment\npub const X: u32 = 1;\n";
390        let root = fixture(
391            "ok",
392            &[
393                ("secure-store", Some(&ss), META),
394                ("tv", Some(plain), "[package]\nname = \"nativeview-tv\"\n"),
395                ("alpha", Some(&alpha), &META.replace("SecureStore", "Alpha")),
396            ],
397        );
398        let specs = discover_direct_specs(&root).expect("discover");
399        let rels: Vec<&str> = specs.iter().map(|s| s.spec_rel.as_str()).collect();
400        assert_eq!(rels, ["packages/modules/alpha/src/spec.rs", "packages/modules/secure-store/src/spec.rs"]);
401        let s = &specs[1];
402        assert_eq!((s.cap_dir.as_str(), s.stem.as_str(), s.swift_target.as_str()), ("secure-store", "secure_store", "NativeViewSecureStoreApple"));
403        assert_eq!(s.leaf_dir(ModuleLeaf::CxxInclude).unwrap(), "packages/modules/secure-store/cxx/include/nv/secure_store");
404        assert_eq!(s.leaf_dir(ModuleLeaf::AppleSources).unwrap(), "packages/modules/secure-store/apple/Sources/NativeViewSecureStoreApple");
405        assert_eq!(s.path, root.join(&s.spec_rel));
406        assert!(discover_direct_specs(&root.join("absent")).expect("no modules dir").is_empty());
407        let overlay = fixture("overlay", &[("secure-store", Some(&ss), META), ("beta", Some(&beta), &META.replace("SecureStore", "Beta"))]);
408        let merged = discover_direct_specs_in(&[&overlay, &root]).expect("merge");
409        let rels: Vec<&str> = merged.iter().map(|s| s.spec_rel.as_str()).collect();
410        assert_eq!(rels.len(), 3, "{rels:?}");
411        let store = merged.iter().find(|s| s.cap_dir == "secure-store").expect("store");
412        assert!(store.path.starts_with(&overlay), "the first root wins a shared spec");
413        let _ = std::fs::remove_dir_all(&overlay);
414        let _ = std::fs::remove_dir_all(&root);
415    }
416
417    #[test]
418    fn a_spec_without_valid_metadata_fails_naming_it() {
419        let haptics = minimal_spec("haptics", "Haptics", 0x2004);
420        let error = |name: &str, manifest: &str| {
421            let root = fixture(name, &[("haptics", Some(&haptics), manifest)]);
422            let err = discover_direct_specs(&root).expect_err(name).to_string();
423            let _ = std::fs::remove_dir_all(&root);
424            err
425        };
426        let err = error("missing", "[package]\nname = \"nativeview-haptics\"\n");
427        assert!(err.contains("packages/modules/haptics/src/spec.rs") && err.contains("swift_target"), "{err}");
428        assert!(error("invalid", &META.replace("NativeViewSecureStoreApple", "nativeview-haptics")).contains("PascalCase"));
429        assert!(!error("broken", "[package").is_empty(), "unparsable manifest");
430    }
431
432    #[test]
433    fn duplicate_spec_stems_fail_naming_both() {
434        let shared = minimal_spec("shared", "Shared", 0x2005);
435        let root = fixture(
436            "dup",
437            &[
438                ("alpha", Some(&shared), &META.replace("SecureStore", "Alpha")),
439                ("beta", Some(&shared), &META.replace("SecureStore", "Beta")),
440            ],
441        );
442        let err = discover_direct_specs(&root).expect_err("duplicate stem").to_string();
443        assert!(
444            err.contains("packages/modules/alpha/src/spec.rs") && err.contains("packages/modules/beta/src/spec.rs") && err.contains("nv/shared/"),
445            "{err}"
446        );
447        let other = fixture("dup-overlay", &[("gamma", Some(&shared), &META.replace("SecureStore", "Gamma"))]);
448        let alone = fixture("dup-alone", &[("alpha", Some(&shared), &META.replace("SecureStore", "Alpha"))]);
449        let err = discover_direct_specs_in(&[&other, &alone]).expect_err("duplicate stem across roots").to_string();
450        assert!(err.contains("share the spec stem `shared`"), "{err}");
451        for dir in [root, other, alone] {
452            let _ = std::fs::remove_dir_all(dir);
453        }
454    }
455}