What is the purpose of std.testing.refAllDecls()?

Hi there, sorry if this is a newbie question but I was wondering if I was using the testing functionality of zig incorrectly. I have a program that produces a compile error when it calls a function due to a type mismatch. I am assuming that the function is normally skipped by the compiler, since this only happens when I call the function. I wanted to make a test that will catch these sorts of errors since the codebase I am working in is large and there could be many errors like this one. I had assumed that std.testing.refAllDecls(@This()) or std.testing.refAllDeclsRecursive(@This()) in the main.zig file would do what I wanted, but it seems to still be passing. Is there already a way to accomplish what I want, or do I need to manually call each function to find compile errors?

2 Likes

@devindotzip Welcome to the forum!

First, I’m going to point you to a Git issue: `std.testing.refAllDecls` references `pub` decls only, private ones are ignored · Issue #12838 · ziglang/zig · GitHub

In there, you’ll find the following quote from @andrewrk:

refAllDecls is a hack that will almost certainly be removed from 
the standard library, and reflection will never inspect private 
declarations.

So we need a bit more info about your code. If you have private functions/declarations, then you will not get those picked up (see the Git issue). In the library file itself, consider putting a test inside that file with refAllDecls called where the functions are still internally accessible.

3 Likes

You correctly understand the purpose of refAllDecls(), and assuming that the erroneous function is actually referenced directly or indirectly from main then it should be analyzed—but not its body, if it’s not called.

In this example, foo is referenced but not called, so the test passes despite the bug.

test {
    _ = foo;
}
fn foo() void {
    var x: bool = 2; // compilation error if foo() is called
    _ = x;
}
$ zig test blah.zig
All 1 tests passed.
5 Likes