Skip to main content

nativeview_hybrid_spec/schema/
mod.rs

1//! Intermediate Representation (IR), deterministic XXH64 schema hashing, interface ID
2//! assignment, and strict semantic validation for NV's Nitro-inspired Rust-first Hybrid FFI
3//! code generator.
4
5mod file_spec;
6mod types;
7mod validate;
8
9pub use file_spec::{HybridFileSpec, PodOptionScope};
10pub use types::{DefaultLiteral, HybridDefaultValue, HybridType};
11
12use std::collections::BTreeSet;
13use std::fmt;
14
15use nativeview_hash::{Key64, Xxh64Hasher};
16
17use crate::error::SpecError;
18use crate::naming::{to_pascal_case, to_snake_case};
19pub(crate) use file_spec::hash_str;
20use file_spec::{hash_method, hash_transitive_types};
21pub(crate) use validate::validate_namespace;
22
23/// Modular C ABI interface identifier (`>= 0x1000_0000` for generated hybrid modules, or explicit low IDs).
24#[repr(transparent)]
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
26pub struct InterfaceId(pub u32);
27
28impl InterfaceId {
29    #[inline(always)]
30    pub const fn raw(self) -> u32 {
31        self.0
32    }
33}
34
35impl fmt::Display for InterfaceId {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        write!(f, "{}", self.0)
38    }
39}
40
41impl fmt::UpperHex for InterfaceId {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        fmt::UpperHex::fmt(&self.0, f)
44    }
45}
46
47/// Base interface ID for generated hybrid vtables (`>= 0x1000_0000`), keeping the low range
48/// (`1..=4`) permanently reserved for core NV interfaces (`NV_IFACE_SURFACE..NV_IFACE_DEV`).
49pub const NV_HYBRID_INTERFACE_ID_BASE: u32 = 0x1000_0000;
50
51/// Bitmask for the 28-bit deterministic hash payload inside a hybrid `interface_id`.
52pub const NV_HYBRID_INTERFACE_ID_MASK: u32 = 0x0FFF_FFFF;
53
54/// Current Hybrid FFI vtable ABI version stamped into every generated vtable (compile-time locked
55/// against `nativeview_abi::hybrid::NV_HYBRID_ABI_VERSION` in `nativeview-codegen`).
56pub const NV_HYBRID_ABI_VERSION: u32 = 1;
57
58/// Reserved `NvModStatus` protocol error codes that custom `#[batchable]` error enums cannot reuse
59/// (compile-time locked against `nativeview_abi::NvModStatus::ALL` + `is_batch_protocol_status` in `nativeview-codegen`).
60pub const RESERVED_BATCH_PROTOCOL_STATUSES: &[(i32, &str)] = &[
61    (-8, "InternalError"),
62    (-9, "SchemaMismatch"),
63    (-10, "NullHandle"),
64    (-11, "Codec"),
65];
66
67/// Returns the `NvModStatus` variant name if `code` is a reserved batch protocol status.
68#[inline]
69pub const fn reserved_batch_protocol_status_name(code: i32) -> Option<&'static str> {
70    let mut i = 0;
71    while i < RESERVED_BATCH_PROTOCOL_STATUSES.len() {
72        let (reserved_code, name) = RESERVED_BATCH_PROTOCOL_STATUSES[i];
73        if reserved_code == code {
74            return Some(name);
75        }
76        i += 1;
77    }
78    None
79}
80
81/// Computes a deterministic hybrid `interface_id >= 0x1000_0000` for a module or view.
82pub fn compute_hybrid_interface_id(kind: &str, name: &str) -> InterfaceId {
83    let mut h = Xxh64Hasher::new(0);
84    h.update(b"nv.hybrid.iface.v1:");
85    h.update(kind.as_bytes());
86    h.update(b":");
87    h.update(name.as_bytes());
88    let k = Key64(h.digest());
89    let folded = (k.lo() ^ k.hi()) & NV_HYBRID_INTERFACE_ID_MASK;
90    InterfaceId(NV_HYBRID_INTERFACE_ID_BASE | folded)
91}
92
93/// Target languages emitted by the Hybrid FFI generator.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95pub enum HybridTarget {
96    Rust,
97    Cpp,
98    Swift,
99    Kotlin,
100    Dart,
101    TypeScript,
102}
103
104/// FFI binding mechanism for a hybrid module or view (`binding = "direct"` default, or `"vtable"`).
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
106pub enum HybridBinding {
107    /// Direct C-ABI exports (`impl = "rust"`) or `NvMod<Name>HostOps` table (`impl = "host"`).
108    #[default]
109    Direct,
110    /// Legacy `nv_get_interface` vtable with `NvBinValue` payloads.
111    Vtable,
112}
113
114impl HybridBinding {
115    pub const fn as_str(self) -> &'static str {
116        match self {
117            Self::Direct => "direct",
118            Self::Vtable => "vtable",
119        }
120    }
121}
122
123/// Which side implements a `binding = "direct"` module (`impl = "rust"` default, or `"host"`).
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
125pub enum HybridImpl {
126    /// Rust implements the module trait; foreign hosts invoke direct `nv_mod_<snake>_*` C exports.
127    #[default]
128    Rust,
129    /// Foreign or Rust host registers `NvMod<Name>HostOps`; Rust invokes it directly.
130    Host,
131}
132
133impl HybridImpl {
134    pub const fn as_str(self) -> &'static str {
135        match self {
136            Self::Rust => "rust",
137            Self::Host => "host",
138        }
139    }
140}
141
142impl HybridTarget {
143    pub const ALL: &'static [Self] = &[
144        Self::Rust,
145        Self::Cpp,
146        Self::Swift,
147        Self::Kotlin,
148        Self::Dart,
149        Self::TypeScript,
150    ];
151
152    pub const fn dir_name(self) -> &'static str {
153        match self {
154            Self::Rust => "rust",
155            Self::Cpp => "cpp",
156            Self::Swift => "swift",
157            Self::Kotlin => "kotlin",
158            Self::Dart => "dart",
159            Self::TypeScript => "ts",
160        }
161    }
162
163    pub fn from_name(raw: &str) -> Option<Self> {
164        let s = raw.trim();
165        if s.eq_ignore_ascii_case("rust") || s.eq_ignore_ascii_case("rs") {
166            Some(Self::Rust)
167        } else if s.eq_ignore_ascii_case("cpp")
168            || s.eq_ignore_ascii_case("c++")
169            || s.eq_ignore_ascii_case("c")
170            || s.eq_ignore_ascii_case("cxx")
171        {
172            Some(Self::Cpp)
173        } else if s.eq_ignore_ascii_case("swift") {
174            Some(Self::Swift)
175        } else if s.eq_ignore_ascii_case("kotlin")
176            || s.eq_ignore_ascii_case("kt")
177            || s.eq_ignore_ascii_case("android")
178            || s.eq_ignore_ascii_case("jni")
179        {
180            Some(Self::Kotlin)
181        } else if s.eq_ignore_ascii_case("dart") || s.eq_ignore_ascii_case("flutter") {
182            Some(Self::Dart)
183        } else if s.eq_ignore_ascii_case("ts")
184            || s.eq_ignore_ascii_case("typescript")
185            || s.eq_ignore_ascii_case("wasm")
186            || s.eq_ignore_ascii_case("web")
187        {
188            Some(Self::TypeScript)
189        } else {
190            None
191        }
192    }
193}
194
195/// Named constant declared with `#[nv_hybrid_const] pub const ...`.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct HybridConstSpec {
198    pub name: String,
199    pub ty: HybridType,
200    pub value: u64,
201    pub hex: bool,
202    pub doc: Option<String>,
203}
204
205/// Opaque handle or typedef alias declared with `#[nv_hybrid_alias] pub type ... = ...;`.
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct HybridAliasSpec {
208    pub name: String,
209    pub target: HybridType,
210    pub doc: Option<String>,
211}
212
213/// One variant of a `#[repr(u8|u16|u32|i32)] #[nv_hybrid_enum]`.
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct HybridEnumVariant {
216    pub name: String,
217    pub value: i64,
218    pub doc: Option<String>,
219}
220
221/// C-ABI enum declared with `#[nv_hybrid_enum]`.
222#[derive(Debug, Clone, PartialEq, Eq, Default)]
223pub struct HybridEnumSpec {
224    pub name: String,
225    pub variants: Vec<HybridEnumVariant>,
226    pub doc: Option<String>,
227    /// Optional explicit C enumerator prefix (e.g. `"NV_OP_"`).
228    pub c_prefix: Option<String>,
229    /// Optional explicit Rust `#[repr(...)]` width (`"u8"`, `"u16"`, `"u32"`, `"i32"`).
230    pub repr: Option<String>,
231    /// Optional fallback variant name for non-nullable Dart `fromCode(int)` decoding.
232    pub dart_fallback: Option<String>,
233}
234
235impl HybridEnumSpec {
236    /// Effective integer representation width (`"u32"` when omitted).
237    #[inline]
238    pub fn repr_str(&self) -> &str {
239        self.repr.as_deref().unwrap_or("u32")
240    }
241
242    /// True iff `#[repr(i32)]` and every variant discriminant is strictly negative (`< 0`),
243    /// allowing this enum to serve as the `E` in `Result<T, E>` without overlapping `0`/`1`.
244    #[inline]
245    pub fn is_signed_error_enum(&self) -> bool {
246        self.repr.as_deref() == Some("i32")
247            && !self.variants.is_empty()
248            && self.variants.iter().all(|v| v.value < 0)
249    }
250}
251
252/// Named field of a `#[nv_hybrid_struct]` or `#[nv_hybrid_union]`.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct HybridFieldSpec {
255    pub name: String,
256    pub ty: HybridType,
257    pub doc: Option<String>,
258    /// Optional fixed byte offset across all targets (`#[offset(N)]` -> `NV_STATIC_ASSERT`).
259    pub offset: Option<usize>,
260    /// Optional fixed byte offset on 64-bit targets (`#[offset64(N)]` -> `sizeof(void*) != 8 || offsetof(...) == N`).
261    pub offset_64: Option<usize>,
262}
263
264/// Structured record declared with `#[nv_hybrid_struct]` or `#[nv_hybrid_union]`.
265#[derive(Debug, Clone, PartialEq, Eq, Default)]
266pub struct HybridStructSpec {
267    pub name: String,
268    pub fields: Vec<HybridFieldSpec>,
269    pub doc: Option<String>,
270    /// True when declared as `#[nv_hybrid_union] pub union ...`.
271    pub is_union: bool,
272    /// Optional explicit `#[repr(C, align(N))]` alignment descriptor.
273    pub align: Option<usize>,
274    /// Optional exact target-independent byte size (`#[nv_hybrid_struct(size = N)]`).
275    pub expected_size: Option<usize>,
276    /// Optional exact 64-bit byte size (`#[nv_hybrid_struct(size_64 = N)]`).
277    pub expected_size_64: Option<usize>,
278    /// When true (`#[nv_hybrid_struct(default = false)]`), omit Rust `Default` derive/impl so
279    /// the owning crate can supply a domain-specific `Default` implementation.
280    pub no_default: bool,
281}
282
283impl HybridStructSpec {
284    /// Returns true if all fields (transitively) are fixed-size C-ABI scalars/enums/POD structs.
285    pub fn is_pod(&self, file: &HybridFileSpec) -> bool {
286        if self.is_union {
287            return false;
288        }
289        self.is_pod_inner(file, &mut BTreeSet::new())
290    }
291
292    /// Returns true if every field (transitively) implements Rust `Eq` and `Hash`
293    /// (i.e. contains no `f32`, `f64`, dynamic `Value`, raw pointer, handle, or union).
294    pub fn supports_eq_and_hash(&self, file: &HybridFileSpec) -> bool {
295        if self.is_union {
296            return false;
297        }
298        self.supports_eq_and_hash_inner(file, &mut BTreeSet::new())
299    }
300
301    pub(crate) fn supports_eq_and_hash_inner<'a>(
302        &'a self,
303        file: &'a HybridFileSpec,
304        visited: &mut BTreeSet<&'a str>,
305    ) -> bool {
306        if self.is_union || !visited.insert(&self.name) {
307            return false;
308        }
309        let ok = self
310            .fields
311            .iter()
312            .all(|f| f.ty.supports_eq_and_hash_inner(file, visited));
313        visited.remove(self.name.as_str());
314        ok
315    }
316
317    /// Returns true if this struct and every transitive field type support Rust `Default`
318    /// generation (i.e. neither this struct nor any transitive nested struct sets `default = false`,
319    /// and no field is a union, `NvModStatus`, `Result`, raw pointer, or handle).
320    pub fn supports_default(&self, file: &HybridFileSpec) -> bool {
321        if self.is_union || self.no_default {
322            return false;
323        }
324        self.supports_default_inner(file, &mut BTreeSet::new())
325    }
326
327    pub(crate) fn supports_default_inner<'a>(
328        &'a self,
329        file: &'a HybridFileSpec,
330        visited: &mut BTreeSet<&'a str>,
331    ) -> bool {
332        if self.is_union || self.no_default || !visited.insert(&self.name) {
333            return false;
334        }
335        let ok = self
336            .fields
337            .iter()
338            .all(|f| f.ty.supports_default_inner(file, visited));
339        visited.remove(self.name.as_str());
340        ok
341    }
342
343    /// `visited` holds the structs on the current path, so a cycle (only possible in an
344    /// unvalidated spec, e.g. `struct A { x: [A; 1] }`) is not POD instead of recursing forever.
345    fn is_pod_inner<'a>(
346        &'a self,
347        file: &'a HybridFileSpec,
348        visited: &mut BTreeSet<&'a str>,
349    ) -> bool {
350        if self.is_union || !visited.insert(&self.name) {
351            return false;
352        }
353        let ok = !self.fields.is_empty()
354            && self.fields.iter().all(|f| {
355                let mut ty = &f.ty;
356                while let HybridType::FixedArray { elem, .. } = ty {
357                    ty = elem;
358                }
359                match ty {
360                    HybridType::Struct(other) => file
361                        .find_struct(other)
362                        .is_some_and(|s| s.is_pod_inner(file, visited)),
363                    // Neither an array nor a struct: `is_pod` never recurses.
364                    leaf => leaf.is_pod(file),
365                }
366            });
367        visited.remove(self.name.as_str());
368        ok
369    }
370}
371
372/// Named parameter of a method or view event.
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub struct HybridParamSpec {
375    pub name: String,
376    pub ty: HybridType,
377}
378
379/// Method declared on a `HybridModuleSpec`, imperative `#[method]` on a `HybridViewSpec`, or C API function.
380#[derive(Debug, Clone, PartialEq, Eq)]
381pub struct HybridMethodSpec {
382    pub name: String,
383    pub params: Vec<HybridParamSpec>,
384    pub return_type: HybridType,
385    pub doc: Option<String>,
386    /// Whether the trait method takes a `self` receiver (`true` for instance methods, `false` for static/create fns).
387    pub has_self: bool,
388    /// Whether this vtable or host-ops slot may be NULL (`#[optional]`).
389    pub optional: bool,
390    /// Whether this method is declared `async fn` (direct binding only; callback-based C ABI).
391    pub is_async: bool,
392    /// Whether this method is opted into `#[batchable]` command-buffer codegen (direct sync only).
393    pub batchable: bool,
394}
395
396impl HybridMethodSpec {
397    /// Returns the underlying success payload type (unwrapping `Result<ok, _>` when fallible).
398    #[inline]
399    pub fn ok_type(&self) -> &HybridType {
400        match &self.return_type {
401            HybridType::Result { ok, .. } => ok.as_ref(),
402            other => other,
403        }
404    }
405}
406
407/// Typed prop declared with `#[prop]` on a `HybridViewSpec`.
408#[derive(Debug, Clone, PartialEq)]
409pub struct HybridPropSpec {
410    pub name: String,
411    pub ty: HybridType,
412    pub default_value: Option<HybridDefaultValue>,
413    pub doc: Option<String>,
414}
415
416/// Typed event declared with `#[event]` or `#[event(retained)]` on a `HybridModuleSpec` or `HybridViewSpec`.
417#[derive(Debug, Clone, PartialEq, Eq)]
418pub struct HybridEventSpec {
419    pub name: String,
420    pub params: Vec<HybridParamSpec>,
421    pub doc: Option<String>,
422    /// When true (`#[event(retained)]`), the latest payload is retained by `DirectEventHub` and
423    /// replayed automatically to newly attached or reloaded surfaces.
424    pub retained: bool,
425}
426
427/// Nitro-style native module declared with `#[nv_hybrid_module(name = "...")]`.
428#[derive(Debug, Clone, PartialEq, Eq)]
429pub struct HybridModuleSpec {
430    pub name: String,
431    pub trait_name: String,
432    pub binding: HybridBinding,
433    pub implementation: HybridImpl,
434    pub emit_wire: bool,
435    pub stateless: bool,
436    pub surface_scoped: bool,
437    pub methods: Vec<HybridMethodSpec>,
438    pub events: Vec<HybridEventSpec>,
439    pub doc: Option<String>,
440    /// Optional explicit fixed interface ID override (e.g. `interface_id = 1` for core engine
441    /// interfaces `NV_IFACE_SURFACE..NV_IFACE_DEV`). When `None`, defaults to deterministic
442    /// XXH64 ID `>= 0x1000_0000`.
443    pub explicit_interface_id: Option<InterfaceId>,
444    /// Optional explicit C vtable struct name (e.g. `"NvSurfaceApi"`, `binding = "vtable"` only).
445    pub c_name: Option<String>,
446}
447
448impl Default for HybridModuleSpec {
449    fn default() -> Self {
450        Self {
451            name: String::new(),
452            trait_name: String::new(),
453            binding: HybridBinding::Direct,
454            implementation: HybridImpl::Rust,
455            emit_wire: true,
456            stateless: false,
457            surface_scoped: false,
458            methods: Vec::new(),
459            events: Vec::new(),
460            doc: None,
461            explicit_interface_id: None,
462            c_name: None,
463        }
464    }
465}
466
467impl HybridModuleSpec {
468    /// Interface ID: returns `explicit_interface_id` when set, otherwise a deterministic ID
469    /// in the reserved hybrid range (`>= 0x1000_0000`).
470    pub fn interface_id(&self) -> InterfaceId {
471        self.explicit_interface_id
472            .unwrap_or_else(|| compute_hybrid_interface_id("module", &self.name))
473    }
474
475    /// True iff at least one method on this module is `#[batchable]`.
476    #[inline]
477    pub fn has_batchable(&self) -> bool {
478        self.methods.iter().any(|m| m.batchable)
479    }
480
481    /// True iff at least one `#[batchable]` method on this module returns a non-void value.
482    #[inline]
483    pub fn has_batch_replies(&self) -> bool {
484        self.methods
485            .iter()
486            .any(|m| m.batchable && !matches!(m.ok_type(), HybridType::Void))
487    }
488
489    /// Deterministic XXH64 schema hash covering this module's binding, implementation, methods,
490    /// events, and all transitively referenced structs and enums.
491    pub fn schema_hash(&self, file: &HybridFileSpec) -> u64 {
492        let mut h = Xxh64Hasher::new(0);
493        hash_str(&mut h, "nv.hybrid.module.v2");
494        hash_str(&mut h, &self.name);
495        hash_str(&mut h, self.binding.as_str());
496        hash_str(&mut h, self.implementation.as_str());
497        h.update(&[u8::from(self.stateless)]);
498        if self.surface_scoped {
499            hash_str(&mut h, "surface_scoped");
500        }
501        if let Some(id) = self.explicit_interface_id {
502            hash_str(&mut h, "iface_id");
503            h.update(&id.raw().to_le_bytes());
504        }
505        let mut ref_structs = BTreeSet::new();
506        let mut ref_enums = BTreeSet::new();
507        for m in &self.methods {
508            hash_method(&mut h, m, &mut ref_structs, &mut ref_enums);
509        }
510        if self.has_batch_replies() {
511            hash_str(&mut h, "batch_replies");
512        }
513        for ev in &self.events {
514            hash_str(&mut h, "event");
515            hash_str(&mut h, &ev.name);
516            h.update(&[u8::from(ev.retained)]);
517            for param in &ev.params {
518                hash_str(&mut h, &param.name);
519                hash_str(&mut h, &param.ty.canonical_signature());
520                param.ty.collect_refs(&mut ref_structs, &mut ref_enums);
521            }
522        }
523        hash_transitive_types(&mut h, file, ref_structs, ref_enums);
524        h.digest()
525    }
526}
527
528/// Nitro-style native view component declared with `#[nv_hybrid_view(name = "...")]`.
529#[derive(Debug, Clone, PartialEq, Default)]
530pub struct HybridViewSpec {
531    pub name: String,
532    pub trait_name: String,
533    pub binding: HybridBinding,
534    pub props: Vec<HybridPropSpec>,
535    pub events: Vec<HybridEventSpec>,
536    pub methods: Vec<HybridMethodSpec>,
537    pub doc: Option<String>,
538    /// Optional explicit fixed interface ID override. Defaults to deterministic XXH64 ID
539    /// `>= 0x1000_0000` when `None`.
540    pub explicit_interface_id: Option<InterfaceId>,
541    /// Optional explicit C entry-point symbol (`#[nv_hybrid_view(symbol = "...")]`).
542    /// Defaults to `"nv_get_interface"` for single-view specs or `"nv_get_interface_<snake>"`
543    /// when a spec file exports multiple views.
544    pub symbol: Option<String>,
545}
546