feat(natu): detect redundant let expressions

This commit was merged in pull request #125.
This commit is contained in:
2026-10-04 21:23:35 -04:00
parent c91094234f
commit 3e9295134e
6 changed files with 183 additions and 13 deletions

View File

@@ -0,0 +1,98 @@
use crate::ast;
pub struct Finding {
pub range: ast::SourceRange,
}
pub fn check(expr: &ast::Expr) -> Vec<Finding> {
let mut findings = Vec::new();
check_expr(expr, &mut findings);
findings
}
fn check_expr(expr: &ast::Expr, findings: &mut Vec<Finding>) {
match expr {
ast::Expr::Let {
range,
bindings,
body,
} => {
if is_redundant(bindings, body) {
findings.push(Finding { range: *range });
}
for binding in bindings {
check_expr(&binding.value, findings);
}
check_expr(body, findings);
}
ast::Expr::AttrSet(bindings) => {
for binding in bindings {
check_expr(&binding.value, findings);
}
}
ast::Expr::Lambda { body, .. } => check_expr(body, findings),
ast::Expr::Apply(application) => {
check_expr(&application.lambda, findings);
check_expr(&application.argument, findings);
}
ast::Expr::Other(expressions) => {
for expression in expressions {
check_expr(expression, findings);
}
}
ast::Expr::Ident(_) | ast::Expr::Select(_) => { }
}
}
fn is_redundant(bindings: &[ast::Binding], body: &ast::Expr) -> bool {
let Some((binding_index, binding)) = bindings
.iter()
.enumerate()
.find(|(_, binding)| is_ident(body, &binding.key.name))
else {
return false;
};
!references_name(&binding.value, &binding.key.name)
&& !bindings.iter().enumerate().any(|(candidate_index, candidate)| {
candidate_index != binding_index && references_name(&candidate.value, &binding.key.name)
})
}
fn is_ident(expr: &ast::Expr, name: &str) -> bool {
matches!(unwrap_expr(expr), ast::Expr::Ident(ident) if ident.name == name)
}
fn references_name(expr: &ast::Expr, name: &str) -> bool {
match expr {
ast::Expr::Ident(ident) => ident.name == name,
ast::Expr::Select(select) => select.receiver == name,
ast::Expr::Apply(application) => {
references_name(&application.lambda, name) || references_name(&application.argument, name)
}
ast::Expr::Let { bindings, body, .. } => {
!bindings.iter().any(|binding| binding.key.name == name)
&& (bindings
.iter()
.any(|binding| references_name(&binding.value, name))
|| references_name(body, name))
}
ast::Expr::AttrSet(bindings) => bindings
.iter()
.any(|binding| references_name(&binding.value, name)),
ast::Expr::Lambda { parameters, body } => {
!parameters.iter().any(|parameter| parameter.name == name)
&& references_name(body, name)
}
ast::Expr::Other(expressions) => expressions
.iter()
.any(|expression| references_name(expression, name)),
}
}
fn unwrap_expr(expr: &ast::Expr) -> &ast::Expr {
match expr {
ast::Expr::Other(expressions) if expressions.len() == 1 => unwrap_expr(&expressions[0]),
_ => expr,
}
}