Repository navigation
Description
When I add safety checks to code (e.g. a panic that fires if the API user violates their end of the API contract), I want to be able to test those safety checks (e.g. by intentionally violating contract in the test, and checking that we get the expected panic). However, there doesn't seem to be any way to catch panics in Zig, even with a custom panic handler (which has to return noreturn, and thus cannot swallow the panic, or otherwise not halt/hang the program, as far as I can tell?), so this kind of testing doesn't seem to be possible. For comparison, Rust tests support this via the #[should_panic(expected = "substr")] annotation.
Some possible proposals:
-
Add a general mechanism for catching panics. Go has this in the form of
recover, and Rust hascatch_unwind. Zig could have a builtin to do a similar job. This builtin would be usable anywhere, but explicitly anti-recommended for ordinary error handling. -
Provide a
test-block-specific way to expect panics. Zig could have a builtin (e.g.@expectPanic(comptime expected_message_substr: []const u8)that would apply to the scope of thetestblock, and would cause the test to succeed if it panics with a matching message, or fail if it panics with the wrong message or doesn't panic at all. -
Don't add this feature at all, and live with the fact that safety checks have to be tested at a higher level (e.g. by running each expect-panic-test as a separate subprocess and expecting that subprocess to crash, e.g. how
{#code_begin|test_err|expected message#}inlangref.html.inappears to work). Perhaps some mechanism could be added tostd.buildto make this a bit easier.
My personal preference would be for (2), since that makes the tests very easy to write. If we want (1) as a more general mechanism, then perhaps we could still have (2), or something like it (possibly in userspace), as a convenience. If we don't want to support catching panics, then (3) could work, but I worry that that would make writing safety tests painful enough that library authors would be discouraged from writing them.
Activity
andrewrk commentedon Aug 8, 2018
This proposal would have the added benefit of allowing zig to self-host its runtime safety tests: https://github.com/ziglang/zig/blob/master/test/runtime_safety.zig
PavelVozenilek commentedon Aug 8, 2018
For tests which call
@panicor are rightfully expected to crash, add test annotation (as proposed in #1010 (comment), #567 and #513). Test runner would then fork, invoke just the crashing test and check the exit code. I'd say this is variant of the proposal # 3.Do not add any save-me-from-the-crash feature available to the user, that's the road to hell.
There's use case when you do handle very, very rare situation, but add an assert there, just to make sure that this rare situation doesn't occur by some mistake in your regular code. For this special variant of assert should be invented, as proposed in #1304 (comment). I use not very helpful name
assert2in C.Example:
bronze1man commentedon Aug 9, 2018
Please provide only one way to return and cache error.
Golang's
recoverfeature just make programer process their error withpanicand recover which is less code thanif xxx return xxx.But you will need to define function with two version, one return error, another panic if error happen. And two version of one functions is the begin of hell.But I think zig's error handle is easy enough which can just only use return error.
Crash process and catch by the parent process should be a good idea.
binary132 commentedon Aug 9, 2018
In my experience panic / recover is not really abused in Go much.
isaachier commentedon Aug 9, 2018
@binary132, look at how the Go JSON parser cleverly uses recover to handle invalid input errors.
Edit: Speak of the devil... an article on this topic: https://eli.thegreenplace.net/2018/on-the-uses-and-misuses-of-panics-in-go.
thejoshwolfe commentedon Aug 10, 2018
isn't this possible in userspace using setjmp (or equivalent) to effectively create a restore point and then longjmp out of your panic handler? Pretty sure this would never fly at comptime though.
isaachier commentedon Aug 10, 2018
This relates more to the LLVM IR and how it implements panics. There is definitely a mechanism in the IR to throw and recover from exceptions, but Zig might not want to expose this in the language to avoid abuse.
Update: More details here: https://llvm.org/docs/ExceptionHandling.html.
kristoff-it commentedon Apr 24, 2019
I think it's fairly common practice in Go to use
recoverto get a last chance to log remotely the final error message in a program before crashing.Without a way to do so, any logging instrumentation added to an executable will not be able to record everything and in some environments it can be a problem if you can't do remote logging properly. An alternative could be to use an external process to do the remote logging (so that it can also read the Zig executable's final message), but it's a nuisance, especially when deploying to a container.
If there are no bad technical implications, I would recommend leaving the option of using some kind of
recoverto the user also at run-time, not just for tests, even if the odd json parser library might abuse it.andrewrk commentedon Apr 25, 2019
Hi Loris, this is not documented yet (See #1517) but you can override the default panic function in the root source file. In the panic function you define what happens when an assertion fails. The default behavior is here: https://github.com/ziglang/zig/blob/56e07622c692f70eb10836b86c5fda02c53e2394/std/special/panic.zig
If you specify a panic handler in the root source file, like this:
Here you can do this logging instrumentation and then call the default panic handler, or do some other strategy.
kristoff-it commentedon Apr 25, 2019
Oh I see, so, if understand correctly, it can already be done but only at top level, where recover can instead be called at any level.
Could there be a legitimate reason for a library to want to hide panics?
I honestly don't know. Food for thought, at least for me.
Thank you for the clarification :)
thejoshwolfe commentedon Apr 26, 2019
It would be rare for a library to handle panics or to expect panics to be handled. such a library would probably advertise itself as a library specifically for managing application state, such as a logging library that "owns" stdout, stderr, and the panic handler. in such a scenario, the library would document that any application that wishes to take advantage of the panic handling code should define a top-level panic handler that calls into the library's implementation.
The reason there's no library-local support for handling panic is that crash-related situations have app-wide impact, and managing that is the responsibility of the app.
43 remaining items
matu3ba commentedon Apr 20, 2023
Andrew said, that he had some ideas (for pointer to stack memory, not sure if thats https://gist.github.com/PeyTy/7983dd85026cc061980a6a966bc1afc2), but the overall issue with #782 is that it is unfeasible to compute all possible paths to ensure proper cleanup happens (and its a huge compilation time cost) and then you are stuck with either affine memory ownership semantics (Rust) or linear ones + all the edge cases not handled by such system. Rust for example can introduce memory leaks.
That does not fix the core of the problem: Code, which panics may not have the cleanup handled in any way, because the user could assume the process crashes and the Kernel does the cleanup.
DoumanAsh commentedon Apr 20, 2023
As users it should be our responsibility to ensure that destructor code doesn't panic which would screw up stack unwinding even further.
Another important thing is that like in C++ it might be the best have way to detect if stack unwinding is ongoing, but overall I would just recommend not to panic in stack unwinding, or actually all panics should result in aborts if there is already stack unwinding
Do you mean that user didn't set up
defer?Because if
deferruns always, regardless of how function exits (normally or due to stack unwinding from panic) it would then let user ensure it runs, but it is up to user to use destructorNot necessary to be stack analysis, but even simplest way to disallow linking panic handler would be nice
We do not live in ideal world, so if your zig code is entry point you might want to have as much control as possible
jamii commentedon Apr 21, 2023
I was hoping that the below might do the trick, but it seems that panic is always referenced. Presumably because it's referenced directly from the compiler rather than by normal mechanisms?
DoumanAsh commentedon Apr 21, 2023
Yes, it should not work, compiler should still be able to compile code even if it is never used as it needs to verify validity of your code
The way I did it in Rust is by introducing destructor function that links invalid item and it would be eliminated during optimization if panic never happened.
This unfortunately is very bad way to do it so I don't think it is good idea to even try to use it
jamii commentedon Apr 21, 2023
Huh, yeah, that works (EDIT only in release-fast - it still fails to compile in release-safe):
@compileErroris only an error if it is reachable. Usually a function that contains compileError but is never called is fine. But panic must be special - maybe because it's referenced directly from the compiler, or from some builtin code that is always emitted.std.Build.RunStep: show test name on process termination
test_runner: enable testing panics in mainTerminal
loganbnielsen commentedon Jan 17, 2025
Looks like this hasn't been talked about in a hot minute. Any plans for it still or with the compiler optimizations, async, etc. is this something that we reasonably shouldn't expect for a couple years?