• 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 #include <memory>
32 #ifndef _SHARED_PTR_H
33 #include <google/protobuf/stubs/shared_ptr.h>
34 #endif
35 
36 #include <google/protobuf/compiler/cpp/cpp_helpers.h>
37 #include <google/protobuf/compiler/cpp/cpp_generator.h>
38 #include <google/protobuf/compiler/command_line_interface.h>
39 #include <google/protobuf/io/zero_copy_stream.h>
40 #include <google/protobuf/io/zero_copy_stream_impl_lite.h>
41 #include <google/protobuf/io/printer.h>
42 #include <google/protobuf/descriptor.pb.h>
43 
44 #include <google/protobuf/testing/file.h>
45 #include <google/protobuf/testing/file.h>
46 #include <google/protobuf/testing/googletest.h>
47 #include <gtest/gtest.h>
48 
49 namespace google {
50 namespace protobuf {
51 namespace compiler {
52 namespace cpp {
53 namespace {
54 
55 // A CodeGenerator that captures the FileDescriptor it's passed as a
56 // FileDescriptorProto.
57 class DescriptorCapturingGenerator : public CodeGenerator {
58  public:
59   // Does not own file; file must outlive the Generator.
DescriptorCapturingGenerator(FileDescriptorProto * file)60   explicit DescriptorCapturingGenerator(FileDescriptorProto* file)
61       : file_(file) {}
62 
Generate(const FileDescriptor * file,const string & parameter,GeneratorContext * context,string * error) const63   virtual bool Generate(const FileDescriptor* file, const string& parameter,
64                         GeneratorContext* context, string* error) const {
65     file->CopyTo(file_);
66     return true;
67   }
68 
69  private:
70   FileDescriptorProto* file_;
71 };
72 
73 class CppMetadataTest : public ::testing::Test {
74  public:
75   // Adds a file with name `filename` and content `data`.
AddFile(const string & filename,const string & data)76   void AddFile(const string& filename, const string& data) {
77     GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/" + filename, data,
78                                true));
79   }
80 
81   // Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output
82   // code from the previously added file with name `filename`. Returns true on
83   // success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to
84   // pb_h and pb_h_info respecfively); similarly for proto_h and proto_h_info.
CaptureMetadata(const string & filename,FileDescriptorProto * file,string * pb_h,GeneratedCodeInfo * pb_h_info,string * proto_h,GeneratedCodeInfo * proto_h_info,string * pb_cc)85   bool CaptureMetadata(const string& filename, FileDescriptorProto* file,
86                        string* pb_h, GeneratedCodeInfo* pb_h_info,
87                        string* proto_h, GeneratedCodeInfo* proto_h_info,
88                        string* pb_cc) {
89     google::protobuf::compiler::CommandLineInterface cli;
90     cli.SetInputsAreProtoPathRelative(true);
91 
92     CppGenerator cpp_generator;
93     DescriptorCapturingGenerator capturing_generator(file);
94     cli.RegisterGenerator("--cpp_out", &cpp_generator, "");
95     cli.RegisterGenerator("--capture_out", &capturing_generator, "");
96 
97     string proto_path = "-I" + TestTempDir();
98     string cpp_out =
99         "--cpp_out=annotate_headers=true,"
100         "annotation_pragma_name=pragma_name,"
101         "annotation_guard_name=guard_name:" +
102         TestTempDir();
103     string capture_out = "--capture_out=" + TestTempDir();
104 
105     const char* argv[] = {"protoc", proto_path.c_str(), cpp_out.c_str(),
106                           capture_out.c_str(), filename.c_str()};
107 
108     if (cli.Run(5, argv) != 0) {
109       return false;
110     }
111 
112     string output_base = TestTempDir() + "/" + StripProto(filename);
113 
114     if (pb_cc != NULL) {
115       GOOGLE_CHECK_OK(
116           File::GetContents(output_base + ".pb.cc", pb_cc, true));
117     }
118 
119     if (pb_h != NULL && pb_h_info != NULL) {
120       GOOGLE_CHECK_OK(
121           File::GetContents(output_base + ".pb.h", pb_h, true));
122       if (!DecodeMetadata(output_base + ".pb.h.meta", pb_h_info)) {
123         return false;
124       }
125     }
126 
127     if (proto_h != NULL && proto_h_info != NULL) {
128       GOOGLE_CHECK_OK(File::GetContents(output_base + ".proto.h", proto_h,
129                                  true));
130       if (!DecodeMetadata(output_base + ".proto.h.meta", proto_h_info)) {
131         return false;
132       }
133     }
134 
135     return true;
136   }
137 
138  private:
139   // Decodes GeneratedCodeInfo stored in path and copies it to info.
140   // Returns true on success.
DecodeMetadata(const string & path,GeneratedCodeInfo * info)141   bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) {
142     string data;
143     GOOGLE_CHECK_OK(File::GetContents(path, &data, true));
144     io::ArrayInputStream input(data.data(), data.size());
145     return info->ParseFromZeroCopyStream(&input);
146   }
147 };
148 
149 const char kSmallTestFile[] =
150     "syntax = \"proto2\";\n"
151     "package foo;\n"
152     "enum Enum { VALUE = 0; }\n"
153     "message Message { }\n";
154 
155 // Finds the Annotation for a given source file and path (or returns null if it
156 // couldn't).
FindAnnotationOnPath(const GeneratedCodeInfo & info,const string & source_file,const vector<int> & path)157 const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
158     const GeneratedCodeInfo& info, const string& source_file,
159     const vector<int>& path) {
160   for (int i = 0; i < info.annotation_size(); ++i) {
161     const GeneratedCodeInfo::Annotation* annotation = &info.annotation(i);
162     if (annotation->source_file() != source_file ||
163         annotation->path_size() != path.size()) {
164       continue;
165     }
166     int node = 0;
167     for (; node < path.size(); ++node) {
168       if (annotation->path(node) != path[node]) {
169         break;
170       }
171     }
172     if (node == path.size()) {
173       return annotation;
174     }
175   }
176   return NULL;
177 }
178 
179 // Returns true if the provided annotation covers a given substring in
180 // file_content.
AnnotationMatchesSubstring(const string & file_content,const GeneratedCodeInfo::Annotation * annotation,const string & expected_text)181 bool AnnotationMatchesSubstring(const string& file_content,
182                                 const GeneratedCodeInfo::Annotation* annotation,
183                                 const string& expected_text) {
184   uint32 begin = annotation->begin();
185   uint32 end = annotation->end();
186   if (end < begin || end > file_content.size()) {
187     return false;
188   }
189   return file_content.substr(begin, end - begin) == expected_text;
190 }
191 
TEST_F(CppMetadataTest,CapturesEnumNames)192 TEST_F(CppMetadataTest, CapturesEnumNames) {
193   FileDescriptorProto file;
194   GeneratedCodeInfo info;
195   string pb_h;
196   AddFile("test.proto", kSmallTestFile);
197   EXPECT_TRUE(
198       CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
199   EXPECT_EQ("Enum", file.enum_type(0).name());
200   vector<int> enum_path;
201   enum_path.push_back(FileDescriptorProto::kEnumTypeFieldNumber);
202   enum_path.push_back(0);
203   const GeneratedCodeInfo::Annotation* enum_annotation =
204       FindAnnotationOnPath(info, "test.proto", enum_path);
205   EXPECT_TRUE(NULL != enum_annotation);
206   EXPECT_TRUE(AnnotationMatchesSubstring(pb_h, enum_annotation, "Enum"));
207 }
208 
TEST_F(CppMetadataTest,AddsPragma)209 TEST_F(CppMetadataTest, AddsPragma) {
210   FileDescriptorProto file;
211   GeneratedCodeInfo info;
212   string pb_h;
213   AddFile("test.proto", kSmallTestFile);
214   EXPECT_TRUE(
215       CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
216   EXPECT_TRUE(pb_h.find("#ifdef guard_name") != string::npos);
217   EXPECT_TRUE(pb_h.find("#pragma pragma_name \"test.pb.h.meta\"") !=
218               string::npos);
219 }
220 
TEST_F(CppMetadataTest,CapturesMessageNames)221 TEST_F(CppMetadataTest, CapturesMessageNames) {
222   FileDescriptorProto file;
223   GeneratedCodeInfo info;
224   string pb_h;
225   AddFile("test.proto", kSmallTestFile);
226   EXPECT_TRUE(
227       CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
228   EXPECT_EQ("Message", file.message_type(0).name());
229   vector<int> message_path;
230   message_path.push_back(FileDescriptorProto::kMessageTypeFieldNumber);
231   message_path.push_back(0);
232   const GeneratedCodeInfo::Annotation* message_annotation =
233       FindAnnotationOnPath(info, "test.proto", message_path);
234   EXPECT_TRUE(NULL != message_annotation);
235   EXPECT_TRUE(AnnotationMatchesSubstring(pb_h, message_annotation, "Message"));
236 }
237 
238 }  // namespace
239 }  // namespace cpp
240 }  // namespace compiler
241 }  // namespace protobuf
242 }  // namespace google
243