Skip to main content

lean_ctx/core/
compressor.rs

1use similar::{ChangeTag, TextDiff};
2
3pub fn strip_ansi(s: &str) -> String {
4    if !s.contains('\x1b') {
5        return s.to_string();
6    }
7    let mut result = String::with_capacity(s.len());
8    let mut in_escape = false;
9    for c in s.chars() {
10        if c == '\x1b' {
11            in_escape = true;
12            continue;
13        }
14        if in_escape {
15            if c.is_ascii_alphabetic() {
16                in_escape = false;
17            }
18            continue;
19        }
20        result.push(c);
21    }
22    result
23}
24
25pub fn ansi_density(s: &str) -> f64 {
26    if s.is_empty() {
27        return 0.0;
28    }
29    let escape_bytes = s.chars().filter(|&c| c == '\x1b').count();
30    escape_bytes as f64 / s.len() as f64
31}
32
33pub fn aggressive_compress(content: &str, ext: Option<&str>) -> String {
34    let mut result: Vec<String> = Vec::new();
35    let is_python = matches!(ext, Some("py"));
36    let is_html = matches!(ext, Some("html" | "htm" | "xml" | "svg"));
37    let is_sql = matches!(ext, Some("sql"));
38    let is_shell = matches!(ext, Some("sh" | "bash" | "zsh" | "fish"));
39
40    let mut in_block_comment = false;
41
42    for line in content.lines() {
43        let trimmed = line.trim();
44
45        if trimmed.is_empty() {
46            continue;
47        }
48
49        if in_block_comment {
50            if trimmed.contains("*/") || (is_html && trimmed.contains("-->")) {
51                in_block_comment = false;
52            }
53            continue;
54        }
55
56        if trimmed.starts_with("/*") || (is_html && trimmed.starts_with("<!--")) {
57            if !(trimmed.contains("*/") || trimmed.contains("-->")) {
58                in_block_comment = true;
59            }
60            continue;
61        }
62
63        if trimmed.starts_with("//") && !trimmed.starts_with("///") {
64            continue;
65        }
66        if trimmed.starts_with('*') || trimmed.starts_with("*/") {
67            continue;
68        }
69        if is_python && trimmed.starts_with('#') {
70            continue;
71        }
72        if is_sql && trimmed.starts_with("--") {
73            continue;
74        }
75        if is_shell && trimmed.starts_with('#') && !trimmed.starts_with("#!") {
76            continue;
77        }
78        if !is_python && trimmed.starts_with('#') && trimmed.contains('[') {
79            continue;
80        }
81
82        if trimmed == "}" || trimmed == "};" || trimmed == ");" || trimmed == "});" {
83            if let Some(last) = result.last() {
84                let last_trimmed = last.trim();
85                if matches!(last_trimmed, "}" | "};" | ");" | "});") {
86                    if let Some(last_mut) = result.last_mut() {
87                        last_mut.push_str(trimmed);
88                    }
89                    continue;
90                }
91            }
92            result.push(trimmed.to_string());
93            continue;
94        }
95
96        let normalized = normalize_indentation(line);
97        result.push(normalized);
98    }
99
100    result.join("\n")
101}
102
103/// Lightweight post-processing cleanup: collapses consecutive closing braces,
104/// removes whitespace-only lines, and limits consecutive blank lines to 1.
105pub fn lightweight_cleanup(content: &str) -> String {
106    let mut result: Vec<String> = Vec::new();
107    let mut blank_count = 0u32;
108    let mut close_brace_count = 0u32;
109
110    for line in content.lines() {
111        let trimmed = line.trim();
112
113        if trimmed.is_empty() {
114            close_brace_count = 0;
115            blank_count += 1;
116            if blank_count <= 1 {
117                result.push(String::new());
118            }
119            continue;
120        }
121        blank_count = 0;
122
123        if matches!(trimmed, "}" | "};" | ");" | "});" | ")") {
124            close_brace_count += 1;
125            if close_brace_count <= 2 {
126                result.push(trimmed.to_string());
127            }
128            continue;
129        }
130        close_brace_count = 0;
131
132        result.push(line.to_string());
133    }
134
135    result.join("\n")
136}
137
138/// Safeguard: ensures compression ratio stays within safe bounds.
139/// Returns the compressed content if ratio is in [0.15, 1.0], otherwise the original.
140pub fn safeguard_ratio(original: &str, compressed: &str) -> String {
141    let orig_tokens = super::tokens::count_tokens(original);
142    let comp_tokens = super::tokens::count_tokens(compressed);
143
144    if orig_tokens == 0 {
145        return compressed.to_string();
146    }
147
148    let ratio = comp_tokens as f64 / orig_tokens as f64;
149    if ratio < 0.15 || comp_tokens > orig_tokens {
150        original.to_string()
151    } else {
152        compressed.to_string()
153    }
154}
155
156fn normalize_indentation(line: &str) -> String {
157    let content = line.trim_start();
158    let leading = line.len() - content.len();
159    let has_tabs = line.starts_with('\t');
160    let reduced = if has_tabs { leading } else { leading / 2 };
161    format!("{}{}", " ".repeat(reduced), content)
162}
163
164pub fn diff_content(old_content: &str, new_content: &str) -> String {
165    if old_content == new_content {
166        return "(no changes)".to_string();
167    }
168
169    let diff = TextDiff::from_lines(old_content, new_content);
170    let mut changes = Vec::new();
171    let mut additions = 0usize;
172    let mut deletions = 0usize;
173
174    for change in diff.iter_all_changes() {
175        let line_no = change.new_index().or(change.old_index()).map(|i| i + 1);
176        let text = change.value().trim_end_matches('\n');
177        match change.tag() {
178            ChangeTag::Insert => {
179                additions += 1;
180                if let Some(n) = line_no {
181                    changes.push(format!("+{n}: {text}"));
182                }
183            }
184            ChangeTag::Delete => {
185                deletions += 1;
186                if let Some(n) = line_no {
187                    changes.push(format!("-{n}: {text}"));
188                }
189            }
190            ChangeTag::Equal => {}
191        }
192    }
193
194    if changes.is_empty() {
195        return "(no changes)".to_string();
196    }
197
198    changes.push(format!("\ndiff +{additions}/-{deletions} lines"));
199    changes.join("\n")
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn test_diff_insertion() {
208        let old = "line1\nline2\nline3";
209        let new = "line1\nline2\nnew_line\nline3";
210        let result = diff_content(old, new);
211        assert!(result.contains("+"), "should show additions");
212        assert!(result.contains("new_line"));
213    }
214
215    #[test]
216    fn test_diff_deletion() {
217        let old = "line1\nline2\nline3";
218        let new = "line1\nline3";
219        let result = diff_content(old, new);
220        assert!(result.contains("-"), "should show deletions");
221        assert!(result.contains("line2"));
222    }
223
224    #[test]
225    fn test_diff_no_changes() {
226        let content = "same\ncontent";
227        assert_eq!(diff_content(content, content), "(no changes)");
228    }
229
230    #[test]
231    fn test_lightweight_cleanup_collapses_braces() {
232        let input = "fn main() {\n    inner()\n}\n}\n}\n}\n}\nfn next() {}";
233        let result = lightweight_cleanup(input);
234        assert!(
235            result.matches('}').count() <= 3,
236            "should collapse consecutive closing braces"
237        );
238        assert!(result.contains("fn next()"));
239    }
240
241    #[test]
242    fn test_lightweight_cleanup_blank_lines() {
243        let input = "line1\n\n\n\n\nline2";
244        let result = lightweight_cleanup(input);
245        let blank_runs = result.split("line1").nth(1).unwrap();
246        let blanks = blank_runs.matches('\n').count();
247        assert!(blanks <= 2, "should collapse multiple blank lines");
248    }
249
250    #[test]
251    fn test_safeguard_ratio_prevents_over_compression() {
252        let original = "a ".repeat(100);
253        let too_compressed = "a";
254        let result = safeguard_ratio(&original, too_compressed);
255        assert_eq!(result, original, "should return original when ratio < 0.15");
256    }
257
258    #[test]
259    fn test_aggressive_strips_comments() {
260        let code = "fn main() {\n    // a comment\n    let x = 1;\n}";
261        let result = aggressive_compress(code, Some("rs"));
262        assert!(!result.contains("// a comment"));
263        assert!(result.contains("let x = 1"));
264    }
265
266    #[test]
267    fn test_aggressive_python_comments() {
268        let code = "def main():\n    # comment\n    x = 1";
269        let result = aggressive_compress(code, Some("py"));
270        assert!(!result.contains("# comment"));
271        assert!(result.contains("x = 1"));
272    }
273
274    #[test]
275    fn test_aggressive_preserves_doc_comments() {
276        let code = "/// Doc comment\nfn main() {}";
277        let result = aggressive_compress(code, Some("rs"));
278        assert!(result.contains("/// Doc comment"));
279    }
280
281    #[test]
282    fn test_aggressive_block_comment() {
283        let code = "/* start\n * middle\n */ end\nfn main() {}";
284        let result = aggressive_compress(code, Some("rs"));
285        assert!(!result.contains("start"));
286        assert!(!result.contains("middle"));
287        assert!(result.contains("fn main()"));
288    }
289
290    #[test]
291    fn test_strip_ansi_removes_escape_codes() {
292        let input = "\x1b[31mERROR\x1b[0m: something failed";
293        let result = strip_ansi(input);
294        assert_eq!(result, "ERROR: something failed");
295        assert!(!result.contains('\x1b'));
296    }
297
298    #[test]
299    fn test_strip_ansi_passthrough_clean_text() {
300        let input = "clean text without escapes";
301        let result = strip_ansi(input);
302        assert_eq!(result, input);
303    }
304
305    #[test]
306    fn test_ansi_density_zero_for_clean() {
307        assert_eq!(ansi_density("hello world"), 0.0);
308    }
309
310    #[test]
311    fn test_ansi_density_nonzero_for_colored() {
312        let input = "\x1b[31mred\x1b[0m";
313        assert!(ansi_density(input) > 0.0);
314    }
315}