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) {
// Anything extra to add to the guard?
if (!postfix.empty()) { guard += postfix + "_"; }
guard += "H_";
- std::transform(guard.begin(), guard.end(), guard.begin(), ToUpper);
+ std::transform(guard.begin(), guard.end(), guard.begin(), CharToUpper);
return guard;
}
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.
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",
: 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_ += " };";
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 + "> {";
}
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);
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) +
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); }
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",
// that doesn't need alignment code.
std::string GenVectorForceAlign(const FieldDef &field,
const std::string &field_size) {
- FLATBUFFERS_ASSERT(field.value.type.base_type == BASE_TYPE_VECTOR);
+ 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;
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
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()) {
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_ += "__\\";
}
}
}
}
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: {
// 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) {
+ if (!field.IsRequired()) {
auto empty_value = opts_.set_empty_strings_to_null
? "0"
: "_fbb.CreateSharedString(\"\")";
}
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 (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_ +=
"inline " + TableUnPackSignature(struct_def, false, opts_) + " {";
- if(opts_.g_cpp_std == cpp::CPP_STD_X0) {
- auto native_name =
- NativeName(WrapInNameSpace(struct_def), &struct_def, parser_.opts);
+ 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 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}}>();";
}
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) { continue; }
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ 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; }
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;
- *code_ptr += " (void)padding" + NumToString((*id)++) + "__;\n";
+ if (!code_ptr->empty()) *code_ptr += '\n';
+ *code_ptr += " (void)padding" + NumToString((*id)++) + "__;";
}
void GenStructDefaultConstructor(const StructDef &struct_def) {
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) {
+ it != struct_def.fields.vec.end(); ++it) {
const auto field = *it;
const auto field_name = field->name + "_";
code_ += " {}";
} else {
code_.SetValue("INIT_LIST", init_list);
- code_.SetValue("DEFAULT_CONSTRUCTOR_BODY", body);
code_ += " {{STRUCT_NAME}}()";
code_ += " : {{INIT_LIST}} {";
- code_ += "{{DEFAULT_CONSTRUCTOR_BODY}} }";
+ if (!body.empty()) { code_ += body; }
+ code_ += " }";
}
}
- void GenStructConstructor(const StructDef &struct_def) {
+ void GenStructConstructor(const StructDef &struct_def,
+ GenArrayArgMode array_mode) {
std::string arg_list;
std::string init_list;
int padding_id = 0;
- bool first_arg = true;
- bool first_init = true;
+ 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 &field_type = field.value.type;
- const auto member_name = Name(field) + "_";
+ const auto &type = field.value.type;
+ const auto is_array = IsArray(type);
const auto arg_name = "_" + Name(field);
- const auto arg_type = GenTypeGet(field_type, " ", "const ", " &", true);
-
- if (!IsArray(field_type)) {
- if (first_arg) {
- first_arg = false;
- } else {
- arg_list += ", ";
- }
- arg_list += arg_type;
+ 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;
}
- if (first_init) {
- first_init = false;
- } else {
- init_list += ",";
- init_list += "\n ";
- }
- init_list += member_name;
- if (IsScalar(field_type.base_type)) {
- auto type = GenUnderlyingCast(field, false, arg_name);
- init_list += "(flatbuffers::EndianScalar(" + type + "))";
- } else if (IsArray(field_type)) {
- // 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 += "(" + 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) {
+ if (field.padding)
GenPadding(field, &init_list, &padding_id, PaddingInitializer);
- }
}
if (!arg_list.empty()) {
} 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_ +=
GenStructDefaultConstructor(struct_def);
// Generate a constructor that takes all fields as arguments,
- // excluding arrays
- GenStructConstructor(struct_def);
+ // excluding arrays.
+ GenStructConstructor(struct_def, kArrayArgModeNone);
+
+ 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:
// type name() const { return flatbuffers::EndianScalar(name_); }
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();
}