lean_ctx_ext/core/
symbol_map.rs1use std::collections::HashMap;
3
4use crate::core::tokens::count_tokens;
5
6macro_rules! static_regex {
7 ($pattern:expr_2021) => {{
8 static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
9 RE.get_or_init(|| {
10 regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
11 })
12 }};
13}
14
15const MIN_IDENT_LENGTH: usize = 6;
16const SHORT_ID_PREFIX: char = 'α';
17
18pub fn substitution_enabled() -> bool {
26 if let Ok(v) = std::env::var("LEAN_CTX_SYMBOL_MAP") {
27 return v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("on");
28 }
29 let cfg = crate::core::config::Config::load();
30 if cfg.symbol_map_auto {
31 return auto_detect_large_project();
32 }
33 false
34}
35
36fn auto_detect_large_project() -> bool {
37 use std::sync::OnceLock;
38 static DETECTED: OnceLock<bool> = OnceLock::new();
39 *DETECTED.get_or_init(|| {
40 let cwd = std::env::current_dir().unwrap_or_default();
41 let source_exts = [
42 "rs", "ts", "tsx", "js", "jsx", "py", "go", "java", "rb", "cpp", "c", "h", "gd",
43 ];
44 let count = ignore::WalkBuilder::new(&cwd)
45 .hidden(true)
46 .max_depth(Some(6))
47 .git_ignore(true)
48 .require_git(false)
49 .filter_entry(crate::core::walk_filter::keep_entry)
50 .build()
51 .filter_map(std::result::Result::ok)
52 .filter(|e| {
53 e.file_type().is_some_and(|ft| ft.is_file())
54 && crate::core::io_boundary::is_secret_like(
57 e.path().strip_prefix(&cwd).unwrap_or(e.path()),
58 )
59 .is_none()
60 && e.path()
61 .extension()
62 .and_then(|ext| ext.to_str())
63 .is_some_and(|ext| source_exts.contains(&ext))
64 })
65 .take(51)
66 .count();
67 count > 50
68 })
69}
70
71#[derive(Debug, Clone)]
72pub struct SymbolMap {
73 forward: HashMap<String, String>,
74 next_id: usize,
75}
76
77impl Default for SymbolMap {
78 fn default() -> Self {
79 Self::new()
80 }
81}
82
83impl SymbolMap {
84 pub fn new() -> Self {
85 Self {
86 forward: HashMap::new(),
87 next_id: 1,
88 }
89 }
90
91 pub fn register(&mut self, identifier: &str) -> Option<String> {
92 if identifier.len() < MIN_IDENT_LENGTH {
93 return None;
94 }
95
96 if let Some(existing) = self.forward.get(identifier) {
97 return Some(existing.clone());
98 }
99
100 let short_id = format!("{SHORT_ID_PREFIX}{}", self.next_id);
101 self.next_id += 1;
102 self.forward
103 .insert(identifier.to_string(), short_id.clone());
104 Some(short_id)
105 }
106
107 pub fn apply(&self, text: &str) -> String {
108 if self.forward.is_empty() {
109 return text.to_string();
110 }
111
112 let mut sorted: Vec<(&String, &String)> = self.forward.iter().collect();
113 sorted.sort_by_key(|x| std::cmp::Reverse(x.0.len()));
114
115 let mut result = text.to_string();
116 for (long, short) in &sorted {
117 result = result.replace(long.as_str(), short.as_str());
118 }
119 result
120 }
121
122 pub fn format_table(&self) -> String {
123 if self.forward.is_empty() {
124 return String::new();
125 }
126
127 let mut entries: Vec<(&String, &String)> = self.forward.iter().collect();
128 entries.sort_by_key(|(_, v)| {
129 v.trim_start_matches(SHORT_ID_PREFIX)
130 .parse::<usize>()
131 .unwrap_or(0)
132 });
133
134 let mut table = String::from("\n§MAP:");
135 for (long, short) in &entries {
136 table.push_str(&format!("\n {short}={long}"));
137 }
138 table
139 }
140
141 pub fn len(&self) -> usize {
142 self.forward.len()
143 }
144
145 pub fn is_empty(&self) -> bool {
146 self.forward.is_empty()
147 }
148}
149
150const MAP_ENTRY_OVERHEAD: usize = 2;
152
153pub fn should_register(identifier: &str, occurrences: usize, next_id: usize) -> bool {
157 if identifier.len() < MIN_IDENT_LENGTH {
158 return false;
159 }
160 let ident_tokens = count_tokens(identifier);
161 let short_id = format!("{SHORT_ID_PREFIX}{next_id}");
162 let short_tokens = count_tokens(&short_id);
163
164 let token_saving_per_use = ident_tokens.saturating_sub(short_tokens);
165 if token_saving_per_use == 0 {
166 return false;
167 }
168
169 let total_savings = occurrences * token_saving_per_use;
170 let entry_cost = ident_tokens + short_tokens + MAP_ENTRY_OVERHEAD;
171
172 total_savings > entry_cost
173}
174
175pub fn extract_identifiers(content: &str, exts: &[&str]) -> Vec<String> {
176 let ident_re = static_regex!(r"\b[a-zA-Z_][a-zA-Z0-9_]*\b");
177
178 let mut seen = HashMap::new();
179 for mat in ident_re.find_iter(content) {
180 let word = mat.as_str();
181 if word.len() >= MIN_IDENT_LENGTH && !is_keyword(word, exts) {
182 *seen.entry(word.to_string()).or_insert(0usize) += 1;
183 }
184 }
185
186 let mut next_id = 1usize;
187 let mut idents: Vec<(String, usize)> = seen
188 .into_iter()
189 .filter(|(ident, count)| {
190 let pass = should_register(ident, *count, next_id);
191 if pass {
192 next_id += 1;
193 }
194 pass
195 })
196 .collect();
197
198 idents.sort_by(|a, b| {
199 let savings_a = a.0.len() * a.1;
200 let savings_b = b.0.len() * b.1;
201 savings_b.cmp(&savings_a)
202 });
203
204 idents.into_iter().map(|(s, _)| s).collect()
205}
206
207fn is_keyword(word: &str, exts: &[&str]) -> bool {
211 exts.iter().any(|&ext| match ext {
212 "rs" => matches!(
213 word,
214 "continue" | "default" | "return" | "struct" | "unsafe" | "where"
215 ),
216 "ts" | "tsx" | "js" | "jsx" => matches!(
217 word,
218 "constructor" | "arguments" | "undefined" | "prototype" | "instanceof"
219 ),
220 "py" => matches!(word, "continue" | "lambda" | "return" | "import" | "class"),
221 _ => false,
222 })
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 #[test]
230 fn test_should_register_short_ident_rejected() {
231 assert!(!should_register("foo", 100, 1));
232 assert!(!should_register("bar", 50, 1));
233 assert!(!should_register("x", 1000, 1));
234 }
235
236 #[test]
237 fn test_should_register_roi_positive() {
238 assert!(should_register(
240 "authenticate_user_credentials_handler",
241 5,
242 1
243 ));
244 }
245
246 #[test]
247 fn test_should_register_roi_negative_single_use() {
248 assert!(!should_register(
250 "authenticate_user_credentials_handler",
251 1,
252 1
253 ));
254 }
255
256 #[test]
257 fn test_should_register_roi_scales_with_frequency() {
258 let ident = "configuration_manager_instance";
259 let passes_at_low = should_register(ident, 2, 1);
261 let passes_at_high = should_register(ident, 10, 1);
262 assert!(passes_at_high || !passes_at_low);
264 }
265
266 #[test]
267 fn test_extract_identifiers_roi_filtering() {
268 let long = "authenticate_user_credentials_handler";
270 let content = format!("{long} {long} {long} {long} {long} short");
271 let result = extract_identifiers(&content, &["rs"]);
272 assert!(result.contains(&long.to_string()));
273 assert!(!result.contains(&"short".to_string()));
274 }
275
276 #[test]
277 fn test_register_returns_existing() {
278 let mut map = SymbolMap::new();
279 let first = map.register("validateToken");
280 let second = map.register("validateToken");
281 assert_eq!(first, second);
282 }
283
284 #[test]
285 fn test_apply_replaces_identifiers() {
286 let mut map = SymbolMap::new();
287 map.register("validateToken");
288 let result = map.apply("call validateToken here");
289 assert!(result.contains("α1"));
290 assert!(!result.contains("validateToken"));
291 }
292
293 #[test]
294 fn test_format_table_output() {
295 let mut map = SymbolMap::new();
296 map.register("validateToken");
297 let table = map.format_table();
298 assert!(table.contains("§MAP:"));
299 assert!(table.contains("α1=validateToken"));
300 }
301}