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 namespace google {
58 namespace protobuf {
59 namespace compiler {
60 namespace java {
61
62 namespace {
63
64 struct FieldDescriptorCompare {
operator ()google::protobuf::compiler::java::__anon1f5df0950111::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
390
GenerateDescriptorInitializationCodeForImmutable(io::Printer * printer)391 void FileGenerator::GenerateDescriptorInitializationCodeForImmutable(
392 io::Printer* printer) {
393 printer->Print(
394 "public static com.google.protobuf.Descriptors.FileDescriptor\n"
395 " getDescriptor() {\n"
396 " return descriptor;\n"
397 "}\n"
398 "private static $final$ com.google.protobuf.Descriptors.FileDescriptor\n"
399 " descriptor;\n"
400 "static {\n",
401 // TODO(dweis): Mark this as final.
402 "final", "");
403 printer->Indent();
404
405 SharedCodeGenerator shared_code_generator(file_, options_);
406 shared_code_generator.GenerateDescriptors(printer);
407
408 int bytecode_estimate = 0;
409 int method_num = 0;
410
411 for (int i = 0; i < file_->message_type_count(); i++) {
412 bytecode_estimate +=
413 message_generators_[i]->GenerateStaticVariableInitializers(printer);
414 MaybeRestartJavaMethod(
415 printer, &bytecode_estimate, &method_num,
416 "_clinit_autosplit_dinit_$method_num$();\n",
417 "private static void _clinit_autosplit_dinit_$method_num$() {\n");
418 }
419 for (int i = 0; i < file_->extension_count(); i++) {
420 bytecode_estimate +=
421 extension_generators_[i]->GenerateNonNestedInitializationCode(printer);
422 MaybeRestartJavaMethod(
423 printer, &bytecode_estimate, &method_num,
424 "_clinit_autosplit_dinit_$method_num$();\n",
425 "private static void _clinit_autosplit_dinit_$method_num$() {\n");
426 }
427
428 // Proto compiler builds a DescriptorPool, which holds all the descriptors to
429 // generate, when processing the ".proto" files. We call this DescriptorPool
430 // the parsed pool (a.k.a. file_->pool()).
431 //
432 // Note that when users try to extend the (.*)DescriptorProto in their
433 // ".proto" files, it does not affect the pre-built FileDescriptorProto class
434 // in proto compiler. When we put the descriptor data in the file_proto, those
435 // extensions become unknown fields.
436 //
437 // Now we need to find out all the extension value to the (.*)DescriptorProto
438 // in the file_proto message, and prepare an ExtensionRegistry to return.
439 //
440 // To find those extensions, we need to parse the data into a dynamic message
441 // of the FileDescriptor based on the builder-pool, then we can use
442 // reflections to find all extension fields
443 FileDescriptorProto file_proto;
444 file_->CopyTo(&file_proto);
445 std::string file_data;
446 file_proto.SerializeToString(&file_data);
447 FieldDescriptorSet extensions;
448 CollectExtensions(file_proto, *file_->pool(), &extensions, file_data);
449
450 if (extensions.size() > 0) {
451 // Must construct an ExtensionRegistry containing all existing extensions
452 // and use it to parse the descriptor data again to recognize extensions.
453 printer->Print(
454 "com.google.protobuf.ExtensionRegistry registry =\n"
455 " com.google.protobuf.ExtensionRegistry.newInstance();\n");
456 FieldDescriptorSet::iterator it;
457 for (it = extensions.begin(); it != extensions.end(); it++) {
458 std::unique_ptr<ExtensionGenerator> generator(
459 generator_factory_->NewExtensionGenerator(*it));
460 bytecode_estimate += generator->GenerateRegistrationCode(printer);
461 MaybeRestartJavaMethod(
462 printer, &bytecode_estimate, &method_num,
463 "_clinit_autosplit_dinit_$method_num$(registry);\n",
464 "private static void _clinit_autosplit_dinit_$method_num$(\n"
465 " com.google.protobuf.ExtensionRegistry registry) {\n");
466 }
467 printer->Print(
468 "com.google.protobuf.Descriptors.FileDescriptor\n"
469 " .internalUpdateFileDescriptor(descriptor, registry);\n");
470 }
471
472 // Force descriptor initialization of all dependencies.
473 for (int i = 0; i < file_->dependency_count(); i++) {
474 if (ShouldIncludeDependency(file_->dependency(i), true)) {
475 std::string dependency =
476 name_resolver_->GetImmutableClassName(file_->dependency(i));
477 printer->Print("$dependency$.getDescriptor();\n", "dependency",
478 dependency);
479 }
480 }
481
482 printer->Outdent();
483 printer->Print("}\n");
484 }
485
GenerateDescriptorInitializationCodeForMutable(io::Printer * printer)486 void FileGenerator::GenerateDescriptorInitializationCodeForMutable(
487 io::Printer* printer) {
488 printer->Print(
489 "public static com.google.protobuf.Descriptors.FileDescriptor\n"
490 " getDescriptor() {\n"
491 " return descriptor;\n"
492 "}\n"
493 "private static final com.google.protobuf.Descriptors.FileDescriptor\n"
494 " descriptor;\n"
495 "static {\n");
496 printer->Indent();
497
498 printer->Print(
499 "descriptor = $immutable_package$.$descriptor_classname$.descriptor;\n",
500 "immutable_package", FileJavaPackage(file_, true), "descriptor_classname",
501 name_resolver_->GetDescriptorClassName(file_));
502
503 for (int i = 0; i < file_->message_type_count(); i++) {
504 message_generators_[i]->GenerateStaticVariableInitializers(printer);
505 }
506 for (int i = 0; i < file_->extension_count(); i++) {
507 extension_generators_[i]->GenerateNonNestedInitializationCode(printer);
508 }
509
510 // Check if custom options exist. If any, try to load immutable classes since
511 // custom options are only represented with immutable messages.
512 FileDescriptorProto file_proto;
513 file_->CopyTo(&file_proto);
514 std::string file_data;
515 file_proto.SerializeToString(&file_data);
516 FieldDescriptorSet extensions;
517 CollectExtensions(file_proto, *file_->pool(), &extensions, file_data);
518
519 if (extensions.size() > 0) {
520 // Try to load immutable messages' outer class. Its initialization code
521 // will take care of interpreting custom options.
522 printer->Print(
523 "try {\n"
524 // Note that we have to load the immutable class dynamically here as
525 // we want the mutable code to be independent from the immutable code
526 // at compile time. It is required to implement dual-compile for
527 // mutable and immutable API in blaze.
528 " java.lang.Class<?> immutableClass = java.lang.Class.forName(\n"
529 " \"$immutable_classname$\");\n"
530 "} catch (java.lang.ClassNotFoundException e) {\n",
531 "immutable_classname", name_resolver_->GetImmutableClassName(file_));
532 printer->Indent();
533
534 // The immutable class can not be found. We try our best to collect all
535 // custom option extensions to interpret the custom options.
536 printer->Print(
537 "com.google.protobuf.ExtensionRegistry registry =\n"
538 " com.google.protobuf.ExtensionRegistry.newInstance();\n"
539 "com.google.protobuf.MessageLite defaultExtensionInstance = null;\n");
540 FieldDescriptorSet::iterator it;
541 for (it = extensions.begin(); it != extensions.end(); it++) {
542 const FieldDescriptor* field = *it;
543 std::string scope;
544 if (field->extension_scope() != NULL) {
545 scope = name_resolver_->GetMutableClassName(field->extension_scope()) +
546 ".getDescriptor()";
547 } else {
548 scope = FileJavaPackage(field->file(), true) + "." +
549 name_resolver_->GetDescriptorClassName(field->file()) +
550 ".descriptor";
551 }
552 if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
553 printer->Print(
554 "defaultExtensionInstance = com.google.protobuf.Internal\n"
555 " .getDefaultInstance(\"$class$\");\n"
556 "if (defaultExtensionInstance != null) {\n"
557 " registry.add(\n"
558 " $scope$.getExtensions().get($index$),\n"
559 " (com.google.protobuf.Message) defaultExtensionInstance);\n"
560 "}\n",
561 "scope", scope, "index", StrCat(field->index()), "class",
562 name_resolver_->GetImmutableClassName(field->message_type()));
563 } else {
564 printer->Print("registry.add($scope$.getExtensions().get($index$));\n",
565 "scope", scope, "index", StrCat(field->index()));
566 }
567 }
568 printer->Print(
569 "com.google.protobuf.Descriptors.FileDescriptor\n"
570 " .internalUpdateFileDescriptor(descriptor, registry);\n");
571
572 printer->Outdent();
573 printer->Print("}\n");
574 }
575
576 // Force descriptor initialization of all dependencies.
577 for (int i = 0; i < file_->dependency_count(); i++) {
578 if (ShouldIncludeDependency(file_->dependency(i), false)) {
579 std::string dependency =
580 name_resolver_->GetMutableClassName(file_->dependency(i));
581 printer->Print("$dependency$.getDescriptor();\n", "dependency",
582 dependency);
583 }
584 }
585
586 printer->Outdent();
587 printer->Print("}\n");
588 }
589
590 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))591 static void GenerateSibling(
592 const std::string& package_dir, const std::string& java_package,
593 const DescriptorClass* descriptor, GeneratorContext* context,
594 std::vector<std::string>* file_list, bool annotate_code,
595 std::vector<std::string>* annotation_list, const std::string& name_suffix,
596 GeneratorClass* generator,
597 void (GeneratorClass::*pfn)(io::Printer* printer)) {
598 std::string filename =
599 package_dir + descriptor->name() + name_suffix + ".java";
600 file_list->push_back(filename);
601 std::string info_full_path = filename + ".pb.meta";
602 GeneratedCodeInfo annotations;
603 io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
604 &annotations);
605
606 std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
607 io::Printer printer(output.get(), '$',
608 annotate_code ? &annotation_collector : NULL);
609
610 printer.Print(
611 "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
612 "// source: $filename$\n"
613 "\n",
614 "filename", descriptor->file()->name());
615 if (!java_package.empty()) {
616 printer.Print(
617 "package $package$;\n"
618 "\n",
619 "package", java_package);
620 }
621
622 (generator->*pfn)(&printer);
623
624 if (annotate_code) {
625 std::unique_ptr<io::ZeroCopyOutputStream> info_output(
626 context->Open(info_full_path));
627 annotations.SerializeToZeroCopyStream(info_output.get());
628 annotation_list->push_back(info_full_path);
629 }
630 }
631
GenerateSiblings(const std::string & package_dir,GeneratorContext * context,std::vector<std::string> * file_list,std::vector<std::string> * annotation_list)632 void FileGenerator::GenerateSiblings(
633 const std::string& package_dir, GeneratorContext* context,
634 std::vector<std::string>* file_list,
635 std::vector<std::string>* annotation_list) {
636 if (MultipleJavaFiles(file_, immutable_api_)) {
637 for (int i = 0; i < file_->enum_type_count(); i++) {
638 if (HasDescriptorMethods(file_, context_->EnforceLite())) {
639 EnumGenerator generator(file_->enum_type(i), immutable_api_,
640 context_.get());
641 GenerateSibling<EnumGenerator>(
642 package_dir, java_package_, file_->enum_type(i), context, file_list,
643 options_.annotate_code, annotation_list, "", &generator,
644 &EnumGenerator::Generate);
645 } else {
646 EnumLiteGenerator generator(file_->enum_type(i), immutable_api_,
647 context_.get());
648 GenerateSibling<EnumLiteGenerator>(
649 package_dir, java_package_, file_->enum_type(i), context, file_list,
650 options_.annotate_code, annotation_list, "", &generator,
651 &EnumLiteGenerator::Generate);
652 }
653 }
654 for (int i = 0; i < file_->message_type_count(); i++) {
655 if (immutable_api_) {
656 GenerateSibling<MessageGenerator>(
657 package_dir, java_package_, file_->message_type(i), context,
658 file_list, options_.annotate_code, annotation_list, "OrBuilder",
659 message_generators_[i].get(), &MessageGenerator::GenerateInterface);
660 }
661 GenerateSibling<MessageGenerator>(
662 package_dir, java_package_, file_->message_type(i), context,
663 file_list, options_.annotate_code, annotation_list, "",
664 message_generators_[i].get(), &MessageGenerator::Generate);
665 }
666 if (HasGenericServices(file_, context_->EnforceLite())) {
667 for (int i = 0; i < file_->service_count(); i++) {
668 std::unique_ptr<ServiceGenerator> generator(
669 generator_factory_->NewServiceGenerator(file_->service(i)));
670 GenerateSibling<ServiceGenerator>(
671 package_dir, java_package_, file_->service(i), context, file_list,
672 options_.annotate_code, annotation_list, "", generator.get(),
673 &ServiceGenerator::Generate);
674 }
675 }
676 }
677 }
678
ShouldIncludeDependency(const FileDescriptor * descriptor,bool immutable_api)679 bool FileGenerator::ShouldIncludeDependency(const FileDescriptor* descriptor,
680 bool immutable_api) {
681 return true;
682 }
683
684 } // namespace java
685 } // namespace compiler
686 } // namespace protobuf
687 } // namespace google
688