From 036366dd7ccfd4245230e3b0664632a692eaa1b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20R=C3=A9mond?= Date: Sun, 15 Nov 2026 21:58:23 +0100 Subject: [PATCH 1/3] fix(warnings): count reads after exported branch bindings --- CHANGELOG.md | 11 + crates/nera-ir/src/warnings/unused_vars.rs | 207 +++++++++++------- .../nera-ir/src/warnings/unused_vars_tests.rs | 61 +++++- tests/README.md | 1 + tests/branch_export_warnings.erl | 136 ++++++++++++ 5 files changed, 333 insertions(+), 83 deletions(-) create mode 100644 tests/branch_export_warnings.erl diff --git a/CHANGELOG.md b/CHANGELOG.md index 58a3327..7806fcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,17 @@ All notable milestones for the nera project are documented in this file. partial-byte, large and extracted bitstrings, non-bitstrings and higher-order fun consumers with explicit completion. +## Branch exports count later reads as uses + +- Names bound in `case`, `if` and `receive` branches no longer get false + unused-variable warnings when code reads them after the construct, including + nested branches, clause patterns, receive timeouts and later fun captures. +- The unused-variable pass checks direct matches consistently in branch bodies + and keeps warnings for genuinely unread or fun-local bindings. A later fun + that shadows a name does not count as reading the exported value. +- Warning regressions cover the existing `nested_case_exports` fixture and + `branch_export_warnings`, shared by native and BEAM execution. + ## Regression coverage for case exports inside maybe bodies - A diagnostic regression protects names bound in every `case` branch and read diff --git a/crates/nera-ir/src/warnings/unused_vars.rs b/crates/nera-ir/src/warnings/unused_vars.rs index 4c9a17b..7ca6526 100644 --- a/crates/nera-ir/src/warnings/unused_vars.rs +++ b/crates/nera-ir/src/warnings/unused_vars.rs @@ -6,7 +6,7 @@ use nera_syntax::ast::{self, AtomId, Pattern}; use nera_syntax::error::Diagnostic; use super::ast_walkers::{ - collect_expr_refs, collect_guard_refs, collect_pattern_bindings, + collect_enclosing_refs, collect_expr_refs, collect_guard_refs, collect_pattern_bindings, collect_pattern_bindings_with_spans, collect_pattern_expr_refs, collect_pattern_local_refs, }; use super::unbound_vars::collect_exported_bindings; @@ -31,6 +31,7 @@ pub(super) fn check_unused_variables_fn( warnings, &empty_scope, &empty_scope, + &empty_scope, ); } } @@ -41,7 +42,12 @@ pub(super) fn check_unused_variables_fn( /// `outer_scope` holds the names bound before the clause. `compared` holds /// the names its patterns compare against instead of binding: the outer /// scope for case, receive, try and maybe arms, and nothing for function and -/// fun heads, which shadow outer names. +/// fun heads, which shadow outer names. `used_after` contains reads after the +/// enclosing expression, restricted to names that expression exports. +#[expect( + clippy::too_many_arguments, + reason = "Clause patterns, scope and later reads are distinct inputs to unused-variable analysis" +)] fn check_clause_unused_vars( patterns: &[Pattern], guard: Option<&ast::Guard>, @@ -50,6 +56,7 @@ fn check_clause_unused_vars( warnings: &mut Vec, compared: &HashSet, outer_scope: &HashSet, + used_after: &HashSet, ) { // 1. Collect all variable bindings from patterns (with spans) let mut bound: Vec<(AtomId, nera_syntax::span::Span)> = Vec::new(); @@ -88,6 +95,8 @@ fn check_clause_unused_vars( collect_expr_refs(expr, &mut referenced); } + referenced.extend(used_after); + // 5. Emit warning for each bound var not in referenced set // and not used for equality matching (duplicated). for (atom_id, span) in &bound { @@ -103,16 +112,12 @@ fn check_clause_unused_vars( if name.starts_with('_') { continue; } - warnings.push(Diagnostic::warning_at( - format!("variable '{}' is unused", name), - *span, - ).with_code("unused_variable")); + warnings.push( + Diagnostic::warning_at(format!("variable '{}' is unused", name), *span) + .with_code("unused_variable"), + ); } - // 5b. Check for unused variables bound by body-level match expressions. - let pattern_bound_ids: HashSet = bound.iter().map(|(id, _)| *id).collect(); - check_body_match_unused_vars(body, atom_names, warnings, outer_scope, &pattern_bound_ids); - // 6. Build nested scope (outer + newly bound) for recursion into body. let mut nested_scope = outer_scope.clone(); for (atom_id, _) in &bound { @@ -121,19 +126,28 @@ fn check_clause_unused_vars( // 7. Recurse into case/receive/try/fun clauses nested in body. Walking // in order, `X = 42, case ... of {msg, X} -> ...` sees X in scope. - check_unused_in_body(body, atom_names, warnings, &mut nested_scope); + check_unused_in_body(body, atom_names, warnings, &mut nested_scope, used_after); } /// Walk a body in order: each expression sees the names earlier ones bind, -/// including names bound in a block, a branch or a receive timeout. +/// including names bound in a block, a branch or a receive timeout. Later +/// reads flow back into nested branches as well as direct matches. fn check_unused_in_body( body: &[ast::Expr], atom_names: &HashMap, warnings: &mut Vec, scope: &mut HashSet, + used_after: &HashSet, ) { - for expr in body { - check_unused_in_expr(expr, atom_names, warnings, scope); + for (i, expr) in body.iter().enumerate() { + let mut later_refs = used_after.clone(); + for later in &body[i + 1..] { + collect_enclosing_refs(later, &mut later_refs); + } + if matches!(expr, ast::Expr::Match(..)) { + warn_unused_match_bindings(expr, &later_refs, scope, atom_names, warnings); + } + check_unused_in_expr(expr, atom_names, warnings, scope, &later_refs); collect_exported_bindings(expr, scope); } } @@ -145,10 +159,20 @@ fn check_unused_in_expr( atom_names: &HashMap, warnings: &mut Vec, outer_scope: &HashSet, + used_after: &HashSet, ) { + // Only exported bindings can be used by the continuation. In particular, + // an outer read must not mark a same-named fun-local binding as used. + let mut exported_uses = HashSet::new(); + collect_exported_bindings(expr, &mut exported_uses); + exported_uses.retain(|id| used_after.contains(id)); + let used_after = &exported_uses; + match expr { ast::Expr::Case(scrutinee, clauses, _) => { - check_unused_in_expr(scrutinee, atom_names, warnings, outer_scope); + let mut input_uses = used_after.clone(); + collect_clause_refs(clauses, &mut input_uses); + check_unused_in_expr(scrutinee, atom_names, warnings, outer_scope, &input_uses); // Names the scrutinee binds are bound in every clause. let mut input = outer_scope.clone(); collect_exported_bindings(scrutinee, &mut input); @@ -161,6 +185,7 @@ fn check_unused_in_expr( warnings, &input, &input, + used_after, ); } } @@ -174,12 +199,19 @@ fn check_unused_in_expr( warnings, outer_scope, outer_scope, + used_after, ); } if let Some(after) = after { // As in erlc, the after body does not see the timeout's // bindings. - check_unused_in_body(&after.body, atom_names, warnings, &mut outer_scope.clone()); + check_unused_in_body( + &after.body, + atom_names, + warnings, + &mut outer_scope.clone(), + used_after, + ); } } ast::Expr::Try { @@ -191,7 +223,9 @@ fn check_unused_in_expr( } => { // The of-clauses see the try body's bindings. let mut try_scope = outer_scope.clone(); - check_unused_in_body(body, atom_names, warnings, &mut try_scope); + let mut of_uses = HashSet::new(); + collect_clause_refs(of_clauses, &mut of_uses); + check_unused_in_body(body, atom_names, warnings, &mut try_scope, &of_uses); for clause in of_clauses { check_clause_unused_vars( std::slice::from_ref(&clause.pattern), @@ -201,6 +235,7 @@ fn check_unused_in_expr( warnings, &try_scope, &try_scope, + used_after, ); } for clause in catch_clauses { @@ -222,10 +257,17 @@ fn check_unused_in_expr( warnings, outer_scope, &catch_scope, + used_after, ); } if let Some(after) = after_body { - check_unused_in_body(after, atom_names, warnings, &mut outer_scope.clone()); + check_unused_in_body( + after, + atom_names, + warnings, + &mut outer_scope.clone(), + used_after, + ); } } ast::Expr::Fun(name, clauses, _) => { @@ -245,62 +287,75 @@ fn check_unused_in_expr( warnings, &fresh, &fun_scope, + used_after, ); } } ast::Expr::If(clauses, _) => { for clause in clauses { - check_unused_in_body(&clause.body, atom_names, warnings, &mut outer_scope.clone()); + check_unused_in_body( + &clause.body, + atom_names, + warnings, + &mut outer_scope.clone(), + used_after, + ); } } // Recurse into sub-expressions for completeness ast::Expr::Block(exprs, _) => { - check_unused_in_body(exprs, atom_names, warnings, &mut outer_scope.clone()); + check_unused_in_body( + exprs, + atom_names, + warnings, + &mut outer_scope.clone(), + used_after, + ); } ast::Expr::Tuple(exprs, _) => { for e in exprs { - check_unused_in_expr(e, atom_names, warnings, outer_scope); + check_unused_in_expr(e, atom_names, warnings, outer_scope, used_after); } } ast::Expr::Cons(h, t, _) | ast::Expr::Send(h, t, _) | ast::Expr::BinOp(_, h, t, _) => { - check_unused_in_expr(h, atom_names, warnings, outer_scope); - check_unused_in_expr(t, atom_names, warnings, outer_scope); + check_unused_in_expr(h, atom_names, warnings, outer_scope, used_after); + check_unused_in_expr(t, atom_names, warnings, outer_scope, used_after); } ast::Expr::Match(_, e, _) => { - check_unused_in_expr(e, atom_names, warnings, outer_scope); + check_unused_in_expr(e, atom_names, warnings, outer_scope, used_after); } ast::Expr::UnaryOp(_, e, _) | ast::Expr::Throw(e, _) | ast::Expr::Catch(e, _) => { - check_unused_in_expr(e, atom_names, warnings, outer_scope); + check_unused_in_expr(e, atom_names, warnings, outer_scope, used_after); } ast::Expr::Call(target, args, _) => { if let ast::CallTarget::Remote(module_expr, fun_expr) = target { - check_unused_in_expr(module_expr, atom_names, warnings, outer_scope); - check_unused_in_expr(fun_expr, atom_names, warnings, outer_scope); + check_unused_in_expr(module_expr, atom_names, warnings, outer_scope, used_after); + check_unused_in_expr(fun_expr, atom_names, warnings, outer_scope, used_after); } for arg in args { - check_unused_in_expr(arg, atom_names, warnings, outer_scope); + check_unused_in_expr(arg, atom_names, warnings, outer_scope, used_after); } } ast::Expr::MapUpdate(base, fields, _) => { - check_unused_in_expr(base, atom_names, warnings, outer_scope); + check_unused_in_expr(base, atom_names, warnings, outer_scope, used_after); for field in fields { - check_unused_in_expr(&field.key, atom_names, warnings, outer_scope); - check_unused_in_expr(&field.value, atom_names, warnings, outer_scope); + check_unused_in_expr(&field.key, atom_names, warnings, outer_scope, used_after); + check_unused_in_expr(&field.value, atom_names, warnings, outer_scope, used_after); } } ast::Expr::RecordUpdate { base, fields, .. } => { - check_unused_in_expr(base, atom_names, warnings, outer_scope); + check_unused_in_expr(base, atom_names, warnings, outer_scope, used_after); for field in fields { - check_unused_in_expr(&field.value, atom_names, warnings, outer_scope); + check_unused_in_expr(&field.value, atom_names, warnings, outer_scope, used_after); } } ast::Expr::RecordCreate { fields, .. } => { for field in fields { - check_unused_in_expr(&field.value, atom_names, warnings, outer_scope); + check_unused_in_expr(&field.value, atom_names, warnings, outer_scope, used_after); } } ast::Expr::RecordAccess { base, .. } => { - check_unused_in_expr(base, atom_names, warnings, outer_scope); + check_unused_in_expr(base, atom_names, warnings, outer_scope, used_after); } ast::Expr::ListComp(body, qualifiers, _) | ast::Expr::BinComp(body, qualifiers, _) => { // Generator patterns bind names for later qualifiers and the body. @@ -309,41 +364,43 @@ fn check_unused_in_expr( match q { ast::LcQualifier::Generator(pat, expr, _) | ast::LcQualifier::BinGenerator(pat, expr, _) => { - check_unused_in_expr(expr, atom_names, warnings, &lc_scope); + check_unused_in_expr(expr, atom_names, warnings, &lc_scope, used_after); collect_pattern_bindings(pat, &mut lc_scope); } ast::LcQualifier::Filter(expr, _) => { - check_unused_in_expr(expr, atom_names, warnings, &lc_scope); + check_unused_in_expr(expr, atom_names, warnings, &lc_scope, used_after); collect_exported_bindings(expr, &mut lc_scope); } } } - check_unused_in_expr(body, atom_names, warnings, &lc_scope); + check_unused_in_expr(body, atom_names, warnings, &lc_scope, used_after); } ast::Expr::Binary(segments, _) => { for seg in segments { - check_unused_in_expr(&seg.value, atom_names, warnings, outer_scope); + check_unused_in_expr(&seg.value, atom_names, warnings, outer_scope, used_after); if let Some(ref size) = seg.size { - check_unused_in_expr(size, atom_names, warnings, outer_scope); + check_unused_in_expr(size, atom_names, warnings, outer_scope, used_after); } } } ast::Expr::Map(fields, _) => { for field in fields { - check_unused_in_expr(&field.key, atom_names, warnings, outer_scope); - check_unused_in_expr(&field.value, atom_names, warnings, outer_scope); + check_unused_in_expr(&field.key, atom_names, warnings, outer_scope, used_after); + check_unused_in_expr(&field.value, atom_names, warnings, outer_scope, used_after); } } - ast::Expr::Maybe { body, else_clauses, .. } => { + ast::Expr::Maybe { + body, else_clauses, .. + } => { let mut maybe_scope = outer_scope.clone(); for item in body { match item { ast::MaybeExpr::Expr(e) => { - check_unused_in_expr(e, atom_names, warnings, &maybe_scope); + check_unused_in_expr(e, atom_names, warnings, &maybe_scope, used_after); collect_exported_bindings(e, &mut maybe_scope); } ast::MaybeExpr::CondMatch(pat, e, _) => { - check_unused_in_expr(e, atom_names, warnings, &maybe_scope); + check_unused_in_expr(e, atom_names, warnings, &maybe_scope, used_after); collect_exported_bindings(e, &mut maybe_scope); collect_pattern_bindings(pat, &mut maybe_scope); } @@ -358,6 +415,7 @@ fn check_unused_in_expr( warnings, outer_scope, outer_scope, + used_after, ); } } @@ -372,20 +430,34 @@ fn check_unused_in_expr( | ast::Expr::FunRef(ast::FunRefTarget::Local(..) | ast::FunRefTarget::Remote(..), _) | ast::Expr::RecordIndex { .. } => {} ast::Expr::FunRef(ast::FunRefTarget::DynamicRemote(m, f, a), _) => { - check_unused_in_expr(m, atom_names, warnings, outer_scope); - check_unused_in_expr(f, atom_names, warnings, outer_scope); - check_unused_in_expr(a, atom_names, warnings, outer_scope); + check_unused_in_expr(m, atom_names, warnings, outer_scope, used_after); + check_unused_in_expr(f, atom_names, warnings, outer_scope, used_after); + check_unused_in_expr(a, atom_names, warnings, outer_scope, used_after); } ast::Expr::MacroCall { args, .. } => { if let Some(args) = args { for arg in args { - check_unused_in_expr(arg, atom_names, warnings, outer_scope); + check_unused_in_expr(arg, atom_names, warnings, outer_scope, used_after); } } } } } +/// Reads in case/try-of clauses can consume bindings from their input. +fn collect_clause_refs(clauses: &[ast::CaseClause], refs: &mut HashSet) { + for clause in clauses { + collect_pattern_bindings(&clause.pattern, refs); + collect_pattern_expr_refs(&clause.pattern, refs); + if let Some(guard) = &clause.guard { + collect_guard_refs(guard, refs); + } + for expr in &clause.body { + collect_enclosing_refs(expr, refs); + } + } +} + /// Collect bindings with spans and reads in the patterns of a (possibly /// chained) match. A size can use an earlier segment bound in this same match. fn collect_match_bindings_and_refs( @@ -400,35 +472,11 @@ fn collect_match_bindings_and_refs( } } -/// Check for unused variables bound by top-level match expressions in a -/// clause body. Walks the body sequentially: for each `Match` expression, -/// any NEW bindings that are not referenced by any subsequent expression -/// (and not `_`-prefixed) are flagged as unused. -fn check_body_match_unused_vars( - body: &[ast::Expr], - atom_names: &HashMap, - warnings: &mut Vec, - outer_scope: &HashSet, - pattern_bound: &HashSet, -) { - let mut in_scope: HashSet = outer_scope.clone(); - in_scope.extend(pattern_bound); - - for (i, expr) in body.iter().enumerate() { - if matches!(expr, ast::Expr::Match(..)) { - warn_unused_match_bindings(expr, &body[i + 1..], &in_scope, atom_names, warnings); - } - // Every name the expression binds, including in a block or a receive - // timeout, is bound for later matches: they compare against it. - collect_exported_bindings(expr, &mut in_scope); - } -} - /// Warn about each name a body-level match binds fresh that neither the /// match itself nor a later expression reads. fn warn_unused_match_bindings( expr: &ast::Expr, - later: &[ast::Expr], + later_refs: &HashSet, in_scope: &HashSet, atom_names: &HashMap, warnings: &mut Vec, @@ -445,9 +493,7 @@ fn warn_unused_match_bindings( } // Add references from subsequent expressions to the same-match reads. - for subsequent in later { - collect_expr_refs(subsequent, &mut referenced); - } + referenced.extend(later_refs); let mut warned: HashSet = HashSet::new(); for (atom_id, span) in &new_bindings { @@ -462,11 +508,8 @@ fn warn_unused_match_bindings( continue; } warnings.push( - Diagnostic::warning_at( - format!("variable '{}' is unused", name), - *span, - ) - .with_code("unused_variable"), + Diagnostic::warning_at(format!("variable '{}' is unused", name), *span) + .with_code("unused_variable"), ); warned.insert(*atom_id); } diff --git a/crates/nera-ir/src/warnings/unused_vars_tests.rs b/crates/nera-ir/src/warnings/unused_vars_tests.rs index a1cdaee..f8688fd 100644 --- a/crates/nera-ir/src/warnings/unused_vars_tests.rs +++ b/crates/nera-ir/src/warnings/unused_vars_tests.rs @@ -1,9 +1,68 @@ -//! Regression for false unused-variable warnings on map keys and binary sizes. +//! Regressions for unused-variable diagnostics on real Erlang programs. use nera_syntax::error::Severity; use nera_syntax::parser::Parser; use nera_syntax::span::Span; +#[test] +fn branch_exports_read_afterward_are_used() { + // Intent: exported branch bindings read after case/if/receive are used, + // as with erlc -Wall. Unread and fun-local bindings must still warn. + let source = include_str!("../../../../tests/branch_export_warnings.erl"); + let mut parser = Parser::new(source); + let parsed = parser.parse_module(); + assert!(parsed.errors.is_empty(), "{:?}", parsed.errors); + let diagnostics = crate::warnings::analyze_module(&parsed.module, &parser.atom_names(), None); + assert!( + diagnostics.iter().all(|d| d.severity != Severity::Error), + "unexpected errors: {diagnostics:#?}" + ); + let mut actual: Vec<_> = diagnostics + .iter() + .filter(|d| d.code.as_deref() == Some("unused_variable")) + .map(|d| (d.message.clone(), d.span.expect("binding span").start)) + .collect(); + let mut expected: Vec<_> = [ + ("LocalCode", "LocalCode = 200"), + ("LocalCode", "LocalCode = 503"), + ("UnusedPrimary", "UnusedPrimary = 200"), + ("UnusedFallback", "UnusedFallback = 503"), + ("UnusedIf", "UnusedIf = 200"), + ("UnusedIf", "UnusedIf = 503"), + ("UnusedResponse", "UnusedResponse = 200"), + ("UnusedTimeout", "UnusedTimeout = 504"), + ("ShadowedCode", "ShadowedCode = 200"), + ("ShadowedCode", "ShadowedCode = 503"), + ] + .into_iter() + .map(|(name, binding)| { + ( + format!("variable '{name}' is unused"), + source.find(binding).expect("control binding in fixture"), + ) + }) + .collect(); + actual.sort(); + expected.sort(); + assert_eq!(actual, expected, "unexpected diagnostics: {diagnostics:#?}"); +} + +#[test] +fn nested_case_exports_read_afterward_are_used() { + // The existing native fixture supplied the original false-warning report. + let source = include_str!("../../../../tests/nested_case_exports.erl"); + let mut parser = Parser::new(source); + let parsed = parser.parse_module(); + assert!(parsed.errors.is_empty(), "{:?}", parsed.errors); + let diagnostics = crate::warnings::analyze_module(&parsed.module, &parser.atom_names(), None); + assert!( + diagnostics + .iter() + .all(|d| d.severity != Severity::Error && d.code.as_deref() != Some("unused_variable")), + "unexpected diagnostics: {diagnostics:#?}" + ); +} + #[test] fn pattern_expression_reads_preserve_unused_value_warnings() { // Intent: keys and sizes count as uses without treating value bindings as diff --git a/tests/README.md b/tests/README.md index 36059a5..4009c8e 100644 --- a/tests/README.md +++ b/tests/README.md @@ -516,6 +516,7 @@ committed catalogue with the pinned OTP abstract code. | Test File | Feature Category | Assertions | |--------------------------------|--------------------------------------------------------|-----------------| +| `branch_export_warnings.erl` | Later reads of case/if/receive bindings, nested branches, patterns, timeouts and captures; unread and fun-local controls; shared with warning analysis and run on BEAM | Exact unused diagnostics and completion | | `pattern_expr_warnings.erl` | Map-key and binary-size reads, including earlier segments in clause/body-match patterns; real unused-value controls; shared with warning analysis and run on BEAM | Exact diagnostics and completion | | `andalso_unsafe_binding.erl` | Reject a later read of a name bound only in the right operand of `andalso`, with OTP's unsafe-variable diagnostic | (compile error) | | `orelse_unsafe_binding.erl` | Reject a later read of a name bound only in the right operand of `orelse`, with OTP's unsafe-variable diagnostic | (compile error) | diff --git a/tests/branch_export_warnings.erl b/tests/branch_export_warnings.erl new file mode 100644 index 0000000..08eff6a --- /dev/null +++ b/tests/branch_export_warnings.erl @@ -0,0 +1,136 @@ +%% EXPECT: branch_export_warnings_ok +-module(branch_export_warnings). +-export([test/0]). + +%% Branch bindings supply values read only after the branching expression. +test() -> + lists:foreach(fun({Route, Code}) -> + Code = case_body(Route), + Code = case_pattern({Route, Code}), + Code = if_body(Route), + Code = nested(Route), + Code = captured(Route), + Code = scrutinee(Route), + Code = try_input(Route), + Code = receive_body(Route), + Code = receive_pattern(Code) + end, [{primary, 200}, {fallback, 503}]), + 504 = receive_timeout(), + {ok, 204} = local_fun(primary), + ok = unused(primary), + ignored = shadowed(primary), + io:format("branch_export_warnings_ok~n"), + ok. + +case_body(Route) -> + case Route of + primary -> Code = 200; + fallback -> Code = 503 + end, + Code. + +case_pattern(Response) -> + case Response of + {primary, Code} -> ok; + {fallback, Code} -> ok + end, + Code. + +if_body(Route) -> + if Route =:= primary -> Code = 200; + true -> Code = 503 + end, + Code. + +nested(Route) -> + Result = case Route of + primary -> + begin + if Route =:= primary -> Code = 200; + true -> Code = 500 + end + end; + fallback -> Code = 503 + end, + {Result, Code} = {Code, Result}, + Code. + +captured(Route) -> + case Route of + primary -> Code = 200; + fallback -> Code = 503 + end, + Read = fun() -> Code end, + Read(). + +scrutinee(Route) -> + case (case Route of + primary -> Code = 200; + fallback -> Code = 503 + end) of + _ -> Code + end. + +try_input(Route) -> + try case Route of + primary -> Code = 200; + fallback -> Code = 503 + end of + _ -> Code + catch + _:_ -> failed + end. + +receive_body(Route) -> + self() ! Route, + receive + primary -> Code = 200; + fallback -> Code = 503 + end, + Code. + +receive_pattern(Response) -> + self() ! {response, Response}, + receive {response, Code} -> ok end, + Code. + +receive_timeout() -> + receive + response -> Code = 200 + after 0 -> Code = 504 + end, + Code. + +%% Reading an outer Code must not mark a fun-local Code as used. +local_fun(Route) -> + Run = fun() -> + case Route of + primary -> LocalCode = 200; + fallback -> LocalCode = 503 + end, + ok + end, + LocalCode = 204, + {Run(), LocalCode}. + +%% Unread bindings keep their warnings in each branch and timeout body. +unused(Route) -> + case Route of + primary -> UnusedPrimary = 200; + fallback -> UnusedFallback = 503 + end, + if Route =:= primary -> UnusedIf = 200; + true -> UnusedIf = 503 + end, + receive response -> UnusedResponse = 200 + after 0 -> UnusedTimeout = 504 + end, + ok. + +%% A later fun head shadows Code instead of reading the branch bindings. +shadowed(Route) -> + case Route of + primary -> ShadowedCode = 200; + fallback -> ShadowedCode = 503 + end, + (fun(ShadowedCode) -> ShadowedCode end)(ignored). From 3ce3e24e166ad8e2901aef9c05761a32fb68b653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20R=C3=A9mond?= Date: Sun, 15 Nov 2026 22:10:12 +0100 Subject: [PATCH 2/3] fix(warnings): preserve local and pattern continuations --- CHANGELOG.md | 2 + crates/nera-ir/src/warnings/unused_vars.rs | 137 ++++++++++++++---- .../nera-ir/src/warnings/unused_vars_tests.rs | 1 + tests/README.md | 2 +- tests/branch_export_warnings.erl | 31 +++- 5 files changed, 144 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7806fcd..12dac11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ All notable milestones for the nera project are documented in this file. - The unused-variable pass checks direct matches consistently in branch bodies and keeps warnings for genuinely unread or fun-local bindings. A later fun that shadows a name does not count as reading the exported value. +- Later reads inside comprehensions and `maybe`, and key/size reads in match + patterns, reach the bindings they consume without leaking across local scopes. - Warning regressions cover the existing `nested_case_exports` fixture and `branch_export_warnings`, shared by native and BEAM execution. diff --git a/crates/nera-ir/src/warnings/unused_vars.rs b/crates/nera-ir/src/warnings/unused_vars.rs index 7ca6526..3c2cba5 100644 --- a/crates/nera-ir/src/warnings/unused_vars.rs +++ b/crates/nera-ir/src/warnings/unused_vars.rs @@ -8,6 +8,7 @@ use nera_syntax::error::Diagnostic; use super::ast_walkers::{ collect_enclosing_refs, collect_expr_refs, collect_guard_refs, collect_pattern_bindings, collect_pattern_bindings_with_spans, collect_pattern_expr_refs, collect_pattern_local_refs, + collect_pattern_refs, }; use super::unbound_vars::collect_exported_bindings; @@ -139,17 +140,18 @@ fn check_unused_in_body( scope: &mut HashSet, used_after: &HashSet, ) { - for (i, expr) in body.iter().enumerate() { - let mut later_refs = used_after.clone(); - for later in &body[i + 1..] { - collect_enclosing_refs(later, &mut later_refs); - } - if matches!(expr, ast::Expr::Match(..)) { - warn_unused_match_bindings(expr, &later_refs, scope, atom_names, warnings); - } - check_unused_in_expr(expr, atom_names, warnings, scope, &later_refs); - collect_exported_bindings(expr, scope); - } + with_continuation_uses( + body, + used_after, + collect_enclosing_refs, + |expr, later_refs| { + if matches!(expr, ast::Expr::Match(..)) { + warn_unused_match_bindings(expr, later_refs, scope, atom_names, warnings); + } + check_unused_in_expr(expr, atom_names, warnings, scope, later_refs); + collect_exported_bindings(expr, scope); + }, + ); } /// Recursively walk an expression tree looking for nested clause constructs @@ -161,12 +163,25 @@ fn check_unused_in_expr( outer_scope: &HashSet, used_after: &HashSet, ) { - // Only exported bindings can be used by the continuation. In particular, - // an outer read must not mark a same-named fun-local binding as used. + // Filter only at branch boundaries, not at every node of a literal tree. + // Scope-local constructs cannot consume reads from outside their scope. let mut exported_uses = HashSet::new(); - collect_exported_bindings(expr, &mut exported_uses); - exported_uses.retain(|id| used_after.contains(id)); - let used_after = &exported_uses; + let used_after = match expr { + ast::Expr::Case(..) | ast::Expr::If(..) | ast::Expr::Receive(..) + if !used_after.is_empty() => + { + collect_exported_bindings(expr, &mut exported_uses); + exported_uses.retain(|id| used_after.contains(id)); + &exported_uses + } + ast::Expr::Fun(..) + | ast::Expr::ListComp(..) + | ast::Expr::BinComp(..) + | ast::Expr::Try { .. } + | ast::Expr::Maybe { .. } + | ast::Expr::Catch(..) => &exported_uses, + _ => used_after, + }; match expr { ast::Expr::Case(scrutinee, clauses, _) => { @@ -321,8 +336,10 @@ fn check_unused_in_expr( check_unused_in_expr(h, atom_names, warnings, outer_scope, used_after); check_unused_in_expr(t, atom_names, warnings, outer_scope, used_after); } - ast::Expr::Match(_, e, _) => { - check_unused_in_expr(e, atom_names, warnings, outer_scope, used_after); + ast::Expr::Match(pat, e, _) => { + let mut pattern_uses = used_after.clone(); + collect_pattern_expr_refs(pat, &mut pattern_uses); + check_unused_in_expr(e, atom_names, warnings, outer_scope, &pattern_uses); } ast::Expr::UnaryOp(_, e, _) | ast::Expr::Throw(e, _) | ast::Expr::Catch(e, _) => { check_unused_in_expr(e, atom_names, warnings, outer_scope, used_after); @@ -359,16 +376,38 @@ fn check_unused_in_expr( } ast::Expr::ListComp(body, qualifiers, _) | ast::Expr::BinComp(body, qualifiers, _) => { // Generator patterns bind names for later qualifiers and the body. + let mut later_refs = HashSet::new(); + collect_enclosing_refs(body, &mut later_refs); + let mut continuations = Vec::with_capacity(qualifiers.len()); + for q in qualifiers.iter().rev() { + match q { + ast::LcQualifier::Generator(pat, expr, _) + | ast::LcQualifier::BinGenerator(pat, expr, _) => { + // The generator head shadows earlier names, but its + // source and pattern inputs still read those names. + let mut fresh = HashSet::new(); + collect_pattern_bindings(pat, &mut fresh); + later_refs.retain(|id| !fresh.contains(id)); + collect_pattern_refs(pat, &mut later_refs); + continuations.push(later_refs.clone()); + collect_enclosing_refs(expr, &mut later_refs); + } + ast::LcQualifier::Filter(expr, _) => { + continuations.push(later_refs.clone()); + collect_enclosing_refs(expr, &mut later_refs); + } + } + } let mut lc_scope = outer_scope.clone(); - for q in qualifiers { + for (q, later_refs) in qualifiers.iter().zip(continuations.iter().rev()) { match q { ast::LcQualifier::Generator(pat, expr, _) | ast::LcQualifier::BinGenerator(pat, expr, _) => { - check_unused_in_expr(expr, atom_names, warnings, &lc_scope, used_after); + check_unused_in_expr(expr, atom_names, warnings, &lc_scope, later_refs); collect_pattern_bindings(pat, &mut lc_scope); } ast::LcQualifier::Filter(expr, _) => { - check_unused_in_expr(expr, atom_names, warnings, &lc_scope, used_after); + check_unused_in_expr(expr, atom_names, warnings, &lc_scope, later_refs); collect_exported_bindings(expr, &mut lc_scope); } } @@ -393,19 +432,30 @@ fn check_unused_in_expr( body, else_clauses, .. } => { let mut maybe_scope = outer_scope.clone(); - for item in body { - match item { + with_continuation_uses( + body, + used_after, + |item, refs| match item { + ast::MaybeExpr::Expr(e) => collect_enclosing_refs(e, refs), + ast::MaybeExpr::CondMatch(pat, e, _) => { + collect_pattern_expr_refs(pat, refs); + collect_enclosing_refs(e, refs); + } + }, + |item, later_refs| match item { ast::MaybeExpr::Expr(e) => { - check_unused_in_expr(e, atom_names, warnings, &maybe_scope, used_after); + check_unused_in_expr(e, atom_names, warnings, &maybe_scope, later_refs); collect_exported_bindings(e, &mut maybe_scope); } ast::MaybeExpr::CondMatch(pat, e, _) => { - check_unused_in_expr(e, atom_names, warnings, &maybe_scope, used_after); + let mut pattern_uses = later_refs.clone(); + collect_pattern_expr_refs(pat, &mut pattern_uses); + check_unused_in_expr(e, atom_names, warnings, &maybe_scope, &pattern_uses); collect_exported_bindings(e, &mut maybe_scope); collect_pattern_bindings(pat, &mut maybe_scope); } - } - } + }, + ); for clause in else_clauses { check_clause_unused_vars( std::slice::from_ref(&clause.pattern), @@ -444,6 +494,39 @@ fn check_unused_in_expr( } } +/// Visit a sequence with its remaining reads. Count each item's reads once, +/// then subtract them in order, without rescanning or copying whole suffixes. +fn with_continuation_uses( + items: &[T], + used_after: &HashSet, + collect: impl Fn(&T, &mut HashSet), + mut visit: impl FnMut(&T, &HashSet), +) { + let reads: Vec<_> = items + .iter() + .map(|item| { + let mut refs = HashSet::new(); + collect(item, &mut refs); + refs + }) + .collect(); + let mut counts = HashMap::::new(); + for id in used_after.iter().chain(reads.iter().flatten()) { + *counts.entry(*id).or_default() += 1; + } + let mut remaining = counts.keys().copied().collect::>(); + for (item, refs) in items.iter().zip(reads) { + for id in refs { + let count = counts.get_mut(&id).expect("counted read"); + *count -= 1; + if *count == 0 { + remaining.remove(&id); + } + } + visit(item, &remaining); + } +} + /// Reads in case/try-of clauses can consume bindings from their input. fn collect_clause_refs(clauses: &[ast::CaseClause], refs: &mut HashSet) { for clause in clauses { diff --git a/crates/nera-ir/src/warnings/unused_vars_tests.rs b/crates/nera-ir/src/warnings/unused_vars_tests.rs index f8688fd..b4c68aa 100644 --- a/crates/nera-ir/src/warnings/unused_vars_tests.rs +++ b/crates/nera-ir/src/warnings/unused_vars_tests.rs @@ -23,6 +23,7 @@ fn branch_exports_read_afterward_are_used() { .map(|d| (d.message.clone(), d.span.expect("binding span").start)) .collect(); let mut expected: Vec<_> = [ + ("UnusedFilter", "UnusedFilter = Input"), ("LocalCode", "LocalCode = 200"), ("LocalCode", "LocalCode = 503"), ("UnusedPrimary", "UnusedPrimary = 200"), diff --git a/tests/README.md b/tests/README.md index 4009c8e..30a207d 100644 --- a/tests/README.md +++ b/tests/README.md @@ -516,7 +516,7 @@ committed catalogue with the pinned OTP abstract code. | Test File | Feature Category | Assertions | |--------------------------------|--------------------------------------------------------|-----------------| -| `branch_export_warnings.erl` | Later reads of case/if/receive bindings, nested branches, patterns, timeouts and captures; unread and fun-local controls; shared with warning analysis and run on BEAM | Exact unused diagnostics and completion | +| `branch_export_warnings.erl` | Later reads of case/if/receive bindings, nested branches, patterns, timeouts and captures; comprehension/maybe continuations and RHS key/size inputs; unread, generator-shadowed and fun-local controls; shared with warning analysis and run on BEAM | Exact unused diagnostics and completion | | `pattern_expr_warnings.erl` | Map-key and binary-size reads, including earlier segments in clause/body-match patterns; real unused-value controls; shared with warning analysis and run on BEAM | Exact diagnostics and completion | | `andalso_unsafe_binding.erl` | Reject a later read of a name bound only in the right operand of `andalso`, with OTP's unsafe-variable diagnostic | (compile error) | | `orelse_unsafe_binding.erl` | Reject a later read of a name bound only in the right operand of `orelse`, with OTP's unsafe-variable diagnostic | (compile error) | diff --git a/tests/branch_export_warnings.erl b/tests/branch_export_warnings.erl index 08eff6a..7fb07e8 100644 --- a/tests/branch_export_warnings.erl +++ b/tests/branch_export_warnings.erl @@ -13,12 +13,16 @@ test() -> Code = scrutinee(Route), Code = try_input(Route), Code = receive_body(Route), - Code = receive_pattern(Code) + Code = receive_pattern(Code), + {[Code], <>, Code, Code} = local_sequences(Code), + {Code, Code, Code} = pattern_rhs(Code), + {Code, Code} = maybe_pattern_rhs(Code) end, [{primary, 200}, {fallback, 503}]), 504 = receive_timeout(), {ok, 204} = local_fun(primary), ok = unused(primary), ignored = shadowed(primary), + [503] = generator_shadow(), io:format("branch_export_warnings_ok~n"), ok. @@ -101,6 +105,31 @@ receive_timeout() -> end, Code. +%% Local sequence continuations do not escape comprehensions or maybe. +local_sequences(Status) -> + Codes = [Code || Input <- [Status], begin Code = Input, true end], + Binary = << <> || Input <- [Status], begin Code = Input, true end >>, + Plain = maybe begin PlainCode = Status end, PlainCode end, + Conditional = maybe true ?= begin ConditionalCode = Status, true end, ConditionalCode end, + {Codes, Binary, Plain, Conditional}. + +%% Pattern keys/sizes consume bindings from ordinary and chained RHS values. +pattern_rhs(Status) -> + #{Key := Value} = (Map = begin Key = route, #{route => Status} end), + <> = begin Width = 16, <> end, + {Value, Body, maps:get(route, Map)}. + +maybe_pattern_rhs(Status) -> + maybe + #{Key := Value} ?= begin Key = route, #{route => Status} end, + <> ?= begin Width = 16, <> end, + {Value, Body} + end. + +generator_shadow() -> + [UnusedFilter || Input <- [200], begin UnusedFilter = Input, true end, + UnusedFilter <- [503]]. + %% Reading an outer Code must not mark a fun-local Code as used. local_fun(Route) -> Run = fun() -> From 29c96bdb142ee9075b34b22ae6bd174e42f0956c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20R=C3=A9mond?= Date: Sun, 15 Nov 2026 22:18:50 +0100 Subject: [PATCH 3/3] fix(warnings): count conditional pattern comparison reads --- CHANGELOG.md | 5 +- crates/nera-ir/src/warnings/ast_walkers.rs | 6 +- crates/nera-ir/src/warnings/tests.rs | 87 ++++++++++++++++------ crates/nera-ir/src/warnings/unused_vars.rs | 4 + tests/branch_export_warnings.erl | 20 ++++- 5 files changed, 92 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12dac11..5ef3735 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,8 +20,9 @@ All notable milestones for the nera project are documented in this file. - The unused-variable pass checks direct matches consistently in branch bodies and keeps warnings for genuinely unread or fun-local bindings. A later fun that shadows a name does not count as reading the exported value. -- Later reads inside comprehensions and `maybe`, and key/size reads in match - patterns, reach the bindings they consume without leaking across local scopes. +- Later reads inside comprehensions and `maybe`, including conditional-pattern + comparisons, and key/size reads in match patterns reach the bindings they + consume without leaking across local scopes. - Warning regressions cover the existing `nested_case_exports` fixture and `branch_export_warnings`, shared by native and BEAM execution. diff --git a/crates/nera-ir/src/warnings/ast_walkers.rs b/crates/nera-ir/src/warnings/ast_walkers.rs index 38a8544..4178093 100644 --- a/crates/nera-ir/src/warnings/ast_walkers.rs +++ b/crates/nera-ir/src/warnings/ast_walkers.rs @@ -457,9 +457,9 @@ fn collect_refs(expr: &ast::Expr, refs: &mut HashSet, scoping: RefScopin match item { ast::MaybeExpr::Expr(e) => collect_refs(e, refs, scoping), ast::MaybeExpr::CondMatch(pat, e, _) => { - if scoping == RefScoping::Lexical { - collect_pattern_bindings(pat, refs); - } + // As with an ordinary match, an already-bound value + // name is read for equality, not rebound. + collect_pattern_bindings(pat, refs); collect_pattern_refs(pat, refs); collect_refs(e, refs, scoping); } diff --git a/crates/nera-ir/src/warnings/tests.rs b/crates/nera-ir/src/warnings/tests.rs index 6fbdad3..4a13a2a 100644 --- a/crates/nera-ir/src/warnings/tests.rs +++ b/crates/nera-ir/src/warnings/tests.rs @@ -1470,37 +1470,76 @@ fn comprehension_filter_bindings_are_available_to_later_qualifiers() { #[test] fn comprehension_filter_bindings_reach_scope_sensitive_diagnostics() { + // A later fun head or generator shadows N, so the earlier filter's N + // is genuinely unused as well as shadowed (erlc -Wall). + let cases: &[(&str, &str, &[&str])] = &[ + ( + "case V of N -> <<1>>; _ -> <<0>> end", + "X <- [1], begin N = X, true end", + &[], + ), + ( + "begin case V of true -> N = 1; false -> ok end, <> end", + "X <- [1], begin N = X, true end", + &[], + ), + ( + "begin case V of true -> N = 1; false -> N = 1 end, <> end", + "X <- [1], begin N = X, true end", + &[], + ), + ( + "begin F = fun(N) -> <> end, F(V) end", + "X <- [1], begin N = X, true end", + &["unused_variable", "shadowed_variable"], + ), + ( + "<>", + "X <- [1], begin N = X, true end, N <- [V]", + &["unused_variable", "shadowed_variable"], + ), + ( + "<<_N>>", + "X <- [V], begin _N = X, true end, begin _N = 1, true end", + &["match_underscore_var"], + ), + ( + "<<_N>>", + "X <- [true], X orelse begin _N = 1, true end, _N <- [V]", + &[], + ), + ("<>", "_ <- [V], {N, N} <- [{1, 1}]", &[]), + ]; for (open, close) in [("[", "]"), ("<<", ">>")] { - for (template, qualifiers, expected) in [ - ("case V of N -> <<1>>; _ -> <<0>> end", - "X <- [1], begin N = X, true end", None), - ("begin case V of true -> N = 1; false -> ok end, <> end", - "X <- [1], begin N = X, true end", None), - ("begin case V of true -> N = 1; false -> N = 1 end, <> end", - "X <- [1], begin N = X, true end", None), - ("begin F = fun(N) -> <> end, F(V) end", - "X <- [1], begin N = X, true end", Some("shadowed_variable")), - ("<>", "X <- [1], begin N = X, true end, N <- [V]", - Some("shadowed_variable")), - ("<<_N>>", "X <- [V], begin _N = X, true end, begin _N = 1, true end", - Some("match_underscore_var")), - ("<<_N>>", "X <- [true], X orelse begin _N = 1, true end, _N <- [V]", None), - ("<>", "_ <- [V], {N, N} <- [{1, 1}]", None), - ] { - let source = format!("-module(test). -export([f/1]). f(V) -> - {open} ({template}) || {qualifiers} {close}."); + for (template, qualifiers, expected) in cases { + let source = format!( + "-module(test). -export([f/1]). f(V) -> + {open} ({template}) || {qualifiers} {close}." + ); let (module, names) = parse_module(&source); let diagnostics = analyze_module(&module, &names, None); assert!( - !diagnostics.iter().any(|d| d.severity == nera_syntax::error::Severity::Error), + !diagnostics + .iter() + .any(|d| d.severity == nera_syntax::error::Severity::Error), "{source}\n{diagnostics:?}" ); - let relevant: Vec<_> = diagnostics.iter().filter_map(|d| d.code.as_deref()) - .filter(|code| ["unsafe_variable", "exported_var", "unreachable_clause", - "unused_variable", "shadowed_variable", "match_underscore_var"].contains(code)) + let relevant: Vec<_> = diagnostics + .iter() + .filter_map(|d| d.code.as_deref()) + .filter(|code| { + [ + "unsafe_variable", + "exported_var", + "unreachable_clause", + "unused_variable", + "shadowed_variable", + "match_underscore_var", + ] + .contains(code) + }) .collect(); - assert_eq!(relevant, expected.into_iter().collect::>(), - "{source}\n{diagnostics:?}"); + assert_eq!(relevant, *expected, "{source}\n{diagnostics:?}"); } } } diff --git a/crates/nera-ir/src/warnings/unused_vars.rs b/crates/nera-ir/src/warnings/unused_vars.rs index 3c2cba5..1a057d6 100644 --- a/crates/nera-ir/src/warnings/unused_vars.rs +++ b/crates/nera-ir/src/warnings/unused_vars.rs @@ -338,6 +338,7 @@ fn check_unused_in_expr( } ast::Expr::Match(pat, e, _) => { let mut pattern_uses = used_after.clone(); + collect_pattern_bindings(pat, &mut pattern_uses); collect_pattern_expr_refs(pat, &mut pattern_uses); check_unused_in_expr(e, atom_names, warnings, outer_scope, &pattern_uses); } @@ -438,6 +439,8 @@ fn check_unused_in_expr( |item, refs| match item { ast::MaybeExpr::Expr(e) => collect_enclosing_refs(e, refs), ast::MaybeExpr::CondMatch(pat, e, _) => { + // Already-bound value names are comparison inputs too. + collect_pattern_bindings(pat, refs); collect_pattern_expr_refs(pat, refs); collect_enclosing_refs(e, refs); } @@ -449,6 +452,7 @@ fn check_unused_in_expr( } ast::MaybeExpr::CondMatch(pat, e, _) => { let mut pattern_uses = later_refs.clone(); + collect_pattern_bindings(pat, &mut pattern_uses); collect_pattern_expr_refs(pat, &mut pattern_uses); check_unused_in_expr(e, atom_names, warnings, &maybe_scope, &pattern_uses); collect_exported_bindings(e, &mut maybe_scope); diff --git a/tests/branch_export_warnings.erl b/tests/branch_export_warnings.erl index 7fb07e8..2820367 100644 --- a/tests/branch_export_warnings.erl +++ b/tests/branch_export_warnings.erl @@ -16,13 +16,16 @@ test() -> Code = receive_pattern(Code), {[Code], <>, Code, Code} = local_sequences(Code), {Code, Code, Code} = pattern_rhs(Code), - {Code, Code} = maybe_pattern_rhs(Code) + {Code, Code} = maybe_pattern_rhs(Code), + {ok, Code} = comparison_after_case(Route, {ok, Code}), + {ok, Code} = comparison_capture(Code, {ok, Code}) end, [{primary, 200}, {fallback, 503}]), 504 = receive_timeout(), {ok, 204} = local_fun(primary), ok = unused(primary), ignored = shadowed(primary), [503] = generator_shadow(), + {ok, 200} = local_comparison({ok, 200}), io:format("branch_export_warnings_ok~n"), ok. @@ -126,6 +129,21 @@ maybe_pattern_rhs(Status) -> {Value, Body} end. +%% A conditional value pattern reads an existing name solely for equality. +local_comparison(Input) -> + maybe begin Code = 200 end, {ok, Code} ?= Input end. + +comparison_after_case(Route, Input) -> + case Route of + primary -> Code = 200; + fallback -> Code = 503 + end, + maybe {ok, Code} ?= Input end. + +comparison_capture(Code, Input) -> + Read = fun() -> maybe {ok, Code} ?= Input end end, + Read(). + generator_shadow() -> [UnusedFilter || Input <- [200], begin UnusedFilter = Input, true end, UnusedFilter <- [503]].