namespace flatbuffers {
-// Pedantic warning free version of toupper().
-inline char ToUpper(char c) {
- return static_cast<char>(::toupper(static_cast<unsigned char>(c)));
-}
-
// Make numerical literal with type-suffix.
// This function is only needed for C++! Other languages do not need it.
static inline std::string NumToStringCpp(std::string val, BaseType type) {
}
}
-static std::string GeneratedFileName(const std::string &path,
- const std::string &file_name) {
- return path + file_name + "_generated.h";
-}
-
static std::string GenIncludeGuard(const std::string &file_name,
const Namespace &name_space,
- const std::string &postfix= "") {
- // Generate include guard.
- std::string guard = file_name;
- // Remove any non-alpha-numeric characters that may appear in a filename.
- struct IsAlnum {
- bool operator()(char c) const { return !is_alnum(c); }
- };
- guard.erase(std::remove_if(guard.begin(), guard.end(), IsAlnum()),
- guard.end());
- guard = "FLATBUFFERS_GENERATED_" + guard;
- guard += "_";
- // For further uniqueness, also add the namespace.
- for (auto it = name_space.components.begin();
- it != name_space.components.end(); ++it) {
- guard += *it + "_";
- }
- // Anything extra to add to the guard?
- if (!postfix.empty()) {
- guard += postfix + "_";
- }
- guard += "H_";
- std::transform(guard.begin(), guard.end(), guard.begin(), ToUpper);
- return guard;
+ const std::string &postfix = "") {
+ // Generate include guard.
+ std::string guard = file_name;
+ // Remove any non-alpha-numeric characters that may appear in a filename.
+ struct IsAlnum {
+ bool operator()(char c) const { return !is_alnum(c); }
+ };
+ guard.erase(std::remove_if(guard.begin(), guard.end(), IsAlnum()),
+ guard.end());
+ guard = "FLATBUFFERS_GENERATED_" + guard;
+ guard += "_";
+ // For further uniqueness, also add the namespace.
+ for (auto it = name_space.components.begin();
+ it != name_space.components.end(); ++it) {
+ guard += *it + "_";
+ }
+ // Anything extra to add to the guard?
+ if (!postfix.empty()) { guard += postfix + "_"; }
+ guard += "H_";
+ std::transform(guard.begin(), guard.end(), guard.begin(), CharToUpper);
+ return guard;
}
namespace cpp {
enum CppStandard { CPP_STD_X0 = 0, CPP_STD_11, CPP_STD_17 };
+// Define a style of 'struct' constructor if it has 'Array' fields.
+enum GenArrayArgMode {
+ kArrayArgModeNone, // don't generate initialization args
+ kArrayArgModeSpanStatic, // generate flatbuffers::span<T,N>
+};
+
// Extension of IDLOptions for cpp-generator.
struct IDLOptionsCpp : public IDLOptions {
// All fields start with 'g_' prefix to distinguish from the base IDLOptions.
CppStandard g_cpp_std; // Base version of C++ standard.
bool g_only_fixed_enums; // Generate underlaying type for all enums.
- // clang-format off
+
IDLOptionsCpp(const IDLOptions &opts)
- : IDLOptions(opts),
- g_cpp_std(CPP_STD_11),
- g_only_fixed_enums(true)
- {}
- // clang-format on
+ : IDLOptions(opts), g_cpp_std(CPP_STD_11), g_only_fixed_enums(true) {}
};
class CppGenerator : public BaseGenerator {
public:
CppGenerator(const Parser &parser, const std::string &path,
const std::string &file_name, IDLOptionsCpp opts)
- : BaseGenerator(parser, path, file_name, "", "::"),
+ : BaseGenerator(parser, path, file_name, "", "::", "h"),
cur_name_space_(nullptr),
opts_(opts),
float_const_gen_("std::numeric_limits<double>::",
void GenIncludeDependencies() {
int num_includes = 0;
- for (auto it = parser_.native_included_files_.begin();
- it != parser_.native_included_files_.end(); ++it) {
- code_ += "#include \"" + *it + "\"";
- num_includes++;
+ if (opts_.generate_object_based_api) {
+ for (auto it = parser_.native_included_files_.begin();
+ it != parser_.native_included_files_.end(); ++it) {
+ code_ += "#include \"" + *it + "\"";
+ num_includes++;
+ }
}
for (auto it = parser_.included_files_.begin();
it != parser_.included_files_.end(); ++it) {
if (it->second.empty()) continue;
auto noext = flatbuffers::StripExtension(it->second);
auto basename = flatbuffers::StripPath(noext);
-
- code_ += "#include \"" + opts_.include_prefix +
- (opts_.keep_include_path ? noext : basename) + "_generated.h\"";
+ auto includeName =
+ GeneratedFileName(opts_.include_prefix,
+ opts_.keep_include_path ? noext : basename, opts_);
+ code_ += "#include \"" + includeName + "\"";
num_includes++;
}
if (num_includes) code_ += "";
code_ += "// Binary schema not generated, no root struct found";
} else {
auto &struct_def = *parser_.root_struct_def_;
- const auto include_guard = GenIncludeGuard(file_name_, *struct_def.defined_namespace, "bfbs");
+ const auto include_guard =
+ GenIncludeGuard(file_name_, *struct_def.defined_namespace, "bfbs");
code_ += "#ifndef " + include_guard;
code_ += "#define " + include_guard;
code_.SetValue("STRUCT_NAME", name);
// Create code to return the binary schema data.
- auto binary_schema_hex_text = BufferToHexText(parser_.builder_.GetBufferPointer(),
- parser_.builder_.GetSize(), 105, " ", "");
+ auto binary_schema_hex_text =
+ BufferToHexText(parser_.builder_.GetBufferPointer(),
+ parser_.builder_.GetSize(), 105, " ", "");
code_ += "struct {{STRUCT_NAME}}BinarySchema {";
code_ += " static const uint8_t *data() {";
code_ += " // Buffer containing the binary schema.";
- code_ += " static const uint8_t bfbsData[" + NumToString(parser_.builder_.GetSize()) + "] = {";
+ code_ += " static const uint8_t bfbsData[" +
+ NumToString(parser_.builder_.GetSize()) + "] = {";
code_ += binary_schema_hex_text;
code_ += " };";
code_ += " return bfbsData;";
}
// We are just adding "_bfbs" to the generated filename.
- const auto file_path = GeneratedFileName(path_, file_name_ + "_bfbs");
+ const auto file_path =
+ GeneratedFileName(path_, file_name_ + "_bfbs", opts_);
const auto final_code = code_.ToString();
return SaveFile(file_path.c_str(), final_code, false);
code_.Clear();
code_ += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
- const auto include_guard = GenIncludeGuard(file_name_, *parser_.current_namespace_);
+ const auto include_guard =
+ GenIncludeGuard(file_name_, *parser_.current_namespace_);
code_ += "#ifndef " + include_guard;
code_ += "#define " + include_guard;
code_ += "";
if (opts_.generate_object_based_api) {
// A convenient root unpack function.
- auto native_name =
- NativeName(WrapInNameSpace(struct_def), &struct_def, opts_);
+ auto native_name = WrapNativeNameInNameSpace(struct_def, opts_);
code_.SetValue("UNPACK_RETURN",
GenTypeNativePtr(native_name, nullptr, false));
code_.SetValue("UNPACK_TYPE",
// Close the include guard.
code_ += "#endif // " + include_guard;
- const auto file_path = GeneratedFileName(path_, file_name_);
+ const auto file_path = GeneratedFileName(path_, file_name_, opts_);
const auto final_code = code_.ToString();
// Save the file and optionally generate the binary schema code.
return SaveFile(file_path.c_str(), final_code, false) &&
- (!parser_.opts.binary_schema_gen_embed || generate_bfbs_embed());
+ (!parser_.opts.binary_schema_gen_embed || generate_bfbs_embed());
}
private:
return false;
}
- bool VectorElementUserFacing(const Type& type) const {
- return opts_.g_cpp_std >= cpp::CPP_STD_17 &&
- opts_.g_only_fixed_enums &&
+ bool VectorElementUserFacing(const Type &type) const {
+ return opts_.g_cpp_std >= cpp::CPP_STD_17 && opts_.g_only_fixed_enums &&
IsEnum(type);
}
return "flatbuffers::String";
}
case BASE_TYPE_VECTOR: {
- const auto type_name = GenTypeWire(type.VectorType(), "",
- VectorElementUserFacing(type.VectorType()));
+ const auto type_name = GenTypeWire(
+ type.VectorType(), "", VectorElementUserFacing(type.VectorType()));
return "flatbuffers::Vector<" + type_name + ">";
}
case BASE_TYPE_STRUCT: {
return WrapInNameSpace(*type.struct_def);
}
case BASE_TYPE_UNION:
- // fall through
+ // fall through
default: {
return "void";
}
: name;
}
+ std::string WrapNativeNameInNameSpace(const StructDef &struct_def,
+ const IDLOptions &opts) {
+ return WrapInNameSpace(struct_def.defined_namespace,
+ NativeName(Name(struct_def), &struct_def, opts));
+ }
+
const std::string &PtrType(const FieldDef *field) {
auto attr = field ? field->attributes.Lookup("cpp_ptr_type") : nullptr;
return attr ? attr->constant : opts_.cpp_object_api_pointer_type;
return ptr_type == "naked" ? "" : ".get()";
}
+ std::string GenOptionalNull() { return "flatbuffers::nullopt"; }
+
+ std::string GenOptionalDecl(const Type &type) {
+ return "flatbuffers::Optional<" + GenTypeBasic(type, true) + ">";
+ }
+
std::string GenTypeNative(const Type &type, bool invector,
const FieldDef &field) {
switch (type.base_type) {
return GenTypeNativePtr(type_name, &field, false);
}
} else {
- return GenTypeNativePtr(NativeName(type_name, type.struct_def, opts_),
- &field, false);
+ return GenTypeNativePtr(
+ WrapNativeNameInNameSpace(*type.struct_def, opts_), &field,
+ false);
}
}
case BASE_TYPE_UNION: {
return type_name + "Union";
}
default: {
- return GenTypeBasic(type, true);
+ return field.IsScalarOptional() ? GenOptionalDecl(type)
+ : GenTypeBasic(type, true);
}
}
}
}
}
+ std::string GenTypeSpan(const Type &type, bool immutable, size_t extent) {
+ // Generate "flatbuffers::span<const U, extent>".
+ FLATBUFFERS_ASSERT(IsSeries(type) && "unexpected type");
+ auto element_type = type.VectorType();
+ std::string text = "flatbuffers::span<";
+ text += immutable ? "const " : "";
+ if (IsScalar(element_type.base_type)) {
+ text += GenTypeBasic(element_type, IsEnum(element_type));
+ } else {
+ switch (element_type.base_type) {
+ case BASE_TYPE_STRING: {
+ text += "char";
+ break;
+ }
+ case BASE_TYPE_STRUCT: {
+ FLATBUFFERS_ASSERT(type.struct_def);
+ text += WrapInNameSpace(*type.struct_def);
+ break;
+ }
+ default:
+ FLATBUFFERS_ASSERT(false && "unexpected element's type");
+ break;
+ }
+ }
+ if (extent != flatbuffers::dynamic_extent) {
+ text += ", ";
+ text += NumToString(extent);
+ }
+ text += "> ";
+ return text;
+ }
+
std::string GenEnumValDecl(const EnumDef &enum_def,
const std::string &enum_val) const {
return opts_.prefixed_enums ? Name(enum_def) + "_" + enum_val : enum_val;
return name.substr(0, name.size() - strlen(UnionTypeFieldSuffix()));
}
- std::string GetUnionElement(const EnumVal &ev, bool wrap, bool actual_type,
- bool native_type = false) {
+ std::string GetUnionElement(const EnumVal &ev, bool native_type,
+ const IDLOptions &opts) {
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
- auto name = actual_type ? ev.union_type.struct_def->name : Name(ev);
- return wrap ? WrapInNameSpace(ev.union_type.struct_def->defined_namespace,
- name)
- : name;
- } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
- return actual_type ? (native_type ? "std::string" : "flatbuffers::String")
- : Name(ev);
+ auto name = ev.union_type.struct_def->name;
+ if (native_type) {
+ name = NativeName(name, ev.union_type.struct_def, opts);
+ }
+ return WrapInNameSpace(ev.union_type.struct_def->defined_namespace, name);
+ } else if (IsString(ev.union_type)) {
+ return native_type ? "std::string" : "flatbuffers::String";
} else {
FLATBUFFERS_ASSERT(false);
return Name(ev);
}
std::string ts;
std::vector<std::string> type_refs;
+ std::vector<uint16_t> array_sizes;
for (auto it = types.begin(); it != types.end(); ++it) {
auto &type = *it;
if (!ts.empty()) ts += ",\n ";
- auto is_vector = type.base_type == BASE_TYPE_VECTOR;
- auto bt = is_vector ? type.element : type.base_type;
+ auto is_vector = IsVector(type);
+ auto is_array = IsArray(type);
+ auto bt = is_vector || is_array ? type.element : type.base_type;
auto et = IsScalar(bt) || bt == BASE_TYPE_STRING
? bt - BASE_TYPE_UTYPE + ET_UTYPE
: ET_SEQUENCE;
type_refs.push_back(ref_name);
}
}
+ if (is_array) { array_sizes.push_back(type.fixed_length); }
ts += "{ flatbuffers::" + std::string(ElementaryTypeNames()[et]) + ", " +
- NumToString(is_vector) + ", " + NumToString(ref_idx) + " }";
+ NumToString(is_vector || is_array) + ", " + NumToString(ref_idx) +
+ " }";
}
std::string rs;
for (auto it = type_refs.begin(); it != type_refs.end(); ++it) {
if (!rs.empty()) rs += ",\n ";
rs += *it + "TypeTable";
}
+ std::string as;
+ for (auto it = array_sizes.begin(); it != array_sizes.end(); ++it) {
+ as += NumToString(*it);
+ as += ", ";
+ }
std::string ns;
for (auto it = names.begin(); it != names.end(); ++it) {
if (!ns.empty()) ns += ",\n ";
}
code_.SetValue("TYPES", ts);
code_.SetValue("REFS", rs);
+ code_.SetValue("ARRAYSIZES", as);
code_.SetValue("NAMES", ns);
code_.SetValue("VALUES", vs);
code_ += "inline const flatbuffers::TypeTable *{{NAME}}TypeTable() {";
code_ += " {{REFS}}";
code_ += " };";
}
+ if (!as.empty()) {
+ code_ += " static const int16_t array_sizes[] = { {{ARRAYSIZES}} };";
+ }
if (!vs.empty()) {
// Problem with uint64_t values greater than 9223372036854775807ULL.
code_ += " static const int64_t values[] = { {{VALUES}} };";
code_ += std::string(" flatbuffers::{{SEQ_TYPE}}, {{NUM_FIELDS}}, ") +
(num_fields ? "type_codes, " : "nullptr, ") +
(!type_refs.empty() ? "type_refs, " : "nullptr, ") +
+ (!as.empty() ? "array_sizes, " : "nullptr, ") +
(!vs.empty() ? "values, " : "nullptr, ") +
(has_names ? "names" : "nullptr");
code_ += " };";
GenComment(enum_def.doc_comment);
code_ +=
(opts_.scoped_enums ? "enum class " : "enum ") + Name(enum_def) + "\\";
- if (opts_.g_only_fixed_enums) {
- code_ += " : {{BASE_TYPE}}\\";
- }
+ if (opts_.g_only_fixed_enums) { code_ += " : {{BASE_TYPE}}\\"; }
code_ += " {";
code_.SetValue("SEP", ",");
if (it == enum_def.Vals().begin()) {
code_ += "template<typename T> struct {{ENUM_NAME}}Traits {";
} else {
- auto name = GetUnionElement(ev, true, true);
+ auto name = GetUnionElement(ev, false, opts_);
code_ += "template<> struct {{ENUM_NAME}}Traits<" + name + "> {";
}
code_ += " {{NAME}}Union({{NAME}}Union&& u) FLATBUFFERS_NOEXCEPT :";
code_ += " type({{NONE}}), value(nullptr)";
code_ += " { std::swap(type, u.type); std::swap(value, u.value); }";
- code_ += " {{NAME}}Union(const {{NAME}}Union &) FLATBUFFERS_NOEXCEPT;";
- code_ +=
- " {{NAME}}Union &operator=(const {{NAME}}Union &u) "
- "FLATBUFFERS_NOEXCEPT";
+ code_ += " {{NAME}}Union(const {{NAME}}Union &);";
+ code_ += " {{NAME}}Union &operator=(const {{NAME}}Union &u)";
code_ +=
" { {{NAME}}Union t(u); std::swap(type, t.type); std::swap(value, "
"t.value); return *this; }";
const auto &ev = **it;
if (ev.IsZero()) { continue; }
- const auto native_type =
- NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_);
+ const auto native_type = GetUnionElement(ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_.SetValue("NATIVE_NAME", Name(ev));
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
const auto &ev = **it;
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
if (ev.IsNonZero()) {
- const auto native_type =
- NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_);
+ const auto native_type = GetUnionElement(ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_ += " case {{NATIVE_ID}}: {";
code_ +=
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
if (ev.IsNonZero()) {
- code_.SetValue("TYPE", GetUnionElement(ev, true, true));
+ code_.SetValue("TYPE", GetUnionElement(ev, false, opts_));
code_ += " case {{LABEL}}: {";
auto getptr =
" auto ptr = reinterpret_cast<const {{TYPE}} *>(obj);";
code_ += getptr;
code_ += " return verifier.VerifyTable(ptr);";
}
- } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
+ } else if (IsString(ev.union_type)) {
code_ += getptr;
code_ += " return verifier.VerifyString(ptr);";
} else {
if (ev.IsZero()) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", GetUnionElement(ev, true, true));
+ code_.SetValue("TYPE", GetUnionElement(ev, false, opts_));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<const {{TYPE}} *>(obj);";
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
} else {
code_ += " return ptr->UnPack(resolver);";
}
- } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
+ } else if (IsString(ev.union_type)) {
code_ += " return new std::string(ptr->c_str(), ptr->size());";
} else {
FLATBUFFERS_ASSERT(false);
if (ev.IsZero()) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_));
- code_.SetValue("NAME", GetUnionElement(ev, false, true));
+ code_.SetValue("TYPE", GetUnionElement(ev, true, opts_));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<const {{TYPE}} *>(value);";
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
if (ev.union_type.struct_def->fixed) {
code_ += " return _fbb.CreateStruct(*ptr).Union();";
} else {
+ code_.SetValue("NAME", ev.union_type.struct_def->name);
code_ +=
" return Create{{NAME}}(_fbb, ptr, _rehasher).Union();";
}
- } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
+ } else if (IsString(ev.union_type)) {
code_ += " return _fbb.CreateString(*ptr).Union();";
} else {
FLATBUFFERS_ASSERT(false);
// Union copy constructor
code_ +=
"inline {{ENUM_NAME}}Union::{{ENUM_NAME}}Union(const "
- "{{ENUM_NAME}}Union &u) FLATBUFFERS_NOEXCEPT : type(u.type), "
- "value(nullptr) {";
+ "{{ENUM_NAME}}Union &u) : type(u.type), value(nullptr) {";
code_ += " switch (type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
if (ev.IsZero()) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_));
+ code_.SetValue("TYPE", GetUnionElement(ev, true, opts_));
code_ += " case {{LABEL}}: {";
bool copyable = true;
- if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
+ if (ev.union_type.base_type == BASE_TYPE_STRUCT &&
+ !ev.union_type.struct_def->fixed) {
// Don't generate code to copy if table is not copyable.
// TODO(wvo): make tables copyable instead.
for (auto fit = ev.union_type.struct_def->fields.vec.begin();
const auto &ev = **it;
if (ev.IsZero()) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_));
+ code_.SetValue("TYPE", GetUnionElement(ev, true, opts_));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<{{TYPE}} *>(value);";
code_ += " delete ptr;";
std::string GenFieldOffsetName(const FieldDef &field) {
std::string uname = Name(field);
- std::transform(uname.begin(), uname.end(), uname.begin(), ToUpper);
+ std::transform(uname.begin(), uname.end(), uname.begin(), CharToUpper);
return "VT_" + uname;
}
}
std::string GetDefaultScalarValue(const FieldDef &field, bool is_ctor) {
- if (field.value.type.enum_def && IsScalar(field.value.type.base_type)) {
- auto ev = field.value.type.enum_def->FindByValue(field.value.constant);
+ const auto &type = field.value.type;
+ if (field.IsScalarOptional()) {
+ return GenOptionalNull();
+ } else if (type.enum_def && IsScalar(type.base_type)) {
+ auto ev = type.enum_def->FindByValue(field.value.constant);
if (ev) {
- return WrapInNameSpace(field.value.type.enum_def->defined_namespace,
- GetEnumValUse(*field.value.type.enum_def, *ev));
+ return WrapInNameSpace(type.enum_def->defined_namespace,
+ GetEnumValUse(*type.enum_def, *ev));
} else {
return GenUnderlyingCast(
- field, true,
- NumToStringCpp(field.value.constant, field.value.type.base_type));
+ field, true, NumToStringCpp(field.value.constant, type.base_type));
}
- } else if (field.value.type.base_type == BASE_TYPE_BOOL) {
+ } else if (type.base_type == BASE_TYPE_BOOL) {
return field.value.constant == "0" ? "false" : "true";
} else if (field.attributes.Lookup("cpp_type")) {
if (is_ctor) {
void GenParam(const FieldDef &field, bool direct, const char *prefix) {
code_.SetValue("PRE", prefix);
code_.SetValue("PARAM_NAME", Name(field));
- if (direct && field.value.type.base_type == BASE_TYPE_STRING) {
+ if (direct && IsString(field.value.type)) {
code_.SetValue("PARAM_TYPE", "const char *");
code_.SetValue("PARAM_VALUE", "nullptr");
- } else if (direct && field.value.type.base_type == BASE_TYPE_VECTOR) {
+ } else if (direct && IsVector(field.value.type)) {
const auto vtype = field.value.type.VectorType();
std::string type;
if (IsStruct(vtype)) {
}
code_.SetValue("PARAM_VALUE", "nullptr");
} else {
- code_.SetValue("PARAM_TYPE", GenTypeWire(field.value.type, " ", true));
+ const auto &type = field.value.type;
code_.SetValue("PARAM_VALUE", GetDefaultScalarValue(field, false));
+ if (field.IsScalarOptional())
+ code_.SetValue("PARAM_TYPE", GenOptionalDecl(type) + " ");
+ else
+ code_.SetValue("PARAM_TYPE", GenTypeWire(type, " ", true));
}
code_ += "{{PRE}}{{PARAM_TYPE}}{{PARAM_NAME}} = {{PARAM_VALUE}}\\";
}
auto cpp_type = field.attributes.Lookup("cpp_type");
auto full_type =
(cpp_type
- ? (field.value.type.base_type == BASE_TYPE_VECTOR
+ ? (IsVector(field.value.type)
? "std::vector<" +
GenTypeNativePtr(cpp_type->constant, &field,
false) +
"> "
: GenTypeNativePtr(cpp_type->constant, &field, false))
: type + " ");
+ // Generate default member initializers for >= C++11.
+ std::string field_di = "";
+ if (opts_.g_cpp_std >= cpp::CPP_STD_11) {
+ field_di = "{}";
+ auto native_default = field.attributes.Lookup("native_default");
+ // Scalar types get parsed defaults, raw pointers get nullptrs.
+ if (IsScalar(field.value.type.base_type)) {
+ field_di =
+ " = " + (native_default ? std::string(native_default->constant)
+ : GetDefaultScalarValue(field, true));
+ } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
+ if (IsStruct(field.value.type) && native_default) {
+ field_di = " = " + native_default->constant;
+ }
+ }
+ }
code_.SetValue("FIELD_TYPE", full_type);
code_.SetValue("FIELD_NAME", Name(field));
- code_ += " {{FIELD_TYPE}}{{FIELD_NAME}};";
+ code_.SetValue("FIELD_DI", field_di);
+ code_ += " {{FIELD_TYPE}}{{FIELD_NAME}}{{FIELD_DI}};";
}
}
// Generate the default constructor for this struct. Properly initialize all
// scalar members with default values.
void GenDefaultConstructor(const StructDef &struct_def) {
+ code_.SetValue("NATIVE_NAME",
+ NativeName(Name(struct_def), &struct_def, opts_));
+ // In >= C++11, default member initializers are generated.
+ if (opts_.g_cpp_std >= cpp::CPP_STD_11) { return; }
std::string initializer_list;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
initializer_list = "\n : " + initializer_list;
}
- code_.SetValue("NATIVE_NAME",
- NativeName(Name(struct_def), &struct_def, opts_));
code_.SetValue("INIT_LIST", initializer_list);
code_ += " {{NATIVE_NAME}}(){{INIT_LIST}} {";
void GenVerifyCall(const FieldDef &field, const char *prefix) {
code_.SetValue("PRE", prefix);
code_.SetValue("NAME", Name(field));
- code_.SetValue("REQUIRED", field.required ? "Required" : "");
+ code_.SetValue("REQUIRED", field.IsRequired() ? "Required" : "");
code_.SetValue("SIZE", GenTypeSize(field.value.type));
code_.SetValue("OFFSET", GenFieldOffsetName(field));
if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type)) {
// Generate CompareWithValue method for a key field.
void GenKeyFieldMethods(const FieldDef &field) {
FLATBUFFERS_ASSERT(field.key);
- const bool is_string = (field.value.type.base_type == BASE_TYPE_STRING);
+ const bool is_string = (IsString(field.value.type));
code_ += " bool KeyCompareLessThan(const {{STRUCT_NAME}} *o) const {";
if (is_string) {
}
}
+ void GenTableUnionAsGetters(const FieldDef &field) {
+ const auto &type = field.value.type;
+ auto u = type.enum_def;
+
+ if (!type.enum_def->uses_multiple_type_instances)
+ code_ +=
+ " template<typename T> "
+ "const T *{{NULLABLE_EXT}}{{FIELD_NAME}}_as() const;";
+
+ for (auto u_it = u->Vals().begin(); u_it != u->Vals().end(); ++u_it) {
+ auto &ev = **u_it;
+ if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ auto full_struct_name = GetUnionElement(ev, false, opts_);
+
+ // @TODO: Mby make this decisions more universal? How?
+ code_.SetValue("U_GET_TYPE",
+ EscapeKeyword(field.name + UnionTypeFieldSuffix()));
+ code_.SetValue("U_ELEMENT_TYPE", WrapInNameSpace(u->defined_namespace,
+ GetEnumValUse(*u, ev)));
+ code_.SetValue("U_FIELD_TYPE", "const " + full_struct_name + " *");
+ code_.SetValue("U_FIELD_NAME", Name(field) + "_as_" + Name(ev));
+ code_.SetValue("U_NULLABLE", NullableExtension());
+
+ // `const Type *union_name_asType() const` accessor.
+ code_ += " {{U_FIELD_TYPE}}{{U_NULLABLE}}{{U_FIELD_NAME}}() const {";
+ code_ +=
+ " return {{U_GET_TYPE}}() == {{U_ELEMENT_TYPE}} ? "
+ "static_cast<{{U_FIELD_TYPE}}>({{FIELD_NAME}}()) "
+ ": nullptr;";
+ code_ += " }";
+ }
+ }
+
+ void GenTableFieldGetter(const FieldDef &field) {
+ const auto &type = field.value.type;
+ const auto offset_str = GenFieldOffsetName(field);
+
+ GenComment(field.doc_comment, " ");
+ // Call a different accessor for pointers, that indirects.
+ if (false == field.IsScalarOptional()) {
+ const bool is_scalar = IsScalar(type.base_type);
+ std::string accessor;
+ if (is_scalar)
+ accessor = "GetField<";
+ else if (IsStruct(type))
+ accessor = "GetStruct<";
+ else
+ accessor = "GetPointer<";
+ auto offset_type = GenTypeGet(type, "", "const ", " *", false);
+ auto call = accessor + offset_type + ">(" + offset_str;
+ // Default value as second arg for non-pointer types.
+ if (is_scalar) { call += ", " + GenDefaultConstant(field); }
+ call += ")";
+
+ std::string afterptr = " *" + NullableExtension();
+ code_.SetValue("FIELD_TYPE",
+ GenTypeGet(type, " ", "const ", afterptr.c_str(), true));
+ code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, call));
+ code_.SetValue("NULLABLE_EXT", NullableExtension());
+ code_ += " {{FIELD_TYPE}}{{FIELD_NAME}}() const {";
+ code_ += " return {{FIELD_VALUE}};";
+ code_ += " }";
+ } else {
+ auto wire_type = GenTypeBasic(type, false);
+ auto face_type = GenTypeBasic(type, true);
+ auto opt_value = "GetOptional<" + wire_type + ", " + face_type + ">(" +
+ offset_str + ")";
+ code_.SetValue("FIELD_TYPE", GenOptionalDecl(type));
+ code_ += " {{FIELD_TYPE}} {{FIELD_NAME}}() const {";
+ code_ += " return " + opt_value + ";";
+ code_ += " }";
+ }
+
+ if (type.base_type == BASE_TYPE_UNION) { GenTableUnionAsGetters(field); }
+ }
+
+ void GenTableFieldType(const FieldDef &field) {
+ const auto &type = field.value.type;
+ const auto offset_str = GenFieldOffsetName(field);
+ if (!field.IsScalarOptional()) {
+ std::string afterptr = " *" + NullableExtension();
+ code_.SetValue("FIELD_TYPE",
+ GenTypeGet(type, "", "const ", afterptr.c_str(), true));
+ code_ += " {{FIELD_TYPE}}\\";
+ } else {
+ code_.SetValue("FIELD_TYPE", GenOptionalDecl(type));
+ code_ += " {{FIELD_TYPE}}\\";
+ }
+ }
+
+ void GenStructFieldType(const FieldDef &field) {
+ const auto is_array = IsArray(field.value.type);
+ std::string field_type =
+ GenTypeGet(field.value.type, "", is_array ? "" : "const ",
+ is_array ? "" : " &", true);
+ code_.SetValue("FIELD_TYPE", field_type);
+ code_ += " {{FIELD_TYPE}}\\";
+ }
+
+ void GenFieldTypeHelper(const StructDef &struct_def) {
+ if (struct_def.fields.vec.empty()) { return; }
+ code_ += " template<size_t Index>";
+ code_ += " using FieldType = \\";
+ code_ += "decltype(std::declval<type>().get_field<Index>());";
+ }
+
+ void GenIndexBasedFieldGetter(const StructDef &struct_def) {
+ if (struct_def.fields.vec.empty()) { return; }
+ code_ += " template<size_t Index>";
+ code_ += " auto get_field() const {";
+
+ size_t index = 0;
+ bool need_else = false;
+ // Generate one index-based getter for each field.
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ if (field.deprecated) {
+ // Deprecated fields won't be accessible.
+ continue;
+ }
+ code_.SetValue("FIELD_NAME", Name(field));
+ code_.SetValue("FIELD_INDEX",
+ std::to_string(static_cast<long long>(index++)));
+ if (need_else) {
+ code_ += " else \\";
+ } else {
+ code_ += " \\";
+ }
+ need_else = true;
+ code_ += "if constexpr (Index == {{FIELD_INDEX}}) \\";
+ code_ += "return {{FIELD_NAME}}();";
+ }
+ code_ += " else static_assert(Index != Index, \"Invalid Field Index\");";
+ code_ += " }";
+ }
+
+ // Sample for Vec3:
+ //
+ // static constexpr std::array<const char *, 3> field_names = {
+ // "x",
+ // "y",
+ // "z"
+ // };
+ //
+ void GenFieldNames(const StructDef &struct_def) {
+ auto non_deprecated_field_count = std::count_if(
+ struct_def.fields.vec.begin(), struct_def.fields.vec.end(),
+ [](const FieldDef *field) { return !field->deprecated; });
+ code_ += " static constexpr std::array<\\";
+ code_.SetValue(
+ "FIELD_COUNT",
+ std::to_string(static_cast<long long>(non_deprecated_field_count)));
+ code_ += "const char *, {{FIELD_COUNT}}> field_names = {\\";
+ if (struct_def.fields.vec.empty()) {
+ code_ += "};";
+ return;
+ }
+ code_ += "";
+ // Generate the field_names elements.
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ if (field.deprecated) {
+ // Deprecated fields won't be accessible.
+ continue;
+ }
+ code_.SetValue("FIELD_NAME", Name(field));
+ code_ += " \"{{FIELD_NAME}}\"\\";
+ if (it + 1 != struct_def.fields.vec.end()) { code_ += ","; }
+ }
+ code_ += "\n };";
+ }
+
+ void GenFieldsNumber(const StructDef &struct_def) {
+ auto non_deprecated_field_count = std::count_if(
+ struct_def.fields.vec.begin(), struct_def.fields.vec.end(),
+ [](const FieldDef *field) { return !field->deprecated; });
+ code_.SetValue(
+ "FIELD_COUNT",
+ std::to_string(static_cast<long long>(non_deprecated_field_count)));
+ code_ += " static constexpr size_t fields_number = {{FIELD_COUNT}};";
+ }
+
+ void GenTraitsStruct(const StructDef &struct_def) {
+ code_.SetValue(
+ "FULLY_QUALIFIED_NAME",
+ struct_def.defined_namespace->GetFullyQualifiedName(Name(struct_def)));
+ code_ += "struct {{STRUCT_NAME}}::Traits {";
+ code_ += " using type = {{STRUCT_NAME}};";
+ if (!struct_def.fixed) {
+ // We have a table and not a struct.
+ code_ += " static auto constexpr Create = Create{{STRUCT_NAME}};";
+ }
+ if (opts_.cpp_static_reflection) {
+ code_ += " static constexpr auto name = \"{{STRUCT_NAME}}\";";
+ code_ +=
+ " static constexpr auto fully_qualified_name = "
+ "\"{{FULLY_QUALIFIED_NAME}}\";";
+ GenFieldNames(struct_def);
+ GenFieldTypeHelper(struct_def);
+ GenFieldsNumber(struct_def);
+ }
+ code_ += "};";
+ code_ += "";
+ }
+
+ void GenTableFieldSetter(const FieldDef &field) {
+ const auto &type = field.value.type;
+ const bool is_scalar = IsScalar(type.base_type);
+ if (is_scalar && IsUnion(type))
+ return; // changing of a union's type is forbidden
+
+ auto offset_str = GenFieldOffsetName(field);
+ if (is_scalar) {
+ const auto wire_type = GenTypeWire(type, "", false);
+ code_.SetValue("SET_FN", "SetField<" + wire_type + ">");
+ code_.SetValue("OFFSET_NAME", offset_str);
+ code_.SetValue("FIELD_TYPE", GenTypeBasic(type, true));
+ code_.SetValue("FIELD_VALUE",
+ GenUnderlyingCast(field, false, "_" + Name(field)));
+
+ code_ +=
+ " bool mutate_{{FIELD_NAME}}({{FIELD_TYPE}} "
+ "_{{FIELD_NAME}}) {";
+ if (false == field.IsScalarOptional()) {
+ code_.SetValue("DEFAULT_VALUE", GenDefaultConstant(field));
+ code_ +=
+ " return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}}, "
+ "{{DEFAULT_VALUE}});";
+ } else {
+ code_ += " return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}});";
+ }
+ code_ += " }";
+ } else {
+ auto postptr = " *" + NullableExtension();
+ auto wire_type = GenTypeGet(type, " ", "", postptr.c_str(), true);
+ std::string accessor = IsStruct(type) ? "GetStruct<" : "GetPointer<";
+ auto underlying = accessor + wire_type + ">(" + offset_str + ")";
+ code_.SetValue("FIELD_TYPE", wire_type);
+ code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, underlying));
+
+ code_ += " {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
+ code_ += " return {{FIELD_VALUE}};";
+ code_ += " }";
+ }
+ }
+
// Generate an accessor struct, builder structs & function for a table.
void GenTable(const StructDef &struct_def) {
if (opts_.generate_object_based_api) { GenNativeTable(struct_def); }
code_ += " typedef {{NATIVE_NAME}} NativeTableType;";
}
code_ += " typedef {{STRUCT_NAME}}Builder Builder;";
- if (opts_.g_cpp_std >= cpp::CPP_STD_17) {
- code_ += " struct Traits;";
- }
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) { code_ += " struct Traits;"; }
if (opts_.mini_reflect != IDLOptions::kNone) {
code_ +=
" static const flatbuffers::TypeTable *MiniReflectTypeTable() {";
continue;
}
- const bool is_struct = IsStruct(field.value.type);
- const bool is_scalar = IsScalar(field.value.type.base_type);
code_.SetValue("FIELD_NAME", Name(field));
-
- // Call a different accessor for pointers, that indirects.
- std::string accessor = "";
- if (is_scalar) {
- accessor = "GetField<";
- } else if (is_struct) {
- accessor = "GetStruct<";
- } else {
- accessor = "GetPointer<";
- }
- auto offset_str = GenFieldOffsetName(field);
- auto offset_type =
- GenTypeGet(field.value.type, "", "const ", " *", false);
-
- auto call = accessor + offset_type + ">(" + offset_str;
- // Default value as second arg for non-pointer types.
- if (is_scalar) { call += ", " + GenDefaultConstant(field); }
- call += ")";
-
- std::string afterptr = " *" + NullableExtension();
- GenComment(field.doc_comment, " ");
- code_.SetValue("FIELD_TYPE", GenTypeGet(field.value.type, " ", "const ",
- afterptr.c_str(), true));
- code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, call));
- code_.SetValue("NULLABLE_EXT", NullableExtension());
-
- code_ += " {{FIELD_TYPE}}{{FIELD_NAME}}() const {";
- code_ += " return {{FIELD_VALUE}};";
- code_ += " }";
-
- if (field.value.type.base_type == BASE_TYPE_UNION) {
- auto u = field.value.type.enum_def;
-
- if (!field.value.type.enum_def->uses_multiple_type_instances)
- code_ +=
- " template<typename T> "
- "const T *{{NULLABLE_EXT}}{{FIELD_NAME}}_as() const;";
-
- for (auto u_it = u->Vals().begin(); u_it != u->Vals().end(); ++u_it) {
- auto &ev = **u_it;
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
- auto full_struct_name = GetUnionElement(ev, true, true);
-
- // @TODO: Mby make this decisions more universal? How?
- code_.SetValue("U_GET_TYPE",
- EscapeKeyword(field.name + UnionTypeFieldSuffix()));
- code_.SetValue(
- "U_ELEMENT_TYPE",
- WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev)));
- code_.SetValue("U_FIELD_TYPE", "const " + full_struct_name + " *");
- code_.SetValue("U_FIELD_NAME", Name(field) + "_as_" + Name(ev));
- code_.SetValue("U_NULLABLE", NullableExtension());
-
- // `const Type *union_name_asType() const` accessor.
- code_ += " {{U_FIELD_TYPE}}{{U_NULLABLE}}{{U_FIELD_NAME}}() const {";
- code_ +=
- " return {{U_GET_TYPE}}() == {{U_ELEMENT_TYPE}} ? "
- "static_cast<{{U_FIELD_TYPE}}>({{FIELD_NAME}}()) "
- ": nullptr;";
- code_ += " }";
- }
- }
-
- if (opts_.mutable_buffer && !(is_scalar && IsUnion(field.value.type))) {
- if (is_scalar) {
- const auto type = GenTypeWire(field.value.type, "", false);
- code_.SetValue("SET_FN", "SetField<" + type + ">");
- code_.SetValue("OFFSET_NAME", offset_str);
- code_.SetValue("FIELD_TYPE", GenTypeBasic(field.value.type, true));
- code_.SetValue("FIELD_VALUE",
- GenUnderlyingCast(field, false, "_" + Name(field)));
- code_.SetValue("DEFAULT_VALUE", GenDefaultConstant(field));
-
- code_ +=
- " bool mutate_{{FIELD_NAME}}({{FIELD_TYPE}} "
- "_{{FIELD_NAME}}) {";
- code_ +=
- " return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}}, "
- "{{DEFAULT_VALUE}});";
- code_ += " }";
- } else {
- auto postptr = " *" + NullableExtension();
- auto type =
- GenTypeGet(field.value.type, " ", "", postptr.c_str(), true);
- auto underlying = accessor + type + ">(" + offset_str + ")";
- code_.SetValue("FIELD_TYPE", type);
- code_.SetValue("FIELD_VALUE",
- GenUnderlyingCast(field, true, underlying));
-
- code_ += " {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
- code_ += " return {{FIELD_VALUE}};";
- code_ += " }";
- }
- }
+ GenTableFieldGetter(field);
+ if (opts_.mutable_buffer) { GenTableFieldSetter(field); }
auto nested = field.attributes.Lookup("nested_flatbuffer");
if (nested) {
if (field.key) { GenKeyFieldMethods(field); }
}
+ if (opts_.cpp_static_reflection) { GenIndexBasedFieldGetter(struct_def); }
+
// Generate a verifier function that can check a buffer from an untrusted
// source will never cause reads outside the buffer.
code_ += " bool Verify(flatbuffers::Verifier &verifier) const {";
auto &ev = **u_it;
if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
- auto full_struct_name = GetUnionElement(ev, true, true);
+ auto full_struct_name = GetUnionElement(ev, false, opts_);
code_.SetValue(
"U_ELEMENT_TYPE",
}
}
+ // Generate code to force vector alignment. Return empty string for vector
+ // that doesn't need alignment code.
+ std::string GenVectorForceAlign(const FieldDef &field,
+ const std::string &field_size) {
+ FLATBUFFERS_ASSERT(IsVector(field.value.type));
+ // Get the value of the force_align attribute.
+ const auto *force_align = field.attributes.Lookup("force_align");
+ const int align = force_align ? atoi(force_align->constant.c_str()) : 1;
+ // Generate code to do force_align for the vector.
+ if (align > 1) {
+ const auto vtype = field.value.type.VectorType();
+ const auto type = IsStruct(vtype) ? WrapInNameSpace(*vtype.struct_def)
+ : GenTypeWire(vtype, "", false);
+ return "_fbb.ForceVectorAlignment(" + field_size + ", sizeof(" + type +
+ "), " + std::to_string(static_cast<long long>(align)) + ");";
+ }
+ return "";
+ }
+
void GenBuilders(const StructDef &struct_def) {
code_.SetValue("STRUCT_NAME", Name(struct_def));
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (!field.deprecated) {
- const bool is_scalar = IsScalar(field.value.type.base_type);
- const bool is_string = field.value.type.base_type == BASE_TYPE_STRING;
- const bool is_vector = field.value.type.base_type == BASE_TYPE_VECTOR;
- if (is_string || is_vector) { has_string_or_vector_fields = true; }
-
- std::string offset = GenFieldOffsetName(field);
- std::string name = GenUnderlyingCast(field, false, Name(field));
- std::string value = is_scalar ? GenDefaultConstant(field) : "";
-
- // Generate accessor functions of the form:
- // void add_name(type name) {
- // fbb_.AddElement<type>(offset, name, default);
- // }
- code_.SetValue("FIELD_NAME", Name(field));
- code_.SetValue("FIELD_TYPE", GenTypeWire(field.value.type, " ", true));
- code_.SetValue("ADD_OFFSET", Name(struct_def) + "::" + offset);
- code_.SetValue("ADD_NAME", name);
- code_.SetValue("ADD_VALUE", value);
- if (is_scalar) {
- const auto type = GenTypeWire(field.value.type, "", false);
- code_.SetValue("ADD_FN", "AddElement<" + type + ">");
- } else if (IsStruct(field.value.type)) {
- code_.SetValue("ADD_FN", "AddStruct");
- } else {
- code_.SetValue("ADD_FN", "AddOffset");
- }
+ if (field.deprecated) continue;
+ const bool is_scalar = IsScalar(field.value.type.base_type);
+ const bool is_default_scalar = is_scalar && !field.IsScalarOptional();
+ const bool is_string = IsString(field.value.type);
+ const bool is_vector = IsVector(field.value.type);
+ if (is_string || is_vector) { has_string_or_vector_fields = true; }
+
+ std::string offset = GenFieldOffsetName(field);
+ std::string name = GenUnderlyingCast(field, false, Name(field));
+ std::string value = is_default_scalar ? GenDefaultConstant(field) : "";
+
+ // Generate accessor functions of the form:
+ // void add_name(type name) {
+ // fbb_.AddElement<type>(offset, name, default);
+ // }
+ code_.SetValue("FIELD_NAME", Name(field));
+ code_.SetValue("FIELD_TYPE", GenTypeWire(field.value.type, " ", true));
+ code_.SetValue("ADD_OFFSET", Name(struct_def) + "::" + offset);
+ code_.SetValue("ADD_NAME", name);
+ code_.SetValue("ADD_VALUE", value);
+ if (is_scalar) {
+ const auto type = GenTypeWire(field.value.type, "", false);
+ code_.SetValue("ADD_FN", "AddElement<" + type + ">");
+ } else if (IsStruct(field.value.type)) {
+ code_.SetValue("ADD_FN", "AddStruct");
+ } else {
+ code_.SetValue("ADD_FN", "AddOffset");
+ }
- code_ += " void add_{{FIELD_NAME}}({{FIELD_TYPE}}{{FIELD_NAME}}) {";
- code_ += " fbb_.{{ADD_FN}}(\\";
- if (is_scalar) {
- code_ += "{{ADD_OFFSET}}, {{ADD_NAME}}, {{ADD_VALUE}});";
- } else {
- code_ += "{{ADD_OFFSET}}, {{ADD_NAME}});";
- }
- code_ += " }";
+ code_ += " void add_{{FIELD_NAME}}({{FIELD_TYPE}}{{FIELD_NAME}}) {";
+ code_ += " fbb_.{{ADD_FN}}(\\";
+ if (is_default_scalar) {
+ code_ += "{{ADD_OFFSET}}, {{ADD_NAME}}, {{ADD_VALUE}});";
+ } else {
+ code_ += "{{ADD_OFFSET}}, {{ADD_NAME}});";
}
+ code_ += " }";
}
// Builder constructor
code_ += " start_ = fbb_.StartTable();";
code_ += " }";
- // Assignment operator;
- code_ +=
- " {{STRUCT_NAME}}Builder &operator="
- "(const {{STRUCT_NAME}}Builder &);";
-
// Finish() function.
code_ += " flatbuffers::Offset<{{STRUCT_NAME}}> Finish() {";
code_ += " const auto end = fbb_.EndTable(start_);";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (!field.deprecated && field.required) {
+ if (!field.deprecated && field.IsRequired()) {
code_.SetValue("FIELD_NAME", Name(field));
code_.SetValue("OFFSET_NAME", GenFieldOffsetName(field));
code_ += " fbb_.Required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}});";
if (!field.deprecated && (!struct_def.sortbysize ||
size == SizeOf(field.value.type.base_type))) {
code_.SetValue("FIELD_NAME", Name(field));
- code_ += " builder_.add_{{FIELD_NAME}}({{FIELD_NAME}});";
+ if (field.IsScalarOptional()) {
+ code_ +=
+ " if({{FIELD_NAME}}) { "
+ "builder_.add_{{FIELD_NAME}}(*{{FIELD_NAME}}); }";
+ } else {
+ code_ += " builder_.add_{{FIELD_NAME}}({{FIELD_NAME}});";
+ }
}
}
}
// Definition for type traits for this table type. This allows querying var-
// ious compile-time traits of the table.
- if (opts_.g_cpp_std >= cpp::CPP_STD_17) {
- code_ += "struct {{STRUCT_NAME}}::Traits {";
- code_ += " using type = {{STRUCT_NAME}};";
- code_ += " static auto constexpr Create = Create{{STRUCT_NAME}};";
- code_ += "};";
- code_ += "";
- }
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) { GenTraitsStruct(struct_def); }
// Generate a CreateXDirect function with vector types as parameters
- if (has_string_or_vector_fields) {
+ if (opts_.cpp_direct_copy && has_string_or_vector_fields) {
code_ +=
"inline flatbuffers::Offset<{{STRUCT_NAME}}> "
"Create{{STRUCT_NAME}}Direct(";
const auto &field = **it;
if (!field.deprecated) {
code_.SetValue("FIELD_NAME", Name(field));
- if (field.value.type.base_type == BASE_TYPE_STRING) {
+ if (IsString(field.value.type)) {
if (!field.shared) {
code_.SetValue("CREATE_STRING", "CreateString");
} else {
code_ +=
" auto {{FIELD_NAME}}__ = {{FIELD_NAME}} ? "
"_fbb.{{CREATE_STRING}}({{FIELD_NAME}}) : 0;";
- } else if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ } else if (IsVector(field.value.type)) {
+ const std::string force_align_code =
+ GenVectorForceAlign(field, Name(field) + "->size()");
+ if (!force_align_code.empty()) {
+ code_ += " if ({{FIELD_NAME}}) { " + force_align_code + " }";
+ }
code_ += " auto {{FIELD_NAME}}__ = {{FIELD_NAME}} ? \\";
const auto vtype = field.value.type.VectorType();
const auto has_key = TypeHasKey(vtype);
const auto type = WrapInNameSpace(*vtype.struct_def);
code_ += "_fbb.CreateVectorOfSortedTables<" + type + ">\\";
} else {
- const auto type = GenTypeWire(
- vtype, "", VectorElementUserFacing(vtype));
+ const auto type =
+ GenTypeWire(vtype, "", VectorElementUserFacing(vtype));
code_ += "_fbb.CreateVector<" + type + ">\\";
}
code_ +=
if (!field.deprecated) {
code_.SetValue("FIELD_NAME", Name(field));
code_ += ",\n {{FIELD_NAME}}\\";
- if (field.value.type.base_type == BASE_TYPE_STRING ||
- field.value.type.base_type == BASE_TYPE_VECTOR) {
+ if (IsString(field.value.type) || IsVector(field.value.type)) {
code_ += "__\\";
}
}
const char *vec_elem_access,
const char *vec_type_access) {
auto type_name = WrapInNameSpace(*afield.value.type.enum_def);
- return type_name + "Union::UnPack(" + "_e" +
- vec_elem_access + ", " +
+ return type_name + "Union::UnPack(" + "_e" + vec_elem_access + ", " +
EscapeKeyword(afield.name + UnionTypeFieldSuffix()) + "()" +
vec_type_access + ", _resolver)";
}
}
}
case BASE_TYPE_STRUCT: {
- const auto name = WrapInNameSpace(*type.struct_def);
if (IsStruct(type)) {
- auto native_type = type.struct_def->attributes.Lookup("native_type");
+ const auto &struct_attrs = type.struct_def->attributes;
+ const auto native_type = struct_attrs.Lookup("native_type");
if (native_type) {
- return "flatbuffers::UnPack(*" + val + ")";
+ std::string unpack_call = "flatbuffers::UnPack";
+ const auto pack_name = struct_attrs.Lookup("native_type_pack_name");
+ if (pack_name) { unpack_call += pack_name->constant; }
+ unpack_call += "(*" + val + ")";
+ return unpack_call;
} else if (invector || afield.native_inline) {
return "*" + val;
} else {
+ const auto name = WrapInNameSpace(*type.struct_def);
const auto ptype = GenTypeNativePtr(name, &afield, true);
return ptype + "(new " + name + "(*" + val + "))";
}
} else {
const auto ptype = GenTypeNativePtr(
- NativeName(name, type.struct_def, opts_), &afield, true);
+ WrapNativeNameInNameSpace(*type.struct_def, opts_), &afield,
+ true);
return ptype + "(" + val + "->UnPack(_resolver))";
}
}
std::string code;
switch (field.value.type.base_type) {
case BASE_TYPE_VECTOR: {
- auto cpp_type = field.attributes.Lookup("cpp_type");
- std::string indexing;
- if (field.value.type.enum_def) {
- indexing += "static_cast<" +
- WrapInNameSpace(*field.value.type.enum_def) + ">(";
- }
- indexing += "_e->Get(_i)";
- if (field.value.type.enum_def) { indexing += ")"; }
- if (field.value.type.element == BASE_TYPE_BOOL) { indexing += " != 0"; }
-
- // Generate code that pushes data from _e to _o in the form:
- // for (uoffset_t i = 0; i < _e->size(); ++i) {
- // _o->field.push_back(_e->Get(_i));
- // }
auto name = Name(field);
if (field.value.type.element == BASE_TYPE_UTYPE) {
name = StripUnionType(Name(field));
}
- auto access =
- field.value.type.element == BASE_TYPE_UTYPE
- ? ".type"
- : (field.value.type.element == BASE_TYPE_UNION ? ".value" : "");
code += "{ _o->" + name + ".resize(_e->size()); ";
- code += "for (flatbuffers::uoffset_t _i = 0;";
- code += " _i < _e->size(); _i++) { ";
- if (cpp_type) {
- // Generate code that resolves the cpp pointer type, of the form:
- // if (resolver)
- // (*resolver)(&_o->field, (hash_value_t)(_e));
- // else
- // _o->field = nullptr;
- code += "//vector resolver, " + PtrType(&field) + "\n";
- code += "if (_resolver) ";
- code += "(*_resolver)";
- code += "(reinterpret_cast<void **>(&_o->" + name + "[_i]" + access +
- "), ";
- code += "static_cast<flatbuffers::hash_value_t>(" + indexing + "));";
- if (PtrType(&field) == "naked") {
- code += " else ";
- code += "_o->" + name + "[_i]" + access + " = nullptr";
+ if (!field.value.type.enum_def && !IsBool(field.value.type.element) &&
+ IsOneByte(field.value.type.element)) {
+ // For vectors of bytes, std::copy is used to improve performance.
+ // This doesn't work for:
+ // - enum types because they have to be explicitly static_cast.
+ // - vectors of bool, since they are a template specialization.
+ // - multiple-byte types due to endianness.
+ code +=
+ "std::copy(_e->begin(), _e->end(), _o->" + name + ".begin()); }";
+ } else {
+ std::string indexing;
+ if (field.value.type.enum_def) {
+ indexing += "static_cast<" +
+ WrapInNameSpace(*field.value.type.enum_def) + ">(";
+ }
+ indexing += "_e->Get(_i)";
+ if (field.value.type.enum_def) { indexing += ")"; }
+ if (field.value.type.element == BASE_TYPE_BOOL) {
+ indexing += " != 0";
+ }
+ // Generate code that pushes data from _e to _o in the form:
+ // for (uoffset_t i = 0; i < _e->size(); ++i) {
+ // _o->field.push_back(_e->Get(_i));
+ // }
+ auto access =
+ field.value.type.element == BASE_TYPE_UTYPE
+ ? ".type"
+ : (field.value.type.element == BASE_TYPE_UNION ? ".value"
+ : "");
+
+ code += "for (flatbuffers::uoffset_t _i = 0;";
+ code += " _i < _e->size(); _i++) { ";
+ auto cpp_type = field.attributes.Lookup("cpp_type");
+ if (cpp_type) {
+ // Generate code that resolves the cpp pointer type, of the form:
+ // if (resolver)
+ // (*resolver)(&_o->field, (hash_value_t)(_e));
+ // else
+ // _o->field = nullptr;
+ code += "//vector resolver, " + PtrType(&field) + "\n";
+ code += "if (_resolver) ";
+ code += "(*_resolver)";
+ code += "(reinterpret_cast<void **>(&_o->" + name + "[_i]" +
+ access + "), ";
+ code +=
+ "static_cast<flatbuffers::hash_value_t>(" + indexing + "));";
+ if (PtrType(&field) == "naked") {
+ code += " else ";
+ code += "_o->" + name + "[_i]" + access + " = nullptr";
+ } else {
+ // code += " else ";
+ // code += "_o->" + name + "[_i]" + access + " = " +
+ // GenTypeNativePtr(cpp_type->constant, &field, true) + "();";
+ code += "/* else do nothing */";
+ }
} else {
- // code += " else ";
- // code += "_o->" + name + "[_i]" + access + " = " +
- // GenTypeNativePtr(cpp_type->constant, &field, true) + "();";
- code += "/* else do nothing */";
+ code += "_o->" + name + "[_i]" + access + " = ";
+ code += GenUnpackVal(field.value.type.VectorType(), indexing, true,
+ field);
}
- } else {
- code += "_o->" + name + "[_i]" + access + " = ";
- code += GenUnpackVal(field.value.type.VectorType(), indexing, true,
- field);
+ code += "; } }";
}
- code += "; } }";
break;
}
case BASE_TYPE_UTYPE: {
// For optional fields, check to see if there actually is any data
// in _o->field before attempting to access it. If there isn't,
- // depending on set_empty_strings_to_null either set it to 0 or an empty string.
- if (!field.required) {
- auto empty_value =
- opts_.set_empty_strings_to_null ? "0" : "_fbb.CreateSharedString(\"\")";
+ // depending on set_empty_strings_to_null either set it to 0 or an empty
+ // string.
+ if (!field.IsRequired()) {
+ auto empty_value = opts_.set_empty_strings_to_null
+ ? "0"
+ : "_fbb.CreateSharedString(\"\")";
code = value + ".empty() ? " + empty_value + " : " + code;
}
break;
}
- // Vector fields come in several flavours, of the forms:
- // _fbb.CreateVector(_o->field);
- // _fbb.CreateVector((const utype*)_o->field.data(), _o->field.size());
- // _fbb.CreateVectorOfStrings(_o->field)
- // _fbb.CreateVectorOfStructs(_o->field)
- // _fbb.CreateVector<Offset<T>>(_o->field.size() [&](size_t i) {
- // return CreateT(_fbb, _o->Get(i), rehasher);
- // });
+ // Vector fields come in several flavours, of the forms:
+ // _fbb.CreateVector(_o->field);
+ // _fbb.CreateVector((const utype*)_o->field.data(),
+ // _o->field.size()); _fbb.CreateVectorOfStrings(_o->field)
+ // _fbb.CreateVectorOfStructs(_o->field)
+ // _fbb.CreateVector<Offset<T>>(_o->field.size() [&](size_t i) {
+ // return CreateT(_fbb, _o->Get(i), rehasher);
+ // });
case BASE_TYPE_VECTOR: {
auto vector_type = field.value.type.VectorType();
switch (vector_type.base_type) {
}
case BASE_TYPE_STRUCT: {
if (IsStruct(vector_type)) {
- auto native_type =
- field.value.type.struct_def->attributes.Lookup("native_type");
+ const auto &struct_attrs =
+ field.value.type.struct_def->attributes;
+ const auto native_type = struct_attrs.Lookup("native_type");
if (native_type) {
code += "_fbb.CreateVectorOfNativeStructs<";
- code += WrapInNameSpace(*vector_type.struct_def) + ">";
+ code += WrapInNameSpace(*vector_type.struct_def) + ", " +
+ native_type->constant + ">";
+ code += "(" + value;
+ const auto pack_name =
+ struct_attrs.Lookup("native_type_pack_name");
+ if (pack_name) {
+ code += ", flatbuffers::Pack" + pack_name->constant;
+ }
+ code += ")";
} else {
code += "_fbb.CreateVectorOfStructs";
+ code += "(" + value + ")";
}
- code += "(" + value + ")";
} else {
code += "_fbb.CreateVector<flatbuffers::Offset<";
code += WrapInNameSpace(*vector_type.struct_def) + ">> ";
}
}
- // If set_empty_vectors_to_null option is enabled, for optional fields, check to
- // see if there actually is any data in _o->field before attempting to
- // access it.
- if (opts_.set_empty_vectors_to_null && !field.required) {
+ // If set_empty_vectors_to_null option is enabled, for optional fields,
+ // check to see if there actually is any data in _o->field before
+ // attempting to access it.
+ if (opts_.set_empty_vectors_to_null && !field.IsRequired()) {
code = value + ".size() ? " + code + " : 0";
}
break;
}
case BASE_TYPE_STRUCT: {
if (IsStruct(field.value.type)) {
- auto native_type =
- field.value.type.struct_def->attributes.Lookup("native_type");
+ const auto &struct_attribs = field.value.type.struct_def->attributes;
+ const auto native_type = struct_attribs.Lookup("native_type");
if (native_type) {
- code += "flatbuffers::Pack(" + value + ")";
+ code += "flatbuffers::Pack";
+ const auto pack_name =
+ struct_attribs.Lookup("native_type_pack_name");
+ if (pack_name) { code += pack_name->constant; }
+ code += "(" + value + ")";
} else if (field.native_inline) {
code += "&" + value;
} else {
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_.SetValue("NATIVE_NAME",
NativeName(Name(struct_def), &struct_def, opts_));
- auto native_name =
- NativeName(WrapInNameSpace(struct_def), &struct_def, parser_.opts);
- code_.SetValue("POINTER_TYPE",
- GenTypeNativePtr(native_name, nullptr, false));
if (opts_.generate_object_based_api) {
// Generate the X::UnPack() method.
code_ +=
"inline " + TableUnPackSignature(struct_def, false, opts_) + " {";
- code_ +=
- " {{POINTER_TYPE}} _o = {{POINTER_TYPE}}(new {{NATIVE_NAME}}());";
+ if (opts_.g_cpp_std == cpp::CPP_STD_X0) {
+ auto native_name = WrapNativeNameInNameSpace(struct_def, parser_.opts);
+ code_.SetValue("POINTER_TYPE",
+ GenTypeNativePtr(native_name, nullptr, false));
+ code_ +=
+ " {{POINTER_TYPE}} _o = {{POINTER_TYPE}}(new {{NATIVE_NAME}}());";
+ } else if (opts_.g_cpp_std == cpp::CPP_STD_11) {
+ code_ +=
+ " auto _o = std::unique_ptr<{{NATIVE_NAME}}>(new "
+ "{{NATIVE_NAME}}());";
+ } else {
+ code_ += " auto _o = std::make_unique<{{NATIVE_NAME}}>();";
+ }
code_ += " UnPackTo(_o.get(), _resolver);";
code_ += " return _o.release();";
-
code_ += "}";
code_ += "";
-
code_ +=
"inline " + TableUnPackToSignature(struct_def, false, opts_) + " {";
code_ += " (void)_o;";
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) { continue; }
+ if (IsVector(field.value.type)) {
+ const std::string force_align_code =
+ GenVectorForceAlign(field, "_o->" + Name(field) + ".size()");
+ if (!force_align_code.empty()) { code_ += " " + force_align_code; }
+ }
code_ += " auto _" + Name(field) + " = " + GenCreateParam(field) + ";";
}
// Need to call "Create" with the struct namespace.
static void PaddingInitializer(int bits, std::string *code_ptr, int *id) {
(void)bits;
- if (*code_ptr != "") *code_ptr += ",\n ";
+ if (!code_ptr->empty()) *code_ptr += ",\n ";
*code_ptr += "padding" + NumToString((*id)++) + "__(0)";
}
static void PaddingNoop(int bits, std::string *code_ptr, int *id) {
(void)bits;
+ if (!code_ptr->empty()) *code_ptr += '\n';
*code_ptr += " (void)padding" + NumToString((*id)++) + "__;";
}
+ void GenStructDefaultConstructor(const StructDef &struct_def) {
+ std::string init_list;
+ std::string body;
+ bool first_in_init_list = true;
+ int padding_initializer_id = 0;
+ int padding_body_id = 0;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto field = *it;
+ const auto field_name = field->name + "_";
+
+ if (first_in_init_list) {
+ first_in_init_list = false;
+ } else {
+ init_list += ",";
+ init_list += "\n ";
+ }
+
+ init_list += field_name;
+ if (IsStruct(field->value.type) || IsArray(field->value.type)) {
+ // this is either default initialization of struct
+ // or
+ // implicit initialization of array
+ // for each object in array it:
+ // * sets it as zeros for POD types (integral, floating point, etc)
+ // * calls default constructor for classes/structs
+ init_list += "()";
+ } else {
+ init_list += "(0)";
+ }
+ if (field->padding) {
+ GenPadding(*field, &init_list, &padding_initializer_id,
+ PaddingInitializer);
+ GenPadding(*field, &body, &padding_body_id, PaddingNoop);
+ }
+ }
+
+ if (init_list.empty()) {
+ code_ += " {{STRUCT_NAME}}()";
+ code_ += " {}";
+ } else {
+ code_.SetValue("INIT_LIST", init_list);
+ code_ += " {{STRUCT_NAME}}()";
+ code_ += " : {{INIT_LIST}} {";
+ if (!body.empty()) { code_ += body; }
+ code_ += " }";
+ }
+ }
+
+ void GenStructConstructor(const StructDef &struct_def,
+ GenArrayArgMode array_mode) {
+ std::string arg_list;
+ std::string init_list;
+ int padding_id = 0;
+ auto first = struct_def.fields.vec.begin();
+ // skip arrays if generate ctor without array assignment
+ const auto init_arrays = (array_mode != kArrayArgModeNone);
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ const auto &type = field.value.type;
+ const auto is_array = IsArray(type);
+ const auto arg_name = "_" + Name(field);
+ if (!is_array || init_arrays) {
+ if (it != first && !arg_list.empty()) { arg_list += ", "; }
+ arg_list += !is_array ? GenTypeGet(type, " ", "const ", " &", true)
+ : GenTypeSpan(type, true, type.fixed_length);
+ arg_list += arg_name;
+ }
+ // skip an array with initialization from span
+ if (false == (is_array && init_arrays)) {
+ if (it != first && !init_list.empty()) { init_list += ",\n "; }
+ init_list += Name(field) + "_";
+ if (IsScalar(type.base_type)) {
+ auto scalar_type = GenUnderlyingCast(field, false, arg_name);
+ init_list += "(flatbuffers::EndianScalar(" + scalar_type + "))";
+ } else {
+ FLATBUFFERS_ASSERT((is_array && !init_arrays) || IsStruct(type));
+ if (!is_array)
+ init_list += "(" + arg_name + ")";
+ else
+ init_list += "()";
+ }
+ }
+ if (field.padding)
+ GenPadding(field, &init_list, &padding_id, PaddingInitializer);
+ }
+
+ if (!arg_list.empty()) {
+ code_.SetValue("ARG_LIST", arg_list);
+ code_.SetValue("INIT_LIST", init_list);
+ if (!init_list.empty()) {
+ code_ += " {{STRUCT_NAME}}({{ARG_LIST}})";
+ code_ += " : {{INIT_LIST}} {";
+ } else {
+ code_ += " {{STRUCT_NAME}}({{ARG_LIST}}) {";
+ }
+ padding_id = 0;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ const auto &type = field.value.type;
+ if (IsArray(type) && init_arrays) {
+ const auto &element_type = type.VectorType();
+ const auto is_enum = IsEnum(element_type);
+ FLATBUFFERS_ASSERT(
+ (IsScalar(element_type.base_type) || IsStruct(element_type)) &&
+ "invalid declaration");
+ const auto face_type = GenTypeGet(type, " ", "", "", is_enum);
+ std::string get_array =
+ is_enum ? "CastToArrayOfEnum<" + face_type + ">" : "CastToArray";
+ const auto field_name = Name(field) + "_";
+ const auto arg_name = "_" + Name(field);
+ code_ += " flatbuffers::" + get_array + "(" + field_name +
+ ").CopyFromSpan(" + arg_name + ");";
+ }
+ if (field.padding) {
+ std::string padding;
+ GenPadding(field, &padding, &padding_id, PaddingNoop);
+ code_ += padding;
+ }
+ }
+ code_ += " }";
+ }
+ }
+
+ void GenArrayAccessor(const Type &type, bool mutable_accessor) {
+ FLATBUFFERS_ASSERT(IsArray(type));
+ const auto is_enum = IsEnum(type.VectorType());
+ // The Array<bool,N> is a tricky case, like std::vector<bool>.
+ // It requires a specialization of Array class.
+ // Generate Array<uint8_t> for Array<bool>.
+ const auto face_type = GenTypeGet(type, " ", "", "", is_enum);
+ std::string ret_type = "flatbuffers::Array<" + face_type + ", " +
+ NumToString(type.fixed_length) + ">";
+ if (mutable_accessor)
+ code_ += " " + ret_type + " *mutable_{{FIELD_NAME}}() {";
+ else
+ code_ += " const " + ret_type + " *{{FIELD_NAME}}() const {";
+
+ std::string get_array =
+ is_enum ? "CastToArrayOfEnum<" + face_type + ">" : "CastToArray";
+ code_ += " return &flatbuffers::" + get_array + "({{FIELD_VALUE}});";
+ code_ += " }";
+ }
+
// Generate an accessor struct with constructor for a flatbuffers struct.
void GenStruct(const StructDef &struct_def) {
// Generate an accessor struct, with private variables of the form:
code_ += "";
code_ += " public:";
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) { code_ += " struct Traits;"; }
+
// Make TypeTable accessible via the generated struct.
if (opts_.mini_reflect != IDLOptions::kNone) {
code_ +=
GenFullyQualifiedNameGetter(struct_def, Name(struct_def));
// Generate a default constructor.
- code_ += " {{STRUCT_NAME}}() {";
- code_ +=
- " memset(static_cast<void *>(this), 0, sizeof({{STRUCT_NAME}}));";
- code_ += " }";
+ GenStructDefaultConstructor(struct_def);
// Generate a constructor that takes all fields as arguments,
- // excluding arrays
- std::string arg_list;
- std::string init_list;
- padding_id = 0;
- auto first = struct_def.fields.vec.begin();
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (IsArray(field.value.type)) {
- first++;
- continue;
- }
- const auto member_name = Name(field) + "_";
- const auto arg_name = "_" + Name(field);
- const auto arg_type =
- GenTypeGet(field.value.type, " ", "const ", " &", true);
-
- if (it != first) { arg_list += ", "; }
- arg_list += arg_type;
- arg_list += arg_name;
- if (!IsArray(field.value.type)) {
- if (it != first && init_list != "") { init_list += ",\n "; }
- init_list += member_name;
- if (IsScalar(field.value.type.base_type)) {
- auto type = GenUnderlyingCast(field, false, arg_name);
- init_list += "(flatbuffers::EndianScalar(" + type + "))";
- } else {
- init_list += "(" + arg_name + ")";
- }
- }
- if (field.padding) {
- GenPadding(field, &init_list, &padding_id, PaddingInitializer);
- }
- }
+ // excluding arrays.
+ GenStructConstructor(struct_def, kArrayArgModeNone);
- if (!arg_list.empty()) {
- code_.SetValue("ARG_LIST", arg_list);
- code_.SetValue("INIT_LIST", init_list);
- if (!init_list.empty()) {
- code_ += " {{STRUCT_NAME}}({{ARG_LIST}})";
- code_ += " : {{INIT_LIST}} {";
- } else {
- code_ += " {{STRUCT_NAME}}({{ARG_LIST}}) {";
- }
- padding_id = 0;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (IsArray(field.value.type)) {
- const auto &member = Name(field) + "_";
- code_ +=
- " std::memset(" + member + ", 0, sizeof(" + member + "));";
- }
- if (field.padding) {
- std::string padding;
- GenPadding(field, &padding, &padding_id, PaddingNoop);
- code_ += padding;
- }
- }
- code_ += " }";
+ auto arrays_num = std::count_if(struct_def.fields.vec.begin(),
+ struct_def.fields.vec.end(),
+ [](const flatbuffers::FieldDef *fd) {
+ return IsArray(fd->value.type);
+ });
+ if (arrays_num > 0) {
+ GenStructConstructor(struct_def, kArrayArgModeSpanStatic);
}
// Generate accessor methods of the form:
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
+ const auto &type = field.value.type;
+ const auto is_scalar = IsScalar(type.base_type);
+ const auto is_array = IsArray(type);
- auto field_type = GenTypeGet(field.value.type, " ",
- IsArray(field.value.type) ? "" : "const ",
- IsArray(field.value.type) ? "" : " &", true);
- auto is_scalar = IsScalar(field.value.type.base_type);
+ const auto field_type = GenTypeGet(type, " ", is_array ? "" : "const ",
+ is_array ? "" : " &", true);
auto member = Name(field) + "_";
auto value =
is_scalar ? "flatbuffers::EndianScalar(" + member + ")" : member;
GenComment(field.doc_comment, " ");
// Generate a const accessor function.
- if (IsArray(field.value.type)) {
- auto underlying = GenTypeGet(field.value.type, "", "", "", false);
- code_ += " const flatbuffers::Array<" + field_type + ", " +
- NumToString(field.value.type.fixed_length) + "> *" +
- "{{FIELD_NAME}}() const {";
- code_ += " return reinterpret_cast<const flatbuffers::Array<" +
- field_type + ", " +
- NumToString(field.value.type.fixed_length) +
- "> *>({{FIELD_VALUE}});";
- code_ += " }";
+ if (is_array) {
+ GenArrayAccessor(type, false);
} else {
code_ += " {{FIELD_TYPE}}{{FIELD_NAME}}() const {";
code_ += " return {{FIELD_VALUE}};";
// Generate a mutable accessor function.
if (opts_.mutable_buffer) {
auto mut_field_type =
- GenTypeGet(field.value.type, " ", "",
- IsArray(field.value.type) ? "" : " &", true);
+ GenTypeGet(type, " ", "", is_array ? "" : " &", true);
code_.SetValue("FIELD_TYPE", mut_field_type);
if (is_scalar) {
- code_.SetValue("ARG", GenTypeBasic(field.value.type, true));
+ code_.SetValue("ARG", GenTypeBasic(type, true));
code_.SetValue("FIELD_VALUE",
GenUnderlyingCast(field, false, "_" + Name(field)));
" flatbuffers::WriteScalar(&{{FIELD_NAME}}_, "
"{{FIELD_VALUE}});";
code_ += " }";
- } else if (IsArray(field.value.type)) {
- auto underlying = GenTypeGet(field.value.type, "", "", "", false);
- code_ += " flatbuffers::Array<" + mut_field_type + ", " +
- NumToString(field.value.type.fixed_length) + "> *" +
- "mutable_{{FIELD_NAME}}() {";
- code_ += " return reinterpret_cast<flatbuffers::Array<" +
- mut_field_type + ", " +
- NumToString(field.value.type.fixed_length) +
- "> *>({{FIELD_VALUE}});";
- code_ += " }";
+ } else if (is_array) {
+ GenArrayAccessor(type, true);
} else {
code_ += " {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
code_ += " return {{FIELD_VALUE}};";
}
code_.SetValue("NATIVE_NAME", Name(struct_def));
GenOperatorNewDelete(struct_def);
+
+ if (opts_.cpp_static_reflection) { GenIndexBasedFieldGetter(struct_def); }
+
code_ += "};";
code_.SetValue("STRUCT_BYTE_SIZE", NumToString(struct_def.bytesize));
code_ += "FLATBUFFERS_STRUCT_END({{STRUCT_NAME}}, {{STRUCT_BYTE_SIZE}});";
if (opts_.gen_compare) GenCompareOperator(struct_def, "()");
code_ += "";
+
+ // Definition for type traits for this table type. This allows querying var-
+ // ious compile-time traits of the table.
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) { GenTraitsStruct(struct_def); }
}
// Set up the correct namespace. Only open a namespace if the existing one is
cpp::IDLOptionsCpp opts(parser.opts);
// The '--cpp_std' argument could be extended (like ASAN):
// Example: "flatc --cpp_std c++17:option1:option2".
- auto cpp_std = !opts.cpp_std.empty() ? opts.cpp_std : "C++0X";
- std::transform(cpp_std.begin(), cpp_std.end(), cpp_std.begin(), ToUpper);
+ auto cpp_std = !opts.cpp_std.empty() ? opts.cpp_std : "C++11";
+ std::transform(cpp_std.begin(), cpp_std.end(), cpp_std.begin(), CharToUpper);
if (cpp_std == "C++0X") {
opts.g_cpp_std = cpp::CPP_STD_X0;
opts.g_only_fixed_enums = false;
// The opts.scoped_enums has priority.
opts.g_only_fixed_enums |= opts.scoped_enums;
+ if (opts.cpp_static_reflection && opts.g_cpp_std < cpp::CPP_STD_17) {
+ LogCompilerError(
+ "--cpp-static-reflection requires using --cpp-std at \"C++17\" or "
+ "higher.");
+ return false;
+ }
+
cpp::CppGenerator generator(parser, path, file_name, opts);
return generator.generate();
}
const std::string &file_name) {
const auto filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
+ cpp::CppGenerator geneartor(parser, path, file_name, parser.opts);
const auto included_files = parser.GetIncludedFilesRecursive(file_name);
- std::string make_rule = GeneratedFileName(path, filebase) + ": ";
+ std::string make_rule =
+ geneartor.GeneratedFileName(path, filebase, parser.opts) + ": ";
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}