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
//! Discovery of the Direct-FFI capability specs `nv codegen abi` renders, and the module-leaf
//! layout their host bindings (and module-homed `nv_policy!` constants) land in.
//!
//! Every `packages/modules/<cap>/src/spec.rs` carrying a `#[nativeview_hybrid_spec]` module is a spec: no
//! registration list exists (`[INV:direct-ffi-specs-discovered]`). `<cap>` comes from the path,
//! `<stem>` from `parsed.stem_snake()`, and the Swift target directory from the module root crate's
//! `packages/modules/<cap>/Cargo.toml`:
//!
//! ```toml
//! [package.metadata.nativeview]
//! swift_target = "Nv<Pascal>Apple"
//! ```
//!
//! A spec whose module lacks that key fails discovery with a message naming the file, and two
//! specs with one stem fail it too: their C/C++ headers would collide under `nv/<stem>/` on the
//! shared include path.

use std::path::{Path, PathBuf};

use crate::error::CodegenError;
use crate::schema::export::GeneratedFile;
use crate::schema::hybrid::HybridTarget;

/// Parent of every capability module.
pub const MODULES_DIR: &str = "packages/modules";

/// One discovered `src/spec.rs` Direct-FFI spec and the module it belongs to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DirectSpec {
    /// Repository-relative spec path (`packages/modules/<cap>/src/spec.rs`).
    pub spec_rel: String,
    /// The spec file as found on disk (`<repo root>/<spec_rel>`).
    pub path: PathBuf,
    /// Module directory name (`secure-store`).
    pub cap_dir: String,
    /// Spec namespace/stem (`secure_store`): the C/C++ include directory under `cxx/include/nv/`.
    pub stem: String,
    /// `[package.metadata.nativeview] swift_target`: the `apple/Sources/<target>` directory.
    pub swift_target: String,
    /// Optional `[package.metadata.nativeview] java_package` (e.g. `io.github.nativeview.modules.secure_store`).
    pub java_package: Option<String>,
}

/// A module leaf directory generated host sources land in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ModuleLeaf {
    CxxInclude,
    AppleSources,
    JavaGenerated,
    KotlinSources,
    Jni,
    WebTs,
    DartLib,
}

impl DirectSpec {
    /// `packages/modules/<cap>/<leaf dir>`, unified with [`ModuleLayout::leaf_dir`].
    pub fn leaf_dir(&self, leaf: ModuleLeaf) -> Result<String, CodegenError> {
        self.layout().leaf_dir(leaf)
    }

    /// Converts this Direct-FFI spec into a generic [`ModuleLayout`].
    pub fn layout(&self) -> ModuleLayout {
        ModuleLayout {
            cap_dir: self.cap_dir.clone(),
            stem: self.stem.clone(),
            swift_target: Some(self.swift_target.clone()),
            java_package: self.java_package.clone(),
            has_direct_spec: true,
        }
    }
}

/// Discovered leaf layout of any capability module under `packages/modules/<cap>`, whether backed
/// by a Direct-FFI `src/spec.rs` or a table/policy-only `[package.metadata.nativeview]` manifest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ModuleLayout {
    /// Module directory name (`image`, `secure-store`).
    pub cap_dir: String,
    /// C/C++ include stem (`image`, `secure_store`).
    pub stem: String,
    /// Optional `[package.metadata.nativeview]` `swift_target` / `swift_tables_target`.
    pub swift_target: Option<String>,
    /// Optional `[package.metadata.nativeview]` `java_package` (e.g. `io.github.nativeview.modules.image`).
    pub java_package: Option<String>,
    /// `true` for Direct-FFI modules (`web/ts`), `false` for table/policy-only modules (`ts`).
    pub has_direct_spec: bool,
}

impl ModuleLayout {
    /// `packages/modules/<cap>/<leaf dir>`, failing clearly if `AppleSources` or `JavaGenerated`
    /// is requested for a module without the required `[package.metadata.nativeview]` metadata.
    pub fn leaf_dir(&self, leaf: ModuleLeaf) -> Result<String, CodegenError> {
        let root = format!("{MODULES_DIR}/{}", self.cap_dir);
        Ok(match leaf {
            ModuleLeaf::CxxInclude => format!("{root}/cxx/include/nv/{}", self.stem),
            ModuleLeaf::AppleSources => {
                let target = self.swift_target.as_deref().ok_or_else(|| {
                    CodegenError::validation(format!(
                        "module `{}` has no `[package.metadata.nativeview] swift_target` for Swift output",
                        self.cap_dir
                    ))
                })?;
                format!("{root}/apple/Sources/{target}")
            }
            ModuleLeaf::JavaGenerated => {
                let pkg = self.java_package.as_deref().ok_or_else(|| {
                    CodegenError::validation(format!(
                        "module `{}` has no `[package.metadata.nativeview] java_package` for Java output",
                        self.cap_dir
                    ))
                })?;
                format!("{root}/android/src/main/java/{}/generated", pkg.replace('.', "/"))
            }
            ModuleLeaf::KotlinSources => format!("{root}/android/src/main/kotlin/io/github/nativeview/hybrid"),
            ModuleLeaf::Jni => format!("{root}/android/jni"),
            ModuleLeaf::WebTs => {
                if self.has_direct_spec {
                    format!("{root}/web/ts")
                } else {
                    format!("{root}/ts")
                }
            }
            ModuleLeaf::DartLib => format!("{root}/dart/lib/src"),
        })
    }
}


/// Sorted entries of `dir` (an absent directory has none).
fn sorted_entries(dir: &Path) -> Result<Vec<std::path::PathBuf>, CodegenError> {
    if !dir.is_dir() {
        return Ok(Vec::new());
    }
    let mut out = std::fs::read_dir(dir)
        .map_err(|e| CodegenError::io_path(dir, e))?
        .map(|entry| entry.map(|e| e.path()).map_err(|e| CodegenError::io_path(dir, e)))
        .collect::<Result<Vec<_>, _>>()?;
    out.sort();
    Ok(out)
}

/// `[package.metadata.nativeview]` (`swift_target`, optional `java_package`) of `manifest`.
fn direct_spec_metadata(manifest: &Path, spec_rel: &str) -> Result<(String, Option<String>), CodegenError> {
    let text = std::fs::read_to_string(manifest).map_err(|e| CodegenError::io_path(manifest, e))?;
    let table: toml::Table = text.parse().map_err(|e| CodegenError::io_path(manifest, e))?;
    let nv = table
        .get("package")
        .and_then(|p| p.get("metadata"))
        .and_then(|m| m.get("nativeview"))
        .and_then(toml::Value::as_table);
    let target = nv
        .and_then(|n| n.get("swift_target"))
        .and_then(toml::Value::as_str)
        .ok_or_else(|| {
            CodegenError::validation(format!(
                "{spec_rel}: its module manifest {} has no `[package.metadata.nativeview] swift_target = \"Nv<Pascal>Apple\"`",
                manifest.display()
            ))
        })?;
    let swift_target = validate_swift_target(target, manifest)?;
    let java_package = parse_optional_java_package(nv, manifest)?;
    Ok((swift_target, java_package))
}

fn validate_swift_target(target: &str, manifest: &Path) -> Result<String, CodegenError> {
    let valid = target.chars().next().is_some_and(|c| c.is_ascii_uppercase())
        && target.chars().all(|c| c.is_ascii_alphanumeric());
    if !valid {
        return Err(CodegenError::validation(format!(
            "{}: swift_target `{target}` must be a PascalCase Swift target name",
            manifest.display()
        )));
    }
    Ok(target.to_owned())
}

fn validate_java_package(pkg: &str, manifest: &Path) -> Result<String, CodegenError> {
    let valid = !pkg.is_empty()
        && pkg.split('.').all(|seg| {
            !seg.is_empty()
                && seg.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
                && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        });
    if !valid {
        return Err(CodegenError::validation(format!(
            "{}: java_package `{pkg}` must be a dot-separated Java package identifier (e.g. `io.github.nativeview.modules.image`)",
            manifest.display()
        )));
    }
    Ok(pkg.to_owned())
}

fn parse_optional_java_package(
    nv: Option<&toml::Table>,
    manifest: &Path,
) -> Result<Option<String>, CodegenError> {
    let Some(val) = nv.and_then(|n| n.get("java_package")) else {
        return Ok(None);
    };
    let pkg = val.as_str().ok_or_else(|| {
        CodegenError::validation(format!(
            "{}: `[package.metadata.nativeview] java_package` must be a string",
            manifest.display()
        ))
    })?;
    validate_java_package(pkg, manifest).map(Some)
}

/// Discovers [`ModuleLayout`]s for every capability module across `roots`: every discovered
/// [`DirectSpec`] plus every table/policy-only module carrying `[package.metadata.nativeview]` in its
/// `Cargo.toml` (earlier roots win per `cap_dir` for `--out` overlay).
pub fn discover_module_layouts_in(
    roots: &[&Path],
    specs: &[DirectSpec],
) -> Result<Vec<ModuleLayout>, CodegenError> {
    let mut by_cap: std::collections::BTreeMap<String, ModuleLayout> = std::collections::BTreeMap::new();
    for spec in specs {
        by_cap.insert(spec.cap_dir.clone(), spec.layout());
    }
    for root in roots {
        for module in sorted_entries(&root.join(MODULES_DIR))? {
            let Some(cap_dir) = module.file_name().and_then(|n| n.to_str()) else { continue };
            if by_cap.contains_key(cap_dir) {
                continue;
            }
            let manifest = module.join("Cargo.toml");
            if !manifest.is_file() {
                continue;
            }
            let text = std::fs::read_to_string(&manifest).map_err(|e| CodegenError::io_path(&manifest, e))?;
            let parsed: toml::Table = text.parse().map_err(|e| CodegenError::io_path(&manifest, e))?;
            let Some(nv) = parsed
                .get("package")
                .and_then(|p| p.get("metadata"))
                .and_then(|m| m.get("nativeview"))
                .and_then(toml::Value::as_table)
            else {
                continue;
            };
            let swift_raw = nv
                .get("swift_target")
                .or_else(|| nv.get("swift_tables_target"))
                .and_then(toml::Value::as_str);
            let swift_target = match swift_raw {
                Some(t) => Some(validate_swift_target(t, &manifest)?),
                None => None,
            };
            let java_package = parse_optional_java_package(Some(nv), &manifest)?;
            by_cap.insert(
                cap_dir.to_owned(),
                ModuleLayout {
                    cap_dir: cap_dir.to_owned(),
                    stem: cap_dir.replace('-', "_"),
                    swift_target,
                    java_package,
                    has_direct_spec: false,
                },
            );
        }
    }
    Ok(by_cap.into_values().collect())
}

pub use nativeview_hybrid_spec::source_has_hybrid_spec_attr;

/// Every `packages/modules/*/src/spec.rs` carrying `#[...nativeview_hybrid_spec...]` under `repo_root`,
/// sorted by path.
pub fn discover_direct_specs(repo_root: &Path) -> Result<Vec<DirectSpec>, CodegenError> {
    let mut out = Vec::new();
    for module in sorted_entries(&repo_root.join(MODULES_DIR))? {
        let Some(cap_dir) = module.file_name().and_then(|n| n.to_str()) else { continue };
        let spec = module.join("src/spec.rs");
        if !spec.is_file() {
            continue;
        }
        let source = std::fs::read_to_string(&spec).map_err(|e| CodegenError::io_path(&spec, e))?;
        if !source_has_hybrid_spec_attr(&source) {
            continue;
        }
        let spec_rel = format!("{MODULES_DIR}/{cap_dir}/src/spec.rs");
        let parsed = crate::parse_hybrid_rust_spec(&source)
            .map_err(|e| CodegenError::validation(format!("{spec_rel}: {e}")))?;
        let stem = parsed.stem_snake();
        let (swift_target, java_package) = direct_spec_metadata(&module.join("Cargo.toml"), &spec_rel)?;
        out.push(DirectSpec { spec_rel, path: spec, cap_dir: cap_dir.to_owned(), stem, swift_target, java_package });
    }
    unique_stems(out)
}

/// Rejects two specs with one stem (`nv/<stem>/` include directories would collide).
fn unique_stems(specs: Vec<DirectSpec>) -> Result<Vec<DirectSpec>, CodegenError> {
    for (i, spec) in specs.iter().enumerate() {
        if let Some(first) = specs[..i].iter().find(|s| s.stem == spec.stem) {
            return Err(CodegenError::validation(format!(
                "{} and {} share the spec stem `{}`: their headers would collide under `nv/{}/`; rename one",
                first.spec_rel, spec.spec_rel, spec.stem, spec.stem
            )));
        }
    }
    Ok(specs)
}

/// The host languages a Direct-FFI spec's bindings are generated for (Rust is built in-crate).
const HOST_TARGETS: &[HybridTarget] =
    &[HybridTarget::Cpp, HybridTarget::Swift, HybridTarget::Kotlin, HybridTarget::TypeScript, HybridTarget::Dart];

/// Every spec under each of `roots`, the first root winning a `spec_rel` several hold (an
/// out-of-tree workspace overlaying a checkout), sorted by `spec_rel`.
pub fn discover_direct_specs_in(roots: &[&Path]) -> Result<Vec<DirectSpec>, CodegenError> {
    let mut out: Vec<DirectSpec> = Vec::new();
    for root in roots {
        for spec in discover_direct_specs(root)? {
            if !out.iter().any(|s| s.spec_rel == spec.spec_rel) {
                out.push(spec);
            }
        }
    }
    out.sort_by(|a, b| a.spec_rel.cmp(&b.spec_rel));
    unique_stems(out)
}

/// The C/C++, Swift, Kotlin + JNI, TypeScript and Dart bindings of every spec in `specs`, at
/// their module-leaf paths.
pub fn generate_direct_spec_host_files(specs: &[DirectSpec]) -> Result<Vec<GeneratedFile>, CodegenError> {
    let mut out = Vec::with_capacity(specs.len() * 8);
    for spec in specs {
        let in_spec = |e: CodegenError| CodegenError::validation(format!("{}: {e}", spec.spec_rel));
        let parsed = crate::parse_hybrid_rust_spec_file(&spec.path).map_err(in_spec)?;
        for bundle in crate::generate_hybrid_all(&parsed, HOST_TARGETS).map_err(in_spec)? {
            for file in bundle.files {
                let leaf = match bundle.target {
                    HybridTarget::Cpp => ModuleLeaf::CxxInclude,
                    HybridTarget::Swift => ModuleLeaf::AppleSources,
                    HybridTarget::Kotlin if file.relative_path.ends_with(".kt") => ModuleLeaf::KotlinSources,
                    HybridTarget::Kotlin => ModuleLeaf::Jni,
                    HybridTarget::TypeScript => ModuleLeaf::WebTs,
                    HybridTarget::Dart => ModuleLeaf::DartLib,
                    HybridTarget::Rust => continue,
                };
                out.push(GeneratedFile {
                    relative_path: format!("{}/{}", spec.leaf_dir(leaf)?, file.relative_path),
                    content: file.content,
                });
            }
        }
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn minimal_spec(ns: &str, pascal: &str, id: u16) -> String {
        format!(
            "#[nativeview_hybrid_macros::nativeview_hybrid_spec(namespace = \"{ns}\")]\n\
             pub mod ffi {{\n\
                 #[nv_hybrid_module(name = \"{pascal}\", binding = \"direct\", impl = \"host\", interface_id = 0x{id:04X})]\n\
                 pub trait {pascal}Spec {{\n\
                     fn ping(&self) -> Result<bool, NvModStatus>;\n\
                 }}\n\
             }}\n\
             pub use ffi::*;\n"
        )
    }

    fn fixture(name: &str, modules: &[(&str, Option<&str>, &str)]) -> std::path::PathBuf {
        let root = std::env::temp_dir().join(format!("nv_direct_specs_{name}_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        for (cap, spec_src, manifest) in modules {
            let dir = root.join(MODULES_DIR).join(cap);
            std::fs::create_dir_all(dir.join("src")).expect("mkdir");
            std::fs::write(dir.join("Cargo.toml"), manifest).expect("manifest");
            if let Some(src) = spec_src {
                std::fs::write(dir.join("src/spec.rs"), src).expect("spec");
            }
        }
        root
    }

    const META: &str = "[package]\nname = \"x\"\n\n[package.metadata.nativeview]\nswift_target = \"NativeViewSecureStoreApple\"\n";

    #[test]
    fn discovers_sorted_specs_with_their_swift_target() {
        let ss = minimal_spec("secure_store", "SecureStore", 0x2001);
        let alpha = minimal_spec("alpha", "Alpha", 0x2002);
        let beta = minimal_spec("beta", "Beta", 0x2003);
        let plain = "// plain spec.rs mentioning nativeview_hybrid_spec only in a comment\npub const X: u32 = 1;\n";
        let root = fixture(
            "ok",
            &[
                ("secure-store", Some(&ss), META),
                ("tv", Some(plain), "[package]\nname = \"nativeview-tv\"\n"),
                ("alpha", Some(&alpha), &META.replace("SecureStore", "Alpha")),
            ],
        );
        let specs = discover_direct_specs(&root).expect("discover");
        let rels: Vec<&str> = specs.iter().map(|s| s.spec_rel.as_str()).collect();
        assert_eq!(rels, ["packages/modules/alpha/src/spec.rs", "packages/modules/secure-store/src/spec.rs"]);
        let s = &specs[1];
        assert_eq!((s.cap_dir.as_str(), s.stem.as_str(), s.swift_target.as_str()), ("secure-store", "secure_store", "NativeViewSecureStoreApple"));
        assert_eq!(s.leaf_dir(ModuleLeaf::CxxInclude).unwrap(), "packages/modules/secure-store/cxx/include/nv/secure_store");
        assert_eq!(s.leaf_dir(ModuleLeaf::AppleSources).unwrap(), "packages/modules/secure-store/apple/Sources/NativeViewSecureStoreApple");
        assert_eq!(s.path, root.join(&s.spec_rel));
        assert!(discover_direct_specs(&root.join("absent")).expect("no modules dir").is_empty());
        let overlay = fixture("overlay", &[("secure-store", Some(&ss), META), ("beta", Some(&beta), &META.replace("SecureStore", "Beta"))]);
        let merged = discover_direct_specs_in(&[&overlay, &root]).expect("merge");
        let rels: Vec<&str> = merged.iter().map(|s| s.spec_rel.as_str()).collect();
        assert_eq!(rels.len(), 3, "{rels:?}");
        let store = merged.iter().find(|s| s.cap_dir == "secure-store").expect("store");
        assert!(store.path.starts_with(&overlay), "the first root wins a shared spec");
        let _ = std::fs::remove_dir_all(&overlay);
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_spec_without_valid_metadata_fails_naming_it() {
        let haptics = minimal_spec("haptics", "Haptics", 0x2004);
        let error = |name: &str, manifest: &str| {
            let root = fixture(name, &[("haptics", Some(&haptics), manifest)]);
            let err = discover_direct_specs(&root).expect_err(name).to_string();
            let _ = std::fs::remove_dir_all(&root);
            err
        };
        let err = error("missing", "[package]\nname = \"nativeview-haptics\"\n");
        assert!(err.contains("packages/modules/haptics/src/spec.rs") && err.contains("swift_target"), "{err}");
        assert!(error("invalid", &META.replace("NativeViewSecureStoreApple", "nativeview-haptics")).contains("PascalCase"));
        assert!(!error("broken", "[package").is_empty(), "unparsable manifest");
    }

    #[test]
    fn duplicate_spec_stems_fail_naming_both() {
        let shared = minimal_spec("shared", "Shared", 0x2005);
        let root = fixture(
            "dup",
            &[
                ("alpha", Some(&shared), &META.replace("SecureStore", "Alpha")),
                ("beta", Some(&shared), &META.replace("SecureStore", "Beta")),
            ],
        );
        let err = discover_direct_specs(&root).expect_err("duplicate stem").to_string();
        assert!(
            err.contains("packages/modules/alpha/src/spec.rs") && err.contains("packages/modules/beta/src/spec.rs") && err.contains("nv/shared/"),
            "{err}"
        );
        let other = fixture("dup-overlay", &[("gamma", Some(&shared), &META.replace("SecureStore", "Gamma"))]);
        let alone = fixture("dup-alone", &[("alpha", Some(&shared), &META.replace("SecureStore", "Alpha"))]);
        let err = discover_direct_specs_in(&[&other, &alone]).expect_err("duplicate stem across roots").to_string();
        assert!(err.contains("share the spec stem `shared`"), "{err}");
        for dir in [root, other, alone] {
            let _ = std::fs::remove_dir_all(dir);
        }
    }
}