Skip to content

Commit df8bf16

Browse files
authored
[refine](core) add compile-time safety checks to assert_cast (apache#63133)
### What problem does this PR solve? Issue Number: N/A Problem Summary: `assert_cast` previously only performed runtime type checks (via `typeid` comparison). Misuse — such as casting between unrelated types or upcasting — would only be caught at runtime, making it easy for incorrect usage to slip into release builds where `TypeCheckOnRelease::DISABLE` turns checks into `static_cast` without any verification. This catches invalid casts at build time instead of producing undefined behavior or hard-to-diagnose runtime errors.
1 parent ab7f8a6 commit df8bf16

1 file changed

Lines changed: 8 additions & 0 deletions

File tree

‎be/src/core/assert_cast.h‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ struct AssertCastNormalizedType {
4242
template <typename T>
4343
using AssertCastNormalizedType_t = typename AssertCastNormalizedType<T>::type;
4444

45+
template <typename T>
46+
using AssertCastClassType_t = std::remove_pointer_t<AssertCastNormalizedType_t<T>>;
47+
4548
/** Perform static_cast in release build when TypeCheckOnRelease is set to DISABLE.
4649
* Checks type by comparing typeid and throw an exception in all the other situations.
4750
* The exact match of the type is checked. That is, cast to the ancestor will be unsuccessful.
@@ -50,6 +53,11 @@ template <typename To, TypeCheckOnRelease check = TypeCheckOnRelease::ENABLE, ty
5053
PURE To assert_cast(From&& from) {
5154
static_assert(!std::is_same_v<AssertCastNormalizedType_t<To>, AssertCastNormalizedType_t<From>>,
5255
"assert_cast is redundant for the same type after removing cv/ref qualifiers");
56+
static_assert(std::is_class_v<AssertCastClassType_t<To>> &&
57+
std::is_class_v<AssertCastClassType_t<From>>,
58+
"assert_cast requires casting between class pointer/reference types");
59+
static_assert(std::is_base_of_v<AssertCastClassType_t<From>, AssertCastClassType_t<To>>,
60+
"assert_cast only supports downcast from a base type to a derived type");
5361

5462
// https://godbolt.org/z/nrsx7nYhs
5563
// perform_cast will not be compiled to asm in release build with TypeCheckOnRelease::DISABLE

0 commit comments

Comments
 (0)