Formats cpp code (#6349)

This commit is contained in:
mustiikhalil
2021-01-22 21:46:53 +03:00
committed by GitHub
parent 1da0a2dfac
commit 786f69b248
11 changed files with 167 additions and 100 deletions

View File

@@ -21,7 +21,7 @@
#include "flatbuffers/stl_emulation.h" #include "flatbuffers/stl_emulation.h"
#ifndef FLATBUFFERS_CPP98_STL #ifndef FLATBUFFERS_CPP98_STL
#include <functional> # include <functional>
#endif #endif
#if defined(FLATBUFFERS_NAN_DEFAULTS) #if defined(FLATBUFFERS_NAN_DEFAULTS)
@@ -505,8 +505,8 @@ template<typename T, uint16_t length> class Array {
(void)p2; (void)p2;
CopyFromSpanImpl( CopyFromSpanImpl(
flatbuffers::integral_constant<bool, flatbuffers::integral_constant < bool,
!scalar_tag::value || sizeof(T) == 1 || FLATBUFFERS_LITTLEENDIAN>(), !scalar_tag::value || sizeof(T) == 1 || FLATBUFFERS_LITTLEENDIAN > (),
src); src);
} }
@@ -584,12 +584,12 @@ template<typename T, uint16_t length> class Array<Offset<T>, length> {
// Cast a raw T[length] to a raw flatbuffers::Array<T, length> // Cast a raw T[length] to a raw flatbuffers::Array<T, length>
// without endian conversion. Use with care. // without endian conversion. Use with care.
template<typename T, uint16_t length> template<typename T, uint16_t length>
Array<T, length>& CastToArray(T (&arr)[length]) { Array<T, length> &CastToArray(T (&arr)[length]) {
return *reinterpret_cast<Array<T, length> *>(arr); return *reinterpret_cast<Array<T, length> *>(arr);
} }
template<typename T, uint16_t length> template<typename T, uint16_t length>
const Array<T, length>& CastToArray(const T (&arr)[length]) { const Array<T, length> &CastToArray(const T (&arr)[length]) {
return *reinterpret_cast<const Array<T, length> *>(arr); return *reinterpret_cast<const Array<T, length> *>(arr);
} }
@@ -648,7 +648,7 @@ static inline const char *GetCstring(const String *str) {
static inline flatbuffers::string_view GetStringView(const String *str) { static inline flatbuffers::string_view GetStringView(const String *str) {
return str ? str->string_view() : flatbuffers::string_view(); return str ? str->string_view() : flatbuffers::string_view();
} }
#endif // FLATBUFFERS_HAS_STRING_VIEW #endif // FLATBUFFERS_HAS_STRING_VIEW
// Allocator interface. This is flatbuffers-specific and meant only for // Allocator interface. This is flatbuffers-specific and meant only for
// `vector_downward` usage. // `vector_downward` usage.
@@ -1692,9 +1692,7 @@ class FlatBufferBuilder {
// causing the wrong overload to be selected, remove it. // causing the wrong overload to be selected, remove it.
AssertScalarT<T>(); AssertScalarT<T>();
StartVector(len, sizeof(T)); StartVector(len, sizeof(T));
if (len == 0) { if (len == 0) { return Offset<Vector<T>>(EndVector(len)); }
return Offset<Vector<T>>(EndVector(len));
}
// clang-format off // clang-format off
#if FLATBUFFERS_LITTLEENDIAN #if FLATBUFFERS_LITTLEENDIAN
PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T)); PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
@@ -2825,9 +2823,12 @@ inline const char * const *ElementaryTypeNames() {
// bitfields is otherwise implementation-defined and causes warnings on older // bitfields is otherwise implementation-defined and causes warnings on older
// GCC compilers. // GCC compilers.
struct TypeCode { struct TypeCode {
unsigned short base_type : 4; // ElementaryType // ElementaryType
unsigned short is_repeating : 1; // Either vector (in table) or array (in struct) unsigned short base_type : 4;
signed short sequence_ref : 11; // Index into type_refs below, or -1 for none. // Either vector (in table) or array (in struct)
unsigned short is_repeating : 1;
// Index into type_refs below, or -1 for none.
signed short sequence_ref : 11;
}; };
static_assert(sizeof(TypeCode) == 2, "TypeCode"); static_assert(sizeof(TypeCode) == 2, "TypeCode");

View File

@@ -47,29 +47,31 @@ inline bool IsLong(reflection::BaseType t) {
inline size_t GetTypeSize(reflection::BaseType base_type) { inline size_t GetTypeSize(reflection::BaseType base_type) {
// This needs to correspond to the BaseType enum. // This needs to correspond to the BaseType enum.
static size_t sizes[] = { static size_t sizes[] = {
0, // None 0, // None
1, // UType 1, // UType
1, // Bool 1, // Bool
1, // Byte 1, // Byte
1, // UByte 1, // UByte
2, // Short 2, // Short
2, // UShort 2, // UShort
4, // Int 4, // Int
4, // UInt 4, // UInt
8, // Long 8, // Long
8, // ULong 8, // ULong
4, // Float 4, // Float
8, // Double 8, // Double
4, // String 4, // String
4, // Vector 4, // Vector
4, // Obj 4, // Obj
4, // Union 4, // Union
0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds errors. 0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds
// errors.
0 // MaxBaseType. This must be kept the last entry in this array. 0 // MaxBaseType. This must be kept the last entry in this array.
}; };
static_assert(sizeof(sizes) / sizeof(size_t) == reflection::MaxBaseType + 1, static_assert(sizeof(sizes) / sizeof(size_t) == reflection::MaxBaseType + 1,
"Size of sizes[] array does not match the count of BaseType enum values."); "Size of sizes[] array does not match the count of BaseType "
"enum values.");
return sizes[base_type]; return sizes[base_type];
} }

View File

@@ -1,4 +1,4 @@
/* /*
* Copyright 2014 Google Inc. All rights reserved. * Copyright 2014 Google Inc. All rights reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
@@ -2462,8 +2462,7 @@ class CppGenerator : public BaseGenerator {
if (!field.deprecated) { if (!field.deprecated) {
code_.SetValue("FIELD_NAME", Name(field)); code_.SetValue("FIELD_NAME", Name(field));
code_ += ",\n {{FIELD_NAME}}\\"; code_ += ",\n {{FIELD_NAME}}\\";
if (IsString(field.value.type) || if (IsString(field.value.type) || IsVector(field.value.type)) {
IsVector(field.value.type)) {
code_ += "__\\"; code_ += "__\\";
} }
} }
@@ -2551,9 +2550,7 @@ class CppGenerator : public BaseGenerator {
WrapInNameSpace(*field.value.type.enum_def) + ">("; WrapInNameSpace(*field.value.type.enum_def) + ">(";
} }
indexing += "_e->Get(_i)"; indexing += "_e->Get(_i)";
if (field.value.type.enum_def) { if (field.value.type.enum_def) { indexing += ")"; }
indexing += ")";
}
if (field.value.type.element == BASE_TYPE_BOOL) { if (field.value.type.element == BASE_TYPE_BOOL) {
indexing += " != 0"; indexing += " != 0";
} }

View File

@@ -1515,10 +1515,11 @@ class CSharpGenerator : public BaseGenerator {
case BASE_TYPE_ARRAY: { case BASE_TYPE_ARRAY: {
auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts); auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts);
auto length_str = NumToString(field.value.type.fixed_length); auto length_str = NumToString(field.value.type.fixed_length);
auto unpack_method = field.value.type.struct_def == nullptr ? "" auto unpack_method = field.value.type.struct_def == nullptr
: field.value.type.struct_def->fixed ? ""
? ".UnPack()" : field.value.type.struct_def->fixed
: "?.UnPack()"; ? ".UnPack()"
: "?.UnPack()";
code += start + "new " + type_name.substr(0, type_name.length() - 1) + code += start + "new " + type_name.substr(0, type_name.length() - 1) +
length_str + "];\n"; length_str + "];\n";
code += " for (var _j = 0; _j < " + length_str + "; ++_j) { _o." + code += " for (var _j = 0; _j < " + length_str + "; ++_j) { _o." +

View File

@@ -266,7 +266,9 @@ class GoGenerator : public BaseGenerator {
if (i == 0) { if (i == 0) {
code += "\tn := flatbuffers.GetUOffsetT(buf[offset:])\n"; code += "\tn := flatbuffers.GetUOffsetT(buf[offset:])\n";
} else { } else {
code += "\tn := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])\n"; code +=
"\tn := "
"flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])\n";
} }
code += "\tx := &" + struct_def.name + "{}\n"; code += "\tx := &" + struct_def.name + "{}\n";
if (i == 0) { if (i == 0) {

View File

@@ -268,8 +268,7 @@ class JsonSchemaGenerator : public BaseGenerator {
} }
bool save() const { bool save() const {
const auto file_path = const auto file_path = GeneratedFileName(path_, file_name_, parser_.opts);
GeneratedFileName(path_, file_name_, parser_.opts);
return SaveFile(file_path.c_str(), code_, false); return SaveFile(file_path.c_str(), code_, false);
} }

View File

@@ -735,9 +735,7 @@ class PhpGenerator : public BaseGenerator {
} else { } else {
BuildFieldOfTable(field, offset, code_ptr); BuildFieldOfTable(field, offset, code_ptr);
} }
if (IsVector(field.value.type)) { if (IsVector(field.value.type)) { BuildVectorOfTable(field, code_ptr); }
BuildVectorOfTable(field, code_ptr);
}
} }
GetEndOffsetOnTable(struct_def, code_ptr); GetEndOffsetOnTable(struct_def, code_ptr);

View File

@@ -413,14 +413,14 @@ class PythonGenerator : public BaseGenerator {
const FieldDef &field, const FieldDef &field,
std::string *code_ptr) { std::string *code_ptr) {
auto nested = field.attributes.Lookup("nested_flatbuffer"); auto nested = field.attributes.Lookup("nested_flatbuffer");
if (!nested) { return; } // There is no nested flatbuffer. if (!nested) { return; } // There is no nested flatbuffer.
std::string unqualified_name = nested->constant; std::string unqualified_name = nested->constant;
std::string qualified_name = nested->constant; std::string qualified_name = nested->constant;
auto nested_root = parser_.LookupStruct(nested->constant); auto nested_root = parser_.LookupStruct(nested->constant);
if (nested_root == nullptr) { if (nested_root == nullptr) {
qualified_name = parser_.current_namespace_->GetFullyQualifiedName( qualified_name =
nested->constant); parser_.current_namespace_->GetFullyQualifiedName(nested->constant);
nested_root = parser_.LookupStruct(qualified_name); nested_root = parser_.LookupStruct(qualified_name);
} }
FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser. FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
@@ -1250,7 +1250,8 @@ class PythonGenerator : public BaseGenerator {
field_instance_name + "))):"; field_instance_name + "))):";
code_prefix += code_prefix +=
GenIndents(4) + "self." + field_instance_name + "[i].Pack(builder)"; GenIndents(4) + "self." + field_instance_name + "[i].Pack(builder)";
code_prefix += GenIndents(3) + field_instance_name + " = builder.EndVector()"; code_prefix +=
GenIndents(3) + field_instance_name + " = builder.EndVector()";
} else { } else {
// If the vector is a struct vector, we need to first build accessor for // If the vector is a struct vector, we need to first build accessor for
// each struct element. // each struct element.
@@ -1267,7 +1268,8 @@ class PythonGenerator : public BaseGenerator {
field_instance_name + "))):"; field_instance_name + "))):";
code_prefix += GenIndents(4) + "builder.PrependUOffsetTRelative" + "(" + code_prefix += GenIndents(4) + "builder.PrependUOffsetTRelative" + "(" +
field_instance_name + "list[i])"; field_instance_name + "list[i])";
code_prefix += GenIndents(3) + field_instance_name + " = builder.EndVector()"; code_prefix +=
GenIndents(3) + field_instance_name + " = builder.EndVector()";
} }
// Adds the field into the struct. // Adds the field into the struct.
@@ -1341,7 +1343,8 @@ class PythonGenerator : public BaseGenerator {
field_instance_name + "[i]))"; field_instance_name + "[i]))";
GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 3); GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 3);
code_prefix += "(" + MakeLowerCamel(field) + "list[i])"; code_prefix += "(" + MakeLowerCamel(field) + "list[i])";
code_prefix += GenIndents(3) + field_instance_name + " = builder.EndVector()"; code_prefix +=
GenIndents(3) + field_instance_name + " = builder.EndVector()";
return; return;
} }
@@ -1353,7 +1356,8 @@ class PythonGenerator : public BaseGenerator {
code_prefix += GenIndents(3) + "else:"; code_prefix += GenIndents(3) + "else:";
GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 4); GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 4);
code_prefix += "(self." + field_instance_name + "[i])"; code_prefix += "(self." + field_instance_name + "[i])";
code_prefix += GenIndents(4) + field_instance_name + " = builder.EndVector()"; code_prefix +=
GenIndents(4) + field_instance_name + " = builder.EndVector()";
} }
void GenPackForStructField(const StructDef &struct_def, const FieldDef &field, void GenPackForStructField(const StructDef &struct_def, const FieldDef &field,

View File

@@ -200,19 +200,77 @@ class RustGenerator : public BaseGenerator {
// changes to that webpage in the future. // changes to that webpage in the future.
// currently-used keywords // currently-used keywords
"as", "break", "const", "continue", "crate", "else", "enum", "extern", "as",
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "break",
"move", "mut", "pub", "ref", "return", "Self", "self", "static", "struct", "const",
"super", "trait", "true", "type", "unsafe", "use", "where", "while", "continue",
"crate",
"else",
"enum",
"extern",
"false",
"fn",
"for",
"if",
"impl",
"in",
"let",
"loop",
"match",
"mod",
"move",
"mut",
"pub",
"ref",
"return",
"Self",
"self",
"static",
"struct",
"super",
"trait",
"true",
"type",
"unsafe",
"use",
"where",
"while",
// future possible keywords // future possible keywords
"abstract", "alignof", "become", "box", "do", "final", "macro", "abstract",
"offsetof", "override", "priv", "proc", "pure", "sizeof", "typeof", "alignof",
"unsized", "virtual", "yield", "become",
"box",
"do",
"final",
"macro",
"offsetof",
"override",
"priv",
"proc",
"pure",
"sizeof",
"typeof",
"unsized",
"virtual",
"yield",
// other rust terms we should not use // other rust terms we should not use
"std", "usize", "isize", "u8", "i8", "u16", "i16", "u32", "i32", "u64", "std",
"i64", "u128", "i128", "f32", "f64", "usize",
"isize",
"u8",
"i8",
"u16",
"i16",
"u32",
"i32",
"u64",
"i64",
"u128",
"i128",
"f32",
"f64",
// These are terms the code generator can implement on types. // These are terms the code generator can implement on types.
// //
@@ -223,12 +281,19 @@ class RustGenerator : public BaseGenerator {
// implementation detail, and how we implement methods could change in // implementation detail, and how we implement methods could change in
// the future. as a result, we proactively block these out as reserved // the future. as a result, we proactively block these out as reserved
// words. // words.
"follow", "push", "size", "alignment", "to_little_endian", "follow",
"from_little_endian", nullptr, "push",
"size",
"alignment",
"to_little_endian",
"from_little_endian",
nullptr,
// used by Enum constants // used by Enum constants
"ENUM_MAX", "ENUM_MIN", "ENUM_VALUES", "ENUM_MAX",
}; // clang-format on "ENUM_MIN",
"ENUM_VALUES",
};
for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw); for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
} }

View File

@@ -143,8 +143,7 @@ void Parser::Message(const std::string &msg) {
} }
void Parser::Warning(const std::string &msg) { void Parser::Warning(const std::string &msg) {
if (!opts.no_warnings) if (!opts.no_warnings) Message("warning: " + msg);
Message("warning: " + msg);
} }
CheckedError Parser::Error(const std::string &msg) { CheckedError Parser::Error(const std::string &msg) {
@@ -203,8 +202,7 @@ bool atot_scalar(const char *s, T *val, bool_constant<true>) {
return true; return true;
} }
template<typename T> template<typename T> CheckedError atot(const char *s, Parser &parser, T *val) {
CheckedError atot(const char *s, Parser &parser, T *val) {
auto done = atot_scalar(s, val, bool_constant<is_floating_point<T>::value>()); auto done = atot_scalar(s, val, bool_constant<is_floating_point<T>::value>());
if (done) return NoError(); if (done) return NoError();
if (0 == *val) if (0 == *val)
@@ -3301,13 +3299,11 @@ CheckedError Parser::DoParse(const char *source, const char **include_paths,
return NoError(); return NoError();
} }
CheckedError Parser::DoParseJson() CheckedError Parser::DoParseJson() {
{
if (token_ != '{') { if (token_ != '{') {
EXPECT('{'); EXPECT('{');
} else { } else {
if (!root_struct_def_) if (!root_struct_def_) return Error("no root type set to parse json with");
return Error("no root type set to parse json with");
if (builder_.GetSize()) { if (builder_.GetSize()) {
return Error("cannot have more than one json object in a file"); return Error("cannot have more than one json object in a file");
} }
@@ -3319,8 +3315,8 @@ CheckedError Parser::DoParseJson()
file_identifier_.length() ? file_identifier_.c_str() : nullptr); file_identifier_.length() ? file_identifier_.c_str() : nullptr);
} else { } else {
builder_.Finish(Offset<Table>(toff), file_identifier_.length() builder_.Finish(Offset<Table>(toff), file_identifier_.length()
? file_identifier_.c_str() ? file_identifier_.c_str()
: nullptr); : nullptr);
} }
} }
// Check that JSON file doesn't contain more objects or IDL directives. // Check that JSON file doesn't contain more objects or IDL directives.

View File

@@ -697,7 +697,7 @@ template<typename T, typename U, U qnan_base> bool is_quiet_nan_impl(T v) {
std::memcpy(&b, &v, sizeof(T)); std::memcpy(&b, &v, sizeof(T));
return ((b & qnan_base) == qnan_base); return ((b & qnan_base) == qnan_base);
} }
#if defined(__mips__) || defined(__hppa__) # if defined(__mips__) || defined(__hppa__)
static bool is_quiet_nan(float v) { static bool is_quiet_nan(float v) {
return is_quiet_nan_impl<float, uint32_t, 0x7FC00000u>(v) || return is_quiet_nan_impl<float, uint32_t, 0x7FC00000u>(v) ||
is_quiet_nan_impl<float, uint32_t, 0x7FBFFFFFu>(v); is_quiet_nan_impl<float, uint32_t, 0x7FBFFFFFu>(v);
@@ -706,14 +706,14 @@ static bool is_quiet_nan(double v) {
return is_quiet_nan_impl<double, uint64_t, 0x7FF8000000000000ul>(v) || return is_quiet_nan_impl<double, uint64_t, 0x7FF8000000000000ul>(v) ||
is_quiet_nan_impl<double, uint64_t, 0x7FF7FFFFFFFFFFFFu>(v); is_quiet_nan_impl<double, uint64_t, 0x7FF7FFFFFFFFFFFFu>(v);
} }
#else # else
static bool is_quiet_nan(float v) { static bool is_quiet_nan(float v) {
return is_quiet_nan_impl<float, uint32_t, 0x7FC00000u>(v); return is_quiet_nan_impl<float, uint32_t, 0x7FC00000u>(v);
} }
static bool is_quiet_nan(double v) { static bool is_quiet_nan(double v) {
return is_quiet_nan_impl<double, uint64_t, 0x7FF8000000000000ul>(v); return is_quiet_nan_impl<double, uint64_t, 0x7FF8000000000000ul>(v);
} }
#endif # endif
void TestMonsterExtraFloats() { void TestMonsterExtraFloats() {
TEST_EQ(is_quiet_nan(1.0), false); TEST_EQ(is_quiet_nan(1.0), false);
@@ -3420,21 +3420,21 @@ void FixedLengthArrayTest() {
// set memory chunk of size ArrayStruct to 1's // set memory chunk of size ArrayStruct to 1's
std::memset(static_cast<void *>(non_zero_memory), 1, arr_size); std::memset(static_cast<void *>(non_zero_memory), 1, arr_size);
// after placement-new it should be all 0's // after placement-new it should be all 0's
#if defined (_MSC_VER) && defined (_DEBUG) # if defined(_MSC_VER) && defined(_DEBUG)
#undef new # undef new
#endif # endif
MyGame::Example::ArrayStruct *ap = new (non_zero_memory) MyGame::Example::ArrayStruct; MyGame::Example::ArrayStruct *ap =
#if defined (_MSC_VER) && defined (_DEBUG) new (non_zero_memory) MyGame::Example::ArrayStruct;
#define new DEBUG_NEW # if defined(_MSC_VER) && defined(_DEBUG)
#endif # define new DEBUG_NEW
# endif
(void)ap; (void)ap;
for (size_t i = 0; i < arr_size; ++i) { for (size_t i = 0; i < arr_size; ++i) { TEST_EQ(non_zero_memory[i], 0); }
TEST_EQ(non_zero_memory[i], 0);
}
#endif #endif
} }
#if !defined(FLATBUFFERS_SPAN_MINIMAL) && (!defined(_MSC_VER) || _MSC_VER >= 1700) #if !defined(FLATBUFFERS_SPAN_MINIMAL) && \
(!defined(_MSC_VER) || _MSC_VER >= 1700)
void FixedLengthArrayConstructorTest() { void FixedLengthArrayConstructorTest() {
const int32_t nested_a[2] = { 1, 2 }; const int32_t nested_a[2] = { 1, 2 };
MyGame::Example::TestEnum nested_c[2] = { MyGame::Example::TestEnum::A, MyGame::Example::TestEnum nested_c[2] = { MyGame::Example::TestEnum::A,
@@ -3481,8 +3481,7 @@ void FixedLengthArrayConstructorTest() {
TEST_EQ(arr_struct.f()->Get(1), -1); TEST_EQ(arr_struct.f()->Get(1), -1);
} }
#else #else
void FixedLengthArrayConstructorTest() { void FixedLengthArrayConstructorTest() {}
}
#endif #endif
void NativeTypeTest() { void NativeTypeTest() {
@@ -3639,12 +3638,15 @@ void OptionalScalarsTest() {
schemas.push_back("table Monster { mana : bool; }"); schemas.push_back("table Monster { mana : bool; }");
schemas.push_back("table Monster { mana : bool = 42; }"); schemas.push_back("table Monster { mana : bool = 42; }");
schemas.push_back("table Monster { mana : bool = null; }"); schemas.push_back("table Monster { mana : bool = null; }");
schemas.push_back("enum Enum: int {A=0, B=1} " schemas.push_back(
"table Monster { mana : Enum; }"); "enum Enum: int {A=0, B=1} "
schemas.push_back("enum Enum: int {A=0, B=1} " "table Monster { mana : Enum; }");
"table Monster { mana : Enum = B; }"); schemas.push_back(
schemas.push_back("enum Enum: int {A=0, B=1} " "enum Enum: int {A=0, B=1} "
"table Monster { mana : Enum = null; }"); "table Monster { mana : Enum = B; }");
schemas.push_back(
"enum Enum: int {A=0, B=1} "
"table Monster { mana : Enum = null; }");
// Check the FieldDef is correctly set. // Check the FieldDef is correctly set.
for (auto schema = schemas.begin(); schema < schemas.end(); schema++) { for (auto schema = schemas.begin(); schema < schemas.end(); schema++) {