Skip to main content

nativeview_cli/
codegen.rs

1//! `nv codegen` — pure-`nativeview-codegen` user commands (`hybrid`, `import-rn`, `export`) and
2//! monorepo `cargo xtask codegen abi` dispatch helper for local SDK checkouts.
3
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7use clap::Subcommand;
8use nativeview_codegen::{ExportTarget, HybridTarget};
9
10use crate::cargo_env::NvSdkRoot;
11
12#[derive(Subcommand)]
13pub enum CodegenAction {
14    /// Parse a declarative Rust `#[nativeview_hybrid_spec]` spec file and emit binary FFI bindings.
15    Hybrid {
16        /// Path to the declarative Rust `#[nativeview_hybrid_spec]` spec file (`.rs`).
17        spec: PathBuf,
18        /// Target language(s): `rust`, `cpp`, `swift`, `kotlin`, `dart`, `ts`, or `all` (comma-separated allowed).
19        #[arg(long, default_value = "all")]
20        target: String,
21        /// Output root directory (each target writes into `<out>/<target>/`).
22        #[arg(long, default_value = "generated/hybrid")]
23        out: PathBuf,
24    },
25    /// Parse a React Native `*NativeComponent.{ts,js}` or `Native*.{ts,js}` spec and emit zero-JS Rust bindings (plus a C++20 host interface for TurboModules).
26    ImportRn {
27        /// Path to the React Native TypeScript/Flow spec file.
28        spec: PathBuf,
29        /// Output directory for the generated files.
30        #[arg(long, default_value = "generated/import-rn")]
31        out: PathBuf,
32    },
33    /// Export `#[nv_hybrid_view]` declarations from a Rust `#[nativeview_hybrid_spec]` file into native wrappers.
34    Export {
35        /// Path to the declarative Rust `#[nativeview_hybrid_spec]` spec file (`.rs`).
36        spec: PathBuf,
37        /// Target framework(s): `rn`, `nitro-ui`, `web`, `swiftui`, `compose`, `flutter`, or `all` (comma-separated allowed).
38        #[arg(long, default_value = "all")]
39        target: String,
40        /// Output root directory (each target writes into `<out>/<target>/`).
41        #[arg(long, default_value = "generated/export")]
42        out: PathBuf,
43    },
44}
45
46pub fn parse_export_targets(target: &str) -> Result<Vec<ExportTarget>, String> {
47    if target.trim().eq_ignore_ascii_case("all") {
48        return Ok(ExportTarget::ALL.to_vec());
49    }
50    let mut out = Vec::new();
51    for part in target.split(',') {
52        let trimmed = part.trim();
53        if trimmed.is_empty() {
54            return Err("empty target name in comma-separated list".into());
55        }
56        let parsed = ExportTarget::from_name(trimmed)
57            .map_err(|e| format!("invalid target '{trimmed}': {e}"))?;
58        out.push(parsed);
59    }
60    Ok(out)
61}
62
63pub fn parse_hybrid_targets(target: &str) -> Result<Vec<HybridTarget>, String> {
64    if target.trim().eq_ignore_ascii_case("all") {
65        return Ok(HybridTarget::ALL.to_vec());
66    }
67    let mut out = Vec::new();
68    for part in target.split(',') {
69        let trimmed = part.trim();
70        if trimmed.is_empty() {
71            return Err("empty hybrid target name in comma-separated list".into());
72        }
73        let parsed = HybridTarget::from_name(trimmed).ok_or_else(|| {
74            format!(
75                "invalid hybrid target '{trimmed}' (expected rust, cpp, swift, kotlin, dart, ts, or all)"
76            )
77        })?;
78        out.push(parsed);
79    }
80    Ok(out)
81}
82
83/// Ensures generated host ABI headers exist for `sdk_root`:
84/// - Packaged SDKs (`sdk-manifest.json` with `prebuilt_codegen: true`) are strictly read-only:
85///   skips codegen and verifies the pre-materialized `nv_abi.generated.h` header is present.
86/// - Local monorepo checkouts invoke `cargo run --locked -q -p nativeview-xtask -- codegen abi`.
87pub fn ensure_sdk_abi_headers(sdk_root: &NvSdkRoot) -> Result<(), String> {
88    if sdk_root.has_prebuilt_codegen() {
89        let abi_header = sdk_root
90            .path()
91            .join("packages/core/host-cxx/include/nv/generated/nv_abi.generated.h");
92        if !abi_header.is_file() {
93            return Err(format!(
94                "packaged SDK at '{}' declares prebuilt_codegen=true but '{}' is missing (run `nv sdk verify` or reinstall with `nv sdk install`)",
95                sdk_root.path().display(),
96                abi_header.display()
97            ));
98        }
99        return Ok(());
100    }
101    let xtask_manifest = sdk_root.path().join("packages/tools/xtask/Cargo.toml");
102    if !xtask_manifest.is_file() {
103        return Err(format!(
104            "SDK root '{}' has neither `sdk-manifest.json` (`prebuilt_codegen: true`) nor `packages/tools/xtask/Cargo.toml`",
105            sdk_root.path().display()
106        ));
107    }
108    let mut cmd = Command::new("cargo");
109    cmd.current_dir(sdk_root.path()).args(["run"]);
110    if sdk_root.path().join("Cargo.lock").is_file() {
111        cmd.arg("--locked");
112    }
113    cmd.args(["-q", "-p", "nativeview-xtask", "--", "codegen", "abi"]);
114    let status = cmd
115        .status()
116        .map_err(|e| format!("failed to run `cargo xtask codegen abi`: {e}"))?;
117    if !status.success() {
118        return Err(format!("`cargo xtask codegen abi` exited with {status}"));
119    }
120    Ok(())
121}
122
123pub fn run_codegen_export(
124    spec_path: &Path,
125    target: &str,
126    out_root: &Path,
127) -> Result<Vec<(ExportTarget, PathBuf, Vec<PathBuf>)>, String> {
128    let targets = parse_export_targets(target)?;
129    let spec = nativeview_codegen::parse_hybrid_rust_spec_file(spec_path)
130        .map_err(|e| format!("hybrid spec parse failed for {}: {e}", spec_path.display()))?;
131    if spec.views.is_empty() {
132        return Err(format!(
133            "export failed for {}: spec declares no #[nv_hybrid_view] traits",
134            spec_path.display()
135        ));
136    }
137    let bundles = nativeview_codegen::export_all_targets(&spec, &targets)
138        .map_err(|e| format!("export failed for {}: {e}", spec_path.display()))?;
139
140    let mut summary = Vec::with_capacity(bundles.len());
141    for bundle in bundles {
142        let target_dir = out_root.join(bundle.target.dir_name());
143        let written = bundle
144            .write_to_dir(&target_dir)
145            .map_err(|e| format!("failed writing {} output: {e}", bundle.target.dir_name()))?;
146        summary.push((bundle.target, target_dir, written));
147    }
148    Ok(summary)
149}
150
151pub fn run_codegen_hybrid(
152    spec_path: &Path,
153    target: &str,
154    out_root: &Path,
155) -> Result<Vec<(HybridTarget, PathBuf, Vec<PathBuf>)>, String> {
156    let targets = parse_hybrid_targets(target)?;
157    let spec = nativeview_codegen::parse_hybrid_rust_spec_file(spec_path)
158        .map_err(|e| format!("hybrid spec parse failed for {}: {e}", spec_path.display()))?;
159    let outputs = nativeview_codegen::generate_hybrid_all(&spec, &targets)
160        .map_err(|e| format!("hybrid codegen failed for {}: {e}", spec_path.display()))?;
161
162    let mut summary = Vec::with_capacity(outputs.len());
163    for bundle in outputs {
164        let target_dir = out_root.join(bundle.target.dir_name());
165        let written = bundle
166            .write_to_dir(&target_dir)
167            .map_err(|e| format!("failed writing {} output: {e}", bundle.target.dir_name()))?;
168        summary.push((bundle.target, target_dir, written));
169    }
170    Ok(summary)
171}
172
173pub fn cmd_codegen(action: CodegenAction) {
174    match action {
175        CodegenAction::Hybrid { spec, target, out } => {
176            let summary = run_codegen_hybrid(&spec, &target, &out).unwrap_or_else(|e| {
177                eprintln!("{e}");
178                std::process::exit(1);
179            });
180            for (tgt, target_dir, written) in summary {
181                println!(
182                    "[{}] wrote {} file(s) -> {}",
183                    tgt.dir_name(),
184                    written.len(),
185                    target_dir.display()
186                );
187                for path in written {
188                    println!("  - {}", path.display());
189                }
190            }
191        }
192        CodegenAction::ImportRn { spec, out } => {
193            let generated = nativeview_codegen::import_rn_file(&spec).unwrap_or_else(|e| {
194                eprintln!("import-rn failed for {}: {e}", spec.display());
195                std::process::exit(1);
196            });
197            let written = generated.write_to_dir(&out).unwrap_or_else(|e| {
198                eprintln!("failed writing output to {}: {e}", out.display());
199                std::process::exit(1);
200            });
201            println!("Generated {} files in {}:", written.len(), out.display());
202            for path in written {
203                println!("  - {}", path.display());
204            }
205        }
206        CodegenAction::Export { spec, target, out } => {
207            let summary = run_codegen_export(&spec, &target, &out).unwrap_or_else(|e| {
208                eprintln!("{e}");
209                std::process::exit(1);
210            });
211            for (tgt, target_dir, written) in summary {
212                println!(
213                    "[{}] wrote {} file(s) -> {}",
214                    tgt.dir_name(),
215                    written.len(),
216                    target_dir.display()
217                );
218                for path in written {
219                    println!("  - {}", path.display());
220                }
221            }
222        }
223    }
224}