diff --git a/CHANGELOG.md b/CHANGELOG.md index 9961721..4876ea2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,17 @@ All notable milestones for the nera project are documented in this file. covering evaluation order, guards, handlers, heads, funs, receive and list/binary comprehensions. +## Catch expressions preserve error stacktraces + +- `catch Expr` now returns `{'EXIT', {Reason, Stacktrace}}` for errors with + the captured stacktrace from `try ... catch Class:Reason:Stacktrace`, + instead of always returning an empty list. +- Re-raising with `erlang:raise/3` preserves the supplied trace, including + an explicitly empty one. Normal values, throws and exits are unchanged. +- The `catch_error_stacktrace` regression runs unchanged natively and on BEAM, + checking shared raising/caller frames and metadata, resumed errors, nested + catches and real full, shortened and empty re-raised traces. + ## Nested case bindings remain safe outer inputs - A variable bound on every path through nested cases remains available after diff --git a/crates/nera-ir/src/lower/expr.rs b/crates/nera-ir/src/lower/expr.rs index 828db6d..042ca2d 100644 --- a/crates/nera-ir/src/lower/expr.rs +++ b/crates/nera-ir/src/lower/expr.rs @@ -465,10 +465,11 @@ impl IrBuilder { // try Expr catch // throw:V -> V; // exit:V -> {'EXIT', V}; - // error:V -> {'EXIT', {V, []}} + // error:V:Stack -> {'EXIT', {V, Stack}} // end ast::Expr::Catch(operand, span) => { let val_id = self.atom_id_for("__catch_val__"); + let stack_id = self.atom_id_for("__catch_stack__"); let exit_id = self.atom_id_for("EXIT"); let s = *span; let val_pat = || ast::Pattern::Variable(val_id, s); @@ -498,11 +499,11 @@ impl IrBuilder { ast::CatchClause { class: ast::CatchClass::Error, pattern: val_pat(), - stacktrace: None, + stacktrace: Some(ast::Pattern::Variable(stack_id, s)), guard: None, body: vec![ast::Expr::Tuple(vec![ exit_atom(), - ast::Expr::Tuple(vec![val_var(), ast::Expr::Nil(s)], s), + ast::Expr::Tuple(vec![val_var(), ast::Expr::Variable(stack_id, s)], s), ], s)], span: s, }, diff --git a/tests/README.md b/tests/README.md index adb5107..13cc21f 100644 --- a/tests/README.md +++ b/tests/README.md @@ -273,6 +273,7 @@ These are automatically skipped by the runner and show up as SKIP in output. | `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, including each migrated arithmetic operator before a later side effect with exactly one cleanup entry; an after body that waits, times out and collects garbage; an uncaught exit; also run on BEAM | Table-driven | | `catch_expr.erl` | Catch expression | ~4 | +| `catch_error_stacktrace.erl` | Unary catch errors retain the real raising/caller frames and metadata from try/catch, including resumed errors, nested catches and full/shortened/empty real traces supplied to raise/3; normal/throw/exit controls; also run on BEAM | Table-driven | | `error_2.erl` | `error/2` and `erlang:error/2` raise `error:Reason` through the auto-imported and qualified names, a tail call, `apply/3`, a fun and a computed module, whatever `Args` holds; the code after the call does not run; `catch` gives `{'EXIT', {Reason, Stack}}`; also run on BEAM | 16 | | `error_3.erl` | `error/3` and `erlang:error/3` raise `error:Reason` with `error_info` options through direct, tail, apply, fun and computed calls; arbitrary Args/Options, argument evaluation, no continuation after raising, cleanup and catch; also run on BEAM | Table-driven | | `try_operation_short_circuit.erl` | An operator, unary op, map update, send, spawn, comprehension or `throw` that raises in a `try` body goes to the handler at once: no later send, put, receive or call runs and the first reason is kept, including `catch`, nested `try`, `of`, catch and `after` clauses; a raising guard there still just fails; outside `try`, each migrated arithmetic operator, a failed send or spawn or a `throw` stops the process at once and a map update evaluates every value first; also run on BEAM | Table-driven | diff --git a/tests/catch_error_stacktrace.erl b/tests/catch_error_stacktrace.erl new file mode 100644 index 0000000..0f08cda --- /dev/null +++ b/tests/catch_error_stacktrace.erl @@ -0,0 +1,118 @@ +%% EXPECT: catch_error_stacktrace_ok +%% Unary catch must return the real error stack, just like try/catch and BEAM. +-module(catch_error_stacktrace). +-export([test/0]). + +test() -> + lists:foreach(fun check_error/1, [error, badmatch, badarith]), + ok = check_resumed_error(), + ok = check_saved_stack(), + %% The other catch results do not acquire an error stack wrapper. + {outer, {middle, ok}} = caught(ok), + thrown = caught(throw), + {'EXIT', stopped} = caught(exit), + %% An inner catch clears the exception; an outer catch leaves its value alone. + {'EXIT', {boom, Nested}} = catch caught(error), + ok = check_frames(Nested), + %% A later error gets its own reason and stack, not the preceding catch's. + {'EXIT', {{badmatch, 2}, Later}} = caught(badmatch), + ok = check_frames(Later), + io:format("catch_error_stacktrace_ok~n"), + ok. + +check_error(Mode) -> + {error, Reason, TryStack} = captured(Mode), + {'EXIT', {Reason, CatchStack}} = caught(Mode), + %% The shared raising functions have identical frames, including metadata. + %% BEAM can prepend a BIF frame (for div/2); compare the shared Erlang calls. + %% Catching callers and runner frames can differ beyond that prefix. + Prefix = lists:sublist(module_frames(TryStack), 3), + Prefix = lists:sublist(module_frames(CatchStack), 3), + Label = case Mode of + {resumed_error, _} -> + %% Native try/catch currently loses callers across suspension. + %% Catch must preserve the same available frames, not fabricate them. + [{?MODULE, inner, 1, Info} | _] = Prefix, + true = is_list(Info), + resumed_error; + _ -> ok = check_frames(CatchStack), Mode + end, + io:format("~p: ~p~n", [Label, [{M, F, A} || {M, F, A, _} <- Prefix]]). + +check_resumed_error() -> + Parent = self(), + {Pid, Ref} = spawn_monitor(fun() -> + check_error({resumed_error, Parent}), + Parent ! {resumed_done, self()} + end), + %% Both captured/1 and caught/1 must suspend before their error is released. + release_waiter(Pid), + release_waiter(Pid), + receive {resumed_done, Pid} -> ok after 5000 -> error(missing_resumed_result) end, + receive {'DOWN', Ref, process, Pid, normal} -> ok + after 5000 -> error(missing_resumed_exit) + end. + +release_waiter(Pid) -> + receive + {stack_waiting, Pid} -> ok; + {'DOWN', _, process, Pid, Reason} -> error({stack_waiter_failed, Reason}) + after 5000 -> error(missing_stack_waiter) + end, + await_suspension(Pid), + Pid ! stack_go, + ok. + +%% Observe waiting rather than assume a timeout caused a real suspension. +await_suspension(Pid) -> + case process_info(Pid, status) of + {status, waiting} -> ok; + undefined -> error(stack_waiter_exited); + _ -> await_suspension(Pid) + end. + +check_frames(Stack) -> + [{?MODULE, inner, 1, InnerInfo}, {?MODULE, middle, 1, MiddleInfo}, + {?MODULE, outer, 1, OuterInfo} | _] = module_frames(Stack), + true = is_list(InnerInfo), + true = is_list(MiddleInfo), + true = is_list(OuterInfo), + ok. + +module_frames(Stack) -> + [Frame || {?MODULE, _, _, _} = Frame <- Stack]. + +check_saved_stack() -> + {error, boom, Original} = captured(error), + %% Use real captured frames, not a fabricated trace. raise/3 must preserve + %% every frame and its metadata, and an explicitly empty trace stays empty. + lists:foreach(fun(Stack) -> + {'EXIT', {reraised, Stack}} = catch erlang:raise(error, reraised, Stack), + %% An exit or throw still returns its usual form, even with a saved stack. + {'EXIT', stopped} = catch erlang:raise(exit, stopped, Stack), + thrown = catch erlang:raise(throw, thrown, Stack) + end, [Original, lists:sublist(Original, 3), []]), + io:format("saved full, shortened and empty stacks preserved~n"), + ok. + +caught(Mode) -> catch outer(Mode). + +captured(Mode) -> + try outer(Mode) + catch Class:Reason:Stack -> {Class, Reason, Stack} + end. + +%% Keep these calls non-tail so both native and BEAM retain the shared frames. +outer(Mode) -> {outer, middle(Mode)}. +middle(Mode) -> {middle, inner(Mode)}. +inner(error) -> erlang:error(boom); +inner(badmatch) -> 1 = id(2), ok; +inner(badarith) -> 1 div id(0); +inner({resumed_error, Parent}) -> + Parent ! {stack_waiting, self()}, + receive stack_go -> erlang:error(boom) end; +inner(throw) -> throw(thrown); +inner(exit) -> exit(stopped); +inner(ok) -> ok. + +id(X) -> X.