diff --git a/CHANGELOG.md b/CHANGELOG.md index 050fb91..acf2937 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,16 @@ All notable milestones for the nera project are documented in this file. `term_to_binary/1`, `erlang:phash2/1` or `iolist_to_binary/1` on them can still crash; [known limits](docs/KNOWN_LIMITS.md) gives the depths. +## Unmatched try-of clauses keep the unmatched value in their error + +- When no `try ... of` clause matches, Nera now raises + `error:{try_clause, Value}` with the try body's unmatched result, as on + BEAM. Previously it raised the bare atom `try_clause`. +- The exception still bypasses that try's own catch clauses, and any + `after` body runs once before an enclosing handler receives the error. +- The `try_clause` fixture checks unmatched terms, failed guards, matching + clauses and exception handling natively and on BEAM. + ## error/3 compiles and raises its reason - `error(Reason, Args, Options)` and `erlang:error(Reason, Args, Options)` diff --git a/crates/nera-ir/src/lower/exception.rs b/crates/nera-ir/src/lower/exception.rs index 095f70c..76d41f6 100644 --- a/crates/nera-ir/src/lower/exception.rs +++ b/crates/nera-ir/src/lower/exception.rs @@ -307,7 +307,9 @@ impl IrBuilder { self.emit_set_line(first_clause.span); } let tc_atom = self.atom_id_for("try_clause"); - let reason = self.emit_const(Literal::Atom(tc_atom)); + let reason_atom = self.emit_const(Literal::Atom(tc_atom)); + let reason = self.fresh_var(); + self.emit(Instruction::MakeTuple(reason, vec![reason_atom, body_result])); let exc_result = self.fresh_var(); self.emit(Instruction::RaiseException(exc_result, ExceptionClass::Error, reason)); self.set_raise_terminator(exc_result); diff --git a/crates/nera-ir/src/lower/tests.rs b/crates/nera-ir/src/lower/tests.rs index 02ebf30..569a1e4 100644 --- a/crates/nera-ir/src/lower/tests.rs +++ b/crates/nera-ir/src/lower/tests.rs @@ -2142,6 +2142,47 @@ fn case_clause_reason_retains_scrutinee_in_each_context() { } } +#[test] +fn try_clause_reason_retains_body_result() { + // The runtime fixture owns observable exception behavior. This test owns + // the lowering contract: the error tuple must use the try body's result. + let source = include_str!("../../../../tests/try_clause.erl"); + let ir = lower_source(source).unwrap(); + let mut parser = Parser::new(source); + parser.parse_module(); + let atoms = parser.atom_names(); + let atom = |name: &str| { + *atoms.iter().find(|(_, text)| text.as_str() == name).unwrap().0 + }; + for name in ["unmatched", "guarded", "with_after", "with_catch_after"] { + let function = ir.functions.iter().find(|f| f.name == atom(name)).unwrap(); + let instructions: Vec<_> = function.blocks.iter() + .flat_map(|block| &block.instructions).collect(); + let body_result = instructions.iter().find_map(|instruction| match instruction { + Instruction::Call(result, CallTarget::Local(target), args) + if *target == atom("id") && args == &function.params => Some(*result), + _ => None, + }).expect("fixture must pass its argument through id/1"); + let mut checked = 0; + for instruction in &instructions { + if let Instruction::RaiseException(_, ExceptionClass::Error, reason) = instruction { + let fields = instructions.iter().find_map(|instruction| match instruction { + Instruction::MakeTuple(dst, fields) if dst == reason => Some(fields), + _ => None, + }).expect("try_clause reason must be a tuple"); + assert_eq!(fields.len(), 2); + assert_eq!(fields[1], body_result, "{name} lost the try body's result"); + assert!(instructions.iter().any(|instruction| matches!(instruction, + Instruction::Const(dst, Literal::Atom(tag)) + if *dst == fields[0] && *tag == atom("try_clause") + ))); + checked += 1; + } + } + assert_eq!(checked, 1, "expected one try-of failure path in {name}"); + } +} + #[test] fn try_protection_is_lexical_not_forward_reachable() { let ir = lower_source("-module(test). -export([f/0]). f() -> g(), try g() catch throw:E -> E end, ok. g() -> ok.").unwrap(); diff --git a/tests/README.md b/tests/README.md index 3cd840e..d1211a5 100644 --- a/tests/README.md +++ b/tests/README.md @@ -225,6 +225,7 @@ These are automatically skipped by the runner and show up as SKIP in output. | `receive_timeout_bindings.erl` | Names bound in a `receive`'s `after` timeout expression, read after the `receive`: the timeout and message paths, a block timeout, binary tails, later patterns, guards, fun captures and fun-head map keys; also run on BEAM | 6 | | `exception_basic.erl` | try/catch/throw/error/exit | ~12 | | `try_of.erl` | try...of clause | ~6 | +| `try_clause.erl` | Unmatched try-of results raise error:{try_clause, Value}: exact unmatched terms, failed guards, local-catch bypass and after cleanup, with matching and body-exception controls; also run on BEAM | Table-driven | | `try_catch_bound_vars.erl` | Bound names in try-of and catch class/reason patterns: exact equality, guards, fresh names, binary tails and re-raise; also run on BEAM | Table-driven | | `try_after_reraise.erl` | `try ... after` as the only handler in its function: the after body runs once when the body, an `of` clause or a catch clause raises, then the same class, reason and stacktrace reach the caller; a normal return keeps the body's value; an exception from the after body replaces the held one; an after body that waits, times out and collects garbage; an uncaught exit; also run on BEAM | 28 | | `catch_expr.erl` | Catch expression | ~4 | diff --git a/tests/try_clause.erl b/tests/try_clause.erl new file mode 100644 index 0000000..42a9758 --- /dev/null +++ b/tests/try_clause.erl @@ -0,0 +1,92 @@ +%% EXPECT: try_clause_ok +%% Unmatched try-of results raise error:{try_clause, Value}, outside the +%% try's own catch clauses, after running any after body once. Run this +%% same fixture on native Nera and BEAM. +-module(try_clause). +-export([test/0]). + +test() -> + Values = [unexpected, 42, 1.5, [], [1, two | tail], + {accepted, 0}, {accepted, not_integer}, + {reply, error, <<"payload">>}, <<"bytes">>, + #{status => rejected, detail => [1, 2]}, 1 bsl 100], + lists:foreach(fun(Value) -> + {error, {try_clause, Value}} = outcome(fun() -> unmatched(Value) end), + {error, {try_clause, Value}} = outcome(fun() -> guarded(Value) end), + {error, {try_clause, Value}} = outcome(fun() -> with_after(Value) end), + [cleaned] = drain(), + {error, {try_clause, Value}} = outcome(fun() -> with_catch_after(Value) end), + [cleaned] = drain() + end, Values), + + %% An enclosing handler in the same function sees the tuple too. + Value = id({unmatched, <<"outer">>}), + {try_clause, Value} = try + try id(Value) of + accepted -> wrong + catch + _:_ -> wrong_local_handler + end + catch + error:Reason -> Reason + end, + + %% Matching clauses still return their result; body exceptions still + %% reach this try's catch, unlike failures in the of clauses. + matched = unmatched(accepted), + matched = guarded({accepted, 7}), + matched = with_after(accepted), + [cleaned] = drain(), + caught_body = try error(body_failure) of + _ -> wrong + catch + error:body_failure -> caught_body + end, + {error, of_failure} = outcome(fun() -> + try id(accepted) of + accepted -> error(of_failure) + catch + _:_ -> wrong_local_handler + end + end), + [] = drain(), + io:format("try_clause_ok~n"), + ok. + +unmatched(Value) -> + try id(Value) of + accepted -> matched + catch + _:_ -> wrong_local_handler + end. + +guarded(Value) -> + try id(Value) of + {accepted, N} when is_integer(N), N > 0 -> matched; + _ when Value =:= accepted -> matched + catch + _:_ -> wrong_local_handler + end. + +with_after(Value) -> + try id(Value) of + accepted -> matched + after + self() ! cleaned + end. + +with_catch_after(Value) -> + try id(Value) of + accepted -> matched + catch + _:_ -> wrong_local_handler + after + self() ! cleaned + end. + +outcome(F) -> + try {ok, F()} catch Class:Reason -> {Class, Reason} end. + +drain() -> receive Message -> [Message | drain()] after 0 -> [] end. + +id(Value) -> Value.