Debian Codegraph @

crates/wit-component/src/encoding/types.rs

raw
1 use super::EncodingState;
2 use anyhow::Result;
3 use std::collections::HashMap;
4 use wasm_encoder::*;
5 use wit_parser::{
6 Enum, Flags, Function, Handle, InterfaceId, Record, Resolve, Result_, Tuple, Type, TypeDefKind,
7 TypeId, TypeOwner, Variant,
8 };
9
10 /// Represents a key type for interface function definitions.
11 #[derive(Hash, PartialEq, Eq, Clone)]
12 pub struct FunctionKey<'a> {
13 params: &'a [(String, Type)],
14 result: &'a Option<Type>,
15 }
16
17 #[derive(Default, Clone)]
18 pub struct TypeEncodingMaps<'a> {
19 pub id_to_index: HashMap<TypeId, u32>,
20 pub def_to_index: HashMap<&'a TypeDefKind, u32>,
21 pub func_type_map: HashMap<FunctionKey<'a>, u32>,
22 }
23
24 impl<'a> TypeEncodingMaps<'a> {
25 /// Returns the index used to encode `id`, if it has been previously
26 /// encoded.
27 fn lookup(&self, resolve: &'a Resolve, id: TypeId) -> Option<u32> {
28 // If this exact id has been encoded before, use that.
29 if let Some(index) = self.id_to_index.get(&id) {
30 return Some(*index);
31 }
32
33 // If this is an anonymous type, or one where the name of the type is
34 // `none`, then consult the `def_to_index` map as well.
35 let ty = &resolve.types[id];
36 if ty.name.is_none() {
37 if let Some(index) = self.def_to_index.get(&ty.kind) {
38 return Some(*index);
39 }
40 }
41
42 // Failing all that this hasn't previously been encoded.
43 None
44 }
45
46 /// Inserts that `id` was encoded as `index`.
47 fn insert(&mut self, resolve: &'a Resolve, id: TypeId, index: u32) {
48 // Always record the id=>index mapping.
49 self.id_to_index.insert(id, index);
50
51 // Conditionally record the kind=>index mapping if the type is anonymous
52 // and thus a candidate to use.
53 let ty = &resolve.types[id];
54 if ty.name.is_none() {
55 self.def_to_index.insert(&ty.kind, index);
56 }
57 }
58 }
59
60 /// Support for encoding a wit-parser type into a component.
61 ///
62 /// This is a `trait` to enable different implementations which define types
63 /// slightly differently in different contexts. For example types might be
64 /// defined within an instance type's index space or might be defined in the
65 /// component's root index space in a type section. The default trait methods
66 /// here are intended to assist in multiplexing over this difference.
67 pub trait ValtypeEncoder<'a> {
68 /// Returns a new type encoder used to define a new type in this type
69 /// section.
70 ///
71 /// The `u32` returned is the index of the type being defined in this type
72 /// index space and the encoder returned must be used to define a type.
73 fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>);
74
75 /// Returns the index of a new function type and the encoder of where to
76 /// place its results.
77 fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>);
78
79 /// Creates an export item for the specified type index.
80 fn export_type(&mut self, index: u32, name: &'a str) -> Option<u32>;
81
82 /// Creates a new `(type (sub resource))` export with the given name,
83 /// returning the type index that refers to the fresh type created.
84 fn export_resource(&mut self, name: &'a str) -> u32;
85
86 /// Returns the encoding maps used to encoding types such as id-to-index
87 /// maps.
88 fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a>;
89
90 /// Imports `id` from a different interface, returning the index of the
91 /// imported type into this index space.
92 fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32;
93
94 /// Returns the identifier of the interface that generation is for.
95 fn interface(&self) -> Option<InterfaceId>;
96
97 /// Encodes a new function type which is defined within the provided
98 /// document.
99 fn encode_func_type(&mut self, resolve: &'a Resolve, func: &'a Function) -> Result<u32> {
100 let key = FunctionKey {
101 params: &func.params,
102 result: &func.result,
103 };
104 if let Some(index) = self.type_encoding_maps().func_type_map.get(&key) {
105 return Ok(*index);
106 }
107
108 // Encode all referenced parameter types from this function.
109 let params: Vec<_> = self.encode_params(resolve, &func.params)?;
110
111 let result = func
112 .result
113 .map(|ty| self.encode_valtype(resolve, &ty))
114 .transpose()?;
115
116 // Encode the function type
117 let (index, mut f) = self.define_function_type();
118 f.params(params).result(result);
119 let prev = self.type_encoding_maps().func_type_map.insert(key, index);
120 assert!(prev.is_none());
121 Ok(index)
122 }
123
124 fn encode_params(
125 &mut self,
126 resolve: &'a Resolve,
127 params: &'a [(String, Type)],
128 ) -> Result<Vec<(&'a str, ComponentValType)>> {
129 params
130 .iter()
131 .map(|(name, ty)| Ok((name.as_str(), self.encode_valtype(resolve, ty)?)))
132 .collect::<Result<_>>()
133 }
134
135 /// Encodes the `ty`, defined within `resolve`, into this encoder and returns
136 /// the corresponding `ComponentValType` that it represents.
137 ///
138 /// This will recursively define the entire structure of `ty` within `self`
139 /// if necessary.
140 fn encode_valtype(&mut self, resolve: &'a Resolve, ty: &Type) -> Result<ComponentValType> {
141 Ok(match *ty {
142 Type::Bool => ComponentValType::Primitive(PrimitiveValType::Bool),
143 Type::U8 => ComponentValType::Primitive(PrimitiveValType::U8),
144 Type::U16 => ComponentValType::Primitive(PrimitiveValType::U16),
145 Type::U32 => ComponentValType::Primitive(PrimitiveValType::U32),
146 Type::U64 => ComponentValType::Primitive(PrimitiveValType::U64),
147 Type::S8 => ComponentValType::Primitive(PrimitiveValType::S8),
148 Type::S16 => ComponentValType::Primitive(PrimitiveValType::S16),
149 Type::S32 => ComponentValType::Primitive(PrimitiveValType::S32),
150 Type::S64 => ComponentValType::Primitive(PrimitiveValType::S64),
151 Type::F32 => ComponentValType::Primitive(PrimitiveValType::F32),
152 Type::F64 => ComponentValType::Primitive(PrimitiveValType::F64),
153 Type::Char => ComponentValType::Primitive(PrimitiveValType::Char),
154 Type::String => ComponentValType::Primitive(PrimitiveValType::String),
155 Type::ErrorContext => ComponentValType::Primitive(PrimitiveValType::ErrorContext),
156 Type::Id(id) => {
157 // If this id has already been prior defined into this section
158 // refer to that definition.
159 if let Some(index) = self.type_encoding_maps().lookup(resolve, id) {
160 return Ok(ComponentValType::Type(index));
161 }
162
163 let ty = &resolve.types[id];
164
165 // If this type is imported from another interface then return
166 // it as it was bound here with an alias.
167 log::trace!("encode type name={:?} {:?}", ty.name, &ty.kind);
168 if let Some(index) = self.maybe_import_type(resolve, id) {
169 self.type_encoding_maps().insert(resolve, id, index);
170 return Ok(ComponentValType::Type(index));
171 }
172
173 // ... and failing all that insert the type export.
174 let mut encoded = match &ty.kind {
175 TypeDefKind::Record(r) => self.encode_record(resolve, r)?,
176 TypeDefKind::Tuple(t) => self.encode_tuple(resolve, t)?,
177 TypeDefKind::Flags(r) => self.encode_flags(r)?,
178 TypeDefKind::Variant(v) => self.encode_variant(resolve, v)?,
179 TypeDefKind::Option(t) => self.encode_option(resolve, t)?,
180 TypeDefKind::Result(r) => self.encode_result(resolve, r)?,
181 TypeDefKind::Enum(e) => self.encode_enum(e)?,
182 TypeDefKind::List(ty) => {
183 let ty = self.encode_valtype(resolve, ty)?;
184 let (index, encoder) = self.defined_type();
185 encoder.list(ty);
186 ComponentValType::Type(index)
187 }
188 TypeDefKind::FixedSizeList(ty, elements) => {
189 let ty = self.encode_valtype(resolve, ty)?;
190 let (index, encoder) = self.defined_type();
191 encoder.fixed_size_list(ty, *elements);
192 ComponentValType::Type(index)
193 }
194 TypeDefKind::Type(ty) => self.encode_valtype(resolve, ty)?,
195 TypeDefKind::Future(ty) => self.encode_future(resolve, ty)?,
196 TypeDefKind::Stream(ty) => self.encode_stream(resolve, ty)?,
197 TypeDefKind::Unknown => unreachable!(),
198 TypeDefKind::Resource => {
199 let name = ty.name.as_ref().expect("resources must be named");
200 let index = self.export_resource(name);
201 self.type_encoding_maps().id_to_index.insert(id, index);
202 return Ok(ComponentValType::Type(index));
203 }
204 TypeDefKind::Handle(Handle::Own(id)) => {
205 let ty = match self.encode_valtype(resolve, &Type::Id(*id))? {
206 ComponentValType::Type(index) => index,
207 _ => panic!("must be an indexed type"),
208 };
209 let (index, encoder) = self.defined_type();
210 encoder.own(ty);
211 ComponentValType::Type(index)
212 }
213 TypeDefKind::Handle(Handle::Borrow(id)) => {
214 let ty = match self.encode_valtype(resolve, &Type::Id(*id))? {
215 ComponentValType::Type(index) => index,
216 _ => panic!("must be an indexed type"),
217 };
218 let (index, encoder) = self.defined_type();
219 encoder.borrow(ty);
220 ComponentValType::Type(index)
221 }
222 };
223
224 if let Some(name) = &ty.name {
225 let index = match encoded {
226 ComponentValType::Type(index) => index,
227 ComponentValType::Primitive(ty) => {
228 // Named primitive types need entries in the type
229 // section, so convert this to a type reference
230 let (index, encoder) = self.defined_type();
231 encoder.primitive(ty);
232 index
233 }
234 };
235 let index = self.export_type(index, name).unwrap_or(index);
236
237 encoded = ComponentValType::Type(index);
238 }
239
240 if let ComponentValType::Type(index) = encoded {
241 self.type_encoding_maps().insert(resolve, id, index);
242 }
243
244 encoded
245 }
246 })
247 }
248
249 /// Optionally imports `id` from a different interface, returning the index
250 /// of the imported type into this index space.
251 ///
252 /// Returns `None` if `id` can't be imported.
253 fn maybe_import_type(&mut self, resolve: &Resolve, id: TypeId) -> Option<u32> {
254 let ty = &resolve.types[id];
255 let owner = match ty.owner {
256 TypeOwner::Interface(i) => i,
257 _ => return None,
258 };
259 if Some(owner) == self.interface() {
260 return None;
261 }
262 Some(self.import_type(owner, id))
263 }
264
265 fn encode_optional_valtype(
266 &mut self,
267 resolve: &'a Resolve,
268 ty: Option<&Type>,
269 ) -> Result<Option<ComponentValType>> {
270 match ty {
271 Some(ty) => self.encode_valtype(resolve, ty).map(Some),
272 None => Ok(None),
273 }
274 }
275
276 fn encode_record(&mut self, resolve: &'a Resolve, record: &Record) -> Result<ComponentValType> {
277 let fields = record
278 .fields
279 .iter()
280 .map(|f| Ok((f.name.as_str(), self.encode_valtype(resolve, &f.ty)?)))
281 .collect::<Result<Vec<_>>>()?;
282
283 let (index, encoder) = self.defined_type();
284 encoder.record(fields);
285 Ok(ComponentValType::Type(index))
286 }
287
288 fn encode_tuple(&mut self, resolve: &'a Resolve, tuple: &Tuple) -> Result<ComponentValType> {
289 let tys = tuple
290 .types
291 .iter()
292 .map(|ty| self.encode_valtype(resolve, ty))
293 .collect::<Result<Vec<_>>>()?;
294 let (index, encoder) = self.defined_type();
295 encoder.tuple(tys);
296 Ok(ComponentValType::Type(index))
297 }
298
299 fn encode_flags(&mut self, flags: &Flags) -> Result<ComponentValType> {
300 let (index, encoder) = self.defined_type();
301 encoder.flags(flags.flags.iter().map(|f| f.name.as_str()));
302 Ok(ComponentValType::Type(index))
303 }
304
305 fn encode_variant(
306 &mut self,
307 resolve: &'a Resolve,
308 variant: &Variant,
309 ) -> Result<ComponentValType> {
310 let cases = variant
311 .cases
312 .iter()
313 .map(|c| {
314 Ok((
315 c.name.as_str(),
316 self.encode_optional_valtype(resolve, c.ty.as_ref())?,
317 None, // TODO: support defaulting case values in the future
318 ))
319 })
320 .collect::<Result<Vec<_>>>()?;
321
322 let (index, encoder) = self.defined_type();
323 encoder.variant(cases);
324 Ok(ComponentValType::Type(index))
325 }
326
327 fn encode_option(&mut self, resolve: &'a Resolve, payload: &Type) -> Result<ComponentValType> {
328 let ty = self.encode_valtype(resolve, payload)?;
329 let (index, encoder) = self.defined_type();
330 encoder.option(ty);
331 Ok(ComponentValType::Type(index))
332 }
333
334 fn encode_result(
335 &mut self,
336 resolve: &'a Resolve,
337 result: &Result_,
338 ) -> Result<ComponentValType> {
339 let ok = self.encode_optional_valtype(resolve, result.ok.as_ref())?;
340 let error = self.encode_optional_valtype(resolve, result.err.as_ref())?;
341 let (index, encoder) = self.defined_type();
342 encoder.result(ok, error);
343 Ok(ComponentValType::Type(index))
344 }
345
346 fn encode_enum(&mut self, enum_: &Enum) -> Result<ComponentValType> {
347 let (index, encoder) = self.defined_type();
348 encoder.enum_type(enum_.cases.iter().map(|c| c.name.as_str()));
349 Ok(ComponentValType::Type(index))
350 }
351
352 fn encode_future(
353 &mut self,
354 resolve: &'a Resolve,
355 payload: &Option<Type>,
356 ) -> Result<ComponentValType> {
357 let ty = self.encode_optional_valtype(resolve, payload.as_ref())?;
358 let (index, encoder) = self.defined_type();
359 encoder.future(ty);
360 Ok(ComponentValType::Type(index))
361 }
362
363 fn encode_stream(
364 &mut self,
365 resolve: &'a Resolve,
366 payload: &Option<Type>,
367 ) -> Result<ComponentValType> {
368 let ty = self.encode_optional_valtype(resolve, payload.as_ref())?;
369 let (index, encoder) = self.defined_type();
370 encoder.stream(ty);
371 Ok(ComponentValType::Type(index))
372 }
373 }
374
375 pub struct RootTypeEncoder<'state, 'a> {
376 pub state: &'state mut EncodingState<'a>,
377 pub interface: Option<InterfaceId>,
378 pub import_types: bool,
379 }
380
381 impl<'a> ValtypeEncoder<'a> for RootTypeEncoder<'_, 'a> {
382 fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) {
383 self.state.component.type_defined()
384 }
385 fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) {
386 self.state.component.type_function()
387 }
388 fn interface(&self) -> Option<InterfaceId> {
389 self.interface
390 }
391 fn export_type(&mut self, idx: u32, name: &'a str) -> Option<u32> {
392 // When encoding types for the root the root component will export
393 // this type, but when encoding types for a targeted interface then we
394 // can't export types just yet. Interfaces will be created as an
395 // instance with a bag-of-exports construction which can't refer to its
396 // own types.
397 if self.interface.is_none() {
398 Some(if self.import_types {
399 self.state
400 .component
401 .import(name, ComponentTypeRef::Type(TypeBounds::Eq(idx)))
402 } else {
403 self.state
404 .component
405 .export(name, ComponentExportKind::Type, idx, None)
406 })
407 } else {
408 assert!(!self.import_types);
409 None
410 }
411 }
412 fn export_resource(&mut self, name: &'a str) -> u32 {
413 assert!(self.interface.is_none());
414 assert!(self.import_types);
415 self.state
416 .component
417 .import(name, ComponentTypeRef::Type(TypeBounds::SubResource))
418 }
419 fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
420 if !self.import_types {
421 if let Some(cur) = self.interface {
422 let set = &self.state.info.exports_used[&cur];
423 if set.contains(&interface) {
424 return self.state.alias_exported_type(interface, id);
425 }
426 }
427 }
428 self.state.alias_imported_type(interface, id)
429 }
430 fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> {
431 if self.import_types {
432 &mut self.state.import_type_encoding_maps
433 } else {
434 &mut self.state.export_type_encoding_maps
435 }
436 }
437 }
438
439 pub struct InstanceTypeEncoder<'state, 'a> {
440 pub state: &'state mut EncodingState<'a>,
441 pub interface: InterfaceId,
442 pub type_encoding_maps: TypeEncodingMaps<'a>,
443 pub ty: InstanceType,
444 }
445
446 impl<'a> ValtypeEncoder<'a> for InstanceTypeEncoder<'_, 'a> {
447 fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) {
448 (self.ty.type_count(), self.ty.ty().defined_type())
449 }
450 fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) {
451 (self.ty.type_count(), self.ty.ty().function())
452 }
453 fn export_type(&mut self, idx: u32, name: &str) -> Option<u32> {
454 let ret = self.ty.type_count();
455 self.ty
456 .export(name, ComponentTypeRef::Type(TypeBounds::Eq(idx)));
457 Some(ret)
458 }
459 fn export_resource(&mut self, name: &str) -> u32 {
460 let ret = self.ty.type_count();
461 self.ty
462 .export(name, ComponentTypeRef::Type(TypeBounds::SubResource));
463 ret
464 }
465 fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> {
466 &mut self.type_encoding_maps
467 }
468 fn interface(&self) -> Option<InterfaceId> {
469 Some(self.interface)
470 }
471 fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
472 self.ty.alias(Alias::Outer {
473 count: 1,
474 index: self.state.alias_imported_type(interface, id),
475 kind: ComponentOuterAliasKind::Type,
476 });
477 self.ty.type_count() - 1
478 }
479 }