Skip to content

Commit

Permalink
Add formatting for source_location.
Browse files Browse the repository at this point in the history
  • Loading branch information
asoffer committed Sep 25, 2024
1 parent 7c0bad0 commit 0bc8d84
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
4 changes: 4 additions & 0 deletions nth/debug/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ cc_library(
name = "source_location",
hdrs = ["source_location.h"],
deps = [
"//nth/format",
"//nth/io/writer",
"//nth/utility:unconstructible",
],
)
Expand All @@ -36,6 +38,8 @@ cc_test(
srcs = ["source_location_test.cc"],
deps = [
":source_location",
"//nth/format",
"//nth/io/writer:string",
],
)

Expand Down
9 changes: 9 additions & 0 deletions nth/debug/source_location.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

#include <string_view>

#include "nth/format/format.h"
#include "nth/io/writer/writer.h"
#include "nth/utility/unconstructible.h"

namespace nth {
Expand Down Expand Up @@ -38,6 +40,13 @@ struct source_location {
// Returns the line number corresponding to this source location.
constexpr unsigned line() const { return line_; }

friend void NthFormat(auto& w, auto&, nth::source_location loc) {
nth::io::write_text(w, loc.file_);
nth::io::write_text(w, ":");
auto fmt = nth::default_formatter<unsigned>();
nth::format(w, fmt, loc.line_);
}

private:
explicit constexpr source_location(char const* file, char const* function,
unsigned line)
Expand Down
14 changes: 13 additions & 1 deletion nth/debug/source_location_test.cc
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
#include "nth/debug/source_location.h"

#include "nth/format/format.h"
#include "nth/io/writer/string.h"

namespace some_namespace {

static_assert([] {
Expand Down Expand Up @@ -35,4 +38,13 @@ static_assert([] {

} // namespace some_namespace

int main() { return 0; }
int main() {
#line 30 "some_file.cc"
nth::source_location loc = nth::source_location::current();
std::string s;
nth::io::string_writer w(s);
nth::format(w, loc);
if (s != "some_file.cc:31") return 1;

return 0;
}

0 comments on commit 0bc8d84

Please sign in to comment.