/src/wasm-tools/crates/wit-component/src/targets.rs
Line | Count | Source |
1 | | use crate::encoding::encode_world; |
2 | | use anyhow::{Context, Result}; |
3 | | use wasm_encoder::{ComponentBuilder, ComponentExportKind, ComponentTypeRef}; |
4 | | use wasmparser::{Validator, WasmFeatures}; |
5 | | use 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. |
10 | 0 | pub fn targets(resolve: &Resolve, world: WorldId, component_to_test: &[u8]) -> Result<()> { |
11 | 0 | let mut root_component = ComponentBuilder::default(); |
12 | | |
13 | | // (1) Embed the component to test. |
14 | 0 | let component_to_test_idx = root_component.component_raw(None, 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 | 0 | let test_component_idx = { |
19 | 0 | let component_ty = encode_world(resolve, world)?; |
20 | 0 | let mut component = ComponentBuilder::default(); |
21 | 0 | let component_ty_idx = component.type_component(None, &component_ty); |
22 | 0 | component.import( |
23 | 0 | &resolve.worlds[world].name, |
24 | 0 | ComponentTypeRef::Component(component_ty_idx), |
25 | | ); |
26 | 0 | root_component.component(None, component) |
27 | | }; |
28 | | |
29 | | // (3) Instantiate the component from (2) with the component to test from (1). |
30 | 0 | let args: Vec<(String, ComponentExportKind, u32)> = vec![( |
31 | 0 | resolve.worlds[world].name.clone(), |
32 | 0 | ComponentExportKind::Component, |
33 | 0 | component_to_test_idx, |
34 | 0 | )]; |
35 | 0 | root_component.instantiate(None, test_component_idx, args); |
36 | | |
37 | 0 | let bytes = root_component.finish(); |
38 | | |
39 | 0 | Validator::new_with_features(WasmFeatures::all()) |
40 | 0 | .validate_all(&bytes) |
41 | 0 | .context("failed to validate encoded bytes")?; |
42 | | |
43 | 0 | Ok(()) |
44 | 0 | } |