wit_parser/
sizealign.rs

1use std::{
2    cmp::Ordering,
3    num::NonZeroUsize,
4    ops::{Add, AddAssign},
5};
6
7use crate::{FlagsRepr, Int, Resolve, Type, TypeDef, TypeDefKind};
8
9/// Architecture specific alignment
10#[derive(Eq, PartialEq, Clone, Copy)]
11pub enum Alignment {
12    /// This represents 4 byte alignment on 32bit and 8 byte alignment on 64bit architectures
13    Pointer,
14    /// This alignment is architecture independent (derived from integer or float types)
15    Bytes(NonZeroUsize),
16}
17
18impl Default for Alignment {
19    fn default() -> Self {
20        Alignment::Bytes(NonZeroUsize::new(1).unwrap())
21    }
22}
23
24impl std::fmt::Debug for Alignment {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        match self {
27            Alignment::Pointer => f.write_str("ptr"),
28            Alignment::Bytes(b) => f.write_fmt(format_args!("{}", b.get())),
29        }
30    }
31}
32
33impl PartialOrd for Alignment {
34    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
35        Some(self.cmp(other))
36    }
37}
38
39impl Ord for Alignment {
40    /// Needed for determining the max alignment of an object from its parts.
41    /// The ordering is: Bytes(1) < Bytes(2) < Bytes(4) < Pointer < Bytes(8)
42    /// as a Pointer is either four or eight byte aligned, depending on the architecture
43    fn cmp(&self, other: &Self) -> Ordering {
44        match (self, other) {
45            (Alignment::Pointer, Alignment::Pointer) => std::cmp::Ordering::Equal,
46            (Alignment::Pointer, Alignment::Bytes(b)) => {
47                if b.get() > 4 {
48                    std::cmp::Ordering::Less
49                } else {
50                    std::cmp::Ordering::Greater
51                }
52            }
53            (Alignment::Bytes(b), Alignment::Pointer) => {
54                if b.get() > 4 {
55                    std::cmp::Ordering::Greater
56                } else {
57                    std::cmp::Ordering::Less
58                }
59            }
60            (Alignment::Bytes(a), Alignment::Bytes(b)) => a.cmp(b),
61        }
62    }
63}
64
65impl Alignment {
66    /// for easy migration this gives you the value for wasm32
67    pub fn align_wasm32(&self) -> usize {
68        match self {
69            Alignment::Pointer => 4,
70            Alignment::Bytes(bytes) => bytes.get(),
71        }
72    }
73
74    pub fn align_wasm64(&self) -> usize {
75        match self {
76            Alignment::Pointer => 8,
77            Alignment::Bytes(bytes) => bytes.get(),
78        }
79    }
80
81    pub fn format(&self, ptrsize_expr: &str) -> String {
82        match self {
83            Alignment::Pointer => ptrsize_expr.into(),
84            Alignment::Bytes(bytes) => format!("{}", bytes.get()),
85        }
86    }
87}
88
89/// Architecture specific measurement of position,
90/// the combined amount in bytes is
91/// `bytes + pointers * core::mem::size_of::<*const u8>()`
92#[derive(Default, Clone, Copy, Eq, PartialEq)]
93pub struct ArchitectureSize {
94    /// architecture independent bytes
95    pub bytes: usize,
96    /// amount of pointer sized units to add
97    pub pointers: usize,
98}
99
100impl Add<ArchitectureSize> for ArchitectureSize {
101    type Output = ArchitectureSize;
102
103    fn add(self, rhs: ArchitectureSize) -> Self::Output {
104        ArchitectureSize::new(self.bytes + rhs.bytes, self.pointers + rhs.pointers)
105    }
106}
107
108impl AddAssign<ArchitectureSize> for ArchitectureSize {
109    fn add_assign(&mut self, rhs: ArchitectureSize) {
110        self.bytes += rhs.bytes;
111        self.pointers += rhs.pointers;
112    }
113}
114
115impl From<Alignment> for ArchitectureSize {
116    fn from(align: Alignment) -> Self {
117        match align {
118            Alignment::Bytes(bytes) => ArchitectureSize::new(bytes.get(), 0),
119            Alignment::Pointer => ArchitectureSize::new(0, 1),
120        }
121    }
122}
123
124impl std::fmt::Debug for ArchitectureSize {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.write_str(&self.format("ptrsz"))
127    }
128}
129
130impl ArchitectureSize {
131    pub fn new(bytes: usize, pointers: usize) -> Self {
132        Self { bytes, pointers }
133    }
134
135    pub fn max<B: std::borrow::Borrow<Self>>(&self, other: B) -> Self {
136        let other = other.borrow();
137        let self32 = self.size_wasm32();
138        let self64 = self.size_wasm64();
139        let other32 = other.size_wasm32();
140        let other64 = other.size_wasm64();
141        if self32 >= other32 && self64 >= other64 {
142            *self
143        } else if self32 <= other32 && self64 <= other64 {
144            *other
145        } else {
146            // we can assume a combination of bytes and pointers, so align to at least pointer size
147            let new32 = align_to(self32.max(other32), 4);
148            let new64 = align_to(self64.max(other64), 8);
149            ArchitectureSize::new(new32 + new32 - new64, (new64 - new32) / 4)
150        }
151    }
152
153    pub fn add_bytes(&self, b: usize) -> Self {
154        Self::new(self.bytes + b, self.pointers)
155    }
156
157    /// The effective offset/size is
158    /// `constant_bytes() + core::mem::size_of::<*const u8>() * pointers_to_add()`
159    pub fn constant_bytes(&self) -> usize {
160        self.bytes
161    }
162
163    pub fn pointers_to_add(&self) -> usize {
164        self.pointers
165    }
166
167    /// Shortcut for compatibility with previous versions
168    pub fn size_wasm32(&self) -> usize {
169        self.bytes + self.pointers * 4
170    }
171
172    pub fn size_wasm64(&self) -> usize {
173        self.bytes + self.pointers * 8
174    }
175
176    /// prefer this over >0
177    pub fn is_empty(&self) -> bool {
178        self.bytes == 0 && self.pointers == 0
179    }
180
181    // create a suitable expression in bytes from a pointer size argument
182    pub fn format(&self, ptrsize_expr: &str) -> String {
183        self.format_term(ptrsize_expr, false)
184    }
185
186    // create a suitable expression in bytes from a pointer size argument,
187    // extended API with optional brackets around the sum
188    pub fn format_term(&self, ptrsize_expr: &str, suppress_brackets: bool) -> String {
189        if self.pointers != 0 {
190            if self.bytes > 0 {
191                // both
192                if suppress_brackets {
193                    format!(
194                        "{}+{}*{ptrsize_expr}",
195                        self.constant_bytes(),
196                        self.pointers_to_add()
197                    )
198                } else {
199                    format!(
200                        "({}+{}*{ptrsize_expr})",
201                        self.constant_bytes(),
202                        self.pointers_to_add()
203                    )
204                }
205            } else if self.pointers == 1 {
206                // one pointer
207                ptrsize_expr.into()
208            } else {
209                // only pointer
210                if suppress_brackets {
211                    format!("{}*{ptrsize_expr}", self.pointers_to_add())
212                } else {
213                    format!("({}*{ptrsize_expr})", self.pointers_to_add())
214                }
215            }
216        } else {
217            // only bytes
218            format!("{}", self.constant_bytes())
219        }
220    }
221}
222
223/// Information per structure element
224#[derive(Default)]
225pub struct ElementInfo {
226    pub size: ArchitectureSize,
227    pub align: Alignment,
228}
229
230impl From<Alignment> for ElementInfo {
231    fn from(align: Alignment) -> Self {
232        ElementInfo {
233            size: align.into(),
234            align,
235        }
236    }
237}
238
239impl ElementInfo {
240    fn new(size: ArchitectureSize, align: Alignment) -> Self {
241        Self { size, align }
242    }
243}
244
245/// Collect size and alignment for sub-elements of a structure
246#[derive(Default)]
247pub struct SizeAlign {
248    map: Vec<ElementInfo>,
249}
250
251impl SizeAlign {
252    pub fn fill(&mut self, resolve: &Resolve) {
253        self.map = Vec::new();
254        for (_, ty) in resolve.types.iter() {
255            let pair = self.calculate(ty);
256            self.map.push(pair);
257        }
258    }
259
260    fn calculate(&self, ty: &TypeDef) -> ElementInfo {
261        match &ty.kind {
262            TypeDefKind::Type(t) => ElementInfo::new(self.size(t), self.align(t)),
263            TypeDefKind::FixedSizeList(t, size) => {
264                let field_align = self.align(t);
265                let field_size = self.size(t);
266                ElementInfo::new(
267                    ArchitectureSize::new(
268                        field_size.bytes.checked_mul(*size as usize).unwrap(),
269                        field_size.pointers.checked_mul(*size as usize).unwrap(),
270                    ),
271                    field_align,
272                )
273            }
274            TypeDefKind::List(_) => {
275                ElementInfo::new(ArchitectureSize::new(0, 2), Alignment::Pointer)
276            }
277            TypeDefKind::Record(r) => self.record(r.fields.iter().map(|f| &f.ty)),
278            TypeDefKind::Tuple(t) => self.record(t.types.iter()),
279            TypeDefKind::Flags(f) => match f.repr() {
280                FlagsRepr::U8 => int_size_align(Int::U8),
281                FlagsRepr::U16 => int_size_align(Int::U16),
282                FlagsRepr::U32(n) => ElementInfo::new(
283                    ArchitectureSize::new(n * 4, 0),
284                    Alignment::Bytes(NonZeroUsize::new(4).unwrap()),
285                ),
286            },
287            TypeDefKind::Variant(v) => self.variant(v.tag(), v.cases.iter().map(|c| c.ty.as_ref())),
288            TypeDefKind::Enum(e) => self.variant(e.tag(), []),
289            TypeDefKind::Option(t) => self.variant(Int::U8, [Some(t)]),
290            TypeDefKind::Result(r) => self.variant(Int::U8, [r.ok.as_ref(), r.err.as_ref()]),
291            // A resource is represented as an index.
292            // A future is represented as an index.
293            // A stream is represented as an index.
294            // An error is represented as an index.
295            TypeDefKind::Handle(_) | TypeDefKind::Future(_) | TypeDefKind::Stream(_) => {
296                int_size_align(Int::U32)
297            }
298            // This shouldn't be used for anything since raw resources aren't part of the ABI -- just handles to
299            // them.
300            TypeDefKind::Resource => ElementInfo::new(
301                ArchitectureSize::new(usize::MAX, 0),
302                Alignment::Bytes(NonZeroUsize::new(usize::MAX).unwrap()),
303            ),
304            TypeDefKind::Unknown => unreachable!(),
305        }
306    }
307
308    pub fn size(&self, ty: &Type) -> ArchitectureSize {
309        match ty {
310            Type::Bool | Type::U8 | Type::S8 => ArchitectureSize::new(1, 0),
311            Type::U16 | Type::S16 => ArchitectureSize::new(2, 0),
312            Type::U32 | Type::S32 | Type::F32 | Type::Char | Type::ErrorContext => {
313                ArchitectureSize::new(4, 0)
314            }
315            Type::U64 | Type::S64 | Type::F64 => ArchitectureSize::new(8, 0),
316            Type::String => ArchitectureSize::new(0, 2),
317            Type::Id(id) => self.map[id.index()].size,
318        }
319    }
320
321    pub fn align(&self, ty: &Type) -> Alignment {
322        match ty {
323            Type::Bool | Type::U8 | Type::S8 => Alignment::Bytes(NonZeroUsize::new(1).unwrap()),
324            Type::U16 | Type::S16 => Alignment::Bytes(NonZeroUsize::new(2).unwrap()),
325            Type::U32 | Type::S32 | Type::F32 | Type::Char | Type::ErrorContext => {
326                Alignment::Bytes(NonZeroUsize::new(4).unwrap())
327            }
328            Type::U64 | Type::S64 | Type::F64 => Alignment::Bytes(NonZeroUsize::new(8).unwrap()),
329            Type::String => Alignment::Pointer,
330            Type::Id(id) => self.map[id.index()].align,
331        }
332    }
333
334    pub fn field_offsets<'a>(
335        &self,
336        types: impl IntoIterator<Item = &'a Type>,
337    ) -> Vec<(ArchitectureSize, &'a Type)> {
338        let mut cur = ArchitectureSize::default();
339        types
340            .into_iter()
341            .map(|ty| {
342                let ret = align_to_arch(cur, self.align(ty));
343                cur = ret + self.size(ty);
344                (ret, ty)
345            })
346            .collect()
347    }
348
349    pub fn payload_offset<'a>(
350        &self,
351        tag: Int,
352        cases: impl IntoIterator<Item = Option<&'a Type>>,
353    ) -> ArchitectureSize {
354        let mut max_align = Alignment::default();
355        for ty in cases {
356            if let Some(ty) = ty {
357                max_align = max_align.max(self.align(ty));
358            }
359        }
360        let tag_size = int_size_align(tag).size;
361        align_to_arch(tag_size, max_align)
362    }
363
364    pub fn record<'a>(&self, types: impl IntoIterator<Item = &'a Type>) -> ElementInfo {
365        let mut size = ArchitectureSize::default();
366        let mut align = Alignment::default();
367        for ty in types {
368            let field_size = self.size(ty);
369            let field_align = self.align(ty);
370            size = align_to_arch(size, field_align) + field_size;
371            align = align.max(field_align);
372        }
373        ElementInfo::new(align_to_arch(size, align), align)
374    }
375
376    pub fn params<'a>(&self, types: impl IntoIterator<Item = &'a Type>) -> ElementInfo {
377        self.record(types.into_iter())
378    }
379
380    fn variant<'a>(
381        &self,
382        tag: Int,
383        types: impl IntoIterator<Item = Option<&'a Type>>,
384    ) -> ElementInfo {
385        let ElementInfo {
386            size: discrim_size,
387            align: discrim_align,
388        } = int_size_align(tag);
389        let mut case_size = ArchitectureSize::default();
390        let mut case_align = Alignment::default();
391        for ty in types {
392            if let Some(ty) = ty {
393                case_size = case_size.max(&self.size(ty));
394                case_align = case_align.max(self.align(ty));
395            }
396        }
397        let align = discrim_align.max(case_align);
398        let discrim_aligned = align_to_arch(discrim_size, case_align);
399        let size_sum = discrim_aligned + case_size;
400        ElementInfo::new(align_to_arch(size_sum, align), align)
401    }
402}
403
404fn int_size_align(i: Int) -> ElementInfo {
405    match i {
406        Int::U8 => Alignment::Bytes(NonZeroUsize::new(1).unwrap()),
407        Int::U16 => Alignment::Bytes(NonZeroUsize::new(2).unwrap()),
408        Int::U32 => Alignment::Bytes(NonZeroUsize::new(4).unwrap()),
409        Int::U64 => Alignment::Bytes(NonZeroUsize::new(8).unwrap()),
410    }
411    .into()
412}
413
414/// Increase `val` to a multiple of `align`;
415/// `align` must be a power of two
416pub(crate) fn align_to(val: usize, align: usize) -> usize {
417    (val + align - 1) & !(align - 1)
418}
419
420/// Increase `val` to a multiple of `align`, with special handling for pointers;
421/// `align` must be a power of two or `Alignment::Pointer`
422pub fn align_to_arch(val: ArchitectureSize, align: Alignment) -> ArchitectureSize {
423    match align {
424        Alignment::Pointer => {
425            let new32 = align_to(val.bytes, 4);
426            if new32 != align_to(new32, 8) {
427                ArchitectureSize::new(new32 - 4, val.pointers + 1)
428            } else {
429                ArchitectureSize::new(new32, val.pointers)
430            }
431        }
432        Alignment::Bytes(align_bytes) => {
433            let align_bytes = align_bytes.get();
434            if align_bytes > 4 && (val.pointers & 1) != 0 {
435                let new_bytes = align_to(val.bytes, align_bytes);
436                if (new_bytes - val.bytes) >= 4 {
437                    // up to four extra bytes fit together with a the extra 32 bit pointer
438                    // and the 64 bit pointer is always 8 bytes (so no change in value)
439                    ArchitectureSize::new(new_bytes - 8, val.pointers + 1)
440                } else {
441                    // there is no room to combine, so the odd pointer aligns to 8 bytes
442                    ArchitectureSize::new(new_bytes + 8, val.pointers - 1)
443                }
444            } else {
445                ArchitectureSize::new(align_to(val.bytes, align_bytes), val.pointers)
446            }
447        }
448    }
449}
450
451#[cfg(test)]
452mod test {
453    use super::*;
454
455    #[test]
456    fn align() {
457        // u8 + ptr
458        assert_eq!(
459            align_to_arch(ArchitectureSize::new(1, 0), Alignment::Pointer),
460            ArchitectureSize::new(0, 1)
461        );
462        // u8 + u64
463        assert_eq!(
464            align_to_arch(
465                ArchitectureSize::new(1, 0),
466                Alignment::Bytes(NonZeroUsize::new(8).unwrap())
467            ),
468            ArchitectureSize::new(8, 0)
469        );
470        // u8 + u32
471        assert_eq!(
472            align_to_arch(
473                ArchitectureSize::new(1, 0),
474                Alignment::Bytes(NonZeroUsize::new(4).unwrap())
475            ),
476            ArchitectureSize::new(4, 0)
477        );
478        // ptr + u64
479        assert_eq!(
480            align_to_arch(
481                ArchitectureSize::new(0, 1),
482                Alignment::Bytes(NonZeroUsize::new(8).unwrap())
483            ),
484            ArchitectureSize::new(8, 0)
485        );
486        // u32 + ptr
487        assert_eq!(
488            align_to_arch(ArchitectureSize::new(4, 0), Alignment::Pointer),
489            ArchitectureSize::new(0, 1)
490        );
491        // u32, ptr + u64
492        assert_eq!(
493            align_to_arch(
494                ArchitectureSize::new(0, 2),
495                Alignment::Bytes(NonZeroUsize::new(8).unwrap())
496            ),
497            ArchitectureSize::new(0, 2)
498        );
499        // ptr, u8 + u64
500        assert_eq!(
501            align_to_arch(
502                ArchitectureSize::new(1, 1),
503                Alignment::Bytes(NonZeroUsize::new(8).unwrap())
504            ),
505            ArchitectureSize::new(0, 2)
506        );
507        // ptr, u8 + ptr
508        assert_eq!(
509            align_to_arch(ArchitectureSize::new(1, 1), Alignment::Pointer),
510            ArchitectureSize::new(0, 2)
511        );
512        // ptr, ptr, u8 + u64
513        assert_eq!(
514            align_to_arch(
515                ArchitectureSize::new(1, 2),
516                Alignment::Bytes(NonZeroUsize::new(8).unwrap())
517            ),
518            ArchitectureSize::new(8, 2)
519        );
520        assert_eq!(
521            align_to_arch(
522                ArchitectureSize::new(30, 3),
523                Alignment::Bytes(NonZeroUsize::new(8).unwrap())
524            ),
525            ArchitectureSize::new(40, 2)
526        );
527
528        assert_eq!(
529            ArchitectureSize::new(12, 0).max(&ArchitectureSize::new(0, 2)),
530            ArchitectureSize::new(8, 1)
531        );
532        assert_eq!(
533            ArchitectureSize::new(10, 0).max(&ArchitectureSize::new(0, 2)),
534            ArchitectureSize::new(8, 1)
535        );
536
537        assert_eq!(
538            align_to_arch(
539                ArchitectureSize::new(2, 0),
540                Alignment::Bytes(NonZeroUsize::new(8).unwrap())
541            ),
542            ArchitectureSize::new(8, 0)
543        );
544        assert_eq!(
545            align_to_arch(ArchitectureSize::new(2, 0), Alignment::Pointer),
546            ArchitectureSize::new(0, 1)
547        );
548    }
549
550    #[test]
551    fn resource_size() {
552        // keep it identical to the old behavior
553        let obj = SizeAlign::default();
554        let elem = obj.calculate(&TypeDef {
555            name: None,
556            kind: TypeDefKind::Resource,
557            owner: crate::TypeOwner::None,
558            docs: Default::default(),
559            stability: Default::default(),
560        });
561        assert_eq!(elem.size, ArchitectureSize::new(usize::MAX, 0));
562        assert_eq!(
563            elem.align,
564            Alignment::Bytes(NonZeroUsize::new(usize::MAX).unwrap())
565        );
566    }
567    #[test]
568    fn result_ptr_10() {
569        let mut obj = SizeAlign::default();
570        let mut resolve = Resolve::default();
571        let tuple = crate::Tuple {
572            types: vec![Type::U16, Type::U16, Type::U16, Type::U16, Type::U16],
573        };
574        let id = resolve.types.alloc(TypeDef {
575            name: None,
576            kind: TypeDefKind::Tuple(tuple),
577            owner: crate::TypeOwner::None,
578            docs: Default::default(),
579            stability: Default::default(),
580        });
581        obj.fill(&resolve);
582        let my_result = crate::Result_ {
583            ok: Some(Type::String),
584            err: Some(Type::Id(id)),
585        };
586        let elem = obj.calculate(&TypeDef {
587            name: None,
588            kind: TypeDefKind::Result(my_result),
589            owner: crate::TypeOwner::None,
590            docs: Default::default(),
591            stability: Default::default(),
592        });
593        assert_eq!(elem.size, ArchitectureSize::new(8, 2));
594        assert_eq!(elem.align, Alignment::Pointer);
595    }
596    #[test]
597    fn result_ptr_64bit() {
598        let obj = SizeAlign::default();
599        let my_record = crate::Record {
600            fields: vec![
601                crate::Field {
602                    name: String::new(),
603                    ty: Type::String,
604                    docs: Default::default(),
605                },
606                crate::Field {
607                    name: String::new(),
608                    ty: Type::U64,
609                    docs: Default::default(),
610                },
611            ],
612        };
613        let elem = obj.calculate(&TypeDef {
614            name: None,
615            kind: TypeDefKind::Record(my_record),
616            owner: crate::TypeOwner::None,
617            docs: Default::default(),
618            stability: Default::default(),
619        });
620        assert_eq!(elem.size, ArchitectureSize::new(8, 2));
621        assert_eq!(elem.align, Alignment::Bytes(NonZeroUsize::new(8).unwrap()));
622    }
623}