blob: 269687df9b2e320442c30219efde4342df162d5d [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001/*
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"
Austin Schuh272c6132020-11-14 16:37:52 -080018
Austin Schuhe89fa2d2019-08-14 20:24:23 -070019#include <assert.h>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070020
21#include <cmath>
22
Austin Schuh272c6132020-11-14 16:37:52 -080023#include "flatbuffers/base.h"
24#include "flatbuffers/util.h"
25
Austin Schuhe89fa2d2019-08-14 20:24:23 -070026#if defined(_MSC_VER)
27# pragma warning(push)
28# pragma warning(disable : 4127) // C4127: conditional expression is constant
29#endif
30
31namespace flatbuffers {
32
33void 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 }
James Kuszmaul8e62b022022-03-22 09:33:25 -070063 if (!text.empty() && text.back() == '\\') {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070064 text.pop_back();
65 ignore_ident_ = true;
66 stream_ << text;
67 } else {
68 ignore_ident_ = false;
69 stream_ << text << std::endl;
70 }
71}
72
73void 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
80const char *BaseGenerator::FlatBuffersGeneratedWarning() {
81 return "automatically generated by the FlatBuffers compiler,"
82 " do not modify";
83}
84
85std::string BaseGenerator::NamespaceDir(const Parser &parser,
86 const std::string &path,
James Kuszmaul8e62b022022-03-22 09:33:25 -070087 const Namespace &ns,
88 const bool dasherize) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070089 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) {
James Kuszmaul8e62b022022-03-22 09:33:25 -070094 namespace_dir +=
95 !dasherize ? *it : ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
96 namespace_dir += kPathSeparator;
Austin Schuhe89fa2d2019-08-14 20:24:23 -070097 EnsureDirExists(namespace_dir);
98 }
99 return namespace_dir;
100}
101
James Kuszmaul8e62b022022-03-22 09:33:25 -0700102std::string BaseGenerator::NamespaceDir(const Namespace &ns,
103 const bool dasherize) const {
104 return BaseGenerator::NamespaceDir(parser_, path_, ns, dasherize);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700105}
106
107std::string BaseGenerator::FullNamespace(const char *separator,
108 const Namespace &ns) {
109 std::string namespace_name;
110 auto &namespaces = ns.components;
111 for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
112 if (namespace_name.length()) namespace_name += separator;
113 namespace_name += *it;
114 }
115 return namespace_name;
116}
117
118std::string BaseGenerator::LastNamespacePart(const Namespace &ns) {
119 if (!ns.components.empty())
120 return ns.components.back();
121 else
122 return std::string("");
123}
124
125// Ensure that a type is prefixed with its namespace.
126std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
127 const std::string &name) const {
128 std::string qualified_name = qualifying_start_;
129 for (auto it = ns->components.begin(); it != ns->components.end(); ++it)
130 qualified_name += *it + qualifying_separator_;
131 return qualified_name + name;
132}
133
134std::string BaseGenerator::WrapInNameSpace(const Definition &def) const {
135 return WrapInNameSpace(def.defined_namespace, def.name);
136}
137
138std::string BaseGenerator::GetNameSpace(const Definition &def) const {
139 const Namespace *ns = def.defined_namespace;
140 if (CurrentNameSpace() == ns) return "";
141 std::string qualified_name = qualifying_start_;
142 for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
143 qualified_name += *it;
144 if ((it + 1) != ns->components.end()) {
145 qualified_name += qualifying_separator_;
146 }
147 }
148
149 return qualified_name;
150}
151
Austin Schuh272c6132020-11-14 16:37:52 -0800152std::string BaseGenerator::GeneratedFileName(const std::string &path,
153 const std::string &file_name,
154 const IDLOptions &options) const {
155 return path + file_name + options.filename_suffix + "." +
156 (options.filename_extension.empty() ? default_extension_
157 : options.filename_extension);
158}
159
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700160// Generate a documentation comment, if available.
161void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
162 const CommentConfig *config, const char *prefix) {
163 if (dc.begin() == dc.end()) {
164 // Don't output empty comment blocks with 0 lines of comment content.
165 return;
166 }
167
168 std::string &code = *code_ptr;
169 if (config != nullptr && config->first_line != nullptr) {
170 code += std::string(prefix) + std::string(config->first_line) + "\n";
171 }
172 std::string line_prefix =
173 std::string(prefix) +
174 ((config != nullptr && config->content_line_prefix != nullptr)
175 ? config->content_line_prefix
176 : "///");
177 for (auto it = dc.begin(); it != dc.end(); ++it) {
178 code += line_prefix + *it + "\n";
179 }
180 if (config != nullptr && config->last_line != nullptr) {
181 code += std::string(prefix) + std::string(config->last_line) + "\n";
182 }
183}
184
185template<typename T>
186std::string FloatConstantGenerator::GenFloatConstantImpl(
187 const FieldDef &field) const {
188 const auto &constant = field.value.constant;
189 T v;
190 auto done = StringToNumber(constant.c_str(), &v);
191 FLATBUFFERS_ASSERT(done);
192 if (done) {
193#if (!defined(_MSC_VER) || (_MSC_VER >= 1800))
194 if (std::isnan(v)) return NaN(v);
195 if (std::isinf(v)) return Inf(v);
196#endif
197 return Value(v, constant);
198 }
199 return "#"; // compile time error
200}
201
202std::string FloatConstantGenerator::GenFloatConstant(
203 const FieldDef &field) const {
204 switch (field.value.type.base_type) {
205 case BASE_TYPE_FLOAT: return GenFloatConstantImpl<float>(field);
206 case BASE_TYPE_DOUBLE: return GenFloatConstantImpl<double>(field);
207 default: {
208 FLATBUFFERS_ASSERT(false);
209 return "INVALID_BASE_TYPE";
210 }
211 };
212}
213
214TypedFloatConstantGenerator::TypedFloatConstantGenerator(
215 const char *double_prefix, const char *single_prefix,
216 const char *nan_number, const char *pos_inf_number,
217 const char *neg_inf_number)
218 : double_prefix_(double_prefix),
219 single_prefix_(single_prefix),
220 nan_number_(nan_number),
221 pos_inf_number_(pos_inf_number),
222 neg_inf_number_(neg_inf_number) {}
223
224std::string TypedFloatConstantGenerator::MakeNaN(
225 const std::string &prefix) const {
226 return prefix + nan_number_;
227}
228std::string TypedFloatConstantGenerator::MakeInf(
229 bool neg, const std::string &prefix) const {
230 if (neg)
231 return !neg_inf_number_.empty() ? (prefix + neg_inf_number_)
232 : ("-" + prefix + pos_inf_number_);
233 else
234 return prefix + pos_inf_number_;
235}
236
237std::string TypedFloatConstantGenerator::Value(double v,
238 const std::string &src) const {
239 (void)v;
240 return src;
241}
242
243std::string TypedFloatConstantGenerator::Inf(double v) const {
244 return MakeInf(v < 0, double_prefix_);
245}
246
247std::string TypedFloatConstantGenerator::NaN(double v) const {
248 (void)v;
249 return MakeNaN(double_prefix_);
250}
251
252std::string TypedFloatConstantGenerator::Value(float v,
253 const std::string &src) const {
254 (void)v;
255 return src + "f";
256}
257
258std::string TypedFloatConstantGenerator::Inf(float v) const {
259 return MakeInf(v < 0, single_prefix_);
260}
261
262std::string TypedFloatConstantGenerator::NaN(float v) const {
263 (void)v;
264 return MakeNaN(single_prefix_);
265}
266
267SimpleFloatConstantGenerator::SimpleFloatConstantGenerator(
268 const char *nan_number, const char *pos_inf_number,
269 const char *neg_inf_number)
270 : nan_number_(nan_number),
271 pos_inf_number_(pos_inf_number),
272 neg_inf_number_(neg_inf_number) {}
273
274std::string SimpleFloatConstantGenerator::Value(double v,
275 const std::string &src) const {
276 (void)v;
277 return src;
278}
279
280std::string SimpleFloatConstantGenerator::Inf(double v) const {
281 return (v < 0) ? neg_inf_number_ : pos_inf_number_;
282}
283
284std::string SimpleFloatConstantGenerator::NaN(double v) const {
285 (void)v;
286 return nan_number_;
287}
288
289std::string SimpleFloatConstantGenerator::Value(float v,
290 const std::string &src) const {
291 return this->Value(static_cast<double>(v), src);
292}
293
294std::string SimpleFloatConstantGenerator::Inf(float v) const {
295 return this->Inf(static_cast<double>(v));
296}
297
298std::string SimpleFloatConstantGenerator::NaN(float v) const {
299 return this->NaN(static_cast<double>(v));
300}
301
James Kuszmaul8e62b022022-03-22 09:33:25 -0700302std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
303 const std::string &path,
Austin Schuh272c6132020-11-14 16:37:52 -0800304 const std::string &file_name) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700305 const std::string file_extension = java ? ".java" : ".cs";
Austin Schuh272c6132020-11-14 16:37:52 -0800306 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
James Kuszmaul8e62b022022-03-22 09:33:25 -0700334std::string JavaMakeRule(const Parser &parser, const std::string &path,
335 const std::string &file_name) {
336 return JavaCSharpMakeRule(true, parser, path, file_name);
337}
338std::string CSharpMakeRule(const Parser &parser, const std::string &path,
339 const std::string &file_name) {
340 return JavaCSharpMakeRule(false, parser, path, file_name);
341}
342
Austin Schuh272c6132020-11-14 16:37:52 -0800343std::string BinaryFileName(const Parser &parser, const std::string &path,
344 const std::string &file_name) {
345 auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
346 return path + file_name + "." + ext;
347}
348
349bool GenerateBinary(const Parser &parser, const std::string &path,
350 const std::string &file_name) {
351 if (parser.opts.use_flexbuffers) {
352 auto data_vec = parser.flex_builder_.GetBuffer();
353 auto data_ptr = reinterpret_cast<char *>(data(data_vec));
354 return !parser.flex_builder_.GetSize() ||
355 flatbuffers::SaveFile(
356 BinaryFileName(parser, path, file_name).c_str(), data_ptr,
357 parser.flex_builder_.GetSize(), true);
358 }
359 return !parser.builder_.GetSize() ||
360 flatbuffers::SaveFile(
361 BinaryFileName(parser, path, file_name).c_str(),
362 reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
363 parser.builder_.GetSize(), true);
364}
365
366std::string BinaryMakeRule(const Parser &parser, const std::string &path,
367 const std::string &file_name) {
368 if (!parser.builder_.GetSize()) return "";
369 std::string filebase =
370 flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
371 std::string make_rule =
372 BinaryFileName(parser, path, filebase) + ": " + file_name;
373 auto included_files =
374 parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
375 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
376 make_rule += " " + *it;
377 }
378 return make_rule;
379}
380
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700381} // namespace flatbuffers
382
383#if defined(_MSC_VER)
384# pragma warning(pop)
385#endif