PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/protobuf/src/google/protobuf/compiler/java/java_file.cc

http://decs.googlecode.com/
C++ | 369 lines | 250 code | 53 blank | 66 comment | 45 complexity | 837cafc4018ccf6ddb027896177fa245 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, LGPL-2.0
  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 (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_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. FileGenerator::~FileGenerator() {}
  80. bool FileGenerator::Validate(string* error) {
  81. // Check that no class name matches the file's class name. This is a common
  82. // problem that leads to Java compile errors that can be hard to understand.
  83. // It's especially bad when using the java_multiple_files, since we would
  84. // end up overwriting the outer class with one of the inner ones.
  85. bool found_conflict = false;
  86. for (int i = 0; i < file_->enum_type_count() && !found_conflict; i++) {
  87. if (file_->enum_type(i)->name() == classname_) {
  88. found_conflict = true;
  89. }
  90. }
  91. for (int i = 0; i < file_->message_type_count() && !found_conflict; i++) {
  92. if (file_->message_type(i)->name() == classname_) {
  93. found_conflict = true;
  94. }
  95. }
  96. for (int i = 0; i < file_->service_count() && !found_conflict; i++) {
  97. if (file_->service(i)->name() == classname_) {
  98. found_conflict = true;
  99. }
  100. }
  101. if (found_conflict) {
  102. error->assign(file_->name());
  103. error->append(
  104. ": Cannot generate Java output because the file's outer class name, \"");
  105. error->append(classname_);
  106. error->append(
  107. "\", matches the name of one of the types declared inside it. "
  108. "Please either rename the type or use the java_outer_classname "
  109. "option to specify a different outer class name for the .proto file.");
  110. return false;
  111. }
  112. return true;
  113. }
  114. void FileGenerator::Generate(io::Printer* printer) {
  115. // We don't import anything because we refer to all classes by their
  116. // fully-qualified names in the generated source.
  117. printer->Print(
  118. "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
  119. "\n");
  120. if (!java_package_.empty()) {
  121. printer->Print(
  122. "package $package$;\n"
  123. "\n",
  124. "package", java_package_);
  125. }
  126. printer->Print(
  127. "public final class $classname$ {\n"
  128. " private $classname$() {}\n",
  129. "classname", classname_);
  130. printer->Indent();
  131. // -----------------------------------------------------------------
  132. printer->Print(
  133. "public static void registerAllExtensions(\n"
  134. " com.google.protobuf.ExtensionRegistry registry) {\n");
  135. printer->Indent();
  136. for (int i = 0; i < file_->extension_count(); i++) {
  137. ExtensionGenerator(file_->extension(i)).GenerateRegistrationCode(printer);
  138. }
  139. for (int i = 0; i < file_->message_type_count(); i++) {
  140. MessageGenerator(file_->message_type(i))
  141. .GenerateExtensionRegistrationCode(printer);
  142. }
  143. printer->Outdent();
  144. printer->Print(
  145. "}\n");
  146. // -----------------------------------------------------------------
  147. if (!file_->options().java_multiple_files()) {
  148. for (int i = 0; i < file_->enum_type_count(); i++) {
  149. EnumGenerator(file_->enum_type(i)).Generate(printer);
  150. }
  151. for (int i = 0; i < file_->message_type_count(); i++) {
  152. MessageGenerator(file_->message_type(i)).Generate(printer);
  153. }
  154. for (int i = 0; i < file_->service_count(); i++) {
  155. ServiceGenerator(file_->service(i)).Generate(printer);
  156. }
  157. }
  158. // Extensions must be generated in the outer class since they are values,
  159. // not classes.
  160. for (int i = 0; i < file_->extension_count(); i++) {
  161. ExtensionGenerator(file_->extension(i)).Generate(printer);
  162. }
  163. // Static variables.
  164. for (int i = 0; i < file_->message_type_count(); i++) {
  165. // TODO(kenton): Reuse MessageGenerator objects?
  166. MessageGenerator(file_->message_type(i)).GenerateStaticVariables(printer);
  167. }
  168. printer->Print("\n");
  169. // -----------------------------------------------------------------
  170. // Embed the descriptor. We simply serialize the entire FileDescriptorProto
  171. // and embed it as a string literal, which is parsed and built into real
  172. // descriptors at initialization time. We unfortunately have to put it in
  173. // a string literal, not a byte array, because apparently using a literal
  174. // byte array causes the Java compiler to generate *instructions* to
  175. // initialize each and every byte of the array, e.g. as if you typed:
  176. // b[0] = 123; b[1] = 456; b[2] = 789;
  177. // This makes huge bytecode files and can easily hit the compiler's internal
  178. // code size limits (error "code to large"). String literals are apparently
  179. // embedded raw, which is what we want.
  180. FileDescriptorProto file_proto;
  181. file_->CopyTo(&file_proto);
  182. string file_data;
  183. file_proto.SerializeToString(&file_data);
  184. printer->Print(
  185. "public static com.google.protobuf.Descriptors.FileDescriptor\n"
  186. " getDescriptor() {\n"
  187. " return descriptor;\n"
  188. "}\n"
  189. "private static com.google.protobuf.Descriptors.FileDescriptor\n"
  190. " descriptor;\n"
  191. "static {\n"
  192. " java.lang.String descriptorData =\n");
  193. printer->Indent();
  194. printer->Indent();
  195. // Only write 40 bytes per line.
  196. static const int kBytesPerLine = 40;
  197. for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
  198. if (i > 0) printer->Print(" +\n");
  199. printer->Print("\"$data$\"",
  200. "data", CEscape(file_data.substr(i, kBytesPerLine)));
  201. }
  202. printer->Print(";\n");
  203. printer->Outdent();
  204. // -----------------------------------------------------------------
  205. // Create the InternalDescriptorAssigner.
  206. printer->Print(
  207. "com.google.protobuf.Descriptors.FileDescriptor."
  208. "InternalDescriptorAssigner assigner =\n"
  209. " new com.google.protobuf.Descriptors.FileDescriptor."
  210. "InternalDescriptorAssigner() {\n"
  211. " public com.google.protobuf.ExtensionRegistry assignDescriptors(\n"
  212. " com.google.protobuf.Descriptors.FileDescriptor root) {\n"
  213. " descriptor = root;\n");
  214. printer->Indent();
  215. printer->Indent();
  216. printer->Indent();
  217. for (int i = 0; i < file_->message_type_count(); i++) {
  218. // TODO(kenton): Reuse MessageGenerator objects?
  219. MessageGenerator(file_->message_type(i))
  220. .GenerateStaticVariableInitializers(printer);
  221. }
  222. for (int i = 0; i < file_->extension_count(); i++) {
  223. // TODO(kenton): Reuse ExtensionGenerator objects?
  224. ExtensionGenerator(file_->extension(i))
  225. .GenerateInitializationCode(printer);
  226. }
  227. if (UsesExtensions(file_proto)) {
  228. // Must construct an ExtensionRegistry containing all possible extensions
  229. // and return it.
  230. printer->Print(
  231. "com.google.protobuf.ExtensionRegistry registry =\n"
  232. " com.google.protobuf.ExtensionRegistry.newInstance();\n"
  233. "registerAllExtensions(registry);\n");
  234. for (int i = 0; i < file_->dependency_count(); i++) {
  235. printer->Print(
  236. "$dependency$.registerAllExtensions(registry);\n",
  237. "dependency", ClassName(file_->dependency(i)));
  238. }
  239. printer->Print(
  240. "return registry;\n");
  241. } else {
  242. printer->Print(
  243. "return null;\n");
  244. }
  245. printer->Outdent();
  246. printer->Outdent();
  247. printer->Outdent();
  248. printer->Print(
  249. " }\n"
  250. " };\n");
  251. // -----------------------------------------------------------------
  252. // Invoke internalBuildGeneratedFileFrom() to build the file.
  253. printer->Print(
  254. "com.google.protobuf.Descriptors.FileDescriptor\n"
  255. " .internalBuildGeneratedFileFrom(descriptorData,\n"
  256. " new com.google.protobuf.Descriptors.FileDescriptor[] {\n");
  257. for (int i = 0; i < file_->dependency_count(); i++) {
  258. printer->Print(
  259. " $dependency$.getDescriptor(),\n",
  260. "dependency", ClassName(file_->dependency(i)));
  261. }
  262. printer->Print(
  263. " }, assigner);\n");
  264. printer->Outdent();
  265. printer->Print(
  266. "}\n");
  267. printer->Outdent();
  268. printer->Print("}\n");
  269. }
  270. template<typename GeneratorClass, typename DescriptorClass>
  271. static void GenerateSibling(const string& package_dir,
  272. const string& java_package,
  273. const DescriptorClass* descriptor,
  274. OutputDirectory* output_directory,
  275. vector<string>* file_list) {
  276. string filename = package_dir + descriptor->name() + ".java";
  277. file_list->push_back(filename);
  278. scoped_ptr<io::ZeroCopyOutputStream> output(
  279. output_directory->Open(filename));
  280. io::Printer printer(output.get(), '$');
  281. printer.Print(
  282. "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
  283. "\n");
  284. if (!java_package.empty()) {
  285. printer.Print(
  286. "package $package$;\n"
  287. "\n",
  288. "package", java_package);
  289. }
  290. GeneratorClass(descriptor).Generate(&printer);
  291. }
  292. void FileGenerator::GenerateSiblings(const string& package_dir,
  293. OutputDirectory* output_directory,
  294. vector<string>* file_list) {
  295. if (file_->options().java_multiple_files()) {
  296. for (int i = 0; i < file_->enum_type_count(); i++) {
  297. GenerateSibling<EnumGenerator>(package_dir, java_package_,
  298. file_->enum_type(i),
  299. output_directory, file_list);
  300. }
  301. for (int i = 0; i < file_->message_type_count(); i++) {
  302. GenerateSibling<MessageGenerator>(package_dir, java_package_,
  303. file_->message_type(i),
  304. output_directory, file_list);
  305. }
  306. for (int i = 0; i < file_->service_count(); i++) {
  307. GenerateSibling<ServiceGenerator>(package_dir, java_package_,
  308. file_->service(i),
  309. output_directory, file_list);
  310. }
  311. }
  312. }
  313. } // namespace java
  314. } // namespace compiler
  315. } // namespace protobuf
  316. } // namespace google