Proposal to add builtin @illegal(x: bool) void

I propose to add a builtin function that looks something like this:
@illegal(x: bool) void
EDIT: actually i meant the following signature: @illegal(x: anytype) void
It asserts that the given expression triggers safety checked illegal behavior.
It’s a no-op in unchecked built modes.

Furthermore, this builtin could have arguments to indicate which type of illegal behaviour should trigger, in which function …

I’m not sure if an idea similiar to this one was already discussed, please give a link in that case.

std.debug.assert(x: bool) void also triggers safety checked illegal behavior and is no-op in unchecked built modes. How this one will be different?

From quick search i found this discussion which sounds similar to what you are proposing Proposal : builtin @assert() One assert to rule them all

1 Like

no, my proposal does not assert that the expression is true, but that the expression itself triggers illegal behaviour somewhere. (the argument x could actually be of any type)

ie. if the expression does not trigger illegal behaviour then this builtin triggers illegal behviour otherwise does nothing.

In what situations would you use @illegal()?

to document behaviour. just like you do with normal asserts, but to ensure expected illegal beviour is actually illegal.
eg. in a test:
// this documents that key must be absent from the map for a call to insert_unique(key, val) to be legal.
map.insert(key, value1);
@illegal(map.insert_unique(key, value2));
// this documents that array.get_last() is illegal behaviour if array.length() == 0
array.clear();
assert(array.length() == 0);
@illegal(array.get_last())

In these cases I would do assert(map.contains(key)) or assert(array.items.len == 0). Do you have situations, where you would use @illegal(), where an assert is not possible.

No, because for @illegal to work there the respective safety checks / assertions must already be implemented.
However I argue that this builtin would make expressing some intent simpler without duplicating the assertion code.
assertions check that code that is supposed to be legal is legal and is semantically correct.
@illegal() checks that code that is supposed to be illegal is illegal.
ie. assertions check normal code and @illegal checks the assertion.
you could think of them as meta assertions. dont know if this makes sense though.

one use case i have in mind:
currently api users have to read documentation or internal source code to know the assumptions of the api. violating these assumptions would be illegal behaviour.
with my proposed builtin is is possible to document those assumptions with code tests from the outside.
again im unsure about the usefulness.