Skip to main content

gaia_assembler/adapters/
mod.rs

1//! 统一的适配器接口定义
2//!
3//! 本模块定义了导入和导出适配器的统一接口,以及相关的配置和管理结构。
4//! 这些接口旨在抽象不同平台之间的差异,提供一致的API。
5
6use crate::{config::GaiaSettings, instruction::GaiaInstruction, program::GaiaModule};
7use gaia_types::{
8    helpers::{AbiCompatible, ApiCompatible, Architecture, CompilationTarget},
9    GaiaError, Result,
10};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
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        // 使用默认 GaiaSettings 统一初始化,避免硬编码重复
57        // 默认映射包含 __builtin_print / malloc / free 等通用函数
58        Self::from_settings(&GaiaSettings::default())
59    }
60
61    /// 从配置创建函数映射器
62    pub fn from_config(config: &GaiaSettings) -> Result<Self> {
63        Ok(Self::from_settings(config))
64    }
65
66    /// 基于 GaiaSettings 生成统一的函数映射(覆盖默认值)
67    fn from_settings(settings: &GaiaSettings) -> Self {
68        let mut mapper = Self { mappings: HashMap::new() };
69
70        // 预定义的平台目标(统一键:IL/JVM/PE/WASI)
71        let il_target = CompilationTarget {
72            build: Architecture::CLR,
73            host: AbiCompatible::MicrosoftIntermediateLanguage,
74            target: ApiCompatible::ClrRuntime(4),
75        };
76        let jvm_target = CompilationTarget {
77            build: Architecture::JVM,
78            host: AbiCompatible::JavaAssembly,
79            target: ApiCompatible::JvmRuntime(8),
80        };
81        let pe_target =
82            CompilationTarget { build: Architecture::X86_64, host: AbiCompatible::PE, target: ApiCompatible::MicrosoftVisualC };
83        let wasi_target = CompilationTarget {
84            build: Architecture::WASM32,
85            host: AbiCompatible::WebAssemblyTextFormat,
86            target: ApiCompatible::WASI,
87        };
88
89        let mut platform_index: HashMap<String, CompilationTarget> = HashMap::new();
90        platform_index.insert("IL".to_string(), il_target.clone());
91        platform_index.insert("JVM".to_string(), jvm_target.clone());
92        platform_index.insert("PE".to_string(), pe_target.clone());
93        platform_index.insert("WASI".to_string(), wasi_target.clone());
94
95        // 1) 基线:提供合理的默认别名,避免因设置缺失导致不可用
96        // IL 默认:带签名的 WriteLine,适配当前 MsilWriter 的 call 语法
97        mapper.add_mapping(&il_target, "console.log", "void [mscorlib]System.Console::WriteLine(string)");
98        mapper.add_mapping(&il_target, "console.write", "void [mscorlib]System.Console::WriteLine(string)");
99        mapper.add_mapping(&il_target, "conosole.read", "string [mscorlib]System.Console::ReadLine()");
100        mapper.add_mapping(&il_target, "malloc", "System.Runtime.InteropServices.Marshal.AllocHGlobal");
101        mapper.add_mapping(&il_target, "free", "System.Runtime.InteropServices.Marshal.FreeHGlobal");
102        mapper.add_mapping(&il_target, "print", "void [mscorlib]System.Console::WriteLine(string)");
103        mapper.add_mapping(&il_target, "println", "void [mscorlib]System.Console::WriteLine(string)");
104
105        // JVM 默认
106        mapper.add_mapping(&jvm_target, "console.log", "java.lang.System.out.println");
107        mapper.add_mapping(&jvm_target, "console.write", "java.lang.System.out.println");
108        mapper.add_mapping(&jvm_target, "console.read", "java.util.Scanner.nextLine");
109        mapper.add_mapping(&jvm_target, "malloc", "java.nio.ByteBuffer.allocateDirect");
110        mapper.add_mapping(&jvm_target, "free", "System.gc");
111        mapper.add_mapping(&jvm_target, "print", "java.lang.System.out.println");
112        mapper.add_mapping(&jvm_target, "println", "java.lang.System.out.println");
113
114        // PE 默认
115        mapper.add_mapping(&pe_target, "console.log", "puts");
116        mapper.add_mapping(&pe_target, "console.write", "printf");
117        mapper.add_mapping(&pe_target, "console.read", "gets_s");
118        mapper.add_mapping(&pe_target, "malloc", "HeapAlloc");
119        mapper.add_mapping(&pe_target, "free", "HeapFree");
120        mapper.add_mapping(&pe_target, "print", "puts");
121        mapper.add_mapping(&pe_target, "println", "puts");
122
123        // WASI 默认
124        mapper.add_mapping(&wasi_target, "console.log", "wasi_println");
125        mapper.add_mapping(&wasi_target, "console.write", "wasi_print");
126        mapper.add_mapping(&wasi_target, "console.read", "wasi_read");
127        mapper.add_mapping(&wasi_target, "malloc", "malloc");
128        mapper.add_mapping(&wasi_target, "free", "free");
129        mapper.add_mapping(&wasi_target, "print", "wasi_println");
130        mapper.add_mapping(&wasi_target, "println", "wasi_println");
131
132        // 2) 覆盖:使用 settings.function_mappings 覆盖/扩展默认映射
133        for fm in &settings.function_mappings {
134            for (platform_name, target_func) in &fm.platform_mappings {
135                let key = platform_name.to_ascii_uppercase();
136                if let Some(platform_target) = platform_index.get(&key) {
137                    // 直接映射通用名
138                    mapper.add_mapping(platform_target, &fm.common_name, target_func);
139
140                    // 为常见别名提供联动(减少前端重复工作)
141                    if fm.common_name == "__builtin_print" {
142                        let is_il = matches!(platform_target.host, AbiCompatible::MicrosoftIntermediateLanguage);
143                        // IL 平台保留带签名的默认 print 映射,避免生成不完整的 MSIL 调用操作数
144                        if !is_il {
145                            mapper.add_mapping(platform_target, "print", target_func);
146                        }
147                        mapper.add_mapping(platform_target, "console.log", target_func);
148                        mapper.add_mapping(platform_target, "console.write", target_func);
149                    }
150                }
151            }
152        }
153
154        mapper
155    }
156
157    /// 添加函数映射
158    pub fn add_mapping(&mut self, target: &CompilationTarget, source_func: &str, target_func: &str) {
159        self.mappings
160            .entry(target.clone())
161            .or_insert_with(HashMap::new)
162            .insert(source_func.to_string(), target_func.to_string());
163    }
164
165    /// 映射函数名
166    pub fn map_function(&self, target: &CompilationTarget, function_name: &str) -> Option<&str> {
167        self.mappings.get(target).and_then(|platform_mappings| platform_mappings.get(function_name)).map(|s| s.as_str())
168    }
169}
170
171impl Default for FunctionMapper {
172    fn default() -> Self {
173        Self::new()
174    }
175}
176
177/// 统一的导出适配器接口
178///
179/// 定义了将Gaia指令和程序导出到特定平台格式的标准接口
180pub trait ExportAdapter: Send + Sync {
181    /// 获取适配器元数据
182    fn metadata(&self) -> &AdapterMetadata;
183
184    /// 配置适配器
185    ///
186    /// # 参数
187    /// * `config` - 适配器配置
188    ///
189    /// # 返回值
190    /// 配置成功返回Ok(()),失败返回错误信息
191    fn configure(&mut self, config: AdapterConfig) -> Result<()>;
192
193    /// 导出单个指令
194    ///
195    /// # 参数
196    /// * `instruction` - 要导出的Gaia指令
197    ///
198    /// # 返回值
199    /// 导出成功返回平台特定的指令数据,失败返回错误信息
200    fn export_instruction(&self, instruction: &GaiaInstruction) -> Result<Vec<u8>>;
201
202    /// 导出完整程序
203    ///
204    /// # 参数
205    /// * `program` - 要导出的Gaia程序
206    /// 导出程序
207    ///
208    /// # 返回值
209    /// 导出成功返回平台特定的程序数据,失败返回错误信息
210    fn export_program(&self, program: &GaiaModule) -> Result<Vec<u8>>;
211
212    /// 验证指令是否支持
213    ///
214    /// # 参数
215    /// * `instruction` - 要验证的指令
216    ///
217    /// # 返回值
218    /// 支持返回true,不支持返回false
219    fn supports_instruction(&self, instruction: &GaiaInstruction) -> bool;
220
221    /// 获取输出文件扩展名
222    ///
223    /// # 返回值
224    /// 平台特定的文件扩展名
225    fn file_extension(&self) -> &str;
226
227    /// 清理资源
228    ///
229    /// 在适配器不再使用时调用,用于清理相关资源
230    fn cleanup(&mut self) -> Result<()> {
231        Ok(())
232    }
233}
234
235/// 统一的导入适配器接口
236///
237/// 定义了从特定平台格式导入到Gaia指令和程序的标准接口
238pub trait ImportAdapter: Send + Sync {
239    /// 获取适配器元数据
240    fn metadata(&self) -> &AdapterMetadata;
241
242    /// 配置适配器
243    ///
244    /// # 参数
245    /// * `config` - 适配器配置
246    ///
247    /// # 返回值
248    /// 配置成功返回Ok(()),失败返回错误信息
249    fn configure(&mut self, config: AdapterConfig) -> Result<()>;
250
251    /// 导入单个指令
252    ///
253    /// # 参数
254    /// * `data` - 平台特定的指令数据
255    ///
256    /// # 返回值
257    /// 导入成功返回Gaia指令,失败返回错误信息
258    fn import_instruction(&self, data: &[u8]) -> Result<GaiaInstruction>;
259
260    /// 导入程序
261    ///
262    /// # 参数
263    /// * `data` - 平台特定的程序数据
264    ///
265    /// # 返回值
266    /// 导入成功返回转换后的Gaia程序,失败返回错误信息
267    fn import_program(&self, data: &[u8]) -> Result<GaiaModule>;
268
269    /// 验证数据格式
270    ///
271    /// # 参数
272    /// * `data` - 要验证的数据
273    ///
274    /// # 返回值
275    /// 格式正确返回true,错误返回false
276    fn validate_format(&self, data: &[u8]) -> bool;
277
278    /// 获取支持的文件扩展名
279    ///
280    /// # 返回值
281    /// 支持的文件扩展名列表
282    fn supported_extensions(&self) -> Vec<&str>;
283
284    /// 清理资源
285    ///
286    /// 在适配器不再使用时调用,用于清理相关资源
287    fn cleanup(&mut self) -> Result<()> {
288        Ok(())
289    }
290}
291
292/// 适配器管理器
293pub struct AdapterManager {
294    /// 导出适配器注册表
295    export_adapters: HashMap<CompilationTarget, Box<dyn ExportAdapter>>,
296    /// 导入适配器注册表
297    import_adapters: HashMap<CompilationTarget, Box<dyn ImportAdapter>>,
298}
299
300impl AdapterManager {
301    /// 创建新的适配器管理器
302    pub fn new() -> Self {
303        Self { export_adapters: HashMap::new(), import_adapters: HashMap::new() }
304    }
305
306    /// 注册导出适配器
307    ///
308    /// # 参数
309    /// * `target` - 编译目标
310    /// * `adapter` - 要注册的导出适配器
311    ///
312    /// # 返回值
313    /// 注册成功返回Ok(()),失败返回错误信息
314    pub fn register_export_adapter(&mut self, target: CompilationTarget, adapter: Box<dyn ExportAdapter>) -> Result<()> {
315        if self.export_adapters.contains_key(&target) {
316            return Err(GaiaError::adapter_error(&format!("{:?}", target), "导出适配器已存在", None));
317        }
318        self.export_adapters.insert(target, adapter);
319        Ok(())
320    }
321
322    /// 注册导入适配器
323    ///
324    /// # 参数
325    /// * `target` - 编译目标
326    /// * `adapter` - 要注册的导入适配器
327    ///
328    /// # 返回值
329    /// 注册成功返回Ok(()),失败返回错误信息
330    pub fn register_import_adapter(&mut self, target: CompilationTarget, adapter: Box<dyn ImportAdapter>) -> Result<()> {
331        if self.import_adapters.contains_key(&target) {
332            return Err(GaiaError::adapter_error(&format!("{:?}", target), "导入适配器已存在", None));
333        }
334        self.import_adapters.insert(target, adapter);
335        Ok(())
336    }
337
338    /// 获取导出适配器
339    ///
340    /// # 参数
341    /// * `target` - 编译目标
342    ///
343    /// # 返回值
344    /// 找到返回适配器引用,未找到返回错误
345    pub fn get_export_adapter(&self, target: &CompilationTarget) -> Result<&dyn ExportAdapter> {
346        self.export_adapters
347            .get(target)
348            .map(|adapter| adapter.as_ref())
349            .ok_or_else(|| GaiaError::adapter_error(&format!("{:?}", target), "导出适配器未找到", None))
350    }
351
352    /// 获取可变导出适配器
353    ///
354    /// # 参数
355    /// * `target` - 编译目标
356    ///
357    /// # 返回值
358    /// 找到返回适配器可变引用,未找到返回错误
359    pub fn get_export_adapter_mut(&mut self, target: &CompilationTarget) -> Result<&mut (dyn ExportAdapter + '_)> {
360        match self.export_adapters.get_mut(target) {
361            Some(adapter) => Ok(adapter.as_mut()),
362            None => Err(GaiaError::adapter_error(&format!("{:?}", target), "导出适配器未找到", None)),
363        }
364    }
365
366    /// 获取导入适配器
367    ///
368    /// # 参数
369    /// * `target` - 编译目标
370    ///
371    /// # 返回值
372    /// 找到返回适配器引用,未找到返回错误
373    pub fn get_import_adapter(&self, target: &CompilationTarget) -> Result<&dyn ImportAdapter> {
374        self.import_adapters
375            .get(target)
376            .map(|adapter| adapter.as_ref())
377            .ok_or_else(|| GaiaError::adapter_error(&format!("{:?}", target), "导入适配器未找到", None))
378    }
379
380    /// 获取可变导入适配器
381    ///
382    /// # 参数
383    /// * `target` - 编译目标
384    ///
385    /// # 返回值
386    /// 找到返回适配器可变引用,未找到返回错误
387    pub fn get_import_adapter_mut(&mut self, target: &CompilationTarget) -> Result<&mut (dyn ImportAdapter + '_)> {
388        match self.import_adapters.get_mut(target) {
389            Some(adapter) => Ok(adapter.as_mut()),
390            None => Err(GaiaError::adapter_error(&format!("{:?}", target), "导入适配器未找到", None)),
391        }
392    }
393
394    /// 列出所有支持的编译目标
395    ///
396    /// # 返回值
397    /// 编译目标列表
398    pub fn list_supported_targets(&self) -> Vec<CompilationTarget> {
399        let mut targets = Vec::new();
400        targets.extend(self.export_adapters.keys().cloned());
401        targets.extend(self.import_adapters.keys().cloned());
402        targets.sort_by_key(|t| format!("{:?}", t));
403        targets.dedup();
404        targets
405    }
406
407    /// 清理所有适配器资源
408    ///
409    /// # 返回值
410    /// 清理成功返回Ok(()),失败返回错误信息
411    pub fn cleanup_all(&mut self) -> Result<()> {
412        for (target, adapter) in &mut self.export_adapters {
413            if let Err(e) = adapter.cleanup() {
414                return Err(GaiaError::adapter_error(&format!("{:?}", target), "清理导出适配器失败", Some(Box::new(e))));
415            }
416        }
417
418        for (target, adapter) in &mut self.import_adapters {
419            if let Err(e) = adapter.cleanup() {
420                return Err(GaiaError::adapter_error(&format!("{:?}", target), "清理导入适配器失败", Some(Box::new(e))));
421            }
422        }
423
424        Ok(())
425    }
426}
427
428impl Default for AdapterManager {
429    fn default() -> Self {
430        Self::new()
431    }
432}