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