[C++] Refactor to conform to Google C++ style guide (#5608)
[platform/upstream/flatbuffers.git] / src / code_generators.cpp
1 /*
2  * Copyright 2016 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "flatbuffers/code_generators.h"
18
19 #include <assert.h>
20
21 #include <cmath>
22
23 #include "flatbuffers/base.h"
24 #include "flatbuffers/util.h"
25
26 #if defined(_MSC_VER)
27 #  pragma warning(push)
28 #  pragma warning(disable : 4127)  // C4127: conditional expression is constant
29 #endif
30
31 namespace flatbuffers {
32
33 void CodeWriter::operator+=(std::string text) {
34   if (!ignore_ident_ && !text.empty()) AppendIdent(stream_);
35
36   while (true) {
37     auto begin = text.find("{{");
38     if (begin == std::string::npos) { break; }
39
40     auto end = text.find("}}");
41     if (end == std::string::npos || end < begin) { break; }
42
43     // Write all the text before the first {{ into the stream.
44     stream_.write(text.c_str(), begin);
45
46     // The key is between the {{ and }}.
47     const std::string key = text.substr(begin + 2, end - begin - 2);
48
49     // Find the value associated with the key.  If it exists, write the
50     // value into the stream, otherwise write the key itself into the stream.
51     auto iter = value_map_.find(key);
52     if (iter != value_map_.end()) {
53       const std::string &value = iter->second;
54       stream_ << value;
55     } else {
56       FLATBUFFERS_ASSERT(false && "could not find key");
57       stream_ << key;
58     }
59
60     // Update the text to everything after the }}.
61     text = text.substr(end + 2);
62   }
63   if (!text.empty() && string_back(text) == '\\') {
64     text.pop_back();
65     ignore_ident_ = true;
66     stream_ << text;
67   } else {
68     ignore_ident_ = false;
69     stream_ << text << std::endl;
70   }
71 }
72
73 void CodeWriter::AppendIdent(std::stringstream &stream) {
74   int lvl = cur_ident_lvl_;
75   while (lvl--) {
76     stream.write(pad_.c_str(), static_cast<std::streamsize>(pad_.size()));
77   }
78 }
79
80 const char *BaseGenerator::FlatBuffersGeneratedWarning() {
81   return "automatically generated by the FlatBuffers compiler,"
82          " do not modify";
83 }
84
85 std::string BaseGenerator::NamespaceDir(const Parser &parser,
86                                         const std::string &path,
87                                         const Namespace &ns) {
88   EnsureDirExists(path);
89   if (parser.opts.one_file) return path;
90   std::string namespace_dir = path;  // Either empty or ends in separator.
91   auto &namespaces = ns.components;
92   for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
93     namespace_dir += *it + kPathSeparator;
94     EnsureDirExists(namespace_dir);
95   }
96   return namespace_dir;
97 }
98
99 std::string BaseGenerator::NamespaceDir(const Namespace &ns) const {
100   return BaseGenerator::NamespaceDir(parser_, path_, ns);
101 }
102
103 std::string BaseGenerator::FullNamespace(const char *separator,
104                                          const Namespace &ns) {
105   std::string namespace_name;
106   auto &namespaces = ns.components;
107   for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
108     if (namespace_name.length()) namespace_name += separator;
109     namespace_name += *it;
110   }
111   return namespace_name;
112 }
113
114 std::string BaseGenerator::LastNamespacePart(const Namespace &ns) {
115   if (!ns.components.empty())
116     return ns.components.back();
117   else
118     return std::string("");
119 }
120
121 // Ensure that a type is prefixed with its namespace.
122 std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
123                                            const std::string &name) const {
124   std::string qualified_name = qualifying_start_;
125   for (auto it = ns->components.begin(); it != ns->components.end(); ++it)
126     qualified_name += *it + qualifying_separator_;
127   return qualified_name + name;
128 }
129
130 std::string BaseGenerator::WrapInNameSpace(const Definition &def) const {
131   return WrapInNameSpace(def.defined_namespace, def.name);
132 }
133
134 std::string BaseGenerator::GetNameSpace(const Definition &def) const {
135   const Namespace *ns = def.defined_namespace;
136   if (CurrentNameSpace() == ns) return "";
137   std::string qualified_name = qualifying_start_;
138   for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
139     qualified_name += *it;
140     if ((it + 1) != ns->components.end()) {
141       qualified_name += qualifying_separator_;
142     }
143   }
144
145   return qualified_name;
146 }
147
148 // Generate a documentation comment, if available.
149 void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
150                 const CommentConfig *config, const char *prefix) {
151   if (dc.begin() == dc.end()) {
152     // Don't output empty comment blocks with 0 lines of comment content.
153     return;
154   }
155
156   std::string &code = *code_ptr;
157   if (config != nullptr && config->first_line != nullptr) {
158     code += std::string(prefix) + std::string(config->first_line) + "\n";
159   }
160   std::string line_prefix =
161       std::string(prefix) +
162       ((config != nullptr && config->content_line_prefix != nullptr)
163            ? config->content_line_prefix
164            : "///");
165   for (auto it = dc.begin(); it != dc.end(); ++it) {
166     code += line_prefix + *it + "\n";
167   }
168   if (config != nullptr && config->last_line != nullptr) {
169     code += std::string(prefix) + std::string(config->last_line) + "\n";
170   }
171 }
172
173 template<typename T>
174 std::string FloatConstantGenerator::GenFloatConstantImpl(
175     const FieldDef &field) const {
176   const auto &constant = field.value.constant;
177   T v;
178   auto done = StringToNumber(constant.c_str(), &v);
179   FLATBUFFERS_ASSERT(done);
180   if (done) {
181 #if (!defined(_MSC_VER) || (_MSC_VER >= 1800))
182     if (std::isnan(v)) return NaN(v);
183     if (std::isinf(v)) return Inf(v);
184 #endif
185     return Value(v, constant);
186   }
187   return "#";  // compile time error
188 }
189
190 std::string FloatConstantGenerator::GenFloatConstant(
191     const FieldDef &field) const {
192   switch (field.value.type.base_type) {
193     case BASE_TYPE_FLOAT: return GenFloatConstantImpl<float>(field);
194     case BASE_TYPE_DOUBLE: return GenFloatConstantImpl<double>(field);
195     default: {
196       FLATBUFFERS_ASSERT(false);
197       return "INVALID_BASE_TYPE";
198     }
199   };
200 }
201
202 TypedFloatConstantGenerator::TypedFloatConstantGenerator(
203     const char *double_prefix, const char *single_prefix,
204     const char *nan_number, const char *pos_inf_number,
205     const char *neg_inf_number)
206     : double_prefix_(double_prefix),
207       single_prefix_(single_prefix),
208       nan_number_(nan_number),
209       pos_inf_number_(pos_inf_number),
210       neg_inf_number_(neg_inf_number) {}
211
212 std::string TypedFloatConstantGenerator::MakeNaN(
213     const std::string &prefix) const {
214   return prefix + nan_number_;
215 }
216 std::string TypedFloatConstantGenerator::MakeInf(
217     bool neg, const std::string &prefix) const {
218   if (neg)
219     return !neg_inf_number_.empty() ? (prefix + neg_inf_number_)
220                                     : ("-" + prefix + pos_inf_number_);
221   else
222     return prefix + pos_inf_number_;
223 }
224
225 std::string TypedFloatConstantGenerator::Value(double v,
226                                                const std::string &src) const {
227   (void)v;
228   return src;
229 }
230
231 std::string TypedFloatConstantGenerator::Inf(double v) const {
232   return MakeInf(v < 0, double_prefix_);
233 }
234
235 std::string TypedFloatConstantGenerator::NaN(double v) const {
236   (void)v;
237   return MakeNaN(double_prefix_);
238 }
239
240 std::string TypedFloatConstantGenerator::Value(float v,
241                                                const std::string &src) const {
242   (void)v;
243   return src + "f";
244 }
245
246 std::string TypedFloatConstantGenerator::Inf(float v) const {
247   return MakeInf(v < 0, single_prefix_);
248 }
249
250 std::string TypedFloatConstantGenerator::NaN(float v) const {
251   (void)v;
252   return MakeNaN(single_prefix_);
253 }
254
255 SimpleFloatConstantGenerator::SimpleFloatConstantGenerator(
256     const char *nan_number, const char *pos_inf_number,
257     const char *neg_inf_number)
258     : nan_number_(nan_number),
259       pos_inf_number_(pos_inf_number),
260       neg_inf_number_(neg_inf_number) {}
261
262 std::string SimpleFloatConstantGenerator::Value(double v,
263                                                 const std::string &src) const {
264   (void)v;
265   return src;
266 }
267
268 std::string SimpleFloatConstantGenerator::Inf(double v) const {
269   return (v < 0) ? neg_inf_number_ : pos_inf_number_;
270 }
271
272 std::string SimpleFloatConstantGenerator::NaN(double v) const {
273   (void)v;
274   return nan_number_;
275 }
276
277 std::string SimpleFloatConstantGenerator::Value(float v,
278                                                 const std::string &src) const {
279   return this->Value(static_cast<double>(v), src);
280 }
281
282 std::string SimpleFloatConstantGenerator::Inf(float v) const {
283   return this->Inf(static_cast<double>(v));
284 }
285
286 std::string SimpleFloatConstantGenerator::NaN(float v) const {
287   return this->NaN(static_cast<double>(v));
288 }
289
290 }  // namespace flatbuffers
291
292 #if defined(_MSC_VER)
293 #  pragma warning(pop)
294 #endif