Skip to main content

wasmedge_types/
lib.rs

1#![doc(
2    html_logo_url = "https://github.com/cncf/artwork/blob/master/projects/wasm-edge-runtime/icon/color/wasm-edge-runtime-icon-color.png?raw=true",
3    html_favicon_url = "https://raw.githubusercontent.com/cncf/artwork/49169bdbc88a7ce3c4a722c641cc2d548bd5c340/projects/wasm-edge-runtime/icon/color/wasm-edge-runtime-icon-color.svg"
4)]
5
6//! The [wasmedge-types](https://crates.io/crates/wasmedge-types) crate defines a group of common data structures used by both [wasmedge-sdk](https://crates.io/crates/wasmedge-sdk) and [wasmedge-sys](https://crates.io/crates/wasmedge-sys) crates.
7//!
8//! See also
9//!
10//! * [WasmEdge Runtime](https://wasmedge.org/)
11
12pub mod error;
13
14/// Defines WasmEdge reference types.
15#[derive(Debug, Copy, Clone, Eq, PartialEq)]
16pub enum RefType {
17    /// Refers to the infinite union of all references to host functions, regardless of their function types.
18    FuncRef,
19
20    /// Refers to the infinite union of all references to objects and that can be passed into WebAssembly under this type.
21    ExternRef,
22}
23
24impl From<ValType> for RefType {
25    fn from(value: ValType) -> Self {
26        match value {
27            ValType::FuncRef => RefType::FuncRef,
28            ValType::ExternRef => RefType::ExternRef,
29            _ => panic!("[wasmedge-types] Invalid WasmEdge_RefType: {value:#X?}"),
30        }
31    }
32}
33
34impl From<RefType> for ValType {
35    fn from(value: RefType) -> Self {
36        match value {
37            RefType::FuncRef => ValType::FuncRef,
38            RefType::ExternRef => ValType::ExternRef,
39        }
40    }
41}
42
43/// Defines WasmEdge value types.
44#[derive(Debug, Copy, Clone, Eq, PartialEq)]
45pub enum ValType {
46    /// 32-bit integer.
47    ///
48    /// Integers are not inherently signed or unsigned, their interpretation is determined by individual operations.
49    I32,
50    /// 64-bit integer.
51    ///
52    /// Integers are not inherently signed or unsigned, their interpretation is determined by individual operations.
53    I64,
54    /// 32-bit floating-point data as defined by the [IEEE 754-2019](https://ieeexplore.ieee.org/document/8766229).
55    F32,
56    /// 64-bit floating-point data as defined by the [IEEE 754-2019](https://ieeexplore.ieee.org/document/8766229).
57    F64,
58    /// 128-bit vector of packed integer or floating-point data.
59    ///
60    /// The packed data can be interpreted as signed or unsigned integers, single or double precision floating-point
61    /// values, or a single 128 bit type. The interpretation is determined by individual operations.
62    V128,
63    /// A reference to a host function.
64    FuncRef,
65    /// A reference to object.
66    ExternRef,
67    /// A reference that unsupported by c-api.
68    UnsupportedRef,
69}
70
71/// Defines the mutability property of WasmEdge Global variables.
72///
73/// `Mutability` determines the mutability property of a WasmEdge Global variable is either mutable or immutable.
74#[derive(Debug, Copy, Clone, Eq, PartialEq)]
75pub enum Mutability {
76    /// Identifies an immutable global variable.
77    Const,
78    /// Identifies a mutable global variable.
79    Var,
80}
81impl From<u32> for Mutability {
82    fn from(value: u32) -> Self {
83        match value {
84            0 => Mutability::Const,
85            1 => Mutability::Var,
86            _ => panic!("[wasmedge-types] Invalid WasmEdge_Mutability: {value:#X}"),
87        }
88    }
89}
90impl From<Mutability> for u32 {
91    fn from(value: Mutability) -> Self {
92        match value {
93            Mutability::Const => 0,
94            Mutability::Var => 1,
95        }
96    }
97}
98impl From<i32> for Mutability {
99    fn from(value: i32) -> Self {
100        match value {
101            0 => Mutability::Const,
102            1 => Mutability::Var,
103            _ => panic!("[wasmedge-types] Invalid WasmEdge_Mutability: {value:#X}"),
104        }
105    }
106}
107impl From<Mutability> for i32 {
108    fn from(value: Mutability) -> Self {
109        match value {
110            Mutability::Const => 0,
111            Mutability::Var => 1,
112        }
113    }
114}
115
116/// Defines WasmEdge AOT compiler optimization level.
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub enum CompilerOptimizationLevel {
119    /// Disable as many optimizations as possible.
120    O0,
121
122    /// Optimize quickly without destroying debuggability.
123    O1,
124
125    /// Optimize for fast execution as much as possible without triggering significant incremental compile time or code size growth.
126    O2,
127
128    ///  Optimize for fast execution as much as possible.
129    O3,
130
131    ///  Optimize for small code size as much as possible without triggering
132    ///  significant incremental compile time or execution time slowdowns.
133    Os,
134
135    /// Optimize for small code size as much as possible.
136    Oz,
137}
138impl From<u32> for CompilerOptimizationLevel {
139    fn from(val: u32) -> CompilerOptimizationLevel {
140        match val {
141            0 => CompilerOptimizationLevel::O0,
142            1 => CompilerOptimizationLevel::O1,
143            2 => CompilerOptimizationLevel::O2,
144            3 => CompilerOptimizationLevel::O3,
145            4 => CompilerOptimizationLevel::Os,
146            5 => CompilerOptimizationLevel::Oz,
147            _ => panic!("Unknown CompilerOptimizationLevel value: {val}"),
148        }
149    }
150}
151impl From<CompilerOptimizationLevel> for u32 {
152    fn from(val: CompilerOptimizationLevel) -> u32 {
153        match val {
154            CompilerOptimizationLevel::O0 => 0,
155            CompilerOptimizationLevel::O1 => 1,
156            CompilerOptimizationLevel::O2 => 2,
157            CompilerOptimizationLevel::O3 => 3,
158            CompilerOptimizationLevel::Os => 4,
159            CompilerOptimizationLevel::Oz => 5,
160        }
161    }
162}
163impl From<i32> for CompilerOptimizationLevel {
164    fn from(val: i32) -> CompilerOptimizationLevel {
165        match val {
166            0 => CompilerOptimizationLevel::O0,
167            1 => CompilerOptimizationLevel::O1,
168            2 => CompilerOptimizationLevel::O2,
169            3 => CompilerOptimizationLevel::O3,
170            4 => CompilerOptimizationLevel::Os,
171            5 => CompilerOptimizationLevel::Oz,
172            _ => panic!("Unknown CompilerOptimizationLevel value: {val}"),
173        }
174    }
175}
176impl From<CompilerOptimizationLevel> for i32 {
177    fn from(val: CompilerOptimizationLevel) -> i32 {
178        match val {
179            CompilerOptimizationLevel::O0 => 0,
180            CompilerOptimizationLevel::O1 => 1,
181            CompilerOptimizationLevel::O2 => 2,
182            CompilerOptimizationLevel::O3 => 3,
183            CompilerOptimizationLevel::Os => 4,
184            CompilerOptimizationLevel::Oz => 5,
185        }
186    }
187}
188
189/// Defines WasmEdge AOT compiler output binary format.
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum CompilerOutputFormat {
192    /// Native dynamic library format.
193    Native,
194
195    /// WebAssembly with AOT compiled codes in custom sections.
196    Wasm,
197}
198impl From<u32> for CompilerOutputFormat {
199    fn from(val: u32) -> CompilerOutputFormat {
200        match val {
201            0 => CompilerOutputFormat::Native,
202            1 => CompilerOutputFormat::Wasm,
203            _ => panic!("Unknown CompilerOutputFormat value: {val}"),
204        }
205    }
206}
207impl From<CompilerOutputFormat> for u32 {
208    fn from(val: CompilerOutputFormat) -> u32 {
209        match val {
210            CompilerOutputFormat::Native => 0,
211            CompilerOutputFormat::Wasm => 1,
212        }
213    }
214}
215impl From<i32> for CompilerOutputFormat {
216    fn from(val: i32) -> CompilerOutputFormat {
217        match val {
218            0 => CompilerOutputFormat::Native,
219            1 => CompilerOutputFormat::Wasm,
220            _ => panic!("Unknown CompilerOutputFormat value: {val}"),
221        }
222    }
223}
224impl From<CompilerOutputFormat> for i32 {
225    fn from(val: CompilerOutputFormat) -> i32 {
226        match val {
227            CompilerOutputFormat::Native => 0,
228            CompilerOutputFormat::Wasm => 1,
229        }
230    }
231}
232
233/// Defines the execution mode of the WasmEdge runtime.
234///
235/// Since WasmEdge 0.17.0, the runtime no longer executes the AOT-compiled
236/// code embedded in a WASM file by default for safety reasons. The execution
237/// mode must be set explicitly to enable the JIT or AOT execution.
238#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
239pub enum RunMode {
240    /// Executes WASM in the interpreter. AOT-compiled code embedded in a WASM
241    /// file is ignored. This is the default mode.
242    #[default]
243    Interpreter,
244
245    /// Executes WASM with the just-in-time compiler.
246    Jit,
247
248    /// Executes the AOT-compiled code. This is the only mode that loads AOT
249    /// custom sections from a universal WASM file or `dlopen`s a
250    /// shared-library WASM artifact.
251    Aot,
252}
253impl From<u32> for RunMode {
254    fn from(val: u32) -> RunMode {
255        match val {
256            0 => RunMode::Interpreter,
257            1 => RunMode::Jit,
258            2 => RunMode::Aot,
259            _ => panic!("Unknown RunMode value: {val}"),
260        }
261    }
262}
263impl From<RunMode> for u32 {
264    fn from(val: RunMode) -> u32 {
265        match val {
266            RunMode::Interpreter => 0,
267            RunMode::Jit => 1,
268            RunMode::Aot => 2,
269        }
270    }
271}
272impl From<i32> for RunMode {
273    fn from(val: i32) -> RunMode {
274        match val {
275            0 => RunMode::Interpreter,
276            1 => RunMode::Jit,
277            2 => RunMode::Aot,
278            _ => panic!("Unknown RunMode value: {val}"),
279        }
280    }
281}
282impl From<RunMode> for i32 {
283    fn from(val: RunMode) -> i32 {
284        match val {
285            RunMode::Interpreter => 0,
286            RunMode::Jit => 1,
287            RunMode::Aot => 2,
288        }
289    }
290}
291
292/// Defines the WebAssembly standard versions.
293///
294/// A standard selects the preset of WebAssembly proposals that belong to that
295/// version of the specification. Applying a standard to a configuration resets
296/// the enabled proposals to exactly that preset.
297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298pub enum WasmStandard {
299    /// WebAssembly 1.0: the MVP plus the `ImportExportMutGlobals` proposal.
300    Wasm1,
301
302    /// WebAssembly 2.0: WASM 1.0 plus the `NonTrapFloatToIntConversions`,
303    /// `SignExtensionOperators`, `MultiValue`, `BulkMemoryOperations`,
304    /// `ReferenceTypes`, and `SIMD` proposals.
305    Wasm2,
306
307    /// WebAssembly 3.0: WASM 2.0 plus the `TailCall`, `ExtendedConst`,
308    /// `FunctionReferences`, `GC`, `MultiMemories`, `RelaxSIMD`,
309    /// `ExceptionHandling`, and `Memory64` proposals.
310    Wasm3,
311}
312impl From<u32> for WasmStandard {
313    fn from(val: u32) -> WasmStandard {
314        match val {
315            0 => WasmStandard::Wasm1,
316            1 => WasmStandard::Wasm2,
317            2 => WasmStandard::Wasm3,
318            _ => panic!("Unknown WasmStandard value: {val}"),
319        }
320    }
321}
322impl From<WasmStandard> for u32 {
323    fn from(val: WasmStandard) -> u32 {
324        match val {
325            WasmStandard::Wasm1 => 0,
326            WasmStandard::Wasm2 => 1,
327            WasmStandard::Wasm3 => 2,
328        }
329    }
330}
331impl From<i32> for WasmStandard {
332    fn from(val: i32) -> WasmStandard {
333        match val {
334            0 => WasmStandard::Wasm1,
335            1 => WasmStandard::Wasm2,
336            2 => WasmStandard::Wasm3,
337            _ => panic!("Unknown WasmStandard value: {val}"),
338        }
339    }
340}
341impl From<WasmStandard> for i32 {
342    fn from(val: WasmStandard) -> i32 {
343        match val {
344            WasmStandard::Wasm1 => 0,
345            WasmStandard::Wasm2 => 1,
346            WasmStandard::Wasm3 => 2,
347        }
348    }
349}
350
351/// Defines WasmEdge host module registration enum.
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
353pub enum HostRegistration {
354    Wasi,
355    WasmEdgeProcess,
356    WasiNn,
357    WasiCryptoCommon,
358    WasiCryptoAsymmetricCommon,
359    WasiCryptoKx,
360    WasiCryptoSignatures,
361    WasiCryptoSymmetric,
362}
363impl From<u32> for HostRegistration {
364    fn from(val: u32) -> Self {
365        match val {
366            0 => HostRegistration::Wasi,
367            1 => HostRegistration::WasmEdgeProcess,
368            2 => HostRegistration::WasiNn,
369            3 => HostRegistration::WasiCryptoCommon,
370            4 => HostRegistration::WasiCryptoAsymmetricCommon,
371            5 => HostRegistration::WasiCryptoKx,
372            6 => HostRegistration::WasiCryptoSignatures,
373            7 => HostRegistration::WasiCryptoSymmetric,
374            _ => panic!("Unknown WasmEdge_HostRegistration value: {val}"),
375        }
376    }
377}
378impl From<HostRegistration> for u32 {
379    fn from(val: HostRegistration) -> u32 {
380        match val {
381            HostRegistration::Wasi => 0,
382            HostRegistration::WasmEdgeProcess => 1,
383            HostRegistration::WasiNn => 2,
384            HostRegistration::WasiCryptoCommon => 3,
385            HostRegistration::WasiCryptoAsymmetricCommon => 4,
386            HostRegistration::WasiCryptoKx => 5,
387            HostRegistration::WasiCryptoSignatures => 6,
388            HostRegistration::WasiCryptoSymmetric => 7,
389        }
390    }
391}
392
393/// Defines the type of external WasmEdge instances.
394#[derive(Debug, Clone, PartialEq, Eq)]
395pub enum ExternalInstanceType {
396    /// A WasmEdge instance that is a WasmEdge Func.
397    Func(FuncType),
398    /// A WasmEdge instance that is a WasmEdge Table.
399    Table(TableType),
400    /// A WasmEdge instance that is a WasmEdge Memory.
401    Memory(MemoryType),
402    /// A WasmEdge instance that is a WasmEdge Global.
403    Global(GlobalType),
404}
405impl From<u32> for ExternalInstanceType {
406    fn from(value: u32) -> Self {
407        match value {
408            0 => ExternalInstanceType::Func(FuncType::default()),
409            1 => ExternalInstanceType::Table(TableType::default()),
410            2 => ExternalInstanceType::Memory(MemoryType::default()),
411            3 => ExternalInstanceType::Global(GlobalType::default()),
412            _ => panic!("[wasmedge-types] Invalid WasmEdge_ExternalType: {value:#X}",),
413        }
414    }
415}
416impl From<i32> for ExternalInstanceType {
417    fn from(value: i32) -> Self {
418        match value {
419            0 => ExternalInstanceType::Func(FuncType::default()),
420            1 => ExternalInstanceType::Table(TableType::default()),
421            2 => ExternalInstanceType::Memory(MemoryType::default()),
422            3 => ExternalInstanceType::Global(GlobalType::default()),
423            _ => panic!("[wasmedge-types] Invalid WasmEdge_ExternalType: {value:#X}",),
424        }
425    }
426}
427impl std::fmt::Display for ExternalInstanceType {
428    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
429        let message = match self {
430            ExternalInstanceType::Func(_) => "function",
431            ExternalInstanceType::Table(_) => "table",
432            ExternalInstanceType::Memory(_) => "memory",
433            ExternalInstanceType::Global(_) => "global",
434        };
435        write!(f, "{message}")
436    }
437}
438
439/// Struct of WasmEdge FuncType.
440///
441/// A [FuncType] is used to declare the types of the parameters and return values of a WasmEdge Func to be created.
442#[derive(Debug, Clone, PartialEq, Eq, Default)]
443pub struct FuncType {
444    args: Vec<ValType>,
445    returns: Vec<ValType>,
446}
447impl FuncType {
448    /// Creates a new [FuncType] with the given types of arguments and returns.
449    ///
450    /// # Arguments
451    ///
452    /// * `args` - A vector of [ValType]s that represent the types of the arguments.
453    ///
454    /// * `returns` - A vector of [ValType]s that represent the types of the returns.
455    pub fn new(args: Vec<ValType>, returns: Vec<ValType>) -> Self {
456        Self { args, returns }
457    }
458
459    /// Returns the types of the arguments of a host function.
460    pub fn args(&self) -> &[ValType] {
461        &self.args
462    }
463
464    /// Returns the number of the arguments of a host function.
465    pub fn args_len(&self) -> usize {
466        self.args.len()
467    }
468
469    /// Returns the types of the returns of a host function.
470    pub fn returns(&self) -> &[ValType] {
471        &self.returns
472    }
473
474    /// Returns the number of the returns of a host function.
475    pub fn returns_len(&self) -> usize {
476        self.returns.len()
477    }
478}
479
480/// Struct of WasmEdge TableType.
481///
482/// A [TableType] is used to declare the element type and the size range of a WasmEdge Table to be created.
483#[derive(Debug, Clone, PartialEq, Eq)]
484pub struct TableType {
485    elem_ty: RefType,
486    min: u32,
487    max: Option<u32>,
488}
489impl TableType {
490    /// Creates a new [TableType] with the given element type and the size range.
491    ///
492    /// # Arguments
493    ///
494    /// * `elem_ty` - The element type of the table to be created.
495    ///
496    /// * `min` - The minimum size of the table to be created.
497    ///
498    /// * `max` - The maximum size of the table to be created.    
499    pub fn new(elem_ty: RefType, min: u32, max: Option<u32>) -> Self {
500        Self { elem_ty, min, max }
501    }
502
503    /// Returns the element type defined in the [TableType].
504    pub fn elem_ty(&self) -> RefType {
505        self.elem_ty
506    }
507
508    /// Returns the minimum size defined in the [TableType].
509    pub fn minimum(&self) -> u32 {
510        self.min
511    }
512
513    /// Returns the maximum size defined in the [TableType].
514    pub fn maximum(&self) -> Option<u32> {
515        self.max
516    }
517}
518impl Default for TableType {
519    fn default() -> Self {
520        Self {
521            elem_ty: RefType::FuncRef,
522            min: 0,
523            max: None,
524        }
525    }
526}
527
528/// Struct of WasmEdge MemoryType.
529///
530/// A [MemoryType] is used to declare the size range of a WasmEdge Memory to be created.
531#[derive(Debug, Clone, PartialEq, Eq, Default)]
532pub struct MemoryType {
533    min: u32,
534    max: Option<u32>,
535    shared: bool,
536}
537impl MemoryType {
538    /// Creates a new [MemoryType] with the given size range.
539    ///
540    /// # Arguments
541    ///
542    /// * `min` - The minimum size of the memory to be created.
543    ///
544    /// * `max` - The maximum size of the memory to be created. If `shared` is set to true, `max` must be set.
545    ///
546    /// * `shared` - Enables shared memory if true.
547    pub fn new(min: u32, max: Option<u32>, shared: bool) -> WasmEdgeResult<Self> {
548        if shared && max.is_none() {
549            return Err(Box::new(error::WasmEdgeError::Mem(
550                error::MemError::CreateSharedType,
551            )));
552        }
553        Ok(Self { min, max, shared })
554    }
555
556    /// Returns the minimum size defined in the [MemoryType].
557    pub fn minimum(&self) -> u32 {
558        self.min
559    }
560
561    /// Returns the maximum size defined in the [MemoryType].
562    pub fn maximum(&self) -> Option<u32> {
563        self.max
564    }
565
566    /// Returns whether the memory is shared.
567    pub fn shared(&self) -> bool {
568        self.shared
569    }
570}
571
572/// Struct of WasmEdge GlobalType.
573///
574/// A [GlobalType] is used to declare the type of a WasmEdge Global to be created.
575#[derive(Debug, Clone, PartialEq, Eq)]
576pub struct GlobalType {
577    ty: ValType,
578    mutability: Mutability,
579}
580impl GlobalType {
581    /// Creates a new [GlobalType] with the given value type and mutability.
582    ///
583    /// # Arguments
584    ///
585    /// * `ty` - The value type of the global to be created.
586    ///
587    /// * `mutability` - The value mutability property of the global to be created.
588    pub fn new(ty: ValType, mutability: Mutability) -> Self {
589        Self { ty, mutability }
590    }
591
592    /// Returns the value type defined in the [GlobalType].
593    pub fn value_ty(&self) -> ValType {
594        self.ty
595    }
596
597    /// Returns the value mutability property defined in the [GlobalType].
598    pub fn mutability(&self) -> Mutability {
599        self.mutability
600    }
601}
602impl Default for GlobalType {
603    fn default() -> Self {
604        Self {
605            ty: ValType::I32,
606            mutability: Mutability::Var,
607        }
608    }
609}
610
611/// Parses in-memory bytes as either the [WebAssembly Text format](http://webassembly.github.io/spec/core/text/index.html), or a binary WebAssembly module.
612pub use wat::parse_bytes as wat2wasm;
613
614/// The WasmEdge result type.
615pub type WasmEdgeResult<T> = Result<T, Box<error::WasmEdgeError>>;
616
617/// This is a workaround solution to the [`never`](https://doc.rust-lang.org/std/primitive.never.html) type in Rust. It will be replaced by `!` once it is stable.
618#[derive(Debug, Clone)]
619pub enum NeverType {}
620unsafe impl Send for NeverType {}
621unsafe impl Sync for NeverType {}