• 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 // Helper functions for generating ObjectiveC code.
32 
33 #ifndef GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__
34 #define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__
35 
36 #include <string>
37 #include <vector>
38 
39 #include <google/protobuf/descriptor.h>
40 #include <google/protobuf/descriptor.pb.h>
41 
42 #include <google/protobuf/port_def.inc>
43 
44 namespace google {
45 namespace protobuf {
46 namespace compiler {
47 namespace objectivec {
48 
49 // Generator options (see objectivec_generator.cc for a description of each):
50 struct Options {
51   Options();
52   std::string expected_prefixes_path;
53   std::vector<std::string> expected_prefixes_suppressions;
54   std::string generate_for_named_framework;
55   std::string named_framework_to_proto_path_mappings_path;
56   std::string runtime_import_prefix;
57 };
58 
59 // Escape C++ trigraphs by escaping question marks to "\?".
60 std::string PROTOC_EXPORT EscapeTrigraphs(const std::string& to_escape);
61 
62 // Strips ".proto" or ".protodevel" from the end of a filename.
63 std::string PROTOC_EXPORT StripProto(const std::string& filename);
64 
65 // Remove white space from either end of a StringPiece.
66 void PROTOC_EXPORT TrimWhitespace(StringPiece* input);
67 
68 // Returns true if the name requires a ns_returns_not_retained attribute applied
69 // to it.
70 bool PROTOC_EXPORT IsRetainedName(const std::string& name);
71 
72 // Returns true if the name starts with "init" and will need to have special
73 // handling under ARC.
74 bool PROTOC_EXPORT IsInitName(const std::string& name);
75 
76 // Gets the objc_class_prefix.
77 std::string PROTOC_EXPORT FileClassPrefix(const FileDescriptor* file);
78 
79 // Gets the path of the file we're going to generate (sans the .pb.h
80 // extension).  The path will be dependent on the objectivec package
81 // declared in the proto package.
82 std::string PROTOC_EXPORT FilePath(const FileDescriptor* file);
83 
84 // Just like FilePath(), but without the directory part.
85 std::string PROTOC_EXPORT FilePathBasename(const FileDescriptor* file);
86 
87 // Gets the name of the root class we'll generate in the file.  This class
88 // is not meant for external consumption, but instead contains helpers that
89 // the rest of the classes need
90 std::string PROTOC_EXPORT FileClassName(const FileDescriptor* file);
91 
92 // These return the fully-qualified class name corresponding to the given
93 // descriptor.
94 std::string PROTOC_EXPORT ClassName(const Descriptor* descriptor);
95 std::string PROTOC_EXPORT ClassName(const Descriptor* descriptor,
96                                std::string* out_suffix_added);
97 std::string PROTOC_EXPORT EnumName(const EnumDescriptor* descriptor);
98 
99 // Returns the fully-qualified name of the enum value corresponding to the
100 // the descriptor.
101 std::string PROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor);
102 
103 // Returns the name of the enum value corresponding to the descriptor.
104 std::string PROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor);
105 
106 // Reverse what an enum does.
107 std::string PROTOC_EXPORT UnCamelCaseEnumShortName(const std::string& name);
108 
109 // Returns the name to use for the extension (used as the method off the file's
110 // Root class).
111 std::string PROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor);
112 
113 // Returns the transformed field name.
114 std::string PROTOC_EXPORT FieldName(const FieldDescriptor* field);
115 std::string PROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field);
116 
117 // Returns the transformed oneof name.
118 std::string PROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor);
119 std::string PROTOC_EXPORT OneofName(const OneofDescriptor* descriptor);
120 std::string PROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor);
121 
122 // Returns a symbol that can be used in C code to refer to an Objective C
123 // class without initializing the class.
124 std::string PROTOC_EXPORT ObjCClass(const std::string& class_name);
125 
126 // Declares an Objective C class without initializing the class so that it can
127 // be refrerred to by ObjCClass.
128 std::string PROTOC_EXPORT ObjCClassDeclaration(const std::string& class_name);
129 
HasPreservingUnknownEnumSemantics(const FileDescriptor * file)130 inline bool HasPreservingUnknownEnumSemantics(const FileDescriptor* file) {
131   return file->syntax() == FileDescriptor::SYNTAX_PROTO3;
132 }
133 
IsMapEntryMessage(const Descriptor * descriptor)134 inline bool IsMapEntryMessage(const Descriptor* descriptor) {
135   return descriptor->options().map_entry();
136 }
137 
138 // Reverse of the above.
139 std::string PROTOC_EXPORT UnCamelCaseFieldName(const std::string& name,
140                                                const FieldDescriptor* field);
141 
142 enum ObjectiveCType {
143   OBJECTIVECTYPE_INT32,
144   OBJECTIVECTYPE_UINT32,
145   OBJECTIVECTYPE_INT64,
146   OBJECTIVECTYPE_UINT64,
147   OBJECTIVECTYPE_FLOAT,
148   OBJECTIVECTYPE_DOUBLE,
149   OBJECTIVECTYPE_BOOLEAN,
150   OBJECTIVECTYPE_STRING,
151   OBJECTIVECTYPE_DATA,
152   OBJECTIVECTYPE_ENUM,
153   OBJECTIVECTYPE_MESSAGE
154 };
155 
156 enum FlagType {
157   FLAGTYPE_DESCRIPTOR_INITIALIZATION,
158   FLAGTYPE_EXTENSION,
159   FLAGTYPE_FIELD
160 };
161 
162 template <class TDescriptor>
163 std::string GetOptionalDeprecatedAttribute(const TDescriptor* descriptor,
164                                            const FileDescriptor* file = NULL,
165                                            bool preSpace = true,
166                                            bool postNewline = false) {
167   bool isDeprecated = descriptor->options().deprecated();
168   // The file is only passed when checking Messages & Enums, so those types
169   // get tagged. At the moment, it doesn't seem to make sense to tag every
170   // field or enum value with when the file is deprecated.
171   bool isFileLevelDeprecation = false;
172   if (!isDeprecated && file) {
173     isFileLevelDeprecation = file->options().deprecated();
174     isDeprecated = isFileLevelDeprecation;
175   }
176   if (isDeprecated) {
177     std::string message;
178     const FileDescriptor* sourceFile = descriptor->file();
179     if (isFileLevelDeprecation) {
180       message = sourceFile->name() + " is deprecated.";
181     } else {
182       message = descriptor->full_name() + " is deprecated (see " +
183                 sourceFile->name() + ").";
184     }
185 
186     std::string result = std::string("GPB_DEPRECATED_MSG(\"") + message + "\")";
187     if (preSpace) {
188       result.insert(0, " ");
189     }
190     if (postNewline) {
191       result.append("\n");
192     }
193     return result;
194   } else {
195     return "";
196   }
197 }
198 
199 std::string PROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field);
200 
201 ObjectiveCType PROTOC_EXPORT
202 GetObjectiveCType(FieldDescriptor::Type field_type);
203 
GetObjectiveCType(const FieldDescriptor * field)204 inline ObjectiveCType GetObjectiveCType(const FieldDescriptor* field) {
205   return GetObjectiveCType(field->type());
206 }
207 
208 bool PROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field);
209 bool PROTOC_EXPORT IsReferenceType(const FieldDescriptor* field);
210 
211 std::string PROTOC_EXPORT
212 GPBGenericValueFieldName(const FieldDescriptor* field);
213 std::string PROTOC_EXPORT DefaultValue(const FieldDescriptor* field);
214 bool PROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field);
215 
216 std::string PROTOC_EXPORT
217 BuildFlagsString(const FlagType type, const std::vector<std::string>& strings);
218 
219 // Builds HeaderDoc/appledoc style comments out of the comments in the .proto
220 // file.
221 std::string PROTOC_EXPORT BuildCommentsString(const SourceLocation& location,
222                                               bool prefer_single_line);
223 
224 // The name the commonly used by the library when built as a framework.
225 // This lines up to the name used in the CocoaPod.
226 extern PROTOC_EXPORT const char* const ProtobufLibraryFrameworkName;
227 // Returns the CPP symbol name to use as the gate for framework style imports
228 // for the given framework name to use.
229 std::string PROTOC_EXPORT
230 ProtobufFrameworkImportSymbol(const std::string& framework_name);
231 
232 // Checks if the file is one of the proto's bundled with the library.
233 bool PROTOC_EXPORT
234 IsProtobufLibraryBundledProtoFile(const FileDescriptor* file);
235 
236 // Checks the prefix for the given files and outputs any warnings as needed. If
237 // there are flat out errors, then out_error is filled in with the first error
238 // and the result is false.
239 bool PROTOC_EXPORT ValidateObjCClassPrefixes(
240     const std::vector<const FileDescriptor*>& files,
241     const Options& generation_options, std::string* out_error);
242 
243 // Generate decode data needed for ObjC's GPBDecodeTextFormatName() to transform
244 // the input into the expected output.
245 class PROTOC_EXPORT TextFormatDecodeData {
246  public:
247   TextFormatDecodeData();
248   ~TextFormatDecodeData();
249 
250   TextFormatDecodeData(const TextFormatDecodeData&) = delete;
251   TextFormatDecodeData& operator=(const TextFormatDecodeData&) = delete;
252 
253   void AddString(int32 key, const std::string& input_for_decode,
254                  const std::string& desired_output);
num_entries()255   size_t num_entries() const { return entries_.size(); }
256   std::string Data() const;
257 
258   static std::string DecodeDataForString(const std::string& input_for_decode,
259                                          const std::string& desired_output);
260 
261  private:
262   typedef std::pair<int32, std::string> DataEntry;
263   std::vector<DataEntry> entries_;
264 };
265 
266 // Helper for parsing simple files.
267 class PROTOC_EXPORT LineConsumer {
268  public:
269   LineConsumer();
270   virtual ~LineConsumer();
271   virtual bool ConsumeLine(const StringPiece& line, std::string* out_error) = 0;
272 };
273 
274 bool PROTOC_EXPORT ParseSimpleFile(const std::string& path,
275                                    LineConsumer* line_consumer,
276                                    std::string* out_error);
277 
278 // Helper class for parsing framework import mappings and generating
279 // import statements.
280 class PROTOC_EXPORT ImportWriter {
281  public:
282   ImportWriter(const std::string& generate_for_named_framework,
283                const std::string& named_framework_to_proto_path_mappings_path,
284                const std::string& runtime_import_prefix,
285                bool include_wkt_imports);
286   ~ImportWriter();
287 
288   void AddFile(const FileDescriptor* file, const std::string& header_extension);
289   void Print(io::Printer *printer) const;
290 
291   static void PrintRuntimeImports(io::Printer *printer,
292                                   const std::vector<std::string>& header_to_import,
293                                   const std::string& runtime_import_prefix,
294                                   bool default_cpp_symbol = false);
295 
296  private:
297   class ProtoFrameworkCollector : public LineConsumer {
298    public:
ProtoFrameworkCollector(std::map<std::string,std::string> * inout_proto_file_to_framework_name)299     ProtoFrameworkCollector(std::map<std::string, std::string>* inout_proto_file_to_framework_name)
300         : map_(inout_proto_file_to_framework_name) {}
301 
302     virtual bool ConsumeLine(const StringPiece& line, std::string* out_error);
303 
304    private:
305     std::map<std::string, std::string>* map_;
306   };
307 
308   void ParseFrameworkMappings();
309 
310   const std::string generate_for_named_framework_;
311   const std::string named_framework_to_proto_path_mappings_path_;
312   const std::string runtime_import_prefix_;
313   const bool include_wkt_imports_;
314   std::map<std::string, std::string> proto_file_to_framework_name_;
315   bool need_to_parse_mapping_file_;
316 
317   std::vector<std::string> protobuf_imports_;
318   std::vector<std::string> other_framework_imports_;
319   std::vector<std::string> other_imports_;
320 };
321 
322 }  // namespace objectivec
323 }  // namespace compiler
324 }  // namespace protobuf
325 }  // namespace google
326 
327 #include <google/protobuf/port_undef.inc>
328 
329 #endif  // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__
330