Add further diagnostics under clang for string_view(nullptr)

Detection isn't perfect, but it is better than nothing:
https://godbolt.org/z/YzeMeb58j

PiperOrigin-RevId: 837204651
Change-Id: Id1027c4c27bd95ad923e4c5d242a28079b16db79
This commit is contained in:
Derek Mauro
2025-11-26 11:46:04 -08:00
committed by Copybara-Service
parent 9d35bf52e7
commit 18bd00ad42

View File

@@ -58,6 +58,15 @@ ABSL_NAMESPACE_END
#else // ABSL_USES_STD_STRING_VIEW
#if ABSL_HAVE_ATTRIBUTE(diagnose_if)
#define ABSL_INTERNAL_DIAGNOSE_IF_NULLPTR(x) \
__attribute__((diagnose_if( \
x == nullptr, \
"null passed to a callee that requires a non-null argument", "error")))
#else
#define ABSL_INTERNAL_DIAGNOSE_IF_NULLPTR(x)
#endif
#if ABSL_HAVE_BUILTIN(__builtin_memcmp) || \
(defined(__GNUC__) && !defined(__clang__)) || \
(defined(_MSC_VER) && _MSC_VER >= 1928)
@@ -225,7 +234,7 @@ class ABSL_ATTRIBUTE_VIEW string_view {
// instead (see below).
// The length check is skipped since it is unnecessary and causes code bloat.
constexpr string_view( // NOLINT(runtime/explicit)
const char* absl_nonnull str)
const char* absl_nonnull str) ABSL_INTERNAL_DIAGNOSE_IF_NULLPTR(str)
: ptr_(str), length_(str ? StrlenInternal(str) : 0) {
ABSL_HARDENING_ASSERT(str != nullptr);
}
@@ -779,6 +788,7 @@ std::ostream& operator<<(std::ostream& o, string_view piece);
ABSL_NAMESPACE_END
} // namespace absl
#undef ABSL_INTERNAL_DIAGNOSE_IF_NULLPTR
#undef ABSL_INTERNAL_STRING_VIEW_MEMCMP
#endif // ABSL_USES_STD_STRING_VIEW