• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Author: kenton@google.com (Kenton Varda)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 
35 #include <map>
36 
37 #include <google/protobuf/compiler/cpp/cpp_enum.h>
38 #include <google/protobuf/compiler/cpp/cpp_helpers.h>
39 #include <google/protobuf/io/printer.h>
40 #include <google/protobuf/stubs/strutil.h>
41 
42 namespace google {
43 namespace protobuf {
44 namespace compiler {
45 namespace cpp {
46 
47 namespace {
48 // The GOOGLE_ARRAYSIZE constant is the max enum value plus 1. If the max enum value
49 // is kint32max, GOOGLE_ARRAYSIZE will overflow. In such cases we should omit the
50 // generation of the GOOGLE_ARRAYSIZE constant.
ShouldGenerateArraySize(const EnumDescriptor * descriptor)51 bool ShouldGenerateArraySize(const EnumDescriptor* descriptor) {
52   int32 max_value = descriptor->value(0)->number();
53   for (int i = 0; i < descriptor->value_count(); i++) {
54     if (descriptor->value(i)->number() > max_value) {
55       max_value = descriptor->value(i)->number();
56     }
57   }
58   return max_value != kint32max;
59 }
60 
61 // Returns the number of unique numeric enum values. This is less than
62 // descriptor->value_count() when there are aliased values.
CountUniqueValues(const EnumDescriptor * descriptor)63 int CountUniqueValues(const EnumDescriptor* descriptor) {
64   std::set<int> values;
65   for (int i = 0; i < descriptor->value_count(); ++i) {
66     values.insert(descriptor->value(i)->number());
67   }
68   return values.size();
69 }
70 
71 }  // namespace
72 
EnumGenerator(const EnumDescriptor * descriptor,const std::map<std::string,std::string> & vars,const Options & options)73 EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
74                              const std::map<std::string, std::string>& vars,
75                              const Options& options)
76     : descriptor_(descriptor),
77       classname_(ClassName(descriptor, false)),
78       options_(options),
79       generate_array_size_(ShouldGenerateArraySize(descriptor)),
80       variables_(vars) {
81   variables_["classname"] = classname_;
82   variables_["classtype"] = QualifiedClassName(descriptor_, options);
83   variables_["short_name"] = descriptor_->name();
84   variables_["nested_name"] = descriptor_->name();
85   variables_["resolved_name"] = ResolveKeyword(descriptor_->name());
86   variables_["prefix"] =
87       (descriptor_->containing_type() == NULL) ? "" : classname_ + "_";
88 }
89 
~EnumGenerator()90 EnumGenerator::~EnumGenerator() {}
91 
GenerateDefinition(io::Printer * printer)92 void EnumGenerator::GenerateDefinition(io::Printer* printer) {
93   Formatter format(printer, variables_);
94   format("enum ${1$$classname$$}$ : int {\n", descriptor_);
95   format.Indent();
96 
97   const EnumValueDescriptor* min_value = descriptor_->value(0);
98   const EnumValueDescriptor* max_value = descriptor_->value(0);
99 
100   for (int i = 0; i < descriptor_->value_count(); i++) {
101     auto format_value = format;
102     format_value.Set("name", EnumValueName(descriptor_->value(i)));
103     // In C++, an value of -2147483648 gets interpreted as the negative of
104     // 2147483648, and since 2147483648 can't fit in an integer, this produces a
105     // compiler warning.  This works around that issue.
106     format_value.Set("number", Int32ToString(descriptor_->value(i)->number()));
107     format_value.Set("deprecation",
108                      DeprecatedAttribute(options_, descriptor_->value(i)));
109 
110     if (i > 0) format_value(",\n");
111     format_value("${1$$prefix$$name$$}$ $deprecation$= $number$",
112                  descriptor_->value(i));
113 
114     if (descriptor_->value(i)->number() < min_value->number()) {
115       min_value = descriptor_->value(i);
116     }
117     if (descriptor_->value(i)->number() > max_value->number()) {
118       max_value = descriptor_->value(i);
119     }
120   }
121 
122   if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
123     // For new enum semantics: generate min and max sentinel values equal to
124     // INT32_MIN and INT32_MAX
125     if (descriptor_->value_count() > 0) format(",\n");
126     format(
127         "$classname$_$prefix$INT_MIN_SENTINEL_DO_NOT_USE_ = "
128         "std::numeric_limits<$int32$>::min(),\n"
129         "$classname$_$prefix$INT_MAX_SENTINEL_DO_NOT_USE_ = "
130         "std::numeric_limits<$int32$>::max()");
131   }
132 
133   format.Outdent();
134   format("\n};\n");
135 
136   format(
137       "$dllexport_decl $bool $classname$_IsValid(int value);\n"
138       "constexpr $classname$ ${1$$prefix$$short_name$_MIN$}$ = "
139       "$prefix$$2$;\n"
140       "constexpr $classname$ ${1$$prefix$$short_name$_MAX$}$ = "
141       "$prefix$$3$;\n",
142       descriptor_, EnumValueName(min_value), EnumValueName(max_value));
143 
144   if (generate_array_size_) {
145     format(
146         "constexpr int ${1$$prefix$$short_name$_ARRAYSIZE$}$ = "
147         "$prefix$$short_name$_MAX + 1;\n\n",
148         descriptor_);
149   }
150 
151   if (HasDescriptorMethods(descriptor_->file(), options_)) {
152     format(
153         "$dllexport_decl $const ::$proto_ns$::EnumDescriptor* "
154         "$classname$_descriptor();\n");
155   }
156 
157   // The _Name and _Parse functions. The lite implementation is table-based, so
158   // we make sure to keep the tables hidden in the .cc file.
159   if (!HasDescriptorMethods(descriptor_->file(), options_)) {
160     format("const std::string& $classname$_Name($classname$ value);\n");
161   }
162   // The _Name() function accepts the enum type itself but also any integral
163   // type.
164   format(
165       "template<typename T>\n"
166       "inline const std::string& $classname$_Name(T enum_t_value) {\n"
167       "  static_assert(::std::is_same<T, $classname$>::value ||\n"
168       "    ::std::is_integral<T>::value,\n"
169       "    \"Incorrect type passed to function $classname$_Name.\");\n");
170   if (HasDescriptorMethods(descriptor_->file(), options_)) {
171     format(
172         "  return ::$proto_ns$::internal::NameOfEnum(\n"
173         "    $classname$_descriptor(), enum_t_value);\n");
174   } else {
175     format(
176         "  return $classname$_Name(static_cast<$classname$>(enum_t_value));\n");
177   }
178   format("}\n");
179 
180   if (HasDescriptorMethods(descriptor_->file(), options_)) {
181     format(
182         "inline bool $classname$_Parse(\n"
183         "    ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, $classname$* "
184         "value) "
185         "{\n"
186         "  return ::$proto_ns$::internal::ParseNamedEnum<$classname$>(\n"
187         "    $classname$_descriptor(), name, value);\n"
188         "}\n");
189   } else {
190     format(
191         "bool $classname$_Parse(\n"
192         "    ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, $classname$* "
193         "value);\n");
194   }
195 }
196 
GenerateGetEnumDescriptorSpecializations(io::Printer * printer)197 void EnumGenerator::GenerateGetEnumDescriptorSpecializations(
198     io::Printer* printer) {
199   Formatter format(printer, variables_);
200   format(
201       "template <> struct is_proto_enum< $classtype$> : ::std::true_type "
202       "{};\n");
203   if (HasDescriptorMethods(descriptor_->file(), options_)) {
204     format(
205         "template <>\n"
206         "inline const EnumDescriptor* GetEnumDescriptor< $classtype$>() {\n"
207         "  return $classtype$_descriptor();\n"
208         "}\n");
209   }
210 }
211 
GenerateSymbolImports(io::Printer * printer) const212 void EnumGenerator::GenerateSymbolImports(io::Printer* printer) const {
213   Formatter format(printer, variables_);
214   format("typedef $classname$ $resolved_name$;\n");
215 
216   for (int j = 0; j < descriptor_->value_count(); j++) {
217     std::string deprecated_attr =
218         DeprecatedAttribute(options_, descriptor_->value(j));
219     format(
220         "$1$static constexpr $resolved_name$ ${2$$3$$}$ =\n"
221         "  $classname$_$3$;\n",
222         deprecated_attr, descriptor_->value(j),
223         EnumValueName(descriptor_->value(j)));
224   }
225 
226   format(
227       "static inline bool $nested_name$_IsValid(int value) {\n"
228       "  return $classname$_IsValid(value);\n"
229       "}\n"
230       "static constexpr $resolved_name$ ${1$$nested_name$_MIN$}$ =\n"
231       "  $classname$_$nested_name$_MIN;\n"
232       "static constexpr $resolved_name$ ${1$$nested_name$_MAX$}$ =\n"
233       "  $classname$_$nested_name$_MAX;\n",
234       descriptor_);
235   if (generate_array_size_) {
236     format(
237         "static constexpr int ${1$$nested_name$_ARRAYSIZE$}$ =\n"
238         "  $classname$_$nested_name$_ARRAYSIZE;\n",
239         descriptor_);
240   }
241 
242   if (HasDescriptorMethods(descriptor_->file(), options_)) {
243     format(
244         "static inline const ::$proto_ns$::EnumDescriptor*\n"
245         "$nested_name$_descriptor() {\n"
246         "  return $classname$_descriptor();\n"
247         "}\n");
248   }
249 
250   format(
251       "template<typename T>\n"
252       "static inline const std::string& $nested_name$_Name(T enum_t_value) {\n"
253       "  static_assert(::std::is_same<T, $resolved_name$>::value ||\n"
254       "    ::std::is_integral<T>::value,\n"
255       "    \"Incorrect type passed to function $nested_name$_Name.\");\n"
256       "  return $classname$_Name(enum_t_value);\n"
257       "}\n");
258   format(
259       "static inline bool "
260       "$nested_name$_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name,\n"
261       "    $resolved_name$* value) {\n"
262       "  return $classname$_Parse(name, value);\n"
263       "}\n");
264 }
265 
GenerateMethods(int idx,io::Printer * printer)266 void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) {
267   Formatter format(printer, variables_);
268   if (HasDescriptorMethods(descriptor_->file(), options_)) {
269     format(
270         "const ::$proto_ns$::EnumDescriptor* $classname$_descriptor() {\n"
271         "  ::$proto_ns$::internal::AssignDescriptors(&$desc_table$);\n"
272         "  return $file_level_enum_descriptors$[$1$];\n"
273         "}\n",
274         idx);
275   }
276 
277   format(
278       "bool $classname$_IsValid(int value) {\n"
279       "  switch (value) {\n");
280 
281   // Multiple values may have the same number.  Make sure we only cover
282   // each number once by first constructing a set containing all valid
283   // numbers, then printing a case statement for each element.
284 
285   std::set<int> numbers;
286   for (int j = 0; j < descriptor_->value_count(); j++) {
287     const EnumValueDescriptor* value = descriptor_->value(j);
288     numbers.insert(value->number());
289   }
290 
291   for (std::set<int>::iterator iter = numbers.begin(); iter != numbers.end();
292        ++iter) {
293     format("    case $1$:\n", Int32ToString(*iter));
294   }
295 
296   format(
297       "      return true;\n"
298       "    default:\n"
299       "      return false;\n"
300       "  }\n"
301       "}\n"
302       "\n");
303 
304   if (!HasDescriptorMethods(descriptor_->file(), options_)) {
305     // In lite mode (where descriptors are unavailable), we generate separate
306     // tables for mapping between enum names and numbers. The _entries table
307     // contains the bulk of the data and is sorted by name, while
308     // _entries_by_number is sorted by number and just contains pointers into
309     // _entries. The two tables allow mapping from name to number and number to
310     // name, both in time logarithmic in the number of enum entries. This could
311     // probably be made faster, but for now the tables are intended to be simple
312     // and compact.
313     //
314     // Enums with allow_alias = true support multiple entries with the same
315     // numerical value. In cases where there are multiple names for the same
316     // number, we treat the first name appearing in the .proto file as the
317     // canonical one.
318     std::map<std::string, int> name_to_number;
319     std::map<int, std::string> number_to_canonical_name;
320     for (int i = 0; i < descriptor_->value_count(); i++) {
321       const EnumValueDescriptor* value = descriptor_->value(i);
322       name_to_number.emplace(value->name(), value->number());
323       // The same number may appear with multiple names, so we use emplace() to
324       // let the first name win.
325       number_to_canonical_name.emplace(value->number(), value->name());
326     }
327 
328     format(
329         "static ::$proto_ns$::internal::ExplicitlyConstructed<std::string> "
330         "$classname$_strings[$1$] = {};\n\n",
331         CountUniqueValues(descriptor_));
332 
333     // We concatenate all the names for a given enum into one big string
334     // literal. If instead we store an array of string literals, the linker
335     // seems to put all enum strings for a given .proto file in the same
336     // section, which hinders its ability to strip out unused strings.
337     format("static const char $classname$_names[] =");
338     for (const auto& p : name_to_number) {
339       format("\n  \"$1$\"", p.first);
340     }
341     format(";\n\n");
342 
343     format(
344         "static const ::$proto_ns$::internal::EnumEntry $classname$_entries[] "
345         "= {\n");
346     int i = 0;
347     std::map<int, int> number_to_index;
348     int data_index = 0;
349     for (const auto& p : name_to_number) {
350       format("  { {$classname$_names + $1$, $2$}, $3$ },\n", data_index,
351              p.first.size(), p.second);
352       if (number_to_canonical_name[p.second] == p.first) {
353         number_to_index.emplace(p.second, i);
354       }
355       ++i;
356       data_index += p.first.size();
357     }
358 
359     format(
360         "};\n"
361         "\n"
362         "static const int $classname$_entries_by_number[] = {\n");
363     for (const auto& p : number_to_index) {
364       format("  $1$, // $2$ -> $3$\n", p.second, p.first,
365              number_to_canonical_name[p.first]);
366     }
367     format(
368         "};\n"
369         "\n");
370 
371     format(
372         "const std::string& $classname$_Name(\n"
373         "    $classname$ value) {\n"
374         "  static const bool dummy =\n"
375         "      ::$proto_ns$::internal::InitializeEnumStrings(\n"
376         "          $classname$_entries,\n"
377         "          $classname$_entries_by_number,\n"
378         "          $1$, $classname$_strings);\n"
379         "  (void) dummy;\n"
380         "  int idx = ::$proto_ns$::internal::LookUpEnumName(\n"
381         "      $classname$_entries,\n"
382         "      $classname$_entries_by_number,\n"
383         "      $1$, value);\n"
384         "  return idx == -1 ? ::$proto_ns$::internal::GetEmptyString() :\n"
385         "                     $classname$_strings[idx].get();\n"
386         "}\n",
387         CountUniqueValues(descriptor_));
388     format(
389         "bool $classname$_Parse(\n"
390         "    ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, $classname$* "
391         "value) "
392         "{\n"
393         "  int int_value;\n"
394         "  bool success = ::$proto_ns$::internal::LookUpEnumValue(\n"
395         "      $classname$_entries, $1$, name, &int_value);\n"
396         "  if (success) {\n"
397         "    *value = static_cast<$classname$>(int_value);\n"
398         "  }\n"
399         "  return success;\n"
400         "}\n",
401         descriptor_->value_count());
402   }
403 
404   if (descriptor_->containing_type() != NULL) {
405     std::string parent = ClassName(descriptor_->containing_type(), false);
406     // Before C++17, we must define the static constants which were
407     // declared in the header, to give the linker a place to put them.
408     // But pre-2015 MSVC++ insists that we not.
409     format(
410         "#if (__cplusplus < 201703) && "
411         "(!defined(_MSC_VER) || _MSC_VER >= 1900)\n");
412 
413     for (int i = 0; i < descriptor_->value_count(); i++) {
414       format("constexpr $classname$ $1$::$2$;\n", parent,
415              EnumValueName(descriptor_->value(i)));
416     }
417     format(
418         "constexpr $classname$ $1$::$nested_name$_MIN;\n"
419         "constexpr $classname$ $1$::$nested_name$_MAX;\n",
420         parent);
421     if (generate_array_size_) {
422       format("constexpr int $1$::$nested_name$_ARRAYSIZE;\n", parent);
423     }
424 
425     format(
426         "#endif  // (__cplusplus < 201703) && "
427         "(!defined(_MSC_VER) || _MSC_VER >= 1900)\n");
428   }
429 }
430 
431 }  // namespace cpp
432 }  // namespace compiler
433 }  // namespace protobuf
434 }  // namespace google
435