Skip to main content

wasi_assembler/
lib.rs

1#![feature(once_cell_try)]
2#![warn(missing_docs)]
3#![doc = include_str!("readme.md")]
4
5pub mod formats;
6pub mod helpers;
7pub mod program;
8
9// 重新导出常用模块
10#[cfg(feature = "wat")]
11pub use formats::wat;
12use gaia_types::GaiaError;
13pub use program::{
14    WasiAlias, WasiAliasTarget, WasiCanonicalOperation, WasiComponentItem, WasiCoreFunc, WasiCoreInstance, WasiCoreModule,
15    WasiCoreType, WasiCustomSection, WasiDataSegment, WasiElementSegment, WasiExport, WasiFunction, WasiFunctionType,
16    WasiGlobal, WasiImport, WasiInstance, WasiInstanceArg, WasiInstanceType, WasiInstruction, WasiMemory, WasiPrimitiveType,
17    WasiProgram, WasiProgramBuilder, WasiProgramType, WasiRecordField, WasiResourceMethod, WasiResourceType, WasiSymbol,
18    WasiSymbolType, WasiTable, WasiType, WasiTypeDefinition, WasiVariantCase, WasmExportType, WasmGlobalType, WasmImportType,
19    WasmInfo, WasmLocal, WasmMemoryType, WasmReferenceType, WasmTableType, WasmValueType,
20};
21
22/// WASI 错误类型
23#[derive(Debug)]
24pub enum WasiError {
25    /// 解析错误
26    ParseError(String),
27    /// 验证错误
28    ValidationError(String),
29    /// 编译错误
30    CompilationError(String),
31    /// 其他错误
32    Other(String),
33}
34
35impl std::fmt::Display for WasiError {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            WasiError::ParseError(msg) => write!(f, "Parse error: {}", msg),
39            WasiError::ValidationError(msg) => write!(f, "Validation error: {}", msg),
40            WasiError::CompilationError(msg) => write!(f, "Compilation error: {}", msg),
41            WasiError::Other(msg) => write!(f, "Other error: {}", msg),
42        }
43    }
44}
45
46impl std::error::Error for WasiError {}
47
48impl From<GaiaError> for WasiError {
49    fn from(error: GaiaError) -> Self {
50        WasiError::Other(error.to_string())
51    }
52}
53
54/// WASI 汇编器
55pub struct WasiAssembler {
56    target: String,
57}
58
59impl WasiAssembler {
60    /// 创建新的汇编器实例
61    pub fn new() -> Self {
62        Self { target: "wasm32-wasi".to_string() }
63    }
64
65    /// 设置目标架构
66    pub fn set_target(&mut self, target: &str) {
67        self.target = target.to_string();
68    }
69
70    /// 从字符串汇编 WASI 代码
71    pub fn assemble_from_str(&self, _source: &str) -> std::result::Result<Vec<u8>, WasiError> {
72        // 这是一个占位实现
73        Ok(vec![0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00])
74    }
75
76    /// 从文件汇编 WASI 代码
77    pub fn assemble_from_file(&self, path: impl AsRef<std::path::Path>) -> std::result::Result<Vec<u8>, WasiError> {
78        let source = std::fs::read_to_string(path).map_err(|e| WasiError::Other(e.to_string()))?;
79        self.assemble_from_str(&source)
80    }
81}
82
83impl Default for WasiAssembler {
84    fn default() -> Self {
85        Self::new()
86    }
87}