Skip to content

Commit

Permalink
Fix Bugzilla 24582 - Detect unsafe cast(bool[])
Browse files Browse the repository at this point in the history
Allow literal cast

Make deprecation

Add specific supplemental message
  • Loading branch information
ntrel committed Jun 12, 2024
1 parent 295b000 commit 04bd8b2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
8 changes: 8 additions & 0 deletions compiler/src/dmd/safe.d
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,14 @@ bool isSafeCast(Expression e, Type tfrom, Type tto, string* msg = null)
return false;
}

// For bool, only 0 and 1 are safe values
// Runtime array cast reinterprets data
if (ttobn.ty == Tbool && tfromn.ty != Tbool && e.op != EXP.arrayLiteral)
{
if (msg)
*msg = "Array data may have bytes which are not 0 or 1";
}

// If the struct is opaque we don't know about the struct members then the cast becomes unsafe
if (ttobn.ty == Tstruct && !(cast(TypeStruct)ttobn).sym.members ||
tfromn.ty == Tstruct && !(cast(TypeStruct)tfromn).sym.members)
Expand Down
15 changes: 15 additions & 0 deletions compiler/test/fail_compilation/bool_cast.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
REQUIRED_ARGS: -de
TEST_OUTPUT:
---
fail_compilation/bool_cast.d(13): Deprecation: cast from `ubyte[]` to `bool[]` not allowed in safe code
fail_compilation/bool_cast.d(13): Array data may have bytes which are not 0 or 1
---
*/

void main() @safe
{
ubyte[] a = [2, 4];
auto b = cast(bool[]) a; // reinterprets a's data
auto c = cast(bool[]) [2, 4]; // literal cast applies to each element
}

0 comments on commit 04bd8b2

Please sign in to comment.