Skip to main content

nativeview_hybrid_spec/schema/
file_spec.rs

1use std::borrow::Cow;
2use std::collections::{BTreeMap, BTreeSet};
3
4use super::*;
5
6/// Complete parsed or programmatically constructed Hybrid FFI specification file.
7#[derive(Debug, Clone, PartialEq, Default)]
8pub struct HybridFileSpec {
9    pub namespace: Option<String>,
10    pub consts: Vec<HybridConstSpec>,
11    pub aliases: Vec<HybridAliasSpec>,
12    pub enums: Vec<HybridEnumSpec>,
13    pub structs: Vec<HybridStructSpec>,
14    pub modules: Vec<HybridModuleSpec>,
15    pub views: Vec<HybridViewSpec>,
16    pub c_functions: Vec<HybridMethodSpec>,
17}
18
19impl HybridFileSpec {
20    /// Rewrites `Struct(name)` references that name a declared enum into `Enum(name)` and a
21    /// declared alias into `Handle(name)`. Frontends call it once every declaration is known, since
22    /// a type can be used before it is declared.
23    pub(crate) fn resolve_named_types(&mut self) {
24        let Self {
25            consts,
26            aliases,
27            enums,
28            structs,
29            modules,
30            views,
31            c_functions,
32            ..
33        } = self;
34        if enums.is_empty() && aliases.is_empty() {
35            return;
36        }
37        let enum_names: BTreeSet<&str> = enums.iter().map(|e| e.name.as_str()).collect();
38        let alias_names: BTreeSet<String> = aliases.iter().map(|a| a.name.clone()).collect();
39        let rewrite = |ty: &mut HybridType| rewrite_named_type(ty, &enum_names, &alias_names);
40        consts.iter_mut().for_each(|c| rewrite(&mut c.ty));
41        aliases.iter_mut().for_each(|a| rewrite(&mut a.target));
42        for f in structs.iter_mut().flat_map(|s| s.fields.iter_mut()) {
43            rewrite(&mut f.ty);
44        }
45        for m in modules.iter_mut() {
46            for p in m.events.iter_mut().flat_map(|e| e.params.iter_mut()) {
47                rewrite(&mut p.ty);
48            }
49            for method in &mut m.methods {
50                method.params.iter_mut().for_each(|p| rewrite(&mut p.ty));
51                rewrite(&mut method.return_type);
52            }
53        }
54        for v in views.iter_mut() {
55            v.props.iter_mut().for_each(|p| rewrite(&mut p.ty));
56            for p in v.events.iter_mut().flat_map(|e| e.params.iter_mut()) {
57                rewrite(&mut p.ty);
58            }
59            for m in &mut v.methods {
60                m.params.iter_mut().for_each(|p| rewrite(&mut p.ty));
61                rewrite(&mut m.return_type);
62            }
63        }
64        for m in c_functions.iter_mut() {
65            m.params.iter_mut().for_each(|p| rewrite(&mut p.ty));
66            rewrite(&mut m.return_type);
67        }
68    }
69
70    pub fn find_struct(&self, name: &str) -> Option<&HybridStructSpec> {
71        self.structs.iter().find(|s| s.name == name)
72    }
73
74    pub fn find_enum(&self, name: &str) -> Option<&HybridEnumSpec> {
75        self.enums.iter().find(|e| e.name == name)
76    }
77
78    /// PascalCase stem used for generated filenames (`<Stem>HybridAbi.h`, `<Stem>HybridSpec.swift`, etc.).
79    pub fn stem_pascal(&self) -> String {
80        if let Some(ns) = &self.namespace
81            && !ns.trim().is_empty()
82        {
83            let tail = ns.rsplit('.').next().unwrap_or(ns);
84            return to_pascal_case(tail);
85        }
86        if let Some(m) = self.modules.first() {
87            return to_pascal_case(&m.name);
88        }
89        if let Some(v) = self.views.first() {
90            return to_pascal_case(&v.name);
91        }
92        if let Some(s) = self.structs.first() {
93            return to_pascal_case(&s.name);
94        }
95        if let Some(e) = self.enums.first() {
96            return to_pascal_case(&e.name);
97        }
98        "Nv".to_string()
99    }
100
101    /// snake_case stem used for Rust/Dart/TS generated filenames (`<stem>_hybrid.rs`, etc.).
102    pub fn stem_snake(&self) -> String {
103        to_snake_case(&self.stem_pascal())
104    }
105
106    /// Java/Kotlin package name derived from `namespace`.
107    /// Dotted namespaces (e.g. `"io.github.nativeview.components"`) are kept verbatim; single-segment
108    /// namespaces (e.g. `"acme_media"`) are scoped under `"io.github.nativeview.<snake>"`; omitted namespaces
109    /// default to `"io.github.nativeview.components"`.
110    pub fn android_package(&self) -> String {
111        match self.namespace.as_deref().map(str::trim) {
112            Some(ns) if !ns.is_empty() && ns.contains('.') => ns.to_owned(),
113            Some(ns) if !ns.is_empty() => format!("io.github.nativeview.{}", to_snake_case(ns)),
114            _ => "io.github.nativeview.components".to_owned(),
115        }
116    }
117
118    /// Deterministic file-wide 64-bit schema hash covering all items in order.
119    pub fn file_schema_hash(&self) -> u64 {
120        let mut h = Xxh64Hasher::new(0);
121        hash_str(&mut h, "nv.hybrid.file.v1");
122        for c in &self.consts {
123            hash_str(&mut h, "const");
124            hash_str(&mut h, &c.name);
125            hash_str(&mut h, &c.ty.canonical_signature());
126            h.update(&c.value.to_le_bytes());
127        }
128        for a in &self.aliases {
129            hash_str(&mut h, "alias");
130            hash_str(&mut h, &a.name);
131            hash_str(&mut h, &a.target.canonical_signature());
132        }
133        for e in &self.enums {
134            hash_enum(&mut h, e);
135        }
136        for s in &self.structs {
137            hash_struct(&mut h, s);
138        }
139        for m in &self.modules {
140            h.update(&m.schema_hash(self).to_le_bytes());
141        }
142        for v in &self.views {
143            h.update(&v.schema_hash(self).to_le_bytes());
144        }
145        for f in &self.c_functions {
146            let mut rs = BTreeSet::new();
147            let mut re = BTreeSet::new();
148            hash_method(&mut h, f, &mut rs, &mut re);
149        }
150        h.digest()
151    }
152
153    /// Returns all structs in topological dependency order (dependencies emitted before dependents
154    /// so C11/C++20 structs that embed POD structs by value always compile cleanly).
155    pub fn structs_topological(&self) -> Vec<&HybridStructSpec> {
156        let mut result = Vec::with_capacity(self.structs.len());
157        let mut visited = BTreeSet::new();
158        for s in &self.structs {
159            self.visit_struct_topo(s, &mut visited, &mut result);
160        }
161        result
162    }
163
164    fn visit_struct_topo<'a>(
165        &'a self,
166        s: &'a HybridStructSpec,
167        visited: &mut BTreeSet<&'a str>,
168        out: &mut Vec<&'a HybridStructSpec>,
169    ) {
170        if !visited.insert(s.name.as_str()) {
171            return;
172        }
173        for f in &s.fields {
174            // A struct held by value, in an option, a `Vec`, or a `[T; N]` must be complete first.
175            let mut ty = &f.ty;
176            while let HybridType::Optional(inner)
177            | HybridType::Vec(inner)
178            | HybridType::FixedArray { elem: inner, .. } = ty
179            {
180                ty = inner;
181            }
182            if let HybridType::Struct(dep) = ty
183                && let Some(dep_spec) = self.find_struct(dep)
184            {
185                self.visit_struct_topo(dep_spec, visited, out);
186            }
187        }
188        out.push(s);
189    }
190
191    /// Every `(suffix, inner)` use of a C option `NvHybridOpt<suffix>`: an `Option<T>` of a POD
192    /// `T` as a parameter, return, or `Result` ok type of a method in `scope`. Two uses may share a
193    /// suffix; validation rejects two different `inner`s on one suffix.
194    pub fn pod_option_uses(
195        &self,
196        scope: PodOptionScope,
197    ) -> impl Iterator<Item = (Cow<'static, str>, &HybridType)> + '_ {
198        let interfaces = self.modules.iter().map(|m| &m.methods).chain(self.views.iter().map(|v| &v.methods));
199        let c_functions = match scope {
200            PodOptionScope::Interfaces => &self.c_functions[..0],
201            PodOptionScope::WithCFunctions => &self.c_functions[..],
202        };
203        interfaces
204            .flatten()
205            .chain(c_functions)
206            .flat_map(|method| method.params.iter().map(|p| &p.ty).chain([&method.return_type]))
207            .filter_map(|ty| {
208                let ty = match ty {
209                    HybridType::Result { ok, .. } => ok,
210                    other => other,
211                };
212                let HybridType::Optional(inner) = ty else { return None };
213                Some((inner.pod_opt_suffix_for(self)?, inner.as_ref()))
214            })
215    }
216
217    /// The distinct C options `NvHybridOpt<suffix>` of `scope`, by suffix.
218    pub fn collect_pod_option_types(&self, scope: PodOptionScope) -> Vec<(Cow<'static, str>, HybridType)> {
219        let mut by_suffix: BTreeMap<Cow<'static, str>, HybridType> = BTreeMap::new();
220        for (suffix, inner) in self.pod_option_uses(scope) {
221            by_suffix.entry(suffix).or_insert_with(|| inner.clone());
222        }
223        by_suffix.into_iter().collect()
224    }
225}
226
227/// Which signatures carry C options: Dart, Rust, Swift, TS, and Kotlin bind only modules and views;
228/// the C header also declares the static C functions.
229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
230pub enum PodOptionScope {
231    Interfaces,
232    WithCFunctions,
233}
234
235pub(crate) fn hash_str(h: &mut Xxh64Hasher, s: &str) {
236    h.update_u32(s.len() as u32);
237    h.update(s.as_bytes());
238}
239
240pub(super) fn hash_method(
241    h: &mut Xxh64Hasher,
242    m: &HybridMethodSpec,
243    ref_structs: &mut BTreeSet<String>,
244    ref_enums: &mut BTreeSet<String>,
245) {
246    hash_str(h, "method");
247    hash_str(h, &m.name);
248    h.update(&[u8::from(m.is_async), u8::from(m.optional)]);
249    if m.batchable {
250        hash_str(h, "batchable");
251    }
252    h.update_u32(m.params.len() as u32);
253    for p in &m.params {
254        hash_str(h, &p.name);
255        hash_str(h, &p.ty.canonical_signature());
256        p.ty.collect_refs(ref_structs, ref_enums);
257    }
258    hash_str(h, &m.return_type.canonical_signature());
259    m.return_type.collect_refs(ref_structs, ref_enums);
260}
261
262fn hash_enum(h: &mut Xxh64Hasher, e: &HybridEnumSpec) {
263    hash_str(h, "enum");
264    hash_str(h, &e.name);
265    hash_str(h, e.repr_str());
266    for v in &e.variants {
267        hash_str(h, &v.name);
268        h.update(&v.value.to_le_bytes());
269    }
270}
271
272fn hash_struct(h: &mut Xxh64Hasher, s: &HybridStructSpec) {
273    hash_str(h, if s.is_union { "union" } else { "struct" });
274    hash_str(h, &s.name);
275    if let Some(align) = s.align {
276        hash_str(h, "align");
277        h.update_u64(align as u64);
278    }
279    if let Some(sz) = s.expected_size {
280        hash_str(h, "size");
281        h.update_u64(sz as u64);
282    }
283    if let Some(sz64) = s.expected_size_64 {
284        hash_str(h, "size64");
285        h.update_u64(sz64 as u64);
286    }
287    for f in &s.fields {
288        hash_str(h, &f.name);
289        hash_str(h, &f.ty.canonical_signature());
290        if let Some(off) = f.offset {
291            hash_str(h, "offset");
292            h.update_u64(off as u64);
293        }
294        if let Some(off64) = f.offset_64 {
295            hash_str(h, "offset64");
296            h.update_u64(off64 as u64);
297        }
298    }
299}
300
301impl HybridViewSpec {
302    /// Interface ID: returns `explicit_interface_id` when set, otherwise a deterministic ID
303    /// in the reserved hybrid range (`>= 0x1000_0000`).
304    pub fn interface_id(&self) -> InterfaceId {
305        self.explicit_interface_id
306            .unwrap_or_else(|| compute_hybrid_interface_id("view", &self.name))
307    }
308
309    /// Deterministic, collision-free C vtable entry-point symbol for exporting this view.
310    ///
311    /// Uses `symbol` if explicitly provided; otherwise `"nv_get_interface"` when `file` declares
312    /// at most one view, or `"nv_get_interface_<snake_name>"` when `file` declares multiple views.
313    pub fn vtable_symbol(&self, file: &HybridFileSpec) -> String {
314        if let Some(sym) = self.symbol.as_deref().filter(|s| !s.is_empty()) {
315            return sym.to_owned();
316        }
317        if file.views.len() <= 1 {
318            "nv_get_interface".to_owned()
319        } else {
320            format!("nv_get_interface_{}", to_snake_case(&self.name))
321        }
322    }
323
324    /// Collects all transitively referenced enums (in declaration order) and structs (in
325    /// topological dependency order) reachable from this view's props, events, and methods.
326    pub fn referenced_types<'a>(
327        &self,
328        file: &'a HybridFileSpec,
329    ) -> (Vec<&'a HybridEnumSpec>, Vec<&'a HybridStructSpec>) {
330        let mut pending_structs = BTreeSet::new();
331        let mut seen_enums = BTreeSet::new();
332        for p in &self.props {
333            p.ty.collect_refs(&mut pending_structs, &mut seen_enums);
334        }
335        for ev in &self.events {
336            for param in &ev.params {
337                param.ty.collect_refs(&mut pending_structs, &mut seen_enums);
338            }
339        }
340        for m in &self.methods {
341            for param in &m.params {
342                param.ty.collect_refs(&mut pending_structs, &mut seen_enums);
343            }
344            m.return_type
345                .collect_refs(&mut pending_structs, &mut seen_enums);
346        }
347        let (seen_structs, seen_enums) =
348            expand_transitive_refs(file, pending_structs, seen_enums);
349        let enums = file
350            .enums
351            .iter()
352            .filter(|e| seen_enums.contains(e.name.as_str()))
353            .collect();
354        let structs = file
355            .structs_topological()
356            .into_iter()
357            .filter(|s| seen_structs.contains(s.name.as_str()))
358            .collect();
359        (enums, structs)
360    }
361
362    /// Deterministic XXH64 schema hash covering this view's props, events, methods,
363    /// and all transitively referenced structs and enums.
364    pub fn schema_hash(&self, file: &HybridFileSpec) -> u64 {
365        let mut h = Xxh64Hasher::new(0);
366        hash_str(&mut h, "nv.hybrid.view.v2");
367        hash_str(&mut h, &self.name);
368        hash_str(&mut h, self.binding.as_str());
369        if let Some(id) = self.explicit_interface_id {
370            hash_str(&mut h, "iface_id");
371            h.update(&id.raw().to_le_bytes());
372        }
373        if let Some(sym) = &self.symbol {
374            hash_str(&mut h, "symbol");
375            hash_str(&mut h, sym);
376        }
377        let mut ref_structs = BTreeSet::new();
378        let mut ref_enums = BTreeSet::new();
379        for p in &self.props {
380            hash_str(&mut h, "prop");
381            hash_str(&mut h, &p.name);
382            hash_str(&mut h, &p.ty.canonical_signature());
383            if let Some(def) = &p.default_value {
384                hash_str(&mut h, &def.canonical_signature());
385            }
386            p.ty.collect_refs(&mut ref_structs, &mut ref_enums);
387        }
388        for ev in &self.events {
389            hash_str(&mut h, "event");
390            hash_str(&mut h, &ev.name);
391            h.update(&[u8::from(ev.retained)]);
392            for param in &ev.params {
393                hash_str(&mut h, &param.name);
394                hash_str(&mut h, &param.ty.canonical_signature());
395                param.ty.collect_refs(&mut ref_structs, &mut ref_enums);
396            }
397        }
398        for m in &self.methods {
399            hash_method(&mut h, m, &mut ref_structs, &mut ref_enums);
400        }
401        hash_transitive_types(&mut h, file, ref_structs, ref_enums);
402        h.digest()
403    }
404}
405
406fn expand_transitive_refs(
407    file: &HybridFileSpec,
408    mut pending_structs: BTreeSet<String>,
409    mut seen_enums: BTreeSet<String>,
410) -> (BTreeSet<String>, BTreeSet<String>) {
411    let mut seen_structs = BTreeSet::new();
412    while let Some(name) = pending_structs.pop_first() {
413        if !seen_structs.insert(name.clone()) {
414            continue;
415        }
416        if let Some(s) = file.find_struct(&name) {
417            for f in &s.fields {
418                let mut child_structs = BTreeSet::new();
419                f.ty.collect_refs(&mut child_structs, &mut seen_enums);
420                for cs in child_structs {
421                    if !seen_structs.contains(&cs) {
422                        pending_structs.insert(cs);
423                    }
424                }
425            }
426        }
427    }
428    (seen_structs, seen_enums)
429}
430
431pub(super) fn hash_transitive_types(
432    h: &mut Xxh64Hasher,
433    file: &HybridFileSpec,
434    pending_structs: BTreeSet<String>,
435    seen_enums: BTreeSet<String>,
436) {
437    let (seen_structs, seen_enums) = expand_transitive_refs(file, pending_structs, seen_enums);
438    for e_name in seen_enums {
439        if let Some(e) = file.find_enum(&e_name) {
440            hash_enum(h, e);
441        }
442    }
443    for s_name in seen_structs {
444        if let Some(s) = file.find_struct(&s_name) {
445            hash_struct(h, s);
446        }
447    }
448}
449
450fn rewrite_named_type(ty: &mut HybridType, enums: &BTreeSet<&str>, aliases: &BTreeSet<String>) {
451    match ty {
452        HybridType::Struct(name) if enums.contains(name.as_str()) => {
453            *ty = HybridType::Enum(std::mem::take(name))
454        }
455        HybridType::Struct(name) if aliases.contains(name) => {
456            *ty = HybridType::Handle(std::mem::take(name))
457        }
458        HybridType::Optional(inner)
459        | HybridType::Vec(inner)
460        | HybridType::ConstPtr(inner)
461        | HybridType::MutPtr(inner)
462        | HybridType::FixedArray { elem: inner, .. } => rewrite_named_type(inner, enums, aliases),
463        HybridType::Result { ok, err } => {
464            rewrite_named_type(ok, enums, aliases);
465            rewrite_named_type(err, enums, aliases);
466        }
467        _ => {}
468    }
469}