/thirdparty/breakpad/third_party/protobuf/protobuf/src/google/protobuf/compiler/java/java_file.cc

http://github.com/tomahawk-player/tomahawk · C++ · 428 lines · 301 code · 59 blank · 68 comment · 55 complexity · 0ed69056d26484abdb3057efd857af2e MD5 · raw file

  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://code.google.com/p/protobuf/
  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 <google/protobuf/compiler/java/java_enum.h>
  35. #include <google/protobuf/compiler/java/java_service.h>
  36. #include <google/protobuf/compiler/java/java_extension.h>
  37. #include <google/protobuf/compiler/java/java_helpers.h>
  38. #include <google/protobuf/compiler/java/java_message.h>
  39. #include <google/protobuf/compiler/code_generator.h>
  40. #include <google/protobuf/io/printer.h>
  41. #include <google/protobuf/io/zero_copy_stream.h>
  42. #include <google/protobuf/descriptor.pb.h>
  43. #include <google/protobuf/stubs/strutil.h>
  44. namespace google {
  45. namespace protobuf {
  46. namespace compiler {
  47. namespace java {
  48. namespace {
  49. // Recursively searches the given message to see if it contains any extensions.
  50. bool UsesExtensions(const Message& message) {
  51. const Reflection* reflection = message.GetReflection();
  52. // We conservatively assume that unknown fields are extensions.
  53. if (reflection->GetUnknownFields(message).field_count() > 0) return true;
  54. vector<const FieldDescriptor*> fields;
  55. reflection->ListFields(message, &fields);
  56. for (int i = 0; i < fields.size(); i++) {
  57. if (fields[i]->is_extension()) return true;
  58. if (GetJavaType(fields[i]) == JAVATYPE_MESSAGE) {
  59. if (fields[i]->is_repeated()) {
  60. int size = reflection->FieldSize(message, fields[i]);
  61. for (int j = 0; j < size; j++) {
  62. const Message& sub_message =
  63. reflection->GetRepeatedMessage(message, fields[i], j);
  64. if (UsesExtensions(sub_message)) return true;
  65. }
  66. } else {
  67. const Message& sub_message = reflection->GetMessage(message, fields[i]);
  68. if (UsesExtensions(sub_message)) return true;
  69. }
  70. }
  71. }
  72. return false;
  73. }
  74. } // namespace
  75. FileGenerator::FileGenerator(const FileDescriptor* file)
  76. : file_(file),
  77. java_package_(FileJavaPackage(file)),
  78. classname_(FileClassName(file)) {
  79. }
  80. FileGenerator::~FileGenerator() {}
  81. bool FileGenerator::Validate(string* error) {
  82. // Check that no class name matches the file's class name. This is a common
  83. // problem that leads to Java compile errors that can be hard to understand.
  84. // It's especially bad when using the java_multiple_files, since we would
  85. // end up overwriting the outer class with one of the inner ones.
  86. bool found_conflict = false;
  87. for (int i = 0; i < file_->enum_type_count() && !found_conflict; i++) {
  88. if (file_->enum_type(i)->name() == classname_) {
  89. found_conflict = true;
  90. }
  91. }
  92. for (int i = 0; i < file_->message_type_count() && !found_conflict; i++) {
  93. if (file_->message_type(i)->name() == classname_) {
  94. found_conflict = true;
  95. }
  96. }
  97. for (int i = 0; i < file_->service_count() && !found_conflict; i++) {
  98. if (file_->service(i)->name() == classname_) {
  99. found_conflict = true;
  100. }
  101. }
  102. if (found_conflict) {
  103. error->assign(file_->name());
  104. error->append(
  105. ": Cannot generate Java output because the file's outer class name, \"");
  106. error->append(classname_);
  107. error->append(
  108. "\", matches the name of one of the types declared inside it. "
  109. "Please either rename the type or use the java_outer_classname "
  110. "option to specify a different outer class name for the .proto file.");
  111. return false;
  112. }
  113. return true;
  114. }
  115. void FileGenerator::Generate(io::Printer* printer) {
  116. // We don't import anything because we refer to all classes by their
  117. // fully-qualified names in the generated source.
  118. printer->Print(
  119. "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
  120. "// source: $filename$\n"
  121. "\n",
  122. "filename", file_->name());
  123. if (!java_package_.empty()) {
  124. printer->Print(
  125. "package $package$;\n"
  126. "\n",
  127. "package", java_package_);
  128. }
  129. printer->Print(
  130. "public final class $classname$ {\n"
  131. " private $classname$() {}\n",
  132. "classname", classname_);
  133. printer->Indent();
  134. // -----------------------------------------------------------------
  135. printer->Print(
  136. "public static void registerAllExtensions(\n"
  137. " com.google.protobuf.ExtensionRegistry$lite$ registry) {\n",
  138. "lite", HasDescriptorMethods(file_) ? "" : "Lite");
  139. printer->Indent();
  140. for (int i = 0; i < file_->extension_count(); i++) {
  141. ExtensionGenerator(file_->extension(i)).GenerateRegistrationCode(printer);
  142. }
  143. for (int i = 0; i < file_->message_type_count(); i++) {
  144. MessageGenerator(file_->message_type(i))
  145. .GenerateExtensionRegistrationCode(printer);
  146. }
  147. printer->Outdent();
  148. printer->Print(
  149. "}\n");
  150. // -----------------------------------------------------------------
  151. if (!file_->options().java_multiple_files()) {
  152. for (int i = 0; i < file_->enum_type_count(); i++) {
  153. EnumGenerator(file_->enum_type(i)).Generate(printer);
  154. }
  155. for (int i = 0; i < file_->message_type_count(); i++) {
  156. MessageGenerator messageGenerator(file_->message_type(i));
  157. messageGenerator.GenerateInterface(printer);
  158. messageGenerator.Generate(printer);
  159. }
  160. if (HasGenericServices(file_)) {
  161. for (int i = 0; i < file_->service_count(); i++) {
  162. ServiceGenerator(file_->service(i)).Generate(printer);
  163. }
  164. }
  165. }
  166. // Extensions must be generated in the outer class since they are values,
  167. // not classes.
  168. for (int i = 0; i < file_->extension_count(); i++) {
  169. ExtensionGenerator(file_->extension(i)).Generate(printer);
  170. }
  171. // Static variables.
  172. for (int i = 0; i < file_->message_type_count(); i++) {
  173. // TODO(kenton): Reuse MessageGenerator objects?
  174. MessageGenerator(file_->message_type(i)).GenerateStaticVariables(printer);
  175. }
  176. printer->Print("\n");
  177. if (HasDescriptorMethods(file_)) {
  178. GenerateEmbeddedDescriptor(printer);
  179. } else {
  180. printer->Print(
  181. "static {\n");
  182. printer->Indent();
  183. for (int i = 0; i < file_->message_type_count(); i++) {
  184. // TODO(kenton): Reuse MessageGenerator objects?
  185. MessageGenerator(file_->message_type(i))
  186. .GenerateStaticVariableInitializers(printer);
  187. }
  188. printer->Outdent();
  189. printer->Print(
  190. "}\n");
  191. }
  192. printer->Print(
  193. "\n"
  194. "// @@protoc_insertion_point(outer_class_scope)\n");
  195. printer->Outdent();
  196. printer->Print("}\n");
  197. }
  198. void FileGenerator::GenerateEmbeddedDescriptor(io::Printer* printer) {
  199. // Embed the descriptor. We simply serialize the entire FileDescriptorProto
  200. // and embed it as a string literal, which is parsed and built into real
  201. // descriptors at initialization time. We unfortunately have to put it in
  202. // a string literal, not a byte array, because apparently using a literal
  203. // byte array causes the Java compiler to generate *instructions* to
  204. // initialize each and every byte of the array, e.g. as if you typed:
  205. // b[0] = 123; b[1] = 456; b[2] = 789;
  206. // This makes huge bytecode files and can easily hit the compiler's internal
  207. // code size limits (error "code to large"). String literals are apparently
  208. // embedded raw, which is what we want.
  209. FileDescriptorProto file_proto;
  210. file_->CopyTo(&file_proto);
  211. string file_data;
  212. file_proto.SerializeToString(&file_data);
  213. printer->Print(
  214. "public static com.google.protobuf.Descriptors.FileDescriptor\n"
  215. " getDescriptor() {\n"
  216. " return descriptor;\n"
  217. "}\n"
  218. "private static com.google.protobuf.Descriptors.FileDescriptor\n"
  219. " descriptor;\n"
  220. "static {\n"
  221. " java.lang.String[] descriptorData = {\n");
  222. printer->Indent();
  223. printer->Indent();
  224. // Only write 40 bytes per line.
  225. static const int kBytesPerLine = 40;
  226. for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
  227. if (i > 0) {
  228. // Every 400 lines, start a new string literal, in order to avoid the
  229. // 64k length limit.
  230. if (i % 400 == 0) {
  231. printer->Print(",\n");
  232. } else {
  233. printer->Print(" +\n");
  234. }
  235. }
  236. printer->Print("\"$data$\"",
  237. "data", CEscape(file_data.substr(i, kBytesPerLine)));
  238. }
  239. printer->Outdent();
  240. printer->Print("\n};\n");
  241. // -----------------------------------------------------------------
  242. // Create the InternalDescriptorAssigner.
  243. printer->Print(
  244. "com.google.protobuf.Descriptors.FileDescriptor."
  245. "InternalDescriptorAssigner assigner =\n"
  246. " new com.google.protobuf.Descriptors.FileDescriptor."
  247. "InternalDescriptorAssigner() {\n"
  248. " public com.google.protobuf.ExtensionRegistry assignDescriptors(\n"
  249. " com.google.protobuf.Descriptors.FileDescriptor root) {\n"
  250. " descriptor = root;\n");
  251. printer->Indent();
  252. printer->Indent();
  253. printer->Indent();
  254. for (int i = 0; i < file_->message_type_count(); i++) {
  255. // TODO(kenton): Reuse MessageGenerator objects?
  256. MessageGenerator(file_->message_type(i))
  257. .GenerateStaticVariableInitializers(printer);
  258. }
  259. for (int i = 0; i < file_->extension_count(); i++) {
  260. // TODO(kenton): Reuse ExtensionGenerator objects?
  261. ExtensionGenerator(file_->extension(i))
  262. .GenerateNonNestedInitializationCode(printer);
  263. }
  264. if (UsesExtensions(file_proto)) {
  265. // Must construct an ExtensionRegistry containing all possible extensions
  266. // and return it.
  267. printer->Print(
  268. "com.google.protobuf.ExtensionRegistry registry =\n"
  269. " com.google.protobuf.ExtensionRegistry.newInstance();\n"
  270. "registerAllExtensions(registry);\n");
  271. for (int i = 0; i < file_->dependency_count(); i++) {
  272. if (ShouldIncludeDependency(file_->dependency(i))) {
  273. printer->Print(
  274. "$dependency$.registerAllExtensions(registry);\n",
  275. "dependency", ClassName(file_->dependency(i)));
  276. }
  277. }
  278. printer->Print(
  279. "return registry;\n");
  280. } else {
  281. printer->Print(
  282. "return null;\n");
  283. }
  284. printer->Outdent();
  285. printer->Outdent();
  286. printer->Outdent();
  287. printer->Print(
  288. " }\n"
  289. " };\n");
  290. // -----------------------------------------------------------------
  291. // Invoke internalBuildGeneratedFileFrom() to build the file.
  292. printer->Print(
  293. "com.google.protobuf.Descriptors.FileDescriptor\n"
  294. " .internalBuildGeneratedFileFrom(descriptorData,\n"
  295. " new com.google.protobuf.Descriptors.FileDescriptor[] {\n");
  296. for (int i = 0; i < file_->dependency_count(); i++) {
  297. if (ShouldIncludeDependency(file_->dependency(i))) {
  298. printer->Print(
  299. " $dependency$.getDescriptor(),\n",
  300. "dependency", ClassName(file_->dependency(i)));
  301. }
  302. }
  303. printer->Print(
  304. " }, assigner);\n");
  305. printer->Outdent();
  306. printer->Print(
  307. "}\n");
  308. }
  309. template<typename GeneratorClass, typename DescriptorClass>
  310. static void GenerateSibling(const string& package_dir,
  311. const string& java_package,
  312. const DescriptorClass* descriptor,
  313. GeneratorContext* context,
  314. vector<string>* file_list,
  315. const string& name_suffix,
  316. void (GeneratorClass::*pfn)(io::Printer* printer)) {
  317. string filename = package_dir + descriptor->name() + name_suffix + ".java";
  318. file_list->push_back(filename);
  319. scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
  320. io::Printer printer(output.get(), '$');
  321. printer.Print(
  322. "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
  323. "\n");
  324. if (!java_package.empty()) {
  325. printer.Print(
  326. "package $package$;\n"
  327. "\n",
  328. "package", java_package);
  329. }
  330. GeneratorClass generator(descriptor);
  331. (generator.*pfn)(&printer);
  332. }
  333. void FileGenerator::GenerateSiblings(const string& package_dir,
  334. GeneratorContext* context,
  335. vector<string>* file_list) {
  336. if (file_->options().java_multiple_files()) {
  337. for (int i = 0; i < file_->enum_type_count(); i++) {
  338. GenerateSibling<EnumGenerator>(package_dir, java_package_,
  339. file_->enum_type(i),
  340. context, file_list, "",
  341. &EnumGenerator::Generate);
  342. }
  343. for (int i = 0; i < file_->message_type_count(); i++) {
  344. GenerateSibling<MessageGenerator>(package_dir, java_package_,
  345. file_->message_type(i),
  346. context, file_list, "OrBuilder",
  347. &MessageGenerator::GenerateInterface);
  348. GenerateSibling<MessageGenerator>(package_dir, java_package_,
  349. file_->message_type(i),
  350. context, file_list, "",
  351. &MessageGenerator::Generate);
  352. }
  353. if (HasGenericServices(file_)) {
  354. for (int i = 0; i < file_->service_count(); i++) {
  355. GenerateSibling<ServiceGenerator>(package_dir, java_package_,
  356. file_->service(i),
  357. context, file_list, "",
  358. &ServiceGenerator::Generate);
  359. }
  360. }
  361. }
  362. }
  363. bool FileGenerator::ShouldIncludeDependency(const FileDescriptor* descriptor) {
  364. return true;
  365. }
  366. } // namespace java
  367. } // namespace compiler
  368. } // namespace protobuf
  369. } // namespace google