Add flatc '--cpp_std' switch (#5656)

* Add flatc '--cpp_std' switch and sandbox for C++17 code generator

- Added 'flac --cpp_std legacy' for compatibility with old compilers (VS2010);
- Added experimental switch 'flac --cpp_std c++17' for future development;
- Added C++17 sandbox test_cpp17.cpp;
- C++ code generator generates enums with explicit underlying type to avoid problems with the forward and backward schema compatibility;
- Adjusted CMakeLists.txt, CI and generate code scripts to support of introduced '--cpp_std';

* Fix --cpp_std values: c++0x, c++11, c++17

* Add 'cpp::CppStandard' enum

* Add testing engine into test_cpp17

* Rebase to upstream/master

* Set default '--cpp-std C++0x'

* Fix code generation (--cpp_std C++11) in CMakeLists.txt

- Fix dependency declaration of grpctest target

* Revert --cpp-std for the tests from explicit C++11 to flatc default value (C++0x)
This commit is contained in:
Vladimir Glavnyy
2019-12-24 03:13:48 +07:00
committed by Wouter van Oortmerssen
parent 3e8f15df90
commit 44bf719883
41 changed files with 4363 additions and 254 deletions

1
.gitignore vendored
View File

@@ -116,3 +116,4 @@ dart/doc/api/
Cargo.lock
.corpus**
.seed**
grpc/google/

View File

@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 2.8)
cmake_minimum_required(VERSION 2.8.12)
# generate compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include(CheckCXXSymbolExists)
@@ -31,6 +31,13 @@ option(FLATBUFFERS_PACKAGE_REDHAT
option(FLATBUFFERS_PACKAGE_DEBIAN
"Build an deb using the 'package' target."
OFF)
option(FLATBUFFERS_BUILD_CPP17
"Enable the build of c++17 test target. \"
Requirements: Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher."
OFF)
option(FLATBUFFERS_BUILD_LEGACY
"Run C++ code generator with '--cpp-std c++0x' switch."
OFF)
if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
message(WARNING
@@ -128,6 +135,11 @@ set(FlatBuffers_Tests_SRCS
tests/native_type_test_impl.cpp
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
# file generate by running compiler on namespace_test/namespace_test1.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test1_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test2_generated.h
# file generate by running compiler on union_vector/union_vector.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/union_vector/union_vector_generated.h
# file generate by running compiler on tests/arrays_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h
# file generate by running compiler on tests/native_type_test.fbs
@@ -136,6 +148,16 @@ set(FlatBuffers_Tests_SRCS
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h
)
set(FlatBuffers_Tests_CPP17_SRCS
${FlatBuffers_Library_SRCS}
tests/test_assert.h
tests/test_assert.cpp
tests/cpp17/test_cpp17.cpp
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/monster_test_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
)
set(FlatBuffers_Sample_Binary_SRCS
include/flatbuffers/flatbuffers.h
samples/sample_binary.cpp
@@ -170,8 +192,8 @@ set(FlatBuffers_GRPCTest_SRCS
tests/test_builder.cpp
grpc/tests/grpctest.cpp
grpc/tests/message_builder_test.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
)
# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS})
@@ -248,23 +270,28 @@ if(FLATBUFFERS_CODE_COVERAGE)
endif()
function(add_fsanitize_to_target _target _sanitizer)
# FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer.
# List of sanitizer is string starts with '=': "=address,undefined,thread,memory".
if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR
((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9"))
)
set(_sanitizer_flags "=address,undefined")
if(_sanitizer MATCHES "=.*")
# override default by user-defined sanitizer list
set(_sanitizer_flags ${_sanitizer})
if(WIN32)
target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING)
message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to ${_target}")
else()
# FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer.
# List of sanitizer is string starts with '=': "=address,undefined,thread,memory".
if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR
((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9"))
)
set(_sanitizer_flags "=address,undefined")
if(_sanitizer MATCHES "=.*")
# override default by user-defined sanitizer list
set(_sanitizer_flags ${_sanitizer})
endif()
target_compile_options(${_target} PRIVATE
-g -fsigned-char -fno-omit-frame-pointer
"-fsanitize${_sanitizer_flags}")
target_link_libraries(${_target} PRIVATE
"-fsanitize${_sanitizer_flags}")
set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON)
message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}")
endif()
target_compile_options(${_target} PRIVATE
-g -fsigned-char -fno-omit-frame-pointer
"-fsanitize${_sanitizer_flags}")
target_link_libraries(${_target} PRIVATE
"-fsanitize${_sanitizer_flags}")
set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON)
message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}")
endif()
endfunction()
@@ -278,7 +305,7 @@ include_directories(grpc)
if(FLATBUFFERS_BUILD_FLATLIB)
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
# CMake > 2.8.11: Attach header directory for when build via add_subdirectory().
# Attach header directory for when build via add_subdirectory().
target_include_directories(flatbuffers INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
@@ -321,7 +348,12 @@ if(FLATBUFFERS_BUILD_SHAREDLIB)
endif()
function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT)
message(STATUS "Add the code-generation command for the `${SRC_FBS}` schema.")
if(FLATBUFFERS_BUILD_LEGACY)
set(OPT ${OPT};--cpp-std c++0x)
else()
# --cpp-std is defined by flatc default settings.
endif()
message(STATUS "Add the code-generation command for the `${SRC_FBS}` schema with '${OPT}'")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
add_custom_command(
@@ -336,7 +368,7 @@ function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT)
endfunction()
function(compile_flatbuffers_schema_to_cpp SRC_FBS)
compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare")
compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare")
endfunction()
function(compile_flatbuffers_schema_to_binary SRC_FBS)
@@ -350,10 +382,14 @@ function(compile_flatbuffers_schema_to_binary SRC_FBS)
endfunction()
if(FLATBUFFERS_BUILD_TESTS)
# TODO: Replace this sequence by custom_target which calls the generate_code.bat(sh).
compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
compile_flatbuffers_schema_to_cpp(tests/namespace_test/namespace_test1.fbs)
compile_flatbuffers_schema_to_cpp(tests/namespace_test/namespace_test2.fbs)
compile_flatbuffers_schema_to_cpp(tests/union_vector/union_vector.fbs)
compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "")
compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
if(NOT (MSVC AND MSVC_VERSION LESS 1900))
if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
endif()
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
@@ -362,12 +398,7 @@ if(FLATBUFFERS_BUILD_TESTS)
PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1)
if(FLATBUFFERS_CODE_SANITIZE)
if(WIN32)
target_compile_definitions(flattests PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING)
message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to flattests")
else()
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
endif()
endif()
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
@@ -375,6 +406,22 @@ if(FLATBUFFERS_BUILD_TESTS)
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
if(FLATBUFFERS_BUILD_CPP17)
# Don't generate header for flattests_cpp17 target.
# This target uses "generated_cpp17/monster_test_generated.h"
# produced by direct call of generate_code.bat(sh) script.
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
target_compile_definitions(flattests_cpp17 PRIVATE
FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1
)
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
endif()
endif(FLATBUFFERS_BUILD_CPP17)
endif()
if(FLATBUFFERS_BUILD_GRPCTEST)
@@ -391,7 +438,11 @@ if(FLATBUFFERS_BUILD_GRPCTEST)
INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src)
LINK_DIRECTORIES(${GRPC_INSTALL_PATH}/lib)
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
target_link_libraries(grpctest grpc++_unsecure grpc_unsecure gpr pthread dl)
target_link_libraries(grpctest PRIVATE grpc++_unsecure grpc_unsecure gpr pthread dl)
if(NOT WIN32 AND FLATBUFFERS_CODE_SANITIZE)
# GRPC test has problems with alignment and will fail under ASAN/UBSAN.
# add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE})
endif()
endif()
include(CMake/Version.cmake)

View File

@@ -10,9 +10,13 @@ environment:
# Workaround for https://github.com/conda/conda-build/issues/636
PYTHONIOENCODING: UTF-8
CONDA_INSTALL_LOCN: "C:\\Miniconda35-x64"
CMAKE_OPTIONS: ""
CPP_TEST_OPTIONS: ""
matrix:
- CMAKE_VS_VERSION: "10 2010"
CMAKE_OPTIONS: "-DFLATBUFFERS_BUILD_LEGACY=1"
CPP_TEST_OPTIONS: "--std-cpp c++0x"
MONSTER_EXTRA: "skip"
- CMAKE_VS_VERSION: "12 2013"
@@ -31,7 +35,7 @@ configuration:
before_build:
- set MONSTER_EXTRA=%MONSTER_EXTRA%
- cmake -G"Visual Studio %CMAKE_VS_VERSION%" -DFLATBUFFERS_CODE_SANITIZE=1 .
- cmake . -G"Visual Studio %CMAKE_VS_VERSION%" -DFLATBUFFERS_CODE_SANITIZE=1 %CMAKE_OPTIONS%
# This cuts down on a lot of noise generated by xamarin warnings.
- del "C:\Program Files (x86)\MSBuild\14.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets"
@@ -55,7 +59,7 @@ test_script:
- call .appveyor\check-generate-code.bat -b %CONFIGURATION%
- "cd tests"
- rem "Building all code"
- generate_code.bat -b %CONFIGURATION%
- generate_code.bat -b %CONFIGURATION% %CPP_TEST_OPTIONS%
- 7z a GeneratedMyGameCode.zip MyGame\
- rem "---------------- C++ -----------------"
- "cd .."

View File

@@ -132,6 +132,11 @@ Additional options:
std::string from Flatbuffers, but (char* + length). This allows efficient
construction of custom string types, including zero-copy construction.
- `--cpp-std CPP_STD` : Generate a C++ code using features of selected C++ standard.
Supported `CPP_STD` values:
* `c++0x` - generate code compatible with old compilers (VS2010).
* `c++11` - use C++11 code generator (default);
- `--object-prefix` : Customise class prefix for C++ object-based API.
- `--object-suffix` : Customise class suffix for C++ object-based API.

View File

@@ -5,7 +5,7 @@ grpc_1_15_1_githash=1a60e6971f428323245a930031ad267bb3142ba4
function build_grpc () {
git clone https://github.com/grpc/grpc.git google/grpc
cd google/grpc
git checkout ${grpc_1_15_1_githash}
git checkout ${grpc_1_15_1_githash}
git submodule update --init
make
make install prefix=`pwd`/install

View File

@@ -8,18 +8,19 @@ using MyGame::Example::CreateStat;
using MyGame::Example::Vec3;
bool verify(flatbuffers::grpc::Message<Monster> &msg,
const std::string &expected_name, Color color) {
const std::string &expected_name, Color expected_color) {
const Monster *monster = msg.GetRoot();
return (monster->name()->str() == expected_name) &&
(monster->color() == color);
const auto name = monster->name()->str();
const auto color = monster->color();
TEST_EQ(name, expected_name);
TEST_EQ(color, expected_color);
return (name == expected_name) && (color == expected_color);
}
bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb,
const std::string &expected_name, Color color) {
const std::string &expected_name, Color expected_color) {
flatbuffers::grpc::Message<Monster> msg = mbb.ReleaseMessage<Monster>();
const Monster *monster = msg.GetRoot();
return (monster->name()->str() == expected_name) &&
(monster->color() == color);
return verify(msg, expected_name, expected_color);
}
void builder_move_assign_after_releaseraw_test(
@@ -36,7 +37,7 @@ void builder_move_assign_after_releaseraw_test(
// Move into a released builder.
dst = std::move(src);
TEST_EQ(dst.GetSize(), src_size);
TEST_ASSERT(release_n_verify(dst, m2_name, m2_color));
TEST_ASSERT(release_n_verify(dst, m2_name(), m2_color()));
TEST_EQ(src.GetSize(), 0);
grpc_slice_unref(slice);
}
@@ -53,7 +54,7 @@ struct BuilderReuseTests<flatbuffers::grpc::MessageBuilder, SrcBuilder> {
auto root_offset1 = populate1(mb);
mb.Finish(root_offset1);
buffers.push_back(mb.ReleaseMessage<Monster>());
TEST_ASSERT_FUNC(verify(buffers[i], m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color()));
}
}
@@ -69,7 +70,7 @@ struct BuilderReuseTests<flatbuffers::grpc::MessageBuilder, SrcBuilder> {
auto root_offset1 = populate1(mb);
mb.Finish(root_offset1);
buffers.push_back(mb.Release());
TEST_ASSERT_FUNC(verify(buffers[i], m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color()));
}
}
@@ -83,7 +84,7 @@ struct BuilderReuseTests<flatbuffers::grpc::MessageBuilder, SrcBuilder> {
size_t size, offset;
grpc_slice slice;
const uint8_t *buf = mb.ReleaseRaw(size, offset, slice);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
grpc_slice_unref(slice);
}
}
@@ -103,7 +104,7 @@ struct BuilderReuseTests<flatbuffers::grpc::MessageBuilder, SrcBuilder> {
auto root_offset1 = populate1(dst);
dst.Finish(root_offset1);
buffers.push_back(dst.Release());
TEST_ASSERT_FUNC(verify(buffers[i], m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color()));
// bring dst back to life.
SrcBuilder src;
@@ -126,7 +127,7 @@ struct BuilderReuseTests<flatbuffers::grpc::MessageBuilder, SrcBuilder> {
auto root_offset1 = populate1(dst);
dst.Finish(root_offset1);
buffers.push_back(dst.ReleaseMessage<Monster>());
TEST_ASSERT_FUNC(verify(buffers[i], m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color()));
// bring dst back to life.
SrcBuilder src;
@@ -147,7 +148,7 @@ struct BuilderReuseTests<flatbuffers::grpc::MessageBuilder, SrcBuilder> {
size_t size, offset;
grpc_slice slice = grpc_empty_slice();
const uint8_t *buf = dst.ReleaseRaw(size, offset, slice);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
grpc_slice_unref(slice);
SrcBuilder src;
@@ -199,7 +200,7 @@ void slice_allocator_tests() {
void populate_first_half(MyGame::Example::MonsterBuilder &wrapper,
flatbuffers::Offset<flatbuffers::String> name_offset) {
wrapper.add_name(name_offset);
wrapper.add_color(m1_color);
wrapper.add_color(m1_color());
}
/// This function does not populate exactly the second half of the table. But it
@@ -230,7 +231,7 @@ void test_only_hack_update_fbb_reference(
void builder_move_ctor_conversion_before_finish_half_n_half_table_test() {
for (size_t initial_size = 4; initial_size <= 2048; initial_size *= 2) {
flatbuffers::FlatBufferBuilder fbb(initial_size);
auto name_offset = fbb.CreateString(m1_name);
auto name_offset = fbb.CreateString(m1_name());
MyGame::Example::MonsterBuilder monsterBuilder(
fbb); // starts a table in FlatBufferBuilder
populate_first_half(monsterBuilder, name_offset);
@@ -238,7 +239,7 @@ void builder_move_ctor_conversion_before_finish_half_n_half_table_test() {
test_only_hack_update_fbb_reference(monsterBuilder, mb); // hack
populate_second_half(monsterBuilder);
mb.Finish(monsterBuilder.Finish()); // ends the table in MessageBuilder
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color()));
TEST_EQ_FUNC(fbb.GetSize(), 0);
}
}
@@ -246,15 +247,24 @@ void builder_move_ctor_conversion_before_finish_half_n_half_table_test() {
/// This test populates a COMPLETE inner table before move conversion and later
/// populates more members in the outer table.
void builder_move_ctor_conversion_before_finish_test() {
for (size_t initial_size = 4; initial_size <= 2048; initial_size *= 2) {
for (size_t initial_size = 1; initial_size <= 2048; initial_size += 1) {
flatbuffers::FlatBufferBuilder fbb(initial_size);
auto stat_offset = CreateStat(fbb, fbb.CreateString("SomeId"), 0, 0);
flatbuffers::grpc::MessageBuilder mb(std::move(fbb));
auto monster_offset =
CreateMonster(mb, 0, 150, 100, mb.CreateString(m1_name), 0, m1_color,
CreateMonster(mb, 0, 150, 100, mb.CreateString(m1_name()), 0, m1_color(),
Any_NONE, 0, 0, 0, 0, 0, 0, stat_offset);
mb.Finish(monster_offset);
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name, m1_color));
{
auto mon = flatbuffers::GetRoot<Monster>(mb.GetBufferPointer());
TEST_NOTNULL(mon);
TEST_NOTNULL(mon->name());
TEST_EQ_STR(mon->name()->c_str(), m1_name().c_str());
TEST_EQ(mon->color(), m1_color());
}
TEST_EQ(1, MyGame::Example::Color_Red);
TEST_EQ(1, m1_color());
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color()));
TEST_EQ_FUNC(fbb.GetSize(), 0);
}
}
@@ -269,7 +279,7 @@ void builder_move_assign_conversion_before_finish_half_n_half_table_test() {
for (int i = 0; i < 5; ++i) {
flatbuffers::FlatBufferBuilder fbb;
auto name_offset = fbb.CreateString(m1_name);
auto name_offset = fbb.CreateString(m1_name());
MyGame::Example::MonsterBuilder monsterBuilder(
fbb); // starts a table in FlatBufferBuilder
populate_first_half(monsterBuilder, name_offset);
@@ -277,7 +287,7 @@ void builder_move_assign_conversion_before_finish_half_n_half_table_test() {
test_only_hack_update_fbb_reference(monsterBuilder, mb); // hack
populate_second_half(monsterBuilder);
mb.Finish(monsterBuilder.Finish()); // ends the table in MessageBuilder
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color()));
TEST_EQ_FUNC(fbb.GetSize(), 0);
}
}
@@ -292,10 +302,10 @@ void builder_move_assign_conversion_before_finish_test() {
auto stat_offset = CreateStat(fbb, fbb.CreateString("SomeId"), 0, 0);
mb = std::move(fbb);
auto monster_offset =
CreateMonster(mb, 0, 150, 100, mb.CreateString(m1_name), 0, m1_color,
CreateMonster(mb, 0, 150, 100, mb.CreateString(m1_name()), 0, m1_color(),
Any_NONE, 0, 0, 0, 0, 0, 0, stat_offset);
mb.Finish(monster_offset);
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color()));
TEST_EQ_FUNC(fbb.GetSize(), 0);
}
}
@@ -306,7 +316,7 @@ void builder_move_ctor_conversion_after_finish_test() {
flatbuffers::FlatBufferBuilder fbb;
fbb.Finish(populate1(fbb));
flatbuffers::grpc::MessageBuilder mb(std::move(fbb));
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color()));
TEST_EQ_FUNC(fbb.GetSize(), 0);
}
@@ -319,7 +329,7 @@ void builder_move_assign_conversion_after_finish_test() {
for (int i = 0; i < 5; ++i) {
fbb.Finish(populate1(fbb));
mb = std::move(fbb);
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color()));
TEST_EQ_FUNC(fbb.GetSize(), 0);
}
}

View File

@@ -43,6 +43,20 @@ template<> inline bool IsTheSameAs<double>(double e, double def) {
}
#endif
// Check 'v' is out of closed range [low; high].
// Workaround for GCC warning [-Werror=type-limits]:
// comparison is always true due to limited range of data type.
template<typename T>
inline bool IsOutRange(const T &v, const T &low, const T &high) {
return (v < low) || (high < v);
}
// Check 'v' is in closed range [low; high].
template<typename T>
inline bool IsInRange(const T &v, const T &low, const T &high) {
return !IsOutRange(v, low, high);
}
// Wrapper for uoffset_t to allow safe template specialization.
// Value is allowed to be 0 to indicate a null object (see e.g. AddOffset).
template<typename T> struct Offset {
@@ -351,6 +365,7 @@ template<typename T> class Vector {
// This class is a pointer. Copying will therefore create an invalid object.
// Private and unimplemented copy constructor.
Vector(const Vector &);
Vector& operator=(const Vector&);
template<typename K> static int KeyCompare(const void *ap, const void *bp) {
const K *key = reinterpret_cast<const K *>(ap);
@@ -381,6 +396,7 @@ class VectorOfAny {
private:
VectorOfAny(const VectorOfAny &);
VectorOfAny &operator=(const VectorOfAny &);
};
#ifndef FLATBUFFERS_CPP98_STL
@@ -2377,6 +2393,12 @@ class Struct FLATBUFFERS_FINAL_CLASS {
uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; }
private:
// private constructor & copy constructor: you obtain instances of this
// class by pointing to existing data only
Struct();
Struct(const Struct &);
Struct &operator=(const Struct &);
uint8_t data_[1];
};
@@ -2489,6 +2511,7 @@ class Table {
// class by pointing to existing data only
Table();
Table(const Table &other);
Table &operator=(const Table &);
uint8_t data_[1];
};

View File

@@ -14,6 +14,9 @@
* limitations under the License.
*/
#ifndef FLATBUFFERS_FLATC_H_
#define FLATBUFFERS_FLATC_H_
#include <functional>
#include <limits>
#include <string>
@@ -22,11 +25,11 @@
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#ifndef FLATC_H_
# define FLATC_H_
namespace flatbuffers {
extern void LogCompilerWarn(const std::string &warn);
extern void LogCompilerError(const std::string &err);
class FlatCompiler {
public:
// Output generator for the various programming languages and formats we
@@ -94,4 +97,4 @@ class FlatCompiler {
} // namespace flatbuffers
#endif // FLATC_H_
#endif // FLATBUFFERS_FLATC_H_

View File

@@ -556,6 +556,7 @@ struct IDLOptions {
bool force_defaults;
bool java_primitive_has_method;
std::vector<std::string> cpp_includes;
std::string cpp_std;
// Possible options for the more general generator below.
enum Language {

View File

@@ -97,7 +97,7 @@ inline const char * const *EnumNamesBaseType() {
}
inline const char *EnumNameBaseType(BaseType e) {
if (e < None || e > Array) return "";
if (flatbuffers::IsOutRange(e, None, Array)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesBaseType()[index];
}

View File

@@ -15,4 +15,4 @@
set buildtype=Release
if "%1"=="-b" set buildtype=%2
..\%buildtype%\flatc.exe --cpp --no-prefix -o ../include/flatbuffers reflection.fbs || exit /b 1
..\%buildtype%\flatc.exe --cpp --cpp-std c++0x --no-prefix -o ../include/flatbuffers reflection.fbs || exit /b 1

View File

@@ -15,4 +15,4 @@
# limitations under the License.
set -e
../flatc -c --no-prefix -o ../include/flatbuffers reflection.fbs
../flatc -c --cpp-std c++0x --no-prefix -o ../include/flatbuffers reflection.fbs

View File

@@ -58,7 +58,7 @@ inline const char * const *EnumNamesColor() {
}
inline const char *EnumNameColor(Color e) {
if (e < Color_Red || e > Color_Blue) return "";
if (flatbuffers::IsOutRange(e, Color_Red, Color_Blue)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesColor()[index];
}
@@ -88,7 +88,7 @@ inline const char * const *EnumNamesEquipment() {
}
inline const char *EnumNameEquipment(Equipment e) {
if (e < Equipment_NONE || e > Equipment_Weapon) return "";
if (flatbuffers::IsOutRange(e, Equipment_NONE, Equipment_Weapon)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesEquipment()[index];
}

View File

@@ -116,6 +116,11 @@ std::string FlatCompiler::GetUsageString(const char *program_name) const {
" (see the --cpp-str-flex-ctor option to change this behavior).\n"
" --cpp-str-flex-ctor Don't construct custom string types by passing std::string\n"
" from Flatbuffers, but (char* + length).\n"
" --cpp-std CPP_STD Generate a C++ code using features of selected C++ standard.\n"
" Supported CPP_STD values:\n"
" * 'c++0x' - generate code compatible with old compilers;\n"
" * 'c++11' - use C++11 code generator (default);\n"
" * 'c++17' - use C++17 features in generated code (experimental).\n"
" --object-prefix Customise class prefix for C++ object-based API.\n"
" --object-suffix Customise class suffix for C++ object-based API.\n"
" Default value is \"T\".\n"
@@ -281,7 +286,7 @@ int FlatCompiler::Compile(int argc, const char **argv) {
opts.include_dependence_headers = false;
} else if (arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n");
Warn("warning: --gen-includes is deprecated (it is now default)\n");
} else if (arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
@@ -333,6 +338,9 @@ int FlatCompiler::Compile(int argc, const char **argv) {
opts.java_primitive_has_method = true;
} else if (arg == "--flexbuffers") {
opts.use_flexbuffers = true;
} else if(arg == "--cpp-std") {
if (++argi >= argc) Error("missing C++ standard specification" + arg, true);
opts.cpp_std = argv[argi];
} else {
for (size_t i = 0; i < params_.num_generators; ++i) {
if (arg == params_.generators[i].generator_opt_long ||

View File

@@ -30,10 +30,20 @@ static void Error(const flatbuffers::FlatCompiler *flatc,
const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) { printf("%s: ", g_program_name); }
printf("error: %s\n", err.c_str());
if (usage) { printf("%s", flatc->GetUsageString(g_program_name).c_str()); }
if (usage && flatc) { printf("%s", flatc->GetUsageString(g_program_name).c_str()); }
exit(1);
}
namespace flatbuffers {
void LogCompilerWarn(const std::string &warn) {
Warn(static_cast<const flatbuffers::FlatCompiler *>(nullptr), warn, true);
}
void LogCompilerError(const std::string &err) {
Error(static_cast<const flatbuffers::FlatCompiler *>(nullptr), err, false,
true);
}
} // namespace flatbuffers
int main(int argc, const char *argv[]) {
// Prevent Appveyor-CI hangs.
flatbuffers::SetupDefaultCRTReportMode();

View File

@@ -20,13 +20,16 @@
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/flatc.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
// Pedantic warning free version of toupper().
inline char ToUpper(char c) { return static_cast<char>(::toupper(c)); }
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.
@@ -51,12 +54,30 @@ static std::string GeneratedFileName(const std::string &path,
}
namespace cpp {
enum CppStandard { CPP_STD_X0 = 0, CPP_STD_11, CPP_STD_17 };
// 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
};
class CppGenerator : public BaseGenerator {
public:
CppGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
const std::string &file_name, IDLOptionsCpp opts)
: BaseGenerator(parser, path, file_name, "", "::"),
cur_name_space_(nullptr),
opts_(opts),
float_const_gen_("std::numeric_limits<double>::",
"std::numeric_limits<float>::", "quiet_NaN()",
"infinity()") {
@@ -196,19 +217,18 @@ class CppGenerator : public BaseGenerator {
auto noext = flatbuffers::StripExtension(it->second);
auto basename = flatbuffers::StripPath(noext);
code_ += "#include \"" + parser_.opts.include_prefix +
(parser_.opts.keep_include_path ? noext : basename) +
"_generated.h\"";
code_ += "#include \"" + opts_.include_prefix +
(opts_.keep_include_path ? noext : basename) + "_generated.h\"";
num_includes++;
}
if (num_includes) code_ += "";
}
void GenExtraIncludes() {
for (std::size_t i = 0; i < parser_.opts.cpp_includes.size(); ++i) {
code_ += "#include \"" + parser_.opts.cpp_includes[i] + "\"";
for (std::size_t i = 0; i < opts_.cpp_includes.size(); ++i) {
code_ += "#include \"" + opts_.cpp_includes[i] + "\"";
}
if (!parser_.opts.cpp_includes.empty()) { code_ += ""; }
if (!opts_.cpp_includes.empty()) { code_ += ""; }
}
std::string EscapeKeyword(const std::string &name) const {
@@ -232,9 +252,7 @@ class CppGenerator : public BaseGenerator {
code_ += "#define " + include_guard;
code_ += "";
if (parser_.opts.gen_nullable) {
code_ += "#pragma clang system_header\n\n";
}
if (opts_.gen_nullable) { code_ += "#pragma clang system_header\n\n"; }
code_ += "#include \"flatbuffers/flatbuffers.h\"";
if (parser_.uses_flexbuffers_) {
@@ -242,7 +260,7 @@ class CppGenerator : public BaseGenerator {
}
code_ += "";
if (parser_.opts.include_dependence_headers) { GenIncludeDependencies(); }
if (opts_.include_dependence_headers) { GenIncludeDependencies(); }
GenExtraIncludes();
FLATBUFFERS_ASSERT(!cur_name_space_);
@@ -255,9 +273,8 @@ class CppGenerator : public BaseGenerator {
if (!struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
code_ += "struct " + Name(struct_def) + ";";
if (parser_.opts.generate_object_based_api) {
auto nativeName =
NativeName(Name(struct_def), &struct_def, parser_.opts);
if (opts_.generate_object_based_api) {
auto nativeName = NativeName(Name(struct_def), &struct_def, opts_);
if (!struct_def.fixed) { code_ += "struct " + nativeName + ";"; }
}
code_ += "";
@@ -265,14 +282,13 @@ class CppGenerator : public BaseGenerator {
}
// Generate forward declarations for all equal operators
if (parser_.opts.generate_object_based_api && parser_.opts.gen_compare) {
if (opts_.generate_object_based_api && opts_.gen_compare) {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
const auto &struct_def = **it;
if (!struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
auto nativeName =
NativeName(Name(struct_def), &struct_def, parser_.opts);
auto nativeName = NativeName(Name(struct_def), &struct_def, opts_);
code_ += "bool operator==(const " + nativeName + " &lhs, const " +
nativeName + " &rhs);";
code_ += "bool operator!=(const " + nativeName + " &lhs, const " +
@@ -283,7 +299,7 @@ class CppGenerator : public BaseGenerator {
}
// Generate preablmle code for mini reflection.
if (parser_.opts.mini_reflect != IDLOptions::kNone) {
if (opts_.mini_reflect != IDLOptions::kNone) {
// To break cyclic dependencies, first pre-declare all tables/structs.
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
@@ -342,7 +358,7 @@ class CppGenerator : public BaseGenerator {
}
// Generate code for mini reflection.
if (parser_.opts.mini_reflect != IDLOptions::kNone) {
if (opts_.mini_reflect != IDLOptions::kNone) {
// Then the unions/enums that may refer to them.
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
@@ -393,7 +409,7 @@ class CppGenerator : public BaseGenerator {
code_ += "}";
code_ += "";
if (parser_.opts.mutable_buffer) {
if (opts_.mutable_buffer) {
code_ += "inline \\";
code_ += "{{STRUCT_NAME}} *GetMutable{{STRUCT_NAME}}(void *buf) {";
code_ += " return flatbuffers::GetMutableRoot<{{STRUCT_NAME}}>(buf);";
@@ -466,10 +482,10 @@ class CppGenerator : public BaseGenerator {
code_ += "}";
code_ += "";
if (parser_.opts.generate_object_based_api) {
if (opts_.generate_object_based_api) {
// A convenient root unpack function.
auto native_name =
NativeName(WrapInNameSpace(struct_def), &struct_def, parser_.opts);
NativeName(WrapInNameSpace(struct_def), &struct_def, opts_);
code_.SetValue("UNPACK_RETURN",
GenTypeNativePtr(native_name, nullptr, false));
code_.SetValue("UNPACK_TYPE",
@@ -511,6 +527,9 @@ class CppGenerator : public BaseGenerator {
// This tracks the current namespace so we can insert namespace declarations.
const Namespace *cur_name_space_;
const IDLOptionsCpp opts_;
const TypedFloatConstantGenerator float_const_gen_;
const Namespace *CurrentNameSpace() const { return cur_name_space_; }
// Translates a qualified name in flatbuffer text format to the same name in
@@ -606,7 +625,7 @@ class CppGenerator : public BaseGenerator {
}
std::string NullableExtension() {
return parser_.opts.gen_nullable ? " _Nullable " : "";
return opts_.gen_nullable ? " _Nullable " : "";
}
static std::string NativeName(const std::string &name, const StructDef *sd,
@@ -617,12 +636,12 @@ class CppGenerator : public BaseGenerator {
const std::string &PtrType(const FieldDef *field) {
auto attr = field ? field->attributes.Lookup("cpp_ptr_type") : nullptr;
return attr ? attr->constant : parser_.opts.cpp_object_api_pointer_type;
return attr ? attr->constant : opts_.cpp_object_api_pointer_type;
}
const std::string NativeString(const FieldDef *field) {
auto attr = field ? field->attributes.Lookup("cpp_str_type") : nullptr;
auto &ret = attr ? attr->constant : parser_.opts.cpp_object_api_string_type;
auto &ret = attr ? attr->constant : opts_.cpp_object_api_string_type;
if (ret.empty()) { return "std::string"; }
return ret;
}
@@ -631,8 +650,7 @@ class CppGenerator : public BaseGenerator {
auto attr = field
? (field->attributes.Lookup("cpp_str_flex_ctor") != nullptr)
: false;
auto ret =
attr ? attr : parser_.opts.cpp_object_api_string_flexible_constructor;
auto ret = attr ? attr : opts_.cpp_object_api_string_flexible_constructor;
return ret && NativeString(field) !=
"std::string"; // Only for custom string types.
}
@@ -643,7 +661,7 @@ class CppGenerator : public BaseGenerator {
if (ptr_type != "naked") {
return (ptr_type != "default_ptr_type"
? ptr_type
: parser_.opts.cpp_object_api_pointer_type) +
: opts_.cpp_object_api_pointer_type) +
"<" + type + ">";
} else if (is_constructor) {
return "";
@@ -687,9 +705,8 @@ class CppGenerator : public BaseGenerator {
return GenTypeNativePtr(type_name, &field, false);
}
} else {
return GenTypeNativePtr(
NativeName(type_name, type.struct_def, parser_.opts), &field,
false);
return GenTypeNativePtr(NativeName(type_name, type.struct_def, opts_),
&field, false);
}
}
case BASE_TYPE_UNION: {
@@ -711,6 +728,12 @@ class CppGenerator : public BaseGenerator {
return GenTypeBasic(type, user_facing_type) + afterbasic;
} else if (IsArray(type)) {
auto element_type = type.VectorType();
// Check if enum arrays are used in C++ without specifying --scoped-enums
if (IsEnum(element_type) && !opts_.g_only_fixed_enums) {
LogCompilerError(
"--scoped-enums must be enabled to use enum arrays in C++");
FLATBUFFERS_ASSERT(true);
}
return beforeptr +
(IsScalar(element_type.base_type)
? GenTypeBasic(element_type, user_facing_type)
@@ -721,23 +744,16 @@ class CppGenerator : public BaseGenerator {
}
}
std::string GenEnumDecl(const EnumDef &enum_def) const {
const IDLOptions &opts = parser_.opts;
return (opts.scoped_enums ? "enum class " : "enum ") + Name(enum_def);
}
std::string GenEnumValDecl(const EnumDef &enum_def,
const std::string &enum_val) const {
const IDLOptions &opts = parser_.opts;
return opts.prefixed_enums ? Name(enum_def) + "_" + enum_val : enum_val;
return opts_.prefixed_enums ? Name(enum_def) + "_" + enum_val : enum_val;
}
std::string GetEnumValUse(const EnumDef &enum_def,
const EnumVal &enum_val) const {
const IDLOptions &opts = parser_.opts;
if (opts.scoped_enums) {
if (opts_.scoped_enums) {
return Name(enum_def) + "::" + Name(enum_val);
} else if (opts.prefixed_enums) {
} else if (opts_.prefixed_enums) {
return Name(enum_def) + "_" + Name(enum_val);
} else {
return Name(enum_val);
@@ -942,7 +958,7 @@ class CppGenerator : public BaseGenerator {
code_ += " static const int64_t values[] = { {{VALUES}} };";
}
auto has_names =
num_fields && parser_.opts.mini_reflect == IDLOptions::kTypesAndNames;
num_fields && opts_.mini_reflect == IDLOptions::kTypesAndNames;
if (has_names) {
code_ += " static const char * const names[] = {";
code_ += " {{NAMES}}";
@@ -969,14 +985,11 @@ class CppGenerator : public BaseGenerator {
code_.SetValue("BASE_TYPE", GenTypeBasic(enum_def.underlying_type, false));
GenComment(enum_def.doc_comment);
code_ += GenEnumDecl(enum_def) + "\\";
// MSVC doesn't support int64/uint64 enum without explicitly declared enum
// type. The value 4611686018427387904ULL is truncated to zero with warning:
// "warning C4309: 'initializing': truncation of constant value".
auto add_type = parser_.opts.scoped_enums;
add_type |= (enum_def.underlying_type.base_type == BASE_TYPE_LONG);
add_type |= (enum_def.underlying_type.base_type == BASE_TYPE_ULONG);
if (add_type) code_ += " : {{BASE_TYPE}}\\";
code_ +=
(opts_.scoped_enums ? "enum class " : "enum ") + Name(enum_def) + "\\";
if (opts_.g_only_fixed_enums) {
code_ += " : {{BASE_TYPE}}\\";
}
code_ += " {";
code_.SetValue("SEP", ",");
@@ -995,7 +1008,7 @@ class CppGenerator : public BaseGenerator {
const EnumVal *minv = enum_def.MinValue();
const EnumVal *maxv = enum_def.MaxValue();
if (parser_.opts.scoped_enums || parser_.opts.prefixed_enums) {
if (opts_.scoped_enums || opts_.prefixed_enums) {
FLATBUFFERS_ASSERT(minv && maxv);
code_.SetValue("SEP", ",\n");
@@ -1022,7 +1035,7 @@ class CppGenerator : public BaseGenerator {
code_ += "";
code_ += "};";
if (parser_.opts.scoped_enums && enum_def.attributes.Lookup("bit_flags")) {
if (opts_.scoped_enums && enum_def.attributes.Lookup("bit_flags")) {
code_ +=
"FLATBUFFERS_DEFINE_BITMASK_OPERATORS({{ENUM_NAME}}, {{BASE_TYPE}})";
}
@@ -1076,9 +1089,10 @@ class CppGenerator : public BaseGenerator {
code_ += "inline const char *EnumName{{ENUM_NAME}}({{ENUM_NAME}} e) {";
code_ += " if (e < " + GetEnumValUse(enum_def, *enum_def.MinValue()) +
" || e > " + GetEnumValUse(enum_def, *enum_def.MaxValue()) +
") return \"\";";
code_ += " if (flatbuffers::IsOutRange(e, " +
GetEnumValUse(enum_def, *enum_def.MinValue()) + ", " +
GetEnumValUse(enum_def, *enum_def.MaxValue()) +
")) return \"\";";
code_ += " const size_t index = static_cast<size_t>(e)\\";
if (enum_def.MinValue()->IsNonZero()) {
@@ -1129,7 +1143,7 @@ class CppGenerator : public BaseGenerator {
}
}
if (parser_.opts.generate_object_based_api && enum_def.is_union) {
if (opts_.generate_object_based_api && enum_def.is_union) {
// Generate a union type
code_.SetValue("NAME", Name(enum_def));
FLATBUFFERS_ASSERT(enum_def.Lookup("NONE"));
@@ -1185,7 +1199,7 @@ class CppGenerator : public BaseGenerator {
const auto native_type =
NativeName(GetUnionElement(ev, true, true, true),
ev.union_type.struct_def, parser_.opts);
ev.union_type.struct_def, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_.SetValue("NATIVE_NAME", Name(ev));
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
@@ -1204,7 +1218,7 @@ class CppGenerator : public BaseGenerator {
code_ += "};";
code_ += "";
if (parser_.opts.gen_compare) {
if (opts_.gen_compare) {
code_ += "";
code_ +=
"inline bool operator==(const {{NAME}}Union &lhs, const "
@@ -1219,7 +1233,7 @@ class CppGenerator : public BaseGenerator {
if (ev.IsNonZero()) {
const auto native_type =
NativeName(GetUnionElement(ev, true, true, true),
ev.union_type.struct_def, parser_.opts);
ev.union_type.struct_def, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_ += " case {{NATIVE_ID}}: {";
code_ +=
@@ -1318,7 +1332,7 @@ class CppGenerator : public BaseGenerator {
code_ += "}";
code_ += "";
if (parser_.opts.generate_object_based_api) {
if (opts_.generate_object_based_api) {
// Generate union Unpack() and Pack() functions.
code_ += "inline " + UnionUnPackSignature(enum_def, false) + " {";
code_ += " switch (type) {";
@@ -1358,9 +1372,8 @@ class CppGenerator : public BaseGenerator {
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, parser_.opts));
code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
ev.union_type.struct_def, opts_));
code_.SetValue("NAME", GetUnionElement(ev, false, true));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<const {{TYPE}} *>(value);";
@@ -1394,9 +1407,8 @@ class CppGenerator : public BaseGenerator {
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, parser_.opts));
code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
ev.union_type.struct_def, opts_));
code_ += " case {{LABEL}}: {";
bool copyable = true;
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
@@ -1440,9 +1452,8 @@ class CppGenerator : public BaseGenerator {
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, parser_.opts));
code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
ev.union_type.struct_def, opts_));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<{{TYPE}} *>(value);";
code_ += " delete ptr;";
@@ -1484,7 +1495,7 @@ class CppGenerator : public BaseGenerator {
void GenFullyQualifiedNameGetter(const StructDef &struct_def,
const std::string &name) {
if (!parser_.opts.generate_name_strings) { return; }
if (!opts_.generate_name_strings) { return; }
auto fullname = struct_def.defined_namespace->GetFullyQualifiedName(name);
code_.SetValue("NAME", fullname);
code_.SetValue("CONSTEXPR", "FLATBUFFERS_CONSTEXPR");
@@ -1619,7 +1630,7 @@ class CppGenerator : public BaseGenerator {
}
code_.SetValue("NATIVE_NAME",
NativeName(Name(struct_def), &struct_def, parser_.opts));
NativeName(Name(struct_def), &struct_def, opts_));
code_.SetValue("INIT_LIST", initializer_list);
code_ += " {{NATIVE_NAME}}(){{INIT_LIST}} {";
@@ -1689,8 +1700,7 @@ class CppGenerator : public BaseGenerator {
}
void GenNativeTable(const StructDef &struct_def) {
const auto native_name =
NativeName(Name(struct_def), &struct_def, parser_.opts);
const auto native_name = NativeName(Name(struct_def), &struct_def, opts_);
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_.SetValue("NATIVE_NAME", native_name);
@@ -1705,7 +1715,7 @@ class CppGenerator : public BaseGenerator {
GenOperatorNewDelete(struct_def);
GenDefaultConstructor(struct_def);
code_ += "};";
if (parser_.opts.gen_compare) GenCompareOperator(struct_def);
if (opts_.gen_compare) GenCompareOperator(struct_def);
code_ += "";
}
@@ -1794,7 +1804,7 @@ class CppGenerator : public BaseGenerator {
} else {
FLATBUFFERS_ASSERT(IsScalar(field.value.type.base_type));
auto type = GenTypeBasic(field.value.type, false);
if (parser_.opts.scoped_enums && field.value.type.enum_def &&
if (opts_.scoped_enums && field.value.type.enum_def &&
IsScalar(field.value.type.base_type)) {
type = GenTypeGet(field.value.type, " ", "const ", " *", true);
}
@@ -1810,7 +1820,7 @@ class CppGenerator : public BaseGenerator {
// Generate an accessor struct, builder structs & function for a table.
void GenTable(const StructDef &struct_def) {
if (parser_.opts.generate_object_based_api) { GenNativeTable(struct_def); }
if (opts_.generate_object_based_api) { GenNativeTable(struct_def); }
// Generate an accessor struct, with methods of the form:
// type name() const { return GetField<type>(offset, defaultval); }
@@ -1820,10 +1830,10 @@ class CppGenerator : public BaseGenerator {
code_ +=
"struct {{STRUCT_NAME}} FLATBUFFERS_FINAL_CLASS"
" : private flatbuffers::Table {";
if (parser_.opts.generate_object_based_api) {
if (opts_.generate_object_based_api) {
code_ += " typedef {{NATIVE_NAME}} NativeTableType;";
}
if (parser_.opts.mini_reflect != IDLOptions::kNone) {
if (opts_.mini_reflect != IDLOptions::kNone) {
code_ +=
" static const flatbuffers::TypeTable *MiniReflectTypeTable() {";
code_ += " return {{STRUCT_NAME}}TypeTable();";
@@ -1931,8 +1941,7 @@ class CppGenerator : public BaseGenerator {
}
}
if (parser_.opts.mutable_buffer &&
!(is_scalar && IsUnion(field.value.type))) {
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 + ">");
@@ -2014,13 +2023,11 @@ class CppGenerator : public BaseGenerator {
code_ += " &&\n verifier.EndTable();";
code_ += " }";
if (parser_.opts.generate_object_based_api) {
if (opts_.generate_object_based_api) {
// Generate the UnPack() pre declaration.
code_ +=
" " + TableUnPackSignature(struct_def, true, parser_.opts) + ";";
code_ +=
" " + TableUnPackToSignature(struct_def, true, parser_.opts) + ";";
code_ += " " + TablePackSignature(struct_def, true, parser_.opts) + ";";
code_ += " " + TableUnPackSignature(struct_def, true, opts_) + ";";
code_ += " " + TableUnPackToSignature(struct_def, true, opts_) + ";";
code_ += " " + TablePackSignature(struct_def, true, opts_) + ";";
}
code_ += "};"; // End of table.
@@ -2065,10 +2072,10 @@ class CppGenerator : public BaseGenerator {
GenBuilders(struct_def);
if (parser_.opts.generate_object_based_api) {
if (opts_.generate_object_based_api) {
// Generate a pre-declaration for a CreateX method that works with an
// unpacked C++ object.
code_ += TableCreateSignature(struct_def, true, parser_.opts) + ";";
code_ += TableCreateSignature(struct_def, true, opts_) + ";";
code_ += "";
}
}
@@ -2292,7 +2299,7 @@ class CppGenerator : public BaseGenerator {
}
} else {
const auto ptype = GenTypeNativePtr(
NativeName(name, type.struct_def, parser_.opts), &afield, true);
NativeName(name, type.struct_def, opts_), &afield, true);
return ptype + "(" + val + "->UnPack(_resolver))";
}
}
@@ -2419,8 +2426,6 @@ class CppGenerator : public BaseGenerator {
}
std::string GenCreateParam(const FieldDef &field) {
const IDLOptions &opts = parser_.opts;
std::string value = "_o->";
if (field.value.type.base_type == BASE_TYPE_UTYPE) {
value += StripUnionType(Name(field));
@@ -2457,7 +2462,7 @@ class CppGenerator : public BaseGenerator {
// 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(\"\")";
opts_.set_empty_strings_to_null ? "0" : "_fbb.CreateSharedString(\"\")";
code = value + ".empty() ? " + empty_value + " : " + code;
}
break;
@@ -2562,7 +2567,7 @@ class CppGenerator : public BaseGenerator {
// 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.required) {
code = value + ".size() ? " + code + " : 0";
}
break;
@@ -2604,20 +2609,20 @@ class CppGenerator : public BaseGenerator {
void GenTablePost(const StructDef &struct_def) {
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_.SetValue("NATIVE_NAME",
NativeName(Name(struct_def), &struct_def, parser_.opts));
NativeName(Name(struct_def), &struct_def, opts_));
if (parser_.opts.generate_object_based_api) {
if (opts_.generate_object_based_api) {
// Generate the X::UnPack() method.
code_ += "inline " +
TableUnPackSignature(struct_def, false, parser_.opts) + " {";
code_ +=
"inline " + TableUnPackSignature(struct_def, false, opts_) + " {";
code_ += " auto _o = new {{NATIVE_NAME}}();";
code_ += " UnPackTo(_o, _resolver);";
code_ += " return _o;";
code_ += "}";
code_ += "";
code_ += "inline " +
TableUnPackToSignature(struct_def, false, parser_.opts) + " {";
code_ +=
"inline " + TableUnPackToSignature(struct_def, false, opts_) + " {";
code_ += " (void)_o;";
code_ += " (void)_resolver;";
@@ -2644,15 +2649,14 @@ class CppGenerator : public BaseGenerator {
// Generate the X::Pack member function that simply calls the global
// CreateX function.
code_ += "inline " + TablePackSignature(struct_def, false, parser_.opts) +
" {";
code_ += "inline " + TablePackSignature(struct_def, false, opts_) + " {";
code_ += " return Create{{STRUCT_NAME}}(_fbb, _o, _rehasher);";
code_ += "}";
code_ += "";
// Generate a CreateX method that works with an unpacked C++ object.
code_ += "inline " +
TableCreateSignature(struct_def, false, parser_.opts) + " {";
code_ +=
"inline " + TableCreateSignature(struct_def, false, opts_) + " {";
code_ += " (void)_rehasher;";
code_ += " (void)_o;";
@@ -2660,7 +2664,7 @@ class CppGenerator : public BaseGenerator {
" struct _VectorArgs "
"{ flatbuffers::FlatBufferBuilder *__fbb; "
"const " +
NativeName(Name(struct_def), &struct_def, parser_.opts) +
NativeName(Name(struct_def), &struct_def, opts_) +
"* __o; "
"const flatbuffers::rehasher_function_t *__rehasher; } _va = { "
"&_fbb, _o, _rehasher}; (void)_va;";
@@ -2775,7 +2779,7 @@ class CppGenerator : public BaseGenerator {
code_ += " public:";
// Make TypeTable accessible via the generated struct.
if (parser_.opts.mini_reflect != IDLOptions::kNone) {
if (opts_.mini_reflect != IDLOptions::kNone) {
code_ +=
" static const flatbuffers::TypeTable *MiniReflectTypeTable() {";
code_ += " return {{STRUCT_NAME}}TypeTable();";
@@ -2891,7 +2895,7 @@ class CppGenerator : public BaseGenerator {
}
// Generate a mutable accessor function.
if (parser_.opts.mutable_buffer) {
if (opts_.mutable_buffer) {
auto mut_field_type =
GenTypeGet(field.value.type, " ", "",
IsArray(field.value.type) ? "" : " &", true);
@@ -2932,7 +2936,7 @@ class CppGenerator : public BaseGenerator {
code_.SetValue("STRUCT_BYTE_SIZE", NumToString(struct_def.bytesize));
code_ += "FLATBUFFERS_STRUCT_END({{STRUCT_NAME}}, {{STRUCT_BYTE_SIZE}});";
if (parser_.opts.gen_compare) GenCompareOperator(struct_def, "()");
if (opts_.gen_compare) GenCompareOperator(struct_def, "()");
code_ += "";
}
@@ -2974,15 +2978,39 @@ class CppGenerator : public BaseGenerator {
cur_name_space_ = ns;
}
const TypedFloatConstantGenerator float_const_gen_;
};
} // namespace cpp
bool GenerateCPP(const Parser &parser, const std::string &path,
const std::string &file_name) {
cpp::CppGenerator generator(parser, path, file_name);
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);
if (cpp_std == "C++0X") {
opts.g_cpp_std = cpp::CPP_STD_X0;
opts.g_only_fixed_enums = false;
} else if (cpp_std == "C++11") {
// Use the standard C++11 code generator.
opts.g_cpp_std = cpp::CPP_STD_11;
opts.g_only_fixed_enums = true;
} else if (cpp_std == "C++17") {
opts.g_cpp_std = cpp::CPP_STD_17;
// With c++17 generate strong enums only.
opts.scoped_enums = true;
// By default, prefixed_enums==true, reset it.
opts.prefixed_enums = false;
} else {
LogCompilerError("Unknown value of the '--cpp-std' switch: " +
opts.cpp_std);
return false;
}
// The opts.scoped_enums has priority.
opts.g_only_fixed_enums |= opts.scoped_enums;
cpp::CppGenerator generator(parser, path, file_name, opts);
return generator.generate();
}

View File

@@ -627,12 +627,6 @@ CheckedError Parser::ParseType(Type &type) {
"length of fixed-length array must be positive and fit to "
"uint16_t type");
}
// Check if enum arrays are used in C++ without specifying --scoped-enums
if ((opts.lang_to_generate & IDLOptions::kCpp) && !opts.scoped_enums &&
IsEnum(subtype)) {
return Error(
"--scoped-enums must be enabled to use enum arrays in C++\n");
}
type = Type(BASE_TYPE_ARRAY, subtype.struct_def, subtype.enum_def,
fixed_length);
NEXT();

View File

@@ -57,7 +57,7 @@ inline const char * const *EnumNamesTestEnum() {
}
inline const char *EnumNameTestEnum(TestEnum e) {
if (e < TestEnum::A || e > TestEnum::C) return "";
if (flatbuffers::IsOutRange(e, TestEnum::A, TestEnum::C)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesTestEnum()[index];
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This is a sandbox for modeling C++17 code generator.
// C++17 code generator: "flatc --cpp_std c++17".
// Warning:
// This is an experimental feature and could change at any time.
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/flexbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/minireflect.h"
#include "flatbuffers/registry.h"
#include "flatbuffers/util.h"
#include "test_assert.h"
// Embed generated code into an isolated namespace.
namespace cpp17 {
#include "generated_cpp17/monster_test_generated.h"
} // namespace cpp17
namespace cpp11 {
#include "../monster_test_generated.h"
} // namespace cpp11
int FlatBufferCpp17Tests() {
TEST_ASSERT(true);
return 0;
}
int main(int /*argc*/, const char * /*argv*/[]) {
InitTestEngine();
FlatBufferCpp17Tests();
if (!testing_fails) {
TEST_OUTPUT_LINE("C++17: ALL TESTS PASSED");
} else {
TEST_OUTPUT_LINE("C++17: %d FAILED TESTS", testing_fails);
}
return CloseTestEngine();
}

View File

@@ -12,32 +12,61 @@
:: See the License for the specific language governing permissions and
:: limitations under the License.
@SETLOCAL
set buildtype=Release
if "%1"=="-b" set buildtype=%2
..\%buildtype%\flatc.exe --cpp --java --csharp --dart --go --binary --lobster --lua --js --ts --php --rust --grpc --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes --cpp-ptr-type flatbuffers::unique_ptr --no-fb-import -I include_test monster_test.fbs monsterdata_test.json || goto FAIL
..\%buildtype%\flatc.exe --python --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr --no-fb-import -I include_test monster_test.fbs monsterdata_test.json || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp --dart --go --binary --lobster --lua --python --js --ts --php --rust --gen-mutable --reflect-names --no-fb-import --cpp-ptr-type flatbuffers::unique_ptr -o namespace_test namespace_test/namespace_test1.fbs namespace_test/namespace_test2.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp --js --ts --php --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr -o union_vector ./union_vector/union_vector.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --scoped-enums -o evolution_test ./evolution_test/evolution_v1.fbs ./evolution_test/evolution_v2.fbs|| goto FAIL
set commandline=%*
if NOT "%commandline%"=="%commandline:--cpp-std c++0x=%" (
set TEST_CPP_FLAGS=--cpp-std c++0x
) else (
@rem --cpp-std is defined by flatc default settings.
set TEST_CPP_FLAGS=
)
set TEST_CPP_FLAGS=--gen-compare --cpp-ptr-type flatbuffers::unique_ptr %TEST_CPP_FLAGS%
set TEST_BASE_FLAGS=--reflect-names --gen-mutable --gen-object-api
set TEST_NOINCL_FLAGS=%TEST_BASE_FLAGS% --no-includes --no-fb-import
..\%buildtype%\flatc.exe --binary --cpp --java --kotlin --csharp --dart --go --lobster --lua --js --ts --php --rust --grpc ^
%TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% -I include_test monster_test.fbs monsterdata_test.json || goto FAIL
..\%buildtype%\flatc.exe --python %TEST_BASE_FLAGS% --no-fb-import -I include_test monster_test.fbs monsterdata_test.json || goto FAIL
..\%buildtype%\flatc.exe --binary --cpp --java --csharp --dart --go --lobster --lua --js --ts --php --python --rust ^
%TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% -o namespace_test namespace_test/namespace_test1.fbs namespace_test/namespace_test2.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp --js --ts --php %TEST_BASE_FLAGS% %TEST_CPP_FLAGS% -o union_vector ./union_vector/union_vector.fbs || goto FAIL
..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins -I include_test monster_test.fbs || goto FAIL
..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins -I include_test arrays_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --jsonschema --schema -I include_test monster_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes --scoped-enums --jsonschema --cpp-ptr-type flatbuffers::unique_ptr arrays_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --python --gen-mutable --reflect-names --gen-object-api --gen-compare --scoped-enums --jsonschema --cpp-ptr-type flatbuffers::unique_ptr arrays_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --gen-mutable --gen-object-api --reflect-names --cpp-ptr-type flatbuffers::unique_ptr native_type_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp --jsonschema %TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% --scoped-enums arrays_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --python %TEST_BASE_FLAGS% arrays_test.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp %TEST_BASE_FLAGS% --cpp-ptr-type flatbuffers::unique_ptr native_type_test.fbs || goto FAIL
IF NOT "%MONSTER_EXTRA%"=="skip" (
if NOT "%MONSTER_EXTRA%"=="skip" (
@echo Generate MosterExtra
..\%buildtype%\flatc.exe --cpp --java --csharp --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes --cpp-ptr-type flatbuffers::unique_ptr monster_extra.fbs monsterdata_extra.json || goto FAIL
..\%buildtype%\flatc.exe --python --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr monster_extra.fbs monsterdata_extra.json || goto FAIL
..\%buildtype%\flatc.exe --cpp --java --csharp %TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% monster_extra.fbs monsterdata_extra.json || goto FAIL
..\%buildtype%\flatc.exe --python %TEST_BASE_FLAGS% monster_extra.fbs monsterdata_extra.json || goto FAIL
) else (
@echo monster_extra.fbs skipped (the strtod function from MSVC2013 or older doesn't support NaN/Inf arguments)
)
set TEST_CPP17_FLAGS=--cpp --cpp-std c++17 -o ./cpp17/generated_cpp17 %TEST_NOINCL_FLAGS%
if NOT "%MONSTER_EXTRA%"=="skip" (
@rem Flag c++17 requires Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher.
..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% -I include_test monster_test.fbs || goto FAIL
@rem..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% arrays_test.fbs || goto FAIL
@rem..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% native_type_test.fbs || goto FAIL
@rem..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% monster_extra.fbs || goto FAIL
@rem..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% ./union_vector/union_vector.fbs || goto FAIL
)
cd ../samples
..\%buildtype%\flatc.exe --cpp --lobster --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr monster.fbs || goto FAIL
..\%buildtype%\flatc.exe --cpp --lobster %TEST_BASE_FLAGS% %TEST_CPP_FLAGS% monster.fbs || goto FAIL
..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins monster.fbs || goto FAIL
cd ../reflection
call generate_code.bat %1 %2 || goto FAIL

View File

@@ -15,19 +15,41 @@
# limitations under the License.
set -e
../flatc --cpp --java --kotlin --csharp --dart --go --binary --lobster --lua --js --ts --php --rust --grpc --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes --cpp-ptr-type flatbuffers::unique_ptr --no-fb-import -I include_test monster_test.fbs monsterdata_test.json
../flatc --python --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr --no-fb-import -I include_test monster_test.fbs monsterdata_test.json
../flatc --cpp --java --kotlin --csharp --dart --go --binary --lobster --lua --python --js --ts --php --rust --gen-mutable --reflect-names --no-fb-import --cpp-ptr-type flatbuffers::unique_ptr -o namespace_test namespace_test/namespace_test1.fbs namespace_test/namespace_test2.fbs
../flatc --cpp --java --kotlin --csharp --js --ts --php --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr -o union_vector ./union_vector/union_vector.fbs
../flatc --cpp --scoped-enums -o evolution_test ./evolution_test/evolution_v*.fbs
commandline="'$*'"
if [[ $commandline == *"--cpp-std c++0x"* ]]; then
TEST_CPP_FLAGS="--cpp-std c++0x"
else
# --cpp-std is defined by flatc default settings.
TEST_CPP_FLAGS=
fi
TEST_CPP_FLAGS="--gen-compare --cpp-ptr-type flatbuffers::unique_ptr $TEST_CPP_FLAGS"
TEST_BASE_FLAGS="--reflect-names --gen-mutable --gen-object-api"
TEST_NOINCL_FLAGS="$TEST_BASE_FLAGS --no-includes --no-fb-import"
../flatc --binary --cpp --java --kotlin --csharp --dart --go --lobster --lua --js --ts --php --rust --grpc \
$TEST_NOINCL_FLAGS $TEST_CPP_FLAGS -I include_test monster_test.fbs monsterdata_test.json
../flatc --python $TEST_BASE_FLAGS -I include_test monster_test.fbs monsterdata_test.json
../flatc --cpp --java --kotlin --csharp --dart --go --binary --lobster --lua --js --ts --php --python --rust \
$TEST_NOINCL_FLAGS $TEST_CPP_FLAGS -o namespace_test namespace_test/namespace_test1.fbs namespace_test/namespace_test2.fbs
../flatc --cpp --java --kotlin --csharp --js --ts --php $TEST_BASE_FLAGS $TEST_CPP_FLAGS -o union_vector ./union_vector/union_vector.fbs
../flatc -b --schema --bfbs-comments --bfbs-builtins -I include_test monster_test.fbs
../flatc -b --schema --bfbs-comments --bfbs-builtins -I include_test arrays_test.fbs
../flatc --jsonschema --schema -I include_test monster_test.fbs
../flatc --cpp --java --kotlin --csharp --python --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes --cpp-ptr-type flatbuffers::unique_ptr monster_extra.fbs monsterdata_extra.json
../flatc --cpp --java --csharp --gen-mutable --reflect-names --gen-object-api --gen-compare --no-includes --scoped-enums --jsonschema --cpp-ptr-type flatbuffers::unique_ptr arrays_test.fbs
../flatc --python --gen-mutable --reflect-names --gen-object-api --gen-compare --scoped-enums --jsonschema --cpp-ptr-type flatbuffers::unique_ptr arrays_test.fbs
../flatc --cpp --java --kotlin --csharp --python $TEST_NOINCL_FLAGS $TEST_CPP_FLAGS monster_extra.fbs monsterdata_extra.json
../flatc --cpp --java --csharp --jsonschema $TEST_NOINCL_FLAGS $TEST_CPP_FLAGS --scoped-enums arrays_test.fbs
../flatc --python $TEST_BASE_FLAGS arrays_test.fbs
# Flag c++17 requires Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher.
TEST_CPP17_FLAGS="--cpp --cpp-std c++17 -o ./cpp17/generated_cpp17 $TEST_NOINCL_FLAGS"
../flatc $TEST_CPP17_FLAGS -I include_test monster_test.fbs
cd ../samples
../flatc --cpp --lobster --gen-mutable --reflect-names --gen-object-api --gen-compare --cpp-ptr-type flatbuffers::unique_ptr monster.fbs
../flatc --cpp --lobster $TEST_BASE_FLAGS $TEST_CPP_FLAGS monster.fbs
../flatc -b --schema --bfbs-comments --bfbs-builtins monster.fbs
cd ../reflection
./generate_code.sh
./generate_code.sh --cpp-std c++0x

View File

@@ -136,7 +136,7 @@ inline const char * const *EnumNamesColor() {
}
inline const char *EnumNameColor(Color e) {
if (e < Color_Red || e > Color_Blue) return "";
if (flatbuffers::IsOutRange(e, Color_Red, Color_Blue)) return "";
const size_t index = static_cast<size_t>(e) - static_cast<size_t>(Color_Red);
return EnumNamesColor()[index];
}
@@ -172,7 +172,7 @@ inline const char * const *EnumNamesRace() {
}
inline const char *EnumNameRace(Race e) {
if (e < Race_None || e > Race_Elf) return "";
if (flatbuffers::IsOutRange(e, Race_None, Race_Elf)) return "";
const size_t index = static_cast<size_t>(e) - static_cast<size_t>(Race_None);
return EnumNamesRace()[index];
}
@@ -208,7 +208,7 @@ inline const char * const *EnumNamesAny() {
}
inline const char *EnumNameAny(Any e) {
if (e < Any_NONE || e > Any_MyGame_Example2_Monster) return "";
if (flatbuffers::IsOutRange(e, Any_NONE, Any_MyGame_Example2_Monster)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesAny()[index];
}
@@ -350,7 +350,7 @@ inline const char * const *EnumNamesAnyUniqueAliases() {
}
inline const char *EnumNameAnyUniqueAliases(AnyUniqueAliases e) {
if (e < AnyUniqueAliases_NONE || e > AnyUniqueAliases_M2) return "";
if (flatbuffers::IsOutRange(e, AnyUniqueAliases_NONE, AnyUniqueAliases_M2)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesAnyUniqueAliases()[index];
}
@@ -492,7 +492,7 @@ inline const char * const *EnumNamesAnyAmbiguousAliases() {
}
inline const char *EnumNameAnyAmbiguousAliases(AnyAmbiguousAliases e) {
if (e < AnyAmbiguousAliases_NONE || e > AnyAmbiguousAliases_M3) return "";
if (flatbuffers::IsOutRange(e, AnyAmbiguousAliases_NONE, AnyAmbiguousAliases_M3)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesAnyAmbiguousAliases()[index];
}

View File

@@ -6,6 +6,27 @@ import (
flatbuffers "github.com/google/flatbuffers/go"
)
type StructInNestedNST struct {
A int32
B int32
}
func StructInNestedNSPack(builder *flatbuffers.Builder, t *StructInNestedNST) flatbuffers.UOffsetT {
if t == nil { return 0 }
return CreateStructInNestedNS(builder, t.A, t.B)
}
func (rcv *StructInNestedNS) UnPackTo(t *StructInNestedNST) {
t.A = rcv.A()
t.B = rcv.B()
}
func (rcv *StructInNestedNS) UnPack() *StructInNestedNST {
if rcv == nil { return nil }
t := &StructInNestedNST{}
rcv.UnPackTo(t)
return t
}
type StructInNestedNS struct {
_tab flatbuffers.Struct
}

View File

@@ -23,3 +23,34 @@ def CreateStructInNestedNS(builder, a, b):
builder.PrependInt32(b)
builder.PrependInt32(a)
return builder.Offset()
class StructInNestedNST(object):
# StructInNestedNST
def __init__(self):
self.a = 0 # type: int
self.b = 0 # type: int
@classmethod
def InitFromBuf(cls, buf, pos):
structInNestedNS = StructInNestedNS()
structInNestedNS.Init(buf, pos)
return cls.InitFromObj(structInNestedNS)
@classmethod
def InitFromObj(cls, structInNestedNS):
x = StructInNestedNST()
x._UnPack(structInNestedNS)
return x
# StructInNestedNST
def _UnPack(self, structInNestedNS):
if structInNestedNS is None:
return
self.a = structInNestedNS.A()
self.b = structInNestedNS.B()
# StructInNestedNST
def Pack(self, builder):
return CreateStructInNestedNS(builder, self.a, self.b)

View File

@@ -6,6 +6,28 @@ import (
flatbuffers "github.com/google/flatbuffers/go"
)
type TableInNestedNST struct {
Foo int32
}
func TableInNestedNSPack(builder *flatbuffers.Builder, t *TableInNestedNST) flatbuffers.UOffsetT {
if t == nil { return 0 }
TableInNestedNSStart(builder)
TableInNestedNSAddFoo(builder, t.Foo)
return TableInNestedNSEnd(builder)
}
func (rcv *TableInNestedNS) UnPackTo(t *TableInNestedNST) {
t.Foo = rcv.Foo()
}
func (rcv *TableInNestedNS) UnPack() *TableInNestedNST {
if rcv == nil { return nil }
t := &TableInNestedNST{}
rcv.UnPackTo(t)
return t
}
type TableInNestedNS struct {
_tab flatbuffers.Table
}

View File

@@ -30,3 +30,35 @@ class TableInNestedNS(object):
def TableInNestedNSStart(builder): builder.StartObject(1)
def TableInNestedNSAddFoo(builder, foo): builder.PrependInt32Slot(0, foo, 0)
def TableInNestedNSEnd(builder): return builder.EndObject()
class TableInNestedNST(object):
# TableInNestedNST
def __init__(self):
self.foo = 0 # type: int
@classmethod
def InitFromBuf(cls, buf, pos):
tableInNestedNS = TableInNestedNS()
tableInNestedNS.Init(buf, pos)
return cls.InitFromObj(tableInNestedNS)
@classmethod
def InitFromObj(cls, tableInNestedNS):
x = TableInNestedNST()
x._UnPack(tableInNestedNS)
return x
# TableInNestedNST
def _UnPack(self, tableInNestedNS):
if tableInNestedNS is None:
return
self.foo = tableInNestedNS.Foo()
# TableInNestedNST
def Pack(self, builder):
TableInNestedNSStart(builder)
TableInNestedNSAddFoo(builder, self.foo)
tableInNestedNS = TableInNestedNSEnd(builder)
return tableInNestedNS

View File

@@ -8,6 +8,29 @@ import (
NamespaceC "NamespaceC"
)
type SecondTableInAT struct {
ReferToC *NamespaceC.TableInCT
}
func SecondTableInAPack(builder *flatbuffers.Builder, t *SecondTableInAT) flatbuffers.UOffsetT {
if t == nil { return 0 }
referToCOffset := NamespaceC.TableInCPack(builder, t.ReferToC)
SecondTableInAStart(builder)
SecondTableInAAddReferToC(builder, referToCOffset)
return SecondTableInAEnd(builder)
}
func (rcv *SecondTableInA) UnPackTo(t *SecondTableInAT) {
t.ReferToC = rcv.ReferToC(nil).UnPack()
}
func (rcv *SecondTableInA) UnPack() *SecondTableInAT {
if rcv == nil { return nil }
t := &SecondTableInAT{}
rcv.UnPackTo(t)
return t
}
type SecondTableInA struct {
_tab flatbuffers.Table
}

View File

@@ -25,7 +25,6 @@ class SecondTableInA(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
from NamespaceC.TableInC import TableInC
obj = TableInC()
obj.Init(self._tab.Bytes, x)
return obj
@@ -34,3 +33,43 @@ class SecondTableInA(object):
def SecondTableInAStart(builder): builder.StartObject(1)
def SecondTableInAAddReferToC(builder, referToC): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(referToC), 0)
def SecondTableInAEnd(builder): return builder.EndObject()
try:
from typing import Optional
except:
pass
class SecondTableInAT(object):
# SecondTableInAT
def __init__(self):
self.referToC = None # type: Optional[TableInCT]
@classmethod
def InitFromBuf(cls, buf, pos):
secondTableInA = SecondTableInA()
secondTableInA.Init(buf, pos)
return cls.InitFromObj(secondTableInA)
@classmethod
def InitFromObj(cls, secondTableInA):
x = SecondTableInAT()
x._UnPack(secondTableInA)
return x
# SecondTableInAT
def _UnPack(self, secondTableInA):
if secondTableInA is None:
return
if secondTableInA.ReferToC() is not None:
self.referToC = TableInCT.InitFromObj(secondTableInA.ReferToC())
# SecondTableInAT
def Pack(self, builder):
if self.referToC is not None:
referToC = self.referToC.Pack(builder)
SecondTableInAStart(builder)
if self.referToC is not None:
SecondTableInAAddReferToC(builder, referToC)
secondTableInA = SecondTableInAEnd(builder)
return secondTableInA

View File

@@ -8,6 +8,36 @@ import (
NamespaceA__NamespaceB "NamespaceA/NamespaceB"
)
type TableInFirstNST struct {
FooTable *NamespaceA__NamespaceB.TableInNestedNST
FooEnum NamespaceA__NamespaceB.EnumInNestedNS
FooStruct *NamespaceA__NamespaceB.StructInNestedNST
}
func TableInFirstNSPack(builder *flatbuffers.Builder, t *TableInFirstNST) flatbuffers.UOffsetT {
if t == nil { return 0 }
fooTableOffset := NamespaceA__NamespaceB.TableInNestedNSPack(builder, t.FooTable)
TableInFirstNSStart(builder)
TableInFirstNSAddFooTable(builder, fooTableOffset)
TableInFirstNSAddFooEnum(builder, t.FooEnum)
fooStructOffset := NamespaceA__NamespaceB.StructInNestedNSPack(builder, t.FooStruct)
TableInFirstNSAddFooStruct(builder, fooStructOffset)
return TableInFirstNSEnd(builder)
}
func (rcv *TableInFirstNS) UnPackTo(t *TableInFirstNST) {
t.FooTable = rcv.FooTable(nil).UnPack()
t.FooEnum = rcv.FooEnum()
t.FooStruct = rcv.FooStruct(nil).UnPack()
}
func (rcv *TableInFirstNS) UnPack() *TableInFirstNST {
if rcv == nil { return nil }
t := &TableInFirstNST{}
rcv.UnPackTo(t)
return t
}
type TableInFirstNS struct {
_tab flatbuffers.Table
}

View File

@@ -25,7 +25,6 @@ class TableInFirstNS(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
from NamespaceA.NamespaceB.TableInNestedNS import TableInNestedNS
obj = TableInNestedNS()
obj.Init(self._tab.Bytes, x)
return obj
@@ -43,7 +42,6 @@ class TableInFirstNS(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
if o != 0:
x = o + self._tab.Pos
from NamespaceA.NamespaceB.StructInNestedNS import StructInNestedNS
obj = StructInNestedNS()
obj.Init(self._tab.Bytes, x)
return obj
@@ -54,3 +52,52 @@ def TableInFirstNSAddFooTable(builder, fooTable): builder.PrependUOffsetTRelativ
def TableInFirstNSAddFooEnum(builder, fooEnum): builder.PrependInt8Slot(1, fooEnum, 0)
def TableInFirstNSAddFooStruct(builder, fooStruct): builder.PrependStructSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(fooStruct), 0)
def TableInFirstNSEnd(builder): return builder.EndObject()
try:
from typing import Optional
except:
pass
class TableInFirstNST(object):
# TableInFirstNST
def __init__(self):
self.fooTable = None # type: Optional[TableInNestedNST]
self.fooEnum = 0 # type: int
self.fooStruct = None # type: Optional[StructInNestedNST]
@classmethod
def InitFromBuf(cls, buf, pos):
tableInFirstNS = TableInFirstNS()
tableInFirstNS.Init(buf, pos)
return cls.InitFromObj(tableInFirstNS)
@classmethod
def InitFromObj(cls, tableInFirstNS):
x = TableInFirstNST()
x._UnPack(tableInFirstNS)
return x
# TableInFirstNST
def _UnPack(self, tableInFirstNS):
if tableInFirstNS is None:
return
if tableInFirstNS.FooTable() is not None:
self.fooTable = TableInNestedNST.InitFromObj(tableInFirstNS.FooTable())
self.fooEnum = tableInFirstNS.FooEnum()
if tableInFirstNS.FooStruct() is not None:
self.fooStruct = StructInNestedNST.InitFromObj(tableInFirstNS.FooStruct())
# TableInFirstNST
def Pack(self, builder):
if self.fooTable is not None:
fooTable = self.fooTable.Pack(builder)
TableInFirstNSStart(builder)
if self.fooTable is not None:
TableInFirstNSAddFooTable(builder, fooTable)
TableInFirstNSAddFooEnum(builder, self.fooEnum)
if self.fooStruct is not None:
fooStruct = self.fooStruct.Pack(builder)
TableInFirstNSAddFooStruct(builder, fooStruct)
tableInFirstNS = TableInFirstNSEnd(builder)
return tableInFirstNS

View File

@@ -8,6 +8,33 @@ import (
NamespaceA "NamespaceA"
)
type TableInCT struct {
ReferToA1 *NamespaceA.TableInFirstNST
ReferToA2 *NamespaceA.SecondTableInAT
}
func TableInCPack(builder *flatbuffers.Builder, t *TableInCT) flatbuffers.UOffsetT {
if t == nil { return 0 }
referToA1Offset := NamespaceA.TableInFirstNSPack(builder, t.ReferToA1)
referToA2Offset := NamespaceA.SecondTableInAPack(builder, t.ReferToA2)
TableInCStart(builder)
TableInCAddReferToA1(builder, referToA1Offset)
TableInCAddReferToA2(builder, referToA2Offset)
return TableInCEnd(builder)
}
func (rcv *TableInC) UnPackTo(t *TableInCT) {
t.ReferToA1 = rcv.ReferToA1(nil).UnPack()
t.ReferToA2 = rcv.ReferToA2(nil).UnPack()
}
func (rcv *TableInC) UnPack() *TableInCT {
if rcv == nil { return nil }
t := &TableInCT{}
rcv.UnPackTo(t)
return t
}
type TableInC struct {
_tab flatbuffers.Table
}

View File

@@ -25,7 +25,6 @@ class TableInC(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
from NamespaceA.TableInFirstNS import TableInFirstNS
obj = TableInFirstNS()
obj.Init(self._tab.Bytes, x)
return obj
@@ -36,7 +35,6 @@ class TableInC(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
from NamespaceA.SecondTableInA import SecondTableInA
obj = SecondTableInA()
obj.Init(self._tab.Bytes, x)
return obj
@@ -46,3 +44,50 @@ def TableInCStart(builder): builder.StartObject(2)
def TableInCAddReferToA1(builder, referToA1): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(referToA1), 0)
def TableInCAddReferToA2(builder, referToA2): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(referToA2), 0)
def TableInCEnd(builder): return builder.EndObject()
try:
from typing import Optional
except:
pass
class TableInCT(object):
# TableInCT
def __init__(self):
self.referToA1 = None # type: Optional[TableInFirstNST]
self.referToA2 = None # type: Optional[SecondTableInAT]
@classmethod
def InitFromBuf(cls, buf, pos):
tableInC = TableInC()
tableInC.Init(buf, pos)
return cls.InitFromObj(tableInC)
@classmethod
def InitFromObj(cls, tableInC):
x = TableInCT()
x._UnPack(tableInC)
return x
# TableInCT
def _UnPack(self, tableInC):
if tableInC is None:
return
if tableInC.ReferToA1() is not None:
self.referToA1 = TableInFirstNST.InitFromObj(tableInC.ReferToA1())
if tableInC.ReferToA2() is not None:
self.referToA2 = SecondTableInAT.InitFromObj(tableInC.ReferToA2())
# TableInCT
def Pack(self, builder):
if self.referToA1 is not None:
referToA1 = self.referToA1.Pack(builder)
if self.referToA2 is not None:
referToA2 = self.referToA2.Pack(builder)
TableInCStart(builder)
if self.referToA1 is not None:
TableInCAddReferToA1(builder, referToA1)
if self.referToA2 is not None:
TableInCAddReferToA2(builder, referToA2)
tableInC = TableInCEnd(builder)
return tableInC

View File

@@ -10,9 +10,15 @@ namespace NamespaceA {
namespace NamespaceB {
struct TableInNestedNS;
struct TableInNestedNST;
struct StructInNestedNS;
bool operator==(const TableInNestedNST &lhs, const TableInNestedNST &rhs);
bool operator!=(const TableInNestedNST &lhs, const TableInNestedNST &rhs);
bool operator==(const StructInNestedNS &lhs, const StructInNestedNS &rhs);
bool operator!=(const StructInNestedNS &lhs, const StructInNestedNS &rhs);
inline const flatbuffers::TypeTable *TableInNestedNSTypeTable();
inline const flatbuffers::TypeTable *StructInNestedNSTypeTable();
@@ -45,7 +51,7 @@ inline const char * const *EnumNamesEnumInNestedNS() {
}
inline const char *EnumNameEnumInNestedNS(EnumInNestedNS e) {
if (e < EnumInNestedNS_A || e > EnumInNestedNS_C) return "";
if (flatbuffers::IsOutRange(e, EnumInNestedNS_A, EnumInNestedNS_C)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesEnumInNestedNS()[index];
}
@@ -81,7 +87,37 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructInNestedNS FLATBUFFERS_FINAL_CLASS
};
FLATBUFFERS_STRUCT_END(StructInNestedNS, 8);
inline bool operator==(const StructInNestedNS &lhs, const StructInNestedNS &rhs) {
return
(lhs.a() == rhs.a()) &&
(lhs.b() == rhs.b());
}
inline bool operator!=(const StructInNestedNS &lhs, const StructInNestedNS &rhs) {
return !(lhs == rhs);
}
struct TableInNestedNST : public flatbuffers::NativeTable {
typedef TableInNestedNS TableType;
int32_t foo;
TableInNestedNST()
: foo(0) {
}
};
inline bool operator==(const TableInNestedNST &lhs, const TableInNestedNST &rhs) {
return
(lhs.foo == rhs.foo);
}
inline bool operator!=(const TableInNestedNST &lhs, const TableInNestedNST &rhs) {
return !(lhs == rhs);
}
struct TableInNestedNS FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef TableInNestedNST NativeTableType;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return TableInNestedNSTypeTable();
}
@@ -99,6 +135,9 @@ struct TableInNestedNS FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VerifyField<int32_t>(verifier, VT_FOO) &&
verifier.EndTable();
}
TableInNestedNST *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
void UnPackTo(TableInNestedNST *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
static flatbuffers::Offset<TableInNestedNS> Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
};
struct TableInNestedNSBuilder {
@@ -127,6 +166,34 @@ inline flatbuffers::Offset<TableInNestedNS> CreateTableInNestedNS(
return builder_.Finish();
}
flatbuffers::Offset<TableInNestedNS> CreateTableInNestedNS(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
inline TableInNestedNST *TableInNestedNS::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = new TableInNestedNST();
UnPackTo(_o, _resolver);
return _o;
}
inline void TableInNestedNS::UnPackTo(TableInNestedNST *_o, const flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
{ auto _e = foo(); _o->foo = _e; }
}
inline flatbuffers::Offset<TableInNestedNS> TableInNestedNS::Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST* _o, const flatbuffers::rehasher_function_t *_rehasher) {
return CreateTableInNestedNS(_fbb, _o, _rehasher);
}
inline flatbuffers::Offset<TableInNestedNS> CreateTableInNestedNS(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST *_o, const flatbuffers::rehasher_function_t *_rehasher) {
(void)_rehasher;
(void)_o;
struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const TableInNestedNST* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
auto _foo = _o->foo;
return NamespaceA::NamespaceB::CreateTableInNestedNS(
_fbb,
_foo);
}
inline const flatbuffers::TypeTable *EnumInNestedNSTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_CHAR, 0, 0 },

View File

@@ -6,23 +6,39 @@
#include "flatbuffers/flatbuffers.h"
#include "namespace_test1_generated.h"
namespace NamespaceA {
struct TableInFirstNS;
struct TableInFirstNST;
} // namespace NamespaceA
namespace NamespaceC {
struct TableInC;
struct TableInCT;
} // namespace NamespaceC
namespace NamespaceA {
struct SecondTableInA;
struct SecondTableInAT;
bool operator==(const TableInFirstNST &lhs, const TableInFirstNST &rhs);
bool operator!=(const TableInFirstNST &lhs, const TableInFirstNST &rhs);
} // namespace NamespaceA
namespace NamespaceC {
bool operator==(const TableInCT &lhs, const TableInCT &rhs);
bool operator!=(const TableInCT &lhs, const TableInCT &rhs);
} // namespace NamespaceC
namespace NamespaceA {
bool operator==(const SecondTableInAT &lhs, const SecondTableInAT &rhs);
bool operator!=(const SecondTableInAT &lhs, const SecondTableInAT &rhs);
inline const flatbuffers::TypeTable *TableInFirstNSTypeTable();
@@ -38,7 +54,30 @@ namespace NamespaceA {
inline const flatbuffers::TypeTable *SecondTableInATypeTable();
struct TableInFirstNST : public flatbuffers::NativeTable {
typedef TableInFirstNS TableType;
flatbuffers::unique_ptr<NamespaceA::NamespaceB::TableInNestedNST> foo_table;
NamespaceA::NamespaceB::EnumInNestedNS foo_enum;
flatbuffers::unique_ptr<NamespaceA::NamespaceB::StructInNestedNS> foo_struct;
TableInFirstNST()
: foo_enum(NamespaceA::NamespaceB::EnumInNestedNS_A) {
}
};
inline bool operator==(const TableInFirstNST &lhs, const TableInFirstNST &rhs) {
return
(lhs.foo_table == rhs.foo_table) &&
(lhs.foo_enum == rhs.foo_enum) &&
(lhs.foo_struct == rhs.foo_struct);
}
inline bool operator!=(const TableInFirstNST &lhs, const TableInFirstNST &rhs) {
return !(lhs == rhs);
}
struct TableInFirstNS FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef TableInFirstNST NativeTableType;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return TableInFirstNSTypeTable();
}
@@ -73,6 +112,9 @@ struct TableInFirstNS FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VerifyField<NamespaceA::NamespaceB::StructInNestedNS>(verifier, VT_FOO_STRUCT) &&
verifier.EndTable();
}
TableInFirstNST *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
void UnPackTo(TableInFirstNST *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
static flatbuffers::Offset<TableInFirstNS> Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
};
struct TableInFirstNSBuilder {
@@ -111,11 +153,33 @@ inline flatbuffers::Offset<TableInFirstNS> CreateTableInFirstNS(
return builder_.Finish();
}
flatbuffers::Offset<TableInFirstNS> CreateTableInFirstNS(flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
} // namespace NamespaceA
namespace NamespaceC {
struct TableInCT : public flatbuffers::NativeTable {
typedef TableInC TableType;
flatbuffers::unique_ptr<NamespaceA::TableInFirstNST> refer_to_a1;
flatbuffers::unique_ptr<NamespaceA::SecondTableInAT> refer_to_a2;
TableInCT() {
}
};
inline bool operator==(const TableInCT &lhs, const TableInCT &rhs) {
return
(lhs.refer_to_a1 == rhs.refer_to_a1) &&
(lhs.refer_to_a2 == rhs.refer_to_a2);
}
inline bool operator!=(const TableInCT &lhs, const TableInCT &rhs) {
return !(lhs == rhs);
}
struct TableInC FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef TableInCT NativeTableType;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return TableInCTypeTable();
}
@@ -143,6 +207,9 @@ struct TableInC FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
verifier.VerifyTable(refer_to_a2()) &&
verifier.EndTable();
}
TableInCT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
void UnPackTo(TableInCT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
static flatbuffers::Offset<TableInC> Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInCT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
};
struct TableInCBuilder {
@@ -176,11 +243,31 @@ inline flatbuffers::Offset<TableInC> CreateTableInC(
return builder_.Finish();
}
flatbuffers::Offset<TableInC> CreateTableInC(flatbuffers::FlatBufferBuilder &_fbb, const TableInCT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
} // namespace NamespaceC
namespace NamespaceA {
struct SecondTableInAT : public flatbuffers::NativeTable {
typedef SecondTableInA TableType;
flatbuffers::unique_ptr<NamespaceC::TableInCT> refer_to_c;
SecondTableInAT() {
}
};
inline bool operator==(const SecondTableInAT &lhs, const SecondTableInAT &rhs) {
return
(lhs.refer_to_c == rhs.refer_to_c);
}
inline bool operator!=(const SecondTableInAT &lhs, const SecondTableInAT &rhs) {
return !(lhs == rhs);
}
struct SecondTableInA FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef SecondTableInAT NativeTableType;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return SecondTableInATypeTable();
}
@@ -199,6 +286,9 @@ struct SecondTableInA FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
verifier.VerifyTable(refer_to_c()) &&
verifier.EndTable();
}
SecondTableInAT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
void UnPackTo(SecondTableInAT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
static flatbuffers::Offset<SecondTableInA> Pack(flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
};
struct SecondTableInABuilder {
@@ -227,14 +317,103 @@ inline flatbuffers::Offset<SecondTableInA> CreateSecondTableInA(
return builder_.Finish();
}
flatbuffers::Offset<SecondTableInA> CreateSecondTableInA(flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
inline TableInFirstNST *TableInFirstNS::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = new TableInFirstNST();
UnPackTo(_o, _resolver);
return _o;
}
inline void TableInFirstNS::UnPackTo(TableInFirstNST *_o, const flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
{ auto _e = foo_table(); if (_e) _o->foo_table = flatbuffers::unique_ptr<NamespaceA::NamespaceB::TableInNestedNST>(_e->UnPack(_resolver)); }
{ auto _e = foo_enum(); _o->foo_enum = _e; }
{ auto _e = foo_struct(); if (_e) _o->foo_struct = flatbuffers::unique_ptr<NamespaceA::NamespaceB::StructInNestedNS>(new NamespaceA::NamespaceB::StructInNestedNS(*_e)); }
}
inline flatbuffers::Offset<TableInFirstNS> TableInFirstNS::Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST* _o, const flatbuffers::rehasher_function_t *_rehasher) {
return CreateTableInFirstNS(_fbb, _o, _rehasher);
}
inline flatbuffers::Offset<TableInFirstNS> CreateTableInFirstNS(flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST *_o, const flatbuffers::rehasher_function_t *_rehasher) {
(void)_rehasher;
(void)_o;
struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const TableInFirstNST* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
auto _foo_table = _o->foo_table ? CreateTableInNestedNS(_fbb, _o->foo_table.get(), _rehasher) : 0;
auto _foo_enum = _o->foo_enum;
auto _foo_struct = _o->foo_struct ? _o->foo_struct.get() : 0;
return NamespaceA::CreateTableInFirstNS(
_fbb,
_foo_table,
_foo_enum,
_foo_struct);
}
} // namespace NamespaceA
namespace NamespaceC {
inline TableInCT *TableInC::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = new TableInCT();
UnPackTo(_o, _resolver);
return _o;
}
inline void TableInC::UnPackTo(TableInCT *_o, const flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
{ auto _e = refer_to_a1(); if (_e) _o->refer_to_a1 = flatbuffers::unique_ptr<NamespaceA::TableInFirstNST>(_e->UnPack(_resolver)); }
{ auto _e = refer_to_a2(); if (_e) _o->refer_to_a2 = flatbuffers::unique_ptr<NamespaceA::SecondTableInAT>(_e->UnPack(_resolver)); }
}
inline flatbuffers::Offset<TableInC> TableInC::Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInCT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
return CreateTableInC(_fbb, _o, _rehasher);
}
inline flatbuffers::Offset<TableInC> CreateTableInC(flatbuffers::FlatBufferBuilder &_fbb, const TableInCT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
(void)_rehasher;
(void)_o;
struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const TableInCT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
auto _refer_to_a1 = _o->refer_to_a1 ? CreateTableInFirstNS(_fbb, _o->refer_to_a1.get(), _rehasher) : 0;
auto _refer_to_a2 = _o->refer_to_a2 ? CreateSecondTableInA(_fbb, _o->refer_to_a2.get(), _rehasher) : 0;
return NamespaceC::CreateTableInC(
_fbb,
_refer_to_a1,
_refer_to_a2);
}
} // namespace NamespaceC
namespace NamespaceA {
inline SecondTableInAT *SecondTableInA::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = new SecondTableInAT();
UnPackTo(_o, _resolver);
return _o;
}
inline void SecondTableInA::UnPackTo(SecondTableInAT *_o, const flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
{ auto _e = refer_to_c(); if (_e) _o->refer_to_c = flatbuffers::unique_ptr<NamespaceC::TableInCT>(_e->UnPack(_resolver)); }
}
inline flatbuffers::Offset<SecondTableInA> SecondTableInA::Pack(flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
return CreateSecondTableInA(_fbb, _o, _rehasher);
}
inline flatbuffers::Offset<SecondTableInA> CreateSecondTableInA(flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
(void)_rehasher;
(void)_o;
struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const SecondTableInAT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
auto _refer_to_c = _o->refer_to_c ? CreateTableInC(_fbb, _o->refer_to_c.get(), _rehasher) : 0;
return NamespaceA::CreateSecondTableInA(
_fbb,
_refer_to_c);
}
inline const flatbuffers::TypeTable *TableInFirstNSTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_SEQUENCE, 0, 0 },

View File

@@ -6,7 +6,6 @@ library namespace_a;
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import 'namespace_test1_namespace_a_generated.dart';
import './namespace_test2_namespace_c_generated.dart' as namespace_c;
class TableInFirstNS {

View File

@@ -6,7 +6,6 @@ library namespace_c;
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import 'namespace_test1_namespace_c_generated.dart';
import './namespace_test2_namespace_a_generated.dart' as namespace_a;
class TableInC {

View File

@@ -1459,7 +1459,7 @@ void FuzzTest2() {
break;
}
}
TEST_NOTNULL(nullptr);
TEST_NOTNULL(nullptr); //-V501 (this comment supresses CWE-570 warning)
}
// clang-format off

View File

@@ -5,11 +5,6 @@
using namespace MyGame::Example;
const std::string m1_name = "Cyberdemon";
const Color m1_color = Color_Red;
const std::string m2_name = "Imp";
const Color m2_color = Color_Green;
struct OwnedAllocator : public flatbuffers::DefaultAllocator {};
class TestHeapBuilder : public flatbuffers::FlatBufferBuilder {
@@ -88,14 +83,14 @@ struct GrpcLikeMessageBuilder : private AllocatorMember,
flatbuffers::Offset<Monster> populate1(
flatbuffers::FlatBufferBuilder &builder) {
auto name_offset = builder.CreateString(m1_name);
return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m1_color);
auto name_offset = builder.CreateString(m1_name());
return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m1_color());
}
flatbuffers::Offset<Monster> populate2(
flatbuffers::FlatBufferBuilder &builder) {
auto name_offset = builder.CreateString(m2_name);
return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m2_color);
auto name_offset = builder.CreateString(m2_name());
return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m2_color());
}
uint8_t *release_raw_base(flatbuffers::FlatBufferBuilder &fbb, size_t &size,
@@ -158,3 +153,7 @@ void FlatBufferBuilderTest() {
BuilderReuseTests<GrpcLikeMessageBuilder, GrpcLikeMessageBuilder>::run_tests(
TestSelector(tests, tests + 4));
}
// Link-time check using pointer type.
void CheckTestGeneratedIsValid(const MyGame::Example::Color&)
{}

View File

@@ -21,10 +21,19 @@ template<class T, class U> struct is_same { static const bool value = false; };
template<class T> struct is_same<T, T> { static const bool value = true; };
extern const std::string m1_name;
extern const Color m1_color;
extern const std::string m2_name;
extern const Color m2_color;
inline std::string m1_name() { return "Cyberdemon"; }
inline std::string m2_name() { return "Imp"; }
inline MyGame::Example::Color m1_color() {
return MyGame::Example::Color_Red;
}
inline MyGame::Example::Color m2_color() {
return MyGame::Example::Color_Green;
}
inline void m1_color_check() {
// Ensure that all compilation units see the same monster_test_generated.h.
extern void CheckTestGeneratedIsValid(const MyGame::Example::Color&);
CheckTestGeneratedIsValid(m1_color());
}
flatbuffers::Offset<Monster> populate1(flatbuffers::FlatBufferBuilder &builder);
flatbuffers::Offset<Monster> populate2(flatbuffers::FlatBufferBuilder &builder);
@@ -66,7 +75,7 @@ void builder_move_assign_after_releaseraw_test(Builder b1) {
// Move into a released builder.
b1 = std::move(src);
TEST_EQ_FUNC(b1.GetSize(), src_size);
TEST_ASSERT_FUNC(release_n_verify(b1, m2_name, m2_color));
TEST_ASSERT_FUNC(release_n_verify(b1, m2_name(), m2_color()));
TEST_EQ_FUNC(src.GetSize(), 0);
}
// clang-format off
@@ -104,7 +113,7 @@ struct BuilderTests {
auto root_offset1 = populate1(src);
DestBuilder dst(std::move(src));
dst.Finish(root_offset1);
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color()));
TEST_EQ_FUNC(src.GetSize(), 0);
}
@@ -115,7 +124,7 @@ struct BuilderTests {
auto src_size = src.GetSize();
DestBuilder dst(std::move(src));
TEST_EQ_FUNC(dst.GetSize(), src_size);
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color()));
TEST_EQ_FUNC(src.GetSize(), 0);
}
@@ -126,7 +135,7 @@ struct BuilderTests {
populate2(dst);
dst = std::move(src);
dst.Finish(root_offset1);
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color()));
TEST_EQ_FUNC(src.GetSize(), 0);
}
@@ -140,7 +149,7 @@ struct BuilderTests {
dst.Finish(root_offset2);
dst = std::move(src);
TEST_EQ_FUNC(dst.GetSize(), src_size);
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color()));
TEST_EQ_FUNC(src.GetSize(), 0);
}
@@ -159,7 +168,7 @@ struct BuilderTests {
// Move into a released builder.
dst = std::move(src);
TEST_EQ_FUNC(dst.GetSize(), src_size);
TEST_ASSERT_FUNC(release_n_verify(dst, m2_name, m2_color));
TEST_ASSERT_FUNC(release_n_verify(dst, m2_name(), m2_color()));
TEST_EQ_FUNC(src.GetSize(), 0);
}
// clang-format off
@@ -181,8 +190,8 @@ struct BuilderTests {
dst.Finish(root_offset1);
TEST_EQ_FUNC(src.GetSize() > size2, true);
TEST_EQ_FUNC(dst.GetSize() > size1, true);
TEST_ASSERT_FUNC(release_n_verify(src, m2_name, m2_color));
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(src, m2_name(), m2_color()));
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color()));
}
}
@@ -201,8 +210,8 @@ struct BuilderTests {
src.Swap(dst);
TEST_EQ_FUNC(src.GetSize(), size2);
TEST_EQ_FUNC(dst.GetSize(), size1);
TEST_ASSERT_FUNC(release_n_verify(src, m2_name, m2_color));
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name, m1_color));
TEST_ASSERT_FUNC(release_n_verify(src, m2_name(), m2_color()));
TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color()));
}
}
@@ -247,7 +256,7 @@ template<class DestBuilder, class SrcBuilder> struct BuilderReuseTests {
auto root_offset1 = populate1(fbb);
fbb.Finish(root_offset1);
buffers.push_back(fbb.Release());
TEST_ASSERT_FUNC(verify(buffers[i], m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color()));
}
}
@@ -260,7 +269,7 @@ template<class DestBuilder, class SrcBuilder> struct BuilderReuseTests {
fbb.Finish(root_offset1);
size_t size, offset;
uint8_t *buf = release_raw_base(fbb, size, offset);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
free_raw(fbb, buf);
}
}
@@ -278,7 +287,7 @@ template<class DestBuilder, class SrcBuilder> struct BuilderReuseTests {
auto root_offset1 = populate1(dst);
dst.Finish(root_offset1);
buffers.push_back(dst.Release());
TEST_ASSERT_FUNC(verify(buffers[i], m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color()));
SrcBuilder src;
dst = std::move(src);
TEST_EQ_FUNC(src.GetSize(), 0);
@@ -295,7 +304,7 @@ template<class DestBuilder, class SrcBuilder> struct BuilderReuseTests {
dst.Finish(root_offset1);
size_t size, offset;
uint8_t *buf = release_raw_base(dst, size, offset);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name, m1_color));
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
free_raw(dst, buf);
SrcBuilder src;
dst = std::move(src);

View File

@@ -73,7 +73,7 @@ inline const char * const *EnumNamesCharacter() {
}
inline const char *EnumNameCharacter(Character e) {
if (e < Character_NONE || e > Character_Unused) return "";
if (flatbuffers::IsOutRange(e, Character_NONE, Character_Unused)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesCharacter()[index];
}