1use crate::encoding::encode_world;
2use anyhow::{Context, Result};
3use wasm_encoder::{ComponentBuilder, ComponentExportKind, ComponentTypeRef};
4use wasmparser::Validator;
5use wit_parser::{Resolve, WorldId};
6
7/// This function checks whether `component_to_test` correctly conforms to the world specified.
8/// It does so by instantiating a generated component that imports a component instance with
9/// the component type as described by the "target" world.
10pub fn targets(resolve: &Resolve, world: WorldId, component_to_test: &[u8]) -> Result<()> {
11 let mut root_component = ComponentBuilder::default();
12
13 // (1) Embed the component to test.
14 let component_to_test_idx = root_component.component_raw(component_to_test);
15
16 // (2) Encode the world to a component type and embed a new component which
17 // imports the encoded component type.
18 let test_component_idx = {
19 let component_ty = encode_world(resolve, world)?;
20 let mut component = ComponentBuilder::default();
21 let component_ty_idx = component.type_component(&component_ty);
22 component.import(
23 &resolve.worlds[world].name,
24 ComponentTypeRef::Component(component_ty_idx),
25 );
26 root_component.component(component)
27 };
28
29 // (3) Instantiate the component from (2) with the component to test from (1).
30 let args: Vec<(String, ComponentExportKind, u32)> = vec![(
31 resolve.worlds[world].name.clone(),
32 ComponentExportKind::Component,
33 component_to_test_idx,
34 )];
35 root_component.instantiate(test_component_idx, args);
36
37 let bytes = root_component.finish();
38
39 Validator::new()
40 .validate_all(&bytes)
41 .context("failed to validate encoded bytes")?;
42
43 Ok(())
44}
45