Skip to main content

nyar_assembler/program/
pool.rs

1use super::types::NyarConstant;
2use gaia_types::QualifiedName;
3use std::collections::HashMap;
4
5/// Nyar 常量池构建器
6///
7/// 用于在汇编过程中收集和去重常量,最终导出为 NyarModule 所需的 Vec<NyarConstant>。
8#[derive(Debug, Clone, Default)]
9pub struct NyarConstantPool {
10    /// 常量到索引的映射
11    pub constants: HashMap<NyarConstant, u16>,
12    /// 按索引排序的常量列表
13    pub pool: Vec<NyarConstant>,
14}
15
16impl NyarConstantPool {
17    /// 创建一个新的常量池构建器
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    /// 添加一个常量到池中,返回其索引
23    ///
24    /// 如果常量已存在,则返回现有索引;否则将其添加到池末尾。
25    pub fn add(&mut self, constant: NyarConstant) -> u16 {
26        if let Some(&index) = self.constants.get(&constant) {
27            return index;
28        }
29        let index = self.pool.len() as u16;
30        self.constants.insert(constant.clone(), index);
31        self.pool.push(constant);
32        index
33    }
34
35    /// 添加整数常量
36    pub fn add_int(&mut self, value: i64) -> u16 {
37        self.add(NyarConstant::Int(value))
38    }
39
40    /// 添加浮点数常量
41    pub fn add_float(&mut self, value: f64) -> u16 {
42        self.add(NyarConstant::float(value))
43    }
44
45    /// 添加字符串常量
46    pub fn add_string(&mut self, value: String) -> u16 {
47        self.add(NyarConstant::String(value))
48    }
49
50    /// 添加限定名称常量
51    pub fn add_qualified_name(&mut self, value: QualifiedName) -> u16 {
52        self.add(NyarConstant::QualifiedName(value))
53    }
54
55    /// 获取池中的所有常量
56    pub fn into_vec(self) -> Vec<NyarConstant> {
57        self.pool
58    }
59
60    /// 获取常量池的大小
61    pub fn len(&self) -> usize {
62        self.pool.len()
63    }
64
65    /// 检查常量池是否为空
66    pub fn is_empty(&self) -> bool {
67        self.pool.is_empty()
68    }
69}