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)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 
NamespaceDir(const Namespace & ns) const99 std::string BaseGenerator::NamespaceDir(const Namespace &ns) const {
100   return BaseGenerator::NamespaceDir(parser_, path_, ns);
101 }
102 
FullNamespace(const char * separator,const Namespace & ns)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 
LastNamespacePart(const Namespace & ns)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.
WrapInNameSpace(const Namespace * ns,const std::string & name) const122 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 
WrapInNameSpace(const Definition & def) const130 std::string BaseGenerator::WrapInNameSpace(const Definition &def) const {
131   return WrapInNameSpace(def.defined_namespace, def.name);
132 }
133 
GetNameSpace(const Definition & def) const134 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 
GeneratedFileName(const std::string & path,const std::string & file_name,const IDLOptions & options) const148 std::string BaseGenerator::GeneratedFileName(const std::string &path,
149                                              const std::string &file_name,
150                                              const IDLOptions &options) const {
151   return path + file_name + options.filename_suffix + "." +
152          (options.filename_extension.empty() ? default_extension_
153                                              : options.filename_extension);
154 }
155 
156 // Generate a documentation comment, if available.
GenComment(const std::vector<std::string> & dc,std::string * code_ptr,const CommentConfig * config,const char * prefix)157 void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
158                 const CommentConfig *config, const char *prefix) {
159   if (dc.begin() == dc.end()) {
160     // Don't output empty comment blocks with 0 lines of comment content.
161     return;
162   }
163 
164   std::string &code = *code_ptr;
165   if (config != nullptr && config->first_line != nullptr) {
166     code += std::string(prefix) + std::string(config->first_line) + "\n";
167   }
168   std::string line_prefix =
169       std::string(prefix) +
170       ((config != nullptr && config->content_line_prefix != nullptr)
171            ? config->content_line_prefix
172            : "///");
173   for (auto it = dc.begin(); it != dc.end(); ++it) {
174     code += line_prefix + *it + "\n";
175   }
176   if (config != nullptr && config->last_line != nullptr) {
177     code += std::string(prefix) + std::string(config->last_line) + "\n";
178   }
179 }
180 
181 template<typename T>
GenFloatConstantImpl(const FieldDef & field) const182 std::string FloatConstantGenerator::GenFloatConstantImpl(
183     const FieldDef &field) const {
184   const auto &constant = field.value.constant;
185   T v;
186   auto done = StringToNumber(constant.c_str(), &v);
187   FLATBUFFERS_ASSERT(done);
188   if (done) {
189 #if (!defined(_MSC_VER) || (_MSC_VER >= 1800))
190     if (std::isnan(v)) return NaN(v);
191     if (std::isinf(v)) return Inf(v);
192 #endif
193     return Value(v, constant);
194   }
195   return "#";  // compile time error
196 }
197 
GenFloatConstant(const FieldDef & field) const198 std::string FloatConstantGenerator::GenFloatConstant(
199     const FieldDef &field) const {
200   switch (field.value.type.base_type) {
201     case BASE_TYPE_FLOAT: return GenFloatConstantImpl<float>(field);
202     case BASE_TYPE_DOUBLE: return GenFloatConstantImpl<double>(field);
203     default: {
204       FLATBUFFERS_ASSERT(false);
205       return "INVALID_BASE_TYPE";
206     }
207   };
208 }
209 
TypedFloatConstantGenerator(const char * double_prefix,const char * single_prefix,const char * nan_number,const char * pos_inf_number,const char * neg_inf_number)210 TypedFloatConstantGenerator::TypedFloatConstantGenerator(
211     const char *double_prefix, const char *single_prefix,
212     const char *nan_number, const char *pos_inf_number,
213     const char *neg_inf_number)
214     : double_prefix_(double_prefix),
215       single_prefix_(single_prefix),
216       nan_number_(nan_number),
217       pos_inf_number_(pos_inf_number),
218       neg_inf_number_(neg_inf_number) {}
219 
MakeNaN(const std::string & prefix) const220 std::string TypedFloatConstantGenerator::MakeNaN(
221     const std::string &prefix) const {
222   return prefix + nan_number_;
223 }
MakeInf(bool neg,const std::string & prefix) const224 std::string TypedFloatConstantGenerator::MakeInf(
225     bool neg, const std::string &prefix) const {
226   if (neg)
227     return !neg_inf_number_.empty() ? (prefix + neg_inf_number_)
228                                     : ("-" + prefix + pos_inf_number_);
229   else
230     return prefix + pos_inf_number_;
231 }
232 
Value(double v,const std::string & src) const233 std::string TypedFloatConstantGenerator::Value(double v,
234                                                const std::string &src) const {
235   (void)v;
236   return src;
237 }
238 
Inf(double v) const239 std::string TypedFloatConstantGenerator::Inf(double v) const {
240   return MakeInf(v < 0, double_prefix_);
241 }
242 
NaN(double v) const243 std::string TypedFloatConstantGenerator::NaN(double v) const {
244   (void)v;
245   return MakeNaN(double_prefix_);
246 }
247 
Value(float v,const std::string & src) const248 std::string TypedFloatConstantGenerator::Value(float v,
249                                                const std::string &src) const {
250   (void)v;
251   return src + "f";
252 }
253 
Inf(float v) const254 std::string TypedFloatConstantGenerator::Inf(float v) const {
255   return MakeInf(v < 0, single_prefix_);
256 }
257 
NaN(float v) const258 std::string TypedFloatConstantGenerator::NaN(float v) const {
259   (void)v;
260   return MakeNaN(single_prefix_);
261 }
262 
SimpleFloatConstantGenerator(const char * nan_number,const char * pos_inf_number,const char * neg_inf_number)263 SimpleFloatConstantGenerator::SimpleFloatConstantGenerator(
264     const char *nan_number, const char *pos_inf_number,
265     const char *neg_inf_number)
266     : nan_number_(nan_number),
267       pos_inf_number_(pos_inf_number),
268       neg_inf_number_(neg_inf_number) {}
269 
Value(double v,const std::string & src) const270 std::string SimpleFloatConstantGenerator::Value(double v,
271                                                 const std::string &src) const {
272   (void)v;
273   return src;
274 }
275 
Inf(double v) const276 std::string SimpleFloatConstantGenerator::Inf(double v) const {
277   return (v < 0) ? neg_inf_number_ : pos_inf_number_;
278 }
279 
NaN(double v) const280 std::string SimpleFloatConstantGenerator::NaN(double v) const {
281   (void)v;
282   return nan_number_;
283 }
284 
Value(float v,const std::string & src) const285 std::string SimpleFloatConstantGenerator::Value(float v,
286                                                 const std::string &src) const {
287   return this->Value(static_cast<double>(v), src);
288 }
289 
Inf(float v) const290 std::string SimpleFloatConstantGenerator::Inf(float v) const {
291   return this->Inf(static_cast<double>(v));
292 }
293 
NaN(float v) const294 std::string SimpleFloatConstantGenerator::NaN(float v) const {
295   return this->NaN(static_cast<double>(v));
296 }
297 
JavaCSharpMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)298 std::string JavaCSharpMakeRule(const Parser &parser, const std::string &path,
299                                const std::string &file_name) {
300   FLATBUFFERS_ASSERT(parser.opts.lang == IDLOptions::kJava ||
301                      parser.opts.lang == IDLOptions::kCSharp);
302 
303   std::string file_extension =
304       (parser.opts.lang == IDLOptions::kJava) ? ".java" : ".cs";
305 
306   std::string make_rule;
307 
308   for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end();
309        ++it) {
310     auto &enum_def = **it;
311     if (!make_rule.empty()) make_rule += " ";
312     std::string directory =
313         BaseGenerator::NamespaceDir(parser, path, *enum_def.defined_namespace);
314     make_rule += directory + enum_def.name + file_extension;
315   }
316 
317   for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
318        ++it) {
319     auto &struct_def = **it;
320     if (!make_rule.empty()) make_rule += " ";
321     std::string directory = BaseGenerator::NamespaceDir(
322         parser, path, *struct_def.defined_namespace);
323     make_rule += directory + struct_def.name + file_extension;
324   }
325 
326   make_rule += ": ";
327   auto included_files = parser.GetIncludedFilesRecursive(file_name);
328   for (auto it = included_files.begin(); it != included_files.end(); ++it) {
329     make_rule += " " + *it;
330   }
331   return make_rule;
332 }
333 
BinaryFileName(const Parser & parser,const std::string & path,const std::string & file_name)334 std::string BinaryFileName(const Parser &parser, const std::string &path,
335                            const std::string &file_name) {
336   auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
337   return path + file_name + "." + ext;
338 }
339 
GenerateBinary(const Parser & parser,const std::string & path,const std::string & file_name)340 bool GenerateBinary(const Parser &parser, const std::string &path,
341                     const std::string &file_name) {
342   if (parser.opts.use_flexbuffers) {
343     auto data_vec = parser.flex_builder_.GetBuffer();
344     auto data_ptr = reinterpret_cast<char *>(data(data_vec));
345     return !parser.flex_builder_.GetSize() ||
346            flatbuffers::SaveFile(
347                BinaryFileName(parser, path, file_name).c_str(), data_ptr,
348                parser.flex_builder_.GetSize(), true);
349   }
350   return !parser.builder_.GetSize() ||
351          flatbuffers::SaveFile(
352              BinaryFileName(parser, path, file_name).c_str(),
353              reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
354              parser.builder_.GetSize(), true);
355 }
356 
BinaryMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)357 std::string BinaryMakeRule(const Parser &parser, const std::string &path,
358                            const std::string &file_name) {
359   if (!parser.builder_.GetSize()) return "";
360   std::string filebase =
361       flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
362   std::string make_rule =
363       BinaryFileName(parser, path, filebase) + ": " + file_name;
364   auto included_files =
365       parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
366   for (auto it = included_files.begin(); it != included_files.end(); ++it) {
367     make_rule += " " + *it;
368   }
369   return make_rule;
370 }
371 
372 }  // namespace flatbuffers
373 
374 #if defined(_MSC_VER)
375 #  pragma warning(pop)
376 #endif
377