Coverage Report

Created: 2026-08-02 07:35

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