Skip to main content

nativeview_codegen/targets/c_cpp/hybrid/
mod.rs

1//! C11 & C++20 target emitter for NV Hybrid FFI codegen.
2//!
3//! Emits two clean, binary FFI headers:
4//! 1. `<Stem>HybridAbi.generated.h`: pure C11 header including `nv_abi.generated.h`, declaring
5//!    `NV_HYBRID_<NAME>_INTERFACE_ID`, `NV_HYBRID_<NAME>_SCHEMA_HASH`, `#[repr(C)]` POD
6//!    structs/enums, `NvHybridOwnedBytes`, POD `NvHybridOpt*`, and `NvHybrid<Name>VTable`.
7//! 2. `<Stem>HybridSpec.generated.hpp`: C++20 `namespace nv::hybrid` with `enum class`, native
8//!    structs with `NvBinValue` `encode_bin` / `decode_bin` over the static `nv::host_cxx`
9//!    runtime (`packages/core/host-cxx`), Nitro-style abstract `class Hybrid<Name>Spec`, and RAII
10//!    `class <Name>Client` resolving `nv_get_interface` + checking `schema_hash` on construction.
11
12mod bin_emitter;
13mod client_emitter;
14mod codec_emitter;
15mod direct;
16mod type_helpers;
17
18// The JNI glue includes the C++ client, so it reuses its codec emitters.
19pub(crate) use bin_emitter::{emit_cpp_bin_read, emit_cpp_bin_write};
20pub(crate) use direct::c_emitter::push_c11_direct_params;
21pub(crate) use direct::cpp::emitter::{c11_pod_type, cpp_to_c11_scalar};
22pub(crate) use direct::codec::{emit_cpp_wire_read, emit_cpp_wire_write};
23pub(crate) use type_helpers::cpp_owned_type;
24
25use std::collections::BTreeSet;
26
27use crate::targets::direct_model::{enum_repr_c_type, spec_has_direct_modules};
28use crate::writer::CodeWriter;
29use codec_emitter::emit_cpp20_spec;
30use direct::c_emitter::emit_c11_direct_module;
31use type_helpers::{
32    c_abi_struct_fields, c_fn_type, c_param_type, c_return_type, require_c_value_type,
33};
34
35use crate::error::CodegenError;
36use crate::naming::{
37    c_field_ident, cpp_ident, escape_c_like_string, format_float_literal, to_camel_case,
38    to_pascal_case, to_snake_case,
39};
40use crate::schema::export::GeneratedFile;
41use crate::schema::hybrid::{
42    HybridBinding, HybridDefaultValue, HybridEnumSpec, HybridFileSpec, HybridMethodSpec,
43    HybridModuleSpec, HybridStructSpec, HybridType, HybridViewSpec, NV_HYBRID_ABI_VERSION,
44    PodOptionScope,
45};
46
47/// Emits `<Stem>HybridAbi.generated.h` (pure C11 ABI), `<Stem>HybridSpec.generated.hpp` (C++20),
48/// and `<Stem>HybridWire.generated.h` (pure C11 positional wire codec & direct host helpers).
49pub fn generate_hybrid_cpp(spec: &HybridFileSpec) -> Result<Vec<GeneratedFile>, CodegenError> {
50    spec.validate()?;
51    let stem = spec.stem_pascal();
52    let header_name = format!("{stem}HybridAbi.generated.h");
53    let hpp_name = format!("{stem}HybridSpec.generated.hpp");
54    let wire_name = format!("{stem}HybridWire.generated.h");
55
56    let c_header = emit_c11_header(spec)?;
57    let cpp_header = emit_cpp20_spec(spec, &header_name);
58    let c11_wire_header = direct::c11_wire_codec::emit_c11_wire_header(spec, &header_name);
59
60    Ok(vec![
61        GeneratedFile {
62            relative_path: header_name,
63            content: c_header,
64        },
65        GeneratedFile {
66            relative_path: hpp_name,
67            content: cpp_header,
68        },
69        GeneratedFile {
70            relative_path: wire_name,
71            content: c11_wire_header,
72        },
73    ])
74}
75
76fn emit_c11_header(spec: &HybridFileSpec) -> Result<String, CodegenError> {
77    let mut out = CodeWriter::with_capacity(8 * 1024);
78    writeln!(
79        out,
80        "// @generated by nativeview-codegen (hybrid C11 ABI header) — DO NOT EDIT."
81    );
82    writeln!(out, "#pragma once");
83    writeln!(out);
84    writeln!(out, "#include <stdbool.h>");
85    writeln!(out, "#include <stddef.h>");
86    writeln!(out, "#include <stdint.h>");
87    writeln!(out, "#define NV_DETAIL_USE_CLANG_CNVABI_MODULE 0");
88    writeln!(out, "#if defined(__clang__)");
89    writeln!(out, "#if defined(__has_feature) && defined(__has_include)");
90    writeln!(out, "#if __has_feature(modules) && !__has_include(<nv/generated/nv_abi.generated.h>)");
91    writeln!(out, "#undef NV_DETAIL_USE_CLANG_CNVABI_MODULE");
92    writeln!(out, "#define NV_DETAIL_USE_CLANG_CNVABI_MODULE 1");
93    writeln!(out, "#endif");
94    writeln!(out, "#endif");
95    writeln!(out, "#endif");
96    writeln!(out, "#if NV_DETAIL_USE_CLANG_CNVABI_MODULE");
97    writeln!(out, "#pragma clang module import CNvAbi");
98    writeln!(out, "#else");
99    writeln!(out, "#include <nv/generated/nv_abi.generated.h>");
100    writeln!(out, "#endif");
101    writeln!(out, "#undef NV_DETAIL_USE_CLANG_CNVABI_MODULE");
102    writeln!(out);
103    writeln!(out, "#ifdef __cplusplus");
104    writeln!(out, "extern \"C\" {{");
105    writeln!(out, "#endif");
106    writeln!(out);
107
108    let has_legacy = spec
109        .modules
110        .iter()
111        .any(|m| m.binding != HybridBinding::Direct)
112        || !spec.views.is_empty()
113        || !spec.c_functions.is_empty();
114    if has_legacy {
115        writeln!(out, "#ifndef NV_HYBRID_ABI_COMMON_DEFINED");
116        writeln!(out, "#define NV_HYBRID_ABI_COMMON_DEFINED 1");
117        writeln!(
118            out,
119            "#define NV_HYBRID_ABI_VERSION {NV_HYBRID_ABI_VERSION}u"
120        );
121        writeln!(out);
122        writeln!(out, "typedef enum NvHybridStatus {{");
123        writeln!(out, "  NV_HYBRID_OK = 0,");
124        writeln!(out, "  NV_HYBRID_ERR = 1,");
125        writeln!(out, "  NV_HYBRID_ERR_INVALID_ARG = 2,");
126        writeln!(out, "  NV_HYBRID_ERR_SCHEMA_MISMATCH = 3,");
127        writeln!(out, "  NV_HYBRID_ERR_NULL_HANDLE = 4,");
128        writeln!(out, "}} NvHybridStatus;");
129        writeln!(out);
130        writeln!(out, "typedef struct NvHybridOwnedBytes {{");
131        writeln!(out, "  uint8_t* ptr;");
132        writeln!(out, "  size_t len;");
133        writeln!(out, "  size_t cap;");
134        writeln!(out, "}} NvHybridOwnedBytes;");
135        writeln!(out, "#endif /* NV_HYBRID_ABI_COMMON_DEFINED */");
136        writeln!(out);
137    }
138
139    writeln!(
140        out,
141        "#define NV_HYBRID_{}_FILE_SCHEMA_HASH UINT64_C(0x{:016X})",
142        to_snake_case(&spec.stem_pascal()).to_ascii_uppercase(),
143        spec.file_schema_hash()
144    );
145    writeln!(out);
146
147    // Enums honoring exact `#[repr(u8|u16|u32|i32)]` width across C11/C++/Swift/Rust/Dart
148    for e in &spec.enums {
149        let e_upper = to_snake_case(&e.name).to_ascii_uppercase();
150        let c_repr = enum_repr_c_type(e.repr_str());
151        let suffix = if e.repr_str() == "i32" { "" } else { "u" };
152        writeln!(out, "typedef {c_repr} NvHybrid{};", e.name);
153        writeln!(out, "enum {{");
154        for v in &e.variants {
155            let v_upper = to_snake_case(&v.name).to_ascii_uppercase();
156            writeln!(out, "  NV_HYBRID_{e_upper}_{v_upper} = {}{suffix},", v.value);
157        }
158        writeln!(out, "}};");
159        writeln!(out);
160    }
161
162    // POD & direct C-ABI view structs (topological order so embedded POD fields are always complete)
163    for s in spec.structs_topological() {
164        let Some(decls) = c_abi_struct_fields(s, spec) else {
165            continue;
166        };
167        writeln!(out, "typedef struct NvHybrid{} {{", s.name);
168        for decl in decls {
169            writeln!(out, "  {decl};");
170        }
171        writeln!(out, "}} NvHybrid{};", s.name);
172        if let Some(sz) = s.expected_size {
173            writeln!(
174                out,
175                "NV_STATIC_ASSERT(sizeof(NvHybrid{}) == {sz}u, \"NvHybrid{} size must be {sz}\");",
176                s.name, s.name
177            );
178        }
179        if let Some(sz64) = s.expected_size_64 {
180            writeln!(
181                out,
182                "NV_STATIC_ASSERT(sizeof(void*) != 8 || sizeof(NvHybrid{}) == {sz64}u, \"NvHybrid{} size must be {sz64} on 64-bit\");",
183                s.name, s.name
184            );
185        }
186        for f in &s.fields {
187            let fname = c_field_ident(&f.name);
188            if let Some(off) = f.offset {
189                writeln!(
190                    out,
191                    "NV_STATIC_ASSERT(offsetof(NvHybrid{}, {fname}) == {off}u, \"NvHybrid{}::{fname} offset must be {off}\");",
192                    s.name, s.name
193                );
194            }
195            if let Some(off64) = f.offset_64 {
196                writeln!(
197                    out,
198                    "NV_STATIC_ASSERT(sizeof(void*) != 8 || offsetof(NvHybrid{}, {fname}) == {off64}u, \"NvHybrid{}::{fname} offset must be {off64} on 64-bit\");",
199                    s.name, s.name
200                );
201            }
202        }
203        writeln!(out);
204    }
205
206    // POD Optional<T> structs (uint8_t tag + uint8_t bool value match Rust #[repr(C)] u8 and avoid C _Bool / Swift Bool UB)
207    for (suffix, inner) in spec.collect_pod_option_types(PodOptionScope::WithCFunctions) {
208        let field_ty = if matches!(inner, HybridType::Bool) {
209            "uint8_t".to_string()
210        } else {
211            require_c_value_type(&inner, spec)?
212        };
213        writeln!(out, "typedef struct NvHybridOpt{suffix} {{");
214        writeln!(out, "  uint8_t is_some;");
215        writeln!(out, "  {field_ty} value;");
216        writeln!(out, "}} NvHybridOpt{suffix};");
217        writeln!(out);
218    }
219
220    // Direct static `extern "C"` functions (default for statically linked builds; zero vtable, LTO-inlinable)
221    if !spec.c_functions.is_empty() {
222        // Opaque handles: structs without a C form that C functions point to are incomplete
223        // file-scope typedefs (a tag first named in a prototype would be scoped to it).
224        let opaque: BTreeSet<&str> = spec
225            .c_functions
226            .iter()
227            .flat_map(|f| f.params.iter().map(|p| &p.ty).chain([&f.return_type]))
228            .filter_map(|ty| match ty {
229                HybridType::ConstPtr(inner) | HybridType::MutPtr(inner) => match inner.as_ref() {
230                    HybridType::Struct(name) => Some(name.as_str()),
231                    _ => None,
232                },
233                _ => None,
234            })
235            .filter(|name| spec.find_struct(name).is_none_or(|s| c_abi_struct_fields(s, spec).is_none()))
236            .collect();
237        for name in &opaque {
238            writeln!(out, "typedef struct NvHybrid{name} NvHybrid{name};");
239        }
240        if !opaque.is_empty() {
241            writeln!(out);
242        }
243        for f in &spec.c_functions {
244            let ret = c_fn_type(&f.return_type, spec)?;
245            let params = f
246                .params
247                .iter()
248                .map(|p| {
249                    Ok(format!(
250                        "{} {}",
251                        c_fn_type(&p.ty, spec)?,
252                        c_field_ident(&p.name)
253                    ))
254                })
255                .collect::<Result<Vec<String>, CodegenError>>()?;
256            let param_list = if params.is_empty() {
257                "void".to_string()
258            } else {
259                params.join(", ")
260            };
261            writeln!(
262                out,
263                "NV_API {ret} {}({param_list});",
264                c_field_ident(&f.name)
265            );
266        }
267        writeln!(out);
268    }
269
270    // Modules: Direct-First (`binding = "direct"`) or opt-in vtables (`binding = "vtable"`)
271    for m in &spec.modules {
272        if m.binding == HybridBinding::Direct {
273            emit_c11_direct_module(&mut out, m, spec);
274        } else {
275            emit_c11_vtable(
276                &mut out,
277                &m.name,
278                m.interface_id(),
279                m.schema_hash(spec),
280                &m.methods,
281                false,
282                spec,
283            );
284        }
285    }
286
287    // View vtables
288    for v in &spec.views {
289        emit_c11_vtable(
290            &mut out,
291            &v.name,
292            v.interface_id(),
293            v.schema_hash(spec),
294            &v.methods,
295            true,
296            spec,
297        );
298    }
299
300    writeln!(out, "#ifdef __cplusplus");
301    writeln!(out, "}}");
302    writeln!(out, "#endif");
303    Ok(out.into_string())
304}
305
306fn emit_c11_vtable(
307    out: &mut CodeWriter,
308    name: &str,
309    interface_id: crate::schema::hybrid::InterfaceId,
310    schema_hash: u64,
311    methods: &[HybridMethodSpec],
312    is_view: bool,
313    spec: &HybridFileSpec,
314) {
315    let pascal = to_pascal_case(name);
316    let upper = to_snake_case(name).to_ascii_uppercase();
317
318    writeln!(
319        out,
320        "#define NV_HYBRID_{upper}_INTERFACE_ID UINT32_C(0x{interface_id:08X})"
321    );
322    writeln!(
323        out,
324        "#define NV_HYBRID_{upper}_SCHEMA_HASH UINT64_C(0x{schema_hash:016X})"
325    );
326    writeln!(out);
327    writeln!(out, "typedef struct NvHybrid{pascal}VTable {{");
328    writeln!(out, "  uint32_t abi_version;");
329    writeln!(out, "  uint32_t interface_id;");
330    writeln!(out, "  uint64_t schema_hash;");
331    writeln!(out, "  NvAppHandle (*create)(void);");
332    writeln!(out, "  void (*destroy)(NvAppHandle handle);");
333    writeln!(out, "  NvHybridOwnedBytes (*alloc_bytes)(size_t len);");
334    writeln!(out, "  void (*free_bytes)(NvHybridOwnedBytes buf);");
335    if is_view {
336        writeln!(
337            out,
338            "  int32_t (*set_props_direct)(NvAppHandle handle, const NvMapEntry* entries, uint32_t count);"
339        );
340    }
341    for m in methods {
342        let mname = c_field_ident(&m.name);
343        let ret_ty = match &m.return_type {
344            HybridType::Result { .. } => "int32_t".to_string(),
345            HybridType::Void => "void".to_string(),
346            other => c_return_type(other, spec),
347        };
348        write!(out, "  {ret_ty} (*{mname})(NvAppHandle _nv_handle");
349        for p in &m.params {
350            let pname = c_field_ident(&p.name);
351            write!(out, ", {} {pname}", c_param_type(&p.ty, spec));
352        }
353        if let HybridType::Result { ok, .. } = &m.return_type {
354            if !matches!(ok.as_ref(), HybridType::Void) {
355                write!(out, ", {}* _nv_out_ok", c_return_type(ok, spec));
356            }
357            write!(out, ", NvHybridOwnedBytes* _nv_out_err");
358        }
359        writeln!(out, ");");
360    }
361    writeln!(out, "}} NvHybrid{pascal}VTable;");
362    writeln!(out);
363}