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