1mod 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#[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
47pub const NV_HYBRID_INTERFACE_ID_BASE: u32 = 0x1000_0000;
50
51pub const NV_HYBRID_INTERFACE_ID_MASK: u32 = 0x0FFF_FFFF;
53
54pub const NV_HYBRID_ABI_VERSION: u32 = 1;
57
58pub const RESERVED_BATCH_PROTOCOL_STATUSES: &[(i32, &str)] = &[
61 (-8, "InternalError"),
62 (-9, "SchemaMismatch"),
63 (-10, "NullHandle"),
64 (-11, "Codec"),
65];
66
67#[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
81pub 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
106pub enum HybridBinding {
107 #[default]
109 Direct,
110 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
125pub enum HybridImpl {
126 #[default]
128 Rust,
129 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct HybridAliasSpec {
208 pub name: String,
209 pub target: HybridType,
210 pub doc: Option<String>,
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct HybridEnumVariant {
216 pub name: String,
217 pub value: i64,
218 pub doc: Option<String>,
219}
220
221#[derive(Debug, Clone, PartialEq, Eq, Default)]
223pub struct HybridEnumSpec {
224 pub name: String,
225 pub variants: Vec<HybridEnumVariant>,
226 pub doc: Option<String>,
227 pub c_prefix: Option<String>,
229 pub repr: Option<String>,
231 pub dart_fallback: Option<String>,
233}
234
235impl HybridEnumSpec {
236 #[inline]
238 pub fn repr_str(&self) -> &str {
239 self.repr.as_deref().unwrap_or("u32")
240 }
241
242 #[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#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct HybridFieldSpec {
255 pub name: String,
256 pub ty: HybridType,
257 pub doc: Option<String>,
258 pub offset: Option<usize>,
260 pub offset_64: Option<usize>,
262}
263
264#[derive(Debug, Clone, PartialEq, Eq, Default)]
266pub struct HybridStructSpec {
267 pub name: String,
268 pub fields: Vec<HybridFieldSpec>,
269 pub doc: Option<String>,
270 pub is_union: bool,
272 pub align: Option<usize>,
274 pub expected_size: Option<usize>,
276 pub expected_size_64: Option<usize>,
278 pub no_default: bool,
281}
282
283impl HybridStructSpec {
284 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 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 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 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 leaf => leaf.is_pod(file),
365 }
366 });
367 visited.remove(self.name.as_str());
368 ok
369 }
370}
371
372#[derive(Debug, Clone, PartialEq, Eq)]
374pub struct HybridParamSpec {
375 pub name: String,
376 pub ty: HybridType,
377}
378
379#[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 pub has_self: bool,
388 pub optional: bool,
390 pub is_async: bool,
392 pub batchable: bool,
394}
395
396impl HybridMethodSpec {
397 #[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
418pub struct HybridEventSpec {
419 pub name: String,
420 pub params: Vec<HybridParamSpec>,
421 pub doc: Option<String>,
422 pub retained: bool,
425}
426
427#[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 pub explicit_interface_id: Option<InterfaceId>,
444 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 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 #[inline]
477 pub fn has_batchable(&self) -> bool {
478 self.methods.iter().any(|m| m.batchable)
479 }
480
481 #[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 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, ¶m.name);
519 hash_str(&mut h, ¶m.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#[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 pub explicit_interface_id: Option<InterfaceId>,
541 pub symbol: Option<String>,
545}
546