java_enum.cc 12 KB

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