### Defined Resources Examples Source: https://docs.rs/wasmparser/0.246.2/wasmparser/component_types/struct.ComponentInstanceType.html Examples showing how defined_resources are populated in instance types. ```wat (component (type (instance (export "x" (type sub resource)) ;; one `defined_resources` entry )) ) ``` ```wat (component (type $t (instance (export "x" (type sub resource)))) ;; the type of this instance has no defined resources (import "i" (instance (type $t))) ) ``` -------------------------------- ### InstanceSectionReader Example Usage Source: https://docs.rs/wasmparser/0.246.2/wasmparser/type.InstanceSectionReader.html An example demonstrating how to use the InstanceSectionReader to iterate through instances. ```APIDOC ## §Examples ``` use wasmparser::{InstanceSectionReader, BinaryReader}; let reader = BinaryReader::new(data, 0); let mut reader = InstanceSectionReader::new(reader).unwrap(); for inst in reader { println!("Instance {:?}", inst.expect("instance")); } ``` ``` -------------------------------- ### Struct ComponentStartFunction Source: https://docs.rs/wasmparser/0.246.2/wasmparser/struct.ComponentStartFunction.html Represents the start function in a WebAssembly component. ```APIDOC ## Struct ComponentStartFunction ### Description Represents the start function in a WebAssembly component. ### Fields - **func_index** (u32) - Required - The index to the start function. - **arguments** (Box<[u32]>) - Required - The start function arguments. The arguments are specified by value index. - **results** (u32) - Required - The number of expected results for the start function. ### Trait Implementations - **Clone**: Available on `crate feature`component-model` only. Provides `clone` and `clone_from` methods. - **Debug**: Available on `crate feature`component-model` only. Provides `fmt` method for debugging. - **FromReader**: Available on `crate feature`component-model` only. Provides `from_reader` method to read from a binary reader. ### Auto Trait Implementations - Freeze - RefUnwindSafe - Send - Sync - Unpin - UnsafeUnpin - UnwindSafe ### Blanket Implementations - **Any**: Provides `type_id`. - **Borrow**: Provides `borrow`. - **BorrowMut**: Provides `borrow_mut`. - **CloneToUninit**: (Nightly-only experimental API) Provides `clone_to_uninit`. - **From**: Provides `from`. - **Into**: Provides `into`. - **ToOwned**: Provides `to_owned` and `clone_into`. - **TryFrom**: Provides `try_from`. - **TryInto**: Provides `try_into`. ``` -------------------------------- ### Parse WASM Start Section Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/parser.rs.html Parses the Start section of a WASM module. This example shows how to handle different inputs and expected outcomes, including errors and successful parsing. ```rust assert_matches!(parser_after_header().parse(&[], false), Ok(Chunk::NeedMoreData(1))); assert!(parser_after_header().parse(&[8], true).is_err()); assert!(parser_after_header().parse(&[8, 1], true).is_err()); assert!(parser_after_header().parse(&[8, 2], true).is_err()); assert_matches!(parser_after_header().parse(&[8], false), Ok(Chunk::NeedMoreData(1))); assert_matches!(parser_after_header().parse(&[8, 1], false), Ok(Chunk::NeedMoreData(1))); assert_matches!(parser_after_header().parse(&[8, 2], false), Ok(Chunk::NeedMoreData(2))); assert_matches!(parser_after_header().parse(&[8, 1, 1], false), Ok(Chunk::Parsed { consumed: 3, payload: Payload::StartSection { func: 1, .. } })); assert!(parser_after_header().parse(&[8, 2, 1, 1], false).is_err()); assert!(parser_after_header().parse(&[8, 0], false).is_err()); ``` -------------------------------- ### Visit i31 Get Signed Source: https://docs.rs/wasmparser/0.246.2/wasmparser/trait.VisitOperator.html Callback for visiting an i31.get_s instruction. ```rust fn visit_i31_get_s(&mut self) -> Self::Output; ``` -------------------------------- ### Implement VisitOperator with SIMD Support Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/readers/core/operators.rs.html Example of implementing the `VisitOperator` trait, including the `simd_visitor` method to enable support for Wasm SIMD operations. This setup typically involves implementing `VisitSimdOperator` as well. ```rust # macro_rules! define_visit_operator { # ($( @$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => { # $( fn $visit(&mut self $($(,$arg: $argty)*)?) {} )* # } # } # use wasmparser::{VisitOperator, VisitSimdOperator}; pub struct MyVisitor; impl<'a> VisitOperator<'a> for MyVisitor { type Output = (); fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { Some(self) } // implement remaining visitation methods here ... # wasmparser::for_each_visit_operator!(define_visit_operator); } impl VisitSimdOperator<'_> for MyVisitor { // implement SIMD visitation methods here ... # wasmparser::for_each_visit_simd_operator!(define_visit_operator); } ``` -------------------------------- ### Iterate Over Operators with Offsets in a Code Section Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/readers/core/operators.rs.html This example demonstrates how to read WebAssembly code sections and retrieve both the operators and their byte offsets within the section. The BinaryReader should be initialized with the correct data and starting offset. ```rust use wasmparser::{Operator, CodeSectionReader, Result, BinaryReader}; let data: &[u8] = &[ 0x01, 0x03, 0x00, /* offset = 23 */ 0x01, 0x0b]; let reader = BinaryReader::new(data, 20); let code_reader = CodeSectionReader::new(reader).unwrap(); for body in code_reader { let body = body.expect("function body"); let mut op_reader = body.get_operators_reader().expect("op reader"); let ops = op_reader.into_iter_with_offsets().collect::>>().expect("ops"); assert!( if let [(Operator::Nop, 23), (Operator::End, 24)] = ops.as_slice() { true } else { false }, "found {:?}", ops ); } ``` -------------------------------- ### ComponentInstanceSectionReader Usage Source: https://docs.rs/wasmparser/0.246.2/wasmparser/type.ComponentInstanceSectionReader.html Example demonstrating how to use ComponentInstanceSectionReader to iterate over instances in a WebAssembly component. ```APIDOC ## ComponentInstanceSectionReader Usage Example ### Description This example shows how to create a `ComponentInstanceSectionReader` and iterate through its instances. ### Method `new` (constructor) ### Endpoint N/A (This is a Rust library usage example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use wasmparser::{ComponentInstanceSectionReader, BinaryReader}; let data = b"..."; // Replace with actual WebAssembly component data let reader = BinaryReader::new(data, 0); let mut reader = ComponentInstanceSectionReader::new(reader).unwrap(); for inst in reader { println!("Instance {:?}", inst.expect("instance")); } ``` ### Response #### Success Response (200) N/A (This is a Rust library usage example) #### Response Example Output will vary based on the component instances found. ``` -------------------------------- ### ComponentNameKind Url Variant Example Source: https://docs.rs/wasmparser/0.246.2/wasmparser/names/enum.ComponentNameKind.html Represents a name specified as a URL. ```text `url=https://...` ``` -------------------------------- ### wasmparser Crate Overview Source: https://docs.rs/wasmparser/0.246.2/wasmparser/index.html Overview of the wasmparser crate, its purpose, and how to get started. ```APIDOC ## Crate wasmparser ### Summary A simple event-driven library for parsing WebAssembly binary files (or streams). The parser library reports events as they happen and only stores parsing information for a brief period of time, making it very fast and memory-efficient. The event-driven model, however, has some drawbacks. If you need random access to the entire WebAssembly data-structure, this is not the right library for you. You could however, build such a data-structure using this library. To get started, create a `Parser` using `Parser::new` and then follow the examples documented for `Parser::parse` or `Parser::parse_all`. ``` -------------------------------- ### POST /parser/new Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/parser.rs.html Initializes a new instance of the WebAssembly parser with a specified logical offset. ```APIDOC ## POST /parser/new ### Description Creates a new parser instance. Reports errors and ranges relative to the provided offset, which represents a logical offset within the input stream. ### Method POST ### Endpoint /parser/new ### Parameters #### Request Body - **offset** (u64) - Required - The logical offset within the input stream to start parsing from. ### Response #### Success Response (200) - **parser** (Object) - The initialized Parser instance. ``` -------------------------------- ### Iterate over instance section Source: https://docs.rs/wasmparser/0.246.2/wasmparser/type.InstanceSectionReader.html Example showing how to initialize a reader and iterate through instances in a WebAssembly component section. ```rust use wasmparser::{InstanceSectionReader, BinaryReader}; let reader = BinaryReader::new(data, 0); let mut reader = InstanceSectionReader::new(reader).unwrap(); for inst in reader { println!("Instance {:?}", inst.expect("instance")); } ``` -------------------------------- ### Get Original Position Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/readers/core/operators.rs.html Retrieves the original starting position of the reader within the binary. ```rust pub fn original_position(&self) -> usize { self.reader.original_position() } ``` -------------------------------- ### Struct Instructions Source: https://docs.rs/wasmparser/0.246.2/wasmparser/enum.Operator.html Instructions for creating and accessing struct instances. ```APIDOC ## Struct Instructions ### StructNewDesc ### Description Represents an instruction to create a new struct instance with specified fields. ### Method N/A (Instruction within Wasm module) ### Endpoint N/A ### Parameters #### Request Body - **struct_type_index** (u32) - Required - The index of the struct type. ### StructNewDefaultDesc ### Description Represents an instruction to create a new struct instance with default field values. ### Method N/A (Instruction within Wasm module) ### Endpoint N/A ### Parameters #### Request Body - **struct_type_index** (u32) - Required - The index of the struct type. ### RefGetDesc ### Description Represents an instruction to get a reference to a struct field. ### Method N/A (Instruction within Wasm module) ### Endpoint N/A ### Parameters #### Request Body - **type_index** (u32) - Required - The index of the struct type. ### RefCastDescEqNonNull ### Description Represents an instruction to cast a reference to a non-null struct type. ### Method N/A (Instruction within Wasm module) ### Endpoint N/A ### Parameters #### Request Body - **hty** (HeapType) - Required - The target heap type for the cast. ### RefCastDescEqNullable ### Description Represents an instruction to cast a reference to a nullable struct type. ### Method N/A (Instruction within Wasm module) ### Endpoint N/A ### Parameters #### Request Body - **hty** (HeapType) - Required - The target heap type for the cast. ### BrOnCastDescEq ### Description Represents an instruction to branch based on the result of a struct type cast. ### Method N/A (Instruction within Wasm module) ### Endpoint N/A ### Parameters #### Request Body - **relative_depth** (u32) - Required - The relative depth to branch to. - **from_ref_type** (RefType) - Required - The source reference type. - **to_ref_type** (RefType) - Required - The target reference type. ### BrOnCastDescEqFail ### Description Represents an instruction to branch if a struct type cast fails. ### Method N/A (Instruction within Wasm module) ### Endpoint N/A ### Parameters #### Request Body - **relative_depth** (u32) - Required - The relative depth to branch to. - **from_ref_type** (RefType) - Required - The source reference type. - **to_ref_type** (RefType) - Required - The target reference type. ``` -------------------------------- ### Get Original Position - LocalsReader Source: https://docs.rs/wasmparser/0.246.2/wasmparser/struct.LocalsReader.html Returns the starting byte position of the locals reader within the original binary data. This can be useful for debugging or analysis. ```rust pub fn original_position(&self) -> usize ``` -------------------------------- ### Get Function Body Range Source: https://docs.rs/wasmparser/0.246.2/wasmparser/struct.FunctionBody.html Returns the byte range (start and end indices) of the function body within the WebAssembly module's binary data. ```rust pub fn range(&self) -> Range ``` -------------------------------- ### Visit Struct Creation Instructions Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator/operators.rs.html Handles struct instantiation, including default values and descriptor-based initialization. ```rust fn visit_struct_new_default(&mut self, type_index: u32) -> Self::Output { if let Some(_) = self.sub_type_at(type_index)?.composite_type.descriptor_idx { bail!( self.offset, "type with descriptor requires descriptor allocation: `struct.new_default` with type {type_index}" ); } let ty = self.struct_type_at(type_index)?; for field in ty.fields.iter() { let val_ty = field.element_type.unpack(); if !val_ty.is_defaultable() { bail!( self.offset, "invalid `struct.new_default`: {val_ty} field is not defaultable" ); } } self.push_exact_ref_if_available(false, type_index)?; Ok(()) } ``` ```rust fn visit_struct_new_desc(&mut self, struct_type_index: u32) -> Self::Output { if let Some(descriptor_idx) = self .sub_type_at(struct_type_index)? .composite_type .descriptor_idx { let ty = ValType::Ref(RefType::exact(true, descriptor_idx)); self.pop_operand(Some(ty))?; } else { bail!( self.offset, "invalid `struct.new_desc`: type {struct_type_index} is not described" ); } let struct_ty = self.struct_type_at(struct_type_index)?; for ty in struct_ty.fields.iter().rev() { self.pop_operand(Some(ty.element_type.unpack()))?; } self.push_exact_ref_if_available(false, struct_type_index)?; Ok(()) } ``` ```rust fn visit_struct_new_default_desc(&mut self, type_index: u32) -> Self::Output { if let Some(descriptor_idx) = self.sub_type_at(type_index)?.composite_type.descriptor_idx { let ty = ValType::Ref(RefType::exact(true, descriptor_idx)); self.pop_operand(Some(ty))?; } else { bail!( self.offset, "invalid `struct.new_default_desc`: type {type_index} is not described" ); } let ty = self.struct_type_at(type_index)?; for field in ty.fields.iter() { let val_ty = field.element_type.unpack(); if !val_ty.is_defaultable() { bail!( self.offset, "invalid `struct.new_default`: {val_ty} field is not defaultable" ); } } self.push_exact_ref_if_available(false, type_index)?; Ok(()) } ``` -------------------------------- ### Get Range of Original Offset Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/binary_reader.rs.html Returns a `Range` representing the start offset to the end of the buffer. Useful for determining the full extent of the data being read. ```rust pub fn range(&self) -> Range { self.original_offset..self.original_offset + self.buffer.len() } ``` -------------------------------- ### ComponentNameKind Interface Variant Example Source: https://docs.rs/wasmparser/0.246.2/wasmparser/names/enum.ComponentNameKind.html Represents an interface name, following the format 'name/path@version'. ```text `wasi:http/types@2.0` ``` -------------------------------- ### Visitor Methods for WebAssembly Instructions Source: https://docs.rs/wasmparser/0.246.2/wasmparser/trait.VisitOperator.html This section lists the visitor methods for handling various WebAssembly instructions, including typed selects, references, tables, and return calls. ```APIDOC ## Visitor Methods for WebAssembly Instructions ### Description This section details visitor methods for handling various WebAssembly instructions. ### Methods #### `visit_typed_select_multi` - **Description**: Visits a typed select instruction with multiple types. - **Parameters**: `tys` (Vec) - A vector of value types. #### `visit_ref_null` - **Description**: Visits a `ref.null` instruction. - **Parameters**: `hty` (HeapType) - The heap type for the null reference. #### `visit_ref_is_null` - **Description**: Visits a `ref.is_null` instruction. #### `visit_ref_func` - **Description**: Visits a `ref.func` instruction. - **Parameters**: `function_index` (u32) - The index of the function. #### `visit_table_fill` - **Description**: Visits a `table.fill` instruction. - **Parameters**: `table` (u32) - The index of the table. #### `visit_table_get` - **Description**: Visits a `table.get` instruction. - **Parameters**: `table` (u32) - The index of the table. #### `visit_table_set` - **Description**: Visits a `table.set` instruction. - **Parameters**: `table` (u32) - The index of the table. #### `visit_table_grow` - **Description**: Visits a `table.grow` instruction. - **Parameters**: `table` (u32) - The index of the table. #### `visit_table_size` - **Description**: Visits a `table.size` instruction. - **Parameters**: `table` (u32) - The index of the table. #### `visit_return_call` - **Description**: Visits a `return_call` instruction. - **Parameters**: `function_index` (u32) - The index of the function. #### `visit_return_call_indirect` - **Description**: Visits a `return_call_indirect` instruction. - **Parameters**: - `type_index` (u32) - The index of the function type. - `table_index` (u32) - The index of the table. #### `visit_memory_discard` - **Description**: Visits a `memory.discard` instruction. - **Parameters**: `mem` (u32) - The index of the memory. #### `visit_memory_atomic_notify` - **Description**: Visits a `memory.atomic.notify` instruction. - **Parameters**: `memarg` (MemArg) - The memory access arguments. #### `visit_memory_atomic_wait32` - **Description**: Visits a `memory.atomic.wait32` instruction. - **Parameters**: `memarg` (MemArg) - The memory access arguments. #### `visit_memory_atomic_wait64` - **Description**: Visits a `memory.atomic.wait64` instruction. - **Parameters**: `memarg` (MemArg) - The memory access arguments. #### `visit_atomic_fence` - **Description**: Visits an `atomic.fence` instruction. ``` -------------------------------- ### Parser Struct and Initialization Source: https://docs.rs/wasmparser/0.246.2/wasmparser/struct.Parser.html Documentation for the `Parser` struct, its purpose, and how to create a new instance. ```APIDOC ## Struct Parser ### Description An incremental parser of a binary WebAssembly module or component. This type is intended to be used to incrementally parse a WebAssembly module or component as bytes become available for the module. This can also be used to parse modules or components that are already entirely resident within memory. This primary function for a parser is the `Parser::parse` function which will incrementally consume input. You can also use the `Parser::parse_all` function to parse a module or component that is entirely resident in memory. ## impl Parser ### pub fn new(offset: u64) -> Parser Creates a new parser. Reports errors and ranges relative to `offset` provided, where `offset` is some logical offset within the input stream that we’re parsing. ``` -------------------------------- ### Parser Initialization Source: https://docs.rs/wasmparser/0.246.2/index.html How to initialize the Parser for processing WebAssembly binary data. ```APIDOC ## Parser::new ### Description Creates a new instance of the `Parser` to begin processing a WebAssembly binary stream. ### Method Constructor ### Usage ```rust use wasmparser::Parser; let parser = Parser::new(0); // Initialize with offset ``` ``` -------------------------------- ### Visit Table Init Source: https://docs.rs/wasmparser/0.246.2/wasmparser/trait.VisitOperator.html Callback for visiting a table.init instruction, specifying element index and table index. ```rust fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output; ``` -------------------------------- ### Get TypeId of a Type Source: https://docs.rs/wasmparser/0.246.2/wasmparser/collections/map/struct.IntoKeys.html Gets the `TypeId` of `self`. This is useful for runtime type identification. ```rust fn type_id(&self) -> TypeId Source§ ``` -------------------------------- ### ComponentStartFunction Structure Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/readers/component/start.rs.html Represents the start function in a WebAssembly component, containing the function index, arguments, and result count. ```APIDOC ## ComponentStartFunction ### Description Represents the start function in a WebAssembly component, providing access to the function index, arguments, and result count. ### Fields - **func_index** (u32) - The index to the start function. - **arguments** (Box<[u32]>) - The start function arguments, specified by value index. - **results** (u32) - The number of expected results for the start function. ### Implementation - **FromReader<'a>** - Implements deserialization from a `BinaryReader`. ``` -------------------------------- ### start_section Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator.rs.html Validates the Start section of a Wasm module, ensuring the start function has no parameters or results. ```APIDOC ## start_section ### Description Validates the Start section of a Wasm module. It ensures the specified start function exists and has a signature with no parameters and no results. ### Parameters - **func** (u32) - Required - The index of the start function. - **range** (Range) - Required - The byte range of the section. ``` -------------------------------- ### Example: Dumping Operators with Offsets Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/readers/core/operators.rs.html Demonstrates how to iterate through operators, record their original positions, and visit them using a custom visitor. ```rust # use wasmparser::{OperatorsReader, VisitOperator, Result, for_each_visit_operator}; pub fn dump(mut reader: OperatorsReader) -> Result<()> { let mut visitor = Dumper { offset: 0 }; while !reader.eof() { visitor.offset = reader.original_position(); reader.visit_operator(&mut visitor)?; } Ok(()) } struct Dumper { offset: usize } macro_rules! define_visit_operator { ($(@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => { $( fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output { println!("{}: {}", self.offset, stringify!($visit)); } )* } } impl<'a> VisitOperator<'a> for Dumper { type Output = (); for_each_visit_operator!(define_visit_operator); } ``` -------------------------------- ### ProducersSectionReader Usage Example Source: https://docs.rs/wasmparser/0.246.2/wasmparser/type.ProducersSectionReader.html Example demonstrating how to create and use the ProducersSectionReader to parse the producers custom section. ```APIDOC ## ProducersSectionReader Usage Example ### Description This example shows how to initialize a `ProducersSectionReader` and iterate through its fields to access producer information like language and version. ### Method N/A (Illustrative Example) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```rust let reader = BinaryReader::new(data, 0); let reader = ProducersSectionReader::new(reader).expect("producers reader"); let field = reader.into_iter().next().unwrap().expect("producers field"); assert!(field.name == "language"); let value = field.values.into_iter().collect::>>().expect("values"); assert!(value.len() == 2); assert!(value[0].name == "wat" && value[0].version == "1"); assert!(value[1].name == "C" && value[1].version == "9.0"); ``` ``` -------------------------------- ### Validate Start Section Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator.rs.html Validates the start section of a WebAssembly module, ensuring the specified function has no parameters or results. ```rust pub fn start_section(&mut self, func: u32, range: &Range) -> Result<()> { let offset = range.start; self.state.ensure_module("start", offset)?; let state = self.module.as_mut().unwrap(); let ty = state.module.get_func_type(func, &self.types, offset)?; if !ty.params().is_empty() || !ty.results().is_empty() { return Err(BinaryReaderError::new( "invalid start function type", offset, )); } Ok(()) } ``` -------------------------------- ### Example: Validating a Function Body using Visitor Source: https://docs.rs/wasmparser/0.246.2/wasmparser/struct.FuncValidator.html Demonstrates how to iterate through operators of a function body using `get_binary_reader_for_operators` and the `validator.visitor` method to validate each operator. ```rust pub fn validate(validator: &mut FuncValidator, body: &FunctionBody<'_>) -> Result<()> where R: WasmModuleResources { let mut operator_reader = body.get_binary_reader_for_operators()?; while !operator_reader.eof() { let mut visitor = validator.visitor(operator_reader.original_position()); operator_reader.visit_operator(&mut visitor)?; } operator_reader.finish_expression(&validator.visitor(operator_reader.original_position())) } ``` -------------------------------- ### Table Atomic Get and Set Validation Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator/operators.rs.html Validates that table atomic get and set operations are performed on subtypes of anyref. ```rust fn visit_table_atomic_get(&mut self, _ordering: Ordering, table: u32) -> Self::Output { self.visit_table_get(table)?; // No validation of `ordering` is needed because `table.atomic.get` can // be used on both shared and unshared tables. But we do need to limit // which types can be used with this instruction. let ty = self.table_type_at(table)?.element_type; let supertype = RefType::ANYREF.shared().unwrap(); if !self.resources.is_subtype(ty.into(), supertype.into()) { bail!( self.offset, "invalid type: `table.atomic.get` only allows subtypes of `anyref`" ); } Ok(()) } ``` ```rust fn visit_table_atomic_set(&mut self, _ordering: Ordering, table: u32) -> Self::Output { self.visit_table_set(table)?; // No validation of `ordering` is needed because `table.atomic.set` can // be used on both shared and unshared tables. But we do need to limit // which types can be used with this instruction. let ty = self.table_type_at(table)?.element_type; let supertype = RefType::ANYREF.shared().unwrap(); if !self.resources.is_subtype(ty.into(), supertype.into()) { bail!( self.offset, "invalid type: `table.atomic.set` only allows subtypes of `anyref`" ); } Ok(()) } ``` -------------------------------- ### Trim start of strings Source: https://docs.rs/wasmparser/0.246.2/wasmparser/names/struct.KebabString.html Removes leading whitespace. Note that 'start' refers to the first byte position, which varies by text directionality. ```rust let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld\t\n", s.trim_start()); ``` ```rust let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` -------------------------------- ### SIMD Visitor Methods Source: https://docs.rs/wasmparser/0.246.2/wasmparser/trait.VisitSimdOperator.html A collection of visitor methods for processing WebAssembly SIMD instructions. ```APIDOC ## SIMD Visitor Methods ### Description These methods are part of the visitor pattern for processing WebAssembly SIMD instructions, including relaxed SIMD, conversions, and lane operations. ### Methods - visit_f64x2_max - visit_f64x2_pmin - visit_f64x2_pmax - visit_i32x4_trunc_sat_f32x4_s - visit_i32x4_trunc_sat_f32x4_u - visit_f32x4_convert_i32x4_s - visit_f32x4_convert_i32x4_u - visit_i32x4_trunc_sat_f64x2_s_zero - visit_i32x4_trunc_sat_f64x2_u_zero - visit_f64x2_convert_low_i32x4_s - visit_f64x2_convert_low_i32x4_u - visit_f32x4_demote_f64x2_zero - visit_f64x2_promote_low_f32x4 - visit_i8x16_relaxed_swizzle - visit_i32x4_relaxed_trunc_f32x4_s - visit_i32x4_relaxed_trunc_f32x4_u - visit_i32x4_relaxed_trunc_f64x2_s_zero - visit_i32x4_relaxed_trunc_f64x2_u_zero - visit_f32x4_relaxed_madd - visit_f32x4_relaxed_nmadd - visit_f64x2_relaxed_madd - visit_f64x2_relaxed_nmadd - visit_i8x16_relaxed_laneselect - visit_i16x8_relaxed_laneselect - visit_i32x4_relaxed_laneselect - visit_i64x2_relaxed_laneselect - visit_f32x4_relaxed_min - visit_f32x4_relaxed_max - visit_f64x2_relaxed_min - visit_f64x2_relaxed_max - visit_i16x8_relaxed_q15mulr_s - visit_i16x8_relaxed_dot_i8x16_i7x16_s - visit_i32x4_relaxed_dot_i8x16_i7x16_add_s ``` -------------------------------- ### BinaryReader Initialization Source: https://docs.rs/wasmparser/0.246.2/wasmparser/struct.BinaryReader.html Methods to create a new BinaryReader instance. ```APIDOC ## BinaryReader::new ### Description Creates a new binary reader which will parse the provided data. ### Parameters #### Arguments - **data** (&[u8]) - Required - The binary data to parse. - **original_offset** (usize) - Required - The offset added to the current position in data for error reporting. ## BinaryReader::new_features ### Description Creates a new binary reader with specific WebAssembly features enabled. ### Parameters #### Arguments - **data** (&[u8]) - Required - The binary data to parse. - **original_offset** (usize) - Required - The offset added to the current position in data for error reporting. - **features** (WasmFeatures) - Required - The set of active WebAssembly features. ``` -------------------------------- ### Visit Array Atomic Get Unsigned in Rust Source: https://docs.rs/wasmparser/0.246.2/wasmparser/trait.VisitOperator.html Visits an atomic get operation on an array, specifying ordering and array type index. ```rust fn visit_array_atomic_get_u( &mut self, ordering: Ordering, array_type_index: u32, ) -> Self::Output ``` -------------------------------- ### Read Array Atomic GET Operation Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/binary_reader.rs.html Reads and visits an array atomic GET operation. Requires reading the ordering and a 32-bit unsigned integer. ```rust 0x67 => visitor.visit_array_atomic_get(self.read_ordering()?, self.read_var_u32()?) ``` -------------------------------- ### Instantiate and Iterate CoreTypeSectionReader Source: https://docs.rs/wasmparser/0.246.2/wasmparser/type.CoreTypeSectionReader.html Demonstrates how to create a BinaryReader, initialize a CoreTypeSectionReader, and iterate over its types. Ensure the data is valid WebAssembly binary. ```rust use wasmparser::{CoreTypeSectionReader, BinaryReader}; let reader = BinaryReader::new(data, 0); let mut reader = CoreTypeSectionReader::new(reader).unwrap(); for ty in reader { println!("Type {:?}", ty.expect("type")); } ``` -------------------------------- ### Initialize Module Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator/core.rs.html Creates a new Module instance with default values and specified WasmFeatures. ```rust impl Module { pub fn new(features: WasmFeatures) -> Self { Self { snapshot: Default::default(), types: Default::default(), tables: Default::default(), memories: Default::default(), globals: Default::default(), element_types: Default::default(), data_count: Default::default(), functions: Default::default(), tags: Default::default(), function_references: Default::default(), exact_function_imports: Default::default(), imports: Default::default(), exports: Default::default(), type_size: 1, num_imported_globals: Default::default(), num_imported_functions: Default::default(), features, } } ``` -------------------------------- ### Get Subtyping Depth Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator/types.rs.html Gets the subtyping depth of a given type ID. Types without a supertype have a depth of 0. Panics if the type list has been committed. ```rust /// Get the subtyping depth of the given type. A type without any supertype /// has depth 0. pub fn get_subtyping_depth(&self, id: CoreTypeId) -> u8 { let depth = self .core_type_to_depth .as_ref() .expect("cannot get subtype depth from a committed list")[&id]; debug_assert!(usize::from(depth) <= crate::limits::MAX_WASM_SUBTYPING_DEPTH); depth } ``` -------------------------------- ### IndexMap Initialization Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/collections/index_map/detail.rs.html Methods for creating new IndexMap instances. ```APIDOC ## IndexMap::new() ### Description Creates a new, empty [`IndexMap`]. Does not allocate anything on its own. ### Method `new()` ### Endpoint N/A (Constructor) ### Request Example ```rust let map: IndexMap = IndexMap::new(); ``` ### Response Example An empty `IndexMap`. ``` ```APIDOC ## IndexMap::with_capacity(capacity: usize) ### Description Constructs a new, empty [`IndexMap`] with at least the specified capacity. Does not allocate if `capacity` is zero. ### Method `with_capacity(capacity: usize)` ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let mut map: IndexMap = IndexMap::with_capacity(10); ``` ### Response Example An empty `IndexMap` with pre-allocated capacity. ``` -------------------------------- ### Trim starting patterns from string slices Source: https://docs.rs/wasmparser/0.246.2/wasmparser/names/struct.KebabString.html Removes all leading occurrences of a pattern. Note that 'start' refers to the beginning of the byte sequence, which depends on text directionality. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Visit Return Instruction Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/binary_reader.rs.html Handles the 'return' instruction. ```rust 0x0f => visitor.visit_return(), ``` -------------------------------- ### Read Array Atomic GET Unsigned Operation Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/binary_reader.rs.html Reads and visits an array atomic GET (unsigned) operation. Requires reading the ordering and a 32-bit unsigned integer. ```rust 0x69 => visitor.visit_array_atomic_get_u(self.read_ordering()?, self.read_var_u32()?) ``` -------------------------------- ### WASM Parser Test Setup Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator.rs.html Sets up a test case for WASM module type information using the 'wat' crate to parse string literals into WASM bytes. ```rust #[cfg(test)] mod tests { use crate::{GlobalType, MemoryType, RefType, TableType, ValType, Validator, WasmFeatures}; use anyhow::Result; #[test] fn test_module_type_information() -> Result<()> { let bytes = wat::parse_str( r#"( (module ``` -------------------------------- ### Read Array Atomic GET Signed Operation Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/binary_reader.rs.html Reads and visits an array atomic GET (signed) operation. Requires reading the ordering and a 32-bit unsigned integer. ```rust 0x68 => visitor.visit_array_atomic_get_s(self.read_ordering()?, self.read_var_u32()?) ``` -------------------------------- ### Get Tag Type by Index Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator/core.rs.html Retrieves the `FuncType` associated with a tag index. It first gets the type ID of the tag and then looks up the corresponding `FuncType` in the provided `TypeList`. ```rust fn tag_at(&self, at: u32) -> Option<&FuncType> { let type_id = *self.module.tags.get(at as usize)?; Some(self.types[type_id].unwrap_func()) } ``` -------------------------------- ### Initialize Component Export Instantiation Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/validator/component.rs.html Sets up the initial state for instantiating component exports, including type information and resource maps. ```rust fn instantiate_component_exports( &mut self, exports: Vec, types: &mut TypeAlloc, offset: usize, ) -> Result { let mut info = TypeInfo::new(); let mut inst_exports = IndexMap::default(); let mut explicit_resources = IndexMap::default(); ``` -------------------------------- ### WasmFeatures Usage Example Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/features.rs.html This example shows how to use the `define_wasm_features` macro to create a `WasmFeatures` struct. The struct controls the set of WebAssembly proposals and features active during validation and parsing. The default implementation includes features at Phase 4 or above. ```rust define_wasm_features! { /// Flags for features that are enabled for validation. /// /// This type controls the set of WebAssembly proposals and features that /// are active during validation and parsing of WebAssembly binaries. This /// is used in conjunction with /// [`Validator::new_with_features`](crate::Validator::new_with_features) /// for example. /// /// The [`Default`] implementation for this structure returns the set of /// supported WebAssembly proposals this crate implements. All features are /// required to be in Phase 4 or above in the WebAssembly standardization /// process. /// /// Enabled/disabled features can affect both parsing and validation at this /// time. When decoding a WebAssembly binary it's generally recommended if /// possible to enable all features, as is the default with pub struct WasmFeatures: u32 { /// The Bulk Memory Operations proposal is specified in /// https://github.com/WebAssembly/bulk-memory-operations/blob/master/proposals/bulk-memory-operations.md pub bulk_memory: WasmBulkMemoryFeatures = true; /// The `reference-types` proposal is specified in /// https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types.md pub reference_types: WasmReferenceTypesFeatures = true; /// The `multi-value` proposal is specified in /// https://github.com/WebAssembly/multi-value/blob/master/proposals/multi-value.md pub multi_value: WasmMultiValueFeatures = true; /// The `module-linking` proposal is specified in /// https://github.com/WebAssembly/module-linking/blob/master/proposals/module-linking.md pub module_linking: WasmModuleLinkingFeatures = true; /// The `tail-call` proposal is specified in /// https://github.com/WebAssembly/tail-call/blob/master/proposals/tail-call.md pub tail_call: WasmTailCallFeatures = true; /// The `extended-const` proposal is specified in /// https://github.com/WebAssembly/extended-const/blob/master/proposals/extended-const.md pub extended_const: WasmExtendedConstFeatures = true; /// The `component-model` proposal is specified in /// https://github.com/WebAssembly/component-model/blob/master/proposals/component-model.md pub component_model: WasmComponentModelFeatures = true; /// The `gc` proposal is specified in /// https://github.com/WebAssembly/gc/blob/master/proposals/gc.md pub gc: WasmGcFeatures = true; /// The `memory64` proposal is specified in /// https://github.com/WebAssembly/memory64/blob/master/proposals/memory64.md pub memory64: WasmMemory64Features = true; /// The `typed-function-references` proposal is specified in /// https://github.com/WebAssembly/typed-function-references/blob/master/proposals/typed-function-references.md pub typed_function_references: WasmTypedFunctionReferencesFeatures = true; /// The `relaxed-simd` proposal is specified in /// https://github.com/WebAssembly/relaxed-simd/blob/master/proposals/relaxed-simd.md pub relaxed_simd: WasmRelaxedSimdFeatures = true; /// The `wasm-threads` proposal is specified in /// https://github.com/WebAssembly/threads/blob/master/proposals/threads.md pub threads: WasmThreadsFeatures = true; /// The `mutable-global` proposal is specified in /// https://github.com/WebAssembly/mutable-global/blob/master/proposals/mutable-global.md pub mutable_global: WasmMutableGlobalFeatures = true; /// The `sign-extension` proposal is specified in /// https://github.com/WebAssembly/sign-extension/blob/master/proposals/sign-extension.md pub sign_extension: WasmSignExtensionFeatures = true; /// The `nontrapping-fptoint` proposal is specified in /// https://github.com/WebAssembly/nontrapping-fptoint/blob/master/proposals/nontrapping-fptoint.md pub nontrapping_fptoint: WasmNontrappingFpToIntFeatures = true; /// The `simd` proposal is specified in /// https://github.com/WebAssembly/simd/blob/master/proposals/simd.md pub simd: WasmSimdFeatures = true; /// The `multi-memory` proposal is specified in /// https://github.com/WebAssembly/multi-memory/blob/master/proposals/multi-memory.md pub multi_memory: WasmMultiMemoryFeatures = true; /// The `memory-control` proposal is specified in /// https://github.com/WebAssembly/memory-control/blob/master/proposals/memory-control.md pub memory_control: WasmMemoryControlFeatures = true; /// The `exception-handling` proposal is specified in /// https://github.com/WebAssembly/exception-handling/blob/master/proposals/exception-handling.md pub exception_handling: WasmExceptionHandlingFeatures = true; /// The `tail-call` proposal is specified in /// https://github.com/WebAssembly/tail-call/blob/master/proposals/tail-call.md pub tail_call_anyref: WasmTailCallAnyrefFeatures = true; /// The `new- கட்டு` proposal is specified in /// https://github.com/WebAssembly/new- கட்டு/blob/master/proposals/new- கட்டு.md pub new_ கட்டு: WasmNew கட்டுFeatures = true; /// The `all` feature flag enables all features. pub all: WasmAllFeatures = true; } } ``` -------------------------------- ### Implement Parser Initialization and Validation Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/parser.rs.html Methods for creating a new Parser instance and checking if byte slices represent valid WebAssembly modules. ```rust impl Parser { /// Creates a new parser. /// /// Reports errors and ranges relative to `offset` provided, where `offset` /// is some logical offset within the input stream that we're parsing. pub fn new(offset: u64) -> Parser { Parser { state: State::Header, offset, max_size: u64::MAX, // Assume the encoding is a module until we know otherwise encoding: Encoding::Module, #[cfg(feature = "features")] features: WasmFeatures::all(), counts: ParserCounts::default(), order: (Order::default(), offset), } } /// Tests whether `bytes` looks like a core WebAssembly module. /// /// This will inspect the first 8 bytes of `bytes` and return `true` if it /// starts with the standard core WebAssembly header. pub fn is_core_wasm(bytes: &[u8]) -> bool { const HEADER: [u8; 8] = [ WASM_MAGIC_NUMBER[0], WASM_MAGIC_NUMBER[1], WASM_MAGIC_NUMBER[2], WASM_MAGIC_NUMBER[3], WASM_MODULE_VERSION.to_le_bytes()[0], WASM_MODULE_VERSION.to_le_bytes()[1], KIND_MODULE.to_le_bytes()[0], KIND_MODULE.to_le_bytes()[1], ]; bytes.starts_with(&HEADER) } ``` -------------------------------- ### Initialize and Iterate ProducersSectionReader Source: https://docs.rs/wasmparser/0.246.2/wasmparser/type.ProducersSectionReader.html Demonstrates how to create a ProducersSectionReader from binary data and iterate through its fields. Asserts expected field names and values. ```rust let reader = BinaryReader::new(data, 0); let reader = ProducersSectionReader::new(reader).expect("producers reader"); let field = reader.into_iter().next().unwrap().expect("producers field"); assert!(field.name == "language"); let value = field.values.into_iter().collect::>>().expect("values"); assert!(value.len() == 2); assert!(value[0].name == "wat" && value[0].version == "1"); assert!(value[1].name == "C" && value[1].version == "9.0"); ``` -------------------------------- ### Function Type ID Source: https://docs.rs/wasmparser/0.246.2/src/wasmparser/resources.rs.html Get the CoreTypeId of a function. ```APIDOC ## GET /wasm/functions/{func_idx}/type_id ### Description Retrieves the `CoreTypeId` associated with the function at the given index. ### Method GET ### Endpoint `/wasm/functions/{func_idx}/type_id` ### Parameters #### Path Parameters - **func_idx** (u32) - Required - The index of the function. ### Response #### Success Response (200) - **CoreTypeId** (object) - The `CoreTypeId` of the function. #### Response Example ```json { "type_id": "Some(CoreTypeId { ... })" } ``` ```