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 
31 // Author: xiaofeng@google.com (Feng Xiao)
32 
33 #include <google/protobuf/compiler/java/java_shared_code_generator.h>
34 
35 #include <memory>
36 
37 #include <google/protobuf/compiler/java/java_helpers.h>
38 #include <google/protobuf/compiler/java/java_name_resolver.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/descriptor.h>
44 #include <google/protobuf/stubs/strutil.h>
45 
46 namespace google {
47 namespace protobuf {
48 namespace compiler {
49 namespace java {
50 
SharedCodeGenerator(const FileDescriptor * file)51 SharedCodeGenerator::SharedCodeGenerator(const FileDescriptor* file)
52   : name_resolver_(new ClassNameResolver), file_(file) {
53 }
54 
~SharedCodeGenerator()55 SharedCodeGenerator::~SharedCodeGenerator() {
56 }
57 
Generate(GeneratorContext * context,vector<string> * file_list)58 void SharedCodeGenerator::Generate(GeneratorContext* context,
59                                    vector<string>* file_list) {
60   string java_package = FileJavaPackage(file_);
61   string package_dir = JavaPackageToDir(java_package);
62 
63   if (HasDescriptorMethods(file_)) {
64     // Generate descriptors.
65     string classname = name_resolver_->GetDescriptorClassName(file_);
66     string filename = package_dir + classname + ".java";
67     file_list->push_back(filename);
68     scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
69     scoped_ptr<io::Printer> printer(new io::Printer(output.get(), '$'));
70 
71     printer->Print(
72       "// Generated by the protocol buffer compiler.  DO NOT EDIT!\n"
73       "// source: $filename$\n"
74       "\n",
75       "filename", file_->name());
76     if (!java_package.empty()) {
77       printer->Print(
78         "package $package$;\n"
79         "\n",
80         "package", java_package);
81     }
82     printer->Print(
83       "public final class $classname$ {\n"
84       "  public static com.google.protobuf.Descriptors.FileDescriptor\n"
85       "      descriptor;\n"
86       "  static {\n",
87       "classname", classname);
88     printer->Indent();
89     printer->Indent();
90     GenerateDescriptors(printer.get());
91     printer->Outdent();
92     printer->Outdent();
93     printer->Print(
94       "  }\n"
95       "}\n");
96 
97     printer.reset();
98     output.reset();
99   }
100 }
101 
102 
GenerateDescriptors(io::Printer * printer)103 void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
104   // Embed the descriptor.  We simply serialize the entire FileDescriptorProto
105   // and embed it as a string literal, which is parsed and built into real
106   // descriptors at initialization time.  We unfortunately have to put it in
107   // a string literal, not a byte array, because apparently using a literal
108   // byte array causes the Java compiler to generate *instructions* to
109   // initialize each and every byte of the array, e.g. as if you typed:
110   //   b[0] = 123; b[1] = 456; b[2] = 789;
111   // This makes huge bytecode files and can easily hit the compiler's internal
112   // code size limits (error "code to large").  String literals are apparently
113   // embedded raw, which is what we want.
114   FileDescriptorProto file_proto;
115   file_->CopyTo(&file_proto);
116 
117 
118   string file_data;
119   file_proto.SerializeToString(&file_data);
120 
121   printer->Print(
122     "java.lang.String[] descriptorData = {\n");
123   printer->Indent();
124 
125   // Only write 40 bytes per line.
126   static const int kBytesPerLine = 40;
127   for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
128     if (i > 0) {
129       // Every 400 lines, start a new string literal, in order to avoid the
130       // 64k length limit.
131       if (i % 400 == 0) {
132         printer->Print(",\n");
133       } else {
134         printer->Print(" +\n");
135       }
136     }
137     printer->Print("\"$data$\"",
138       "data", CEscape(file_data.substr(i, kBytesPerLine)));
139   }
140 
141   printer->Outdent();
142   printer->Print("\n};\n");
143 
144   // -----------------------------------------------------------------
145   // Create the InternalDescriptorAssigner.
146 
147   printer->Print(
148     "com.google.protobuf.Descriptors.FileDescriptor."
149     "InternalDescriptorAssigner assigner =\n"
150     "    new com.google.protobuf.Descriptors.FileDescriptor."
151     "    InternalDescriptorAssigner() {\n"
152     "      public com.google.protobuf.ExtensionRegistry assignDescriptors(\n"
153     "          com.google.protobuf.Descriptors.FileDescriptor root) {\n"
154     "        descriptor = root;\n"
155     // Custom options will be handled when immutable messages' outer class is
156     // loaded. Here we just return null and let custom options be unknown
157     // fields.
158     "        return null;\n"
159     "      }\n"
160     "    };\n");
161 
162   // -----------------------------------------------------------------
163   // Find out all dependencies.
164   vector<pair<string, string> > dependencies;
165   for (int i = 0; i < file_->dependency_count(); i++) {
166     if (ShouldIncludeDependency(file_->dependency(i))) {
167       string filename = file_->dependency(i)->name();
168       string classname = FileJavaPackage(file_->dependency(i)) + "." +
169                          name_resolver_->GetDescriptorClassName(
170                              file_->dependency(i));
171       dependencies.push_back(make_pair(filename, classname));
172     }
173   }
174 
175   // -----------------------------------------------------------------
176   // Invoke internalBuildGeneratedFileFrom() to build the file.
177   printer->Print(
178     "com.google.protobuf.Descriptors.FileDescriptor\n"
179     "  .internalBuildGeneratedFileFrom(descriptorData,\n"
180     "    new com.google.protobuf.Descriptors.FileDescriptor[] {\n");
181 
182   for (int i = 0; i < dependencies.size(); i++) {
183     const string& dependency = dependencies[i].second;
184     printer->Print(
185         "      $dependency$.getDescriptor(),\n",
186         "dependency", dependency);
187   }
188 
189   printer->Print(
190     "    }, assigner);\n");
191 }
192 
ShouldIncludeDependency(const FileDescriptor * descriptor)193 bool SharedCodeGenerator::ShouldIncludeDependency(
194     const FileDescriptor* descriptor) {
195   return true;
196 }
197 
198 }  // namespace java
199 }  // namespace compiler
200 }  // namespace protobuf
201 }  // namespace google
202