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