Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ All notable milestones for the nera project are documented in this file.
mixed generators, closures, deferred bitstring tails, short-circuit filters,
conditional rematches and evaluation traces.

## Short-circuit bindings report their unsafe operator

- `nera check` and `nera build` report `variable 'Y' unsafe in 'andalso'`
(or `orelse`) when later code reads a name bound only in the right operand,
matching `erlc` rather than reporting only an unbound-variable error.
- Prebound names, bindings from the left operand and names used only within
the right operand remain valid. Fun and comprehension bindings stay local.
- Enclosing match patterns and later `maybe` items or comprehension filters
cannot reuse conditional names as fresh bindings. The same checks apply in
expression callees, receive timeouts and record-default expressions.
- Formatting preserves parentheses around match, send and catch operands of
binary operators, including flattened chains, so these programs retain their
syntax and grouping after formatting.
- Analyzer, formatter and compile-error regressions cover both short-circuit
operators.

## Unsupported float segment widths compile as on OTP 29

- Literal float segment widths outside the supported encodings no longer reject
Expand Down
20 changes: 11 additions & 9 deletions crates/nera-fmt/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1059,16 +1059,18 @@ impl<'src> Formatter<'src> {
/// This prevents `(A =:= B) and (C =:= D)` from being emitted as
/// `A =:= B and C =:= D` (which re-parses with different grouping).
fn format_binop_child(&mut self, child: &Expr, parent_prec: u8) -> Doc {
if let Expr::BinOp(child_op, _, _, _) = child {
if binop_precedence(*child_op) < parent_prec {
return concat_all(vec![
text("("),
self.format_expr(child),
text(")"),
]);
}
let needs_grouping = match child {
Expr::BinOp(child_op, _, _, _) => binop_precedence(*child_op) < parent_prec,
// These bind more weakly than every binary operator, including
// when they occur at either end of a flattened operator chain.
Expr::Match(..) | Expr::Send(..) | Expr::Catch(..) => true,
_ => false,
};
if needs_grouping {
concat_all(vec![text("("), self.format_expr(child), text(")")])
} else {
self.format_expr(child)
}
self.format_expr(child)
}

// ── Helper formatters ───────────────────────────────────────────
Expand Down
82 changes: 82 additions & 0 deletions crates/nera-fmt/tests/binary_operand_grouping.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
use nera_fmt::{config::FormatConfig, format_source};
use nera_syntax::{ast::Expr, parser::Parser};

#[test]
fn short_circuit_binding_fixtures_preserve_rhs_matches() {
// The unsafe-binding compiler fixtures exposed lost parentheses in CI.
// Formatting must retain their syntax and the match inside the operand.
for source in [
include_str!("../../../tests/andalso_unsafe_binding.erl"),
include_str!("../../../tests/orelse_unsafe_binding.erl"),
] {
let formatted = format_source(source, &FormatConfig::default()).unwrap();
let parsed = Parser::new(&formatted).parse_module();
assert!(!parsed.has_errors(), "{:?}\n{formatted}", parsed.errors);
let Expr::Match(_, value, _) = &parsed.module.functions[0].clauses[0].body[0] else {
panic!("lost outer match: {formatted}");
};
let Expr::BinOp(_, _, rhs, _) = value.as_ref() else {
panic!("lost short-circuit expression: {formatted}");
};
assert!(matches!(rhs.as_ref(), Expr::Match(..)), "{formatted}");
assert_eq!(
formatted,
format_source(&formatted, &FormatConfig::default()).unwrap()
);
}
}

#[test]
fn weak_operands_keep_their_binary_operator_boundary() {
// The shared binary-child formatter handles both operands and flattened
// chains. Match, send and catch all bind more weakly than binary operators.
for (expression, left) in [
("(Y = A) andalso B", true),
("A andalso (Y = B)", false),
("(Y = A) andalso B andalso true", true),
("A andalso B andalso (Y = true)", false),
("(Pid ! true) orelse A", true),
("A orelse (Pid ! true)", false),
("(catch A) orelse B", true),
("A orelse (catch B)", false),
] {
let source = format!("-module(test). f(A, B, Pid) -> {expression}.");
let original = Parser::new(&source).parse_module();
assert!(!original.has_errors(), "{:?}", original.errors);
let formatted = format_source(&source, &FormatConfig::default()).unwrap();
let parsed = Parser::new(&formatted).parse_module();
assert!(!parsed.has_errors(), "{:?}\n{formatted}", parsed.errors);
let before = &original.module.functions[0].clauses[0].body[0];
let after = &parsed.module.functions[0].clauses[0].body[0];
let (
Expr::BinOp(before_op, before_lhs, before_rhs, _),
Expr::BinOp(after_op, after_lhs, after_rhs, _),
) = (before, after)
else {
panic!("lost binary operator boundary: {formatted}");
};
assert_eq!(before_op, after_op);
let (mut before_child, mut after_child) = if left {
(before_lhs.as_ref(), after_lhs.as_ref())
} else {
(before_rhs.as_ref(), after_rhs.as_ref())
};
if left {
while let Expr::BinOp(_, lhs, _, _) = before_child {
before_child = lhs;
}
while let Expr::BinOp(_, lhs, _, _) = after_child {
after_child = lhs;
}
}
assert_eq!(
std::mem::discriminant(before_child),
std::mem::discriminant(after_child),
"changed operand kind: {formatted}"
);
assert_eq!(
formatted,
format_source(&formatted, &FormatConfig::default()).unwrap()
);
}
}
66 changes: 44 additions & 22 deletions crates/nera-ir/src/warnings/ast_walkers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,28 +341,7 @@ fn collect_refs(expr: &ast::Expr, refs: &mut HashSet<AtomId>, scoping: RefScopin
ast::Expr::ListComp(body, qualifiers, _) | ast::Expr::BinComp(body, qualifiers, _)
if scoping == RefScoping::Lexical =>
{
// Generator patterns bind fresh names for later qualifiers and the
// body. A generator's source and pattern inputs are read before
// its own pattern binds.
let mut fresh = HashSet::new();
let mut local = HashSet::new();
for q in qualifiers {
match q {
ast::LcQualifier::Generator(pat, expr, _)
| ast::LcQualifier::BinGenerator(pat, expr, _) => {
collect_pattern_refs(pat, &mut local);
collect_refs(expr, &mut local, scoping);
refs.extend(local.drain().filter(|id| !fresh.contains(id)));
collect_pattern_bindings(pat, &mut fresh);
}
ast::LcQualifier::Filter(expr, _) => {
collect_refs(expr, &mut local, scoping);
refs.extend(local.drain().filter(|id| !fresh.contains(id)));
}
}
}
collect_refs(body, &mut local, scoping);
refs.extend(local.difference(&fresh).copied());
collect_comprehension_refs(body, qualifiers, refs);
}
ast::Expr::ListComp(body, qualifiers, _) | ast::Expr::BinComp(body, qualifiers, _) => {
collect_refs(body, refs, scoping);
Expand Down Expand Up @@ -406,6 +385,15 @@ fn collect_refs(expr: &ast::Expr, refs: &mut HashSet<AtomId>, scoping: RefScopin
}
}
for clause in catch_clauses {
if scoping == RefScoping::Lexical {
if let ast::CatchClass::Variable(name, _) = clause.class {
refs.insert(name);
}
if let Some(stacktrace) = &clause.stacktrace {
collect_pattern_bindings(stacktrace, refs);
collect_pattern_refs(stacktrace, refs);
}
}
collect_pattern_bindings(&clause.pattern, refs);
collect_pattern_refs(&clause.pattern, refs);
if let Some(ref guard) = clause.guard {
Expand Down Expand Up @@ -469,6 +457,9 @@ fn collect_refs(expr: &ast::Expr, refs: &mut HashSet<AtomId>, 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);
}
collect_pattern_refs(pat, refs);
collect_refs(e, refs, scoping);
}
Expand Down Expand Up @@ -517,6 +508,37 @@ fn collect_refs(expr: &ast::Expr, refs: &mut HashSet<AtomId>, scoping: RefScopin
}
}

/// Reads supplied before these qualifiers, respecting later generator
/// bindings. Unsafe-name checks use the same lexical rules as captures.
pub(super) fn collect_comprehension_refs(
body: &ast::Expr,
qualifiers: &[ast::LcQualifier],
refs: &mut HashSet<AtomId>,
) {
// Generator patterns bind fresh names for later qualifiers and the
// body. A generator's source and pattern inputs are read before
// its own pattern binds.
let mut fresh = HashSet::new();
let mut local = HashSet::new();
for q in qualifiers {
match q {
ast::LcQualifier::Generator(pat, expr, _)
| ast::LcQualifier::BinGenerator(pat, expr, _) => {
collect_pattern_refs(pat, &mut local);
collect_enclosing_refs(expr, &mut local);
refs.extend(local.drain().filter(|id| !fresh.contains(id)));
collect_pattern_bindings(pat, &mut fresh);
}
ast::LcQualifier::Filter(expr, _) => {
collect_enclosing_refs(expr, &mut local);
refs.extend(local.drain().filter(|id| !fresh.contains(id)));
}
}
}
collect_enclosing_refs(body, &mut local);
refs.extend(local.difference(&fresh).copied());
}

/// Collect variable references in a guard.
pub(crate) fn collect_guard_refs(
guard: &ast::Guard,
Expand Down
1 change: 1 addition & 0 deletions crates/nera-ir/src/warnings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ pub fn analyze_module_with_source(
unused_funcs::check_unused_functions(module, atom_names, &mut warnings);
binary_segments::check_binary_segments_records(module, &mut warnings);
unbound_vars::check_unbound_variables_records(module, atom_names, &mut warnings);
unsafe_vars::check_unsafe_variables_records(module, atom_names, &mut warnings);
unused_records::check_unused_records(module, atom_names, &mut warnings);
unused_types::check_unused_types(module, atom_names, &mut warnings);
undefined_exports::check_undefined_exports(module, atom_names, &mut warnings);
Expand Down
Loading
Loading