diff --git a/src/google/protobuf/compiler/cpp/helpers.cc b/src/google/protobuf/compiler/cpp/helpers.cc index dc19043434..0139c46477 100644 --- a/src/google/protobuf/compiler/cpp/helpers.cc +++ b/src/google/protobuf/compiler/cpp/helpers.cc @@ -1190,7 +1190,8 @@ bool IsWellKnownMessage(const FileDescriptor* file) { return well_known_files->find(file->name()) != well_known_files->end(); } -void NamespaceOpener::ChangeTo(absl::string_view name) { +void NamespaceOpener::ChangeTo(absl::string_view name, + io::Printer::SourceLocation loc) { std::vector new_stack = absl::StrSplit(name, "::", absl::SkipEmpty()); size_t len = std::min(name_stack_.size(), new_stack.size()); @@ -1205,12 +1206,14 @@ void NamespaceOpener::ChangeTo(absl::string_view name) { for (size_t i = name_stack_.size(); i > common_idx; i--) { p_->Emit({{"ns", name_stack_[i - 1]}}, R"( } // namespace $ns$ - )"); + )", + loc); } for (size_t i = common_idx; i < new_stack.size(); ++i) { p_->Emit({{"ns", new_stack[i]}}, R"( namespace $ns$ { - )"); + )", + loc); } name_stack_ = std::move(new_stack); diff --git a/src/google/protobuf/compiler/cpp/helpers.h b/src/google/protobuf/compiler/cpp/helpers.h index 40bb49f8e5..0ca2d55e75 100644 --- a/src/google/protobuf/compiler/cpp/helpers.h +++ b/src/google/protobuf/compiler/cpp/helpers.h @@ -979,21 +979,37 @@ void PrintFieldComment(const Formatter& format, const T* field, class PROTOC_EXPORT NamespaceOpener { public: - explicit NamespaceOpener(io::Printer* p) : p_(p) {} - explicit NamespaceOpener(const Formatter& format) : p_(format.printer()) {} - NamespaceOpener(absl::string_view name, const Formatter& format) - : NamespaceOpener(format) { - ChangeTo(name); + explicit NamespaceOpener( + io::Printer* p, + io::Printer::SourceLocation loc = io::Printer::SourceLocation::current()) + : p_(p), loc_(loc) {} + + explicit NamespaceOpener( + const Formatter& format, + io::Printer::SourceLocation loc = io::Printer::SourceLocation::current()) + : NamespaceOpener(format.printer(), loc) {} + + NamespaceOpener( + absl::string_view name, const Formatter& format, + io::Printer::SourceLocation loc = io::Printer::SourceLocation::current()) + : NamespaceOpener(name, format.printer(), loc) {} + + NamespaceOpener( + absl::string_view name, io::Printer* p, + io::Printer::SourceLocation loc = io::Printer::SourceLocation::current()) + : NamespaceOpener(p, loc) { + ChangeTo(name, loc); } - NamespaceOpener(absl::string_view name, io::Printer* p) : NamespaceOpener(p) { - ChangeTo(name); - } - ~NamespaceOpener() { ChangeTo(""); } - void ChangeTo(absl::string_view name); + ~NamespaceOpener() { ChangeTo("", loc_); } + + void ChangeTo( + absl::string_view name, + io::Printer::SourceLocation loc = io::Printer::SourceLocation::current()); private: io::Printer* p_; + io::Printer::SourceLocation loc_; std::vector name_stack_; };