From c750f0f6302f554f7366460e784c48810ac03a64 Mon Sep 17 00:00:00 2001 From: Sergei Zimmerman Date: Fri, 29 Aug 2025 00:21:04 +0300 Subject: [PATCH] libutil: Use std::source_location for unreachable Make unreachable a function instead of a macro, since C++20 provides a convenience class as a replacement for older __FILE__, __LINE__ macros. (cherry picked from commit d59b959c8724510532e0beb9d8337a8bb864fb9a) --- src/libutil/error.cc | 11 +++++++++-- src/libutil/include/nix/util/error.hh | 10 ++-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/libutil/error.cc b/src/libutil/error.cc index c36026f6c..35e42823c 100644 --- a/src/libutil/error.cc +++ b/src/libutil/error.cc @@ -6,6 +6,7 @@ #include "nix/util/terminal.hh" #include "nix/util/position.hh" +#include #include #include #include "nix/util/serialise.hh" @@ -439,10 +440,16 @@ void panic(std::string_view msg) std::terminate(); } -void panic(const char * file, int line, const char * func) +void unreachable(std::source_location loc) { char buf[512]; - int n = snprintf(buf, sizeof(buf), "Unexpected condition in %s at %s:%d", func, file, line); + int n = snprintf( + buf, + sizeof(buf), + "Unexpected condition in %s at %s:%" PRIuLEAST32, + loc.function_name(), + loc.file_name(), + loc.line()); if (n < 0) panic("Unexpected condition and could not format error message"); panic(std::string_view(buf, std::min(static_cast(sizeof(buf)), n))); diff --git a/src/libutil/include/nix/util/error.hh b/src/libutil/include/nix/util/error.hh index 549116c4d..e564ca5b9 100644 --- a/src/libutil/include/nix/util/error.hh +++ b/src/libutil/include/nix/util/error.hh @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -304,18 +305,11 @@ void throwExceptionSelfCheck(); [[noreturn]] void panic(std::string_view msg); -/** - * Print a basic error message with source position and std::terminate(). - * Use the unreachable() macro to call this. - */ -[[noreturn]] -void panic(const char * file, int line, const char * func); - /** * Print a basic error message with source position and std::terminate(). * * @note: This assumes that the logger is operational */ -#define unreachable() (::nix::panic(__FILE__, __LINE__, __func__)) +[[gnu::noinline, gnu::cold, noreturn]] void unreachable(std::source_location loc = std::source_location::current()); } // namespace nix