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 <google/protobuf/compiler/java/java_file.h>
36
37 #include <memory>
38 #include <set>
39
40 #include <google/protobuf/compiler/code_generator.h>
41 #include <google/protobuf/io/printer.h>
42 #include <google/protobuf/io/zero_copy_stream.h>
43 #include <google/protobuf/dynamic_message.h>
44 #include <google/protobuf/stubs/strutil.h>
45 #include <google/protobuf/compiler/java/java_context.h>
46 #include <google/protobuf/compiler/java/java_enum.h>
47 #include <google/protobuf/compiler/java/java_enum_lite.h>
48 #include <google/protobuf/compiler/java/java_extension.h>
49 #include <google/protobuf/compiler/java/java_generator_factory.h>
50 #include <google/protobuf/compiler/java/java_helpers.h>
51 #include <google/protobuf/compiler/java/java_message.h>
52 #include <google/protobuf/compiler/java/java_name_resolver.h>
53 #include <google/protobuf/compiler/java/java_service.h>
54 #include <google/protobuf/compiler/java/java_shared_code_generator.h>
55 #include <google/protobuf/descriptor.pb.h>
56
57 namespace google {
58 namespace protobuf {
59 namespace compiler {
60 namespace java {
61
62 namespace {
63
64 struct FieldDescriptorCompare {
operator ()google::protobuf::compiler::java::__anon3ee80fbc0111::FieldDescriptorCompare65 bool operator()(const FieldDescriptor* f1, const FieldDescriptor* f2) const {
66 if (f1 == NULL) {
67 return false;
68 }
69 if (f2 == NULL) {
70 return true;
71 }
72 return f1->full_name() < f2->full_name();
73 }
74 };
75
76 typedef std::set<const FieldDescriptor*, FieldDescriptorCompare>
77 FieldDescriptorSet;
78
79 // Recursively searches the given message to collect extensions.
80 // Returns true if all the extensions can be recognized. The extensions will be
81 // appended in to the extensions parameter.
82 // Returns false when there are unknown fields, in which case the data in the
83 // extensions output parameter is not reliable and should be discarded.
CollectExtensions(const Message & message,FieldDescriptorSet * extensions)84 bool CollectExtensions(const Message& message, FieldDescriptorSet* extensions) {
85 const Reflection* reflection = message.GetReflection();
86
87 // There are unknown fields that could be extensions, thus this call fails.
88 if (reflection->GetUnknownFields(message).field_count() > 0) return false;
89
90 std::vector<const FieldDescriptor*> fields;
91 reflection->ListFields(message, &fields);
92
93 for (int i = 0; i < fields.size(); i++) {
94 if (fields[i]->is_extension()) {
95 extensions->insert(fields[i]);
96 }
97
98 if (GetJavaType(fields[i]) == JAVATYPE_MESSAGE) {
99 if (fields[i]->is_repeated()) {
100 int size = reflection->FieldSize(message, fields[i]);
101 for (int j = 0; j < size; j++) {
102 const Message& sub_message =
103 reflection->GetRepeatedMessage(message, fields[i], j);
104 if (!CollectExtensions(sub_message, extensions)) return false;
105 }
106 } else {
107 const Message& sub_message = reflection->GetMessage(message, fields[i]);
108 if (!CollectExtensions(sub_message, extensions)) return false;
109 }
110 }
111 }
112
113 return true;
114 }
115
116 // Finds all extensions in the given message and its sub-messages. If the
117 // message contains unknown fields (which could be extensions), then those
118 // extensions are defined in alternate_pool.
119 // The message will be converted to a DynamicMessage backed by alternate_pool
120 // in order to handle this case.
CollectExtensions(const FileDescriptorProto & file_proto,const DescriptorPool & alternate_pool,FieldDescriptorSet * extensions,const std::string & file_data)121 void CollectExtensions(const FileDescriptorProto& file_proto,
122 const DescriptorPool& alternate_pool,
123 FieldDescriptorSet* extensions,
124 const std::string& file_data) {
125 if (!CollectExtensions(file_proto, extensions)) {
126 // There are unknown fields in the file_proto, which are probably
127 // extensions. We need to parse the data into a dynamic message based on the
128 // builder-pool to find out all extensions.
129 const Descriptor* file_proto_desc = alternate_pool.FindMessageTypeByName(
130 file_proto.GetDescriptor()->full_name());
131 GOOGLE_CHECK(file_proto_desc)
132 << "Find unknown fields in FileDescriptorProto when building "
133 << file_proto.name()
134 << ". It's likely that those fields are custom options, however, "
135 "descriptor.proto is not in the transitive dependencies. "
136 "This normally should not happen. Please report a bug.";
137 DynamicMessageFactory factory;
138 std::unique_ptr<Message> dynamic_file_proto(
139 factory.GetPrototype(file_proto_desc)->New());
140 GOOGLE_CHECK(dynamic_file_proto.get() != NULL);
141 GOOGLE_CHECK(dynamic_file_proto->ParseFromString(file_data));
142
143 // Collect the extensions again from the dynamic message. There should be no
144 // more unknown fields this time, i.e. all the custom options should be
145 // parsed as extensions now.
146 extensions->clear();
147 GOOGLE_CHECK(CollectExtensions(*dynamic_file_proto, extensions))
148 << "Find unknown fields in FileDescriptorProto when building "
149 << file_proto.name()
150 << ". It's likely that those fields are custom options, however, "
151 "those options cannot be recognized in the builder pool. "
152 "This normally should not happen. Please report a bug.";
153 }
154 }
155
156 // Our static initialization methods can become very, very large.
157 // So large that if we aren't careful we end up blowing the JVM's
158 // 64K bytes of bytecode/method. Fortunately, since these static
159 // methods are executed only once near the beginning of a program,
160 // there's usually plenty of stack space available and we can
161 // extend our methods by simply chaining them to another method
162 // with a tail call. This inserts the sequence call-next-method,
163 // end this one, begin-next-method as needed.
MaybeRestartJavaMethod(io::Printer * printer,int * bytecode_estimate,int * method_num,const char * chain_statement,const char * method_decl)164 void MaybeRestartJavaMethod(io::Printer* printer, int* bytecode_estimate,
165 int* method_num, const char* chain_statement,
166 const char* method_decl) {
167 // The goal here is to stay under 64K bytes of jvm bytecode/method,
168 // since otherwise we hit a hardcoded limit in the jvm and javac will
169 // then fail with the error "code too large". This limit lets our
170 // estimates be off by a factor of two and still we're okay.
171 static const int bytesPerMethod = kMaxStaticSize;
172
173 if ((*bytecode_estimate) > bytesPerMethod) {
174 ++(*method_num);
175 printer->Print(chain_statement, "method_num", StrCat(*method_num));
176 printer->Outdent();
177 printer->Print("}\n");
178 printer->Print(method_decl, "method_num", StrCat(*method_num));
179 printer->Indent();
180 *bytecode_estimate = 0;
181 }
182 }
183 } // namespace
184
FileGenerator(const FileDescriptor * file,const Options & options,bool immutable_api)185 FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options,
186 bool immutable_api)
187 : file_(file),
188 java_package_(FileJavaPackage(file, immutable_api)),
189 message_generators_(file->message_type_count()),
190 extension_generators_(file->extension_count()),
191 context_(new Context(file, options)),
192 name_resolver_(context_->GetNameResolver()),
193 options_(options),
194 immutable_api_(immutable_api) {
195 classname_ = name_resolver_->GetFileClassName(file, immutable_api);
196 generator_factory_.reset(new ImmutableGeneratorFactory(context_.get()));
197 for (int i = 0; i < file_->message_type_count(); ++i) {
198 message_generators_[i].reset(
199 generator_factory_->NewMessageGenerator(file_->message_type(i)));
200 }
201 for (int i = 0; i < file_->extension_count(); ++i) {
202 extension_generators_[i].reset(
203 generator_factory_->NewExtensionGenerator(file_->extension(i)));
204 }
205 }
206
~FileGenerator()207 FileGenerator::~FileGenerator() {}
208
Validate(std::string * error)209 bool FileGenerator::Validate(std::string* error) {
210 // Check that no class name matches the file's class name. This is a common
211 // problem that leads to Java compile errors that can be hard to understand.
212 // It's especially bad when using the java_multiple_files, since we would
213 // end up overwriting the outer class with one of the inner ones.
214 if (name_resolver_->HasConflictingClassName(file_, classname_,
215 NameEquality::EXACT_EQUAL)) {
216 error->assign(file_->name());
217 error->append(
218 ": Cannot generate Java output because the file's outer class name, "
219 "\"");
220 error->append(classname_);
221 error->append(
222 "\", matches the name of one of the types declared inside it. "
223 "Please either rename the type or use the java_outer_classname "
224 "option to specify a different outer class name for the .proto file.");
225 return false;
226 }
227 // Similar to the check above, but ignore the case this time. This is not a
228 // problem on Linux, but will lead to Java compile errors on Windows / Mac
229 // because filenames are case-insensitive on those platforms.
230 if (name_resolver_->HasConflictingClassName(
231 file_, classname_, NameEquality::EQUAL_IGNORE_CASE)) {
232 GOOGLE_LOG(WARNING)
233 << file_->name() << ": The file's outer class name, \"" << classname_
234 << "\", matches the name of one of the types declared inside it when "
235 << "case is ignored. This can cause compilation issues on Windows / "
236 << "MacOS. Please either rename the type or use the "
237 << "java_outer_classname option to specify a different outer class "
238 << "name for the .proto file to be safe.";
239 }
240
241 // Print a warning if optimize_for = LITE_RUNTIME is used.
242 if (file_->options().optimize_for() == FileOptions::LITE_RUNTIME &&
243 !options_.enforce_lite) {
244 GOOGLE_LOG(WARNING)
245 << "The optimize_for = LITE_RUNTIME option is no longer supported by "
246 << "protobuf Java code generator and is ignored--protoc will always "
247 << "generate full runtime code for Java. To use Java Lite runtime, "
248 << "users should use the Java Lite plugin instead. See:\n"
249 << " "
250 "https://github.com/protocolbuffers/protobuf/blob/master/java/"
251 "lite.md";
252 }
253 return true;
254 }
255
Generate(io::Printer * printer)256 void FileGenerator::Generate(io::Printer* printer) {
257 // We don't import anything because we refer to all classes by their
258 // fully-qualified names in the generated source.
259 printer->Print(
260 "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
261 "// source: $filename$\n"
262 "\n",
263 "filename", file_->name());
264 if (!java_package_.empty()) {
265 printer->Print(
266 "package $package$;\n"
267 "\n",
268 "package", java_package_);
269 }
270 PrintGeneratedAnnotation(
271 printer, '$', options_.annotate_code ? classname_ + ".java.pb.meta" : "");
272
273 printer->Print(
274 "$deprecation$public final class $classname$ {\n"
275 " private $ctor$() {}\n",
276 "deprecation",
277 file_->options().deprecated() ? "@java.lang.Deprecated " : "",
278 "classname", classname_, "ctor", classname_);
279 printer->Annotate("classname", file_->name());
280 printer->Indent();
281
282 // -----------------------------------------------------------------
283
284 printer->Print(
285 "public static void registerAllExtensions(\n"
286 " com.google.protobuf.ExtensionRegistryLite registry) {\n");
287
288 printer->Indent();
289
290 for (int i = 0; i < file_->extension_count(); i++) {
291 extension_generators_[i]->GenerateRegistrationCode(printer);
292 }
293
294 for (int i = 0; i < file_->message_type_count(); i++) {
295 message_generators_[i]->GenerateExtensionRegistrationCode(printer);
296 }
297
298 printer->Outdent();
299 printer->Print("}\n");
300 if (HasDescriptorMethods(file_, context_->EnforceLite())) {
301 // Overload registerAllExtensions for the non-lite usage to
302 // redundantly maintain the original signature (this is
303 // redundant because ExtensionRegistryLite now invokes
304 // ExtensionRegistry in the non-lite usage). Intent is
305 // to remove this in the future.
306 printer->Print(
307 "\n"
308 "public static void registerAllExtensions(\n"
309 " com.google.protobuf.ExtensionRegistry registry) {\n"
310 " registerAllExtensions(\n"
311 " (com.google.protobuf.ExtensionRegistryLite) registry);\n"
312 "}\n");
313 }
314
315 // -----------------------------------------------------------------
316
317 if (!MultipleJavaFiles(file_, immutable_api_)) {
318 for (int i = 0; i < file_->enum_type_count(); i++) {
319 if (HasDescriptorMethods(file_, context_->EnforceLite())) {
320 EnumGenerator(file_->enum_type(i), immutable_api_, context_.get())
321 .Generate(printer);
322 } else {
323 EnumLiteGenerator(file_->enum_type(i), immutable_api_, context_.get())
324 .Generate(printer);
325 }
326 }
327 for (int i = 0; i < file_->message_type_count(); i++) {
328 message_generators_[i]->GenerateInterface(printer);
329 message_generators_[i]->Generate(printer);
330 }
331 if (HasGenericServices(file_, context_->EnforceLite())) {
332 for (int i = 0; i < file_->service_count(); i++) {
333 std::unique_ptr<ServiceGenerator> generator(
334 generator_factory_->NewServiceGenerator(file_->service(i)));
335 generator->Generate(printer);
336 }
337 }
338 }
339
340 // Extensions must be generated in the outer class since they are values,
341 // not classes.
342 for (int i = 0; i < file_->extension_count(); i++) {
343 extension_generators_[i]->Generate(printer);
344 }
345
346 // Static variables. We'd like them to be final if possible, but due to
347 // the JVM's 64k size limit on static blocks, we have to initialize some
348 // of them in methods; thus they cannot be final.
349 int static_block_bytecode_estimate = 0;
350 for (int i = 0; i < file_->message_type_count(); i++) {
351 message_generators_[i]->GenerateStaticVariables(
352 printer, &static_block_bytecode_estimate);
353 }
354
355 printer->Print("\n");
356
357 if (HasDescriptorMethods(file_, context_->EnforceLite())) {
358 if (immutable_api_) {
359 GenerateDescriptorInitializationCodeForImmutable(printer);
360 } else {
361 GenerateDescriptorInitializationCodeForMutable(printer);
362 }
363 } else {
364 printer->Print("static {\n");
365 printer->Indent();
366 int bytecode_estimate = 0;
367 int method_num = 0;
368
369 for (int i = 0; i < file_->message_type_count(); i++) {
370 bytecode_estimate +=
371 message_generators_[i]->GenerateStaticVariableInitializers(printer);
372 MaybeRestartJavaMethod(
373 printer, &bytecode_estimate, &method_num,
374 "_clinit_autosplit_$method_num$();\n",
375 "private static void _clinit_autosplit_$method_num$() {\n");
376 }
377
378 printer->Outdent();
379 printer->Print("}\n");
380 }
381
382 printer->Print(
383 "\n"
384 "// @@protoc_insertion_point(outer_class_scope)\n");
385
386 printer->Outdent();
387 printer->Print("}\n");
388 }
389
GenerateDescriptorInitializationCodeForImmutable(io::Printer * printer)390 void FileGenerator::GenerateDescriptorInitializationCodeForImmutable(
391 io::Printer* printer) {
392 printer->Print(
393 "public static com.google.protobuf.Descriptors.FileDescriptor\n"
394 " getDescriptor() {\n"
395 " return descriptor;\n"
396 "}\n"
397 "private static $final$ com.google.protobuf.Descriptors.FileDescriptor\n"
398 " descriptor;\n"
399 "static {\n",
400 // TODO(dweis): Mark this as final.
401 "final", "");
402 printer->Indent();
403
404 SharedCodeGenerator shared_code_generator(file_, options_);
405 shared_code_generator.GenerateDescriptors(printer);
406
407 int bytecode_estimate = 0;
408 int method_num = 0;
409
410 for (int i = 0; i < file_->message_type_count(); i++) {
411 bytecode_estimate +=
412 message_generators_[i]->GenerateStaticVariableInitializers(printer);
413 MaybeRestartJavaMethod(
414 printer, &bytecode_estimate, &method_num,
415 "_clinit_autosplit_dinit_$method_num$();\n",
416 "private static void _clinit_autosplit_dinit_$method_num$() {\n");
417 }
418 for (int i = 0; i < file_->extension_count(); i++) {
419 bytecode_estimate +=
420 extension_generators_[i]->GenerateNonNestedInitializationCode(printer);
421 MaybeRestartJavaMethod(
422 printer, &bytecode_estimate, &method_num,
423 "_clinit_autosplit_dinit_$method_num$();\n",
424 "private static void _clinit_autosplit_dinit_$method_num$() {\n");
425 }
426
427 // Proto compiler builds a DescriptorPool, which holds all the descriptors to
428 // generate, when processing the ".proto" files. We call this DescriptorPool
429 // the parsed pool (a.k.a. file_->pool()).
430 //
431 // Note that when users try to extend the (.*)DescriptorProto in their
432 // ".proto" files, it does not affect the pre-built FileDescriptorProto class
433 // in proto compiler. When we put the descriptor data in the file_proto, those
434 // extensions become unknown fields.
435 //
436 // Now we need to find out all the extension value to the (.*)DescriptorProto
437 // in the file_proto message, and prepare an ExtensionRegistry to return.
438 //
439 // To find those extensions, we need to parse the data into a dynamic message
440 // of the FileDescriptor based on the builder-pool, then we can use
441 // reflections to find all extension fields
442 FileDescriptorProto file_proto;
443 file_->CopyTo(&file_proto);
444 std::string file_data;
445 file_proto.SerializeToString(&file_data);
446 FieldDescriptorSet extensions;
447 CollectExtensions(file_proto, *file_->pool(), &extensions, file_data);
448
449 if (extensions.size() > 0) {
450 // Must construct an ExtensionRegistry containing all existing extensions
451 // and use it to parse the descriptor data again to recognize extensions.
452 printer->Print(
453 "com.google.protobuf.ExtensionRegistry registry =\n"
454 " com.google.protobuf.ExtensionRegistry.newInstance();\n");
455 FieldDescriptorSet::iterator it;
456 for (it = extensions.begin(); it != extensions.end(); it++) {
457 std::unique_ptr<ExtensionGenerator> generator(
458 generator_factory_->NewExtensionGenerator(*it));
459 bytecode_estimate += generator->GenerateRegistrationCode(printer);
460 MaybeRestartJavaMethod(
461 printer, &bytecode_estimate, &method_num,
462 "_clinit_autosplit_dinit_$method_num$(registry);\n",
463 "private static void _clinit_autosplit_dinit_$method_num$(\n"
464 " com.google.protobuf.ExtensionRegistry registry) {\n");
465 }
466 printer->Print(
467 "com.google.protobuf.Descriptors.FileDescriptor\n"
468 " .internalUpdateFileDescriptor(descriptor, registry);\n");
469 }
470
471 // Force descriptor initialization of all dependencies.
472 for (int i = 0; i < file_->dependency_count(); i++) {
473 if (ShouldIncludeDependency(file_->dependency(i), true)) {
474 std::string dependency =
475 name_resolver_->GetImmutableClassName(file_->dependency(i));
476 printer->Print("$dependency$.getDescriptor();\n", "dependency",
477 dependency);
478 }
479 }
480
481 printer->Outdent();
482 printer->Print("}\n");
483 }
484
GenerateDescriptorInitializationCodeForMutable(io::Printer * printer)485 void FileGenerator::GenerateDescriptorInitializationCodeForMutable(
486 io::Printer* printer) {
487 printer->Print(
488 "public static com.google.protobuf.Descriptors.FileDescriptor\n"
489 " getDescriptor() {\n"
490 " return descriptor;\n"
491 "}\n"
492 "private static final com.google.protobuf.Descriptors.FileDescriptor\n"
493 " descriptor;\n"
494 "static {\n");
495 printer->Indent();
496
497 printer->Print(
498 "descriptor = $immutable_package$.$descriptor_classname$.descriptor;\n",
499 "immutable_package", FileJavaPackage(file_, true), "descriptor_classname",
500 name_resolver_->GetDescriptorClassName(file_));
501
502 for (int i = 0; i < file_->message_type_count(); i++) {
503 message_generators_[i]->GenerateStaticVariableInitializers(printer);
504 }
505 for (int i = 0; i < file_->extension_count(); i++) {
506 extension_generators_[i]->GenerateNonNestedInitializationCode(printer);
507 }
508
509 // Check if custom options exist. If any, try to load immutable classes since
510 // custom options are only represented with immutable messages.
511 FileDescriptorProto file_proto;
512 file_->CopyTo(&file_proto);
513 std::string file_data;
514 file_proto.SerializeToString(&file_data);
515 FieldDescriptorSet extensions;
516 CollectExtensions(file_proto, *file_->pool(), &extensions, file_data);
517
518 if (extensions.size() > 0) {
519 // Try to load immutable messages' outer class. Its initialization code
520 // will take care of interpreting custom options.
521 printer->Print(
522 "try {\n"
523 // Note that we have to load the immutable class dynamically here as
524 // we want the mutable code to be independent from the immutable code
525 // at compile time. It is required to implement dual-compile for
526 // mutable and immutable API in blaze.
527 " java.lang.Class<?> immutableClass = java.lang.Class.forName(\n"
528 " \"$immutable_classname$\");\n"
529 "} catch (java.lang.ClassNotFoundException e) {\n",
530 "immutable_classname", name_resolver_->GetImmutableClassName(file_));
531 printer->Indent();
532
533 // The immutable class can not be found. We try our best to collect all
534 // custom option extensions to interpret the custom options.
535 printer->Print(
536 "com.google.protobuf.ExtensionRegistry registry =\n"
537 " com.google.protobuf.ExtensionRegistry.newInstance();\n"
538 "com.google.protobuf.MessageLite defaultExtensionInstance = null;\n");
539 FieldDescriptorSet::iterator it;
540 for (it = extensions.begin(); it != extensions.end(); it++) {
541 const FieldDescriptor* field = *it;
542 std::string scope;
543 if (field->extension_scope() != NULL) {
544 scope = name_resolver_->GetMutableClassName(field->extension_scope()) +
545 ".getDescriptor()";
546 } else {
547 scope = FileJavaPackage(field->file(), true) + "." +
548 name_resolver_->GetDescriptorClassName(field->file()) +
549 ".descriptor";
550 }
551 if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
552 printer->Print(
553 "defaultExtensionInstance = com.google.protobuf.Internal\n"
554 " .getDefaultInstance(\"$class$\");\n"
555 "if (defaultExtensionInstance != null) {\n"
556 " registry.add(\n"
557 " $scope$.getExtensions().get($index$),\n"
558 " (com.google.protobuf.Message) defaultExtensionInstance);\n"
559 "}\n",
560 "scope", scope, "index", StrCat(field->index()), "class",
561 name_resolver_->GetImmutableClassName(field->message_type()));
562 } else {
563 printer->Print("registry.add($scope$.getExtensions().get($index$));\n",
564 "scope", scope, "index", StrCat(field->index()));
565 }
566 }
567 printer->Print(
568 "com.google.protobuf.Descriptors.FileDescriptor\n"
569 " .internalUpdateFileDescriptor(descriptor, registry);\n");
570
571 printer->Outdent();
572 printer->Print("}\n");
573 }
574
575 // Force descriptor initialization of all dependencies.
576 for (int i = 0; i < file_->dependency_count(); i++) {
577 if (ShouldIncludeDependency(file_->dependency(i), false)) {
578 std::string dependency =
579 name_resolver_->GetMutableClassName(file_->dependency(i));
580 printer->Print("$dependency$.getDescriptor();\n", "dependency",
581 dependency);
582 }
583 }
584
585 printer->Outdent();
586 printer->Print("}\n");
587 }
588
589 template <typename GeneratorClass, typename DescriptorClass>
GenerateSibling(const std::string & package_dir,const std::string & java_package,const DescriptorClass * descriptor,GeneratorContext * context,std::vector<std::string> * file_list,bool annotate_code,std::vector<std::string> * annotation_list,const std::string & name_suffix,GeneratorClass * generator,void (GeneratorClass::* pfn)(io::Printer * printer))590 static void GenerateSibling(
591 const std::string& package_dir, const std::string& java_package,
592 const DescriptorClass* descriptor, GeneratorContext* context,
593 std::vector<std::string>* file_list, bool annotate_code,
594 std::vector<std::string>* annotation_list, const std::string& name_suffix,
595 GeneratorClass* generator,
596 void (GeneratorClass::*pfn)(io::Printer* printer)) {
597 std::string filename =
598 package_dir + descriptor->name() + name_suffix + ".java";
599 file_list->push_back(filename);
600 std::string info_full_path = filename + ".pb.meta";
601 GeneratedCodeInfo annotations;
602 io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
603 &annotations);
604
605 std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
606 io::Printer printer(output.get(), '$',
607 annotate_code ? &annotation_collector : NULL);
608
609 printer.Print(
610 "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
611 "// source: $filename$\n"
612 "\n",
613 "filename", descriptor->file()->name());
614 if (!java_package.empty()) {
615 printer.Print(
616 "package $package$;\n"
617 "\n",
618 "package", java_package);
619 }
620
621 (generator->*pfn)(&printer);
622
623 if (annotate_code) {
624 std::unique_ptr<io::ZeroCopyOutputStream> info_output(
625 context->Open(info_full_path));
626 annotations.SerializeToZeroCopyStream(info_output.get());
627 annotation_list->push_back(info_full_path);
628 }
629 }
630
GenerateSiblings(const std::string & package_dir,GeneratorContext * context,std::vector<std::string> * file_list,std::vector<std::string> * annotation_list)631 void FileGenerator::GenerateSiblings(
632 const std::string& package_dir, GeneratorContext* context,
633 std::vector<std::string>* file_list,
634 std::vector<std::string>* annotation_list) {
635 if (MultipleJavaFiles(file_, immutable_api_)) {
636 for (int i = 0; i < file_->enum_type_count(); i++) {
637 if (HasDescriptorMethods(file_, context_->EnforceLite())) {
638 EnumGenerator generator(file_->enum_type(i), immutable_api_,
639 context_.get());
640 GenerateSibling<EnumGenerator>(
641 package_dir, java_package_, file_->enum_type(i), context, file_list,
642 options_.annotate_code, annotation_list, "", &generator,
643 &EnumGenerator::Generate);
644 } else {
645 EnumLiteGenerator generator(file_->enum_type(i), immutable_api_,
646 context_.get());
647 GenerateSibling<EnumLiteGenerator>(
648 package_dir, java_package_, file_->enum_type(i), context, file_list,
649 options_.annotate_code, annotation_list, "", &generator,
650 &EnumLiteGenerator::Generate);
651 }
652 }
653 for (int i = 0; i < file_->message_type_count(); i++) {
654 if (immutable_api_) {
655 GenerateSibling<MessageGenerator>(
656 package_dir, java_package_, file_->message_type(i), context,
657 file_list, options_.annotate_code, annotation_list, "OrBuilder",
658 message_generators_[i].get(), &MessageGenerator::GenerateInterface);
659 }
660 GenerateSibling<MessageGenerator>(
661 package_dir, java_package_, file_->message_type(i), context,
662 file_list, options_.annotate_code, annotation_list, "",
663 message_generators_[i].get(), &MessageGenerator::Generate);
664 }
665 if (HasGenericServices(file_, context_->EnforceLite())) {
666 for (int i = 0; i < file_->service_count(); i++) {
667 std::unique_ptr<ServiceGenerator> generator(
668 generator_factory_->NewServiceGenerator(file_->service(i)));
669 GenerateSibling<ServiceGenerator>(
670 package_dir, java_package_, file_->service(i), context, file_list,
671 options_.annotate_code, annotation_list, "", generator.get(),
672 &ServiceGenerator::Generate);
673 }
674 }
675 }
676 }
677
GetKotlinClassname()678 std::string FileGenerator::GetKotlinClassname() {
679 return name_resolver_->GetFileClassName(file_, immutable_api_, true);
680 }
681
GenerateKotlinSiblings(const std::string & package_dir,GeneratorContext * context,std::vector<std::string> * file_list,std::vector<std::string> * annotation_list)682 void FileGenerator::GenerateKotlinSiblings(
683 const std::string& package_dir, GeneratorContext* context,
684 std::vector<std::string>* file_list,
685 std::vector<std::string>* annotation_list) {
686 for (int i = 0; i < file_->message_type_count(); i++) {
687 const Descriptor* descriptor = file_->message_type(i);
688 MessageGenerator* generator = message_generators_[i].get();
689 auto open_file = [context](const std::string& filename) {
690 return std::unique_ptr<io::ZeroCopyOutputStream>(context->Open(filename));
691 };
692 std::string filename = package_dir + descriptor->name() + "Kt.kt";
693 file_list->push_back(filename);
694 std::string info_full_path = filename + ".pb.meta";
695 GeneratedCodeInfo annotations;
696 io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
697 &annotations);
698 auto output = open_file(filename);
699 io::Printer printer(
700 output.get(), '$',
701 options_.annotate_code ? &annotation_collector : nullptr);
702
703 printer.Print(
704 "//Generated by the protocol buffer compiler. DO NOT EDIT!\n"
705 "// source: $filename$\n"
706 "\n",
707 "filename", descriptor->file()->name());
708 if (!java_package_.empty()) {
709 printer.Print(
710 "package $package$;\n"
711 "\n",
712 "package", java_package_);
713 }
714
715 generator->GenerateKotlinMembers(&printer);
716 generator->GenerateTopLevelKotlinMembers(&printer);
717
718 if (options_.annotate_code) {
719 auto info_output = open_file(info_full_path);
720 annotations.SerializeToZeroCopyStream(info_output.get());
721 annotation_list->push_back(info_full_path);
722 }
723 }
724 }
725
ShouldIncludeDependency(const FileDescriptor * descriptor,bool immutable_api)726 bool FileGenerator::ShouldIncludeDependency(const FileDescriptor* descriptor,
727 bool immutable_api) {
728 return true;
729 }
730
731 } // namespace java
732 } // namespace compiler
733 } // namespace protobuf
734 } // namespace google
735