java_file.cc 27 KB

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