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 #include <algorithm> // std::find()
39
40 namespace google {
41 namespace protobuf {
42 namespace compiler {
43 namespace objectivec {
44
EnumGenerator(const EnumDescriptor * descriptor)45 EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor)
46 : descriptor_(descriptor),
47 name_(EnumName(descriptor_)) {
48 // Track the names for the enum values, and if an alias overlaps a base
49 // value, skip making a name for it. Likewise if two alias overlap, the
50 // first one wins.
51 // The one gap in this logic is if two base values overlap, but for that
52 // to happen you have to have "Foo" and "FOO" or "FOO_BAR" and "FooBar",
53 // and if an enum has that, it is already going to be confusing and a
54 // compile error is just fine.
55 // The values are still tracked to support the reflection apis and
56 // TextFormat handing since they are different there.
57 std::set<std::string> value_names;
58
59 for (int i = 0; i < descriptor_->value_count(); i++) {
60 const EnumValueDescriptor* value = descriptor_->value(i);
61 const EnumValueDescriptor* canonical_value =
62 descriptor_->FindValueByNumber(value->number());
63
64 if (value == canonical_value) {
65 base_values_.push_back(value);
66 value_names.insert(EnumValueName(value));
67 } else {
68 string value_name(EnumValueName(value));
69 if (value_names.find(value_name) != value_names.end()) {
70 alias_values_to_skip_.insert(value);
71 } else {
72 value_names.insert(value_name);
73 }
74 }
75 all_values_.push_back(value);
76 }
77 }
78
~EnumGenerator()79 EnumGenerator::~EnumGenerator() {}
80
GenerateHeader(io::Printer * printer)81 void EnumGenerator::GenerateHeader(io::Printer* printer) {
82 string enum_comments;
83 SourceLocation location;
84 if (descriptor_->GetSourceLocation(&location)) {
85 enum_comments = BuildCommentsString(location, true);
86 } else {
87 enum_comments = "";
88 }
89
90 printer->Print(
91 "#pragma mark - Enum $name$\n"
92 "\n",
93 "name", name_);
94
95 // Swift 5 included SE0192 "Handling Future Enum Cases"
96 // https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md
97 // Since a .proto file can get new values added to an enum at any time, they
98 // are effectively "non-frozen". Even in a proto3 syntax file where there is
99 // support for the unknown value, an edit to the file can always add a new
100 // value moving something from unknown to known. Since Swift is now ABI
101 // stable, it also means a binary could contain Swift compiled against one
102 // version of the .pbobjc.h file, but finally linked against an enum with
103 // more cases. So the Swift code will always have to treat ObjC Proto Enums
104 // as "non-frozen". The default behavior in SE0192 is for all objc enums to
105 // be "non-frozen" unless marked as otherwise, so this means this generation
106 // doesn't have to bother with the `enum_extensibility` attribute, as the
107 // default will be what is needed.
108
109 printer->Print("$comments$typedef$deprecated_attribute$ GPB_ENUM($name$) {\n",
110 "comments", enum_comments,
111 "deprecated_attribute", GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()),
112 "name", name_);
113 printer->Indent();
114
115 if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
116 // Include the unknown value.
117 printer->Print(
118 "/**\n"
119 " * Value used if any message's field encounters a value that is not defined\n"
120 " * by this enum. The message will also have C functions to get/set the rawValue\n"
121 " * of the field.\n"
122 " **/\n"
123 "$name$_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,\n",
124 "name", name_);
125 }
126 for (int i = 0; i < all_values_.size(); i++) {
127 if (alias_values_to_skip_.find(all_values_[i]) != alias_values_to_skip_.end()) {
128 continue;
129 }
130 SourceLocation location;
131 if (all_values_[i]->GetSourceLocation(&location)) {
132 string comments = BuildCommentsString(location, true).c_str();
133 if (comments.length() > 0) {
134 if (i > 0) {
135 printer->Print("\n");
136 }
137 printer->Print(comments.c_str());
138 }
139 }
140
141 printer->Print(
142 "$name$$deprecated_attribute$ = $value$,\n",
143 "name", EnumValueName(all_values_[i]),
144 "deprecated_attribute", GetOptionalDeprecatedAttribute(all_values_[i]),
145 "value", StrCat(all_values_[i]->number()));
146 }
147 printer->Outdent();
148 printer->Print(
149 "};\n"
150 "\n"
151 "GPBEnumDescriptor *$name$_EnumDescriptor(void);\n"
152 "\n"
153 "/**\n"
154 " * Checks to see if the given value is defined by the enum or was not known at\n"
155 " * the time this source was generated.\n"
156 " **/\n"
157 "BOOL $name$_IsValidValue(int32_t value);\n"
158 "\n",
159 "name", name_);
160 }
161
GenerateSource(io::Printer * printer)162 void EnumGenerator::GenerateSource(io::Printer* printer) {
163 printer->Print(
164 "#pragma mark - Enum $name$\n"
165 "\n",
166 "name", name_);
167
168 // Note: For the TextFormat decode info, we can't use the enum value as
169 // the key because protocol buffer enums have 'allow_alias', which lets
170 // a value be used more than once. Instead, the index into the list of
171 // enum value descriptions is used. Note: start with -1 so the first one
172 // will be zero.
173 TextFormatDecodeData text_format_decode_data;
174 int enum_value_description_key = -1;
175 string text_blob;
176
177 for (int i = 0; i < all_values_.size(); i++) {
178 ++enum_value_description_key;
179 string short_name(EnumValueShortName(all_values_[i]));
180 text_blob += short_name + '\0';
181 if (UnCamelCaseEnumShortName(short_name) != all_values_[i]->name()) {
182 text_format_decode_data.AddString(enum_value_description_key, short_name,
183 all_values_[i]->name());
184 }
185 }
186
187 printer->Print(
188 "GPBEnumDescriptor *$name$_EnumDescriptor(void) {\n"
189 " static _Atomic(GPBEnumDescriptor*) descriptor = nil;\n"
190 " if (!descriptor) {\n",
191 "name", name_);
192
193 static const int kBytesPerLine = 40; // allow for escaping
194 printer->Print(
195 " static const char *valueNames =");
196 for (int i = 0; i < text_blob.size(); i += kBytesPerLine) {
197 printer->Print(
198 "\n \"$data$\"",
199 "data", EscapeTrigraphs(CEscape(text_blob.substr(i, kBytesPerLine))));
200 }
201 printer->Print(
202 ";\n"
203 " static const int32_t values[] = {\n");
204 for (int i = 0; i < all_values_.size(); i++) {
205 printer->Print(" $name$,\n", "name", EnumValueName(all_values_[i]));
206 }
207 printer->Print(" };\n");
208
209 if (text_format_decode_data.num_entries() == 0) {
210 printer->Print(
211 " GPBEnumDescriptor *worker =\n"
212 " [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol($name$)\n"
213 " valueNames:valueNames\n"
214 " values:values\n"
215 " count:(uint32_t)(sizeof(values) / sizeof(int32_t))\n"
216 " enumVerifier:$name$_IsValidValue];\n",
217 "name", name_);
218 } else {
219 printer->Print(
220 " static const char *extraTextFormatInfo = \"$extraTextFormatInfo$\";\n"
221 " GPBEnumDescriptor *worker =\n"
222 " [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol($name$)\n"
223 " valueNames:valueNames\n"
224 " values:values\n"
225 " count:(uint32_t)(sizeof(values) / sizeof(int32_t))\n"
226 " enumVerifier:$name$_IsValidValue\n"
227 " extraTextFormatInfo:extraTextFormatInfo];\n",
228 "name", name_,
229 "extraTextFormatInfo", CEscape(text_format_decode_data.Data()));
230 }
231 printer->Print(
232 " GPBEnumDescriptor *expected = nil;\n"
233 " if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) {\n"
234 " [worker release];\n"
235 " }\n"
236 " }\n"
237 " return descriptor;\n"
238 "}\n\n");
239
240 printer->Print(
241 "BOOL $name$_IsValidValue(int32_t value__) {\n"
242 " switch (value__) {\n",
243 "name", name_);
244
245 for (int i = 0; i < base_values_.size(); i++) {
246 printer->Print(
247 " case $name$:\n",
248 "name", EnumValueName(base_values_[i]));
249 }
250
251 printer->Print(
252 " return YES;\n"
253 " default:\n"
254 " return NO;\n"
255 " }\n"
256 "}\n\n");
257 }
258 } // namespace objectivec
259 } // namespace compiler
260 } // namespace protobuf
261 } // namespace google
262