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
operator +=(std::string text)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
AppendIdent(std::stringstream & stream)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
FlatBuffersGeneratedWarning()80 const char *BaseGenerator::FlatBuffersGeneratedWarning() {
81 return "automatically generated by the FlatBuffers compiler,"
82 " do not modify";
83 }
84
NamespaceDir(const Parser & parser,const std::string & path,const Namespace & ns,const bool dasherize)85 std::string BaseGenerator::NamespaceDir(const Parser &parser,
86 const std::string &path,
87 const Namespace &ns,
88 const bool dasherize) {
89 EnsureDirExists(path);
90 if (parser.opts.one_file) return path;
91 std::string namespace_dir = path; // Either empty or ends in separator.
92 auto &namespaces = ns.components;
93 for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
94 namespace_dir += !dasherize ? *it : ToDasherizedCase(*it);
95 namespace_dir += kPathSeparator;
96 EnsureDirExists(namespace_dir);
97 }
98 return namespace_dir;
99 }
100
NamespaceDir(const Namespace & ns,const bool dasherize) const101 std::string BaseGenerator::NamespaceDir(const Namespace &ns,
102 const bool dasherize) const {
103 return BaseGenerator::NamespaceDir(parser_, path_, ns, dasherize);
104 }
105
ToDasherizedCase(const std::string pascal_case)106 std::string BaseGenerator::ToDasherizedCase(const std::string pascal_case) {
107 std::string dasherized_case;
108 char p = 0;
109 for (size_t i = 0; i < pascal_case.length(); i++) {
110 char const &c = pascal_case[i];
111 if (is_alpha_upper(c)) {
112 if (i > 0 && p != kPathSeparator) dasherized_case += "-";
113 dasherized_case += CharToLower(c);
114 } else {
115 dasherized_case += c;
116 }
117 p = c;
118 }
119 return dasherized_case;
120 }
121
FullNamespace(const char * separator,const Namespace & ns)122 std::string BaseGenerator::FullNamespace(const char *separator,
123 const Namespace &ns) {
124 std::string namespace_name;
125 auto &namespaces = ns.components;
126 for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
127 if (namespace_name.length()) namespace_name += separator;
128 namespace_name += *it;
129 }
130 return namespace_name;
131 }
132
LastNamespacePart(const Namespace & ns)133 std::string BaseGenerator::LastNamespacePart(const Namespace &ns) {
134 if (!ns.components.empty())
135 return ns.components.back();
136 else
137 return std::string("");
138 }
139
140 // Ensure that a type is prefixed with its namespace.
WrapInNameSpace(const Namespace * ns,const std::string & name) const141 std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
142 const std::string &name) const {
143 std::string qualified_name = qualifying_start_;
144 for (auto it = ns->components.begin(); it != ns->components.end(); ++it)
145 qualified_name += *it + qualifying_separator_;
146 return qualified_name + name;
147 }
148
WrapInNameSpace(const Definition & def) const149 std::string BaseGenerator::WrapInNameSpace(const Definition &def) const {
150 return WrapInNameSpace(def.defined_namespace, def.name);
151 }
152
GetNameSpace(const Definition & def) const153 std::string BaseGenerator::GetNameSpace(const Definition &def) const {
154 const Namespace *ns = def.defined_namespace;
155 if (CurrentNameSpace() == ns) return "";
156 std::string qualified_name = qualifying_start_;
157 for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
158 qualified_name += *it;
159 if ((it + 1) != ns->components.end()) {
160 qualified_name += qualifying_separator_;
161 }
162 }
163
164 return qualified_name;
165 }
166
GeneratedFileName(const std::string & path,const std::string & file_name,const IDLOptions & options) const167 std::string BaseGenerator::GeneratedFileName(const std::string &path,
168 const std::string &file_name,
169 const IDLOptions &options) const {
170 return path + file_name + options.filename_suffix + "." +
171 (options.filename_extension.empty() ? default_extension_
172 : options.filename_extension);
173 }
174
175 // Generate a documentation comment, if available.
GenComment(const std::vector<std::string> & dc,std::string * code_ptr,const CommentConfig * config,const char * prefix)176 void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
177 const CommentConfig *config, const char *prefix) {
178 if (dc.begin() == dc.end()) {
179 // Don't output empty comment blocks with 0 lines of comment content.
180 return;
181 }
182
183 std::string &code = *code_ptr;
184 if (config != nullptr && config->first_line != nullptr) {
185 code += std::string(prefix) + std::string(config->first_line) + "\n";
186 }
187 std::string line_prefix =
188 std::string(prefix) +
189 ((config != nullptr && config->content_line_prefix != nullptr)
190 ? config->content_line_prefix
191 : "///");
192 for (auto it = dc.begin(); it != dc.end(); ++it) {
193 code += line_prefix + *it + "\n";
194 }
195 if (config != nullptr && config->last_line != nullptr) {
196 code += std::string(prefix) + std::string(config->last_line) + "\n";
197 }
198 }
199
200 template<typename T>
GenFloatConstantImpl(const FieldDef & field) const201 std::string FloatConstantGenerator::GenFloatConstantImpl(
202 const FieldDef &field) const {
203 const auto &constant = field.value.constant;
204 T v;
205 auto done = StringToNumber(constant.c_str(), &v);
206 FLATBUFFERS_ASSERT(done);
207 if (done) {
208 #if (!defined(_MSC_VER) || (_MSC_VER >= 1800))
209 if (std::isnan(v)) return NaN(v);
210 if (std::isinf(v)) return Inf(v);
211 #endif
212 return Value(v, constant);
213 }
214 return "#"; // compile time error
215 }
216
GenFloatConstant(const FieldDef & field) const217 std::string FloatConstantGenerator::GenFloatConstant(
218 const FieldDef &field) const {
219 switch (field.value.type.base_type) {
220 case BASE_TYPE_FLOAT: return GenFloatConstantImpl<float>(field);
221 case BASE_TYPE_DOUBLE: return GenFloatConstantImpl<double>(field);
222 default: {
223 FLATBUFFERS_ASSERT(false);
224 return "INVALID_BASE_TYPE";
225 }
226 };
227 }
228
TypedFloatConstantGenerator(const char * double_prefix,const char * single_prefix,const char * nan_number,const char * pos_inf_number,const char * neg_inf_number)229 TypedFloatConstantGenerator::TypedFloatConstantGenerator(
230 const char *double_prefix, const char *single_prefix,
231 const char *nan_number, const char *pos_inf_number,
232 const char *neg_inf_number)
233 : double_prefix_(double_prefix),
234 single_prefix_(single_prefix),
235 nan_number_(nan_number),
236 pos_inf_number_(pos_inf_number),
237 neg_inf_number_(neg_inf_number) {}
238
MakeNaN(const std::string & prefix) const239 std::string TypedFloatConstantGenerator::MakeNaN(
240 const std::string &prefix) const {
241 return prefix + nan_number_;
242 }
MakeInf(bool neg,const std::string & prefix) const243 std::string TypedFloatConstantGenerator::MakeInf(
244 bool neg, const std::string &prefix) const {
245 if (neg)
246 return !neg_inf_number_.empty() ? (prefix + neg_inf_number_)
247 : ("-" + prefix + pos_inf_number_);
248 else
249 return prefix + pos_inf_number_;
250 }
251
Value(double v,const std::string & src) const252 std::string TypedFloatConstantGenerator::Value(double v,
253 const std::string &src) const {
254 (void)v;
255 return src;
256 }
257
Inf(double v) const258 std::string TypedFloatConstantGenerator::Inf(double v) const {
259 return MakeInf(v < 0, double_prefix_);
260 }
261
NaN(double v) const262 std::string TypedFloatConstantGenerator::NaN(double v) const {
263 (void)v;
264 return MakeNaN(double_prefix_);
265 }
266
Value(float v,const std::string & src) const267 std::string TypedFloatConstantGenerator::Value(float v,
268 const std::string &src) const {
269 (void)v;
270 return src + "f";
271 }
272
Inf(float v) const273 std::string TypedFloatConstantGenerator::Inf(float v) const {
274 return MakeInf(v < 0, single_prefix_);
275 }
276
NaN(float v) const277 std::string TypedFloatConstantGenerator::NaN(float v) const {
278 (void)v;
279 return MakeNaN(single_prefix_);
280 }
281
SimpleFloatConstantGenerator(const char * nan_number,const char * pos_inf_number,const char * neg_inf_number)282 SimpleFloatConstantGenerator::SimpleFloatConstantGenerator(
283 const char *nan_number, const char *pos_inf_number,
284 const char *neg_inf_number)
285 : nan_number_(nan_number),
286 pos_inf_number_(pos_inf_number),
287 neg_inf_number_(neg_inf_number) {}
288
Value(double v,const std::string & src) const289 std::string SimpleFloatConstantGenerator::Value(double v,
290 const std::string &src) const {
291 (void)v;
292 return src;
293 }
294
Inf(double v) const295 std::string SimpleFloatConstantGenerator::Inf(double v) const {
296 return (v < 0) ? neg_inf_number_ : pos_inf_number_;
297 }
298
NaN(double v) const299 std::string SimpleFloatConstantGenerator::NaN(double v) const {
300 (void)v;
301 return nan_number_;
302 }
303
Value(float v,const std::string & src) const304 std::string SimpleFloatConstantGenerator::Value(float v,
305 const std::string &src) const {
306 return this->Value(static_cast<double>(v), src);
307 }
308
Inf(float v) const309 std::string SimpleFloatConstantGenerator::Inf(float v) const {
310 return this->Inf(static_cast<double>(v));
311 }
312
NaN(float v) const313 std::string SimpleFloatConstantGenerator::NaN(float v) const {
314 return this->NaN(static_cast<double>(v));
315 }
316
JavaCSharpMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)317 std::string JavaCSharpMakeRule(const Parser &parser, const std::string &path,
318 const std::string &file_name) {
319 FLATBUFFERS_ASSERT(parser.opts.lang == IDLOptions::kJava ||
320 parser.opts.lang == IDLOptions::kCSharp);
321
322 std::string file_extension =
323 (parser.opts.lang == IDLOptions::kJava) ? ".java" : ".cs";
324
325 std::string make_rule;
326
327 for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end();
328 ++it) {
329 auto &enum_def = **it;
330 if (!make_rule.empty()) make_rule += " ";
331 std::string directory =
332 BaseGenerator::NamespaceDir(parser, path, *enum_def.defined_namespace);
333 make_rule += directory + enum_def.name + file_extension;
334 }
335
336 for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
337 ++it) {
338 auto &struct_def = **it;
339 if (!make_rule.empty()) make_rule += " ";
340 std::string directory = BaseGenerator::NamespaceDir(
341 parser, path, *struct_def.defined_namespace);
342 make_rule += directory + struct_def.name + file_extension;
343 }
344
345 make_rule += ": ";
346 auto included_files = parser.GetIncludedFilesRecursive(file_name);
347 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
348 make_rule += " " + *it;
349 }
350 return make_rule;
351 }
352
BinaryFileName(const Parser & parser,const std::string & path,const std::string & file_name)353 std::string BinaryFileName(const Parser &parser, const std::string &path,
354 const std::string &file_name) {
355 auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
356 return path + file_name + "." + ext;
357 }
358
GenerateBinary(const Parser & parser,const std::string & path,const std::string & file_name)359 bool GenerateBinary(const Parser &parser, const std::string &path,
360 const std::string &file_name) {
361 if (parser.opts.use_flexbuffers) {
362 auto data_vec = parser.flex_builder_.GetBuffer();
363 auto data_ptr = reinterpret_cast<char *>(data(data_vec));
364 return !parser.flex_builder_.GetSize() ||
365 flatbuffers::SaveFile(
366 BinaryFileName(parser, path, file_name).c_str(), data_ptr,
367 parser.flex_builder_.GetSize(), true);
368 }
369 return !parser.builder_.GetSize() ||
370 flatbuffers::SaveFile(
371 BinaryFileName(parser, path, file_name).c_str(),
372 reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
373 parser.builder_.GetSize(), true);
374 }
375
BinaryMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)376 std::string BinaryMakeRule(const Parser &parser, const std::string &path,
377 const std::string &file_name) {
378 if (!parser.builder_.GetSize()) return "";
379 std::string filebase =
380 flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
381 std::string make_rule =
382 BinaryFileName(parser, path, filebase) + ": " + file_name;
383 auto included_files =
384 parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
385 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
386 make_rule += " " + *it;
387 }
388 return make_rule;
389 }
390
391 } // namespace flatbuffers
392
393 #if defined(_MSC_VER)
394 # pragma warning(pop)
395 #endif
396