1 
2 #include "absl/strings/str_replace.h"
3 #include "upbc/common.h"
4 
5 namespace upbc {
6 namespace {
7 
8 namespace protobuf = ::google::protobuf;
9 
AddMessages(const protobuf::Descriptor * message,std::vector<const protobuf::Descriptor * > * messages)10 void AddMessages(const protobuf::Descriptor* message,
11                  std::vector<const protobuf::Descriptor*>* messages) {
12   messages->push_back(message);
13   for (int i = 0; i < message->nested_type_count(); i++) {
14     AddMessages(message->nested_type(i), messages);
15   }
16 }
17 
18 }  // namespace
19 
StripExtension(absl::string_view fname)20 std::string StripExtension(absl::string_view fname) {
21   size_t lastdot = fname.find_last_of(".");
22   if (lastdot == std::string::npos) {
23     return std::string(fname);
24   }
25   return std::string(fname.substr(0, lastdot));
26 }
27 
ToCIdent(absl::string_view str)28 std::string ToCIdent(absl::string_view str) {
29   return absl::StrReplaceAll(str, {{".", "_"}, {"/", "_"}});
30 }
31 
ToPreproc(absl::string_view str)32 std::string ToPreproc(absl::string_view str) {
33   return absl::AsciiStrToUpper(ToCIdent(str));
34 }
35 
EmitFileWarning(const protobuf::FileDescriptor * file,Output & output)36 void EmitFileWarning(const protobuf::FileDescriptor* file, Output& output) {
37   output(
38       "/* This file was generated by upbc (the upb compiler) from the input\n"
39       " * file:\n"
40       " *\n"
41       " *     $0\n"
42       " *\n"
43       " * Do not edit -- your changes will be discarded when the file is\n"
44       " * regenerated. */\n\n",
45       file->name());
46 }
47 
SortedMessages(const protobuf::FileDescriptor * file)48 std::vector<const protobuf::Descriptor*> SortedMessages(
49     const protobuf::FileDescriptor* file) {
50   std::vector<const protobuf::Descriptor*> messages;
51   for (int i = 0; i < file->message_type_count(); i++) {
52     AddMessages(file->message_type(i), &messages);
53   }
54   return messages;
55 }
56 
MessageName(const protobuf::Descriptor * descriptor)57 std::string MessageName(const protobuf::Descriptor* descriptor) {
58   return ToCIdent(descriptor->full_name());
59 }
60 
MessageInit(const protobuf::Descriptor * descriptor)61 std::string MessageInit(const protobuf::Descriptor* descriptor) {
62   return MessageName(descriptor) + "_msginit";
63 }
64 
65 }  // namespace upbc
66