1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/// Code optimization module
use anyhow::Result;
pub fn optimize_code(code: &str, level: u8) -> Result<String> {
match level {
0 => Ok(code.to_string()),
1 => {
// Basic optimization: remove line comments
let result: _ = code
.lines()
.map(|line| {
// Find the position of // and remove everything from there
if let Some(pos) = line.find("//") {
// Check if it's inside a string literal
let before_comment: _ = &line[..pos];
let mut in_string = false;
let mut string_char = '\0';
let _inside_string: _ = false;
for (i, c) in before_comment.chars().enumerate() {
if c == '"' || c == '\'' {
if !in_string {
in_string = true;
string_char = c;
} else if c == string_char {
// Check if it's escaped
if i > 0 && before_comment.chars().nth(i - 1) != Some('\\') {
in_string = false;
}
}
}
}
if !in_string {
line[..pos].trim_end()
} else {
line
}
} else {
line
}
})
.collect::<Vec<_>>()
.join("\n");
Ok(result)
}
2 => {
// Medium optimization: remove comments and extra whitespace
let lines: Vec<&str> = code.lines()
.filter(|line| {
let trimmed: _ = line.trim();
!trimmed.starts_with("//") && !trimmed.starts_with("/*")
})
.map(|line| line.trim())
.filter(|line| !line.is_empty())
.collect();
Ok(lines.join(" "))
}
3 => {
// Aggressive optimization: minify
let mut result = String::new();
let mut in_string = false;
let mut string_char = '\0';
for c in code.chars() {
match c {
'"' | '\'' if !in_string => {
in_string = true;
string_char = c;
result.push(c);
}
c if in_string && c == string_char => {
in_string = false;
result.push(c);
}
c if !in_string => {
if !c.is_whitespace() || c == '\n' {
result.push(c);
}
}
_ => result.push(c),
}
}
Ok(result)
}
_ => Ok(code.to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::{HashMap, BTreeMap};
#[test]
fn test_optimize_level_0() {
let code: _ = "console.log('test'); // comment";
let result: _ = optimize_code(code, 0).unwrap();
assert!(result.contains("// comment"));
}
#[test]
fn test_optimize_level_1() {
let code: _ = "console.log('test'); // comment";
let result: _ = optimize_code(code, 1).unwrap();
assert!(!result.contains("// comment"));
}
}