wit_parser/abi.rs
1use crate::{Function, Handle, Int, Resolve, Type, TypeDefKind};
2
3/// A core WebAssembly signature with params and results.
4#[derive(Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
5pub struct WasmSignature {
6 /// The WebAssembly parameters of this function.
7 pub params: Vec<WasmType>,
8
9 /// The WebAssembly results of this function.
10 pub results: Vec<WasmType>,
11
12 /// Whether or not this signature is passing all of its parameters
13 /// indirectly through a pointer within `params`.
14 ///
15 /// Note that `params` still reflects the true wasm parameters of this
16 /// function, this is auxiliary information for code generators if
17 /// necessary.
18 pub indirect_params: bool,
19
20 /// Whether or not this signature is using a return pointer to store the
21 /// result of the function, which is reflected either in `params` or
22 /// `results` depending on the context this function is used (e.g. an import
23 /// or an export).
24 pub retptr: bool,
25}
26
27/// Enumerates wasm types used by interface types when lowering/lifting.
28#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub enum WasmType {
30 I32,
31 I64,
32 F32,
33 F64,
34
35 /// A pointer type. In core Wasm this typically lowers to either `i32` or
36 /// `i64` depending on the index type of the exported linear memory,
37 /// however bindings can use different source-level types to preserve
38 /// provenance.
39 ///
40 /// Users that don't do anything special for pointers can treat this as
41 /// `i32`.
42 Pointer,
43
44 /// A type for values which can be either pointers or 64-bit integers.
45 /// This occurs in variants, when pointers and non-pointers are unified.
46 ///
47 /// Users that don't do anything special for pointers can treat this as
48 /// `i64`.
49 PointerOrI64,
50
51 /// An array length type. In core Wasm this lowers to either `i32` or `i64`
52 /// depending on the index type of the exported linear memory.
53 ///
54 /// Users that don't do anything special for pointers can treat this as
55 /// `i32`.
56 Length,
57 // NOTE: we don't lower interface types to any other Wasm type,
58 // e.g. externref, so we don't need to define them here.
59}
60
61fn join(a: WasmType, b: WasmType) -> WasmType {
62 use WasmType::*;
63
64 match (a, b) {
65 (I32, I32)
66 | (I64, I64)
67 | (F32, F32)
68 | (F64, F64)
69 | (Pointer, Pointer)
70 | (PointerOrI64, PointerOrI64)
71 | (Length, Length) => a,
72
73 (I32, F32) | (F32, I32) => I32,
74
75 // A length is at least an `i32`, maybe more, so it wins over
76 // 32-bit types.
77 (Length, I32 | F32) => Length,
78 (I32 | F32, Length) => Length,
79
80 // A length might be an `i64`, but might not be, so if we have
81 // 64-bit types, they win.
82 (Length, I64 | F64) => I64,
83 (I64 | F64, Length) => I64,
84
85 // Pointers have provenance and are at least an `i32`, so they
86 // win over 32-bit and length types.
87 (Pointer, I32 | F32 | Length) => Pointer,
88 (I32 | F32 | Length, Pointer) => Pointer,
89
90 // If we need 64 bits and provenance, we need to use the special
91 // `PointerOrI64`.
92 (Pointer, I64 | F64) => PointerOrI64,
93 (I64 | F64, Pointer) => PointerOrI64,
94
95 // PointerOrI64 wins over everything.
96 (PointerOrI64, _) => PointerOrI64,
97 (_, PointerOrI64) => PointerOrI64,
98
99 // Otherwise, `i64` wins.
100 (_, I64 | F64) | (I64 | F64, _) => I64,
101 }
102}
103
104impl From<Int> for WasmType {
105 fn from(i: Int) -> WasmType {
106 match i {
107 Int::U8 | Int::U16 | Int::U32 => WasmType::I32,
108 Int::U64 => WasmType::I64,
109 }
110 }
111}
112
113/// We use a different ABI for wasm importing functions exported by the host
114/// than for wasm exporting functions imported by the host.
115///
116/// Note that this reflects the flavor of ABI we generate, and not necessarily
117/// the way the resulting bindings will be used by end users. See the comments
118/// on the `Direction` enum in gen-core for details.
119///
120/// The bindings ABI has a concept of a "guest" and a "host". There are two
121/// variants of the ABI, one specialized for the "guest" importing and calling
122/// a function defined and exported in the "host", and the other specialized for
123/// the "host" importing and calling a function defined and exported in the "guest".
124#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
125pub enum AbiVariant {
126 /// The guest is importing and calling the function.
127 GuestImport,
128 /// The guest is defining and exporting the function.
129 GuestExport,
130 GuestImportAsync,
131 GuestExportAsync,
132 GuestExportAsyncStackful,
133}
134
135pub struct FlatTypes<'a> {
136 types: &'a mut [WasmType],
137 cur: usize,
138 overflow: bool,
139}
140
141impl<'a> FlatTypes<'a> {
142 pub fn new(types: &'a mut [WasmType]) -> FlatTypes<'a> {
143 FlatTypes {
144 types,
145 cur: 0,
146 overflow: false,
147 }
148 }
149
150 pub fn push(&mut self, ty: WasmType) -> bool {
151 match self.types.get_mut(self.cur) {
152 Some(next) => {
153 *next = ty;
154 self.cur += 1;
155 true
156 }
157 None => {
158 self.overflow = true;
159 false
160 }
161 }
162 }
163
164 pub fn to_vec(&self) -> Vec<WasmType> {
165 self.types[..self.cur].to_vec()
166 }
167}
168
169impl Resolve {
170 const MAX_FLAT_PARAMS: usize = 16;
171 const MAX_FLAT_ASYNC_PARAMS: usize = 4;
172 const MAX_FLAT_RESULTS: usize = 1;
173
174 /// Get the WebAssembly type signature for this interface function
175 ///
176 /// The first entry returned is the list of parameters and the second entry
177 /// is the list of results for the wasm function signature.
178 pub fn wasm_signature(&self, variant: AbiVariant, func: &Function) -> WasmSignature {
179 // Note that one extra parameter is allocated in case a return pointer
180 // is needed down below for imports.
181 let mut storage = [WasmType::I32; Self::MAX_FLAT_PARAMS + 1];
182 let mut params = FlatTypes::new(&mut storage);
183 let ok = self.push_flat_list(func.params.iter().map(|(_, param)| param), &mut params);
184 assert_eq!(ok, !params.overflow);
185
186 let max = match variant {
187 AbiVariant::GuestImport
188 | AbiVariant::GuestExport
189 | AbiVariant::GuestExportAsync
190 | AbiVariant::GuestExportAsyncStackful => Self::MAX_FLAT_PARAMS,
191 AbiVariant::GuestImportAsync => Self::MAX_FLAT_ASYNC_PARAMS,
192 };
193
194 let indirect_params = !ok || params.cur > max;
195 if indirect_params {
196 params.types[0] = WasmType::Pointer;
197 params.cur = 1;
198 } else {
199 if matches!(
200 (&func.kind, variant),
201 (
202 crate::FunctionKind::Method(_) | crate::FunctionKind::AsyncMethod(_),
203 AbiVariant::GuestExport
204 | AbiVariant::GuestExportAsync
205 | AbiVariant::GuestExportAsyncStackful
206 )
207 ) {
208 // Guest exported methods always receive resource rep as first argument
209 //
210 // TODO: Ideally you would distinguish between imported and exported
211 // resource Handles and then use either I32 or Pointer in abi::push_flat().
212 // But this contextual information isn't available, yet.
213 // See https://github.com/bytecodealliance/wasm-tools/pull/1438 for more details.
214 assert!(matches!(params.types[0], WasmType::I32));
215 params.types[0] = WasmType::Pointer;
216 }
217 }
218
219 let mut storage = [WasmType::I32; Self::MAX_FLAT_RESULTS];
220 let mut results = FlatTypes::new(&mut storage);
221 let mut retptr = false;
222 match variant {
223 AbiVariant::GuestImport | AbiVariant::GuestExport => {
224 if let Some(ty) = &func.result {
225 self.push_flat(ty, &mut results);
226 }
227 retptr = results.overflow;
228
229 // Rust/C don't support multi-value well right now, so if a
230 // function would have multiple results then instead truncate
231 // it. Imports take a return pointer to write into and exports
232 // return a pointer they wrote into.
233 if retptr {
234 results.cur = 0;
235 match variant {
236 AbiVariant::GuestImport => {
237 assert!(params.push(WasmType::Pointer));
238 }
239 AbiVariant::GuestExport => {
240 assert!(results.push(WasmType::Pointer));
241 }
242 _ => unreachable!(),
243 }
244 }
245 }
246 AbiVariant::GuestImportAsync => {
247 // If this function has a result, a pointer must be passed to
248 // get filled in by the async runtime.
249 if func.result.is_some() {
250 assert!(params.push(WasmType::Pointer));
251 retptr = true;
252 }
253
254 // The result of this function is a status code.
255 assert!(results.push(WasmType::I32));
256 }
257 AbiVariant::GuestExportAsync => {
258 // The result of this function is a status code. Note that the
259 // function results are entirely ignored here as they aren't
260 // part of the ABI and are handled in the `task.return`
261 // intrinsic.
262 assert!(results.push(WasmType::I32));
263 }
264 AbiVariant::GuestExportAsyncStackful => {
265 // No status code, and like async exports no result handling.
266 }
267 }
268
269 WasmSignature {
270 params: params.to_vec(),
271 indirect_params,
272 results: results.to_vec(),
273 retptr,
274 }
275 }
276
277 fn push_flat_list<'a>(
278 &self,
279 mut list: impl Iterator<Item = &'a Type>,
280 result: &mut FlatTypes<'_>,
281 ) -> bool {
282 list.all(|ty| self.push_flat(ty, result))
283 }
284
285 /// Appends the flat wasm types representing `ty` onto the `result`
286 /// list provided.
287 pub fn push_flat(&self, ty: &Type, result: &mut FlatTypes<'_>) -> bool {
288 match ty {
289 Type::Bool
290 | Type::S8
291 | Type::U8
292 | Type::S16
293 | Type::U16
294 | Type::S32
295 | Type::U32
296 | Type::Char
297 | Type::ErrorContext => result.push(WasmType::I32),
298
299 Type::U64 | Type::S64 => result.push(WasmType::I64),
300 Type::F32 => result.push(WasmType::F32),
301 Type::F64 => result.push(WasmType::F64),
302 Type::String => result.push(WasmType::Pointer) && result.push(WasmType::Length),
303
304 Type::Id(id) => match &self.types[*id].kind {
305 TypeDefKind::Type(t) => self.push_flat(t, result),
306
307 TypeDefKind::Handle(Handle::Own(_) | Handle::Borrow(_)) => {
308 result.push(WasmType::I32)
309 }
310
311 TypeDefKind::Resource => todo!(),
312
313 TypeDefKind::Record(r) => {
314 self.push_flat_list(r.fields.iter().map(|f| &f.ty), result)
315 }
316
317 TypeDefKind::Tuple(t) => self.push_flat_list(t.types.iter(), result),
318
319 TypeDefKind::Flags(r) => {
320 self.push_flat_list((0..r.repr().count()).map(|_| &Type::U32), result)
321 }
322
323 TypeDefKind::List(_) => {
324 result.push(WasmType::Pointer) && result.push(WasmType::Length)
325 }
326
327 TypeDefKind::FixedSizeList(ty, size) => {
328 self.push_flat_list((0..*size).map(|_| ty), result)
329 }
330
331 TypeDefKind::Variant(v) => {
332 result.push(v.tag().into())
333 && self.push_flat_variants(v.cases.iter().map(|c| c.ty.as_ref()), result)
334 }
335
336 TypeDefKind::Enum(e) => result.push(e.tag().into()),
337
338 TypeDefKind::Option(t) => {
339 result.push(WasmType::I32) && self.push_flat_variants([None, Some(t)], result)
340 }
341
342 TypeDefKind::Result(r) => {
343 result.push(WasmType::I32)
344 && self.push_flat_variants([r.ok.as_ref(), r.err.as_ref()], result)
345 }
346
347 TypeDefKind::Future(_) => result.push(WasmType::I32),
348 TypeDefKind::Stream(_) => result.push(WasmType::I32),
349
350 TypeDefKind::Unknown => unreachable!(),
351 },
352 }
353 }
354
355 fn push_flat_variants<'a>(
356 &self,
357 tys: impl IntoIterator<Item = Option<&'a Type>>,
358 result: &mut FlatTypes<'_>,
359 ) -> bool {
360 let mut temp = result.types[result.cur..].to_vec();
361 let mut temp = FlatTypes::new(&mut temp);
362 let start = result.cur;
363
364 // Push each case's type onto a temporary vector, and then
365 // merge that vector into our final list starting at
366 // `start`. Note that this requires some degree of
367 // "unification" so we can handle things like `Result<i32,
368 // f32>` where that turns into `[i32 i32]` where the second
369 // `i32` might be the `f32` bitcasted.
370 for ty in tys {
371 if let Some(ty) = ty {
372 if !self.push_flat(ty, &mut temp) {
373 result.overflow = true;
374 return false;
375 }
376
377 for (i, ty) in temp.types[..temp.cur].iter().enumerate() {
378 let i = i + start;
379 if i < result.cur {
380 result.types[i] = join(result.types[i], *ty);
381 } else if result.cur == result.types.len() {
382 result.overflow = true;
383 return false;
384 } else {
385 result.types[i] = *ty;
386 result.cur += 1;
387 }
388 }
389 temp.cur = 0;
390 }
391 }
392
393 true
394 }
395}