java_file.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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 std::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", StrCat(*method_num));
  158. printer->Outdent();
  159. printer->Print("}\n");
  160. printer->Print(method_decl, "method_num", StrCat(*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(std::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. NameEquality::EXACT_EQUAL)) {
  196. error->assign(file_->name());
  197. error->append(
  198. ": Cannot generate Java output because the file's outer class name, \"");
  199. error->append(classname_);
  200. error->append(
  201. "\", matches the name of one of the types declared inside it. "
  202. "Please either rename the type or use the java_outer_classname "
  203. "option to specify a different outer class name for the .proto file.");
  204. return false;
  205. }
  206. // Similar to the check above, but ignore the case this time. This is not a
  207. // problem on Linux, but will lead to Java compile errors on Windows / Mac
  208. // because filenames are case-insensitive on those platforms.
  209. if (name_resolver_->HasConflictingClassName(
  210. file_, classname_, NameEquality::EQUAL_IGNORE_CASE)) {
  211. GOOGLE_LOG(WARNING)
  212. << file_->name() << ": The file's outer class name, \"" << classname_
  213. << "\", matches the name of one of the types declared inside it when "
  214. << "case is ignored. This can cause compilation issues on Windows / "
  215. << "MacOS. Please either rename the type or use the "
  216. << "java_outer_classname option to specify a different outer class "
  217. << "name for the .proto file to be safe.";
  218. }
  219. // Print a warning if optimize_for = LITE_RUNTIME is used.
  220. if (file_->options().optimize_for() == FileOptions::LITE_RUNTIME) {
  221. GOOGLE_LOG(WARNING)
  222. << "The optimize_for = LITE_RUNTIME option is no longer supported by "
  223. << "protobuf Java code generator and may generate broken code. It "
  224. << "will be ignored by protoc in the future and protoc will always "
  225. << "generate full runtime code for Java. To use Java Lite runtime, "
  226. << "users should use the Java Lite plugin instead. See:\n"
  227. << " "
  228. "https://github.com/protocolbuffers/protobuf/blob/master/java/"
  229. "lite.md";
  230. }
  231. return true;
  232. }
  233. void FileGenerator::Generate(io::Printer* printer) {
  234. // We don't import anything because we refer to all classes by their
  235. // fully-qualified names in the generated source.
  236. printer->Print(
  237. "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
  238. "// source: $filename$\n"
  239. "\n",
  240. "filename", file_->name());
  241. if (!java_package_.empty()) {
  242. printer->Print(
  243. "package $package$;\n"
  244. "\n",
  245. "package", java_package_);
  246. }
  247. PrintGeneratedAnnotation(
  248. printer, '$', options_.annotate_code ? classname_ + ".java.pb.meta" : "");
  249. printer->Print(
  250. "$deprecation$public final class $classname$ {\n"
  251. " private $ctor$() {}\n",
  252. "deprecation", file_->options().deprecated() ?
  253. "@java.lang.Deprecated " : "",
  254. "classname", classname_,
  255. "ctor", classname_);
  256. printer->Annotate("classname", file_->name());
  257. printer->Indent();
  258. // -----------------------------------------------------------------
  259. printer->Print(
  260. "public static void registerAllExtensions(\n"
  261. " com.google.protobuf.ExtensionRegistryLite registry) {\n");
  262. printer->Indent();
  263. for (int i = 0; i < file_->extension_count(); i++) {
  264. extension_generators_[i]->GenerateRegistrationCode(printer);
  265. }
  266. for (int i = 0; i < file_->message_type_count(); i++) {
  267. message_generators_[i]->GenerateExtensionRegistrationCode(printer);
  268. }
  269. printer->Outdent();
  270. printer->Print(
  271. "}\n");
  272. if (HasDescriptorMethods(file_, context_->EnforceLite())) {
  273. // Overload registerAllExtensions for the non-lite usage to
  274. // redundantly maintain the original signature (this is
  275. // redundant because ExtensionRegistryLite now invokes
  276. // ExtensionRegistry in the non-lite usage). Intent is
  277. // to remove this in the future.
  278. printer->Print(
  279. "\n"
  280. "public static void registerAllExtensions(\n"
  281. " com.google.protobuf.ExtensionRegistry registry) {\n"
  282. " registerAllExtensions(\n"
  283. " (com.google.protobuf.ExtensionRegistryLite) registry);\n"
  284. "}\n");
  285. }
  286. // -----------------------------------------------------------------
  287. if (!MultipleJavaFiles(file_, immutable_api_)) {
  288. for (int i = 0; i < file_->enum_type_count(); i++) {
  289. if (HasDescriptorMethods(file_, context_->EnforceLite())) {
  290. EnumGenerator(file_->enum_type(i), immutable_api_, context_.get())
  291. .Generate(printer);
  292. } else {
  293. EnumLiteGenerator(file_->enum_type(i), immutable_api_, context_.get())
  294. .Generate(printer);
  295. }
  296. }
  297. for (int i = 0; i < file_->message_type_count(); i++) {
  298. message_generators_[i]->GenerateInterface(printer);
  299. message_generators_[i]->Generate(printer);
  300. }
  301. if (HasGenericServices(file_, context_->EnforceLite())) {
  302. for (int i = 0; i < file_->service_count(); i++) {
  303. std::unique_ptr<ServiceGenerator> generator(
  304. generator_factory_->NewServiceGenerator(file_->service(i)));
  305. generator->Generate(printer);
  306. }
  307. }
  308. }
  309. // Extensions must be generated in the outer class since they are values,
  310. // not classes.
  311. for (int i = 0; i < file_->extension_count(); i++) {
  312. extension_generators_[i]->Generate(printer);
  313. }
  314. // Static variables. We'd like them to be final if possible, but due to
  315. // the JVM's 64k size limit on static blocks, we have to initialize some
  316. // of them in methods; thus they cannot be final.
  317. int static_block_bytecode_estimate = 0;
  318. for (int i = 0; i < file_->message_type_count(); i++) {
  319. message_generators_[i]->GenerateStaticVariables(
  320. printer, &static_block_bytecode_estimate);
  321. }
  322. printer->Print("\n");
  323. if (HasDescriptorMethods(file_, context_->EnforceLite())) {
  324. if (immutable_api_) {
  325. GenerateDescriptorInitializationCodeForImmutable(printer);
  326. } else {
  327. GenerateDescriptorInitializationCodeForMutable(printer);
  328. }
  329. } else {
  330. printer->Print(
  331. "static {\n");
  332. printer->Indent();
  333. int bytecode_estimate = 0;
  334. int method_num = 0;
  335. for (int i = 0; i < file_->message_type_count(); i++) {
  336. bytecode_estimate += message_generators_[i]->GenerateStaticVariableInitializers(printer);
  337. MaybeRestartJavaMethod(
  338. printer,
  339. &bytecode_estimate, &method_num,
  340. "_clinit_autosplit_$method_num$();\n",
  341. "private static void _clinit_autosplit_$method_num$() {\n");
  342. }
  343. printer->Outdent();
  344. printer->Print(
  345. "}\n");
  346. }
  347. printer->Print(
  348. "\n"
  349. "// @@protoc_insertion_point(outer_class_scope)\n");
  350. printer->Outdent();
  351. printer->Print("}\n");
  352. }
  353. void FileGenerator::GenerateDescriptorInitializationCodeForImmutable(
  354. io::Printer* printer) {
  355. printer->Print(
  356. "public static com.google.protobuf.Descriptors.FileDescriptor\n"
  357. " getDescriptor() {\n"
  358. " return descriptor;\n"
  359. "}\n"
  360. "private static $final$ com.google.protobuf.Descriptors.FileDescriptor\n"
  361. " descriptor;\n"
  362. "static {\n",
  363. // TODO(dweis): Mark this as final.
  364. "final", "");
  365. printer->Indent();
  366. SharedCodeGenerator shared_code_generator(file_, options_);
  367. shared_code_generator.GenerateDescriptors(printer);
  368. int bytecode_estimate = 0;
  369. int method_num = 0;
  370. for (int i = 0; i < file_->message_type_count(); i++) {
  371. bytecode_estimate += message_generators_[i]->GenerateStaticVariableInitializers(printer);
  372. MaybeRestartJavaMethod(
  373. printer,
  374. &bytecode_estimate, &method_num,
  375. "_clinit_autosplit_dinit_$method_num$();\n",
  376. "private static void _clinit_autosplit_dinit_$method_num$() {\n");
  377. }
  378. for (int i = 0; i < file_->extension_count(); i++) {
  379. bytecode_estimate += extension_generators_[i]->GenerateNonNestedInitializationCode(printer);
  380. MaybeRestartJavaMethod(
  381. printer,
  382. &bytecode_estimate, &method_num,
  383. "_clinit_autosplit_dinit_$method_num$();\n",
  384. "private static void _clinit_autosplit_dinit_$method_num$() {\n");
  385. }
  386. // Proto compiler builds a DescriptorPool, which holds all the descriptors to
  387. // generate, when processing the ".proto" files. We call this DescriptorPool
  388. // the parsed pool (a.k.a. file_->pool()).
  389. //
  390. // Note that when users try to extend the (.*)DescriptorProto in their
  391. // ".proto" files, it does not affect the pre-built FileDescriptorProto class
  392. // in proto compiler. When we put the descriptor data in the file_proto, those
  393. // extensions become unknown fields.
  394. //
  395. // Now we need to find out all the extension value to the (.*)DescriptorProto
  396. // in the file_proto message, and prepare an ExtensionRegistry to return.
  397. //
  398. // To find those extensions, we need to parse the data into a dynamic message
  399. // of the FileDescriptor based on the builder-pool, then we can use
  400. // reflections to find all extension fields
  401. FileDescriptorProto file_proto;
  402. file_->CopyTo(&file_proto);
  403. std::string file_data;
  404. file_proto.SerializeToString(&file_data);
  405. FieldDescriptorSet extensions;
  406. CollectExtensions(file_proto, *file_->pool(), &extensions, file_data);
  407. if (extensions.size() > 0) {
  408. // Must construct an ExtensionRegistry containing all existing extensions
  409. // and use it to parse the descriptor data again to recognize extensions.
  410. printer->Print(
  411. "com.google.protobuf.ExtensionRegistry registry =\n"
  412. " com.google.protobuf.ExtensionRegistry.newInstance();\n");
  413. FieldDescriptorSet::iterator it;
  414. for (it = extensions.begin(); it != extensions.end(); it++) {
  415. std::unique_ptr<ExtensionGenerator> generator(
  416. generator_factory_->NewExtensionGenerator(*it));
  417. bytecode_estimate += generator->GenerateRegistrationCode(printer);
  418. MaybeRestartJavaMethod(
  419. printer,
  420. &bytecode_estimate, &method_num,
  421. "_clinit_autosplit_dinit_$method_num$(registry);\n",
  422. "private static void _clinit_autosplit_dinit_$method_num$(\n"
  423. " com.google.protobuf.ExtensionRegistry registry) {\n");
  424. }
  425. printer->Print(
  426. "com.google.protobuf.Descriptors.FileDescriptor\n"
  427. " .internalUpdateFileDescriptor(descriptor, registry);\n");
  428. }
  429. // Force descriptor initialization of all dependencies.
  430. for (int i = 0; i < file_->dependency_count(); i++) {
  431. if (ShouldIncludeDependency(file_->dependency(i), true)) {
  432. std::string dependency =
  433. name_resolver_->GetImmutableClassName(file_->dependency(i));
  434. printer->Print(
  435. "$dependency$.getDescriptor();\n",
  436. "dependency", dependency);
  437. }
  438. }
  439. printer->Outdent();
  440. printer->Print(
  441. "}\n");
  442. }
  443. void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer* printer) {
  444. printer->Print(
  445. "public static com.google.protobuf.Descriptors.FileDescriptor\n"
  446. " getDescriptor() {\n"
  447. " return descriptor;\n"
  448. "}\n"
  449. "private static final com.google.protobuf.Descriptors.FileDescriptor\n"
  450. " descriptor;\n"
  451. "static {\n");
  452. printer->Indent();
  453. printer->Print(
  454. "descriptor = $immutable_package$.$descriptor_classname$.descriptor;\n",
  455. "immutable_package", FileJavaPackage(file_, true),
  456. "descriptor_classname", name_resolver_->GetDescriptorClassName(file_));
  457. for (int i = 0; i < file_->message_type_count(); i++) {
  458. message_generators_[i]->GenerateStaticVariableInitializers(printer);
  459. }
  460. for (int i = 0; i < file_->extension_count(); i++) {
  461. extension_generators_[i]->GenerateNonNestedInitializationCode(printer);
  462. }
  463. // Check if custom options exist. If any, try to load immutable classes since
  464. // custom options are only represented with immutable messages.
  465. FileDescriptorProto file_proto;
  466. file_->CopyTo(&file_proto);
  467. std::string file_data;
  468. file_proto.SerializeToString(&file_data);
  469. FieldDescriptorSet extensions;
  470. CollectExtensions(file_proto, *file_->pool(), &extensions, file_data);
  471. if (extensions.size() > 0) {
  472. // Try to load immutable messages' outer class. Its initialization code
  473. // will take care of interpreting custom options.
  474. printer->Print(
  475. "try {\n"
  476. // Note that we have to load the immutable class dynamically here as
  477. // we want the mutable code to be independent from the immutable code
  478. // at compile time. It is required to implement dual-compile for
  479. // mutable and immutable API in blaze.
  480. " java.lang.Class immutableClass = java.lang.Class.forName(\n"
  481. " \"$immutable_classname$\");\n"
  482. "} catch (java.lang.ClassNotFoundException e) {\n",
  483. "immutable_classname", name_resolver_->GetImmutableClassName(file_));
  484. printer->Indent();
  485. // The immutable class can not be found. We try our best to collect all
  486. // custom option extensions to interpret the custom options.
  487. printer->Print(
  488. "com.google.protobuf.ExtensionRegistry registry =\n"
  489. " com.google.protobuf.ExtensionRegistry.newInstance();\n"
  490. "com.google.protobuf.MessageLite defaultExtensionInstance = null;\n");
  491. FieldDescriptorSet::iterator it;
  492. for (it = extensions.begin(); it != extensions.end(); it++) {
  493. const FieldDescriptor* field = *it;
  494. std::string scope;
  495. if (field->extension_scope() != NULL) {
  496. scope = name_resolver_->GetMutableClassName(field->extension_scope()) +
  497. ".getDescriptor()";
  498. } else {
  499. scope = FileJavaPackage(field->file(), true) + "." +
  500. name_resolver_->GetDescriptorClassName(field->file()) +
  501. ".descriptor";
  502. }
  503. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  504. printer->Print(
  505. "defaultExtensionInstance = com.google.protobuf.Internal\n"
  506. " .getDefaultInstance(\"$class$\");\n"
  507. "if (defaultExtensionInstance != null) {\n"
  508. " registry.add(\n"
  509. " $scope$.getExtensions().get($index$),\n"
  510. " (com.google.protobuf.Message) defaultExtensionInstance);\n"
  511. "}\n",
  512. "scope", scope, "index", StrCat(field->index()), "class",
  513. name_resolver_->GetImmutableClassName(field->message_type()));
  514. } else {
  515. printer->Print("registry.add($scope$.getExtensions().get($index$));\n",
  516. "scope", scope, "index", StrCat(field->index()));
  517. }
  518. }
  519. printer->Print(
  520. "com.google.protobuf.Descriptors.FileDescriptor\n"
  521. " .internalUpdateFileDescriptor(descriptor, registry);\n");
  522. printer->Outdent();
  523. printer->Print("}\n");
  524. }
  525. // Force descriptor initialization of all dependencies.
  526. for (int i = 0; i < file_->dependency_count(); i++) {
  527. if (ShouldIncludeDependency(file_->dependency(i), false)) {
  528. std::string dependency =
  529. name_resolver_->GetMutableClassName(file_->dependency(i));
  530. printer->Print(
  531. "$dependency$.getDescriptor();\n",
  532. "dependency", dependency);
  533. }
  534. }
  535. printer->Outdent();
  536. printer->Print(
  537. "}\n");
  538. }
  539. template <typename GeneratorClass, typename DescriptorClass>
  540. static void GenerateSibling(
  541. const std::string& package_dir, const std::string& java_package,
  542. const DescriptorClass* descriptor, GeneratorContext* context,
  543. std::vector<std::string>* file_list, bool annotate_code,
  544. std::vector<std::string>* annotation_list, const std::string& name_suffix,
  545. GeneratorClass* generator,
  546. void (GeneratorClass::*pfn)(io::Printer* printer)) {
  547. std::string filename =
  548. package_dir + descriptor->name() + name_suffix + ".java";
  549. file_list->push_back(filename);
  550. std::string info_full_path = filename + ".pb.meta";
  551. GeneratedCodeInfo annotations;
  552. io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
  553. &annotations);
  554. std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
  555. io::Printer printer(output.get(), '$',
  556. annotate_code ? &annotation_collector : NULL);
  557. printer.Print(
  558. "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
  559. "// source: $filename$\n"
  560. "\n",
  561. "filename", descriptor->file()->name());
  562. if (!java_package.empty()) {
  563. printer.Print(
  564. "package $package$;\n"
  565. "\n",
  566. "package", java_package);
  567. }
  568. (generator->*pfn)(&printer);
  569. if (annotate_code) {
  570. std::unique_ptr<io::ZeroCopyOutputStream> info_output(
  571. context->Open(info_full_path));
  572. annotations.SerializeToZeroCopyStream(info_output.get());
  573. annotation_list->push_back(info_full_path);
  574. }
  575. }
  576. void FileGenerator::GenerateSiblings(
  577. const std::string& package_dir, GeneratorContext* context,
  578. std::vector<std::string>* file_list,
  579. std::vector<std::string>* annotation_list) {
  580. if (MultipleJavaFiles(file_, immutable_api_)) {
  581. for (int i = 0; i < file_->enum_type_count(); i++) {
  582. if (HasDescriptorMethods(file_, context_->EnforceLite())) {
  583. EnumGenerator generator(file_->enum_type(i), immutable_api_,
  584. context_.get());
  585. GenerateSibling<EnumGenerator>(
  586. package_dir, java_package_, file_->enum_type(i), context, file_list,
  587. options_.annotate_code, annotation_list, "", &generator,
  588. &EnumGenerator::Generate);
  589. } else {
  590. EnumLiteGenerator generator(file_->enum_type(i), immutable_api_,
  591. context_.get());
  592. GenerateSibling<EnumLiteGenerator>(
  593. package_dir, java_package_, file_->enum_type(i), context, file_list,
  594. options_.annotate_code, annotation_list, "", &generator,
  595. &EnumLiteGenerator::Generate);
  596. }
  597. }
  598. for (int i = 0; i < file_->message_type_count(); i++) {
  599. if (immutable_api_) {
  600. GenerateSibling<MessageGenerator>(
  601. package_dir, java_package_, file_->message_type(i), context,
  602. file_list, options_.annotate_code, annotation_list, "OrBuilder",
  603. message_generators_[i].get(), &MessageGenerator::GenerateInterface);
  604. }
  605. GenerateSibling<MessageGenerator>(
  606. package_dir, java_package_, file_->message_type(i), context,
  607. file_list, options_.annotate_code, annotation_list, "",
  608. message_generators_[i].get(), &MessageGenerator::Generate);
  609. }
  610. if (HasGenericServices(file_, context_->EnforceLite())) {
  611. for (int i = 0; i < file_->service_count(); i++) {
  612. std::unique_ptr<ServiceGenerator> generator(
  613. generator_factory_->NewServiceGenerator(file_->service(i)));
  614. GenerateSibling<ServiceGenerator>(
  615. package_dir, java_package_, file_->service(i), context, file_list,
  616. options_.annotate_code, annotation_list, "", generator.get(),
  617. &ServiceGenerator::Generate);
  618. }
  619. }
  620. }
  621. }
  622. bool FileGenerator::ShouldIncludeDependency(
  623. const FileDescriptor* descriptor, bool immutable_api) {
  624. return true;
  625. }
  626. } // namespace java
  627. } // namespace compiler
  628. } // namespace protobuf
  629. } // namespace google