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 #include <map>
32 #include <string>
33 
34 #include <google/protobuf/compiler/objectivec/objectivec_enum.h>
35 #include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
36 #include <google/protobuf/io/printer.h>
37 #include <google/protobuf/stubs/strutil.h>
38 
39 namespace google {
40 namespace protobuf {
41 namespace compiler {
42 namespace objectivec {
43 
EnumGenerator(const EnumDescriptor * descriptor)44 EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor)
45     : descriptor_(descriptor),
46       name_(EnumName(descriptor_)) {
47   for (int i = 0; i < descriptor_->value_count(); i++) {
48     const EnumValueDescriptor* value = descriptor_->value(i);
49     const EnumValueDescriptor* canonical_value =
50         descriptor_->FindValueByNumber(value->number());
51 
52     if (value == canonical_value) {
53       base_values_.push_back(value);
54     }
55     all_values_.push_back(value);
56   }
57 }
58 
~EnumGenerator()59 EnumGenerator::~EnumGenerator() {}
60 
GenerateHeader(io::Printer * printer)61 void EnumGenerator::GenerateHeader(io::Printer* printer) {
62   string enum_comments;
63   SourceLocation location;
64   if (descriptor_->GetSourceLocation(&location)) {
65     enum_comments = BuildCommentsString(location);
66   } else {
67     enum_comments = "";
68   }
69 
70   printer->Print(
71       "#pragma mark - Enum $name$\n"
72       "\n",
73       "name", name_);
74 
75   printer->Print("$comments$typedef$deprecated_attribute$ GPB_ENUM($name$) {\n",
76                  "comments", enum_comments,
77                  "deprecated_attribute", GetOptionalDeprecatedAttribute(descriptor_),
78                  "name", name_);
79   printer->Indent();
80 
81   if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
82     // Include the unknown value.
83     printer->Print(
84       "/// Value used if any message's field encounters a value that is not defined\n"
85       "/// by this enum. The message will also have C functions to get/set the rawValue\n"
86       "/// of the field.\n"
87       "$name$_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,\n",
88       "name", name_);
89   }
90   for (int i = 0; i < all_values_.size(); i++) {
91     SourceLocation location;
92     if (all_values_[i]->GetSourceLocation(&location)) {
93       string comments = BuildCommentsString(location).c_str();
94       if (comments.length() > 0) {
95         if (i > 0) {
96           printer->Print("\n");
97         }
98         printer->Print(comments.c_str());
99       }
100     }
101 
102     printer->Print(
103         "$name$$deprecated_attribute$ = $value$,\n",
104         "name", EnumValueName(all_values_[i]),
105         "deprecated_attribute", GetOptionalDeprecatedAttribute(all_values_[i]),
106         "value", SimpleItoa(all_values_[i]->number()));
107   }
108   printer->Outdent();
109   printer->Print(
110       "};\n"
111       "\n"
112       "GPBEnumDescriptor *$name$_EnumDescriptor(void);\n"
113       "\n"
114       "/// Checks to see if the given value is defined by the enum or was not known at\n"
115       "/// the time this source was generated.\n"
116       "BOOL $name$_IsValidValue(int32_t value);\n"
117       "\n",
118       "name", name_);
119 }
120 
GenerateSource(io::Printer * printer)121 void EnumGenerator::GenerateSource(io::Printer* printer) {
122   printer->Print(
123       "#pragma mark - Enum $name$\n"
124       "\n",
125       "name", name_);
126 
127   // Note: For the TextFormat decode info, we can't use the enum value as
128   // the key because protocol buffer enums have 'allow_alias', which lets
129   // a value be used more than once. Instead, the index into the list of
130   // enum value descriptions is used. Note: start with -1 so the first one
131   // will be zero.
132   TextFormatDecodeData text_format_decode_data;
133   int enum_value_description_key = -1;
134   string text_blob;
135 
136   for (int i = 0; i < all_values_.size(); i++) {
137     ++enum_value_description_key;
138     string short_name(EnumValueShortName(all_values_[i]));
139     text_blob += short_name + '\0';
140     if (UnCamelCaseEnumShortName(short_name) != all_values_[i]->name()) {
141       text_format_decode_data.AddString(enum_value_description_key, short_name,
142                                         all_values_[i]->name());
143     }
144   }
145 
146   printer->Print(
147       "GPBEnumDescriptor *$name$_EnumDescriptor(void) {\n"
148       "  static GPBEnumDescriptor *descriptor = NULL;\n"
149       "  if (!descriptor) {\n",
150       "name", name_);
151 
152   static const int kBytesPerLine = 40;  // allow for escaping
153   printer->Print(
154       "    static const char *valueNames =");
155   for (int i = 0; i < text_blob.size(); i += kBytesPerLine) {
156     printer->Print(
157         "\n        \"$data$\"",
158         "data", EscapeTrigraphs(CEscape(text_blob.substr(i, kBytesPerLine))));
159   }
160   printer->Print(
161       ";\n"
162       "    static const int32_t values[] = {\n");
163   for (int i = 0; i < all_values_.size(); i++) {
164     printer->Print("        $name$,\n",  "name", EnumValueName(all_values_[i]));
165   }
166   printer->Print("    };\n");
167 
168   if (text_format_decode_data.num_entries() == 0) {
169     printer->Print(
170         "    GPBEnumDescriptor *worker =\n"
171         "        [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol($name$)\n"
172         "                                       valueNames:valueNames\n"
173         "                                           values:values\n"
174         "                                            count:(uint32_t)(sizeof(values) / sizeof(int32_t))\n"
175         "                                     enumVerifier:$name$_IsValidValue];\n",
176         "name", name_);
177     } else {
178       printer->Print(
179         "    static const char *extraTextFormatInfo = \"$extraTextFormatInfo$\";\n"
180         "    GPBEnumDescriptor *worker =\n"
181         "        [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol($name$)\n"
182         "                                       valueNames:valueNames\n"
183         "                                           values:values\n"
184         "                                            count:(uint32_t)(sizeof(values) / sizeof(int32_t))\n"
185         "                                     enumVerifier:$name$_IsValidValue\n"
186         "                              extraTextFormatInfo:extraTextFormatInfo];\n",
187         "name", name_,
188         "extraTextFormatInfo", CEscape(text_format_decode_data.Data()));
189     }
190     printer->Print(
191       "    if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) {\n"
192       "      [worker release];\n"
193       "    }\n"
194       "  }\n"
195       "  return descriptor;\n"
196       "}\n\n");
197 
198   printer->Print(
199       "BOOL $name$_IsValidValue(int32_t value__) {\n"
200       "  switch (value__) {\n",
201       "name", name_);
202 
203   for (int i = 0; i < base_values_.size(); i++) {
204     printer->Print(
205         "    case $name$:\n",
206         "name", EnumValueName(base_values_[i]));
207   }
208 
209   printer->Print(
210       "      return YES;\n"
211       "    default:\n"
212       "      return NO;\n"
213       "  }\n"
214       "}\n\n");
215 }
216 }  // namespace objectivec
217 }  // namespace compiler
218 }  // namespace protobuf
219 }  // namespace google
220