1use std::collections::{BTreeMap, BTreeSet};
16
17use nativeview_abi::schema::{AbiFieldDescriptor, AbiFileDescriptor, AbiRecordDescriptor};
18
19use crate::error::CodegenError;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Scalar {
24 Bool,
25 U8,
26 U16,
27 U32,
28 U64,
29 I32,
30 I64,
31 F32,
32 F64,
33 Usize,
34}
35
36impl Scalar {
37 fn parse(s: &str) -> Option<Self> {
38 Some(match s {
39 "bool" => Self::Bool,
40 "u8" | "PrimarySlot" => Self::U8,
41 "u16" | "ShortLen" => Self::U16,
42 "u32" | "NodeIndex" | "Word" => Self::U32,
43 "u64" => Self::U64,
44 "i32" | "ZIndex" => Self::I32,
45 "i64" => Self::I64,
46 "f32" => Self::F32,
47 "f64" => Self::F64,
48 "usize" => Self::Usize,
49 _ => return None,
50 })
51 }
52
53 fn shape(self) -> Shape {
55 match self {
56 Self::Bool | Self::U8 => Shape::same(1),
57 Self::U16 => Shape::same(2),
58 Self::U32 | Self::I32 | Self::F32 => Shape::same(4),
59 Self::U64 | Self::I64 | Self::F64 => Shape {
60 size: Width::same(8),
61 align: Width([8, 8, 4]),
62 },
63 Self::Usize => Shape::POINTER,
64 }
65 }
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Model {
71 P64 = 0,
73 P32 = 1,
75 I386 = 2,
77}
78
79impl Model {
80 pub const fn host() -> Self {
82 #[repr(C)]
83 struct Probe {
84 pad: u8,
85 value: u64,
86 }
87 if size_of::<usize>() == 8 {
88 Self::P64
89 } else if std::mem::offset_of!(Probe, value) == 8 {
90 Self::P32
91 } else {
92 Self::I386
93 }
94 }
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum Ty<'a> {
101 Unit,
102 Void,
103 Scalar(Scalar),
104 Ptr { mutable: bool, pointee: &'a str },
105 Array { elem: &'a str, len: usize },
106 Nullable(&'a str),
109 Named(&'a str),
110}
111
112impl<'a> Ty<'a> {
113 pub fn parse(spelling: &'a str) -> Result<Self, CodegenError> {
114 let s = spelling.trim();
115 if s == "()" {
116 return Ok(Self::Unit);
117 }
118 if s == "c_void" {
119 return Ok(Self::Void);
120 }
121 if let Some(scalar) = Scalar::parse(s) {
122 return Ok(Self::Scalar(scalar));
123 }
124 if let Some(pointee) = s.strip_prefix("*const ") {
125 return Ok(Self::Ptr {
126 mutable: false,
127 pointee: pointee.trim(),
128 });
129 }
130 if let Some(pointee) = s.strip_prefix("*mut ") {
131 return Ok(Self::Ptr {
132 mutable: true,
133 pointee: pointee.trim(),
134 });
135 }
136 if let Some(inner) = s.strip_prefix("Option<").and_then(|b| b.strip_suffix('>')) {
137 let inner = inner.trim();
138 if inner.is_empty() || inner.contains(['(', ')', '<', '>']) {
139 return Err(bad_type(spelling, "unsupported `Option<...>` ABI type"));
140 }
141 return Ok(Self::Nullable(inner));
142 }
143 if let Some(body) = s.strip_prefix('[').and_then(|b| b.strip_suffix(']')) {
144 let (elem, len) = body
145 .split_once(';')
146 .ok_or_else(|| bad_type(spelling, "array needs `[T; N]`"))?;
147 let len = len
148 .trim()
149 .parse()
150 .map_err(|_| bad_type(spelling, "array length"))?;
151 return Ok(Self::Array {
152 elem: elem.trim(),
153 len,
154 });
155 }
156 if !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
157 return Ok(Self::Named(s));
158 }
159 Err(bad_type(spelling, "unsupported ABI type spelling"))
160 }
161}
162
163fn bad_type(spelling: &str, why: &str) -> CodegenError {
164 CodegenError::validation(format!("ABI type `{spelling}`: {why}"))
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct Width(pub [usize; 3]);
170
171impl Width {
172 const fn same(n: usize) -> Self {
173 Self([n; 3])
174 }
175
176 pub const fn at(self, model: Model) -> usize {
177 self.0[model as usize]
178 }
179
180 pub const fn p64(self) -> usize {
182 self.0[0]
183 }
184
185 pub const fn p32(self) -> usize {
187 self.0[1]
188 }
189
190 pub const fn i386(self) -> usize {
192 self.0[2]
193 }
194
195 pub const fn fixed(self) -> Option<usize> {
197 let [a, b, c] = self.0;
198 if a == b && b == c { Some(a) } else { None }
199 }
200
201 fn zip(self, other: Self, f: impl Fn(usize, usize) -> usize) -> Self {
202 Self([
203 f(self.0[0], other.0[0]),
204 f(self.0[1], other.0[1]),
205 f(self.0[2], other.0[2]),
206 ])
207 }
208
209 fn try_zip(
211 self,
212 other: Self,
213 f: impl Fn(usize, usize) -> Option<usize>,
214 ctx: &str,
215 ) -> Result<Self, CodegenError> {
216 let mut out = [0; 3];
217 for (i, slot) in out.iter_mut().enumerate() {
218 *slot = f(self.0[i], other.0[i])
219 .ok_or_else(|| bad_type(ctx, "layout arithmetic overflows usize"))?;
220 }
221 Ok(Self(out))
222 }
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227struct Shape {
228 size: Width,
229 align: Width,
230}
231
232impl Shape {
233 const fn same(size: usize) -> Self {
234 Self {
235 size: Width::same(size),
236 align: Width::same(size),
237 }
238 }
239 const POINTER: Self = Self {
240 size: Width([8, 4, 4]),
241 align: Width([8, 4, 4]),
242 };
243}
244
245#[derive(Debug, Clone, Copy)]
247pub struct FieldLayout<'a> {
248 pub desc: &'a AbiFieldDescriptor,
249 pub ty: Ty<'a>,
250 pub offset: Width,
251}
252
253impl FieldLayout<'_> {
254 pub fn name(&self) -> &str {
255 self.desc.name
256 }
257}
258
259#[derive(Debug, Clone)]
261pub struct RecordLayout<'a> {
262 pub name: &'a str,
263 pub doc: Option<&'a str>,
264 pub is_union: bool,
265 pub size: Width,
266 pub align: Width,
267 pub fields: Vec<FieldLayout<'a>>,
268 pub alignas: Option<usize>,
271 pub slab_align: Option<usize>,
274 pub natural_align: Width,
276}
277
278impl RecordLayout<'_> {
279 pub fn is_fixed(&self) -> bool {
281 self.size.fixed().is_some() && self.fields.iter().all(|f| f.offset.fixed().is_some())
282 }
283}
284
285pub fn layout_records<'a>(
288 files: &[&'a AbiFileDescriptor],
289) -> Result<Vec<RecordLayout<'a>>, CodegenError> {
290 layout_records_on(&[], &[], files)
291}
292
293pub fn layout_records_on<'a>(
297 base: &[RecordLayout<'a>],
298 base_files: &[&'a AbiFileDescriptor],
299 files: &[&'a AbiFileDescriptor],
300) -> Result<Vec<RecordLayout<'a>>, CodegenError> {
301 let mut shapes: BTreeMap<&'a str, Shape> = base
302 .iter()
303 .map(|r| (r.name, Shape { size: r.size, align: r.align }))
304 .collect();
305 let mut enums: BTreeSet<&'a str> = BTreeSet::new();
306 let mut callbacks: BTreeSet<&'a str> = BTreeSet::new();
307 let embedded = embedded_by_value(base_files, files);
308
309 for e in base_files.iter().chain(files).flat_map(|f| f.enums) {
312 Scalar::parse(e.repr).ok_or_else(|| bad_type(e.repr, "enum repr"))?;
313 enums.insert(e.name);
314 }
315 for cb in base_files.iter().chain(files).flat_map(|f| f.callbacks) {
316 callbacks.insert(cb.name);
317 shapes.insert(cb.name, Shape::POINTER);
318 }
319 for alias in base_files.iter().chain(files).flat_map(|f| f.aliases) {
320 let shape = shape_of(Ty::parse(alias.target)?, &shapes, &enums, &callbacks, alias.name)?;
321 shapes.insert(alias.name, shape);
322 if let Some(rn) = alias.rust_name {
323 shapes.insert(rn, shape);
324 }
325 }
326 let mut out = Vec::new();
327 for file in files {
328 for record in file.records {
329 let layout = layout_record(record, &shapes, &enums, &callbacks, &embedded)?;
330 check_against_rustc(record, &layout)?;
331 shapes.insert(
332 layout.name,
333 Shape {
334 size: layout.size,
335 align: layout.align,
336 },
337 );
338 out.push(layout);
339 }
340 }
341 Ok(out)
342}
343
344fn shape_of(
345 ty: Ty<'_>,
346 shapes: &BTreeMap<&str, Shape>,
347 enums: &BTreeSet<&str>,
348 callbacks: &BTreeSet<&str>,
349 ctx: &str,
350) -> Result<Shape, CodegenError> {
351 Ok(match ty {
352 Ty::Ptr { .. } => Shape::POINTER,
354 Ty::Nullable(inner) if callbacks.contains(inner) => Shape::POINTER,
355 Ty::Nullable(inner) => {
356 return Err(CodegenError::validation(format!(
357 "`{ctx}`: `Option<{inner}>` is only valid for declared callback typedefs"
358 )));
359 }
360 Ty::Named(name) if enums.contains(name) => {
361 return Err(CodegenError::validation(format!(
362 "`{ctx}` stores enum `{name}` by value: C enums are `int`-sized whatever the Rust repr; store its integer repr"
363 )));
364 }
365 Ty::Scalar(s) => s.shape(),
366 Ty::Array { len: 0, .. } => {
367 return Err(bad_type(ctx, "zero-length arrays are not valid C"));
368 }
369 Ty::Array { elem, len } => {
370 let e = shape_of(Ty::parse(elem)?, shapes, enums, callbacks, ctx)?;
371 let mut size = [0; 3];
372 for (out, n) in size.iter_mut().zip(e.size.0) {
373 *out = n
374 .checked_mul(len)
375 .ok_or_else(|| bad_type(ctx, "array size overflows usize"))?;
376 }
377 Shape {
378 size: Width(size),
379 align: e.align,
380 }
381 }
382 Ty::Named(name) => *shapes.get(name).ok_or_else(|| {
383 CodegenError::validation(format!("`{ctx}` uses `{name}` before it is declared"))
384 })?,
385 Ty::Unit | Ty::Void => {
386 return Err(bad_type(ctx, "`()` / `c_void` cannot be stored by value"));
387 }
388 })
389}
390
391fn embedded_by_value<'a>(
394 base_files: &[&'a AbiFileDescriptor],
395 files: &[&'a AbiFileDescriptor],
396) -> BTreeSet<&'a str> {
397 let mut aliases: BTreeMap<&str, &str> = BTreeMap::new();
398 for a in base_files.iter().chain(files).flat_map(|f| f.aliases) {
399 aliases.insert(a.name, a.target);
400 if let Some(rn) = a.rust_name {
401 aliases.insert(rn, a.target);
402 }
403 }
404 let mut out = BTreeSet::new();
405 for record in files.iter().flat_map(|f| f.records) {
406 let fields = match record {
407 AbiRecordDescriptor::Struct(s) => s.fields,
408 AbiRecordDescriptor::Union(u) => u.fields,
409 };
410 for f in fields {
411 let mut ty = Ty::parse(f.abi_type());
412 for _ in 0..=aliases.len() {
413 while let Ok(Ty::Array { elem, .. }) = ty {
414 ty = Ty::parse(elem);
415 }
416 let Ok(Ty::Named(name)) = ty else { break };
417 match aliases.get(name) {
418 Some(target) => ty = Ty::parse(target),
419 None => {
420 out.insert(name);
421 break;
422 }
423 }
424 }
425 }
426 }
427 out
428}
429
430fn layout_record<'a>(
431 record: &'a AbiRecordDescriptor,
432 shapes: &BTreeMap<&str, Shape>,
433 enums: &BTreeSet<&str>,
434 callbacks: &BTreeSet<&str>,
435 embedded: &BTreeSet<&str>,
436) -> Result<RecordLayout<'a>, CodegenError> {
437 let (name, doc, is_union, descs, explicit_align) = match record {
438 AbiRecordDescriptor::Struct(s) => (s.name, s.doc, false, s.fields, s.explicit_align),
439 AbiRecordDescriptor::Union(u) => (u.name, u.doc, true, u.fields, u.explicit_align),
440 };
441 let mut fields = Vec::with_capacity(descs.len());
442 let (mut end, mut align) = (Width::same(0), Width::same(1));
443 for desc in descs {
444 let ty = Ty::parse(desc.abi_type())?;
445 let ctx = name;
446 let shape = shape_of(ty, shapes, enums, callbacks, ctx)?;
447 let offset = if is_union {
448 Width::same(0)
449 } else {
450 end.try_zip(shape.align, round_up, ctx)?
451 };
452 end = end.zip(
453 offset.try_zip(shape.size, usize::checked_add, ctx)?,
454 usize::max,
455 );
456 align = align.zip(shape.align, usize::max);
457 fields.push(FieldLayout { desc, ty, offset });
458 }
459 let natural_align = align;
460 let natural_size = end.try_zip(align, round_up, name)?;
461 let (mut alignas, mut slab_align) = (None, None);
462 if let Some(explicit) = explicit_align {
463 if !explicit.is_power_of_two() {
464 return Err(bad_type(name, "`align(N)` must be a non-zero power of two"));
465 }
466 if align.0.iter().any(|&n| explicit > n) {
467 let over = align.zip(Width::same(explicit), usize::max);
468 if explicit <= MAX_C_ALIGNAS {
469 alignas = Some(explicit);
470 align = over;
471 } else if natural_size.try_zip(over, round_up, name)? == natural_size
472 && !embedded.contains(name)
473 {
474 slab_align = Some(explicit);
475 } else {
476 return Err(bad_type(
477 name,
478 &format!(
479 "`align({explicit})` changes the C layout, and C / Swift hosts cannot over-align past {MAX_C_ALIGNAS}"
480 ),
481 ));
482 }
483 }
484 }
485 let size = end.try_zip(align, round_up, name)?;
486 Ok(RecordLayout {
487 name,
488 doc,
489 is_union,
490 size,
491 align,
492 fields,
493 alignas,
494 slab_align,
495 natural_align,
496 })
497}
498
499pub const MAX_C_ALIGNAS: usize = 16;
501
502fn round_up(n: usize, align: usize) -> Option<usize> {
504 n.div_ceil(align).checked_mul(align)
505}
506
507fn check_against_rustc(
509 record: &AbiRecordDescriptor,
510 layout: &RecordLayout<'_>,
511) -> Result<(), CodegenError> {
512 let (size, align, expected_size, expected_size_64) = match record {
513 AbiRecordDescriptor::Struct(s) => (s.size, s.align, s.expected_size, s.expected_size_64),
514 AbiRecordDescriptor::Union(u) => (u.size, u.align, u.expected_size, u.expected_size_64),
515 };
516 let host = Model::host();
517 let fail = |what: String| {
518 Err(CodegenError::validation(format!(
519 "`{}` C layout drifted from `rustc`: {what}",
520 layout.name
521 )))
522 };
523 if layout.size.at(host) != size {
524 return fail(format!("size {} != rustc {size}", layout.size.at(host)));
525 }
526 let c_align = layout.align.at(host);
527 if c_align.max(layout.slab_align.unwrap_or(1)) != align {
528 return fail(format!("alignment {c_align} != rustc {align}"));
529 }
530 if expected_size.is_some_and(|n| layout.size.fixed() != Some(n)) {
531 return fail(format!(
532 "size {:?} breaks the `size = {expected_size:?}` contract",
533 layout.size
534 ));
535 }
536 if expected_size_64.is_some_and(|n| layout.size.p64() != n) {
537 return fail(format!(
538 "64-bit size {} breaks `size_64 = {expected_size_64:?}`",
539 layout.size.p64()
540 ));
541 }
542 for f in &layout.fields {
543 let d = f.desc;
544 if f.offset.at(host) != d.offset {
545 return fail(format!(
546 "`{}` offset {} != rustc {}",
547 d.name,
548 f.offset.at(host),
549 d.offset
550 ));
551 }
552 if d.expected_offset
553 .is_some_and(|n| f.offset.fixed() != Some(n))
554 {
555 return fail(format!(
556 "`{}` offset {:?} breaks `offset = {:?}`",
557 d.name, f.offset, d.expected_offset
558 ));
559 }
560 if d.expected_offset_64.is_some_and(|n| f.offset.p64() != n) {
561 return fail(format!(
562 "`{}` 64-bit offset {} breaks `offset64`",
563 d.name,
564 f.offset.p64()
565 ));
566 }
567 }
568 Ok(())
569}
570
571mod vtable;
572
573pub use vtable::{VtableHeaderLayout, layout_vtable_headers_on};
574
575#[cfg(test)]
576mod tests;