1 // Protocol Buffers - Google's data interchange format 2 // Copyright 2023 Google LLC. All rights reserved. 3 // 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file or at 6 // https://developers.google.com/open-source/licenses/bsd 7 8 #ifndef UPB_GENERATOR_COMMON_H 9 #define UPB_GENERATOR_COMMON_H 10 11 #include <string> 12 #include <vector> 13 14 #include "absl/strings/str_replace.h" 15 #include "absl/strings/substitute.h" 16 #include "upb/reflection/def.hpp" 17 18 // Must be last. 19 #include "google/protobuf/port_def.inc" 20 21 namespace upb { 22 namespace generator { 23 24 class Output { 25 public: 26 template <class... Arg> operator()27 void operator()(absl::string_view format, const Arg&... arg) { 28 Write(absl::Substitute(format, arg...)); 29 } 30 output()31 absl::string_view output() const { return output_; } 32 33 private: Write(absl::string_view data)34 void Write(absl::string_view data) { 35 std::string stripped; 36 if (absl::StartsWith(data, "\n ")) { 37 size_t indent = data.substr(1).find_first_not_of(' '); 38 if (indent != absl::string_view::npos) { 39 // Remove indentation from all lines. 40 auto line_prefix = data.substr(0, indent + 1); 41 // The final line has an extra newline and is indented two less, eg. 42 // R"cc( 43 // UPB_INLINE $0 $1_$2(const $1 *msg) { 44 // return $1_has_$2(msg) ? *UPB_PTR_AT(msg, $3, $0) : $4; 45 // } 46 // )cc", 47 std::string last_line_prefix = std::string(line_prefix); 48 last_line_prefix.resize(last_line_prefix.size() - 2); 49 data.remove_prefix(line_prefix.size()); 50 stripped = absl::StrReplaceAll( 51 data, {{line_prefix, "\n"}, {last_line_prefix, "\n"}}); 52 data = stripped; 53 } 54 } 55 absl::StrAppend(&output_, data); 56 } 57 58 std::string output_; 59 }; 60 61 std::string FieldInitializer(upb::FieldDefPtr field, 62 const upb_MiniTableField* field64, 63 const upb_MiniTableField* field32); 64 std::string ArchDependentSize(int64_t size32, int64_t size64); 65 std::string GetModeInit(const upb_MiniTableField* field32, 66 const upb_MiniTableField* field64); 67 std::string GetFieldRep(const upb_MiniTableField* field32, 68 const upb_MiniTableField* field64); 69 70 } // namespace generator 71 } // namespace upb 72 73 #include "google/protobuf/port_undef.inc" 74 75 #endif // UPB_GENERATOR_COMMON_H 76