Skip to main content

aver/
tco.rs

1/// Tail-call optimization transform pass.
2///
3/// Runs after parsing, before type-checking. Uses the call graph SCC analysis
4/// to find groups of mutually-recursive functions, then rewrites tail-position
5/// calls within each SCC from `FnCall` to `TailCall`.
6///
7/// A call is in tail position if its result is the direct return value of the
8/// function — no further computation wraps it. Specifically:
9///   - The last `Stmt::Expr` in `FnBody::Block`
10///   - Each arm body of a `match` in tail position
11use std::collections::HashSet;
12
13use crate::ast::*;
14use crate::call_graph;
15
16/// Transform all eligible tail calls in the program.
17pub fn transform_program(items: &mut [TopLevel]) {
18    let groups = call_graph::find_tco_groups(items);
19    if groups.is_empty() {
20        return;
21    }
22
23    // Build a map: fn_name → set of SCC peers (including self)
24    let mut fn_to_scc: std::collections::HashMap<String, &HashSet<String>> =
25        std::collections::HashMap::new();
26    for group in &groups {
27        for name in group {
28            fn_to_scc.insert(name.clone(), group);
29        }
30    }
31
32    for item in items.iter_mut() {
33        if let TopLevel::FnDef(fd) = item
34            && let Some(scc_members) = fn_to_scc.get(&fd.name)
35        {
36            transform_fn(fd, scc_members);
37        }
38    }
39}
40
41fn transform_fn(fd: &mut FnDef, scc_members: &HashSet<String>) {
42    let mut body = fd.body.as_ref().clone();
43    // Only the last Stmt::Expr is in tail position
44    if let Some(expr) = body.tail_expr_mut() {
45        transform_tail_expr(expr, scc_members);
46    }
47    fd.body = std::rc::Rc::new(body);
48}
49
50/// Recursively transform an expression in tail position.
51fn transform_tail_expr(expr: &mut Expr, scc_members: &HashSet<String>) {
52    match expr {
53        // Direct call: `f(args)` where f is Ident in SCC
54        Expr::FnCall(fn_expr, args) => {
55            if let Expr::Ident(name) = fn_expr.as_ref()
56                && scc_members.contains(name)
57            {
58                let name = name.clone();
59                let args = std::mem::take(args);
60                *expr = Expr::TailCall(Box::new((name, args)));
61            }
62        }
63        // Match: each arm body is in tail position
64        Expr::Match { arms, .. } => {
65            for arm in arms {
66                transform_tail_expr(&mut arm.body, scc_members);
67            }
68        }
69        // Everything else is not a tail call
70        _ => {}
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    fn parse(src: &str) -> Vec<TopLevel> {
79        let mut lexer = crate::lexer::Lexer::new(src);
80        let tokens = lexer.tokenize().expect("lex failed");
81        let mut parser = crate::parser::Parser::new(tokens);
82        parser.parse().expect("parse failed")
83    }
84
85    /// Helper: extract the match arms from a fn body.
86    /// The parser produces `Block([Expr(Match{subject, arms, ..})])` for indented match bodies.
87    fn extract_match_arms(fd: &FnDef) -> &[MatchArm] {
88        if let Some(Stmt::Expr(Expr::Match { arms, .. })) = fd.body.stmts().last() {
89            arms
90        } else {
91            panic!("expected Match in block body, got {:?}", fd.body)
92        }
93    }
94
95    #[test]
96    fn transforms_self_tail_call() {
97        let src = r#"
98fn factorial(n: Int, acc: Int) -> Int
99    match n
100        0 -> acc
101        _ -> factorial(n - 1, acc * n)
102"#;
103        let mut items = parse(src);
104        transform_program(&mut items);
105
106        let fd = match &items[0] {
107            TopLevel::FnDef(fd) => fd,
108            _ => panic!("expected FnDef"),
109        };
110
111        let arms = extract_match_arms(fd);
112        // arm 0: literal 0 -> acc (unchanged)
113        assert!(!matches!(*arms[0].body, Expr::TailCall(..)));
114        // arm 1: _ -> TailCall("factorial", ...)
115        match &*arms[1].body {
116            Expr::TailCall(boxed) => {
117                let (name, args) = boxed.as_ref();
118                assert_eq!(name, "factorial");
119                assert_eq!(args.len(), 2);
120            }
121            other => panic!("expected TailCall, got {:?}", other),
122        }
123    }
124
125    #[test]
126    fn does_not_transform_non_tail_call() {
127        let src = r#"
128fn fib(n: Int) -> Int
129    match n
130        0 -> 0
131        1 -> 1
132        _ -> fib(n - 1) + fib(n - 2)
133"#;
134        let mut items = parse(src);
135        transform_program(&mut items);
136
137        let fd = match &items[0] {
138            TopLevel::FnDef(fd) => fd,
139            _ => panic!("expected FnDef"),
140        };
141
142        let arms = extract_match_arms(fd);
143        // arm 2: _ -> fib(n-1) + fib(n-2) — BinOp, NOT TailCall
144        assert!(
145            !matches!(*arms[2].body, Expr::TailCall(..)),
146            "fib should NOT be tail-call transformed"
147        );
148    }
149
150    #[test]
151    fn transforms_mutual_recursion() {
152        let src = r#"
153fn isEven(n: Int) -> Bool
154    match n
155        0 -> true
156        _ -> isOdd(n - 1)
157
158fn isOdd(n: Int) -> Bool
159    match n
160        0 -> false
161        _ -> isEven(n - 1)
162"#;
163        let mut items = parse(src);
164        transform_program(&mut items);
165
166        // Check isEven
167        let fd_even = match &items[0] {
168            TopLevel::FnDef(fd) => fd,
169            _ => panic!("expected FnDef"),
170        };
171        let arms_even = extract_match_arms(fd_even);
172        match &*arms_even[1].body {
173            Expr::TailCall(boxed) => assert_eq!(boxed.0, "isOdd"),
174            other => panic!("expected TailCall to isOdd, got {:?}", other),
175        }
176
177        // Check isOdd
178        let fd_odd = match &items[1] {
179            TopLevel::FnDef(fd) => fd,
180            _ => panic!("expected FnDef"),
181        };
182        let arms_odd = extract_match_arms(fd_odd);
183        match &*arms_odd[1].body {
184            Expr::TailCall(boxed) => assert_eq!(boxed.0, "isEven"),
185            other => panic!("expected TailCall to isEven, got {:?}", other),
186        }
187    }
188}