Skip to content

Commit d59b959

Browse files
committed
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.
1 parent 1f607b5 commit d59b959

2 files changed

Lines changed: 11 additions & 10 deletions

File tree

src/libutil/error.cc

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include "nix/util/terminal.hh"
77
#include "nix/util/position.hh"
88

9+
#include <cinttypes>
910
#include <iostream>
1011
#include <optional>
1112
#include "nix/util/serialise.hh"
@@ -439,10 +440,16 @@ void panic(std::string_view msg)
439440
std::terminate();
440441
}
441442

442-
void panic(const char * file, int line, const char * func)
443+
void unreachable(std::source_location loc)
443444
{
444445
char buf[512];
445-
int n = snprintf(buf, sizeof(buf), "Unexpected condition in %s at %s:%d", func, file, line);
446+
int n = snprintf(
447+
buf,
448+
sizeof(buf),
449+
"Unexpected condition in %s at %s:%" PRIuLEAST32,
450+
loc.function_name(),
451+
loc.file_name(),
452+
loc.line());
446453
if (n < 0)
447454
panic("Unexpected condition and could not format error message");
448455
panic(std::string_view(buf, std::min(static_cast<int>(sizeof(buf)), n)));

src/libutil/include/nix/util/error.hh

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <list>
2323
#include <memory>
2424
#include <optional>
25+
#include <utility>
2526

2627
#include <sys/types.h>
2728
#include <sys/stat.h>
@@ -304,18 +305,11 @@ void throwExceptionSelfCheck();
304305
[[noreturn]]
305306
void panic(std::string_view msg);
306307

307-
/**
308-
* Print a basic error message with source position and std::terminate().
309-
* Use the unreachable() macro to call this.
310-
*/
311-
[[noreturn]]
312-
void panic(const char * file, int line, const char * func);
313-
314308
/**
315309
* Print a basic error message with source position and std::terminate().
316310
*
317311
* @note: This assumes that the logger is operational
318312
*/
319-
#define unreachable() (::nix::panic(__FILE__, __LINE__, __func__))
313+
[[gnu::noinline, gnu::cold, noreturn]] void unreachable(std::source_location loc = std::source_location::current());
320314

321315
} // namespace nix

0 commit comments

Comments
 (0)