gaia_assembler/adapters/
mod.rs

1//! 统一的适配器接口定义
2//!
3//! 本模块定义了导入和导出适配器的统一接口,以及相关的配置和管理结构。
4//! 这些接口旨在抽象不同平台之间的差异,提供一致的API。
5
6use crate::instruction::GaiaInstruction;
7use gaia_types::{helpers::CompilationTarget, GaiaError, Result};
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use gaia_types::helpers::{AbiCompatible, ApiCompatible, Architecture};
11use crate::config::GaiaSettings;
12use crate::program::GaiaProgram;
13
14/// 适配器配置信息
15///
16/// 包含适配器运行所需的配置参数
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct AdapterConfig {
19    /// 适配器名称
20    pub name: String,
21    /// 编译目标
22    pub compilation_target: CompilationTarget,
23    /// 配置参数
24    pub parameters: HashMap<String, String>,
25    /// 是否启用
26    pub enabled: bool,
27}
28
29/// 适配器元数据
30///
31/// 描述适配器的基本信息和能力
32#[derive(Debug, Clone)]
33pub struct AdapterMetadata {
34    /// 适配器名称
35    pub name: String,
36    /// 适配器版本
37    pub version: String,
38    /// 支持的编译目标
39    pub compilation_target: CompilationTarget,
40    /// 适配器描述
41    pub description: String,
42    /// 支持的指令集
43    pub supported_instructions: Vec<String>,
44}
45
46/// 函数映射器
47#[derive(Debug)]
48pub struct FunctionMapper {
49    /// 函数映射表 (平台 -> 源函数 -> 目标函数)
50    mappings: HashMap<CompilationTarget, HashMap<String, String>>,
51}
52
53impl FunctionMapper {
54    /// Create a new function mapper with default mappings
55    pub fn new() -> Self {
56        let mut mapper = Self { mappings: HashMap::new() };
57
58        // Initialize platform-specific mappings
59        mapper.init_il_mappings();
60        mapper.init_jvm_mappings();
61        mapper.init_pe_mappings();
62        mapper.init_wasi_mappings();
63
64        mapper
65    }
66
67    /// 从配置创建函数映射器
68    pub fn from_config(config: &GaiaSettings) -> Result<Self> {
69        let mut mapper = Self::new();
70
71        // 加载所有平台的函数映射
72        for mapping in &config.function_mappings {
73            for (platform_name, target_name) in &mapping.platform_mappings {
74                // 找到对应的编译目标
75                for (target, _platform_config) in &config.platforms {
76                    if platform_name == &target.build.to_string() {
77                        mapper.add_mapping(target, &mapping.common_name, target_name);
78                    }
79                }
80            }
81        }
82
83        Ok(mapper)
84    }
85
86    /// 添加函数映射
87    pub fn add_mapping(&mut self, target: &CompilationTarget, source_func: &str, target_func: &str) {
88        self.mappings
89            .entry(target.clone())
90            .or_insert_with(HashMap::new)
91            .insert(source_func.to_string(), target_func.to_string());
92    }
93
94    /// 映射函数名
95    pub fn map_function(&self, target: &CompilationTarget, function_name: &str) -> Option<&str> {
96        self.mappings.get(target).and_then(|platform_mappings| platform_mappings.get(function_name)).map(|s| s.as_str())
97    }
98
99    /// Initialize IL (.NET) platform mappings
100    fn init_il_mappings(&mut self) {
101        let il_target = CompilationTarget {
102            build: Architecture::CLR,
103            host: AbiCompatible::MicrosoftIntermediateLanguage,
104            target: ApiCompatible::ClrRuntime(4),
105        };
106        self.add_mapping(&il_target, "__builtin_print", "void [mscorlib]System.Console::WriteLine(string)");
107        self.add_mapping(&il_target, "__builtin_println", "void [mscorlib]System.Console::WriteLine(string)");
108        self.add_mapping(&il_target, "__builtin_read", "string [mscorlib]System.Console::ReadLine()");
109        self.add_mapping(&il_target, "malloc", "System.Runtime.InteropServices.Marshal.AllocHGlobal");
110        self.add_mapping(&il_target, "free", "System.Runtime.InteropServices.Marshal.FreeHGlobal");
111    }
112
113    /// Initialize JVM platform mappings
114    fn init_jvm_mappings(&mut self) {
115        let jvm_target = CompilationTarget {
116            build: Architecture::JVM,
117            host: AbiCompatible::JavaAssembly,
118            target: ApiCompatible::JvmRuntime(8),
119        };
120        self.add_mapping(&jvm_target, "__builtin_print", "java.lang.System.out.println");
121        self.add_mapping(&jvm_target, "__builtin_println", "java.lang.System.out.println");
122        self.add_mapping(&jvm_target, "__builtin_read", "java.util.Scanner.nextLine");
123        self.add_mapping(&jvm_target, "malloc", "java.nio.ByteBuffer.allocateDirect");
124    }
125
126    /// Initialize PE (Windows) platform mappings
127    fn init_pe_mappings(&mut self) {
128        let pe_target =
129            CompilationTarget { build: Architecture::X86_64, host: AbiCompatible::PE, target: ApiCompatible::MicrosoftVisualC };
130        self.add_mapping(&pe_target, "__builtin_print", "printf");
131        self.add_mapping(&pe_target, "__builtin_println", "puts");
132        self.add_mapping(&pe_target, "__builtin_read", "gets_s");
133        self.add_mapping(&pe_target, "malloc", "HeapAlloc");
134        self.add_mapping(&pe_target, "free", "HeapFree");
135    }
136
137    /// Initialize WASI platform mappings
138    fn init_wasi_mappings(&mut self) {
139        let wasi_target = CompilationTarget {
140            build: Architecture::WASM32,
141            host: AbiCompatible::WebAssemblyTextFormat,
142            target: ApiCompatible::WASI,
143        };
144        self.add_mapping(&wasi_target, "__builtin_print", "wasi_print");
145        self.add_mapping(&wasi_target, "__builtin_println", "wasi_println");
146        self.add_mapping(&wasi_target, "__builtin_read", "wasi_read");
147        self.add_mapping(&wasi_target, "malloc", "malloc");
148        self.add_mapping(&wasi_target, "free", "free");
149    }
150}
151
152impl Default for FunctionMapper {
153    fn default() -> Self {
154        Self::new()
155    }
156}
157
158
159/// 统一的导出适配器接口
160///
161/// 定义了将Gaia指令和程序导出到特定平台格式的标准接口
162pub trait ExportAdapter: Send + Sync {
163    /// 获取适配器元数据
164    fn metadata(&self) -> &AdapterMetadata;
165
166    /// 配置适配器
167    ///
168    /// # 参数
169    /// * `config` - 适配器配置
170    ///
171    /// # 返回值
172    /// 配置成功返回Ok(()),失败返回错误信息
173    fn configure(&mut self, config: AdapterConfig) -> Result<()>;
174
175    /// 导出单个指令
176    ///
177    /// # 参数
178    /// * `instruction` - 要导出的Gaia指令
179    ///
180    /// # 返回值
181    /// 导出成功返回平台特定的指令数据,失败返回错误信息
182    fn export_instruction(&self, instruction: &GaiaInstruction) -> Result<Vec<u8>>;
183
184    /// 导出完整程序
185    ///
186    /// # 参数
187    /// * `program` - 要导出的Gaia程序
188    ///
189    /// # 返回值
190    /// 导出成功返回平台特定的程序数据,失败返回错误信息
191    fn export_program(&self, program: &GaiaProgram) -> Result<Vec<u8>>;
192
193    /// 验证指令是否支持
194    ///
195    /// # 参数
196    /// * `instruction` - 要验证的指令
197    ///
198    /// # 返回值
199    /// 支持返回true,不支持返回false
200    fn supports_instruction(&self, instruction: &GaiaInstruction) -> bool;
201
202    /// 获取输出文件扩展名
203    ///
204    /// # 返回值
205    /// 平台特定的文件扩展名
206    fn file_extension(&self) -> &str;
207
208    /// 清理资源
209    ///
210    /// 在适配器不再使用时调用,用于清理相关资源
211    fn cleanup(&mut self) -> Result<()> {
212        Ok(())
213    }
214}
215
216/// 统一的导入适配器接口
217///
218/// 定义了从特定平台格式导入到Gaia指令和程序的标准接口
219pub trait ImportAdapter: Send + Sync {
220    /// 获取适配器元数据
221    fn metadata(&self) -> &AdapterMetadata;
222
223    /// 配置适配器
224    ///
225    /// # 参数
226    /// * `config` - 适配器配置
227    ///
228    /// # 返回值
229    /// 配置成功返回Ok(()),失败返回错误信息
230    fn configure(&mut self, config: AdapterConfig) -> Result<()>;
231
232    /// 导入单个指令
233    ///
234    /// # 参数
235    /// * `data` - 平台特定的指令数据
236    ///
237    /// # 返回值
238    /// 导入成功返回Gaia指令,失败返回错误信息
239    fn import_instruction(&self, data: &[u8]) -> Result<GaiaInstruction>;
240
241    /// 导入完整程序
242    ///
243    /// # 参数
244    /// * `data` - 平台特定的程序数据
245    ///
246    /// # 返回值
247    /// 导入成功返回Gaia程序,失败返回错误信息
248    fn import_program(&self, data: &[u8]) -> Result<GaiaProgram>;
249
250    /// 验证数据格式
251    ///
252    /// # 参数
253    /// * `data` - 要验证的数据
254    ///
255    /// # 返回值
256    /// 格式正确返回true,错误返回false
257    fn validate_format(&self, data: &[u8]) -> bool;
258
259    /// 获取支持的文件扩展名
260    ///
261    /// # 返回值
262    /// 支持的文件扩展名列表
263    fn supported_extensions(&self) -> Vec<&str>;
264
265    /// 清理资源
266    ///
267    /// 在适配器不再使用时调用,用于清理相关资源
268    fn cleanup(&mut self) -> Result<()> {
269        Ok(())
270    }
271}
272
273/// 适配器管理器
274pub struct AdapterManager {
275    /// 导出适配器注册表
276    export_adapters: HashMap<CompilationTarget, Box<dyn ExportAdapter>>,
277    /// 导入适配器注册表
278    import_adapters: HashMap<CompilationTarget, Box<dyn ImportAdapter>>,
279}
280
281impl AdapterManager {
282    /// 创建新的适配器管理器
283    pub fn new() -> Self {
284        Self { export_adapters: HashMap::new(), import_adapters: HashMap::new() }
285    }
286
287    /// 注册导出适配器
288    ///
289    /// # 参数
290    /// * `target` - 编译目标
291    /// * `adapter` - 要注册的导出适配器
292    ///
293    /// # 返回值
294    /// 注册成功返回Ok(()),失败返回错误信息
295    pub fn register_export_adapter(&mut self, target: CompilationTarget, adapter: Box<dyn ExportAdapter>) -> Result<()> {
296        if self.export_adapters.contains_key(&target) {
297            return Err(GaiaError::adapter_error(&format!("{:?}", target), "导出适配器已存在", None));
298        }
299        self.export_adapters.insert(target, adapter);
300        Ok(())
301    }
302
303    /// 注册导入适配器
304    ///
305    /// # 参数
306    /// * `target` - 编译目标
307    /// * `adapter` - 要注册的导入适配器
308    ///
309    /// # 返回值
310    /// 注册成功返回Ok(()),失败返回错误信息
311    pub fn register_import_adapter(&mut self, target: CompilationTarget, adapter: Box<dyn ImportAdapter>) -> Result<()> {
312        if self.import_adapters.contains_key(&target) {
313            return Err(GaiaError::adapter_error(&format!("{:?}", target), "导入适配器已存在", None));
314        }
315        self.import_adapters.insert(target, adapter);
316        Ok(())
317    }
318
319    /// 获取导出适配器
320    ///
321    /// # 参数
322    /// * `target` - 编译目标
323    ///
324    /// # 返回值
325    /// 找到返回适配器引用,未找到返回错误
326    pub fn get_export_adapter(&self, target: &CompilationTarget) -> Result<&dyn ExportAdapter> {
327        self.export_adapters
328            .get(target)
329            .map(|adapter| adapter.as_ref())
330            .ok_or_else(|| GaiaError::adapter_error(&format!("{:?}", target), "导出适配器未找到", None))
331    }
332
333    /// 获取可变导出适配器
334    ///
335    /// # 参数
336    /// * `target` - 编译目标
337    ///
338    /// # 返回值
339    /// 找到返回适配器可变引用,未找到返回错误
340    pub fn get_export_adapter_mut(&mut self, target: &CompilationTarget) -> Result<&mut (dyn ExportAdapter + '_)> {
341        match self.export_adapters.get_mut(target) {
342            Some(adapter) => Ok(adapter.as_mut()),
343            None => Err(GaiaError::adapter_error(&format!("{:?}", target), "导出适配器未找到", None)),
344        }
345    }
346
347    /// 获取导入适配器
348    ///
349    /// # 参数
350    /// * `target` - 编译目标
351    ///
352    /// # 返回值
353    /// 找到返回适配器引用,未找到返回错误
354    pub fn get_import_adapter(&self, target: &CompilationTarget) -> Result<&dyn ImportAdapter> {
355        self.import_adapters
356            .get(target)
357            .map(|adapter| adapter.as_ref())
358            .ok_or_else(|| GaiaError::adapter_error(&format!("{:?}", target), "导入适配器未找到", None))
359    }
360
361    /// 获取可变导入适配器
362    ///
363    /// # 参数
364    /// * `target` - 编译目标
365    ///
366    /// # 返回值
367    /// 找到返回适配器可变引用,未找到返回错误
368    pub fn get_import_adapter_mut(&mut self, target: &CompilationTarget) -> Result<&mut (dyn ImportAdapter + '_)> {
369        match self.import_adapters.get_mut(target) {
370            Some(adapter) => Ok(adapter.as_mut()),
371            None => Err(GaiaError::adapter_error(&format!("{:?}", target), "导入适配器未找到", None)),
372        }
373    }
374
375    /// 列出所有支持的编译目标
376    ///
377    /// # 返回值
378    /// 编译目标列表
379    pub fn list_supported_targets(&self) -> Vec<CompilationTarget> {
380        let mut targets = Vec::new();
381        targets.extend(self.export_adapters.keys().cloned());
382        targets.extend(self.import_adapters.keys().cloned());
383        targets.sort_by_key(|t| format!("{:?}", t));
384        targets.dedup();
385        targets
386    }
387
388    /// 清理所有适配器资源
389    ///
390    /// # 返回值
391    /// 清理成功返回Ok(()),失败返回错误信息
392    pub fn cleanup_all(&mut self) -> Result<()> {
393        for (target, adapter) in &mut self.export_adapters {
394            if let Err(e) = adapter.cleanup() {
395                return Err(GaiaError::adapter_error(&format!("{:?}", target), "清理导出适配器失败", Some(Box::new(e))));
396            }
397        }
398
399        for (target, adapter) in &mut self.import_adapters {
400            if let Err(e) = adapter.cleanup() {
401                return Err(GaiaError::adapter_error(&format!("{:?}", target), "清理导入适配器失败", Some(Box::new(e))));
402            }
403        }
404
405        Ok(())
406    }
407}
408
409impl Default for AdapterManager {
410    fn default() -> Self {
411        Self::new()
412    }
413}