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 #include <string>
37
38 #include <google/protobuf/compiler/java/java_context.h>
39 #include <google/protobuf/compiler/java/java_doc_comment.h>
40 #include <google/protobuf/compiler/java/java_enum.h>
41 #include <google/protobuf/compiler/java/java_helpers.h>
42 #include <google/protobuf/compiler/java/java_name_resolver.h>
43 #include <google/protobuf/descriptor.pb.h>
44 #include <google/protobuf/io/printer.h>
45 #include <google/protobuf/stubs/strutil.h>
46
47
48 namespace google {
49 namespace protobuf {
50 namespace compiler {
51 namespace java {
52
EnumGenerator(const EnumDescriptor * descriptor,bool immutable_api,Context * context)53 EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
54 bool immutable_api, Context* context)
55 : descriptor_(descriptor),
56 immutable_api_(immutable_api),
57 context_(context),
58 name_resolver_(context->GetNameResolver()) {
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 canonical_values_.push_back(value);
66 } else {
67 Alias alias;
68 alias.value = value;
69 alias.canonical_value = canonical_value;
70 aliases_.push_back(alias);
71 }
72 }
73 }
74
~EnumGenerator()75 EnumGenerator::~EnumGenerator() {}
76
Generate(io::Printer * printer)77 void EnumGenerator::Generate(io::Printer* printer) {
78 WriteEnumDocComment(printer, descriptor_);
79 MaybePrintGeneratedAnnotation(context_, printer, descriptor_, immutable_api_);
80 printer->Print(
81 "public enum $classname$\n"
82 " implements com.google.protobuf.ProtocolMessageEnum {\n",
83 "classname", descriptor_->name());
84 printer->Annotate("classname", descriptor_);
85 printer->Indent();
86
87 bool ordinal_is_index = true;
88 std::string index_text = "ordinal()";
89 for (int i = 0; i < canonical_values_.size(); i++) {
90 if (canonical_values_[i]->index() != i) {
91 ordinal_is_index = false;
92 index_text = "index";
93 break;
94 }
95 }
96
97 for (int i = 0; i < canonical_values_.size(); i++) {
98 std::map<std::string, std::string> vars;
99 vars["name"] = canonical_values_[i]->name();
100 vars["index"] = StrCat(canonical_values_[i]->index());
101 vars["number"] = StrCat(canonical_values_[i]->number());
102 WriteEnumValueDocComment(printer, canonical_values_[i]);
103 if (canonical_values_[i]->options().deprecated()) {
104 printer->Print("@java.lang.Deprecated\n");
105 }
106 if (ordinal_is_index) {
107 printer->Print(vars, "$name$($number$),\n");
108 } else {
109 printer->Print(vars, "$name$($index$, $number$),\n");
110 }
111 printer->Annotate("name", canonical_values_[i]);
112 }
113
114 if (SupportUnknownEnumValue(descriptor_->file())) {
115 if (ordinal_is_index) {
116 printer->Print("${$UNRECOGNIZED$}$(-1),\n", "{", "", "}", "");
117 } else {
118 printer->Print("${$UNRECOGNIZED$}$(-1, -1),\n", "{", "", "}", "");
119 }
120 printer->Annotate("{", "}", descriptor_);
121 }
122
123 printer->Print(
124 ";\n"
125 "\n");
126
127 // -----------------------------------------------------------------
128
129 for (int i = 0; i < aliases_.size(); i++) {
130 std::map<std::string, std::string> vars;
131 vars["classname"] = descriptor_->name();
132 vars["name"] = aliases_[i].value->name();
133 vars["canonical_name"] = aliases_[i].canonical_value->name();
134 WriteEnumValueDocComment(printer, aliases_[i].value);
135 printer->Print(
136 vars, "public static final $classname$ $name$ = $canonical_name$;\n");
137 printer->Annotate("name", aliases_[i].value);
138 }
139
140 for (int i = 0; i < descriptor_->value_count(); i++) {
141 std::map<std::string, std::string> vars;
142 vars["name"] = descriptor_->value(i)->name();
143 vars["number"] = StrCat(descriptor_->value(i)->number());
144 vars["{"] = "";
145 vars["}"] = "";
146 WriteEnumValueDocComment(printer, descriptor_->value(i));
147 printer->Print(vars,
148 "public static final int ${$$name$_VALUE$}$ = $number$;\n");
149 printer->Annotate("{", "}", descriptor_->value(i));
150 }
151 printer->Print("\n");
152
153 // -----------------------------------------------------------------
154
155 printer->Print(
156 "\n"
157 "public final int getNumber() {\n");
158 if (SupportUnknownEnumValue(descriptor_->file())) {
159 if (ordinal_is_index) {
160 printer->Print(
161 " if (this == UNRECOGNIZED) {\n"
162 " throw new java.lang.IllegalArgumentException(\n"
163 " \"Can't get the number of an unknown enum value.\");\n"
164 " }\n");
165 } else {
166 printer->Print(
167 " if (index == -1) {\n"
168 " throw new java.lang.IllegalArgumentException(\n"
169 " \"Can't get the number of an unknown enum value.\");\n"
170 " }\n");
171 }
172 }
173 printer->Print(
174 " return value;\n"
175 "}\n"
176 "\n"
177 "/**\n"
178 " * @deprecated Use {@link #forNumber(int)} instead.\n"
179 " */\n"
180 "@java.lang.Deprecated\n"
181 "public static $classname$ valueOf(int value) {\n"
182 " return forNumber(value);\n"
183 "}\n"
184 "\n"
185 "public static $classname$ forNumber(int value) {\n"
186 " switch (value) {\n",
187 "classname", descriptor_->name());
188 printer->Indent();
189 printer->Indent();
190
191 for (int i = 0; i < canonical_values_.size(); i++) {
192 printer->Print("case $number$: return $name$;\n", "name",
193 canonical_values_[i]->name(), "number",
194 StrCat(canonical_values_[i]->number()));
195 }
196
197 printer->Outdent();
198 printer->Outdent();
199 printer->Print(
200 " default: return null;\n"
201 " }\n"
202 "}\n"
203 "\n"
204 "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n"
205 " internalGetValueMap() {\n"
206 " return internalValueMap;\n"
207 "}\n"
208 "private static final com.google.protobuf.Internal.EnumLiteMap<\n"
209 " $classname$> internalValueMap =\n"
210 " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n"
211 " public $classname$ findValueByNumber(int number) {\n"
212 " return $classname$.forNumber(number);\n"
213 " }\n"
214 " };\n"
215 "\n",
216 "classname", descriptor_->name());
217
218 // -----------------------------------------------------------------
219 // Reflection
220
221 if (HasDescriptorMethods(descriptor_, context_->EnforceLite())) {
222 printer->Print(
223 "public final com.google.protobuf.Descriptors.EnumValueDescriptor\n"
224 " getValueDescriptor() {\n"
225 " return getDescriptor().getValues().get($index_text$);\n"
226 "}\n"
227 "public final com.google.protobuf.Descriptors.EnumDescriptor\n"
228 " getDescriptorForType() {\n"
229 " return getDescriptor();\n"
230 "}\n"
231 "public static final com.google.protobuf.Descriptors.EnumDescriptor\n"
232 " getDescriptor() {\n",
233 "index_text", index_text);
234
235 // TODO(kenton): Cache statically? Note that we can't access descriptors
236 // at module init time because it wouldn't work with descriptor.proto, but
237 // we can cache the value the first time getDescriptor() is called.
238 if (descriptor_->containing_type() == NULL) {
239 // The class generated for the File fully populates the descriptor with
240 // extensions in both the mutable and immutable cases. (In the mutable api
241 // this is accomplished by attempting to load the immutable outer class).
242 printer->Print(
243 " return $file$.getDescriptor().getEnumTypes().get($index$);\n",
244 "file",
245 name_resolver_->GetClassName(descriptor_->file(), immutable_api_),
246 "index", StrCat(descriptor_->index()));
247 } else {
248 printer->Print(
249 " return $parent$.$descriptor$.getEnumTypes().get($index$);\n",
250 "parent",
251 name_resolver_->GetClassName(descriptor_->containing_type(),
252 immutable_api_),
253 "descriptor",
254 descriptor_->containing_type()
255 ->options()
256 .no_standard_descriptor_accessor()
257 ? "getDefaultInstance().getDescriptorForType()"
258 : "getDescriptor()",
259 "index", StrCat(descriptor_->index()));
260 }
261
262 printer->Print(
263 "}\n"
264 "\n"
265 "private static final $classname$[] VALUES = ",
266 "classname", descriptor_->name());
267
268 if (CanUseEnumValues()) {
269 // If the constants we are going to output are exactly the ones we
270 // have declared in the Java enum in the same order, then we can use
271 // the values() method that the Java compiler automatically generates
272 // for every enum.
273 printer->Print("values();\n");
274 } else {
275 printer->Print(
276 "{\n"
277 " ");
278 for (int i = 0; i < descriptor_->value_count(); i++) {
279 printer->Print("$name$, ", "name", descriptor_->value(i)->name());
280 }
281 printer->Print(
282 "\n"
283 "};\n");
284 }
285
286 printer->Print(
287 "\n"
288 "public static $classname$ valueOf(\n"
289 " com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n"
290 " if (desc.getType() != getDescriptor()) {\n"
291 " throw new java.lang.IllegalArgumentException(\n"
292 " \"EnumValueDescriptor is not for this type.\");\n"
293 " }\n",
294 "classname", descriptor_->name());
295 if (SupportUnknownEnumValue(descriptor_->file())) {
296 printer->Print(
297 " if (desc.getIndex() == -1) {\n"
298 " return UNRECOGNIZED;\n"
299 " }\n");
300 }
301 printer->Print(
302 " return VALUES[desc.getIndex()];\n"
303 "}\n"
304 "\n");
305
306 if (!ordinal_is_index) {
307 printer->Print("private final int index;\n");
308 }
309 }
310
311 // -----------------------------------------------------------------
312
313 printer->Print("private final int value;\n\n");
314
315 if (ordinal_is_index) {
316 printer->Print("private $classname$(int value) {\n", "classname",
317 descriptor_->name());
318 } else {
319 printer->Print("private $classname$(int index, int value) {\n", "classname",
320 descriptor_->name());
321 }
322 if (HasDescriptorMethods(descriptor_, context_->EnforceLite()) &&
323 !ordinal_is_index) {
324 printer->Print(" this.index = index;\n");
325 }
326 printer->Print(
327 " this.value = value;\n"
328 "}\n");
329
330 printer->Print(
331 "\n"
332 "// @@protoc_insertion_point(enum_scope:$full_name$)\n",
333 "full_name", descriptor_->full_name());
334
335 printer->Outdent();
336 printer->Print("}\n\n");
337 }
338
CanUseEnumValues()339 bool EnumGenerator::CanUseEnumValues() {
340 if (canonical_values_.size() != descriptor_->value_count()) {
341 return false;
342 }
343 for (int i = 0; i < descriptor_->value_count(); i++) {
344 if (descriptor_->value(i)->name() != canonical_values_[i]->name()) {
345 return false;
346 }
347 }
348 return true;
349 }
350
351 } // namespace java
352 } // namespace compiler
353 } // namespace protobuf
354 } // namespace google
355