javanano_file.cc revision 26266cd4660ffe1f3d6015b715713ee654c5b936
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
31// Author: kenton@google.com (Kenton Varda)
32//  Based on original Protocol Buffers design by
33//  Sanjay Ghemawat, Jeff Dean, and others.
34
35#include <iostream>
36
37#include <google/protobuf/compiler/javanano/javanano_file.h>
38#include <google/protobuf/compiler/javanano/javanano_enum.h>
39#include <google/protobuf/compiler/javanano/javanano_extension.h>
40#include <google/protobuf/compiler/javanano/javanano_helpers.h>
41#include <google/protobuf/compiler/javanano/javanano_message.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/stubs/strutil.h>
47
48namespace google {
49namespace protobuf {
50namespace compiler {
51namespace javanano {
52
53namespace {
54
55// Recursively searches the given message to see if it contains any extensions.
56bool UsesExtensions(const Message& message) {
57  const Reflection* reflection = message.GetReflection();
58
59  // We conservatively assume that unknown fields are extensions.
60  if (reflection->GetUnknownFields(message).field_count() > 0) return true;
61
62  vector<const FieldDescriptor*> fields;
63  reflection->ListFields(message, &fields);
64
65  for (int i = 0; i < fields.size(); i++) {
66    if (fields[i]->is_extension()) return true;
67
68    if (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
69      if (fields[i]->is_repeated()) {
70        int size = reflection->FieldSize(message, fields[i]);
71        for (int j = 0; j < size; j++) {
72          const Message& sub_message =
73            reflection->GetRepeatedMessage(message, fields[i], j);
74          if (UsesExtensions(sub_message)) return true;
75        }
76      } else {
77        const Message& sub_message = reflection->GetMessage(message, fields[i]);
78        if (UsesExtensions(sub_message)) return true;
79      }
80    }
81  }
82
83  return false;
84}
85
86}  // namespace
87
88FileGenerator::FileGenerator(const FileDescriptor* file, const Params& params)
89  : file_(file),
90    params_(params),
91    java_package_(FileJavaPackage(params, file)),
92    classname_(FileClassName(params, file)) {}
93
94FileGenerator::~FileGenerator() {}
95
96bool FileGenerator::Validate(string* error) {
97  // Check for extensions
98  FileDescriptorProto file_proto;
99  file_->CopyTo(&file_proto);
100  if (UsesExtensions(file_proto) && !params_.store_unknown_fields()) {
101    error->assign(file_->name());
102    error->append(
103        ": Java NANO_RUNTIME only supports extensions when the "
104        "'store_unknown_fields' generator option is 'true'.");
105    return false;
106  }
107
108  if (file_->service_count() != 0) {
109    error->assign(file_->name());
110    error->append(
111      ": Java NANO_RUNTIME does not support services\"");
112    return false;
113  }
114
115  if (!IsOuterClassNeeded(params_, file_)) {
116    return true;
117  }
118
119  // Check whether legacy javanano generator would omit the outer class.
120  if (!params_.has_java_outer_classname(file_->name())
121      && file_->message_type_count() == 1
122      && file_->enum_type_count() == 0 && file_->extension_count() == 0) {
123    cout << "INFO: " << file_->name() << ":" << endl;
124    cout << "Javanano generator has changed to align with java generator. "
125        "An outer class will be created for this file and the single message "
126        "in the file will become a nested class. Use java_multiple_files to "
127        "skip generating the outer class, or set an explicit "
128        "java_outer_classname to suppress this message." << endl;
129  }
130
131  // Check that no class name matches the file's class name.  This is a common
132  // problem that leads to Java compile errors that can be hard to understand.
133  // It's especially bad when using the java_multiple_files, since we would
134  // end up overwriting the outer class with one of the inner ones.
135  bool found_conflict = false;
136  for (int i = 0; !found_conflict && i < file_->message_type_count(); i++) {
137    if (file_->message_type(i)->name() == classname_) {
138      found_conflict = true;
139    }
140  }
141  if (params_.java_enum_style()) {
142    for (int i = 0; !found_conflict && i < file_->enum_type_count(); i++) {
143      if (file_->enum_type(i)->name() == classname_) {
144        found_conflict = true;
145      }
146    }
147  }
148  if (found_conflict) {
149    error->assign(file_->name());
150    error->append(
151      ": Cannot generate Java output because the file's outer class name, \"");
152    error->append(classname_);
153    error->append(
154      "\", matches the name of one of the types declared inside it.  "
155      "Please either rename the type or use the java_outer_classname "
156      "option to specify a different outer class name for the .proto file.");
157    return false;
158  }
159  return true;
160}
161
162void FileGenerator::Generate(io::Printer* printer) {
163  // We don't import anything because we refer to all classes by their
164  // fully-qualified names in the generated source.
165  printer->Print(
166    "// Generated by the protocol buffer compiler.  DO NOT EDIT!\n"
167    "\n");
168  if (!java_package_.empty()) {
169    printer->Print(
170      "package $package$;\n"
171      "\n",
172      "package", java_package_);
173  }
174
175  printer->Print(
176    "public final class $classname$ {\n"
177    "  private $classname$() {}\n",
178    "classname", classname_);
179  printer->Indent();
180
181  // -----------------------------------------------------------------
182
183  // Extensions.
184  for (int i = 0; i < file_->extension_count(); i++) {
185    ExtensionGenerator(file_->extension(i), params_).Generate(printer);
186  }
187
188  // Enums.
189  for (int i = 0; i < file_->enum_type_count(); i++) {
190    EnumGenerator(file_->enum_type(i), params_).Generate(printer);
191  }
192
193  // Messages.
194  if (!params_.java_multiple_files(file_->name())) {
195    for (int i = 0; i < file_->message_type_count(); i++) {
196      MessageGenerator(file_->message_type(i), params_).Generate(printer);
197    }
198  }
199
200  // Static variables.
201  for (int i = 0; i < file_->message_type_count(); i++) {
202    // TODO(kenton):  Reuse MessageGenerator objects?
203    MessageGenerator(file_->message_type(i), params_).GenerateStaticVariables(printer);
204  }
205
206  printer->Outdent();
207  printer->Print(
208    "}\n");
209}
210
211template<typename GeneratorClass, typename DescriptorClass>
212static void GenerateSibling(const string& package_dir,
213                            const string& java_package,
214                            const DescriptorClass* descriptor,
215                            OutputDirectory* output_directory,
216                            vector<string>* file_list,
217                            const Params& params) {
218  string filename = package_dir + descriptor->name() + ".java";
219  file_list->push_back(filename);
220
221  scoped_ptr<io::ZeroCopyOutputStream> output(
222    output_directory->Open(filename));
223  io::Printer printer(output.get(), '$');
224
225  printer.Print(
226    "// Generated by the protocol buffer compiler.  DO NOT EDIT!\n"
227    "\n");
228  if (!java_package.empty()) {
229    printer.Print(
230      "package $package$;\n"
231      "\n",
232      "package", java_package);
233  }
234
235  GeneratorClass(descriptor, params).Generate(&printer);
236}
237
238void FileGenerator::GenerateSiblings(const string& package_dir,
239                                     OutputDirectory* output_directory,
240                                     vector<string>* file_list) {
241  if (params_.java_multiple_files(file_->name())) {
242    for (int i = 0; i < file_->message_type_count(); i++) {
243      GenerateSibling<MessageGenerator>(package_dir, java_package_,
244                                        file_->message_type(i),
245                                        output_directory, file_list, params_);
246    }
247
248    if (params_.java_enum_style()) {
249      for (int i = 0; i < file_->enum_type_count(); i++) {
250        GenerateSibling<EnumGenerator>(package_dir, java_package_,
251                                       file_->enum_type(i),
252                                       output_directory, file_list, params_);
253      }
254    }
255  }
256}
257
258}  // namespace javanano
259}  // namespace compiler
260}  // namespace protobuf
261}  // namespace google
262