Debian Codegraph @

third_party/rust/wasmparser/src/validator/component.rs

raw
1 //! State relating to validating a WebAssembly component.
2
3 use super::{
4 check_max,
5 component_types::{
6 AliasableResourceId, ComponentAnyTypeId, ComponentCoreInstanceTypeId,
7 ComponentCoreModuleTypeId, ComponentCoreTypeId, ComponentDefinedType,
8 ComponentDefinedTypeId, ComponentEntityType, ComponentFuncType, ComponentFuncTypeId,
9 ComponentInstanceType, ComponentInstanceTypeId, ComponentType, ComponentTypeId,
10 ComponentValType, Context, CoreInstanceTypeKind, InstanceType, LoweringInfo, ModuleType,
11 RecordType, Remap, Remapping, ResourceId, SubtypeCx, TupleType, VariantCase, VariantType,
12 },
13 core::{InternRecGroup, Module},
14 types::{CoreTypeId, EntityType, TypeAlloc, TypeInfo, TypeList},
15 };
16 use crate::collections::index_map::Entry;
17 use crate::limits::*;
18 use crate::prelude::*;
19 use crate::validator::names::{ComponentName, ComponentNameKind, KebabStr, KebabString};
20 use crate::{
21 BinaryReaderError, CanonicalOption, ComponentExportName, ComponentExternalKind,
22 ComponentOuterAliasKind, ComponentTypeRef, CompositeInnerType, ExternalKind, FuncType,
23 GlobalType, InstantiationArgKind, MemoryType, PackedIndex, RefType, Result, SubType, TableType,
24 TypeBounds, ValType, WasmFeatures,
25 };
26 use core::mem;
27
28 fn to_kebab_str<'a>(s: &'a str, desc: &str, offset: usize) -> Result<&'a KebabStr> {
29 match KebabStr::new(s) {
30 Some(s) => Ok(s),
31 None => {
32 if s.is_empty() {
33 bail!(offset, "{desc} name cannot be empty");
34 }
35
36 bail!(offset, "{desc} name `{s}` is not in kebab case");
37 }
38 }
39 }
40
41 pub(crate) struct ComponentState {
42 /// Whether this state is a concrete component, an instance type, or a
43 /// component type.
44 kind: ComponentKind,
45
46 // Core index spaces
47 pub core_types: Vec<ComponentCoreTypeId>,
48 pub core_funcs: Vec<CoreTypeId>,
49 pub core_tags: Vec<CoreTypeId>,
50 pub core_modules: Vec<ComponentCoreModuleTypeId>,
51 pub core_instances: Vec<ComponentCoreInstanceTypeId>,
52 pub core_memories: Vec<MemoryType>,
53 pub core_tables: Vec<TableType>,
54 pub core_globals: Vec<GlobalType>,
55
56 // Component index spaces
57 pub types: Vec<ComponentAnyTypeId>,
58 pub funcs: Vec<ComponentFuncTypeId>,
59 pub values: Vec<(ComponentValType, bool)>,
60 pub instances: Vec<ComponentInstanceTypeId>,
61 pub components: Vec<ComponentTypeId>,
62
63 pub imports: IndexMap<String, ComponentEntityType>,
64 pub import_names: IndexSet<ComponentName>,
65 pub exports: IndexMap<String, ComponentEntityType>,
66 pub export_names: IndexSet<ComponentName>,
67
68 has_start: bool,
69 type_info: TypeInfo,
70
71 /// A mapping of imported resources in this component.
72 ///
73 /// This mapping represents all "type variables" imported into the
74 /// component, or resources. This could be resources imported directly as
75 /// a top-level type import or additionally transitively through other
76 /// imported instances.
77 ///
78 /// The mapping element here is a "path" which is a list of indexes into
79 /// the import map that will be generated for this component. Each index
80 /// is an index into an `IndexMap`, and each list is guaranteed to have at
81 /// least one element.
82 ///
83 /// An example of this map is:
84 ///
85 /// ```wasm
86 /// (component
87 /// ;; [0] - the first import
88 /// (import "r" (type (sub resource)))
89 ///
90 /// ;; [1] - the second import
91 /// (import "r2" (type (sub resource)))
92 ///
93 /// (import "i" (instance
94 /// ;; [2, 0] - the third import, and the first export the instance
95 /// (export "r3" (type (sub resource)))
96 /// ;; [2, 1] - the third import, and the second export the instance
97 /// (export "r4" (type (sub resource)))
98 /// ))
99 ///
100 /// ;; ...
101 /// )
102 /// ```
103 ///
104 /// The `Vec<usize>` here can be thought of as `Vec<String>` but a
105 /// (hopefully) more efficient representation.
106 ///
107 /// Finally note that this map is listed as an "append only" map because all
108 /// insertions into it should always succeed. Any insertion which overlaps
109 /// with a previous entry indicates a bug in the validator which needs to be
110 /// corrected via other means.
111 //
112 // TODO: make these `SkolemResourceId` and then go fix all the compile
113 // errors, don't add skolem things into the type area
114 imported_resources: IndexMapAppendOnly<ResourceId, Vec<usize>>,
115
116 /// A mapping of "defined" resources in this component, or those which
117 /// are defined within the instantiation of this component.
118 ///
119 /// Defined resources, as the name implies, can sort of be thought of as
120 /// "these are defined within the component". Note though that the means by
121 /// which a local definition can occur are not simply those defined in the
122 /// component but also in its transitively instantiated components
123 /// internally. This means that this set closes over many transitive
124 /// internal items in addition to those defined immediately in the component
125 /// itself.
126 ///
127 /// The `Option<ValType>` in this mapping is whether or not the underlying
128 /// representation of the resource is known to this component. Immediately
129 /// defined resources, for example, will have `Some(I32)` here. Resources
130 /// that come from transitively defined components, for example, will have
131 /// `None`. In the type context all entries here are `None`.
132 ///
133 /// Note that like `imported_resources` all insertions into this map are
134 /// expected to succeed to it's declared as append-only.
135 defined_resources: IndexMapAppendOnly<ResourceId, Option<ValType>>,
136
137 /// A mapping of explicitly exported resources from this component in
138 /// addition to the path that they're exported at.
139 ///
140 /// For more information on the path here see the documentation for
141 /// `imported_resources`. Note that the indexes here index into the
142 /// list of exports of this component.
143 explicit_resources: IndexMap<ResourceId, Vec<usize>>,
144
145 /// The set of types which are considered "exported" from this component.
146 ///
147 /// This is added to whenever a type export is found, or an instance export
148 /// which itself contains a type export. This additionally includes all
149 /// imported types since those are suitable for export as well.
150 ///
151 /// This set is consulted whenever an exported item is added since all
152 /// referenced types must be members of this set.
153 exported_types: Set<ComponentAnyTypeId>,
154
155 /// Same as `exported_types`, but for imports.
156 imported_types: Set<ComponentAnyTypeId>,
157
158 /// The set of top-level resource exports and their names.
159 ///
160 /// This context is used to validate method names such as `[method]foo.bar`
161 /// to ensure that `foo` is an exported resource and that the type mentioned
162 /// in a function type is actually named `foo`.
163 ///
164 /// Note that imports/exports have disjoint contexts to ensure that they're
165 /// validated correctly. Namely you can't retroactively attach methods to an
166 /// import, for example.
167 toplevel_exported_resources: ComponentNameContext,
168
169 /// Same as `toplevel_exported_resources`, but for imports.
170 toplevel_imported_resources: ComponentNameContext,
171 }
172
173 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
174 pub enum ComponentKind {
175 Component,
176 InstanceType,
177 ComponentType,
178 }
179
180 /// Helper context used to track information about resource names for method
181 /// name validation.
182 #[derive(Default)]
183 struct ComponentNameContext {
184 /// A map from a resource type id to an index in the `all_resource_names`
185 /// set for the name of that resource.
186 resource_name_map: Map<AliasableResourceId, usize>,
187
188 /// All known resource names in this context, used to validate static method
189 /// names to by ensuring that static methods' resource names are somewhere
190 /// in this set.
191 all_resource_names: IndexSet<String>,
192 }
193
194 #[derive(Debug, Copy, Clone)]
195 pub enum ExternKind {
196 Import,
197 Export,
198 }
199
200 impl ExternKind {
201 pub fn desc(&self) -> &'static str {
202 match self {
203 ExternKind::Import => "import",
204 ExternKind::Export => "export",
205 }
206 }
207 }
208
209 impl ComponentState {
210 pub fn new(kind: ComponentKind) -> Self {
211 Self {
212 kind,
213 core_types: Default::default(),
214 core_modules: Default::default(),
215 core_instances: Default::default(),
216 core_funcs: Default::default(),
217 core_memories: Default::default(),
218 core_tables: Default::default(),
219 core_globals: Default::default(),
220 core_tags: Default::default(),
221 types: Default::default(),
222 funcs: Default::default(),
223 values: Default::default(),
224 instances: Default::default(),
225 components: Default::default(),
226 imports: Default::default(),
227 exports: Default::default(),
228 import_names: Default::default(),
229 export_names: Default::default(),
230 has_start: Default::default(),
231 type_info: TypeInfo::new(),
232 imported_resources: Default::default(),
233 defined_resources: Default::default(),
234 explicit_resources: Default::default(),
235 exported_types: Default::default(),
236 imported_types: Default::default(),
237 toplevel_exported_resources: Default::default(),
238 toplevel_imported_resources: Default::default(),
239 }
240 }
241
242 pub fn type_count(&self) -> usize {
243 self.core_types.len() + self.types.len()
244 }
245
246 pub fn instance_count(&self) -> usize {
247 self.core_instances.len() + self.instances.len()
248 }
249
250 pub fn function_count(&self) -> usize {
251 self.core_funcs.len() + self.funcs.len()
252 }
253
254 pub fn add_core_type(
255 components: &mut [Self],
256 ty: crate::CoreType,
257 features: &WasmFeatures,
258 types: &mut TypeAlloc,
259 offset: usize,
260 check_limit: bool,
261 ) -> Result<()> {
262 let current = components.last_mut().unwrap();
263 if check_limit {
264 check_max(current.type_count(), 1, MAX_WASM_TYPES, "types", offset)?;
265 }
266 match ty {
267 crate::CoreType::Rec(rec) => {
268 current.canonicalize_and_intern_rec_group(features, types, rec, offset)?;
269 }
270 crate::CoreType::Module(decls) => {
271 let mod_ty = Self::create_module_type(
272 components,
273 decls.into_vec(),
274 features,
275 types,
276 offset,
277 )?;
278 let id = ComponentCoreTypeId::Module(types.push_ty(mod_ty));
279 components.last_mut().unwrap().core_types.push(id);
280 }
281 }
282
283 Ok(())
284 }
285
286 pub fn add_core_module(
287 &mut self,
288 module: &Module,
289 types: &mut TypeAlloc,
290 offset: usize,
291 ) -> Result<()> {
292 let imports = module.imports_for_module_type(offset)?;
293
294 // We have to clone the module's imports and exports here
295 // because we cannot take the data out of the `MaybeOwned`
296 // as it might be shared with a function validator.
297 let mod_ty = ModuleType {
298 info: TypeInfo::core(module.type_size),
299 imports,
300 exports: module.exports.clone(),
301 };
302
303 let mod_id = types.push_ty(mod_ty);
304 self.core_modules.push(mod_id);
305
306 Ok(())
307 }
308
309 pub fn add_core_instance(
310 &mut self,
311 instance: crate::Instance,
312 types: &mut TypeAlloc,
313 offset: usize,
314 ) -> Result<()> {
315 let instance = match instance {
316 crate::Instance::Instantiate { module_index, args } => {
317 self.instantiate_core_module(module_index, args.into_vec(), types, offset)?
318 }
319 crate::Instance::FromExports(exports) => {
320 self.instantiate_core_exports(exports.into_vec(), types, offset)?
321 }
322 };
323
324 self.core_instances.push(instance);
325
326 Ok(())
327 }
328
329 pub fn add_type(
330 components: &mut Vec<Self>,
331 ty: crate::ComponentType,
332 features: &WasmFeatures,
333 types: &mut TypeAlloc,
334 offset: usize,
335 check_limit: bool,
336 ) -> Result<()> {
337 assert!(!components.is_empty());
338
339 fn current(components: &mut Vec<ComponentState>) -> &mut ComponentState {
340 components.last_mut().unwrap()
341 }
342
343 let id = match ty {
344 crate::ComponentType::Defined(ty) => {
345 let ty = current(components).create_defined_type(ty, types, features, offset)?;
346 types.push(ty).into()
347 }
348 crate::ComponentType::Func(ty) => {
349 let ty = current(components).create_function_type(ty, types, features, offset)?;
350 types.push(ty).into()
351 }
352 crate::ComponentType::Component(decls) => {
353 let ty = Self::create_component_type(
354 components,
355 decls.into_vec(),
356 features,
357 types,
358 offset,
359 )?;
360 types.push(ty).into()
361 }
362 crate::ComponentType::Instance(decls) => {
363 let ty = Self::create_instance_type(
364 components,
365 decls.into_vec(),
366 features,
367 types,
368 offset,
369 )?;
370 types.push(ty).into()
371 }
372 crate::ComponentType::Resource { rep, dtor } => {
373 let component = current(components);
374
375 // Resource types cannot be declared in a type context, only
376 // within a component context.
377 if component.kind != ComponentKind::Component {
378 bail!(
379 offset,
380 "resources can only be defined within a concrete component"
381 );
382 }
383
384 // Current MVP restriction of the component model.
385 if rep != ValType::I32 {
386 bail!(offset, "resources can only be represented by `i32`");
387 }
388
389 // If specified validate that the destructor is both a valid
390 // function and has the correct signature.
391 if let Some(dtor) = dtor {
392 let ty = component.core_function_at(dtor, offset)?;
393 let ty = types[ty].composite_type.unwrap_func();
394 if ty.params() != [rep] || ty.results() != [] {
395 bail!(
396 offset,
397 "core function {dtor} has wrong signature for a destructor"
398 );
399 }
400 }
401
402 // As this is the introduction of a resource create a fresh new
403 // identifier for the resource. This is then added into the
404 // list of defined resources for this component, notably with a
405 // rep listed to enable getting access to various intrinsics
406 // such as `resource.rep`.
407 let id = types.alloc_resource_id();
408 component.defined_resources.insert(id.resource(), Some(rep));
409 id.into()
410 }
411 };
412
413 let current = current(components);
414 if check_limit {
415 check_max(current.type_count(), 1, MAX_WASM_TYPES, "types", offset)?;
416 }
417 current.types.push(id);
418
419 Ok(())
420 }
421
422 pub fn add_import(
423 &mut self,
424 import: crate::ComponentImport,
425 features: &WasmFeatures,
426 types: &mut TypeAlloc,
427 offset: usize,
428 ) -> Result<()> {
429 let mut entity = self.check_type_ref(&import.ty, features, types, offset)?;
430 self.add_entity(
431 &mut entity,
432 Some((import.name.0, ExternKind::Import)),
433 features,
434 types,
435 offset,
436 )?;
437 self.toplevel_imported_resources.validate_extern(
438 import.name.0,
439 ExternKind::Import,
440 &entity,
441 types,
442 offset,
443 &mut self.import_names,
444 &mut self.imports,
445 &mut self.type_info,
446 features,
447 )?;
448 Ok(())
449 }
450
451 fn add_entity(
452 &mut self,
453 ty: &mut ComponentEntityType,
454 name_and_kind: Option<(&str, ExternKind)>,
455 features: &WasmFeatures,
456 types: &mut TypeAlloc,
457 offset: usize,
458 ) -> Result<()> {
459 let kind = name_and_kind.map(|(_, k)| k);
460 let (len, max, desc) = match ty {
461 ComponentEntityType::Module(id) => {
462 self.core_modules.push(*id);
463 (self.core_modules.len(), MAX_WASM_MODULES, "modules")
464 }
465 ComponentEntityType::Component(id) => {
466 self.components.push(*id);
467 (self.components.len(), MAX_WASM_COMPONENTS, "components")
468 }
469 ComponentEntityType::Instance(id) => {
470 match kind {
471 Some(ExternKind::Import) => self.prepare_instance_import(id, types),
472 Some(ExternKind::Export) => self.prepare_instance_export(id, types),
473 None => {}
474 }
475 self.instances.push(*id);
476 (self.instance_count(), MAX_WASM_INSTANCES, "instances")
477 }
478 ComponentEntityType::Func(id) => {
479 self.funcs.push(*id);
480 (self.function_count(), MAX_WASM_FUNCTIONS, "functions")
481 }
482 ComponentEntityType::Value(ty) => {
483 self.check_value_support(features, offset)?;
484 let value_used = match kind {
485 Some(ExternKind::Import) | None => false,
486 Some(ExternKind::Export) => true,
487 };
488 self.values.push((*ty, value_used));
489 (self.values.len(), MAX_WASM_VALUES, "values")
490 }
491 ComponentEntityType::Type {
492 created,
493 referenced,
494 } => {
495 self.types.push(*created);
496
497 // Extra logic here for resources being imported and exported.
498 // Note that if `created` is the same as `referenced` then this
499 // is the original introduction of the resource which is where
500 // `self.{imported,defined}_resources` are updated.
501 if let ComponentAnyTypeId::Resource(id) = *created {
502 match kind {
503 Some(ExternKind::Import) => {
504 // A fresh new resource is being imported into a
505 // component. This arises from the import section of
506 // a component or from the import declaration in a
507 // component type. In both cases a new imported
508 // resource is injected with a fresh new identifier
509 // into our state.
510 if created == referenced {
511 self.imported_resources
512 .insert(id.resource(), vec![self.imports.len()]);
513 }
514 }
515
516 Some(ExternKind::Export) => {
517 // A fresh resource is being exported from this
518 // component. This arises as part of the
519 // declaration of a component type, for example. In
520 // this situation brand new resource identifier is
521 // allocated and a definition is added, unlike the
522 // import case where an imported resource is added.
523 // Notably the representation of this new resource
524 // is unknown so it's listed as `None`.
525 if created == referenced {
526 self.defined_resources.insert(id.resource(), None);
527 }
528
529 // If this is a type export of a resource type then
530 // update the `explicit_resources` list. A new
531 // export path is about to be created for this
532 // resource and this keeps track of that.
533 self.explicit_resources
534 .insert(id.resource(), vec![self.exports.len()]);
535 }
536
537 None => {}
538 }
539 }
540 (self.types.len(), MAX_WASM_TYPES, "types")
541 }
542 };
543
544 check_max(len, 0, max, desc, offset)?;
545
546 // Before returning perform the final validation of the type of the item
547 // being imported/exported. This will ensure that everything is
548 // appropriately named with respect to type definitions, resources, etc.
549 if let Some((name, kind)) = name_and_kind {
550 if !self.validate_and_register_named_types(Some(name), kind, ty, types) {
551 bail!(
552 offset,
553 "{} not valid to be used as {}",
554 ty.desc(),
555 kind.desc()
556 );
557 }
558 }
559 Ok(())
560 }
561
562 /// Validates that the `ty` referenced only refers to named types internally
563 /// and then inserts anything necessary, if applicable, to the defined sets
564 /// within this component.
565 ///
566 /// This function will validate that `ty` only refers to named types. For
567 /// example if it's a record then all of its fields must refer to named
568 /// types. This consults either `self.imported_types` or
569 /// `self.exported_types` as specified by `kind`. Note that this is not
570 /// inherently recursive itself but it ends up being recursive since if
571 /// recursive members were named then all their components must also be
572 /// named. Consequently this check stops at the "one layer deep" position,
573 /// or more accurately the position where types must be named (e.g. tuples
574 /// aren't required to be named).
575 fn validate_and_register_named_types(
576 &mut self,
577 toplevel_name: Option<&str>,
578 kind: ExternKind,
579 ty: &ComponentEntityType,
580 types: &TypeAlloc,
581 ) -> bool {
582 if let ComponentEntityType::Type { created, .. } = ty {
583 // If this is a top-level resource then register it in the
584 // appropriate context so later validation of method-like-names
585 // works out.
586 if let Some(name) = toplevel_name {
587 if let ComponentAnyTypeId::Resource(id) = *created {
588 let cx = match kind {
589 ExternKind::Import => &mut self.toplevel_imported_resources,
590 ExternKind::Export => &mut self.toplevel_exported_resources,
591 };
592 cx.register(name, id);
593 }
594 }
595 }
596
597 match self.kind {
598 ComponentKind::Component | ComponentKind::ComponentType => {}
599 ComponentKind::InstanceType => return true,
600 }
601 let set = match kind {
602 ExternKind::Import => &self.imported_types,
603 ExternKind::Export => &self.exported_types,
604 };
605 match ty {
606 // When a type is imported or exported than any recursive type
607 // referred to by that import/export must additionally be exported
608 // or imported. Here this walks the "first layer" of the type which
609 // delegates to `TypeAlloc::type_named_type_id` to determine whether
610 // the components of the type being named here are indeed all they
611 // themselves named.
612 ComponentEntityType::Type {
613 created,
614 referenced,
615 } => {
616 if !self.all_valtypes_named(types, *referenced, set) {
617 return false;
618 }
619 match kind {
620 // Imported types are both valid for import and valid for
621 // export.
622 ExternKind::Import => {
623 self.imported_types.insert(*created);
624 self.exported_types.insert(*created);
625 }
626 ExternKind::Export => {
627 self.exported_types.insert(*created);
628 }
629 }
630
631 true
632 }
633
634 // Instances are slightly nuanced here. The general idea is that if
635 // an instance is imported, then any type exported by the instance
636 // is then also exported. Additionally for exports. To get this to
637 // work out this arm will recursively call
638 // `validate_and_register_named_types` which means that types are
639 // inserted into `self.{imported,exported}_types` as-we-go rather
640 // than all at once.
641 //
642 // This then recursively validates that all items in the instance
643 // itself are valid to import/export, recursive instances are
644 // captured, and everything is appropriately added to the right
645 // imported/exported set.
646 ComponentEntityType::Instance(i) => types[*i]
647 .exports
648 .iter()
649 .all(|(_name, ty)| self.validate_and_register_named_types(None, kind, ty, types)),
650
651 // All types referred to by a function must be named.
652 ComponentEntityType::Func(id) => self.all_valtypes_named_in_func(types, *id, set),
653
654 ComponentEntityType::Value(ty) => types.type_named_valtype(ty, set),
655
656 // Components/modules are always "closed" or "standalone" and don't
657 // need validation with respect to their named types.
658 ComponentEntityType::Component(_) | ComponentEntityType::Module(_) => true,
659 }
660 }
661
662 fn all_valtypes_named(
663 &self,
664 types: &TypeAlloc,
665 id: ComponentAnyTypeId,
666 set: &Set<ComponentAnyTypeId>,
667 ) -> bool {
668 match id {
669 // Resource types, in isolation, are always valid to import or
670 // export since they're either attached to an import or being
671 // exported.
672 //
673 // Note that further validation of this happens in `finish`, too.
674 ComponentAnyTypeId::Resource(_) => true,
675
676 // Component types are validated as they are constructed,
677 // so all component types are valid to export if they've
678 // already been constructed.
679 ComponentAnyTypeId::Component(_) => true,
680
681 ComponentAnyTypeId::Defined(id) => self.all_valtypes_named_in_defined(types, id, set),
682 ComponentAnyTypeId::Func(id) => self.all_valtypes_named_in_func(types, id, set),
683 ComponentAnyTypeId::Instance(id) => self.all_valtypes_named_in_instance(types, id, set),
684 }
685 }
686
687 fn all_valtypes_named_in_instance(
688 &self,
689 types: &TypeAlloc,
690 id: ComponentInstanceTypeId,
691 set: &Set<ComponentAnyTypeId>,
692 ) -> bool {
693 // Instances must recursively have all referenced types named.
694 let ty = &types[id];
695 ty.exports.values().all(|ty| match ty {
696 ComponentEntityType::Module(_) => true,
697 ComponentEntityType::Func(id) => self.all_valtypes_named_in_func(types, *id, set),
698 ComponentEntityType::Type { created: id, .. } => {
699 self.all_valtypes_named(types, *id, set)
700 }
701 ComponentEntityType::Value(ComponentValType::Type(id)) => {
702 self.all_valtypes_named_in_defined(types, *id, set)
703 }
704 ComponentEntityType::Instance(id) => {
705 self.all_valtypes_named_in_instance(types, *id, set)
706 }
707 ComponentEntityType::Component(_)
708 | ComponentEntityType::Value(ComponentValType::Primitive(_)) => return true,
709 })
710 }
711
712 fn all_valtypes_named_in_defined(
713 &self,
714 types: &TypeAlloc,
715 id: ComponentDefinedTypeId,
716 set: &Set<ComponentAnyTypeId>,
717 ) -> bool {
718 let ty = &types[id];
719 match ty {
720 // These types do not contain anything which must be
721 // named.
722 ComponentDefinedType::Primitive(_)
723 | ComponentDefinedType::Flags(_)
724 | ComponentDefinedType::Enum(_) => true,
725
726 // Referenced types of all these aggregates must all be
727 // named.
728 ComponentDefinedType::Record(r) => {
729 r.fields.values().all(|t| types.type_named_valtype(t, set))
730 }
731 ComponentDefinedType::Tuple(r) => {
732 r.types.iter().all(|t| types.type_named_valtype(t, set))
733 }
734 ComponentDefinedType::Variant(r) => r
735 .cases
736 .values()
737 .filter_map(|t| t.ty.as_ref())
738 .all(|t| types.type_named_valtype(t, set)),
739 ComponentDefinedType::Result { ok, err } => {
740 ok.as_ref()
741 .map(|t| types.type_named_valtype(t, set))
742 .unwrap_or(true)
743 && err
744 .as_ref()
745 .map(|t| types.type_named_valtype(t, set))
746 .unwrap_or(true)
747 }
748 ComponentDefinedType::List(ty) | ComponentDefinedType::Option(ty) => {
749 types.type_named_valtype(ty, set)
750 }
751
752 // The resource referred to by own/borrow must be named.
753 ComponentDefinedType::Own(id) | ComponentDefinedType::Borrow(id) => {
754 set.contains(&ComponentAnyTypeId::from(*id))
755 }
756 }
757 }
758
759 fn all_valtypes_named_in_func(
760 &self,
761 types: &TypeAlloc,
762 id: ComponentFuncTypeId,
763 set: &Set<ComponentAnyTypeId>,
764 ) -> bool {
765 let ty = &types[id];
766 // Function types must have all their parameters/results named.
767 ty.params
768 .iter()
769 .map(|(_, ty)| ty)
770 .chain(ty.results.iter().map(|(_, ty)| ty))
771 .all(|ty| types.type_named_valtype(ty, set))
772 }
773
774 /// Updates the type `id` specified, an identifier for a component instance
775 /// type, to be imported into this component.
776 ///
777 /// Importing an instance type into a component specially handles the
778 /// defined resources registered in the instance type. Notably all
779 /// defined resources are "freshened" into brand new type variables and
780 /// these new variables are substituted within the type. This is what
781 /// creates a new `TypeId` and may update the `id` specified.
782 ///
783 /// One side effect of this operation, for example, is that if an instance
784 /// type is used twice to import two different instances then the instances
785 /// do not share resource types despite sharing the same original instance
786 /// type.
787 fn prepare_instance_import(&mut self, id: &mut ComponentInstanceTypeId, types: &mut TypeAlloc) {
788 let ty = &types[*id];
789
790 // No special treatment for imports of instances which themselves have
791 // no defined resources
792 if ty.defined_resources.is_empty() {
793 return;
794 }
795
796 let mut new_ty = ComponentInstanceType {
797 // Copied from the input verbatim
798 info: ty.info,
799
800 // Copied over as temporary storage for now, and both of these are
801 // filled out and expanded below.
802 exports: ty.exports.clone(),
803 explicit_resources: ty.explicit_resources.clone(),
804
805 // Explicitly discard this field since the
806 // defined resources are lifted into `self`
807 defined_resources: Default::default(),
808 };
809
810 // Create brand new resources for all defined ones in the instance.
811 let resources = (0..ty.defined_resources.len())
812 .map(|_| types.alloc_resource_id())
813 .collect::<IndexSet<_>>();
814
815 // Build a map from the defined resources in `ty` to those in `new_ty`.
816 //
817 // As part of this same loop the new resources, which were previously
818 // defined in `ty`, now become imported variables in `self`. Their
819 // path for where they're imported is updated as well with
820 // `self.next_import_index` as the import-to-be soon.
821 let mut mapping = Remapping::default();
822 let ty = &types[*id];
823 for (old, new) in ty.defined_resources.iter().zip(&resources) {
824 let prev = mapping.resources.insert(*old, new.resource());
825 assert!(prev.is_none());
826
827 let mut base = vec![self.imports.len()];
828 base.extend(ty.explicit_resources[old].iter().copied());
829 self.imported_resources.insert(new.resource(), base);
830 }
831
832 // Using the old-to-new resource mapping perform a substitution on
833 // the `exports` and `explicit_resources` fields of `new_ty`
834 for ty in new_ty.exports.values_mut() {
835 types.remap_component_entity(ty, &mut mapping);
836 }
837 for (id, path) in mem::take(&mut new_ty.explicit_resources) {
838 let id = *mapping.resources.get(&id).unwrap_or(&id);
839 new_ty.explicit_resources.insert(id, path);
840 }
841
842 // Now that `new_ty` is complete finish its registration and then
843 // update `id` on the way out.
844 *id = types.push_ty(new_ty);
845 }
846
847 /// Prepares an instance type, pointed to `id`, for being exported as a
848 /// concrete instance from `self`.
849 ///
850 /// This will internally perform any resource "freshening" as required and
851 /// then additionally update metadata within `self` about resources being
852 /// exported or defined.
853 fn prepare_instance_export(&mut self, id: &mut ComponentInstanceTypeId, types: &mut TypeAlloc) {
854 // Exports of an instance mean that the enclosing context
855 // is inheriting the resources that the instance
856 // encapsulates. This means that the instance type
857 // recorded for this export will itself have no
858 // defined resources.
859 let ty = &types[*id];
860
861 // Check to see if `defined_resources` is non-empty, and if so then
862 // "freshen" all the resources and inherit them to our own defined
863 // resources, updating `id` in the process.
864 //
865 // Note though that this specifically is not rewriting the resources of
866 // exported instances. The `defined_resources` set on instance types is
867 // a little subtle (see its documentation for more info), but the
868 // general idea is that for a concrete instance it's always empty. Only
869 // for instance type definitions does it ever have elements in it.
870 //
871 // That means that if this set is non-empty then what's happening is
872 // that we're in a type context an exporting an instance of a previously
873 // specified type. In this case all resources are required to be
874 // "freshened" to ensure that multiple exports of the same type all
875 // export different types of resources.
876 //
877 // And finally note that this operation empties out the
878 // `defined_resources` set of the type that is registered for the
879 // instance, as this export is modeled as producing a concrete instance.
880 if !ty.defined_resources.is_empty() {
881 let mut new_ty = ty.clone();
882 let mut mapping = Remapping::default();
883 for old in mem::take(&mut new_ty.defined_resources) {
884 let new = types.alloc_resource_id();
885 mapping.resources.insert(old, new.resource());
886 self.defined_resources.insert(new.resource(), None);
887 }
888 for ty in new_ty.exports.values_mut() {
889 types.remap_component_entity(ty, &mut mapping);
890 }
891 for (id, path) in mem::take(&mut new_ty.explicit_resources) {
892 let id = mapping.resources.get(&id).copied().unwrap_or(id);
893 new_ty.explicit_resources.insert(id, path);
894 }
895 *id = types.push_ty(new_ty);
896 }
897
898 // Any explicit resources in the instance are now additionally explicit
899 // in this component since it's exported.
900 //
901 // The path to each explicit resources gets one element prepended which
902 // is `self.next_export_index`, the index of the export about to be
903 // generated.
904 let ty = &types[*id];
905 for (id, path) in ty.explicit_resources.iter() {
906 let mut new_path = vec![self.exports.len()];
907 new_path.extend(path);
908 self.explicit_resources.insert(*id, new_path);
909 }
910 }
911
912 pub fn add_export(
913 &mut self,
914 name: ComponentExportName<'_>,
915 mut ty: ComponentEntityType,
916 features: &WasmFeatures,
917 types: &mut TypeAlloc,
918 offset: usize,
919 check_limit: bool,
920 ) -> Result<()> {
921 if check_limit {
922 check_max(self.exports.len(), 1, MAX_WASM_EXPORTS, "exports", offset)?;
923 }
924 self.add_entity(
925 &mut ty,
926 Some((name.0, ExternKind::Export)),
927 features,
928 types,
929 offset,
930 )?;
931 self.toplevel_exported_resources.validate_extern(
932 name.0,
933 ExternKind::Export,
934 &ty,
935 types,
936 offset,
937 &mut self.export_names,
938 &mut self.exports,
939 &mut self.type_info,
940 features,
941 )?;
942 Ok(())
943 }
944
945 pub fn lift_function(
946 &mut self,
947 core_func_index: u32,
948 type_index: u32,
949 options: Vec<CanonicalOption>,
950 types: &TypeList,
951 offset: usize,
952 ) -> Result<()> {
953 let ty = self.function_type_at(type_index, types, offset)?;
954 let core_ty = types[self.core_function_at(core_func_index, offset)?].unwrap_func();
955
956 // Lifting a function is for an export, so match the expected canonical ABI
957 // export signature
958 let info = ty.lower(types, false);
959 self.check_options(Some(core_ty), &info, &options, types, offset)?;
960
961 if core_ty.params() != info.params.as_slice() {
962 bail!(
963 offset,
964 "lowered parameter types `{:?}` do not match parameter types \
965 `{:?}` of core function {core_func_index}",
966 info.params.as_slice(),
967 core_ty.params(),
968 );
969 }
970
971 if core_ty.results() != info.results.as_slice() {
972 bail!(
973 offset,
974 "lowered result types `{:?}` do not match result types \
975 `{:?}` of core function {core_func_index}",
976 info.results.as_slice(),
977 core_ty.results()
978 );
979 }
980
981 self.funcs
982 .push(self.types[type_index as usize].unwrap_func());
983
984 Ok(())
985 }
986
987 pub fn lower_function(
988 &mut self,
989 func_index: u32,
990 options: Vec<CanonicalOption>,
991 types: &mut TypeAlloc,
992 offset: usize,
993 ) -> Result<()> {
994 let ty = &types[self.function_at(func_index, offset)?];
995
996 // Lowering a function is for an import, so use a function type that matches
997 // the expected canonical ABI import signature.
998 let info = ty.lower(types, true);
999
1000 self.check_options(None, &info, &options, types, offset)?;
1001
1002 let lowered_ty = SubType::func(info.into_func_type(), false);
1003 let id = types.intern_sub_type(lowered_ty, offset);
1004 self.core_funcs.push(id);
1005
1006 Ok(())
1007 }
1008
1009 pub fn resource_new(
1010 &mut self,
1011 resource: u32,
1012 types: &mut TypeAlloc,
1013 offset: usize,
1014 ) -> Result<()> {
1015 let rep = self.check_local_resource(resource, types, offset)?;
1016 let func_ty = FuncType::new([rep], [ValType::I32]);
1017 let core_ty = SubType::func(func_ty, false);
1018 let id = types.intern_sub_type(core_ty, offset);
1019 self.core_funcs.push(id);
1020 Ok(())
1021 }
1022
1023 pub fn resource_drop(
1024 &mut self,
1025 resource: u32,
1026 types: &mut TypeAlloc,
1027 offset: usize,
1028 ) -> Result<()> {
1029 self.resource_at(resource, types, offset)?;
1030 let func_ty = FuncType::new([ValType::I32], []);
1031 let core_ty = SubType::func(func_ty, false);
1032 let id = types.intern_sub_type(core_ty, offset);
1033 self.core_funcs.push(id);
1034 Ok(())
1035 }
1036
1037 pub fn resource_rep(
1038 &mut self,
1039 resource: u32,
1040 types: &mut TypeAlloc,
1041 offset: usize,
1042 ) -> Result<()> {
1043 let rep = self.check_local_resource(resource, types, offset)?;
1044 let func_ty = FuncType::new([ValType::I32], [rep]);
1045 let core_ty = SubType::func(func_ty, false);
1046 let id = types.intern_sub_type(core_ty, offset);
1047 self.core_funcs.push(id);
1048 Ok(())
1049 }
1050
1051 fn check_local_resource(&self, idx: u32, types: &TypeList, offset: usize) -> Result<ValType> {
1052 let resource = self.resource_at(idx, types, offset)?;
1053 match self
1054 .defined_resources
1055 .get(&resource.resource())
1056 .and_then(|rep| *rep)
1057 {
1058 Some(ty) => Ok(ty),
1059 None => bail!(offset, "type {idx} is not a local resource"),
1060 }
1061 }
1062
1063 fn resource_at<'a>(
1064 &self,
1065 idx: u32,
1066 _types: &'a TypeList,
1067 offset: usize,
1068 ) -> Result<AliasableResourceId> {
1069 if let ComponentAnyTypeId::Resource(id) = self.component_type_at(idx, offset)? {
1070 return Ok(id);
1071 }
1072 bail!(offset, "type index {} is not a resource type", idx)
1073 }
1074
1075 pub fn thread_spawn(
1076 &mut self,
1077 func_ty_index: u32,
1078 types: &mut TypeAlloc,
1079 offset: usize,
1080 features: &WasmFeatures,
1081 ) -> Result<()> {
1082 if !features.shared_everything_threads() {
1083 bail!(
1084 offset,
1085 "`thread.spawn` requires the shared-everything-threads proposal"
1086 )
1087 }
1088
1089 // Validate the type accepted by `thread.spawn`.
1090 let core_type_id = match self.core_type_at(func_ty_index, offset)? {
1091 ComponentCoreTypeId::Sub(c) => c,
1092 ComponentCoreTypeId::Module(_) => bail!(offset, "expected a core function type"),
1093 };
1094 let sub_ty = &types[core_type_id];
1095 if !sub_ty.composite_type.shared {
1096 bail!(offset, "spawn type must be shared");
1097 }
1098 match &sub_ty.composite_type.inner {
1099 CompositeInnerType::Func(func_ty) => {
1100 if func_ty.params() != [ValType::I32] {
1101 bail!(
1102 offset,
1103 "spawn function must take a single `i32` argument (currently)"
1104 );
1105 }
1106 if func_ty.results() != [] {
1107 bail!(offset, "spawn function must not return any values");
1108 }
1109 }
1110 _ => bail!(offset, "spawn type must be a function"),
1111 }
1112
1113 // Insert the core function.
1114 let packed_index = PackedIndex::from_id(core_type_id).ok_or_else(|| {
1115 format_err!(offset, "implementation limit: too many types in `TypeList`")
1116 })?;
1117 let start_func_ref = RefType::concrete(true, packed_index);
1118 let func_ty = FuncType::new([ValType::Ref(start_func_ref), ValType::I32], [ValType::I32]);
1119 let core_ty = SubType::func(func_ty, true);
1120 let id = types.intern_sub_type(core_ty, offset);
1121 self.core_funcs.push(id);
1122
1123 Ok(())
1124 }
1125
1126 pub fn thread_hw_concurrency(
1127 &mut self,
1128 types: &mut TypeAlloc,
1129 offset: usize,
1130 features: &WasmFeatures,
1131 ) -> Result<()> {
1132 if !features.shared_everything_threads() {
1133 bail!(
1134 offset,
1135 "`thread.hw_concurrency` requires the shared-everything-threads proposal"
1136 )
1137 }
1138
1139 let func_ty = FuncType::new([], [ValType::I32]);
1140 let core_ty = SubType::func(func_ty, true);
1141 let id = types.intern_sub_type(core_ty, offset);
1142 self.core_funcs.push(id);
1143
1144 Ok(())
1145 }
1146
1147 pub fn add_component(&mut self, component: ComponentType, types: &mut TypeAlloc) -> Result<()> {
1148 let id = types.push_ty(component);
1149 self.components.push(id);
1150 Ok(())
1151 }
1152
1153 pub fn add_instance(
1154 &mut self,
1155 instance: crate::ComponentInstance,
1156 features: &WasmFeatures,
1157 types: &mut TypeAlloc,
1158 offset: usize,
1159 ) -> Result<()> {
1160 let instance = match instance {
1161 crate::ComponentInstance::Instantiate {
1162 component_index,
1163 args,
1164 } => self.instantiate_component(
1165 component_index,
1166 args.into_vec(),
1167 features,
1168 types,
1169 offset,
1170 )?,
1171 crate::ComponentInstance::FromExports(exports) => {
1172 self.instantiate_component_exports(exports.into_vec(), features, types, offset)?
1173 }
1174 };
1175
1176 self.instances.push(instance);
1177
1178 Ok(())
1179 }
1180
1181 pub fn add_alias(
1182 components: &mut [Self],
1183 alias: crate::ComponentAlias,
1184 features: &WasmFeatures,
1185 types: &mut TypeAlloc,
1186 offset: usize,
1187 ) -> Result<()> {
1188 match alias {
1189 crate::ComponentAlias::InstanceExport {
1190 instance_index,
1191 kind,
1192 name,
1193 } => components.last_mut().unwrap().alias_instance_export(
1194 instance_index,
1195 kind,
1196 name,
1197 features,
1198 types,
1199 offset,
1200 ),
1201 crate::ComponentAlias::CoreInstanceExport {
1202 instance_index,
1203 kind,
1204 name,
1205 } => components.last_mut().unwrap().alias_core_instance_export(
1206 instance_index,
1207 kind,
1208 name,
1209 types,
1210 offset,
1211 ),
1212 crate::ComponentAlias::Outer { kind, count, index } => match kind {
1213 ComponentOuterAliasKind::CoreModule => {
1214 Self::alias_module(components, count, index, offset)
1215 }
1216 ComponentOuterAliasKind::CoreType => {
1217 Self::alias_core_type(components, count, index, offset)
1218 }
1219 ComponentOuterAliasKind::Type => {
1220 Self::alias_type(components, count, index, types, offset)
1221 }
1222 ComponentOuterAliasKind::Component => {
1223 Self::alias_component(components, count, index, offset)
1224 }
1225 },
1226 }
1227 }
1228
1229 pub fn add_start(
1230 &mut self,
1231 func_index: u32,
1232 args: &[u32],
1233 results: u32,
1234 features: &WasmFeatures,
1235 types: &mut TypeList,
1236 offset: usize,
1237 ) -> Result<()> {
1238 if !features.component_model_values() {
1239 bail!(
1240 offset,
1241 "support for component model `value`s is not enabled"
1242 );
1243 }
1244 if self.has_start {
1245 return Err(BinaryReaderError::new(
1246 "component cannot have more than one start function",
1247 offset,
1248 ));
1249 }
1250
1251 let ft = &types[self.function_at(func_index, offset)?];
1252
1253 if ft.params.len() != args.len() {
1254 bail!(
1255 offset,
1256 "component start function requires {} arguments but was given {}",
1257 ft.params.len(),
1258 args.len()
1259 );
1260 }
1261
1262 if ft.results.len() as u32 != results {
1263 bail!(
1264 offset,
1265 "component start function has a result count of {results} \
1266 but the function type has a result count of {type_results}",
1267 type_results = ft.results.len(),
1268 );
1269 }
1270
1271 let cx = SubtypeCx::new(types, types);
1272 for (i, ((_, ty), arg)) in ft.params.iter().zip(args).enumerate() {
1273 // Ensure the value's type is a subtype of the parameter type
1274 cx.component_val_type(self.value_at(*arg, offset)?, ty, offset)
1275 .with_context(|| {
1276 format!("value type mismatch for component start function argument {i}")
1277 })?;
1278 }
1279
1280 for (_, ty) in ft.results.iter() {
1281 self.values.push((*ty, false));
1282 }
1283
1284 self.has_start = true;
1285
1286 Ok(())
1287 }
1288
1289 fn check_options(
1290 &self,
1291 core_ty: Option<&FuncType>,
1292 info: &LoweringInfo,
1293 options: &[CanonicalOption],
1294 types: &TypeList,
1295 offset: usize,
1296 ) -> Result<()> {
1297 fn display(option: CanonicalOption) -> &'static str {
1298 match option {
1299 CanonicalOption::UTF8 => "utf8",
1300 CanonicalOption::UTF16 => "utf16",
1301 CanonicalOption::CompactUTF16 => "latin1-utf16",
1302 CanonicalOption::Memory(_) => "memory",
1303 CanonicalOption::Realloc(_) => "realloc",
1304 CanonicalOption::PostReturn(_) => "post-return",
1305 }
1306 }
1307
1308 let mut encoding = None;
1309 let mut memory = None;
1310 let mut realloc = None;
1311 let mut post_return = None;
1312
1313 for option in options {
1314 match option {
1315 CanonicalOption::UTF8 | CanonicalOption::UTF16 | CanonicalOption::CompactUTF16 => {
1316 match encoding {
1317 Some(existing) => {
1318 bail!(
1319 offset,
1320 "canonical encoding option `{}` conflicts with option `{}`",
1321 display(existing),
1322 display(*option),
1323 )
1324 }
1325 None => encoding = Some(*option),
1326 }
1327 }
1328 CanonicalOption::Memory(idx) => {
1329 memory = match memory {
1330 None => {
1331 self.memory_at(*idx, offset)?;
1332 Some(*idx)
1333 }
1334 Some(_) => {
1335 return Err(BinaryReaderError::new(
1336 "canonical option `memory` is specified more than once",
1337 offset,
1338 ))
1339 }
1340 }
1341 }
1342 CanonicalOption::Realloc(idx) => {
1343 realloc = match realloc {
1344 None => {
1345 let ty = types[self.core_function_at(*idx, offset)?].unwrap_func();
1346 if ty.params()
1347 != [ValType::I32, ValType::I32, ValType::I32, ValType::I32]
1348 || ty.results() != [ValType::I32]
1349 {
1350 return Err(BinaryReaderError::new(
1351 "canonical option `realloc` uses a core function with an incorrect signature",
1352 offset,
1353 ));
1354 }
1355 Some(*idx)
1356 }
1357 Some(_) => {
1358 return Err(BinaryReaderError::new(
1359 "canonical option `realloc` is specified more than once",
1360 offset,
1361 ))
1362 }
1363 }
1364 }
1365 CanonicalOption::PostReturn(idx) => {
1366 post_return = match post_return {
1367 None => {
1368 let core_ty = core_ty.ok_or_else(|| {
1369 BinaryReaderError::new(
1370 "canonical option `post-return` cannot be specified for lowerings",
1371 offset,
1372 )
1373 })?;
1374
1375 let ty = types[self.core_function_at(*idx, offset)?].unwrap_func();
1376
1377 if ty.params() != core_ty.results() || !ty.results().is_empty() {
1378 return Err(BinaryReaderError::new(
1379 "canonical option `post-return` uses a core function with an incorrect signature",
1380 offset,
1381 ));
1382 }
1383 Some(*idx)
1384 }
1385 Some(_) => {
1386 return Err(BinaryReaderError::new(
1387 "canonical option `post-return` is specified more than once",
1388 offset,
1389 ))
1390 }
1391 }
1392 }
1393 }
1394 }
1395
1396 if info.requires_memory && memory.is_none() {
1397 return Err(BinaryReaderError::new(
1398 "canonical option `memory` is required",
1399 offset,
1400 ));
1401 }
1402
1403 if info.requires_realloc && realloc.is_none() {
1404 return Err(BinaryReaderError::new(
1405 "canonical option `realloc` is required",
1406 offset,
1407 ));
1408 }
1409
1410 Ok(())
1411 }
1412
1413 fn check_type_ref(
1414 &mut self,
1415 ty: &ComponentTypeRef,
1416 features: &WasmFeatures,
1417 types: &mut TypeAlloc,
1418 offset: usize,
1419 ) -> Result<ComponentEntityType> {
1420 Ok(match ty {
1421 ComponentTypeRef::Module(index) => {
1422 let id = self.core_type_at(*index, offset)?;
1423 match id {
1424 ComponentCoreTypeId::Sub(_) => {
1425 bail!(offset, "core type index {index} is not a module type")
1426 }
1427 ComponentCoreTypeId::Module(id) => ComponentEntityType::Module(id),
1428 }
1429 }
1430 ComponentTypeRef::Func(index) => {
1431 let id = self.component_type_at(*index, offset)?;
1432 match id {
1433 ComponentAnyTypeId::Func(id) => ComponentEntityType::Func(id),
1434 _ => bail!(offset, "type index {index} is not a function type"),
1435 }
1436 }
1437 ComponentTypeRef::Value(ty) => {
1438 self.check_value_support(features, offset)?;
1439 let ty = match ty {
1440 crate::ComponentValType::Primitive(ty) => ComponentValType::Primitive(*ty),
1441 crate::ComponentValType::Type(index) => {
1442 ComponentValType::Type(self.defined_type_at(*index, offset)?)
1443 }
1444 };
1445 ComponentEntityType::Value(ty)
1446 }
1447 ComponentTypeRef::Type(TypeBounds::Eq(index)) => {
1448 let referenced = self.component_type_at(*index, offset)?;
1449 let created = types.with_unique(referenced);
1450 ComponentEntityType::Type {
1451 referenced,
1452 created,
1453 }
1454 }
1455 ComponentTypeRef::Type(TypeBounds::SubResource) => {
1456 let id = types.alloc_resource_id();
1457 ComponentEntityType::Type {
1458 referenced: id.into(),
1459 created: id.into(),
1460 }
1461 }
1462 ComponentTypeRef::Instance(index) => {
1463 let id = self.component_type_at(*index, offset)?;
1464 match id {
1465 ComponentAnyTypeId::Instance(id) => ComponentEntityType::Instance(id),
1466 _ => bail!(offset, "type index {index} is not an instance type"),
1467 }
1468 }
1469 ComponentTypeRef::Component(index) => {
1470 let id = self.component_type_at(*index, offset)?;
1471 match id {
1472 ComponentAnyTypeId::Component(id) => ComponentEntityType::Component(id),
1473 _ => bail!(offset, "type index {index} is not a component type"),
1474 }
1475 }
1476 })
1477 }
1478
1479 pub fn export_to_entity_type(
1480 &mut self,
1481 export: &crate::ComponentExport,
1482 features: &WasmFeatures,
1483 types: &mut TypeAlloc,
1484 offset: usize,
1485 ) -> Result<ComponentEntityType> {
1486 let actual = match export.kind {
1487 ComponentExternalKind::Module => {
1488 ComponentEntityType::Module(self.module_at(export.index, offset)?)
1489 }
1490 ComponentExternalKind::Func => {
1491 ComponentEntityType::Func(self.function_at(export.index, offset)?)
1492 }
1493 ComponentExternalKind::Value => {
1494 self.check_value_support(features, offset)?;
1495 ComponentEntityType::Value(*self.value_at(export.index, offset)?)
1496 }
1497 ComponentExternalKind::Type => {
1498 let referenced = self.component_type_at(export.index, offset)?;
1499 let created = types.with_unique(referenced);
1500 ComponentEntityType::Type {
1501 referenced,
1502 created,
1503 }
1504 }
1505 ComponentExternalKind::Instance => {
1506 ComponentEntityType::Instance(self.instance_at(export.index, offset)?)
1507 }
1508 ComponentExternalKind::Component => {
1509 ComponentEntityType::Component(self.component_at(export.index, offset)?)
1510 }
1511 };
1512
1513 let ascribed = match &export.ty {
1514 Some(ty) => self.check_type_ref(ty, features, types, offset)?,
1515 None => return Ok(actual),
1516 };
1517
1518 SubtypeCx::new(types, types)
1519 .component_entity_type(&actual, &ascribed, offset)
1520 .with_context(|| "ascribed type of export is not compatible with item's type")?;
1521
1522 Ok(ascribed)
1523 }
1524
1525 fn create_module_type(
1526 components: &[Self],
1527 decls: Vec<crate::ModuleTypeDeclaration>,
1528 features: &WasmFeatures,
1529 types: &mut TypeAlloc,
1530 offset: usize,
1531 ) -> Result<ModuleType> {
1532 let mut state = Module::default();
1533
1534 for decl in decls {
1535 match decl {
1536 crate::ModuleTypeDeclaration::Type(rec) => {
1537 state.add_types(rec, features, types, offset, true)?;
1538 }
1539 crate::ModuleTypeDeclaration::Export { name, mut ty } => {
1540 let ty = state.check_type_ref(&mut ty, features, types, offset)?;
1541 state.add_export(name, ty, features, offset, true, types)?;
1542 }
1543 crate::ModuleTypeDeclaration::OuterAlias { kind, count, index } => {
1544 match kind {
1545 crate::OuterAliasKind::Type => {
1546 let ty = if count == 0 {
1547 // Local alias, check the local module state
1548 ComponentCoreTypeId::Sub(state.type_id_at(index, offset)?)
1549 } else {
1550 // Otherwise, check the enclosing component state
1551 let component =
1552 Self::check_alias_count(components, count - 1, offset)?;
1553 component.core_type_at(index, offset)?
1554 };
1555
1556 check_max(state.types.len(), 1, MAX_WASM_TYPES, "types", offset)?;
1557
1558 match ty {
1559 ComponentCoreTypeId::Sub(ty) => state.types.push(ty),
1560 // TODO https://github.com/WebAssembly/component-model/issues/265
1561 ComponentCoreTypeId::Module(_) => bail!(
1562 offset,
1563 "not implemented: aliasing core module types into a core \
1564 module's types index space"
1565 ),
1566 }
1567 }
1568 }
1569 }
1570 crate::ModuleTypeDeclaration::Import(import) => {
1571 state.add_import(import, features, types, offset)?;
1572 }
1573 }
1574 }
1575
1576 let imports = state.imports_for_module_type(offset)?;
1577
1578 Ok(ModuleType {
1579 info: TypeInfo::core(state.type_size),
1580 imports,
1581 exports: state.exports,
1582 })
1583 }
1584
1585 fn create_component_type(
1586 components: &mut Vec<Self>,
1587 decls: Vec<crate::ComponentTypeDeclaration>,
1588 features: &WasmFeatures,
1589 types: &mut TypeAlloc,
1590 offset: usize,
1591 ) -> Result<ComponentType> {
1592 components.push(ComponentState::new(ComponentKind::ComponentType));
1593
1594 for decl in decls {
1595 match decl {
1596 crate::ComponentTypeDeclaration::CoreType(ty) => {
1597 Self::add_core_type(components, ty, features, types, offset, true)?;
1598 }
1599 crate::ComponentTypeDeclaration::Type(ty) => {
1600 Self::add_type(components, ty, features, types, offset, true)?;
1601 }
1602 crate::ComponentTypeDeclaration::Export { name, ty } => {
1603 let current = components.last_mut().unwrap();
1604 let ty = current.check_type_ref(&ty, features, types, offset)?;
1605 current.add_export(name, ty, features, types, offset, true)?;
1606 }
1607 crate::ComponentTypeDeclaration::Import(import) => {
1608 components
1609 .last_mut()
1610 .unwrap()
1611 .add_import(import, features, types, offset)?;
1612 }
1613 crate::ComponentTypeDeclaration::Alias(alias) => {
1614 Self::add_alias(components, alias, features, types, offset)?;
1615 }
1616 };
1617 }
1618
1619 components.pop().unwrap().finish(types, offset)
1620 }
1621
1622 fn create_instance_type(
1623 components: &mut Vec<Self>,
1624 decls: Vec<crate::InstanceTypeDeclaration>,
1625 features: &WasmFeatures,
1626 types: &mut TypeAlloc,
1627 offset: usize,
1628 ) -> Result<ComponentInstanceType> {
1629 components.push(ComponentState::new(ComponentKind::InstanceType));
1630
1631 for decl in decls {
1632 match decl {
1633 crate::InstanceTypeDeclaration::CoreType(ty) => {
1634 Self::add_core_type(components, ty, features, types, offset, true)?;
1635 }
1636 crate::InstanceTypeDeclaration::Type(ty) => {
1637 Self::add_type(components, ty, features, types, offset, true)?;
1638 }
1639 crate::InstanceTypeDeclaration::Export { name, ty } => {
1640 let current = components.last_mut().unwrap();
1641 let ty = current.check_type_ref(&ty, features, types, offset)?;
1642 current.add_export(name, ty, features, types, offset, true)?;
1643 }
1644 crate::InstanceTypeDeclaration::Alias(alias) => {
1645 Self::add_alias(components, alias, features, types, offset)?;
1646 }
1647 };
1648 }
1649
1650 let mut state = components.pop().unwrap();
1651
1652 assert!(state.imported_resources.is_empty());
1653
1654 Ok(ComponentInstanceType {
1655 info: state.type_info,
1656
1657 // The defined resources for this instance type are those listed on
1658 // the component state. The path to each defined resource is
1659 // guaranteed to live within the `explicit_resources` map since,
1660 // when in the type context, the introduction of any defined
1661 // resource must have been done with `(export "x" (type (sub
1662 // resource)))` which, in a sense, "fuses" the introduction of the
1663 // variable with the export. This means that all defined resources,
1664 // if any, should be guaranteed to have an `explicit_resources` path
1665 // listed.
1666 defined_resources: mem::take(&mut state.defined_resources)
1667 .into_iter()
1668 .map(|(id, rep)| {
1669 assert!(rep.is_none());
1670 id
1671 })
1672 .collect(),
1673
1674 // The map of what resources are explicitly exported and where
1675 // they're exported is plumbed through as-is.
1676 explicit_resources: mem::take(&mut state.explicit_resources),
1677
1678 exports: mem::take(&mut state.exports),
1679 })
1680 }
1681
1682 fn create_function_type(
1683 &self,
1684 ty: crate::ComponentFuncType,
1685 types: &TypeList,
1686 features: &WasmFeatures,
1687 offset: usize,
1688 ) -> Result<ComponentFuncType> {
1689 let mut info = TypeInfo::new();
1690
1691 if ty.results.type_count() > 1 && !features.component_model_multiple_returns() {
1692 bail!(
1693 offset,
1694 "multiple returns on a function is now a gated feature \
1695 -- https://github.com/WebAssembly/component-model/pull/368"
1696 );
1697 }
1698
1699 let mut set = Set::default();
1700 #[cfg(not(feature = "no-hash-maps"))] // TODO: remove when unified map type is available
1701 set.reserve(core::cmp::max(ty.params.len(), ty.results.type_count()));
1702
1703 let params = ty
1704 .params
1705 .iter()
1706 .map(|(name, ty)| {
1707 let name: &KebabStr = to_kebab_str(name, "function parameter", offset)?;
1708 if !set.insert(name) {
1709 bail!(
1710 offset,
1711 "function parameter name `{name}` conflicts with previous parameter name `{prev}`",
1712 prev = set.get(&name).unwrap(),
1713 );
1714 }
1715
1716 let ty = self.create_component_val_type(*ty, offset)?;
1717 info.combine(ty.info(types), offset)?;
1718 Ok((name.to_owned(), ty))
1719 })
1720 .collect::<Result<_>>()?;
1721
1722 set.clear();
1723
1724 let results = ty
1725 .results
1726 .iter()
1727 .map(|(name, ty)| {
1728 let name = name
1729 .map(|name| {
1730 let name = to_kebab_str(name, "function result", offset)?;
1731 if !set.insert(name) {
1732 bail!(
1733 offset,
1734 "function result name `{name}` conflicts with previous result name `{prev}`",
1735 prev = set.get(name).unwrap(),
1736 );
1737 }
1738
1739 Ok(name.to_owned())
1740 })
1741 .transpose()?;
1742
1743 let ty = self.create_component_val_type(*ty, offset)?;
1744 let ty_info = ty.info(types);
1745 if ty_info.contains_borrow() {
1746 bail!(offset, "function result cannot contain a `borrow` type");
1747 }
1748 info.combine(ty.info(types), offset)?;
1749 Ok((name, ty))
1750 })
1751 .collect::<Result<_>>()?;
1752
1753 Ok(ComponentFuncType {
1754 info,
1755 params,
1756 results,
1757 })
1758 }
1759
1760 fn instantiate_core_module(
1761 &self,
1762 module_index: u32,
1763 module_args: Vec<crate::InstantiationArg>,
1764 types: &mut TypeAlloc,
1765 offset: usize,
1766 ) -> Result<ComponentCoreInstanceTypeId> {
1767 fn insert_arg<'a>(
1768 name: &'a str,
1769 arg: &'a InstanceType,
1770 args: &mut IndexMap<&'a str, &'a InstanceType>,
1771 offset: usize,
1772 ) -> Result<()> {
1773 if args.insert(name, arg).is_some() {
1774 bail!(
1775 offset,
1776 "duplicate module instantiation argument named `{name}`"
1777 );
1778 }
1779
1780 Ok(())
1781 }
1782
1783 let module_type_id = self.module_at(module_index, offset)?;
1784 let mut args = IndexMap::default();
1785
1786 // Populate the arguments
1787 for module_arg in module_args {
1788 match module_arg.kind {
1789 InstantiationArgKind::Instance => {
1790 let instance_type = &types[self.core_instance_at(module_arg.index, offset)?];
1791 insert_arg(module_arg.name, instance_type, &mut args, offset)?;
1792 }
1793 }
1794 }
1795
1796 // Validate the arguments
1797 let module_type = &types[module_type_id];
1798 let cx = SubtypeCx::new(types, types);
1799 for ((module, name), expected) in module_type.imports.iter() {
1800 let instance = args.get(module.as_str()).ok_or_else(|| {
1801 format_err!(
1802 offset,
1803 "missing module instantiation argument named `{module}`"
1804 )
1805 })?;
1806
1807 let arg = instance
1808 .internal_exports(types)
1809 .get(name.as_str())
1810 .ok_or_else(|| {
1811 format_err!(
1812 offset,
1813 "module instantiation argument `{module}` does not \
1814 export an item named `{name}`",
1815 )
1816 })?;
1817
1818 cx.entity_type(arg, expected, offset).with_context(|| {
1819 format!(
1820 "type mismatch for export `{name}` of module \
1821 instantiation argument `{module}`"
1822 )
1823 })?;
1824 }
1825
1826 let mut info = TypeInfo::new();
1827 for (_, ty) in module_type.exports.iter() {
1828 info.combine(ty.info(types), offset)?;
1829 }
1830
1831 Ok(types.push_ty(InstanceType {
1832 info,
1833 kind: CoreInstanceTypeKind::Instantiated(module_type_id),
1834 }))
1835 }
1836
1837 fn instantiate_component(
1838 &mut self,
1839 component_index: u32,
1840 component_args: Vec<crate::ComponentInstantiationArg>,
1841 features: &WasmFeatures,
1842 types: &mut TypeAlloc,
1843 offset: usize,
1844 ) -> Result<ComponentInstanceTypeId> {
1845 let component_type_id = self.component_at(component_index, offset)?;
1846 let mut args = IndexMap::default();
1847
1848 // Populate the arguments
1849 for component_arg in component_args {
1850 let ty = match component_arg.kind {
1851 ComponentExternalKind::Module => {
1852 ComponentEntityType::Module(self.module_at(component_arg.index, offset)?)
1853 }
1854 ComponentExternalKind::Component => {
1855 ComponentEntityType::Component(self.component_at(component_arg.index, offset)?)
1856 }
1857 ComponentExternalKind::Instance => {
1858 ComponentEntityType::Instance(self.instance_at(component_arg.index, offset)?)
1859 }
1860 ComponentExternalKind::Func => {
1861 ComponentEntityType::Func(self.function_at(component_arg.index, offset)?)
1862 }
1863 ComponentExternalKind::Value => {
1864 self.check_value_support(features, offset)?;
1865 ComponentEntityType::Value(*self.value_at(component_arg.index, offset)?)
1866 }
1867 ComponentExternalKind::Type => {
1868 let ty = self.component_type_at(component_arg.index, offset)?;
1869 ComponentEntityType::Type {
1870 referenced: ty,
1871 created: ty,
1872 }
1873 }
1874 };
1875 match args.entry(component_arg.name.to_string()) {
1876 Entry::Occupied(e) => {
1877 bail!(
1878 offset,
1879 "instantiation argument `{name}` conflicts with previous argument `{prev}`",
1880 prev = e.key(),
1881 name = component_arg.name
1882 );
1883 }
1884 Entry::Vacant(e) => {
1885 e.insert(ty);
1886 }
1887 }
1888 }
1889
1890 // Here comes the fun part of the component model, we're instantiating
1891 // the component with type `component_type_id` with the `args`
1892 // specified. Easy enough!
1893 //
1894 // This operation, however, is one of the lynchpins of safety in the
1895 // component model. Additionally what this ends up implementing ranges
1896 // from "well just check the types are equal" to "let's have a
1897 // full-blown ML-style module type system in the component model". There
1898 // are primarily two major tricky pieces to the component model which
1899 // make this operation, instantiating components, hard:
1900 //
1901 // 1. Components can import and exports other components. This means
1902 // that arguments to instantiation are along the lines of functions
1903 // being passed to functions or similar. Effectively this means that
1904 // the term "variance" comes into play with either contravariance
1905 // or covariance depending on where you are in typechecking. This is
1906 // one of the main rationales, however, that this check below is a
1907 // check for subtyping as opposed to exact type equivalence. For
1908 // example an instance that exports something is a subtype of an
1909 // instance that exports nothing. Components get a bit trick since
1910 // they both have imports and exports. My way of thinking about it
1911 // is "who's asking for what". If you're asking for imports then
1912 // I need to at least supply those imports, but I can possibly
1913 // supply more. If you're asking for a thing which you'll give a set
1914 // of imports, then I can give you something which takes less imports
1915 // because what you give still suffices. (things like that). The
1916 // real complication with components, however, comes with...
1917 //
1918 // 2. Resources. Resources in the component model are akin to "abstract
1919 // types". They're not abstract in the sense that they have no
1920 // representation, they're always backed by a 32-bit integer right
1921 // now. Instead they're abstract in the sense that some components
1922 // aren't allowed to understand the representation of a resource.
1923 // For example if you import a resource you can't get the underlying
1924 // internals of it. Furthermore the resource is strictly tracked
1925 // within the component with `own` and `borrow` runtime semantics.
1926 // The hardest part about resources, though, is handling them as
1927 // part of instantiation and subtyping.
1928 //
1929 // For example one major aspect of resources is that if a component
1930 // exports a resource then each instantiation of the component
1931 // produces a fresh resource type. This means that the type recorded
1932 // for the instantiation here can't simply be "I instantiated
1933 // component X" since in such a situation the type of all
1934 // instantiations would be the same, which they aren't.
1935 //
1936 // This sort of subtelty comes up quite frequently for resources.
1937 // This file contains references to `imported_resources` and
1938 // `defined_resources` for example which refer to the formal
1939 // nature of components and their abstract variables. Specifically
1940 // for instantiation though we're eventually faced with the problem
1941 // of subtype checks where resource subtyping is defined as "does
1942 // your id equal mine". Naively implemented that means anything with
1943 // resources isn't subtypes of anything else since resource ids are
1944 // unique between components. Instead what actually needs to happen
1945 // is types need to be substituted.
1946 //
1947 // Much of the complexity here is not actually apparent here in this
1948 // literal one function. Instead it's spread out across validation
1949 // in this file and type-checking in the `types.rs` module. Note that
1950 // the "spread out" nature isn't because we're bad maintainers
1951 // (hopefully), but rather it's quite infectious how many parts need
1952 // to handle resources and account for defined/imported variables.
1953 //
1954 // For example only one subtyping method is called here where `args` is
1955 // passed in. This method is quite recursive in its nature though and
1956 // will internally touch all the fields that this file maintains to
1957 // end up putting into various bits and pieces of type information.
1958 //
1959 // Unfortunately there's probably not really a succinct way to read
1960 // this method and understand everything. If you've written ML module
1961 // type systems this will probably look quite familiar, but otherwise
1962 // the whole system is not really easily approachable at this time. It's
1963 // hoped in the future that there's a formalism to refer to which will
1964 // make things more clear as the code would be able to reference this
1965 // hypothetical formalism. Until that's the case, though, these
1966 // comments are hopefully enough when augmented with communication with
1967 // the authors.
1968
1969 let component_type = &types[component_type_id];
1970 let mut exports = component_type.exports.clone();
1971 let mut info = TypeInfo::new();
1972 for (_, ty) in component_type.exports.iter() {
1973 info.combine(ty.info(types), offset)?;
1974 }
1975
1976 // Perform the subtype check that `args` matches the imports of
1977 // `component_type_id`. The result of this subtype check is the
1978 // production of a mapping of resource types from the imports to the
1979 // arguments provided. This is a substitution map which is then used
1980 // below to perform a substitution into the exports of the instance
1981 // since the types of the exports are now in terms of whatever was
1982 // supplied as imports.
1983 let mut mapping = SubtypeCx::new(types, types).open_instance_type(
1984 &args,
1985 component_type_id,
1986 ExternKind::Import,
1987 offset,
1988 )?;
1989
1990 // Part of the instantiation of a component is that all of its
1991 // defined resources become "fresh" on each instantiation. This
1992 // means that each instantiation of a component gets brand new type
1993 // variables representing its defined resources, modeling that each
1994 // instantiation produces distinct types. The freshening is performed
1995 // here by allocating new ids and inserting them into `mapping`.
1996 //
1997 // Note that technically the `mapping` from subtyping should be applied
1998 // first and then the mapping for freshening should be applied
1999 // afterwards. The keys of the map from subtyping are the imported
2000 // resources from this component which are disjoint from its defined
2001 // resources. That means it should be possible to place everything
2002 // into one large map which maps from:
2003 //
2004 // * the component's imported resources go to whatever was explicitly
2005 // supplied in the import map
2006 // * the component's defined resources go to fresh new resources
2007 //
2008 // These two remapping operations can then get folded into one by
2009 // placing everything in the same `mapping` and using that for a remap
2010 // only once.
2011 let fresh_defined_resources = (0..component_type.defined_resources.len())
2012 .map(|_| types.alloc_resource_id().resource())
2013 .collect::<IndexSet<_>>();
2014 let component_type = &types[component_type_id];
2015 for ((old, _path), new) in component_type
2016 .defined_resources
2017 .iter()
2018 .zip(&fresh_defined_resources)
2019 {
2020 let prev = mapping.resources.insert(*old, *new);
2021 assert!(prev.is_none());
2022 }
2023
2024 // Perform the remapping operation over all the exports that will be
2025 // listed for the final instance type. Note that this is performed
2026 // both for all the export types in addition to the explicitly exported
2027 // resources list.
2028 //
2029 // Note that this is a crucial step of the instantiation process which
2030 // is intentionally transforming the type of a component based on the
2031 // variables provided by imports and additionally ensuring that all
2032 // references to the component's defined resources are rebound to the
2033 // fresh ones introduced just above.
2034 for entity in exports.values_mut() {
2035 types.remap_component_entity(entity, &mut mapping);
2036 }
2037 let component_type = &types[component_type_id];
2038 let explicit_resources = component_type
2039 .explicit_resources
2040 .iter()
2041 .map(|(id, path)| {
2042 (
2043 mapping.resources.get(id).copied().unwrap_or(*id),
2044 path.clone(),
2045 )
2046 })
2047 .collect::<IndexMap<_, _>>();
2048
2049 // Technically in the last formalism that was consulted in writing this
2050 // implementation there are two further steps that are part of the
2051 // instantiation process:
2052 //
2053 // 1. The set of defined resources from the instance created, which are
2054 // added to the outer component, is the subset of the instance's
2055 // original defined resources and the free variables of the exports.
2056 //
2057 // 2. Each element of this subset is required to be "explicit in" the
2058 // instance, or otherwise explicitly exported somewhere within the
2059 // instance.
2060 //
2061 // With the syntactic structure of the component model, however, neither
2062 // of these conditions should be necessary. The main reason for this is
2063 // that this function is specifically dealing with instantiation of
2064 // components which should already have these properties validated
2065 // about them. Subsequently we shouldn't have to re-check them.
2066 //
2067 // In debug mode, however, do a sanity check.
2068 if cfg!(debug_assertions) {
2069 let mut free = IndexSet::default();
2070 for ty in exports.values() {
2071 types.free_variables_component_entity(ty, &mut free);
2072 }
2073 assert!(fresh_defined_resources.is_subset(&free));
2074 for resource in fresh_defined_resources.iter() {
2075 assert!(explicit_resources.contains_key(resource));
2076 }
2077 }
2078
2079 // And as the final step of the instantiation process all of the
2080 // new defined resources from this component instantiation are moved
2081 // onto `self`. Note that concrete instances never have defined
2082 // resources (see more comments in `instantiate_exports`) so the
2083 // `defined_resources` listing in the final type is always empty. This
2084 // represents how by having a concrete instance the definitions
2085 // referred to in that instance are now problems for the outer
2086 // component rather than the inner instance since the instance is bound
2087 // to the component.
2088 //
2089 // All defined resources here have no known representation, so they're
2090 // all listed with `None`. Also note that none of the resources were
2091 // exported yet so `self.explicit_resources` is not updated yet. If
2092 // this instance is exported, however, it'll consult the type's
2093 // `explicit_resources` array and use that appropriately.
2094 for resource in fresh_defined_resources {
2095 self.defined_resources.insert(resource, None);
2096 }
2097
2098 Ok(types.push_ty(ComponentInstanceType {
2099 info,
2100 defined_resources: Default::default(),
2101 explicit_resources,
2102 exports,
2103 }))
2104 }
2105
2106 fn instantiate_component_exports(
2107 &mut self,
2108 exports: Vec<crate::ComponentExport>,
2109 features: &WasmFeatures,
2110 types: &mut TypeAlloc,
2111 offset: usize,
2112 ) -> Result<ComponentInstanceTypeId> {
2113 let mut info = TypeInfo::new();
2114 let mut inst_exports = IndexMap::default();
2115 let mut explicit_resources = IndexMap::default();
2116 let mut export_names = IndexSet::default();
2117
2118 // NB: It's intentional that this context is empty since no indices are
2119 // introduced in the bag-of-exports construct which means there's no
2120 // way syntactically to register something inside of this.
2121 let names = ComponentNameContext::default();
2122
2123 for export in exports {
2124 assert!(export.ty.is_none());
2125 let ty = match export.kind {
2126 ComponentExternalKind::Module => {
2127 ComponentEntityType::Module(self.module_at(export.index, offset)?)
2128 }
2129 ComponentExternalKind::Component => {
2130 ComponentEntityType::Component(self.component_at(export.index, offset)?)
2131 }
2132 ComponentExternalKind::Instance => {
2133 let ty = self.instance_at(export.index, offset)?;
2134
2135 // When an instance is exported from an instance then
2136 // all explicitly exported resources on the sub-instance are
2137 // now also listed as exported resources on the outer
2138 // instance, just with one more element in their path.
2139 explicit_resources.extend(types[ty].explicit_resources.iter().map(
2140 |(id, path)| {
2141 let mut new_path = vec![inst_exports.len()];
2142 new_path.extend(path);
2143 (*id, new_path)
2144 },
2145 ));
2146 ComponentEntityType::Instance(ty)
2147 }
2148 ComponentExternalKind::Func => {
2149 ComponentEntityType::Func(self.function_at(export.index, offset)?)
2150 }
2151 ComponentExternalKind::Value => {
2152 self.check_value_support(features, offset)?;
2153 ComponentEntityType::Value(*self.value_at(export.index, offset)?)
2154 }
2155 ComponentExternalKind::Type => {
2156 let ty = self.component_type_at(export.index, offset)?;
2157 // If this is an export of a resource type be sure to
2158 // record that in the explicit list with the appropriate
2159 // path because if this instance ends up getting used
2160 // it'll count towards the "explicit in" check.
2161 if let ComponentAnyTypeId::Resource(id) = ty {
2162 explicit_resources.insert(id.resource(), vec![inst_exports.len()]);
2163 }
2164 ComponentEntityType::Type {
2165 referenced: ty,
2166 // The created type index here isn't used anywhere
2167 // in index spaces because a "bag of exports"
2168 // doesn't build up its own index spaces. Just fill
2169 // in the same index here in this case as what's
2170 // referenced.
2171 created: ty,
2172 }
2173 }
2174 };
2175
2176 names.validate_extern(
2177 export.name.0,
2178 ExternKind::Export,
2179 &ty,
2180 types,
2181 offset,
2182 &mut export_names,
2183 &mut inst_exports,
2184 &mut info,
2185 features,
2186 )?;
2187 }
2188
2189 Ok(types.push_ty(ComponentInstanceType {
2190 info,
2191 explicit_resources,
2192 exports: inst_exports,
2193
2194 // NB: the list of defined resources for this instance itself
2195 // is always empty. Even if this instance exports resources,
2196 // it's empty.
2197 //
2198 // The reason for this is a bit subtle. The general idea, though, is
2199 // that the defined resources list here is only used for instance
2200 // types that are sort of "floating around" and haven't actually
2201 // been attached to something yet. For example when an instance type
2202 // is simply declared it can have defined resources introduced
2203 // through `(export "name" (type (sub resource)))`. These
2204 // definitions, however, are local to the instance itself and aren't
2205 // defined elsewhere.
2206 //
2207 // Here, though, no new definitions were introduced. The instance
2208 // created here is a "bag of exports" which could only refer to
2209 // preexisting items. This means that inherently no new resources
2210 // were created so there's nothing to put in this list. Any
2211 // resources referenced by the instance must be bound by the outer
2212 // component context or further above.
2213 //
2214 // Furthermore, however, actual instances of instances, which this
2215 // is, aren't allowed to have defined resources. Instead the
2216 // resources would have to be injected into the outer component
2217 // enclosing the instance. That means that even if bag-of-exports
2218 // could declare a new resource then the resource would be moved
2219 // from here to `self.defined_resources`. This doesn't exist at this
2220 // time, though, so this still remains empty and
2221 // `self.defined_resources` remains unperturbed.
2222 defined_resources: Default::default(),
2223 }))
2224 }
2225
2226 fn instantiate_core_exports(
2227 &mut self,
2228 exports: Vec<crate::Export>,
2229 types: &mut TypeAlloc,
2230 offset: usize,
2231 ) -> Result<ComponentCoreInstanceTypeId> {
2232 fn insert_export(
2233 types: &TypeList,
2234 name: &str,
2235 export: EntityType,
2236 exports: &mut IndexMap<String, EntityType>,
2237 info: &mut TypeInfo,
2238 offset: usize,
2239 ) -> Result<()> {
2240 info.combine(export.info(types), offset)?;
2241
2242 if exports.insert(name.to_string(), export).is_some() {
2243 bail!(
2244 offset,
2245 "duplicate instantiation export name `{name}` already defined",
2246 )
2247 }
2248
2249 Ok(())
2250 }
2251
2252 let mut info = TypeInfo::new();
2253 let mut inst_exports = IndexMap::default();
2254 for export in exports {
2255 match export.kind {
2256 ExternalKind::Func => {
2257 insert_export(
2258 types,
2259 export.name,
2260 EntityType::Func(self.core_function_at(export.index, offset)?),
2261 &mut inst_exports,
2262 &mut info,
2263 offset,
2264 )?;
2265 }
2266 ExternalKind::Table => insert_export(
2267 types,
2268 export.name,
2269 EntityType::Table(*self.table_at(export.index, offset)?),
2270 &mut inst_exports,
2271 &mut info,
2272 offset,
2273 )?,
2274 ExternalKind::Memory => insert_export(
2275 types,
2276 export.name,
2277 EntityType::Memory(*self.memory_at(export.index, offset)?),
2278 &mut inst_exports,
2279 &mut info,
2280 offset,
2281 )?,
2282 ExternalKind::Global => {
2283 insert_export(
2284 types,
2285 export.name,
2286 EntityType::Global(*self.global_at(export.index, offset)?),
2287 &mut inst_exports,
2288 &mut info,
2289 offset,
2290 )?;
2291 }
2292 ExternalKind::Tag => insert_export(
2293 types,
2294 export.name,
2295 EntityType::Tag(self.core_function_at(export.index, offset)?),
2296 &mut inst_exports,
2297 &mut info,
2298 offset,
2299 )?,
2300 }
2301 }
2302
2303 Ok(types.push_ty(InstanceType {
2304 info,
2305 kind: CoreInstanceTypeKind::Exports(inst_exports),
2306 }))
2307 }
2308
2309 fn alias_core_instance_export(
2310 &mut self,
2311 instance_index: u32,
2312 kind: ExternalKind,
2313 name: &str,
2314 types: &TypeList,
2315 offset: usize,
2316 ) -> Result<()> {
2317 macro_rules! push_module_export {
2318 ($expected:path, $collection:ident, $ty:literal) => {{
2319 match self.core_instance_export(instance_index, name, types, offset)? {
2320 $expected(ty) => {
2321 self.$collection.push(*ty);
2322 Ok(())
2323 }
2324 _ => {
2325 bail!(
2326 offset,
2327 "export `{name}` for core instance {instance_index} is not a {}",
2328 $ty
2329 )
2330 }
2331 }
2332 }};
2333 }
2334
2335 match kind {
2336 ExternalKind::Func => {
2337 check_max(
2338 self.function_count(),
2339 1,
2340 MAX_WASM_FUNCTIONS,
2341 "functions",
2342 offset,
2343 )?;
2344 push_module_export!(EntityType::Func, core_funcs, "function")
2345 }
2346 ExternalKind::Table => {
2347 check_max(
2348 self.core_tables.len(),
2349 1,
2350 MAX_CORE_INDEX_SPACE_ITEMS,
2351 "tables",
2352 offset,
2353 )?;
2354 push_module_export!(EntityType::Table, core_tables, "table")
2355 }
2356 ExternalKind::Memory => {
2357 check_max(
2358 self.core_memories.len(),
2359 1,
2360 MAX_CORE_INDEX_SPACE_ITEMS,
2361 "memories",
2362 offset,
2363 )?;
2364 push_module_export!(EntityType::Memory, core_memories, "memory")
2365 }
2366 ExternalKind::Global => {
2367 check_max(
2368 self.core_globals.len(),
2369 1,
2370 MAX_CORE_INDEX_SPACE_ITEMS,
2371 "globals",
2372 offset,
2373 )?;
2374 push_module_export!(EntityType::Global, core_globals, "global")
2375 }
2376 ExternalKind::Tag => {
2377 check_max(
2378 self.core_tags.len(),
2379 1,
2380 MAX_CORE_INDEX_SPACE_ITEMS,
2381 "tags",
2382 offset,
2383 )?;
2384 push_module_export!(EntityType::Tag, core_tags, "tag")
2385 }
2386 }
2387 }
2388
2389 fn alias_instance_export(
2390 &mut self,
2391 instance_index: u32,
2392 kind: ComponentExternalKind,
2393 name: &str,
2394 features: &WasmFeatures,
2395 types: &mut TypeAlloc,
2396 offset: usize,
2397 ) -> Result<()> {
2398 if let ComponentExternalKind::Value = kind {
2399 self.check_value_support(features, offset)?;
2400 }
2401 let mut ty = match types[self.instance_at(instance_index, offset)?]
2402 .exports
2403 .get(name)
2404 {
2405 Some(ty) => *ty,
2406 None => bail!(
2407 offset,
2408 "instance {instance_index} has no export named `{name}`"
2409 ),
2410 };
2411
2412 let ok = match (&ty, kind) {
2413 (ComponentEntityType::Module(_), ComponentExternalKind::Module) => true,
2414 (ComponentEntityType::Module(_), _) => false,
2415 (ComponentEntityType::Component(_), ComponentExternalKind::Component) => true,
2416 (ComponentEntityType::Component(_), _) => false,
2417 (ComponentEntityType::Func(_), ComponentExternalKind::Func) => true,
2418 (ComponentEntityType::Func(_), _) => false,
2419 (ComponentEntityType::Instance(_), ComponentExternalKind::Instance) => true,
2420 (ComponentEntityType::Instance(_), _) => false,
2421 (ComponentEntityType::Value(_), ComponentExternalKind::Value) => true,
2422 (ComponentEntityType::Value(_), _) => false,
2423 (ComponentEntityType::Type { .. }, ComponentExternalKind::Type) => true,
2424 (ComponentEntityType::Type { .. }, _) => false,
2425 };
2426 if !ok {
2427 bail!(
2428 offset,
2429 "export `{name}` for instance {instance_index} is not a {}",
2430 kind.desc(),
2431 );
2432 }
2433
2434 self.add_entity(&mut ty, None, features, types, offset)?;
2435 Ok(())
2436 }
2437
2438 fn alias_module(components: &mut [Self], count: u32, index: u32, offset: usize) -> Result<()> {
2439 let component = Self::check_alias_count(components, count, offset)?;
2440 let ty = component.module_at(index, offset)?;
2441
2442 let current = components.last_mut().unwrap();
2443 check_max(
2444 current.core_modules.len(),
2445 1,
2446 MAX_WASM_MODULES,
2447 "modules",
2448 offset,
2449 )?;
2450
2451 current.core_modules.push(ty);
2452 Ok(())
2453 }
2454
2455 fn alias_component(
2456 components: &mut [Self],
2457 count: u32,
2458 index: u32,
2459 offset: usize,
2460 ) -> Result<()> {
2461 let component = Self::check_alias_count(components, count, offset)?;
2462 let ty = component.component_at(index, offset)?;
2463
2464 let current = components.last_mut().unwrap();
2465 check_max(
2466 current.components.len(),
2467 1,
2468 MAX_WASM_COMPONENTS,
2469 "components",
2470 offset,
2471 )?;
2472
2473 current.components.push(ty);
2474 Ok(())
2475 }
2476
2477 fn alias_core_type(
2478 components: &mut [Self],
2479 count: u32,
2480 index: u32,
2481 offset: usize,
2482 ) -> Result<()> {
2483 let component = Self::check_alias_count(components, count, offset)?;
2484 let ty = component.core_type_at(index, offset)?;
2485
2486 let current = components.last_mut().unwrap();
2487 check_max(current.type_count(), 1, MAX_WASM_TYPES, "types", offset)?;
2488
2489 current.core_types.push(ty);
2490
2491 Ok(())
2492 }
2493
2494 fn alias_type(
2495 components: &mut [Self],
2496 count: u32,
2497 index: u32,
2498 types: &mut TypeAlloc,
2499 offset: usize,
2500 ) -> Result<()> {
2501 let component = Self::check_alias_count(components, count, offset)?;
2502 let ty = component.component_type_at(index, offset)?;
2503
2504 // If `count` "crossed a component boundary", meaning that it went from
2505 // one component to another, then this must additionally verify that
2506 // `ty` has no free variables with respect to resources. This is
2507 // intended to preserve the property for components where each component
2508 // is an isolated unit that can theoretically be extracted from other
2509 // components. If resources from other components were allowed to leak
2510 // in then it would prevent that.
2511 //
2512 // This check is done by calculating the `pos` within `components` that
2513 // our target `component` above was selected at. Once this is acquired
2514 // the component to the "right" is checked, and if that's a component
2515 // then it's considered as crossing a component boundary meaning the
2516 // free variables check runs.
2517 //
2518 // The reason this works is that in the list of `ComponentState` types
2519 // it's guaranteed that any `is_type` components are contiguous at the
2520 // end of the array. This means that if state one level deeper than the
2521 // target of this alias is a `!is_type` component, then the target must
2522 // be a component as well. If the one-level deeper state `is_type` then
2523 // the target is either a type or a component, both of which are valid
2524 // (as aliases can reach the enclosing component and have as many free
2525 // variables as they want).
2526 let pos_after_component = components.len() - (count as usize);
2527 if let Some(component) = components.get(pos_after_component) {
2528 if component.kind == ComponentKind::Component {
2529 let mut free = IndexSet::default();
2530 types.free_variables_any_type_id(ty, &mut free);
2531 if !free.is_empty() {
2532 bail!(
2533 offset,
2534 "cannot alias outer type which transitively refers \
2535 to resources not defined in the current component"
2536 );
2537 }
2538 }
2539 }
2540
2541 let current = components.last_mut().unwrap();
2542 check_max(current.type_count(), 1, MAX_WASM_TYPES, "types", offset)?;
2543
2544 current.types.push(ty);
2545
2546 Ok(())
2547 }
2548
2549 fn check_alias_count(components: &[Self], count: u32, offset: usize) -> Result<&Self> {
2550 let count = count as usize;
2551 if count >= components.len() {
2552 bail!(offset, "invalid outer alias count of {count}");
2553 }
2554
2555 Ok(&components[components.len() - count - 1])
2556 }
2557
2558 fn create_defined_type(
2559 &self,
2560 ty: crate::ComponentDefinedType,
2561 types: &TypeList,
2562 features: &WasmFeatures,
2563 offset: usize,
2564 ) -> Result<ComponentDefinedType> {
2565 match ty {
2566 crate::ComponentDefinedType::Primitive(ty) => Ok(ComponentDefinedType::Primitive(ty)),
2567 crate::ComponentDefinedType::Record(fields) => {
2568 self.create_record_type(fields.as_ref(), types, offset)
2569 }
2570 crate::ComponentDefinedType::Variant(cases) => {
2571 self.create_variant_type(cases.as_ref(), types, offset)
2572 }
2573 crate::ComponentDefinedType::List(ty) => Ok(ComponentDefinedType::List(
2574 self.create_component_val_type(ty, offset)?,
2575 )),
2576 crate::ComponentDefinedType::Tuple(tys) => {
2577 self.create_tuple_type(tys.as_ref(), types, offset)
2578 }
2579 crate::ComponentDefinedType::Flags(names) => {
2580 self.create_flags_type(names.as_ref(), features, offset)
2581 }
2582 crate::ComponentDefinedType::Enum(cases) => {
2583 self.create_enum_type(cases.as_ref(), offset)
2584 }
2585 crate::ComponentDefinedType::Option(ty) => Ok(ComponentDefinedType::Option(
2586 self.create_component_val_type(ty, offset)?,
2587 )),
2588 crate::ComponentDefinedType::Result { ok, err } => Ok(ComponentDefinedType::Result {
2589 ok: ok
2590 .map(|ty| self.create_component_val_type(ty, offset))
2591 .transpose()?,
2592 err: err
2593 .map(|ty| self.create_component_val_type(ty, offset))
2594 .transpose()?,
2595 }),
2596 crate::ComponentDefinedType::Own(idx) => Ok(ComponentDefinedType::Own(
2597 self.resource_at(idx, types, offset)?,
2598 )),
2599 crate::ComponentDefinedType::Borrow(idx) => Ok(ComponentDefinedType::Borrow(
2600 self.resource_at(idx, types, offset)?,
2601 )),
2602 }
2603 }
2604
2605 fn create_record_type(
2606 &self,
2607 fields: &[(&str, crate::ComponentValType)],
2608 types: &TypeList,
2609 offset: usize,
2610 ) -> Result<ComponentDefinedType> {
2611 let mut info = TypeInfo::new();
2612 let mut field_map = IndexMap::default();
2613 field_map.reserve(fields.len());
2614
2615 if fields.is_empty() {
2616 bail!(offset, "record type must have at least one field");
2617 }
2618
2619 for (name, ty) in fields {
2620 let name = to_kebab_str(name, "record field", offset)?;
2621 let ty = self.create_component_val_type(*ty, offset)?;
2622
2623 match field_map.entry(name.to_owned()) {
2624 Entry::Occupied(e) => bail!(
2625 offset,
2626 "record field name `{name}` conflicts with previous field name `{prev}`",
2627 prev = e.key()
2628 ),
2629 Entry::Vacant(e) => {
2630 info.combine(ty.info(types), offset)?;
2631 e.insert(ty);
2632 }
2633 }
2634 }
2635
2636 Ok(ComponentDefinedType::Record(RecordType {
2637 info,
2638 fields: field_map,
2639 }))
2640 }
2641
2642 fn create_variant_type(
2643 &self,
2644 cases: &[crate::VariantCase],
2645 types: &TypeList,
2646 offset: usize,
2647 ) -> Result<ComponentDefinedType> {
2648 let mut info = TypeInfo::new();
2649 let mut case_map: IndexMap<KebabString, VariantCase> = IndexMap::default();
2650 case_map.reserve(cases.len());
2651
2652 if cases.is_empty() {
2653 bail!(offset, "variant type must have at least one case");
2654 }
2655
2656 if cases.len() > u32::MAX as usize {
2657 return Err(BinaryReaderError::new(
2658 "variant type cannot be represented with a 32-bit discriminant value",
2659 offset,
2660 ));
2661 }
2662
2663 for (i, case) in cases.iter().enumerate() {
2664 if let Some(refines) = case.refines {
2665 if refines >= i as u32 {
2666 return Err(BinaryReaderError::new(
2667 "variant case can only refine a previously defined case",
2668 offset,
2669 ));
2670 }
2671 }
2672
2673 let name = to_kebab_str(case.name, "variant case", offset)?;
2674
2675 let ty = case
2676 .ty
2677 .map(|ty| self.create_component_val_type(ty, offset))
2678 .transpose()?;
2679
2680 match case_map.entry(name.to_owned()) {
2681 Entry::Occupied(e) => bail!(
2682 offset,
2683 "variant case name `{name}` conflicts with previous case name `{prev}`",
2684 name = case.name,
2685 prev = e.key()
2686 ),
2687 Entry::Vacant(e) => {
2688 if let Some(ty) = ty {
2689 info.combine(ty.info(types), offset)?;
2690 }
2691
2692 // Safety: the use of `KebabStr::new_unchecked` here is safe because the string
2693 // was already verified to be kebab case.
2694 e.insert(VariantCase {
2695 ty,
2696 refines: case
2697 .refines
2698 .map(|i| KebabStr::new_unchecked(cases[i as usize].name).to_owned()),
2699 });
2700 }
2701 }
2702 }
2703
2704 Ok(ComponentDefinedType::Variant(VariantType {
2705 info,
2706 cases: case_map,
2707 }))
2708 }
2709
2710 fn create_tuple_type(
2711 &self,
2712 tys: &[crate::ComponentValType],
2713 types: &TypeList,
2714 offset: usize,
2715 ) -> Result<ComponentDefinedType> {
2716 let mut info = TypeInfo::new();
2717 if tys.is_empty() {
2718 bail!(offset, "tuple type must have at least one type");
2719 }
2720 let types = tys
2721 .iter()
2722 .map(|ty| {
2723 let ty = self.create_component_val_type(*ty, offset)?;
2724 info.combine(ty.info(types), offset)?;
2725 Ok(ty)
2726 })
2727 .collect::<Result<_>>()?;
2728
2729 Ok(ComponentDefinedType::Tuple(TupleType { info, types }))
2730 }
2731
2732 fn create_flags_type(
2733 &self,
2734 names: &[&str],
2735 features: &WasmFeatures,
2736 offset: usize,
2737 ) -> Result<ComponentDefinedType> {
2738 let mut names_set = IndexSet::default();
2739 names_set.reserve(names.len());
2740
2741 if names.is_empty() {
2742 bail!(offset, "flags must have at least one entry");
2743 }
2744
2745 if names.len() > 32 && !features.component_model_more_flags() {
2746 bail!(
2747 offset,
2748 "cannot have more than 32 flags; this was previously \
2749 accepted and if this is required for your project please \
2750 leave a comment on \
2751 https://github.com/WebAssembly/component-model/issues/370"
2752 );
2753 }
2754
2755 for name in names {
2756 let name = to_kebab_str(name, "flag", offset)?;
2757 if !names_set.insert(name.to_owned()) {
2758 bail!(
2759 offset,
2760 "flag name `{name}` conflicts with previous flag name `{prev}`",
2761 prev = names_set.get(name).unwrap()
2762 );
2763 }
2764 }
2765
2766 Ok(ComponentDefinedType::Flags(names_set))
2767 }
2768
2769 fn create_enum_type(&self, cases: &[&str], offset: usize) -> Result<ComponentDefinedType> {
2770 if cases.len() > u32::MAX as usize {
2771 return Err(BinaryReaderError::new(
2772 "enumeration type cannot be represented with a 32-bit discriminant value",
2773 offset,
2774 ));
2775 }
2776
2777 if cases.is_empty() {
2778 bail!(offset, "enum type must have at least one variant");
2779 }
2780
2781 let mut tags = IndexSet::default();
2782 tags.reserve(cases.len());
2783
2784 for tag in cases {
2785 let tag = to_kebab_str(tag, "enum tag", offset)?;
2786 if !tags.insert(tag.to_owned()) {
2787 bail!(
2788 offset,
2789 "enum tag name `{tag}` conflicts with previous tag name `{prev}`",
2790 prev = tags.get(tag).unwrap()
2791 );
2792 }
2793 }
2794
2795 Ok(ComponentDefinedType::Enum(tags))
2796 }
2797
2798 fn create_component_val_type(
2799 &self,
2800 ty: crate::ComponentValType,
2801 offset: usize,
2802 ) -> Result<ComponentValType> {
2803 Ok(match ty {
2804 crate::ComponentValType::Primitive(pt) => ComponentValType::Primitive(pt),
2805 crate::ComponentValType::Type(idx) => {
2806 ComponentValType::Type(self.defined_type_at(idx, offset)?)
2807 }
2808 })
2809 }
2810
2811 pub fn core_type_at(&self, idx: u32, offset: usize) -> Result<ComponentCoreTypeId> {
2812 self.core_types
2813 .get(idx as usize)
2814 .copied()
2815 .ok_or_else(|| format_err!(offset, "unknown type {idx}: type index out of bounds"))
2816 }
2817
2818 pub fn component_type_at(&self, idx: u32, offset: usize) -> Result<ComponentAnyTypeId> {
2819 self.types
2820 .get(idx as usize)
2821 .copied()
2822 .ok_or_else(|| format_err!(offset, "unknown type {idx}: type index out of bounds"))
2823 }
2824
2825 fn function_type_at<'a>(
2826 &self,
2827 idx: u32,
2828 types: &'a TypeList,
2829 offset: usize,
2830 ) -> Result<&'a ComponentFuncType> {
2831 let id = self.component_type_at(idx, offset)?;
2832 match id {
2833 ComponentAnyTypeId::Func(id) => Ok(&types[id]),
2834 _ => bail!(offset, "type index {idx} is not a function type"),
2835 }
2836 }
2837
2838 fn function_at(&self, idx: u32, offset: usize) -> Result<ComponentFuncTypeId> {
2839 self.funcs.get(idx as usize).copied().ok_or_else(|| {
2840 format_err!(
2841 offset,
2842 "unknown function {idx}: function index out of bounds"
2843 )
2844 })
2845 }
2846
2847 fn component_at(&self, idx: u32, offset: usize) -> Result<ComponentTypeId> {
2848 self.components.get(idx as usize).copied().ok_or_else(|| {
2849 format_err!(
2850 offset,
2851 "unknown component {idx}: component index out of bounds"
2852 )
2853 })
2854 }
2855
2856 fn instance_at(&self, idx: u32, offset: usize) -> Result<ComponentInstanceTypeId> {
2857 self.instances.get(idx as usize).copied().ok_or_else(|| {
2858 format_err!(
2859 offset,
2860 "unknown instance {idx}: instance index out of bounds"
2861 )
2862 })
2863 }
2864
2865 fn value_at(&mut self, idx: u32, offset: usize) -> Result<&ComponentValType> {
2866 match self.values.get_mut(idx as usize) {
2867 Some((ty, used)) if !*used => {
2868 *used = true;
2869 Ok(ty)
2870 }
2871 Some(_) => bail!(offset, "value {idx} cannot be used more than once"),
2872 None => bail!(offset, "unknown value {idx}: value index out of bounds"),
2873 }
2874 }
2875
2876 fn defined_type_at(&self, idx: u32, offset: usize) -> Result<ComponentDefinedTypeId> {
2877 match self.component_type_at(idx, offset)? {
2878 ComponentAnyTypeId::Defined(id) => Ok(id),
2879 _ => bail!(offset, "type index {idx} is not a defined type"),
2880 }
2881 }
2882
2883 fn core_function_at(&self, idx: u32, offset: usize) -> Result<CoreTypeId> {
2884 match self.core_funcs.get(idx as usize) {
2885 Some(id) => Ok(*id),
2886 None => bail!(
2887 offset,
2888 "unknown core function {idx}: function index out of bounds"
2889 ),
2890 }
2891 }
2892
2893 fn module_at(&self, idx: u32, offset: usize) -> Result<ComponentCoreModuleTypeId> {
2894 match self.core_modules.get(idx as usize) {
2895 Some(id) => Ok(*id),
2896 None => bail!(offset, "unknown module {idx}: module index out of bounds"),
2897 }
2898 }
2899
2900 fn core_instance_at(&self, idx: u32, offset: usize) -> Result<ComponentCoreInstanceTypeId> {
2901 match self.core_instances.get(idx as usize) {
2902 Some(id) => Ok(*id),
2903 None => bail!(
2904 offset,
2905 "unknown core instance {idx}: instance index out of bounds"
2906 ),
2907 }
2908 }
2909
2910 fn core_instance_export<'a>(
2911 &self,
2912 instance_index: u32,
2913 name: &str,
2914 types: &'a TypeList,
2915 offset: usize,
2916 ) -> Result<&'a EntityType> {
2917 match types[self.core_instance_at(instance_index, offset)?]
2918 .internal_exports(types)
2919 .get(name)
2920 {
2921 Some(export) => Ok(export),
2922 None => bail!(
2923 offset,
2924 "core instance {instance_index} has no export named `{name}`"
2925 ),
2926 }
2927 }
2928
2929 fn global_at(&self, idx: u32, offset: usize) -> Result<&GlobalType> {
2930 match self.core_globals.get(idx as usize) {
2931 Some(t) => Ok(t),
2932 None => bail!(offset, "unknown global {idx}: global index out of bounds"),
2933 }
2934 }
2935
2936 fn table_at(&self, idx: u32, offset: usize) -> Result<&TableType> {
2937 match self.core_tables.get(idx as usize) {
2938 Some(t) => Ok(t),
2939 None => bail!(offset, "unknown table {idx}: table index out of bounds"),
2940 }
2941 }
2942
2943 fn memory_at(&self, idx: u32, offset: usize) -> Result<&MemoryType> {
2944 match self.core_memories.get(idx as usize) {
2945 Some(t) => Ok(t),
2946 None => bail!(offset, "unknown memory {idx}: memory index out of bounds"),
2947 }
2948 }
2949
2950 /// Completes the translation of this component, performing final
2951 /// validation of its structure.
2952 ///
2953 /// This method is required to be called for translating all components.
2954 /// Internally this will convert local data structures into a
2955 /// `ComponentType` which is suitable to use to describe the type of this
2956 /// component.
2957 pub fn finish(&mut self, types: &TypeAlloc, offset: usize) -> Result<ComponentType> {
2958 let mut ty = ComponentType {
2959 // Inherit some fields based on translation of the component.
2960 info: self.type_info,
2961 imports: self.imports.clone(),
2962 exports: self.exports.clone(),
2963
2964 // This is filled in as a subset of `self.defined_resources`
2965 // depending on what's actually used by the exports. See the
2966 // bottom of this function.
2967 defined_resources: Default::default(),
2968
2969 // These are inherited directly from what was calculated for this
2970 // component.
2971 imported_resources: mem::take(&mut self.imported_resources)
2972 .into_iter()
2973 .collect(),
2974 explicit_resources: mem::take(&mut self.explicit_resources),
2975 };
2976
2977 // Collect all "free variables", or resources, from the imports of this
2978 // component. None of the resources defined within this component can
2979 // be used as part of the exports. This set is then used to reject any
2980 // of `self.defined_resources` which show up.
2981 let mut free = IndexSet::default();
2982 for ty in ty.imports.values() {
2983 types.free_variables_component_entity(ty, &mut free);
2984 }
2985 for (resource, _path) in self.defined_resources.iter() {
2986 // FIXME: this error message is quite opaque and doesn't indicate
2987 // more contextual information such as:
2988 //
2989 // * what was the exported resource found in the imports
2990 // * which import was the resource found within
2991 //
2992 // These are possible to calculate here if necessary, however.
2993 if free.contains(resource) {
2994 bail!(offset, "local resource type found in imports");
2995 }
2996 }
2997
2998 // The next step in validation a component, with respect to resources,
2999 // is to minimize the set of defined resources to only those that
3000 // are actually used by the exports. This weeds out resources that are
3001 // defined, used within a component, and never exported, for example.
3002 //
3003 // The free variables of all exports are inserted into the `free` set
3004 // (which is reused from the imports after clearing it). The defined
3005 // resources calculated for this component are then inserted into this
3006 // type's list of defined resources if it's contained somewhere in
3007 // the free variables.
3008 //
3009 // Note that at the same time all defined resources must be exported,
3010 // somehow, transitively from this component. The `explicit_resources`
3011 // map is consulted for this purpose which lists all explicitly
3012 // exported resources in the component, regardless from whence they
3013 // came. If not present in this map then it's not exported and an error
3014 // is returned.
3015 //
3016 // NB: the "types are exported" check is probably sufficient nowadays
3017 // that the check of the `explicit_resources` map is probably not
3018 // necessary, but it's left here for completeness and out of an
3019 // abundance of caution.
3020 free.clear();
3021 for ty in ty.exports.values() {
3022 types.free_variables_component_entity(ty, &mut free);
3023 }
3024 for (id, _rep) in mem::take(&mut self.defined_resources) {
3025 if !free.contains(&id) {
3026 continue;
3027 }
3028
3029 let path = match ty.explicit_resources.get(&id).cloned() {
3030 Some(path) => path,
3031 // FIXME: this error message is quite opaque and doesn't
3032 // indicate more contextual information such as:
3033 //
3034 // * which resource wasn't found in an export
3035 // * which export has a reference to the resource
3036 //
3037 // These are possible to calculate here if necessary, however.
3038 None => bail!(
3039 offset,
3040 "local resource type found in export but not exported itself"
3041 ),
3042 };
3043
3044 ty.defined_resources.push((id, path));
3045 }
3046
3047 Ok(ty)
3048 }
3049
3050 fn check_value_support(&self, features: &WasmFeatures, offset: usize) -> Result<()> {
3051 if !features.component_model_values() {
3052 bail!(
3053 offset,
3054 "support for component model `value`s is not enabled"
3055 );
3056 }
3057 Ok(())
3058 }
3059 }
3060
3061 impl InternRecGroup for ComponentState {
3062 fn add_type_id(&mut self, id: CoreTypeId) {
3063 self.core_types.push(ComponentCoreTypeId::Sub(id));
3064 }
3065
3066 fn type_id_at(&self, idx: u32, offset: usize) -> Result<CoreTypeId> {
3067 match self.core_type_at(idx, offset)? {
3068 ComponentCoreTypeId::Sub(id) => Ok(id),
3069 ComponentCoreTypeId::Module(_) => {
3070 bail!(offset, "type index {idx} is a module type, not a sub type");
3071 }
3072 }
3073 }
3074
3075 fn types_len(&self) -> u32 {
3076 u32::try_from(self.core_types.len()).unwrap()
3077 }
3078 }
3079
3080 impl ComponentNameContext {
3081 /// Registers that the resource `id` is named `name` within this context.
3082 fn register(&mut self, name: &str, id: AliasableResourceId) {
3083 let idx = self.all_resource_names.len();
3084 let prev = self.resource_name_map.insert(id, idx);
3085 assert!(
3086 prev.is_none(),
3087 "for {id:?}, inserted {idx:?} but already had {prev:?}"
3088 );
3089 self.all_resource_names.insert(name.to_string());
3090 }
3091
3092 fn validate_extern(
3093 &self,
3094 name: &str,
3095 kind: ExternKind,
3096 ty: &ComponentEntityType,
3097 types: &TypeAlloc,
3098 offset: usize,
3099 kind_names: &mut IndexSet<ComponentName>,
3100 items: &mut IndexMap<String, ComponentEntityType>,
3101 info: &mut TypeInfo,
3102 features: &WasmFeatures,
3103 ) -> Result<()> {
3104 // First validate that `name` is even a valid kebab name, meaning it's
3105 // in kebab-case, is an ID, etc.
3106 let kebab = ComponentName::new_with_features(name, offset, *features)
3107 .with_context(|| format!("{} name `{name}` is not a valid extern name", kind.desc()))?;
3108
3109 if let ExternKind::Export = kind {
3110 match kebab.kind() {
3111 ComponentNameKind::Label(_)
3112 | ComponentNameKind::Method(_)
3113 | ComponentNameKind::Static(_)
3114 | ComponentNameKind::Constructor(_)
3115 | ComponentNameKind::Interface(_) => {}
3116
3117 ComponentNameKind::Hash(_)
3118 | ComponentNameKind::Url(_)
3119 | ComponentNameKind::Dependency(_) => {
3120 bail!(offset, "name `{name}` is not a valid export name")
3121 }
3122 }
3123 }
3124
3125 // Validate that the kebab name, if it has structure such as
3126 // `[method]a.b`, is indeed valid with respect to known resources.
3127 self.validate(&kebab, ty, types, offset)
3128 .with_context(|| format!("{} name `{kebab}` is not valid", kind.desc()))?;
3129
3130 // Top-level kebab-names must all be unique, even between both imports
3131 // and exports ot a component. For those names consult the `kebab_names`
3132 // set.
3133 if let Some(prev) = kind_names.replace(kebab.clone()) {
3134 bail!(
3135 offset,
3136 "{} name `{kebab}` conflicts with previous name `{prev}`",
3137 kind.desc()
3138 );
3139 }
3140
3141 // Otherwise all strings must be unique, regardless of their name, so
3142 // consult the `items` set to ensure that we're not for example
3143 // importing the same interface ID twice.
3144 match items.entry(name.to_string()) {
3145 Entry::Occupied(e) => {
3146 bail!(
3147 offset,
3148 "{kind} name `{name}` conflicts with previous name `{prev}`",
3149 kind = kind.desc(),
3150 prev = e.key(),
3151 );
3152 }
3153 Entry::Vacant(e) => {
3154 e.insert(*ty);
3155 info.combine(ty.info(types), offset)?;
3156 }
3157 }
3158 Ok(())
3159 }
3160
3161 /// Validates that the `name` provided is allowed to have the type `ty`.
3162 fn validate(
3163 &self,
3164 name: &ComponentName,
3165 ty: &ComponentEntityType,
3166 types: &TypeAlloc,
3167 offset: usize,
3168 ) -> Result<()> {
3169 let func = || {
3170 let id = match ty {
3171 ComponentEntityType::Func(id) => *id,
3172 _ => bail!(offset, "item is not a func"),
3173 };
3174 Ok(&types[id])
3175 };
3176 match name.kind() {
3177 // No validation necessary for these styles of names
3178 ComponentNameKind::Label(_)
3179 | ComponentNameKind::Interface(_)
3180 | ComponentNameKind::Url(_)
3181 | ComponentNameKind::Dependency(_)
3182 | ComponentNameKind::Hash(_) => {}
3183
3184 // Constructors must return `(own $resource)` and the `$resource`
3185 // must be named within this context to match `rname`
3186 ComponentNameKind::Constructor(rname) => {
3187 let ty = func()?;
3188 if ty.results.len() != 1 {
3189 bail!(offset, "function should return one value");
3190 }
3191 let ty = ty.results[0].1;
3192 let resource = match ty {
3193 ComponentValType::Primitive(_) => None,
3194 ComponentValType::Type(ty) => match &types[ty] {
3195 ComponentDefinedType::Own(id) => Some(id),
3196 _ => None,
3197 },
3198 };
3199 let resource = match resource {
3200 Some(id) => id,
3201 None => bail!(offset, "function should return `(own $T)`"),
3202 };
3203 self.validate_resource_name(*resource, rname, offset)?;
3204 }
3205
3206 // Methods must take `(param "self" (borrow $resource))` as the
3207 // first argument where `$resources` matches the name `resource` as
3208 // named in this context.
3209 ComponentNameKind::Method(name) => {
3210 let ty = func()?;
3211 if ty.params.len() == 0 {
3212 bail!(offset, "function should have at least one argument");
3213 }
3214 let (pname, pty) = &ty.params[0];
3215 if pname.as_str() != "self" {
3216 bail!(
3217 offset,
3218 "function should have a first argument called `self`",
3219 );
3220 }
3221 let id = match pty {
3222 ComponentValType::Primitive(_) => None,
3223 ComponentValType::Type(ty) => match &types[*ty] {
3224 ComponentDefinedType::Borrow(id) => Some(id),
3225 _ => None,
3226 },
3227 };
3228 let id = match id {
3229 Some(id) => id,
3230 None => bail!(
3231 offset,
3232 "function should take a first argument of `(borrow $T)`"
3233 ),
3234 };
3235 self.validate_resource_name(*id, name.resource(), offset)?;
3236 }
3237
3238 // Static methods don't have much validation beyond that they must
3239 // be a function and the resource name referred to must already be
3240 // in this context.
3241 ComponentNameKind::Static(name) => {
3242 func()?;
3243 if !self.all_resource_names.contains(name.resource().as_str()) {
3244 bail!(offset, "static resource name is not known in this context");
3245 }
3246 }
3247 }
3248
3249 Ok(())
3250 }
3251
3252 fn validate_resource_name(
3253 &self,
3254 id: AliasableResourceId,
3255 name: &KebabStr,
3256 offset: usize,
3257 ) -> Result<()> {
3258 let expected_name_idx = match self.resource_name_map.get(&id) {
3259 Some(idx) => *idx,
3260 None => {
3261 bail!(
3262 offset,
3263 "resource used in function does not have a name in this context"
3264 )
3265 }
3266 };
3267 let expected_name = &self.all_resource_names[expected_name_idx];
3268 if name.as_str() != expected_name {
3269 bail!(
3270 offset,
3271 "function does not match expected \
3272 resource name `{expected_name}`"
3273 );
3274 }
3275 Ok(())
3276 }
3277 }
3278
3279 use self::append_only::*;
3280
3281 mod append_only {
3282 use crate::prelude::IndexMap;
3283 use core::hash::Hash;
3284 use core::ops::Deref;
3285
3286 pub struct IndexMapAppendOnly<K, V>(IndexMap<K, V>);
3287
3288 impl<K, V> IndexMapAppendOnly<K, V>
3289 where
3290 K: Hash + Eq + Ord + PartialEq + Clone,
3291 {
3292 pub fn insert(&mut self, key: K, value: V) {
3293 let prev = self.0.insert(key, value);
3294 assert!(prev.is_none());
3295 }
3296 }
3297
3298 impl<K, V> Deref for IndexMapAppendOnly<K, V> {
3299 type Target = IndexMap<K, V>;
3300 fn deref(&self) -> &IndexMap<K, V> {
3301 &self.0
3302 }
3303 }
3304
3305 impl<K, V> Default for IndexMapAppendOnly<K, V> {
3306 fn default() -> Self {
3307 Self(Default::default())
3308 }
3309 }
3310
3311 impl<K, V> IntoIterator for IndexMapAppendOnly<K, V> {
3312 type IntoIter = <IndexMap<K, V> as IntoIterator>::IntoIter;
3313 type Item = <IndexMap<K, V> as IntoIterator>::Item;
3314 fn into_iter(self) -> Self::IntoIter {
3315 self.0.into_iter()
3316 }
3317 }
3318 }