Given that only 0 and 1 are safe values:
https://dlang.org/spec/function.html#safe-values
Each of the casts below should fail.
void main() @safe
{
bool v = cast(bool) 2;
ubyte[] a = [2, 4];
auto b = cast(bool[]) a;
auto c = cast(bool[]) [2, 4]; // literal cast
}
PR incoming.
Comment #1 by dlang-bot — 2024-06-03T13:09:06Z
@ntrel created dlang/dmd pull request #16558 "Fix Bugzilla 24582 - Detect unsafe casting to bool" fixing this issue:
- Fix Bugzilla 24582 - Detect unsafe casting to bool
https://github.com/dlang/dmd/pull/16558
Comment #2 by dkorpel — 2024-06-03T16:20:11Z
These casts only produce safe values 0 and 1 right?
Comment #3 by nick — 2024-06-03T19:31:30Z
bool v = cast(bool) 2;
ubyte[] a = [2, 4];
auto b = cast(bool[]) a;
auto c = cast(bool[]) [2, 4]; // literal cast
import std.stdio;
writeln(*cast(byte*)&v); // 1, OK
writeln(*cast(byte*)b.ptr); // 2, unsafe
writeln(*cast(byte*)c.ptr); // 1, OK
So only the runtime array cast is unsafe.
Comment #4 by dlang-bot — 2024-06-13T09:23:40Z
dlang/dmd pull request #16558 "Fix Bugzilla 24582 - Detect unsafe `cast(bool[])`" was merged into master:
- 04bd8b21ee11f7ab16d8dc97c28a5b37365db89f by Nick Treleaven:
Fix Bugzilla 24582 - Detect unsafe `cast(bool[])`
Allow literal cast
Make deprecation
Add specific supplemental message
https://github.com/dlang/dmd/pull/16558