1use crate::ast::{BinOp, Expr, Located, Program, Stmt, UnaryOp, located};
5
6pub struct Optimizer {
8 pub tail_recursion: bool,
10 pub constant_folding: bool,
12 pub dead_code_elimination: bool,
14}
15
16impl Optimizer {
17 pub fn new() -> Self {
19 Optimizer {
20 tail_recursion: true,
21 constant_folding: true,
22 dead_code_elimination: true,
23 }
24 }
25
26 pub fn optimize_program(&self, program: &Program) -> Program {
28 let mut optimized = program.clone();
29
30 if self.constant_folding {
32 optimized = self.fold_constants(optimized);
33 }
34
35 if self.dead_code_elimination {
37 optimized = self.eliminate_dead_code(optimized);
38 }
39
40 if self.tail_recursion {
42 optimized = self.optimize_tail_recursion(optimized);
43 }
44
45 optimized
46 }
47
48 fn fold_constants(&self, program: Program) -> Program {
50 program
51 .into_iter()
52 .map(|l| located(l.line, self.fold_stmt(l.stmt)))
53 .collect()
54 }
55
56 fn fold_body(&self, body: Vec<Located>) -> Vec<Located> {
58 body.into_iter()
59 .map(|l| located(l.line, self.fold_stmt(l.stmt)))
60 .collect()
61 }
62
63 fn fold_stmt(&self, stmt: Stmt) -> Stmt {
65 match stmt {
66 Stmt::Set { name, value } => Stmt::Set {
67 name,
68 value: self.fold_expr(value),
69 },
70 Stmt::FuncDef { name, params, body } => Stmt::FuncDef {
71 name,
72 params,
73 body: self.fold_body(body),
74 },
75 Stmt::GeneratorDef { name, params, body } => Stmt::GeneratorDef {
76 name,
77 params,
78 body: self.fold_body(body),
79 },
80 Stmt::Return(expr) => Stmt::Return(self.fold_expr(expr)),
81 Stmt::Yield(expr) => Stmt::Yield(self.fold_expr(expr)),
82 Stmt::While { condition, body } => Stmt::While {
83 condition: self.fold_expr(condition),
84 body: self.fold_body(body),
85 },
86 Stmt::For {
87 var,
88 iterable,
89 body,
90 } => Stmt::For {
91 var,
92 iterable: self.fold_expr(iterable),
93 body: self.fold_body(body),
94 },
95 Stmt::ForIndexed {
96 index_var,
97 value_var,
98 iterable,
99 body,
100 } => Stmt::ForIndexed {
101 index_var,
102 value_var,
103 iterable: self.fold_expr(iterable),
104 body: self.fold_body(body),
105 },
106 Stmt::Expression(expr) => Stmt::Expression(self.fold_expr(expr)),
107 other => other,
108 }
109 }
110
111 #[allow(clippy::only_used_in_recursion)]
113 fn fold_expr(&self, expr: Expr) -> Expr {
114 match expr {
115 Expr::Binary { left, op, right } => {
117 let left = self.fold_expr(*left);
118 let right = self.fold_expr(*right);
119
120 if let (Expr::Number(l), Expr::Number(r)) = (&left, &right)
122 && let Some(result) = Self::eval_const_binary(*l, &op, *r)
123 {
124 return Expr::Number(result);
125 }
126
127 if let (Expr::BigInteger(l), Expr::BigInteger(r)) = (&left, &right)
129 && let Some(result) = Self::eval_const_bigint(l, &op, r)
130 {
131 return Expr::BigInteger(result);
132 }
133
134 Expr::Binary {
135 left: Box::new(left),
136 op,
137 right: Box::new(right),
138 }
139 }
140
141 Expr::Unary { op, expr } => {
143 let expr = self.fold_expr(*expr);
144
145 if let Expr::Number(n) = expr {
146 match op {
147 UnaryOp::Minus => return Expr::Number(-n),
148 UnaryOp::Not => return Expr::Boolean(n == 0.0),
149 }
150 }
151
152 if let (UnaryOp::Not, Expr::Boolean(b)) = (&op, &expr) {
153 return Expr::Boolean(!b);
154 }
155
156 Expr::Unary {
157 op,
158 expr: Box::new(expr),
159 }
160 }
161
162 Expr::Call { func, args } => Expr::Call {
164 func: Box::new(self.fold_expr(*func)),
165 args: args.into_iter().map(|e| self.fold_expr(e)).collect(),
166 },
167
168 Expr::Array(elements) => {
169 Expr::Array(elements.into_iter().map(|e| self.fold_expr(e)).collect())
170 }
171
172 Expr::Index { object, index } => Expr::Index {
173 object: Box::new(self.fold_expr(*object)),
174 index: Box::new(self.fold_expr(*index)),
175 },
176
177 other => other,
178 }
179 }
180
181 fn eval_const_binary(left: f64, op: &BinOp, right: f64) -> Option<f64> {
183 match op {
184 BinOp::Add => Some(left + right),
185 BinOp::Subtract => Some(left - right),
186 BinOp::Multiply => Some(left * right),
187 BinOp::Divide if right != 0.0 => Some(left / right),
188 BinOp::Modulo if right != 0.0 => Some(left % right),
189 _ => None,
190 }
191 }
192
193 fn eval_const_bigint(
195 left: &num_bigint::BigInt,
196 op: &BinOp,
197 right: &num_bigint::BigInt,
198 ) -> Option<num_bigint::BigInt> {
199 match op {
200 BinOp::Add => Some(left + right),
201 BinOp::Subtract => Some(left - right),
202 BinOp::Multiply => Some(left * right),
203 _ => None,
204 }
205 }
206
207 fn eliminate_dead_code(&self, program: Program) -> Program {
209 program
210 .into_iter()
211 .filter_map(|l| self.eliminate_dead_located(l))
212 .collect()
213 }
214
215 fn eliminate_dead_located(&self, l: Located) -> Option<Located> {
217 self.eliminate_dead_stmt(l.stmt)
218 .map(|stmt| located(l.line, stmt))
219 }
220
221 fn eliminate_dead_body(&self, body: Vec<Located>) -> Vec<Located> {
227 let mut out = Vec::new();
228 for l in body {
229 let is_return = matches!(l.stmt, Stmt::Return(_));
230 if let Some(processed) = self.eliminate_dead_located(l) {
231 out.push(processed);
232 }
233 if is_return {
234 break; }
236 }
237 out
238 }
239
240 fn eliminate_dead_stmt(&self, stmt: Stmt) -> Option<Stmt> {
242 match stmt {
243 Stmt::While { condition, body } => {
245 if let Expr::Boolean(false) = condition {
246 return None;
248 }
249
250 Some(Stmt::While {
251 condition,
252 body: self.eliminate_dead_body(body),
253 })
254 }
255
256 Stmt::FuncDef { name, params, body } => Some(Stmt::FuncDef {
258 name,
259 params,
260 body: self.eliminate_dead_body(body),
261 }),
262
263 Stmt::GeneratorDef { name, params, body } => Some(Stmt::GeneratorDef {
264 name,
265 params,
266 body: self.eliminate_dead_body(body),
267 }),
268
269 Stmt::Expression(expr) => Some(Stmt::Expression(self.eliminate_dead_expr(expr))),
271
272 other => Some(other),
273 }
274 }
275
276 fn eliminate_dead_expr(&self, expr: Expr) -> Expr {
278 match expr {
279 Expr::If {
280 condition,
281 then_branch,
282 elif_branches,
283 else_branch,
284 } => {
285 if let Expr::Boolean(true) = *condition {
286 return Expr::If {
288 condition: Box::new(Expr::Boolean(true)),
289 then_branch,
290 elif_branches: vec![],
291 else_branch: None,
292 };
293 }
294
295 if let Expr::Boolean(false) = *condition {
296 if let Some(else_body) = else_branch {
298 return Expr::If {
300 condition: Box::new(Expr::Boolean(true)),
301 then_branch: else_body,
302 elif_branches: vec![],
303 else_branch: None,
304 };
305 }
306 return Expr::Null;
308 }
309
310 Expr::If {
312 condition,
313 then_branch: self.eliminate_dead_body(then_branch),
314 elif_branches: elif_branches
315 .into_iter()
316 .map(|(c, b)| (self.eliminate_dead_expr(c), self.eliminate_dead_body(b)))
317 .collect(),
318 else_branch: else_branch.map(|b| self.eliminate_dead_body(b)),
319 }
320 }
321 other => other,
322 }
323 }
324
325 fn optimize_tail_recursion(&self, program: Program) -> Program {
327 program
328 .into_iter()
329 .map(|l| located(l.line, self.optimize_tail_recursive_stmt(l.stmt, l.line)))
330 .collect()
331 }
332
333 fn optimize_tail_recursive_stmt(&self, stmt: Stmt, stmt_line: usize) -> Stmt {
338 match stmt {
339 Stmt::FuncDef { name, params, body } => {
340 if self.is_tail_recursive(&name, &body) {
342 Stmt::FuncDef {
344 name: name.clone(),
345 params: params.clone(),
346 body: self.convert_tail_recursion_to_loop(&name, ¶ms, body, stmt_line),
347 }
348 } else {
349 Stmt::FuncDef { name, params, body }
350 }
351 }
352 other => other,
353 }
354 }
355
356 fn is_tail_recursive(&self, func_name: &str, body: &[Located]) -> bool {
358 if body.is_empty() {
359 return false;
360 }
361
362 self.has_tail_recursion_in_body(func_name, body)
364 }
365
366 fn has_tail_recursion_in_body(&self, func_name: &str, body: &[Located]) -> bool {
368 body.iter()
370 .any(|l| self.stmt_has_tail_recursion(func_name, &l.stmt))
371 }
372
373 fn stmt_has_tail_recursion(&self, func_name: &str, stmt: &Stmt) -> bool {
381 match stmt {
382 Stmt::Return(expr) => self.is_tail_call(func_name, expr),
383 Stmt::Expression(expr) => self.expr_has_tail_recursion(func_name, expr),
384 _ => false,
385 }
386 }
387
388 fn expr_has_tail_recursion(&self, func_name: &str, expr: &Expr) -> bool {
390 match expr {
391 Expr::If {
392 then_branch,
393 elif_branches,
394 else_branch,
395 ..
396 } => {
397 let then_tail = self.has_tail_recursion_in_body(func_name, then_branch);
399 let elif_tail = elif_branches
400 .iter()
401 .any(|(_, body)| self.has_tail_recursion_in_body(func_name, body));
402 let else_tail = else_branch
403 .as_ref()
404 .map(|body| self.has_tail_recursion_in_body(func_name, body))
405 .unwrap_or(false);
406
407 then_tail || elif_tail || else_tail
408 }
409 _ => false,
410 }
411 }
412
413 fn is_tail_call(&self, func_name: &str, expr: &Expr) -> bool {
415 match expr {
416 Expr::Call { func, .. } => {
418 if let Expr::Identifier(name) = &**func {
419 name == func_name
420 } else {
421 false
422 }
423 }
424 Expr::If {
426 then_branch,
427 elif_branches,
428 else_branch,
429 ..
430 } => {
431 let then_is_tail = self.branch_ends_with_tail_call(func_name, then_branch);
433
434 let elif_all_tail = elif_branches
435 .iter()
436 .all(|(_, body)| self.branch_ends_with_tail_call(func_name, body));
437
438 let else_is_tail = else_branch
439 .as_ref()
440 .map(|body| self.branch_ends_with_tail_call(func_name, body))
441 .unwrap_or(true);
442
443 then_is_tail && elif_all_tail && else_is_tail
444 }
445 _ => false,
446 }
447 }
448
449 fn branch_ends_with_tail_call(&self, func_name: &str, branch: &[Located]) -> bool {
451 if let Some(last) = branch.last() {
452 match &last.stmt {
453 Stmt::Return(expr) => self.is_tail_call(func_name, expr),
454 Stmt::Expression(expr) => {
455 self.is_tail_call(func_name, expr)
457 }
458 _ => false,
459 }
460 } else {
461 false
462 }
463 }
464
465 fn convert_tail_recursion_to_loop(
469 &self,
470 func_name: &str,
471 params: &[String],
472 body: Vec<Located>,
473 func_line: usize,
474 ) -> Vec<Located> {
475 let mut new_body = Vec::new();
477
478 for param in params {
480 new_body.push(located(
481 func_line,
482 Stmt::Set {
483 name: format!("_loop_{}", param),
484 value: Expr::Identifier(param.clone()),
485 },
486 ));
487 }
488
489 new_body.push(located(
491 func_line,
492 Stmt::Set {
493 name: "_loop_continue".to_string(),
494 value: Expr::Boolean(true),
495 },
496 ));
497
498 let loop_body = self.transform_body_to_loop(func_name, params, body);
500
501 new_body.push(located(
503 func_line,
504 Stmt::While {
505 condition: Expr::Identifier("_loop_continue".to_string()),
506 body: loop_body,
507 },
508 ));
509
510 new_body
511 }
512
513 fn transform_body_to_loop(
515 &self,
516 func_name: &str,
517 params: &[String],
518 body: Vec<Located>,
519 ) -> Vec<Located> {
520 let mut loop_body = Vec::new();
521
522 for l in body {
523 let line = l.line;
524 match l.stmt {
525 Stmt::Return(expr) => {
526 if let Some(new_args) = self.extract_tail_call_args(func_name, &expr) {
528 for (i, param) in params.iter().enumerate() {
530 if let Some(arg) = new_args.get(i) {
531 loop_body.push(located(
532 line,
533 Stmt::Set {
534 name: format!("_loop_{}", param),
535 value: arg.clone(),
536 },
537 ));
538 }
539 }
540
541 for param in params {
543 loop_body.push(located(
544 line,
545 Stmt::Set {
546 name: param.clone(),
547 value: Expr::Identifier(format!("_loop_{}", param)),
548 },
549 ));
550 }
551
552 loop_body.push(located(line, Stmt::Continue));
556 } else {
557 loop_body.push(located(
559 line,
560 Stmt::Set {
561 name: "_loop_continue".to_string(),
562 value: Expr::Boolean(false),
563 },
564 ));
565 loop_body.push(located(line, Stmt::Return(expr)));
566 }
567 }
568 stmt => {
569 loop_body.push(located(
571 line,
572 self.transform_stmt_for_loop(func_name, params, stmt),
573 ));
574 }
575 }
576 }
577
578 loop_body
579 }
580
581 fn extract_tail_call_args(&self, func_name: &str, expr: &Expr) -> Option<Vec<Expr>> {
583 match expr {
584 Expr::Call { func, args } => {
585 if let Expr::Identifier(name) = &**func
586 && name == func_name
587 {
588 return Some(args.clone());
589 }
590 None
591 }
592 _ => None,
593 }
594 }
595
596 fn transform_stmt_for_loop(&self, func_name: &str, params: &[String], stmt: Stmt) -> Stmt {
602 match stmt {
603 Stmt::Expression(expr) => {
604 Stmt::Expression(self.transform_expr_for_loop(func_name, params, expr))
606 }
607 other => other,
608 }
609 }
610
611 fn transform_expr_for_loop(&self, func_name: &str, params: &[String], expr: Expr) -> Expr {
613 match expr {
614 Expr::If {
615 condition,
616 then_branch,
617 elif_branches,
618 else_branch,
619 } => Expr::If {
620 condition,
621 then_branch: self.transform_body_to_loop(func_name, params, then_branch),
622 elif_branches: elif_branches
623 .into_iter()
624 .map(|(cond, body)| {
625 (cond, self.transform_body_to_loop(func_name, params, body))
626 })
627 .collect(),
628 else_branch: else_branch
629 .map(|body| self.transform_body_to_loop(func_name, params, body)),
630 },
631 other => other,
632 }
633 }
634}
635
636impl Default for Optimizer {
637 fn default() -> Self {
638 Self::new()
639 }
640}
641
642#[cfg(test)]
644mod tests {
645 use super::*;
646
647 #[test]
648 fn test_constant_folding() {
649 let optimizer = Optimizer::new();
650
651 let expr = Expr::Binary {
653 left: Box::new(Expr::Number(2.0)),
654 op: BinOp::Add,
655 right: Box::new(Expr::Number(3.0)),
656 };
657
658 let folded = optimizer.fold_expr(expr);
659 assert_eq!(folded, Expr::Number(5.0));
660 }
661
662 #[test]
663 fn test_dead_code_elimination() {
664 let optimizer = Optimizer::new();
665
666 let stmt = Stmt::While {
668 condition: Expr::Boolean(false),
669 body: vec![located(
670 1,
671 Stmt::Set {
672 name: "x".to_string(),
673 value: Expr::Number(10.0),
674 },
675 )],
676 };
677
678 let result = optimizer.eliminate_dead_stmt(stmt);
679 assert!(result.is_none());
680 }
681
682 #[test]
683 fn test_tail_recursion_detection() {
684 let optimizer = Optimizer::new();
685
686 let body = vec![located(
688 1,
689 Stmt::Return(Expr::Call {
690 func: Box::new(Expr::Identifier("factorial".to_string())),
691 args: vec![
692 Expr::Binary {
693 left: Box::new(Expr::Identifier("n".to_string())),
694 op: BinOp::Subtract,
695 right: Box::new(Expr::Number(1.0)),
696 },
697 Expr::Binary {
698 left: Box::new(Expr::Identifier("acc".to_string())),
699 op: BinOp::Multiply,
700 right: Box::new(Expr::Identifier("n".to_string())),
701 },
702 ],
703 }),
704 )];
705
706 assert!(optimizer.is_tail_recursive("factorial", &body));
707 }
708
709 #[test]
710 fn test_non_tail_recursion_detection() {
711 let optimizer = Optimizer::new();
712
713 let body = vec![located(
715 1,
716 Stmt::Return(Expr::Binary {
717 left: Box::new(Expr::Identifier("n".to_string())),
718 op: BinOp::Multiply,
719 right: Box::new(Expr::Call {
720 func: Box::new(Expr::Identifier("factorial".to_string())),
721 args: vec![Expr::Binary {
722 left: Box::new(Expr::Identifier("n".to_string())),
723 op: BinOp::Subtract,
724 right: Box::new(Expr::Number(1.0)),
725 }],
726 }),
727 }),
728 )];
729
730 assert!(!optimizer.is_tail_recursive("factorial", &body));
731 }
732
733 #[test]
734 fn test_tail_recursion_in_if() {
735 let optimizer = Optimizer::new();
736
737 let body = vec![located(
741 1,
742 Stmt::Expression(Expr::If {
743 condition: Box::new(Expr::Binary {
744 left: Box::new(Expr::Identifier("n".to_string())),
745 op: BinOp::LessEqual,
746 right: Box::new(Expr::Number(0.0)),
747 }),
748 then_branch: vec![located(
749 1,
750 Stmt::Return(Expr::Identifier("acc".to_string())),
751 )],
752 elif_branches: vec![],
753 else_branch: Some(vec![located(
754 1,
755 Stmt::Return(Expr::Call {
756 func: Box::new(Expr::Identifier("sum".to_string())),
757 args: vec![
758 Expr::Binary {
759 left: Box::new(Expr::Identifier("n".to_string())),
760 op: BinOp::Subtract,
761 right: Box::new(Expr::Number(1.0)),
762 },
763 Expr::Binary {
764 left: Box::new(Expr::Identifier("acc".to_string())),
765 op: BinOp::Add,
766 right: Box::new(Expr::Identifier("n".to_string())),
767 },
768 ],
769 }),
770 )]),
771 }),
772 )];
773
774 assert!(optimizer.is_tail_recursive("sum", &body));
775 }
776
777 #[test]
778 fn test_tail_recursion_optimization_transform() {
779 let optimizer = Optimizer::new();
780
781 let func_def = Stmt::FuncDef {
783 name: "factorial".to_string(),
784 params: vec!["n".to_string(), "acc".to_string()],
785 body: vec![located(
786 1,
787 Stmt::Return(Expr::Call {
788 func: Box::new(Expr::Identifier("factorial".to_string())),
789 args: vec![
790 Expr::Binary {
791 left: Box::new(Expr::Identifier("n".to_string())),
792 op: BinOp::Subtract,
793 right: Box::new(Expr::Number(1.0)),
794 },
795 Expr::Binary {
796 left: Box::new(Expr::Identifier("acc".to_string())),
797 op: BinOp::Multiply,
798 right: Box::new(Expr::Identifier("n".to_string())),
799 },
800 ],
801 }),
802 )],
803 };
804
805 let optimized = optimizer.optimize_tail_recursive_stmt(func_def, 1);
806
807 if let Stmt::FuncDef { body, .. } = optimized {
809 assert!(
812 body.len() >= 3,
813 "Expected at least 3 statements, got {}",
814 body.len()
815 );
816
817 if let Some(Located {
819 stmt: Stmt::While { .. },
820 ..
821 }) = body.last()
822 {
823 } else {
825 panic!("Expected While loop at the end of optimized function body");
826 }
827 } else {
828 panic!("Expected FuncDef");
829 }
830 }
831}