• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 // Author: kenton@google.com (Kenton Varda)
9 //  Based on original Protocol Buffers design by
10 //  Sanjay Ghemawat, Jeff Dean, and others.
11 
12 #include "google/protobuf/compiler/java/lite/enum.h"
13 
14 #include <string>
15 #include <utility>
16 #include <vector>
17 
18 #include "absl/container/flat_hash_map.h"
19 #include "absl/strings/str_cat.h"
20 #include "google/protobuf/compiler/java/context.h"
21 #include "google/protobuf/compiler/java/doc_comment.h"
22 #include "google/protobuf/compiler/java/helpers.h"
23 #include "google/protobuf/compiler/java/internal_helpers.h"
24 #include "google/protobuf/compiler/java/name_resolver.h"
25 #include "google/protobuf/descriptor.pb.h"
26 #include "google/protobuf/io/printer.h"
27 
28 namespace google {
29 namespace protobuf {
30 namespace compiler {
31 namespace java {
32 
EnumLiteGenerator(const EnumDescriptor * descriptor,bool immutable_api,Context * context)33 EnumLiteGenerator::EnumLiteGenerator(const EnumDescriptor* descriptor,
34                                      bool immutable_api, Context* context)
35     : descriptor_(descriptor),
36       immutable_api_(immutable_api),
37       context_(context),
38       name_resolver_(context->GetNameResolver()) {
39   for (int i = 0; i < descriptor_->value_count(); i++) {
40     const EnumValueDescriptor* value = descriptor_->value(i);
41     const EnumValueDescriptor* canonical_value =
42         descriptor_->FindValueByNumber(value->number());
43 
44     if (value == canonical_value) {
45       canonical_values_.push_back(value);
46     } else {
47       Alias alias;
48       alias.value = value;
49       alias.canonical_value = canonical_value;
50       aliases_.push_back(alias);
51     }
52   }
53 }
54 
~EnumLiteGenerator()55 EnumLiteGenerator::~EnumLiteGenerator() {}
56 
Generate(io::Printer * printer)57 void EnumLiteGenerator::Generate(io::Printer* printer) {
58   WriteEnumDocComment(printer, descriptor_, context_->options());
59   MaybePrintGeneratedAnnotation(context_, printer, descriptor_, immutable_api_);
60 
61 
62   printer->Print(
63       "$deprecation$public enum $classname$\n"
64       "    implements com.google.protobuf.Internal.EnumLite {\n",
65       "classname", descriptor_->name(), "deprecation",
66       descriptor_->options().deprecated() ? "@java.lang.Deprecated " : "");
67   printer->Annotate("classname", descriptor_);
68   printer->Indent();
69 
70   for (int i = 0; i < canonical_values_.size(); i++) {
71     absl::flat_hash_map<absl::string_view, std::string> vars;
72     vars["name"] = canonical_values_[i]->name();
73     vars["number"] = absl::StrCat(canonical_values_[i]->number());
74     WriteEnumValueDocComment(printer, canonical_values_[i],
75                              context_->options());
76     if (canonical_values_[i]->options().deprecated()) {
77       printer->Print("@java.lang.Deprecated\n");
78     }
79     printer->Print(vars, "$name$($number$),\n");
80     printer->Annotate("name", canonical_values_[i]);
81   }
82 
83   if (!descriptor_->is_closed()) {
84     printer->Print("${$UNRECOGNIZED$}$(-1),\n", "{", "", "}", "");
85     printer->Annotate("{", "}", descriptor_);
86   }
87 
88   printer->Print(
89       ";\n"
90       "\n");
91 
92   // -----------------------------------------------------------------
93 
94   for (int i = 0; i < aliases_.size(); i++) {
95     absl::flat_hash_map<absl::string_view, std::string> vars;
96     vars["classname"] = descriptor_->name();
97     vars["name"] = aliases_[i].value->name();
98     vars["canonical_name"] = aliases_[i].canonical_value->name();
99     WriteEnumValueDocComment(printer, aliases_[i].value, context_->options());
100     printer->Print(
101         vars, "public static final $classname$ $name$ = $canonical_name$;\n");
102     printer->Annotate("name", aliases_[i].value);
103   }
104 
105   for (int i = 0; i < descriptor_->value_count(); i++) {
106     absl::flat_hash_map<absl::string_view, std::string> vars;
107     vars["name"] = descriptor_->value(i)->name();
108     vars["number"] = absl::StrCat(descriptor_->value(i)->number());
109     vars["{"] = "";
110     vars["}"] = "";
111     vars["deprecation"] = descriptor_->value(i)->options().deprecated()
112                               ? "@java.lang.Deprecated "
113                               : "";
114     WriteEnumValueDocComment(printer, descriptor_->value(i),
115                              context_->options());
116     printer->Print(vars,
117                    "$deprecation$public static final int ${$$name$_VALUE$}$ = "
118                    "$number$;\n");
119     printer->Annotate("{", "}", descriptor_->value(i));
120   }
121   printer->Print("\n");
122 
123   // -----------------------------------------------------------------
124 
125   printer->Print(
126       "\n"
127       "@java.lang.Override\n"
128       "public final int getNumber() {\n");
129   if (!descriptor_->is_closed()) {
130     printer->Print(
131         "  if (this == UNRECOGNIZED) {\n"
132         "    throw new java.lang.IllegalArgumentException(\n"
133         "        \"Can't get the number of an unknown enum value.\");\n"
134         "  }\n");
135   }
136   printer->Print(
137       "  return value;\n"
138       "}\n"
139       "\n");
140   if (context_->options().opensource_runtime) {
141     printer->Print(
142         "/**\n"
143         " * @param value The number of the enum to look for.\n"
144         " * @return The enum associated with the given number.\n"
145         " * @deprecated Use {@link #forNumber(int)} instead.\n"
146         " */\n"
147         "@java.lang.Deprecated\n"
148         "public static $classname$ valueOf(int value) {\n"
149         "  return forNumber(value);\n"
150         "}\n"
151         "\n",
152         "classname", descriptor_->name());
153   }
154 
155   if (!context_->options().opensource_runtime) {
156     printer->Print("@com.google.protobuf.Internal.ProtoMethodMayReturnNull\n");
157   }
158   printer->Print(
159       "public static $classname$ forNumber(int value) {\n"
160       "  switch (value) {\n",
161       "classname", descriptor_->name());
162   printer->Indent();
163   printer->Indent();
164 
165   for (int i = 0; i < canonical_values_.size(); i++) {
166     printer->Print("case $number$: return $name$;\n", "name",
167                    canonical_values_[i]->name(), "number",
168                    absl::StrCat(canonical_values_[i]->number()));
169   }
170 
171   printer->Outdent();
172   printer->Outdent();
173   printer->Print(
174       "    default: return null;\n"
175       "  }\n"
176       "}\n"
177       "\n"
178       "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n"
179       "    internalGetValueMap() {\n"
180       "  return internalValueMap;\n"
181       "}\n"
182       "private static final com.google.protobuf.Internal.EnumLiteMap<\n"
183       "    $classname$> internalValueMap =\n"
184       "      new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n"
185       "        @java.lang.Override\n"
186       "        public $classname$ findValueByNumber(int number) {\n"
187       "          return $classname$.forNumber(number);\n"
188       "        }\n"
189       "      };\n"
190       "\n"
191       "public static com.google.protobuf.Internal.EnumVerifier \n"
192       "    internalGetVerifier() {\n"
193       "  return $classname$Verifier.INSTANCE;\n"
194       "}\n"
195       "\n"
196       "private static final class $classname$Verifier implements \n"
197       "     com.google.protobuf.Internal.EnumVerifier { \n"
198       "        static final com.google.protobuf.Internal.EnumVerifier "
199       "          INSTANCE = new $classname$Verifier();\n"
200       "        @java.lang.Override\n"
201       "        public boolean isInRange(int number) {\n"
202       "          return $classname$.forNumber(number) != null;\n"
203       "        }\n"
204       "      };\n"
205       "\n",
206       "classname", descriptor_->name());
207   if (!context_->options().opensource_runtime) {
208     printer->Print(
209         "/**\n"
210         " * Override of toString that prints the number and name.\n"
211         " * This is primarily intended as a developer aid.\n"
212         " *\n"
213         " * <p>NOTE: This implementation is liable to change in the future,\n"
214         " * and should not be relied on in code.\n"
215         " */\n"
216         "@java.lang.Override\n"
217         "public java.lang.String toString() {\n"
218         "  StringBuilder result = new StringBuilder(\"<\");\n"
219         "  result.append(getClass().getName()).append('@')\n"
220         "      .append(java.lang.Integer.toHexString(\n"
221         "        java.lang.System.identityHashCode(this)));\n");
222     if (!descriptor_->is_closed()) {
223       printer->Print(
224           "  if (this != UNRECOGNIZED) {\n"
225           "    result.append(\" number=\").append(getNumber());\n"
226           "  }\n");
227     } else {
228       printer->Print("  result.append(\" number=\").append(getNumber());\n");
229     }
230     printer->Print(
231         "  return result.append(\" name=\")\n"
232         "      .append(name()).append('>').toString();\n"
233         "}\n"
234         "\n");
235   }
236 
237   printer->Print(
238       "private final int value;\n\n"
239       "private $classname$(int value) {\n",
240       "classname", descriptor_->name());
241   printer->Print(
242       "  this.value = value;\n"
243       "}\n");
244 
245   printer->Print(
246       "\n"
247       "// @@protoc_insertion_point(enum_scope:$full_name$)\n",
248       "full_name", descriptor_->full_name());
249 
250   printer->Outdent();
251   printer->Print("}\n\n");
252 }
253 
254 }  // namespace java
255 }  // namespace compiler
256 }  // namespace protobuf
257 }  // namespace google
258