1use nativeview_abi::schema::{
6 AbiAliasDescriptor, AbiConstDescriptor, AbiEnumDescriptor, AbiEnumVariantDescriptor,
7 AbiFileDescriptor, AbiMethodDescriptor, AbiVtableDescriptor,
8};
9use nativeview_hash::{PRIME1, xxh64};
10
11use super::layout::{
12 FieldLayout, RecordLayout, VtableHeaderLayout, Width, layout_records, layout_records_on,
13 layout_vtable_headers_on,
14};
15use crate::error::CodegenError;
16
17pub const NO_ALIASES: &[AbiAliasDescriptor] = &[];
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct U64Split {
24 pub value: u64,
25 pub lo: u32,
26 pub hi: u32,
27}
28
29impl U64Split {
30 pub const fn new(value: u64) -> Self {
31 Self {
32 value,
33 lo: value as u32,
34 hi: (value >> 32) as u32,
35 }
36 }
37
38 pub fn hex(&self) -> HexLiteral {
40 HexLiteral {
41 value: self.value,
42 digits: 16,
43 }
44 }
45
46 pub fn lo_hex(&self) -> HexLiteral {
48 HexLiteral {
49 value: u64::from(self.lo),
50 digits: 8,
51 }
52 }
53
54 pub fn hi_hex(&self) -> HexLiteral {
56 HexLiteral {
57 value: u64::from(self.hi),
58 digits: 8,
59 }
60 }
61}
62
63#[derive(Debug, Clone, Copy)]
65pub struct HexLiteral {
66 value: u64,
67 digits: usize,
68}
69
70impl std::fmt::Display for HexLiteral {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 write!(f, "0x{:0width$X}", self.value, width = self.digits)
73 }
74}
75
76#[derive(Debug)]
79pub struct AbiModel<'a> {
80 pub core: &'a AbiFileDescriptor,
81 pub core_hash: U64Split,
82 pub records: Vec<RecordLayout<'a>>,
84 callbacks: Vec<&'a str>,
86 table_view: usize,
88}
89
90impl<'a> AbiModel<'a> {
91 pub fn new(core: &'a AbiFileDescriptor) -> Result<Self, CodegenError> {
92 let records = layout_records(&[core])?;
93 let _ = layout_vtable_headers_on(&[], &[], &[core], &records)?;
94 super::validate::abi(&[core], &records)?;
95 let table_view = find_record(&records, "NvTableView")?;
96 let callbacks = core.callbacks.iter().map(|c| c.name).collect();
97 Ok(Self {
98 core,
99 core_hash: U64Split::new(nativeview_abi::NV_CORE_ABI_SCHEMA_HASH),
100 records,
101 callbacks,
102 table_view,
103 })
104 }
105
106 pub fn table_view(&self) -> &RecordLayout<'a> {
107 &self.records[self.table_view]
108 }
109
110 pub fn consts(&self) -> impl Iterator<Item = &'a AbiConstDescriptor> + use<'a> {
111 self.core.consts.iter()
112 }
113
114 pub fn enums(&self) -> impl Iterator<Item = &'a AbiEnumDescriptor> + use<'a> {
115 self.core.enums.iter()
116 }
117
118 pub fn all_aliases(&self) -> &'a [AbiAliasDescriptor] {
119 self.core.aliases
120 }
121
122 pub fn all_callbacks(&self) -> &[&'a str] {
123 &self.callbacks
124 }
125
126 pub fn modules(&self) -> impl Iterator<Item = &'a AbiVtableDescriptor> + use<'a> {
128 self.core
129 .vtables
130 .iter()
131 .filter(|v| v.interface_id.is_some())
132 }
133}
134
135#[derive(Debug)]
138pub struct ModuleAbiModel<'a> {
139 pub file: &'a AbiFileDescriptor,
140 pub records: Vec<RecordLayout<'a>>,
141}
142
143impl<'a> ModuleAbiModel<'a> {
144 pub fn new(file: &'a AbiFileDescriptor) -> Result<Self, CodegenError> {
145 let records = layout_records(&[file])?;
146 let _ = layout_vtable_headers_on(&[], &[], &[file], &records)?;
147 super::validate::abi(&[file], &records)?;
148 Ok(Self { file, records })
149 }
150
151 pub fn consts(&self) -> impl Iterator<Item = &'a AbiConstDescriptor> + use<'a> {
152 self.file.consts.iter()
153 }
154
155 pub fn enums(&self) -> impl Iterator<Item = &'a AbiEnumDescriptor> + use<'a> {
156 self.file.enums.iter()
157 }
158
159 pub fn all_aliases(&self) -> &'a [AbiAliasDescriptor] {
160 self.file.aliases
161 }
162}
163
164#[derive(Debug)]
167pub struct RuntimeAbiModel<'a> {
168 pub file: &'a AbiFileDescriptor,
169 pub hash: U64Split,
170 pub records: Vec<RecordLayout<'a>>,
171 all_aliases: Vec<AbiAliasDescriptor>,
173 all_callbacks: Vec<&'a str>,
175 vtable_headers: Vec<VtableHeaderLayout<'a>>,
177 vtable: usize,
179 scene_view: usize,
181 scene_fact: usize,
182}
183
184impl<'a> RuntimeAbiModel<'a> {
185 pub fn new(file: &'a AbiFileDescriptor, base: &AbiModel<'a>) -> Result<Self, CodegenError> {
188 let records = layout_records_on(&base.records, &[base.core], &[file])?;
189 let vtable_headers = layout_vtable_headers_on(&base.records, &[base.core], &[file], &records)?;
190 super::validate::abi_on(&[base.core], &base.records, &[file], &records)?;
191 if let Some(r) = records
192 .iter()
193 .find(|r| base.records.iter().any(|b| b.name == r.name))
194 {
195 return Err(CodegenError::validation(format!(
196 "the runtime ABI redeclares `{}`, which `nv_abi.generated.h` already declares",
197 r.name
198 )));
199 }
200 let vtable = file
201 .vtables
202 .iter()
203 .position(|v| v.name == "NvRuntimeApi")
204 .ok_or_else(|| {
205 CodegenError::validation("the runtime ABI declares no `NvRuntimeApi` vtable")
206 })?;
207 let scene_view = find_record(&records, "NvSceneView")?;
208 let scene_fact = find_record(&records, "NvSceneFact")?;
209 let mut all_aliases = Vec::with_capacity(base.core.aliases.len() + file.aliases.len());
210 all_aliases.extend_from_slice(base.core.aliases);
211 all_aliases.extend_from_slice(file.aliases);
212 let all_callbacks = base
213 .core
214 .callbacks
215 .iter()
216 .chain(file.callbacks)
217 .map(|c| c.name)
218 .collect();
219 Ok(Self {
220 file,
221 hash: U64Split::new(nativeview_abi::NV_RUNTIME_SCHEMA_HASH),
222 records,
223 all_aliases,
224 all_callbacks,
225 vtable_headers,
226 vtable,
227 scene_view,
228 scene_fact,
229 })
230 }
231
232 pub fn scene_view(&self) -> &RecordLayout<'a> {
233 &self.records[self.scene_view]
234 }
235
236 pub fn scene_fact(&self) -> &RecordLayout<'a> {
237 &self.records[self.scene_fact]
238 }
239
240 pub fn vtable(&self) -> &'a AbiVtableDescriptor {
241 &self.file.vtables[self.vtable]
242 }
243
244 pub fn vtable_header_fields(&self) -> &[FieldLayout<'a>] {
245 &self.vtable_headers[self.vtable].header_fields
246 }
247
248 pub fn vtable_slots_offset(&self) -> &Width {
249 &self.vtable_headers[self.vtable].slots_offset
250 }
251
252 pub fn slots(&self) -> &'a [AbiMethodDescriptor] {
253 self.vtable().methods
254 }
255
256 pub fn required_slots(&self) -> Vec<&'a AbiMethodDescriptor> {
257 self.slots().iter().filter(|m| !m.optional).collect()
258 }
259
260 pub fn all_aliases(&self) -> &[AbiAliasDescriptor] {
261 &self.all_aliases
262 }
263
264 pub fn all_callbacks(&self) -> &[&'a str] {
265 &self.all_callbacks
266 }
267}
268
269pub fn module_name(v: &AbiVtableDescriptor) -> &str {
271 v.module_name.unwrap_or(v.name)
272}
273
274pub fn interface_id(v: &AbiVtableDescriptor) -> u32 {
276 v.interface_id.map_or(0, |id| id.raw())
277}
278
279pub fn c_enum_prefix(e: &AbiEnumDescriptor) -> String {
281 e.c_prefix.map_or_else(
282 || format!("{}_", super::spell::screaming(e.name)),
283 str::to_owned,
284 )
285}
286
287pub fn is_dart_fallback(e: &AbiEnumDescriptor, v: &AbiEnumVariantDescriptor) -> bool {
289 e.dart_fallback == Some(v.name)
290}
291
292pub fn bare_enum_prefix(e: &AbiEnumDescriptor) -> String {
294 let prefix = c_enum_prefix(e);
295 prefix.strip_prefix("NV_").unwrap_or(&prefix).to_owned()
296}
297
298#[derive(Debug, Clone)]
300pub struct HashVector {
301 pub label: &'static str,
302 pub bytes: Vec<u8>,
303 pub hex: String,
306 pub seed: U64Split,
307 pub expected: U64Split,
308}
309
310fn lower_hex(bytes: &[u8]) -> String {
311 const DIGITS: &[u8; 16] = b"0123456789abcdef";
312 let mut out = String::with_capacity(2 * bytes.len());
313 for &b in bytes {
314 out.push(char::from(DIGITS[usize::from(b >> 4)]));
315 out.push(char::from(DIGITS[usize::from(b & 0xF)]));
316 }
317 out
318}
319
320pub fn max_len(vectors: &[HashVector]) -> usize {
322 vectors.iter().map(|v| v.bytes.len()).max().unwrap_or(0)
323}
324
325const WIRE_SEED: u64 = 0x4E56_4557_4952_4532;
327const PRIME32_SEED: u64 = 0x9E37_79B1;
329
330pub fn hash_vectors() -> Vec<HashVector> {
333 let seq = |n: usize| (0..n).map(|i| (i * 31 + 7) as u8).collect::<Vec<u8>>();
334 let cyan = |n: usize| {
335 let mut state: u64 = PRIME32_SEED;
336 (0..n)
337 .map(|_| {
338 let b = (state >> 56) as u8;
339 state = state.wrapping_mul(PRIME1);
340 b
341 })
342 .collect::<Vec<u8>>()
343 };
344 let text = |s: &str| s.as_bytes().to_vec();
345 let vectors: [(&'static str, Vec<u8>, u64); 19] = [
346 ("empty", Vec::new(), 0),
347 ("a", text("a"), 0),
348 ("abc", text("abc"), 0),
349 ("nv.visual", text("nv.visual"), 0),
350 ("high_bits", vec![0x00, 0x01, 0x7F, 0x80, 0xFF], 0),
351 ("utf8", text("héllo wörld — 日本語 🚀"), 0),
352 ("seq101", seq(101), 0),
353 ("seq101_wire", seq(101), WIRE_SEED),
354 ("seq37_prime1", seq(37), PRIME1),
355 ("seq1024", seq(1024), 0),
356 ("cyan1", cyan(1), 0),
357 ("cyan4", cyan(4), 0),
358 ("cyan14", cyan(14), 0),
359 ("cyan222", cyan(222), 0),
360 ("cyan1024", cyan(1024), 0),
361 ("cyan1_p32", cyan(1), PRIME32_SEED),
362 ("cyan222_p32", cyan(222), PRIME32_SEED),
363 ("cyan32_p1", cyan(32), PRIME1),
364 ("cyan1024_p1", cyan(1024), PRIME1),
365 ];
366 vectors
367 .into_iter()
368 .map(|(label, bytes, seed)| HashVector {
369 label,
370 hex: lower_hex(&bytes),
371 expected: U64Split::new(xxh64(&bytes, seed)),
372 seed: U64Split::new(seed),
373 bytes,
374 })
375 .collect()
376}
377
378fn find_record(records: &[RecordLayout<'_>], name: &str) -> Result<usize, CodegenError> {
380 records
381 .iter()
382 .position(|r| r.name == name)
383 .ok_or_else(|| CodegenError::validation(format!("the ABI declares no record `{name}`")))
384}