java_file.cc 28 KB

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