Skip to main content

aether/
optimizer.rs

1// src/optimizer.rs
2//! 代码优化器 - 包含尾递归优化、常量折叠等
3
4use crate::ast::{BinOp, Expr, Located, Program, Stmt, UnaryOp, located};
5
6/// 代码优化器
7pub struct Optimizer {
8    /// 是否启用尾递归优化
9    pub tail_recursion: bool,
10    /// 是否启用常量折叠
11    pub constant_folding: bool,
12    /// 是否启用死代码消除
13    pub dead_code_elimination: bool,
14}
15
16impl Optimizer {
17    /// 创建新的优化器,所有优化默认启用
18    pub fn new() -> Self {
19        Optimizer {
20            tail_recursion: true,
21            constant_folding: true,
22            dead_code_elimination: true,
23        }
24    }
25
26    /// 优化整个程序
27    pub fn optimize_program(&self, program: &Program) -> Program {
28        let mut optimized = program.clone();
29
30        // 常量折叠
31        if self.constant_folding {
32            optimized = self.fold_constants(optimized);
33        }
34
35        // 死代码消除
36        if self.dead_code_elimination {
37            optimized = self.eliminate_dead_code(optimized);
38        }
39
40        // 尾递归优化
41        if self.tail_recursion {
42            optimized = self.optimize_tail_recursion(optimized);
43        }
44
45        optimized
46    }
47
48    /// 常量折叠优化
49    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    /// 折叠语句体中的常量,保留每条语句的行号
57    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    /// 折叠语句中的常量
64    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    /// 折叠表达式中的常量
112    #[allow(clippy::only_used_in_recursion)]
113    fn fold_expr(&self, expr: Expr) -> Expr {
114        match expr {
115            // 二元运算常量折叠
116            Expr::Binary { left, op, right } => {
117                let left = self.fold_expr(*left);
118                let right = self.fold_expr(*right);
119
120                // 如果两边都是常量,直接计算结果
121                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                // 大整数常量折叠(Add/Subtract/Multiply;Divide 保持运行期 Fraction 语义)
128                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            // 一元运算常量折叠
142            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            // 递归处理其他表达式
163            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    /// 计算常量二元运算
182    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    /// 大整数常量折叠:只折叠保持整数语义的运算
194    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    /// 死代码消除
208    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    /// 消除死语句并保留行号
216    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    /// 消除语句体中的死代码并保留行号
222    ///
223    /// 额外规则:**无条件 `Return` 之后的语句一律删除**(本就不可达)。
224    /// 这同时是尾递归改写正确性的前提——改写后尾调用等价于循环继续,
225    /// 若不删掉其后的语句,它们会在每轮迭代中复活执行。
226    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; // 之后全部不可达
235            }
236        }
237        out
238    }
239
240    /// 消除死语句
241    fn eliminate_dead_stmt(&self, stmt: Stmt) -> Option<Stmt> {
242        match stmt {
243            // While循环的常量条件
244            Stmt::While { condition, body } => {
245                if let Expr::Boolean(false) = condition {
246                    // 永远不执行的循环可以删除
247                    return None;
248                }
249
250                Some(Stmt::While {
251                    condition,
252                    body: self.eliminate_dead_body(body),
253                })
254            }
255
256            // 函数定义递归处理
257            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            // 表达式语句中可能包含If表达式
270            Stmt::Expression(expr) => Some(Stmt::Expression(self.eliminate_dead_expr(expr))),
271
272            other => Some(other),
273        }
274    }
275
276    /// 消除表达式中的死代码
277    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                    // 条件永远为真,简化为then分支
287                    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                    // 条件永远为假,检查elif或else
297                    if let Some(else_body) = else_branch {
298                        // 简化为else块
299                        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                    // 没有else,返回null
307                    return Expr::Null;
308                }
309
310                // 递归处理分支
311                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    /// 尾递归优化
326    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    /// 优化尾递归语句
334    ///
335    /// `stmt_line` 为该语句的源码行号,仅在 FuncDef 被改写为循环时用于
336    /// 给合成语句(循环变量初始化、While 骨架)标注行号
337    fn optimize_tail_recursive_stmt(&self, stmt: Stmt, stmt_line: usize) -> Stmt {
338        match stmt {
339            Stmt::FuncDef { name, params, body } => {
340                // 检查函数体是否包含尾递归
341                if self.is_tail_recursive(&name, &body) {
342                    // 转换为迭代形式
343                    Stmt::FuncDef {
344                        name: name.clone(),
345                        params: params.clone(),
346                        body: self.convert_tail_recursion_to_loop(&name, &params, body, stmt_line),
347                    }
348                } else {
349                    Stmt::FuncDef { name, params, body }
350                }
351            }
352            other => other,
353        }
354    }
355
356    /// 检查是否为尾递归
357    fn is_tail_recursive(&self, func_name: &str, body: &[Located]) -> bool {
358        if body.is_empty() {
359            return false;
360        }
361
362        // 递归检查所有可能的返回路径
363        self.has_tail_recursion_in_body(func_name, body)
364    }
365
366    /// 检查函数体中是否包含尾递归
367    fn has_tail_recursion_in_body(&self, func_name: &str, body: &[Located]) -> bool {
368        // 至少需要有一条return语句包含尾递归调用
369        body.iter()
370            .any(|l| self.stmt_has_tail_recursion(func_name, &l.stmt))
371    }
372
373    /// 检查语句是否包含尾递归
374    ///
375    /// 只检查**函数体顶层**的 Return / If 表达式,不下降进入
376    /// While/For 循环体——循环内的尾调用保持解释执行:
377    /// 改写为「参数更新 + 落空继续」会破坏循环的正常退出路径
378    /// (无法跳出内层循环、循环内后续语句被错误重复执行),
379    /// 正确性优先于优化覆盖率。
380    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    /// 检查表达式是否包含尾递归
389    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                // 检查所有分支
398                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    /// 检查表达式是否为尾调用(增强版)
414    fn is_tail_call(&self, func_name: &str, expr: &Expr) -> bool {
415        match expr {
416            // 直接的递归调用
417            Expr::Call { func, .. } => {
418                if let Expr::Identifier(name) = &**func {
419                    name == func_name
420                } else {
421                    false
422                }
423            }
424            // 条件表达式中的尾调用
425            Expr::If {
426                then_branch,
427                elif_branches,
428                else_branch,
429                ..
430            } => {
431                // 所有分支都必须是尾调用或没有返回值
432                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    /// 检查分支是否以尾调用结束
450    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                    // 表达式可能是If表达式
456                    self.is_tail_call(func_name, expr)
457                }
458                _ => false,
459            }
460        } else {
461            false
462        }
463    }
464
465    /// 将尾递归转换为循环 (完整实现)
466    ///
467    /// `func_line` 为函数定义所在行,用于合成语句的行号标注
468    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        // 步骤1: 为每个参数创建临时变量
476        let mut new_body = Vec::new();
477
478        // 初始化临时变量
479        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        // 步骤2: 创建循环标志
490        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        // 步骤3: 转换函数体为while循环
499        let loop_body = self.transform_body_to_loop(func_name, params, body);
500
501        // 步骤4: 创建while循环
502        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    /// 转换函数体为循环体
514    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                    // 检查是否为尾递归调用
527                    if let Some(new_args) = self.extract_tail_call_args(func_name, &expr) {
528                        // 这是尾递归调用,转换为参数更新
529                        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                        // 更新参数值
542                        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                        // 继续循环:Continue 绑定到合成的 While,
553                        // 跳过本轮剩余语句(检测已保证此处不在嵌套循环内,
554                        // 且死代码消除已删去 Return 之后的不可达语句)
555                        loop_body.push(located(line, Stmt::Continue));
556                    } else {
557                        // 这不是尾递归调用,正常返回
558                        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                    // 其他语句递归转换
570                    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    /// 提取尾调用的参数
582    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    /// 转换语句以适应循环结构
597    ///
598    /// 只转换顶层的 If 表达式分支;**不下降进入 While/For 循环体**
599    /// (检测阶段已保证函数仅在顶层存在尾调用,循环体保持原样,
600    /// 其中的递归调用按普通调用解释执行)。
601    fn transform_stmt_for_loop(&self, func_name: &str, params: &[String], stmt: Stmt) -> Stmt {
602        match stmt {
603            Stmt::Expression(expr) => {
604                // 处理If表达式
605                Stmt::Expression(self.transform_expr_for_loop(func_name, params, expr))
606            }
607            other => other,
608        }
609    }
610
611    /// 转换表达式以适应循环结构
612    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// 此处保留之测试代码都为测试私有函数者
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    #[test]
648    fn test_constant_folding() {
649        let optimizer = Optimizer::new();
650
651        // 测试: 2 + 3 应该折叠为 5
652        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        // While False 应该被删除
667        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        // 测试简单的尾递归
687        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        // 测试非尾递归(递归调用后还有操作)
714        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        // 测试If表达式中的尾递归
738        // 实际上Aether中Return语句后面跟的是表达式,而If是表达式
739        // 所以我们需要Return一个If表达式
740        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        // 创建一个简单的尾递归函数
782        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        // 验证转换后包含While循环
808        if let Stmt::FuncDef { body, .. } = optimized {
809            // 应该包含临时变量初始化、循环标志和while循环
810            // 2个参数 = 2个临时变量 + 1个循环标志 + 1个while循环 = 4个语句
811            assert!(
812                body.len() >= 3,
813                "Expected at least 3 statements, got {}",
814                body.len()
815            );
816
817            // 最后一个语句应该是While循环
818            if let Some(Located {
819                stmt: Stmt::While { .. },
820                ..
821            }) = body.last()
822            {
823                // 成功转换为循环
824            } else {
825                panic!("Expected While loop at the end of optimized function body");
826            }
827        } else {
828            panic!("Expected FuncDef");
829        }
830    }
831}