Skip to main content

aether/
cache.rs

1// src/cache.rs
2//! AST缓存机制,减少重复解析
3
4use crate::ast::Program;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::collections::VecDeque;
8use std::collections::hash_map::DefaultHasher;
9use std::hash::{Hash, Hasher};
10
11/// AST 缓存,用于存储已解析的程序。
12///
13/// - **碰撞安全**:u64 哈希仅作加速索引,命中前必须比对源码
14///   完全一致,哈希碰撞不会返回错误的 AST。
15/// - **LRU 淘汰**:`VecDeque` 维护真实的使用顺序,get 命中会刷新
16///   新鲜度;容量满时淘汰最近最少使用的条目。
17#[derive(Debug)]
18pub struct ASTCache {
19    /// 缓存存储: hash -> (源码, 解析后的 AST)
20    cache: HashMap<u64, (String, Program)>,
21    /// 按使用顺序排列的哈希键(队首 = 最近最少使用)
22    order: VecDeque<u64>,
23    /// 缓存大小限制
24    max_size: usize,
25    /// 缓存命中统计
26    hits: usize,
27    /// 缓存未命中统计
28    misses: usize,
29}
30
31impl ASTCache {
32    /// 创建新的AST缓存
33    pub fn new() -> Self {
34        Self::with_capacity(100)
35    }
36
37    /// 创建指定容量的AST缓存
38    pub fn with_capacity(max_size: usize) -> Self {
39        ASTCache {
40            cache: HashMap::with_capacity(max_size),
41            order: VecDeque::with_capacity(max_size),
42            max_size,
43            hits: 0,
44            misses: 0,
45        }
46    }
47
48    /// 计算代码的哈希值
49    fn hash_code(code: &str) -> u64 {
50        let mut hasher = DefaultHasher::new();
51        code.hash(&mut hasher);
52        hasher.finish()
53    }
54
55    /// 把键移到 LRU 队尾(最近使用)
56    fn touch(&mut self, hash: u64) {
57        if let Some(pos) = self.order.iter().position(|&k| k == hash) {
58            self.order.remove(pos);
59        }
60        self.order.push_back(hash);
61    }
62
63    /// 从缓存中获取AST(命中要求源码完全一致)
64    pub fn get(&mut self, code: &str) -> Option<Program> {
65        let hash = Self::hash_code(code);
66        // 先比对源码(碰撞安全),释放借用后再刷新 LRU 顺序
67        let hit = self
68            .cache
69            .get(&hash)
70            .is_some_and(|(cached_code, _)| cached_code == code);
71        if hit {
72            self.hits += 1;
73            self.touch(hash);
74            self.cache.get(&hash).map(|(_, program)| program.clone())
75        } else {
76            self.misses += 1;
77            None
78        }
79    }
80
81    /// 将AST存入缓存(容量满时淘汰最近最少使用的条目)
82    pub fn insert(&mut self, code: &str, program: Program) {
83        let hash = Self::hash_code(code);
84
85        if self.cache.contains_key(&hash) {
86            // 同键覆盖(源码可能不同):保持容量不变,刷新新鲜度
87            self.touch(hash);
88        } else {
89            while self.cache.len() >= self.max_size {
90                if let Some(lru) = self.order.pop_front() {
91                    self.cache.remove(&lru);
92                } else {
93                    break;
94                }
95            }
96            self.order.push_back(hash);
97        }
98
99        self.cache.insert(hash, (code.to_string(), program));
100    }
101
102    /// 清空缓存
103    pub fn clear(&mut self) {
104        self.cache.clear();
105        self.order.clear();
106        self.hits = 0;
107        self.misses = 0;
108    }
109
110    /// 获取缓存统计信息
111    pub fn stats(&self) -> CacheStats {
112        CacheStats {
113            size: self.cache.len(),
114            max_size: self.max_size,
115            hits: self.hits,
116            misses: self.misses,
117            hit_rate: if self.hits + self.misses > 0 {
118                self.hits as f64 / (self.hits + self.misses) as f64
119            } else {
120                0.0
121            },
122        }
123    }
124}
125
126impl Default for ASTCache {
127    fn default() -> Self {
128        Self::new()
129    }
130}
131
132/// 缓存统计信息
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct CacheStats {
135    /// 当前缓存大小
136    pub size: usize,
137    /// 最大缓存大小
138    pub max_size: usize,
139    /// 缓存命中次数
140    pub hits: usize,
141    /// 缓存未命中次数
142    pub misses: usize,
143    /// 缓存命中率
144    pub hit_rate: f64,
145}
146
147impl std::fmt::Display for CacheStats {
148    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
149        write!(
150            f,
151            "Cache Stats: size={}/{}, hits={}, misses={}, hit_rate={:.2}%",
152            self.size,
153            self.max_size,
154            self.hits,
155            self.misses,
156            self.hit_rate * 100.0
157        )
158    }
159}