use toasty_core::stmt::{self, Expr, visit_mut};
pub(super) fn fold_expr_let(expr_let: &mut stmt::ExprLet) -> Option<Expr> {
if !expr_let.bindings.iter().all(|b| b.is_stable()) {
return None;
}
let mut body = *expr_let.body.clone();
substitute_let_bindings(&mut body, &expr_let.bindings);
Some(body)
}
fn substitute_let_bindings(expr: &mut Expr, bindings: &[Expr]) {
visit_mut::walk_expr_scoped_mut(expr, 0, |expr, scope_depth| match expr {
Expr::Arg(arg) if arg.nesting == scope_depth && arg.position < bindings.len() => {
*expr = bindings[arg.position].clone();
false
}
Expr::Arg(arg) if arg.nesting > scope_depth => {
arg.nesting -= 1;
false
}
_ => true,
});
}