Skip to main content

nativeview_codegen/abi/
spell.rs

1//! Per-language spellings of ABI types, names, and values, called from the Askama templates.
2//!
3//! Every function takes the borrowed `nativeview-abi` descriptors directly. [`super::layout`] and
4//! [`super::validate`] reject every type spelling a template cannot express before rendering
5//! starts, so the `/* unsupported */` fallback below is unreachable (and would fail the host
6//! compile if it were not).
7
8use nativeview_abi::schema::{AbiAliasDescriptor, AbiParamDescriptor};
9
10use super::layout::{FieldLayout, Scalar, Ty, Width};
11use super::model::{HexLiteral, U64Split};
12use crate::naming::{screaming_snake_to_camel_case, to_camel_case, to_pascal_case, to_snake_case};
13
14/// `SCREAMING_SNAKE` of a Rust identifier (`NvValueTag` -> `NV_VALUE_TAG`, `hit_test` -> `HIT_TEST`).
15pub fn screaming(name: &str) -> String {
16    let mut s = to_snake_case(name);
17    s.make_ascii_uppercase();
18    s
19}
20
21/// `lowerCamel` of a snake / SCREAMING identifier (`NV_ABI_MAGIC` -> `nvAbiMagic`). A leading `_`
22/// is dropped: Dart would make the name library-private.
23pub fn camel(name: &str) -> String {
24    let name = name.trim_start_matches('_');
25    if !name.bytes().any(|b| b.is_ascii_lowercase()) {
26        screaming_snake_to_camel_case(name)
27    } else {
28        to_camel_case(name)
29    }
30}
31
32/// `snake_case` of a Rust identifier (`Surface` -> `surface`).
33pub fn snake(name: &str) -> String {
34    to_snake_case(name)
35}
36
37/// `UpperCamel` of a snake / dotted identifier (`nv.text_input` -> `NvTextInput`).
38pub fn pascal(name: &str) -> String {
39    to_pascal_case(&name.replace('.', "_"))
40}
41
42/// Enum discriminant / constant: hex from `0x1000` up, decimal below.
43pub fn int(value: &i64) -> String {
44    if *value >= 0x1000 {
45        format!("0x{value:X}")
46    } else {
47        value.to_string()
48    }
49}
50
51/// Unsigned constant spelled as declared (`hex = true` -> `0x...`).
52pub fn uint(value: &u64, hex: &bool) -> String {
53    if *hex {
54        format!("0x{value:X}")
55    } else {
56        value.to_string()
57    }
58}
59
60/// 64-bit unsigned constant (`hex = true` -> 16-digit `0x...`).
61pub fn uint64(value: &u64, hex: &bool) -> String {
62    if *hex {
63        format!("0x{value:016X}")
64    } else {
65        value.to_string()
66    }
67}
68
69/// Low 32 bits of a 64-bit constant as `0x........`.
70pub fn lo_hex(value: &u64) -> HexLiteral {
71    U64Split::new(*value).lo_hex()
72}
73
74/// High 32 bits of a 64-bit constant as `0x........`.
75pub fn hi_hex(value: &u64) -> HexLiteral {
76    U64Split::new(*value).hi_hex()
77}
78
79/// Java `int` literal: hex above `i32::MAX`, where a decimal literal would not compile.
80pub fn java_int(value: &u64, hex: &bool) -> String {
81    uint(value, &(*hex || *value > 0x7FFF_FFFF))
82}
83
84/// `NvNodeRow` -> `NODE_ROW` (Java / TS constant prefix of a record).
85pub fn record_prefix(name: &str) -> String {
86    screaming(name.strip_prefix("Nv").unwrap_or(name))
87}
88
89/// Constant prefix of one runtime ABI enum's values: its name without the `NvRuntime` / `Nv`
90/// namespace, `SCREAMING` (`NvRuntimeStatus` -> `STATUS`), so each enum owns its own prefix.
91pub fn enum_prefix(name: &str) -> String {
92    screaming(
93        name.strip_prefix("NvRuntime")
94            .or_else(|| name.strip_prefix("Nv"))
95            .unwrap_or(name),
96    )
97}
98
99/// Constant name without the `NV_` namespace (`NV_ABI_MAGIC` -> `ABI_MAGIC`).
100pub fn bare(name: &str) -> &str {
101    name.strip_prefix("NV_").unwrap_or(name)
102}
103
104/// Java `int` constants for a layout value: one constant when every data model agrees, else
105/// `_64` / `_32` (or one constant when those agree) plus `_I386` where i386 differs from ILP32.
106pub fn java_width(name: String, w: &Width) -> String {
107    let line = |suffix: &str, v: usize| format!("    public static final int {name}{suffix} = {v};");
108    let mut out = match w.fixed() {
109        Some(n) => return line("", n),
110        None if w.p64() == w.p32() => line("", w.p64()),
111        None => format!("{}\n{}", line("_64", w.p64()), line("_32", w.p32())),
112    };
113    if w.i386() != w.p32() {
114        out.push('\n');
115        out.push_str(&line("_I386", w.i386()));
116    }
117    out
118}
119
120/// Single-line comment text: newlines folded so a doc can never end the comment early.
121pub fn one_line(doc: &str) -> String {
122    doc.split('\n')
123        .map(str::trim)
124        .filter(|s| !s.is_empty())
125        .collect::<Vec<_>>()
126        .join(" ")
127        .replace("*/", "* /")
128}
129
130pub mod c {
131    use super::*;
132
133    pub fn scalar(s: Scalar) -> &'static str {
134        match s {
135            Scalar::Bool => "bool",
136            Scalar::U8 => "uint8_t",
137            Scalar::U16 => "uint16_t",
138            Scalar::U32 => "uint32_t",
139            Scalar::U64 => "uint64_t",
140            Scalar::I32 => "int32_t",
141            Scalar::I64 => "int64_t",
142            Scalar::F32 => "float",
143            Scalar::F64 => "double",
144            Scalar::Usize => "size_t",
145        }
146    }
147
148    fn resolve_c_alias<'a>(aliases: &'a [AbiAliasDescriptor], name: &'a str) -> &'a str {
149        aliases
150            .iter()
151            .find(|a| a.rust_name == Some(name))
152            .map_or(name, |a| a.name)
153    }
154
155    /// C spelling of an ABI type (arrays spell their element type; see [`decl`]).
156    pub fn ty(aliases: &[AbiAliasDescriptor], spelling: &str) -> String {
157        match Ty::parse(spelling) {
158            Ok(Ty::Unit | Ty::Void) => "void".to_owned(),
159            Ok(Ty::Scalar(s)) => scalar(s).to_owned(),
160            Ok(Ty::Ptr {
161                mutable: false,
162                pointee,
163            }) => {
164                if matches!(Ty::parse(pointee), Ok(Ty::Ptr { .. })) {
165                    format!("{} const*", ty(aliases, pointee))
166                } else {
167                    format!("const {}*", ty(aliases, pointee))
168                }
169            }
170            Ok(Ty::Ptr {
171                mutable: true,
172                pointee,
173            }) => format!("{}*", ty(aliases, pointee)),
174            Ok(Ty::Array { elem, .. }) => ty(aliases, elem),
175            Ok(Ty::Nullable(cb)) => cb.to_owned(),
176            Ok(Ty::Named(name)) => resolve_c_alias(aliases, name).to_owned(),
177            Err(_) => "/* unsupported */".to_owned(),
178        }
179    }
180
181    /// `type name` / `type name[N]` declaration of a field or parameter.
182    pub fn decl(aliases: &[AbiAliasDescriptor], spelling: &str, name: &str) -> String {
183        match Ty::parse(spelling) {
184            Ok(Ty::Array { len, .. }) => format!("{} {name}[{len}]", ty(aliases, spelling)),
185            _ => format!("{} {name}", ty(aliases, spelling)),
186        }
187    }
188
189    /// C parameter list (`void` when empty, else comma-separated `type name`).
190    pub fn fn_params(aliases: &[AbiAliasDescriptor], params: &[AbiParamDescriptor]) -> String {
191        if params.is_empty() {
192            "void".to_owned()
193        } else {
194            params
195                .iter()
196                .map(|p| decl(aliases, p.ty, p.name))
197                .collect::<Vec<_>>()
198                .join(", ")
199        }
200    }
201
202    /// `16u`, `(sizeof(void*) == 8u ? 16u : 8u)`, or, when i386 System V differs from other 32-bit
203    /// targets, `(sizeof(void*) == 8u ? 24u : (NV_ABI_U64_FIELD_ALIGN == 8u ? 16u : 12u))`.
204    pub fn width(w: &Width) -> String {
205        if let Some(n) = w.fixed() {
206            return format!("{n}u");
207        }
208        let p32 = if w.p32() == w.i386() {
209            format!("{}u", w.p32())
210        } else {
211            format!(
212                "(NV_ABI_U64_FIELD_ALIGN == 8u ? {}u : {}u)",
213                w.p32(),
214                w.i386()
215            )
216        };
217        format!("(sizeof(void*) == 8u ? {}u : {p32})", w.p64())
218    }
219
220    pub fn field_decl(aliases: &[AbiAliasDescriptor], f: &FieldLayout<'_>) -> String {
221        match f.ty {
222            Ty::Array { elem, len } => format!("{} {}[{len}]", ty(aliases, elem), f.desc.name),
223            _ => format!("{} {}", ty(aliases, f.desc.abi_type()), f.desc.name),
224        }
225    }
226}
227
228pub mod dart {
229    use super::*;
230
231    /// Follows value-alias chains (`NodeId`/`NvNodeId` -> `u32`, `NvAppHandle` -> `*mut c_void`)
232    /// to their underlying ABI type, stopping at callbacks and aliases emitted as Dart typedefs
233    /// (`keep_aliases`, e.g. `NvRuntimeHandle`). Scalar aliases (`NvOverlayFlags` -> `u16`) are
234    /// never kept: `ffi.Struct` fields need annotated `int`s, and a Dart typedef of the same name
235    /// would collide with the table enum class it mirrors.
236    fn resolve_alias<'a>(
237        spelling: &'a str,
238        aliases: &'a [AbiAliasDescriptor],
239        keep_aliases: &'a [AbiAliasDescriptor],
240        callbacks: &[&str],
241    ) -> &'a str {
242        let mut cur = spelling;
243        for _ in 0..=aliases.len() {
244            let Ok(Ty::Named(name)) = Ty::parse(cur) else {
245                break;
246            };
247            if callbacks.contains(&name) || keep_aliases.iter().any(|k| k.name == name && is_typedef(k)) {
248                break;
249            }
250            match aliases
251                .iter()
252                .find(|a| a.name == name || a.rust_name == Some(name))
253            {
254                Some(alias) => cur = alias.target,
255                None => break,
256            }
257        }
258        cur
259    }
260
261    /// `true` when `alias` is emitted as a Dart `typedef` (every non-scalar alias).
262    pub fn is_typedef(alias: &AbiAliasDescriptor) -> bool {
263        !matches!(Ty::parse(alias.target), Ok(Ty::Scalar(_)))
264    }
265
266    /// `dart:ffi` native type (`ffi.Uint32`, `ffi.Pointer<NvValue>`, `NvStrSlice`,
267    /// `ffi.Pointer<ffi.NativeFunction<NvRuntimeWakeNative>>`).
268    pub fn native(
269        aliases: &[AbiAliasDescriptor],
270        keep_aliases: &[AbiAliasDescriptor],
271        callbacks: &[&str],
272        spelling: &str,
273    ) -> String {
274        match Ty::parse(resolve_alias(spelling, aliases, keep_aliases, callbacks)) {
275            Ok(Ty::Unit | Ty::Void) => "ffi.Void".to_owned(),
276            Ok(Ty::Scalar(s)) => native_scalar(s).to_owned(),
277            Ok(Ty::Ptr { pointee, .. }) => format!(
278                "ffi.Pointer<{}>",
279                native(aliases, keep_aliases, callbacks, pointee)
280            ),
281            Ok(Ty::Array { elem, .. }) => format!(
282                "ffi.Array<{}>",
283                native(aliases, keep_aliases, callbacks, elem)
284            ),
285            Ok(Ty::Nullable(cb)) => {
286                format!(
287                    "ffi.Pointer<ffi.NativeFunction<{}Native>>",
288                    callback_stem(cb)
289                )
290            }
291            Ok(Ty::Named(name)) if callbacks.contains(&name) => {
292                format!(
293                    "ffi.Pointer<ffi.NativeFunction<{}Native>>",
294                    callback_stem(name)
295                )
296            }
297            Ok(Ty::Named(name)) => name.to_owned(),
298            Err(_) => "/* unsupported */".to_owned(),
299        }
300    }
301
302    /// Dart-side `asFunction` type (`int`, `double`, `bool`, `void`, `ffi.Pointer<...>`).
303    pub fn dart_side(
304        aliases: &[AbiAliasDescriptor],
305        keep_aliases: &[AbiAliasDescriptor],
306        callbacks: &[&str],
307        spelling: &str,
308    ) -> String {
309        match Ty::parse(resolve_alias(spelling, aliases, keep_aliases, callbacks)) {
310            Ok(Ty::Unit | Ty::Void) => "void".to_owned(),
311            Ok(Ty::Scalar(s)) => dart_scalar(s).to_owned(),
312            _ => native(aliases, keep_aliases, callbacks, spelling),
313        }
314    }
315
316    /// Single-line `RET Function(T name, ...)` signature (`native` or `dart_side`).
317    pub fn fn_sig(
318        aliases: &[AbiAliasDescriptor],
319        keep_aliases: &[AbiAliasDescriptor],
320        callbacks: &[&str],
321        params: &[AbiParamDescriptor],
322        ret: &str,
323        as_dart: bool,
324    ) -> String {
325        let pick = |ty: &str| {
326            if as_dart {
327                dart_side(aliases, keep_aliases, callbacks, ty)
328            } else {
329                native(aliases, keep_aliases, callbacks, ty)
330            }
331        };
332        let list: Vec<String> = params
333            .iter()
334            .map(|p| format!("{} {}", pick(p.ty), camel(p.name)))
335            .collect();
336        format!("{} Function({})", pick(ret), list.join(", "))
337    }
338
339    fn native_scalar(s: Scalar) -> &'static str {
340        match s {
341            Scalar::Bool => "ffi.Bool",
342            Scalar::U8 => "ffi.Uint8",
343            Scalar::U16 => "ffi.Uint16",
344            Scalar::U32 => "ffi.Uint32",
345            Scalar::U64 => "ffi.Uint64",
346            Scalar::I32 => "ffi.Int32",
347            Scalar::I64 => "ffi.Int64",
348            Scalar::F32 => "ffi.Float",
349            Scalar::F64 => "ffi.Double",
350            Scalar::Usize => "ffi.Size",
351        }
352    }
353
354    fn dart_scalar(s: Scalar) -> &'static str {
355        match s {
356            Scalar::Bool => "bool",
357            Scalar::F32 | Scalar::F64 => "double",
358            _ => "int",
359        }
360    }
361
362    /// `external` field declaration (with its `@ffi.*` annotation) of an `ffi.Struct` / `ffi.Union`.
363    pub fn field(
364        aliases: &[AbiAliasDescriptor],
365        keep_aliases: &[AbiAliasDescriptor],
366        callbacks: &[&str],
367        f: &FieldLayout<'_>,
368    ) -> String {
369        let name = camel(f.desc.name);
370        let resolved = resolve_alias(f.desc.abi_type(), aliases, keep_aliases, callbacks);
371        match Ty::parse(resolved) {
372            Ok(Ty::Scalar(s)) => {
373                format!(
374                    "@{}()\n  external {} {name};",
375                    native_scalar(s),
376                    dart_scalar(s)
377                )
378            }
379            Ok(Ty::Array { len, .. }) => {
380                format!(
381                    "@ffi.Array({len})\n  external {} {name};",
382                    native(aliases, keep_aliases, callbacks, resolved)
383                )
384            }
385            _ => format!(
386                "external {} {name};",
387                native(aliases, keep_aliases, callbacks, resolved)
388            ),
389        }
390    }
391
392    /// Dart typedef stem of a C callback typedef (`NvRuntimeWakeFn` -> `NvRuntimeWake`).
393    pub fn callback_stem(name: &str) -> &str {
394        name.strip_suffix("Fn").unwrap_or(name)
395    }
396
397    /// Dart enum constant name; Dart keywords get a `Value` suffix.
398    pub fn variant(name: &str) -> String {
399        let id = camel(name);
400        match id.as_str() {
401            "null" | "bool" | "default" | "true" | "false" | "switch" | "case" | "class"
402            | "const" | "final" | "in" | "is" | "new" | "this" | "var" | "void" | "with"
403            | "enum" | "super" | "return" | "do" | "if" | "else" | "for" | "while" => {
404                format!("{id}Value")
405            }
406            _ => id,
407        }
408    }
409}
410
411pub mod swift {
412    use super::*;
413
414    /// Swift enum case / static constant name: `lowerCamel`, with a trailing `_` for Swift
415    /// keywords (and `none`, which would shadow `Optional.none`).
416    pub fn variant(name: &str) -> String {
417        const RESERVED: &[&str] = &[
418            "Any", "Self", "as", "break", "case", "catch", "class", "continue", "default", "defer",
419            "deinit", "do", "else", "enum", "extension", "fallthrough", "false", "for", "func",
420            "guard", "if", "import", "in", "init", "inout", "internal", "is", "let", "nil", "none",
421            "operator", "private", "protocol", "public", "repeat", "rethrows", "return", "self",
422            "static", "struct", "subscript", "super", "switch", "throw", "throws", "true", "try",
423            "typealias", "var", "where", "while",
424        ];
425        let id = camel(name);
426        if RESERVED.contains(&id.as_str()) {
427            format!("{id}_")
428        } else {
429            id
430        }
431    }
432}
433
434pub mod ts {
435    use super::*;
436
437    /// TS constant-object key of an enum variant (`PassThrough` -> `PASS_THROUGH`).
438    pub fn key(name: &str) -> String {
439        screaming(name)
440    }
441}