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