Skip to main content

jsx_generator/
optimizer.rs

1use crate::error::{GeneratorError, GeneratorResult};
2use jsxbin_parser::types::Token;
3use log::{debug, trace};
4
5/// Configuration for code optimization
6#[derive(Debug, Clone)]
7pub struct OptimizerConfig {
8    pub dead_code_elimination: bool,
9    pub constant_folding: bool,
10    pub inline_simple_functions: bool,
11    pub remove_unused_vars: bool,
12}
13
14impl Default for OptimizerConfig {
15    fn default() -> Self {
16        OptimizerConfig {
17            dead_code_elimination: true,
18            constant_folding: true,
19            inline_simple_functions: false,
20            remove_unused_vars: false,
21        }
22    }
23}
24
25/// Optimizes JSX AST
26pub struct CodeOptimizer {
27    config: OptimizerConfig,
28}
29
30impl CodeOptimizer {
31    /// Create a new code optimizer
32    pub fn new(config: OptimizerConfig) -> Self {
33        CodeOptimizer { config }
34    }
35
36    /// Create with default config
37    pub fn default() -> Self {
38        Self::new(OptimizerConfig::default())
39    }
40
41    /// Optimize a token
42    pub fn optimize_token(&self, token: &Token) -> GeneratorResult<Token> {
43        match token {
44            // Constant folding for simple operations
45            Token::BinaryOperation {
46                left,
47                operator,
48                right,
49            } => {
50                if self.config.constant_folding {
51                    if let (
52                        Token::NumberLiteral(l),
53                        Token::NumberLiteral(r),
54                    ) = (&*left.token, &*right.token)
55                    {
56                        let result = self.fold_numeric_operation(*l, operator, *r)?;
57                        return Ok(Token::NumberLiteral(result));
58                    }
59                }
60                Ok(token.clone())
61            }
62
63            // Optimize function calls
64            Token::FunctionCall { .. } => {
65                // TODO: Inline simple functions if config enabled
66                Ok(token.clone())
67            }
68
69            // Optimize conditionals
70            Token::IfStatement {
71                condition,
72                consequent,
73                alternate,
74            } => {
75                if self.config.dead_code_elimination {
76                    // Check if condition is a constant
77                    if let Token::BooleanLiteral(b) = &*condition.token {
78                        if *b {
79                            // Condition always true - return consequent only
80                            return Ok(Token::Block(*consequent.clone()));
81                        } else if let Some(alt) = alternate {
82                            // Condition always false - return alternate
83                            return Ok(Token::Block(*alt.clone()));
84                        }
85                    }
86                }
87                Ok(token.clone())
88            }
89
90            // Default: no optimization
91            _ => Ok(token.clone()),
92        }
93    }
94
95    /// Optimize a token stream
96    pub fn optimize_tokens(&self, tokens: &[Token]) -> GeneratorResult<Vec<Token>> {
97        debug!("Optimizing {} tokens", tokens.len());
98
99        let mut optimized = Vec::new();
100
101        for token in tokens {
102            match token {
103                // Skip dead code after return/break/continue
104                Token::ReturnStatement(_) | Token::BreakStatement | Token::ContinueStatement => {
105                    optimized.push(token.clone());
106                    if self.config.dead_code_elimination {
107                        trace!("Dead code after control flow statement will be removed");
108                        break;
109                    }
110                }
111
112                // Optimize and keep other tokens
113                _ => {
114                    let optimized_token = self.optimize_token(token)?;
115                    optimized.push(optimized_token);
116                }
117            }
118        }
119
120        debug!("Optimization complete: {} -> {} tokens", tokens.len(), optimized.len());
121        Ok(optimized)
122    }
123
124    pub fn fold_numeric_operation(
125        &self,
126        left: f64,
127        operator: &str,
128        right: f64,
129    ) -> GeneratorResult<f64> {
130        let result = match operator {
131            "+" => left + right,
132            "-" => left - right,
133            "*" => left * right,
134            "/" => {
135                if right != 0.0 {
136                    left / right
137                } else {
138                    f64::INFINITY
139                }
140            }
141            "%" => {
142                if right != 0.0 {
143                    left % right
144                } else {
145                    f64::NAN
146                }
147            }
148            _ => return Err(GeneratorError::CodeGenerationFailed(
149                format!("Unknown operator: {}", operator),
150            )),
151        };
152        Ok(result)
153    }
154}
155
156/// Analysis results from code optimizer
157#[derive(Debug, Clone)]
158pub struct AnalysisResult {
159    pub has_dead_code: bool,
160    pub unused_variables: Vec<String>,
161    pub function_calls: Vec<String>,
162    pub string_count: usize,
163    pub numeric_count: usize,
164}
165
166impl CodeOptimizer {
167    /// Analyze code for optimization opportunities
168    pub fn analyze(&self, tokens: &[Token]) -> AnalysisResult {
169        let mut result = AnalysisResult {
170            has_dead_code: false,
171            unused_variables: Vec::new(),
172            function_calls: Vec::new(),
173            string_count: 0,
174            numeric_count: 0,
175        };
176
177        let mut found_control_flow = false;
178
179        for token in tokens {
180            match token {
181                Token::StringLiteral(_) => result.string_count += 1,
182                Token::NumberLiteral(_) => result.numeric_count += 1,
183                Token::FunctionCall { callee, .. } => {
184                    if let Token::Identifier(name) = &*callee.token {
185                        result.function_calls.push(name.clone());
186                    }
187                }
188                Token::ReturnStatement(_) | Token::BreakStatement | Token::ContinueStatement => {
189                    found_control_flow = true;
190                }
191                _ => {}
192            }
193        }
194
195        result.has_dead_code = found_control_flow;
196        result
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn test_constant_folding() {
206        let optimizer = CodeOptimizer::default();
207
208        let result = optimizer
209            .fold_numeric_operation(2.0, "+", 3.0)
210            .unwrap();
211        assert_eq!(result, 5.0);
212
213        let result = optimizer
214            .fold_numeric_operation(10.0, "-", 3.0)
215            .unwrap();
216        assert_eq!(result, 7.0);
217
218        let result = optimizer
219            .fold_numeric_operation(4.0, "*", 5.0)
220            .unwrap();
221        assert_eq!(result, 20.0);
222    }
223
224    #[test]
225    fn test_dead_code_elimination() {
226        let optimizer = CodeOptimizer::default();
227
228        let tokens = vec![
229            Token::ReturnStatement(None),
230            Token::BooleanLiteral(true), // Dead code
231        ];
232
233        let optimized = optimizer.optimize_tokens(&tokens).unwrap();
234        assert_eq!(optimized.len(), 1);
235    }
236
237    #[test]
238    fn test_analysis() {
239        let optimizer = CodeOptimizer::default();
240
241        let tokens = vec![
242            Token::StringLiteral("hello".to_string()),
243            Token::NumberLiteral(42.0),
244        ];
245
246        let analysis = optimizer.analyze(&tokens);
247        assert_eq!(analysis.string_count, 1);
248        assert_eq!(analysis.numeric_count, 1);
249    }
250}