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
JavaCSharpMakeRule(const bool java,const Parser & parser,const std::string & path,const std::string & file_name)33 std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
34 const std::string &path,
35 const std::string &file_name) {
36 const std::string file_extension = java ? ".java" : ".cs";
37 std::string make_rule;
38
39 for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end();
40 ++it) {
41 auto &enum_def = **it;
42 if (!make_rule.empty()) make_rule += " ";
43 std::string directory =
44 BaseGenerator::NamespaceDir(parser, path, *enum_def.defined_namespace);
45 make_rule += directory + enum_def.name + file_extension;
46 }
47
48 for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
49 ++it) {
50 auto &struct_def = **it;
51 if (!make_rule.empty()) make_rule += " ";
52 std::string directory = BaseGenerator::NamespaceDir(
53 parser, path, *struct_def.defined_namespace);
54 make_rule += directory + struct_def.name + file_extension;
55 }
56
57 make_rule += ": ";
58 auto included_files = parser.GetIncludedFilesRecursive(file_name);
59 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
60 make_rule += " " + *it;
61 }
62 return make_rule;
63 }
64
operator +=(std::string text)65 void CodeWriter::operator+=(std::string text) {
66 if (!ignore_ident_ && !text.empty()) AppendIdent(stream_);
67
68 while (true) {
69 auto begin = text.find("{{");
70 if (begin == std::string::npos) { break; }
71
72 auto end = text.find("}}");
73 if (end == std::string::npos || end < begin) { break; }
74
75 // Write all the text before the first {{ into the stream.
76 stream_.write(text.c_str(), begin);
77
78 // The key is between the {{ and }}.
79 const std::string key = text.substr(begin + 2, end - begin - 2);
80
81 // Find the value associated with the key. If it exists, write the
82 // value into the stream, otherwise write the key itself into the stream.
83 auto iter = value_map_.find(key);
84 if (iter != value_map_.end()) {
85 const std::string &value = iter->second;
86 stream_ << value;
87 } else {
88 FLATBUFFERS_ASSERT(false && "could not find key");
89 stream_ << key;
90 }
91
92 // Update the text to everything after the }}.
93 text = text.substr(end + 2);
94 }
95 if (!text.empty() && text.back() == '\\') {
96 text.pop_back();
97 ignore_ident_ = true;
98 stream_ << text;
99 } else {
100 ignore_ident_ = false;
101 stream_ << text << std::endl;
102 }
103 }
104
AppendIdent(std::stringstream & stream)105 void CodeWriter::AppendIdent(std::stringstream &stream) {
106 int lvl = cur_ident_lvl_;
107 while (lvl--) {
108 stream.write(pad_.c_str(), static_cast<std::streamsize>(pad_.size()));
109 }
110 }
111
FlatBuffersGeneratedWarning()112 const char *BaseGenerator::FlatBuffersGeneratedWarning() {
113 return "automatically generated by the FlatBuffers compiler,"
114 " do not modify";
115 }
116
NamespaceDir(const Parser & parser,const std::string & path,const Namespace & ns,const bool dasherize)117 std::string BaseGenerator::NamespaceDir(const Parser &parser,
118 const std::string &path,
119 const Namespace &ns,
120 const bool dasherize) {
121 EnsureDirExists(path);
122 if (parser.opts.one_file) return path;
123 std::string namespace_dir = path; // Either empty or ends in separator.
124 auto &namespaces = ns.components;
125 for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
126 namespace_dir +=
127 !dasherize ? *it : ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
128 namespace_dir += kPathSeparator;
129 EnsureDirExists(namespace_dir);
130 }
131 return namespace_dir;
132 }
133
NamespaceDir(const Namespace & ns,const bool dasherize) const134 std::string BaseGenerator::NamespaceDir(const Namespace &ns,
135 const bool dasherize) const {
136 return BaseGenerator::NamespaceDir(parser_, path_, ns, dasherize);
137 }
138
FullNamespace(const char * separator,const Namespace & ns)139 std::string BaseGenerator::FullNamespace(const char *separator,
140 const Namespace &ns) {
141 std::string namespace_name;
142 auto &namespaces = ns.components;
143 for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
144 if (namespace_name.length()) namespace_name += separator;
145 namespace_name += *it;
146 }
147 return namespace_name;
148 }
149
LastNamespacePart(const Namespace & ns)150 std::string BaseGenerator::LastNamespacePart(const Namespace &ns) {
151 if (!ns.components.empty())
152 return ns.components.back();
153 else
154 return std::string("");
155 }
156
157 // Ensure that a type is prefixed with its namespace.
WrapInNameSpace(const Namespace * ns,const std::string & name) const158 std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
159 const std::string &name) const {
160 std::string qualified_name = qualifying_start_;
161 for (auto it = ns->components.begin(); it != ns->components.end(); ++it)
162 qualified_name += *it + qualifying_separator_;
163 return qualified_name + name;
164 }
165
WrapInNameSpace(const Definition & def,const std::string & suffix) const166 std::string BaseGenerator::WrapInNameSpace(const Definition &def,
167 const std::string &suffix) const {
168 return WrapInNameSpace(def.defined_namespace, def.name + suffix);
169 }
170
GetNameSpace(const Definition & def) const171 std::string BaseGenerator::GetNameSpace(const Definition &def) const {
172 const Namespace *ns = def.defined_namespace;
173 if (CurrentNameSpace() == ns) return "";
174 std::string qualified_name = qualifying_start_;
175 for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
176 qualified_name += *it;
177 if ((it + 1) != ns->components.end()) {
178 qualified_name += qualifying_separator_;
179 }
180 }
181
182 return qualified_name;
183 }
184
GeneratedFileName(const std::string & path,const std::string & file_name,const IDLOptions & options) const185 std::string BaseGenerator::GeneratedFileName(const std::string &path,
186 const std::string &file_name,
187 const IDLOptions &options) const {
188 return path + file_name + options.filename_suffix + "." +
189 (options.filename_extension.empty() ? default_extension_
190 : options.filename_extension);
191 }
192
193 // Generate a documentation comment, if available.
GenComment(const std::vector<std::string> & dc,std::string * code_ptr,const CommentConfig * config,const char * prefix)194 void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
195 const CommentConfig *config, const char *prefix) {
196 if (dc.begin() == dc.end()) {
197 // Don't output empty comment blocks with 0 lines of comment content.
198 return;
199 }
200
201 std::string &code = *code_ptr;
202 if (config != nullptr && config->first_line != nullptr) {
203 code += std::string(prefix) + std::string(config->first_line) + "\n";
204 }
205 std::string line_prefix =
206 std::string(prefix) +
207 ((config != nullptr && config->content_line_prefix != nullptr)
208 ? config->content_line_prefix
209 : "///");
210 for (auto it = dc.begin(); it != dc.end(); ++it) {
211 code += line_prefix + *it + "\n";
212 }
213 if (config != nullptr && config->last_line != nullptr) {
214 code += std::string(prefix) + std::string(config->last_line) + "\n";
215 }
216 }
217
218 template<typename T>
GenFloatConstantImpl(const FieldDef & field) const219 std::string FloatConstantGenerator::GenFloatConstantImpl(
220 const FieldDef &field) const {
221 const auto &constant = field.value.constant;
222 T v;
223 auto done = StringToNumber(constant.c_str(), &v);
224 FLATBUFFERS_ASSERT(done);
225 if (done) {
226 #if (!defined(_MSC_VER) || (_MSC_VER >= 1800))
227 if (std::isnan(v)) return NaN(v);
228 if (std::isinf(v)) return Inf(v);
229 #endif
230 return Value(v, constant);
231 }
232 return "#"; // compile time error
233 }
234
GenFloatConstant(const FieldDef & field) const235 std::string FloatConstantGenerator::GenFloatConstant(
236 const FieldDef &field) const {
237 switch (field.value.type.base_type) {
238 case BASE_TYPE_FLOAT: return GenFloatConstantImpl<float>(field);
239 case BASE_TYPE_DOUBLE: return GenFloatConstantImpl<double>(field);
240 default: {
241 FLATBUFFERS_ASSERT(false);
242 return "INVALID_BASE_TYPE";
243 }
244 };
245 }
246
TypedFloatConstantGenerator(const char * double_prefix,const char * single_prefix,const char * nan_number,const char * pos_inf_number,const char * neg_inf_number)247 TypedFloatConstantGenerator::TypedFloatConstantGenerator(
248 const char *double_prefix, const char *single_prefix,
249 const char *nan_number, const char *pos_inf_number,
250 const char *neg_inf_number)
251 : double_prefix_(double_prefix),
252 single_prefix_(single_prefix),
253 nan_number_(nan_number),
254 pos_inf_number_(pos_inf_number),
255 neg_inf_number_(neg_inf_number) {}
256
MakeNaN(const std::string & prefix) const257 std::string TypedFloatConstantGenerator::MakeNaN(
258 const std::string &prefix) const {
259 return prefix + nan_number_;
260 }
MakeInf(bool neg,const std::string & prefix) const261 std::string TypedFloatConstantGenerator::MakeInf(
262 bool neg, const std::string &prefix) const {
263 if (neg)
264 return !neg_inf_number_.empty() ? (prefix + neg_inf_number_)
265 : ("-" + prefix + pos_inf_number_);
266 else
267 return prefix + pos_inf_number_;
268 }
269
Value(double v,const std::string & src) const270 std::string TypedFloatConstantGenerator::Value(double v,
271 const std::string &src) const {
272 (void)v;
273 return src;
274 }
275
Inf(double v) const276 std::string TypedFloatConstantGenerator::Inf(double v) const {
277 return MakeInf(v < 0, double_prefix_);
278 }
279
NaN(double v) const280 std::string TypedFloatConstantGenerator::NaN(double v) const {
281 (void)v;
282 return MakeNaN(double_prefix_);
283 }
284
Value(float v,const std::string & src) const285 std::string TypedFloatConstantGenerator::Value(float v,
286 const std::string &src) const {
287 (void)v;
288 return src + "f";
289 }
290
Inf(float v) const291 std::string TypedFloatConstantGenerator::Inf(float v) const {
292 return MakeInf(v < 0, single_prefix_);
293 }
294
NaN(float v) const295 std::string TypedFloatConstantGenerator::NaN(float v) const {
296 (void)v;
297 return MakeNaN(single_prefix_);
298 }
299
SimpleFloatConstantGenerator(const char * nan_number,const char * pos_inf_number,const char * neg_inf_number)300 SimpleFloatConstantGenerator::SimpleFloatConstantGenerator(
301 const char *nan_number, const char *pos_inf_number,
302 const char *neg_inf_number)
303 : nan_number_(nan_number),
304 pos_inf_number_(pos_inf_number),
305 neg_inf_number_(neg_inf_number) {}
306
Value(double v,const std::string & src) const307 std::string SimpleFloatConstantGenerator::Value(double v,
308 const std::string &src) const {
309 (void)v;
310 return src;
311 }
312
Inf(double v) const313 std::string SimpleFloatConstantGenerator::Inf(double v) const {
314 return (v < 0) ? neg_inf_number_ : pos_inf_number_;
315 }
316
NaN(double v) const317 std::string SimpleFloatConstantGenerator::NaN(double v) const {
318 (void)v;
319 return nan_number_;
320 }
321
Value(float v,const std::string & src) const322 std::string SimpleFloatConstantGenerator::Value(float v,
323 const std::string &src) const {
324 return this->Value(static_cast<double>(v), src);
325 }
326
Inf(float v) const327 std::string SimpleFloatConstantGenerator::Inf(float v) const {
328 return this->Inf(static_cast<double>(v));
329 }
330
NaN(float v) const331 std::string SimpleFloatConstantGenerator::NaN(float v) const {
332 return this->NaN(static_cast<double>(v));
333 }
334
335 } // namespace flatbuffers
336
337 #if defined(_MSC_VER)
338 # pragma warning(pop)
339 #endif
340