Compare commits

..

32 Commits

Author SHA1 Message Date
Derek Bailey
01834de25e FlatBuffers Version 23.3.3 (#7852) 2023-03-03 11:46:55 -08:00
Chuck Atkins
6f9ea7c23c Add Java reflection bindings to the distribution (#7851)
The distributions for C++ and Python include the generated reflection
bindings but are currently missing from the other language packages.
This will bring the Java package generated for releases closer to
feature parity with the C++ and Python release artifacts.
2023-03-03 11:14:07 -08:00
CodeMaster7000
de9791e0a9 Update pom.xml (#7849)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 23:47:54 -08:00
José Luis Millán
3e778aca4d TS/JS: Export object based classes on entry (#7822)
* TS/JS: Export object based classes on entry

Along with the non object ones, for consistency. This is a regression
introduced recently.

Before:
 `export { UpdateSettingsRequest } from './worker/update-settings-request.js';`

Now:
 `export { UpdateSettingsRequest, UpdateSettingsRequestT } from './worker/update-settings-request.js';`

* only export object based classes for structs

Enums are not elegible.

---------

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 23:35:59 -08:00
Paulo Pinheiro
01f4138618 [Android][Kotlin] fixed build after decomission of jcenter and gradle update (#7840)
* [Android] fixed build after decomission of jcenter

JCenter[1] has been removed and now is failing android build. This
change updates the configuration to remove this and few other warnings.

1 - https://developer.android.com/studio/build/jcenter-migration

* [Kotlin] fix build for latest gradle version 8.0.1

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 23:27:06 -08:00
Chuck Atkins
b90cc35a10 Add a --java-package-prefix option to flatc (#7848)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 21:52:03 -08:00
Cedric Schmeits
79d6abb42e Added GENERATE_<TARGET> to flatbuffers_generate_headers (#7845)
The generation of the library interface supplied by this function only
works within the same directory as that the target was defined. By
adding a custom target named GENERATE_<TARGET> now also interface files
will be generated by making a target dependend on the generate target.

Example:
/CMakeLists.txt
  set(MY_INCL_SRC ${CMAKE_CURRENT_SOURCE_DIR}/fbs/my_incl.fbs)
  flatbuffers_generate_headers(TARGET my_incl
                               SCHEMAS ${MY_INCL_SRC})

  add_subdirectory(app)

/app/CMakeLists.txt
  add_executable(app src/test.cpp)
  target_link_libraries(app my_incl)
  add_dependencies(app GENERATE_my_incl)

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 21:47:18 -08:00
tira-misu
d1e4daa178 [CS] Naming collision if field has same name as table and used as key (#7842)
* Fix C/C++ Create<Type>Direct with sorted vectors

If a struct has a key the vector has to be sorted. To sort the vector
you can't use "const".

* Changes due to code review

* Improve code readability

* Add generate of JSON schema to string to lib

* option indent_step is supported

* Remove unused variables

* Fix break in test

* Fix style to be consistent with rest of the code

* [TS] Fix reserved words as arguments (#6955)

* [TS] Fix generation of reserved words in object api (#7106)

* [TS] Fix generation of object api

* [TS] Fix MakeCamel -> ConvertCase

* [C#] Fix collision of field name and type name

* [TS] Add test for struct of struct of struct

* Update generated files

* Add missing files

* [TS] Fix query of null/undefined fields in object api

* Fix collision if field name is equal to table name and used as key in an array

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 21:42:27 -08:00
Khanh Nguyen
4a34cd70dc Add Code Generator for idl_gen_fbs to parse .proto files (#7832)
* Add code generator for proto files

* Update

* Add --proto to script

* Remove cmt

* Move proto parsing logic into else block to share same set up logic for code_generator

* Remove IsValidCodeGenerator
2023-03-02 10:01:44 -08:00
Henner Zeller
6a9cd4411f Editorconfig: als configure to trim whitespaces end EOL. (#7833)
Signed-off-by: Henner Zeller <hzeller@google.com>
2023-02-27 19:56:18 -08:00
Saman
f7a75173f1 Move defined part to idl.h (#7823) 2023-02-17 20:34:32 -08:00
Even Rouault
a56f9ec50e Only use absl headers if C++14 is available. (#7824)
If flatbuffers is built in C++11 mode, but there is a recent version of
absl which requires C++14, the build will fail.
Cf https://github.com/MapServer/MapServer/issues/6822 for the use case
that triggered this.
2023-02-15 10:56:16 -08:00
Derek Bailey
4c71f87619 fixed bad math for --annotate-sparse-vectors 2023-02-06 22:08:09 -08:00
chrismue
6af83a7d05 Sample adjusted for Python3 (#7819)
Co-authored-by: chrismue <chrismue.gitlab@gmail.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-02-06 21:47:39 -08:00
Derek Bailey
535ead8d8c [Annotated Buffers] Improve efficiency (#7820)
* AnnotatedBinaryTextGen switch to ofstream instead of building giant string

* Add --annotate-sparse-vectors to reduce AFB size
2023-02-06 21:42:44 -08:00
Björn Harrtell
85aee1f5c3 Simplify and fix TypeScript compilation output (#7815)
* Simplify and fix TypeScript compilation output

* Revert deps upgrade
2023-02-06 13:10:20 -08:00
Derek Bailey
f3a3f45159 use switch statements for BASE_TYPE_ lookups (#7813) 2023-02-05 12:29:09 -08:00
Derek Bailey
02d7859f8b explicitly declare enum values (#7811) 2023-02-03 15:33:04 -08:00
Derek Bailey
5785784c8a proto_test.cpp don't warn about gaps 2023-02-02 15:57:55 -08:00
Derek Bailey
0fb5519585 Fixed vtable duplication for binary annotator (#7809) 2023-02-02 10:39:39 -08:00
Saman
f838017860 Parsing from proto should keep field ID. (fixes #7645) (#7655)
* Parsing from proto should keep field ID. (fixes #7645)

* Fix failed tests

* Fix windows warning

* Improve attribute generation in proto to fbs

* Check if id is used twice. fix Some clang-format problems

* Test if fake id can solve the test problem

* Validate proto file in proto -> fbs generation.

* Fix error messages

* Ignore id in union

* Add keep proto id for legacy and check gap flag have been added. Reserved id will be checked.

* Add needed flags

* unit tests

* fix fromat problem. fix comments and error messages.

* clear

* More unit tests

* Fix windows build

* Fix include problems

* Fake commit to invoke rebuild

* Fix buzel build

* Fix some issues

* Fix comments, fix return value and sort for android NDK

* Fix return type

* Break down big function

* Place todo

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-02-01 11:17:35 -08:00
Khanh Nguyen
08ebd202e2 Final refactor for bfsb_generator* and text generator (#7806)
* Refactor BfbsGenerator to use CodeGenerator interface

* Update

* Refactor bfbs generator

* Refactor bfbs generator for lua and nim. Remove old code that use Generator
interface.

* Update import

* Update CMakeLists

* Update BUILD file

* Update BUILD file for src

* Remove from Android CMakeLists and add error message

* Update

* Add generate root file function to Code Generator interface

* Update

* Update

* Minor format fix
2023-01-31 09:35:34 -08:00
Bernie Innocenti
a6f4194489 Fix std::span autodetection (#7805)
The current detection method fails on GCC 12.2 with -std=c++20 because
the __cpp_lib_span macro is undefined.

As per https://en.cppreference.com/w/cpp/utility/feature_test ,
__cpp_lib_span requires including either <version> or <span>.

Since both these headers were added in C++20, checking for C++20 is
sufficient (and simpler than using the library feature-test macro).

Signed-off-by: Bernie Innocenti <bernie@codewiz.org>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-30 21:59:17 -08:00
CodeMaster7000
7fb785fd89 Rename LICENSE.txt to LICENSE (#7808)
* Update PackageDebian.cmake

* Rename LICENSE.txt to LICENSE

* Update readme.md

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-30 21:36:30 -08:00
Ilya Lavrenov
ca71fdfb9a Supported cmake 3.8 (#7801) 2023-01-29 23:00:57 -08:00
Khanh Nguyen
a105c26eca Refactor usage message (#7803)
* Update usage string formation

* Rework help message to use code generator interface

* update

* refactor
2023-01-28 13:17:36 -06:00
Khanh Nguyen
5b7a02d037 Code generator refactor bug fix (#7802)
* Swift should use swift generator

* Swift should use swift generator

Co-authored-by: Mo (Khanh) Nguyen <khhn@google.com>
2023-01-26 10:57:47 -08:00
Wen Sun
f5121615d9 Clean up extra white spaces (#7800)
* Clean up extra white spaces

* update

Co-authored-by: Wen Sun <sunwen@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-25 17:37:03 +00:00
Khanh Nguyen
34c821f4ad Refactor languages to use CodeGenerator interface. (#7797)
* Refactor to use CodeGenerator interface.

- Move code to its own header file to be included in flatc_main.cpp
- Refactor code to use CodeGenerator interface for all languages

* Format all files

* remove lua code generator since it doesn't support bfbs generator

* Update CMakeLists file with new idl_gen_*.cpp and idl_gen_*.h files

* Add idl_gen_swift header file

* Add idl_gen_swift header file and update bazel file

* Remove CodeGenerator interface for idl_gen_text.*. Remove comments and extern declaration

* Reorder header and implementation files in CMakeLists.txt

* Add idl_gen_* header files to implementation files

* Update CMakeLists and remove unused import

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-25 09:05:48 -08:00
Wen Sun
802a3a056a [C++] Enable using struct and array of struct as key (#7741)
* add unit tests for support struct as key

* make changes to parser and add helper function to generate comparator for struct

* implement

* add more unit tests

* format

* just a test

* test done

* rerun generator

* restore build file

* address comment

* format

* rebase

* rebase

* add more unit tests

* rerun generator

* address some comments

* address comment

* update

* format

* address comment

Co-authored-by: Wen Sun <sunwen@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-24 16:37:13 -08:00
Derek Bailey
ee848a02e1 FlatBuffers Version 23.1.21 (#7796) 2023-01-21 12:46:57 -08:00
Björn Harrtell
ef76b5ece4 [TS/JS] Entry point per namespace and reworked 1.x compatible single file build (#7510)
* [TS/JS] Entry point per namespace

* Fix handling of outputpath and array_test

* Attempt to fix generate_code

* Fix cwd for ts in generate_code

* Attempt to fixup bazel and some docs

* Add --ts-flat-files to bazel build to get bundle

* Move to DEFAULT_FLATC_TS_ARGS

* Attempt to add esbuild

* Attempt to use npm instead

* Remove futile attempt to add esbuild

* Attempt to as bazel esbuild

* Shuffle

* Upgrade bazel deps

* Revert failed attempts to get bazel working

* Ignore flatc tests for now

* Add esbuild dependency

* `package.json` Include esbuild

* `WORKSPACE` Add fetching esbuild binary

* Update WORKSPACE

* Unfreeze Lockfile

* Update WORKSPACE

* Update BUILD.bazel

* Rework to suggest instead of running external bundler

* Add esbuild generation to test script

* Prelim bundle test

* Run test JavaScriptTest from flatbuffers 1.x

* Deps upgrade

* Clang format fix

* Revert bazel changes

* Fix newline

* Generate with type declarations

* Handle "empty" root namespace

* Adjust tests for typescript_keywords.ts

* Separate test procedure for old node resolution module output

* Fix rel path for root level re-exports

* Bazel support for esbuild-based flatc

Unfortunately, we lose typing information because the new esbuild method
of generating single files does not generate type information.

The method used here is a bit hack-ish because it relies on parsing the
console output of flatc to figure out what to do.

* Try to fix bazel build for when node isn't present on host

* Auto formatting fixes

* Fix missing generated code

Co-authored-by: Derek Bailey <derekbailey@google.com>
Co-authored-by: James Kuszmaul <jabukuszmaul+collab@gmail.com>
2023-01-21 12:22:22 -08:00
540 changed files with 24181 additions and 24605 deletions

View File

@@ -5,3 +5,4 @@ root = true
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

View File

@@ -38,8 +38,10 @@ jobs:
run: |
chmod +x flatc
./flatc --version
- name: flatc tests
run: python3 tests/flatc/main.py
# - name: flatc tests
# run: |
# yarn global add esbuild
# python3 tests/flatc/main.py
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
@@ -143,8 +145,8 @@ jobs:
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
- name: test
run: Release\flattests.exe
- name: flatc tests
run: python3 tests/flatc/main.py --flatc Release\flatc.exe
# - name: flatc tests
# run: python3 tests/flatc/main.py --flatc Release\flatc.exe
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
@@ -245,8 +247,8 @@ jobs:
run: |
chmod +x Release/flatc
Release/flatc --version
- name: flatc tests
run: python3 tests/flatc/main.py --flatc Release/flatc
# - name: flatc tests
# run: python3 tests/flatc/main.py --flatc Release/flatc
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
@@ -501,7 +503,9 @@ jobs:
run: yarn compile
- name: test
working-directory: tests/ts
run: python3 TypeScriptTest.py
run: |
yarn global add esbuild
python3 TypeScriptTest.py
build-dart:
name: Build Dart

View File

@@ -41,7 +41,6 @@ filegroup(
"include/flatbuffers/allocator.h",
"include/flatbuffers/array.h",
"include/flatbuffers/base.h",
"include/flatbuffers/bfbs_generator.h",
"include/flatbuffers/buffer.h",
"include/flatbuffers/buffer_ref.h",
"include/flatbuffers/code_generator.h",

View File

@@ -4,9 +4,20 @@ All major or breaking changes will be documented in this file, as well as any
new features that should be highlighted. Minor fixes or improvements are not
necessarily listed.
## [23.3.3 (Mar 3 2023)](https://github.com/google/flatbuffers/releases/tag/v23.3.3)
* Refactoring of `flatc` generators to use an interface (#7797).
* Removed legacy cmake support and set min to 3.8 (#7801).
## [23.1.21 (Jan 21 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20)
* Reworked entry points for Typescript/Javascript and compatibility for single
file build (#7510)
## [23.1.20 (Jan 20 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20)
* Removed go.mod files after some versioning issues were being report ([#7780](https://github.com/google/flatbuffers/issues/7780)).
* Removed go.mod files after some versioning issues were being report (#7780).
## [23.1.4 (Jan 4 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.4)

View File

@@ -157,6 +157,10 @@ endfunction()
# other flagc flags using the FLAGS option to change the behavior of the flatc
# tool.
#
# When the target_link_libraries is done within a different directory than
# flatbuffers_generate_headers is called, then the target should also be dependent
# the custom generation target called GENERATE_<TARGET>.
#
# Arguments:
# TARGET: The name of the target to generate.
# SCHEMAS: The list of schema files to generate code for.
@@ -182,6 +186,9 @@ endfunction()
# target_link_libraries(MyExecutableTarget
# PRIVATE my_generated_headers_target
# )
#
# Optional (only needed within different directory):
# add_dependencies(app GENERATE_my_generated_headers_target)
function(flatbuffers_generate_headers)
# Parse function arguments.
set(options)
@@ -226,6 +233,8 @@ function(flatbuffers_generate_headers)
"--include-prefix" ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX})
endif()
set(generated_custom_commands)
# Create rules to generate the code for each schema.
foreach(schema ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
get_filename_component(filename ${schema} NAME_WE)
@@ -254,6 +263,7 @@ function(flatbuffers_generate_headers)
COMMENT "Building ${schema} flatbuffers...")
list(APPEND all_generated_header_files ${generated_include})
list(APPEND all_generated_source_files ${generated_source_file})
list(APPEND generated_custom_commands "${generated_include}" "${generated_source_file}")
# Geneate the binary flatbuffers schemas if instructed to.
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "")
@@ -267,10 +277,17 @@ function(flatbuffers_generate_headers)
${schema}
DEPENDS ${FLATC_TARGET} ${schema}
WORKING_DIRECTORY "${working_dir}")
list(APPEND generated_custom_commands "${binary_schema}")
list(APPEND all_generated_binary_files ${binary_schema})
endif()
endforeach()
# Create an additional target as add_custom_command scope is only within same directory (CMakeFile.txt)
set(generate_target GENERATE_${FLATBUFFERS_GENERATE_HEADERS_TARGET})
add_custom_target(${generate_target} ALL
DEPENDS ${generated_custom_commands}
COMMENT "Generating flatbuffer target ${FLATBUFFERS_GENERATE_HEADERS_TARGET}")
# Set up interface library
add_library(${FLATBUFFERS_GENERATE_HEADERS_TARGET} INTERFACE)
target_sources(

View File

@@ -1,778 +0,0 @@
# This was the legacy <root>/CMakeLists.txt that supported cmake version 2.8.12.
# It was originally copied on Jan 30 2022, and is conditionally included in the
# current <root>/CMakeLists.txt if the cmake version used is older than the new
# minimum version.
#
# Only add to this file to fix immediate issues or if a change cannot be made
# <root>/CMakeList.txt in a compatible way.
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
if(CMAKE_VERSION VERSION_LESS 3.9)
project(FlatBuffers
VERSION 2.0.0
LANGUAGES CXX)
else()
project(FlatBuffers
DESCRIPTION "Flatbuffers serialization library"
VERSION 2.0.0
LANGUAGES CXX)
endif()
else()
project(FlatBuffers)
endif (POLICY CMP0048)
include(CMake/Version.cmake)
# generate compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# NOTE: Code coverage only works on Linux & OSX.
option(FLATBUFFERS_CODE_COVERAGE "Enable the code coverage build option." OFF)
option(FLATBUFFERS_BUILD_TESTS "Enable the build of tests and samples." ON)
option(FLATBUFFERS_INSTALL "Enable the installation of targets." ON)
option(FLATBUFFERS_BUILD_FLATLIB "Enable the build of the flatbuffers library"
ON)
option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler"
ON)
option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
OFF)
option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark. \"
Requires C++11."
OFF)
option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
option(FLATBUFFERS_BUILD_SHAREDLIB
"Enable the build of the flatbuffers shared library"
OFF)
option(FLATBUFFERS_LIBCXX_WITH_CLANG "Force libc++ when using Clang" ON)
# NOTE: Sanitizer check only works on Linux & OSX (gcc & llvm).
option(FLATBUFFERS_CODE_SANITIZE
"Add '-fsanitize' flags to 'flattests' and 'flatc' targets."
OFF)
option(FLATBUFFERS_PACKAGE_REDHAT
"Build an rpm using the 'package' target."
OFF)
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)
option(FLATBUFFERS_ENABLE_PCH
"Enable precompile headers support for 'flatbuffers' and 'flatc'. \"
Only work if CMake supports 'target_precompile_headers'. \"
This can speed up compilation time."
OFF)
option(FLATBUFFERS_SKIP_MONSTER_EXTRA
"Skip generating monster_extra.fbs that contains non-supported numerical\"
types." OFF)
option(FLATBUFFERS_OSX_BUILD_UNIVERSAL
"Enable the build for multiple architectures on OS X (arm64, x86_64)."
ON)
if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
message(WARNING
"Cannot build tests without building the compiler. Tests will be disabled.")
set(FLATBUFFERS_BUILD_TESTS OFF)
endif()
if(DEFINED FLATBUFFERS_MAX_PARSING_DEPTH)
# Override the default recursion depth limit.
add_definitions(-DFLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH})
message(STATUS "FLATBUFFERS_MAX_PARSING_DEPTH: ${FLATBUFFERS_MAX_PARSING_DEPTH}")
endif()
# Auto-detect locale-narrow 'strtod_l' and 'strtoull_l' functions.
if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
include(CheckCXXSymbolExists)
set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
if(MSVC)
check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
else()
check_cxx_symbol_exists(strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
check_cxx_symbol_exists(strtoull_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
endif()
if(FLATBUFFERS_HAS_STRTOF_L AND FLATBUFFERS_HAS_STRTOULL_L)
set(FLATBUFFERS_LOCALE_INDEPENDENT 1)
endif()
endif()
add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
set(FlatBuffers_Library_SRCS
include/flatbuffers/allocator.h
include/flatbuffers/array.h
include/flatbuffers/base.h
include/flatbuffers/bfbs_generator.h
include/flatbuffers/buffer.h
include/flatbuffers/buffer_ref.h
include/flatbuffers/default_allocator.h
include/flatbuffers/detached_buffer.h
include/flatbuffers/flatbuffer_builder.h
include/flatbuffers/flatbuffers.h
include/flatbuffers/flexbuffers.h
include/flatbuffers/hash.h
include/flatbuffers/idl.h
include/flatbuffers/minireflect.h
include/flatbuffers/reflection.h
include/flatbuffers/reflection_generated.h
include/flatbuffers/registry.h
include/flatbuffers/stl_emulation.h
include/flatbuffers/string.h
include/flatbuffers/struct.h
include/flatbuffers/table.h
include/flatbuffers/util.h
include/flatbuffers/vector.h
include/flatbuffers/vector_downward.h
include/flatbuffers/verifier.h
src/idl_parser.cpp
src/idl_gen_text.cpp
src/reflection.cpp
src/util.cpp
)
set(FlatBuffers_Compiler_SRCS
${FlatBuffers_Library_SRCS}
src/idl_gen_cpp.cpp
src/idl_gen_csharp.cpp
src/idl_gen_dart.cpp
src/idl_gen_kotlin.cpp
src/idl_gen_go.cpp
src/idl_gen_java.cpp
src/idl_gen_ts.cpp
src/idl_gen_php.cpp
src/idl_gen_python.cpp
src/idl_gen_lobster.cpp
src/idl_gen_lua.cpp
src/idl_gen_rust.cpp
src/idl_gen_fbs.cpp
src/idl_gen_grpc.cpp
src/idl_gen_json_schema.cpp
src/idl_gen_swift.cpp
src/flatc.cpp
src/flatc_main.cpp
src/bfbs_gen.h
src/bfbs_gen_lua.h
include/flatbuffers/code_generators.h
src/bfbs_gen_lua.cpp
src/code_generators.cpp
grpc/src/compiler/schema_interface.h
grpc/src/compiler/cpp_generator.h
grpc/src/compiler/cpp_generator.cc
grpc/src/compiler/go_generator.h
grpc/src/compiler/go_generator.cc
grpc/src/compiler/java_generator.h
grpc/src/compiler/java_generator.cc
grpc/src/compiler/python_generator.h
grpc/src/compiler/python_generator.cc
grpc/src/compiler/swift_generator.h
grpc/src/compiler/swift_generator.cc
grpc/src/compiler/ts_generator.h
grpc/src/compiler/ts_generator.cc
)
set(FlatHash_SRCS
include/flatbuffers/hash.h
src/flathash.cpp
)
set(FlatBuffers_Tests_SRCS
${FlatBuffers_Library_SRCS}
src/idl_gen_fbs.cpp
tests/test.cpp
tests/test_assert.h
tests/test_assert.cpp
tests/test_builder.h
tests/test_builder.cpp
tests/native_type_test_impl.h
tests/native_type_test_impl.cpp
include/flatbuffers/code_generators.h
src/code_generators.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
${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h
# file generate by running compiler on tests/monster_extra.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h
# file generate by running compiler on tests/optional_scalars.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_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
${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/optional_scalars_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
)
set(FlatBuffers_Sample_Binary_SRCS
include/flatbuffers/flatbuffers.h
samples/sample_binary.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_Sample_Text_SRCS
${FlatBuffers_Library_SRCS}
samples/sample_text.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_Sample_BFBS_SRCS
${FlatBuffers_Library_SRCS}
samples/sample_bfbs.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_GRPCTest_SRCS
include/flatbuffers/flatbuffers.h
include/flatbuffers/grpc.h
include/flatbuffers/util.h
src/util.cpp
tests/monster_test.grpc.fb.h
tests/test_assert.h
tests/test_builder.h
tests/monster_test.grpc.fb.cc
tests/test_assert.cpp
tests/test_builder.cpp
grpc/tests/grpctest.cpp
grpc/tests/message_builder_test.cpp
# 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})
# source_group(Tests FILES ${FlatBuffers_Tests_SRCS})
if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
# do not apply any global settings if the toolchain
# is being configured externally
message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.")
elseif(CMAKE_COMPILER_IS_GNUCXX)
if(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=gnu++11")
else(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=c++0x")
endif(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow")
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.4)
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -faligned-new -Werror=implicit-fallthrough=2")
endif()
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter")
endif()
# Certain platforms such as ARM do not use signed chars by default
# which causes issues with certain bounds checks.
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
# MSVC **MUST** come before the Clang check, as clang-cl is flagged by CMake as "MSVC", but it still textually
# matches as Clang in its Compiler Id :)
# Note: in CMake >= 3.14 we can check CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU" or "MSVC" to differentiate...
elseif(MSVC)
# Visual Studio pedantic build settings
# warning C4512: assignment operator could not be generated
# warning C4316: object allocated on the heap may not be aligned
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
if(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D_CRT_SECURE_NO_WARNINGS")
endif()
elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
if(APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
if(FLATBUFFERS_OSX_BUILD_UNIVERSAL)
set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64")
endif()
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8)
list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning
endif()
if(FLATBUFFERS_LIBCXX_WITH_CLANG)
if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "Linux")
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -stdlib=libc++")
endif()
if(NOT ("${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD" OR
"${CMAKE_SYSTEM_NAME}" MATCHES "Linux"))
set(CMAKE_EXE_LINKER_FLAGS
"${CMAKE_EXE_LINKER_FLAGS} -lc++abi")
endif()
endif()
# Certain platforms such as ARM do not use signed chars by default
# which causes issues with certain bounds checks.
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
endif()
# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}")
endif()
message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
if(FLATBUFFERS_CODE_COVERAGE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage")
set(CMAKE_EXE_LINKER_FLAGS
"${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage")
endif()
function(add_fsanitize_to_target _target _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()
endif()
endfunction()
function(add_pch_to_target _target _pch_header)
if(COMMAND target_precompile_headers)
target_precompile_headers(${_target} PRIVATE ${_pch_header})
if(NOT MSVC)
set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
endif()
endif()
endfunction()
if(BIICODE)
include(biicode/cmake/biicode.cmake)
return()
endif()
include_directories(include)
include_directories(grpc)
if(FLATBUFFERS_BUILD_FLATLIB)
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
# 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}")
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
endif()
endif()
if(FLATBUFFERS_BUILD_FLATC)
add_executable(flatc ${FlatBuffers_Compiler_SRCS})
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h)
endif()
target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
endif()
if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
endif()
if(MSVC)
# Make flatc.exe not depend on runtime dlls for easy distribution.
target_compile_options(flatc PUBLIC $<$<CONFIG:Release>:/MT>)
endif()
if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC)
target_link_libraries(flatc PRIVATE -static)
endif()
endif()
if(FLATBUFFERS_BUILD_FLATHASH)
add_executable(flathash ${FlatHash_SRCS})
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
# FlatBuffers use calendar-based versioning and do not provide any ABI
# stability guarantees. Therefore, always use the full version as SOVERSION
# in order to avoid breaking reverse dependencies on upgrades.
set(FlatBuffers_Library_SONAME_FULL "${PROJECT_VERSION}")
set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
SOVERSION "${FlatBuffers_Library_SONAME_FULL}"
VERSION "${FlatBuffers_Library_SONAME_FULL}")
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h)
endif()
endif()
# Global list of generated files.
# Use the global property to be independent of PARENT_SCOPE.
set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
function(get_generated_output generated_files)
get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
set(${generated_files} ${tmp} PARENT_SCOPE)
endfunction(get_generated_output)
function(register_generated_output file_name)
get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
list(APPEND tmp ${file_name})
set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS ${tmp})
endfunction(register_generated_output)
function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT)
if(FLATBUFFERS_BUILD_LEGACY)
set(OPT ${OPT};--cpp-std c++0x)
else()
# --cpp-std is defined by flatc default settings.
endif()
message(STATUS "`${SRC_FBS}`: add generation of C++ code with '${OPT}'")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
add_custom_command(
OUTPUT ${GEN_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
--cpp --gen-mutable --gen-object-api --reflect-names
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
${OPT}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_HEADER}'")
register_generated_output(${GEN_HEADER})
endfunction()
function(compile_flatbuffers_schema_to_cpp SRC_FBS)
compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare")
endfunction()
function(compile_flatbuffers_schema_to_binary SRC_FBS)
message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
# For details about flags see generate_code.py
add_custom_command(
OUTPUT ${GEN_BINARY_SCHEMA}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
-b --schema --bfbs-comments --bfbs-builtins
--bfbs-filenames ${SRC_FBS_DIR}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_BINARY_SCHEMA}'")
register_generated_output(${GEN_BINARY_SCHEMA})
endfunction()
function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT)
if(FLATBUFFERS_BUILD_LEGACY)
set(OPT ${OPT};--cpp-std c++0x)
else()
# --cpp-std is defined by flatc default settings.
endif()
message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS})
# For details about flags see generate_code.py
add_custom_command(
OUTPUT ${GEN_BFBS_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
--cpp --gen-mutable --gen-object-api --reflect-names
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
${OPT}
--bfbs-comments --bfbs-builtins --bfbs-gen-embed
--bfbs-filenames ${SRC_FBS_DIR}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_BFBS_HEADER}'")
register_generated_output(${GEN_BFBS_HEADER})
endfunction()
# Look if we have python 3.5 installed so that we can run the generate code
# python script after flatc is built.
find_package(PythonInterp 3.5)
if(PYTHONINTERP_FOUND AND
# Skip doing this if the MSVC version is below VS 12.
# https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html
(NOT MSVC OR MSVC_VERSION GREATER 1800))
set(GENERATION_SCRIPT ${PYTHON_EXECUTABLE} scripts/generate_code.py)
if(FLATBUFFERS_BUILD_LEGACY)
# Need to set --cpp-std c++-0x options
set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --cpp-0x)
endif()
if(FLATBUFFERS_SKIP_MONSTER_EXTRA)
set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --skip-monster-extra)
endif()
add_custom_command(
TARGET flatc
POST_BUILD
COMMAND ${GENERATION_SCRIPT} --flatc "${FLATBUFFERS_FLATC_EXECUTABLE}"
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
COMMENT "Running ${GENERATION_SCRIPT}..."
VERBATIM)
else()
message("No Python3 interpreter found! Unable to generate files automatically.")
endif()
if(FLATBUFFERS_BUILD_TESTS)
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
# TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon
compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
compile_flatbuffers_schema_to_binary(tests/monster_test.fbs)
compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp(tests/optional_scalars.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")
compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
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)
add_executable(flattests ${FlatBuffers_Tests_SRCS})
add_dependencies(flattests generated_code)
set_property(TARGET flattests
PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1)
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
endif()
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
compile_flatbuffers_schema_to_binary(samples/monster.fbs)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
add_dependencies(flatsamplebinary generated_code)
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
add_dependencies(flatsampletext generated_code)
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
add_dependencies(flatsamplebfbs generated_code)
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.py script.
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
add_dependencies(flattests_cpp17 generated_code)
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)
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-shadow")
endif()
if(NOT GRPC_INSTALL_PATH)
message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md")
endif()
if(NOT PROTOBUF_DOWNLOAD_PATH)
message(SEND_ERROR "PROTOBUF_DOWNLOAD_PATH variable is not defined. See grpc/README.md")
endif()
INCLUDE_DIRECTORIES(${GRPC_INSTALL_PATH}/include)
INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src)
find_package(Threads REQUIRED)
list(APPEND CMAKE_PREFIX_PATH ${GRPC_INSTALL_PATH})
find_package(absl CONFIG REQUIRED)
find_package(protobuf CONFIG REQUIRED)
find_package(gRPC CONFIG REQUIRED)
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
add_dependencies(grpctest generated_code)
target_link_libraries(grpctest PRIVATE gRPC::grpc++_unsecure gRPC::grpc_unsecure gRPC::gpr pthread dl)
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
# GRPC test has problems with alignment and will fail under ASAN/UBSAN.
# add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE})
endif()
endif()
if(FLATBUFFERS_INSTALL)
include(GNUInstallDirs)
install(DIRECTORY include/flatbuffers DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers")
configure_file(CMake/flatbuffers-config-version.cmake.in flatbuffers-config-version.cmake @ONLY)
install(
FILES "CMake/flatbuffers-config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake"
DESTINATION ${FB_CMAKE_DIR}
)
if(FLATBUFFERS_BUILD_FLATLIB)
if(CMAKE_VERSION VERSION_LESS 3.0)
install(
TARGETS flatbuffers EXPORT FlatBuffersTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
else()
install(
TARGETS flatbuffers EXPORT FlatBuffersTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
endif()
install(EXPORT FlatBuffersTargets
FILE FlatBuffersTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
endif()
if(FLATBUFFERS_BUILD_FLATC)
install(
TARGETS flatc EXPORT FlatcTargets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
install(
EXPORT FlatcTargets
FILE FlatcTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
if(CMAKE_VERSION VERSION_LESS 3.0)
install(
TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
else()
install(
TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
endif()
install(
EXPORT FlatBuffersSharedTargets
FILE FlatBuffersSharedTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB OR FLATBUFFERS_BUILD_FLATLIB)
configure_file(CMake/flatbuffers.pc.in flatbuffers.pc @ONLY)
install(
FILES "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers.pc"
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
)
endif()
endif()
if(FLATBUFFERS_BUILD_TESTS)
enable_testing()
add_test(NAME flattests COMMAND flattests)
if(FLATBUFFERS_BUILD_CPP17)
add_test(NAME flattests_cpp17 COMMAND flattests_cpp17)
endif()
if(FLATBUFFERS_BUILD_GRPCTEST)
add_test(NAME grpctest COMMAND grpctest)
endif()
endif()
# This target is sync-barrier.
# Other generate-dependent targets can depend on 'generated_code' only.
get_generated_output(fbs_generated)
if(fbs_generated)
# message(STATUS "Add generated_code target with files:${fbs_generated}")
add_custom_target(generated_code
DEPENDS ${fbs_generated}
COMMENT "All generated files were updated.")
endif()
include(CMake/BuildFlatBuffers.cmake)
if(UNIX)
# Use of CPack only supported on Linux systems.
if(FLATBUFFERS_PACKAGE_DEBIAN)
include(CMake/PackageDebian.cmake)
include(CPack)
endif()
if (FLATBUFFERS_PACKAGE_REDHAT)
include(CMake/PackageRedhat.cmake)
include(CPack)
endif()
endif()
# Include for running Google Benchmarks.
if(FLATBUFFERS_BUILD_BENCHMARKS AND CMAKE_VERSION VERSION_GREATER 3.13)
add_subdirectory(benchmarks)
endif()
# Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare
add_library(FlatBuffers INTERFACE)
add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers)
target_include_directories(
FlatBuffers
INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)

View File

@@ -17,23 +17,9 @@ if (UNIX)
SET(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_COMMIT}")
SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}")
# Derive architecture
IF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE)
FIND_PROGRAM(DPKG_CMD dpkg)
IF(NOT DPKG_CMD)
MESSAGE(STATUS "Can not find dpkg in your path, default to i386.")
SET(CPACK_DEBIAN_PACKAGE_ARCHITECTURE i386)
ENDIF(NOT DPKG_CMD)
EXECUTE_PROCESS(COMMAND "${DPKG_CMD}" --print-architecture
OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE
OUTPUT_STRIP_TRAILING_WHITESPACE
)
ENDIF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE)
# Package name
SET(CPACK_DEBIAN_PACKAGE_NAME "flatbuffers")
SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE.txt)
SET(CPACK_PACKAGE_FILE_NAME
"${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}")
SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE)
set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
endif(UNIX)

View File

@@ -15,7 +15,7 @@ if (UNIX)
set(CPACK_RPM_PACKAGE_NAME "flatbuffers")
# Assume this is not a cross complation build.
# Assume this is not a cross compilation build.
if(NOT CPACK_RPM_PACKAGE_ARCHITECTURE)
set(CPACK_RPM_PACKAGE_ARCHITECTURE "${CMAKE_SYSTEM_PROCESSOR}")
endif(NOT CPACK_RPM_PACKAGE_ARCHITECTURE)

View File

@@ -1,6 +1,6 @@
set(VERSION_MAJOR 23)
set(VERSION_MINOR 1)
set(VERSION_PATCH 20)
set(VERSION_MINOR 3)
set(VERSION_PATCH 3)
set(VERSION_COMMIT 0)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git")

View File

@@ -1,32 +1,12 @@
# This is the legacy minimum version flatbuffers supported for a while.
cmake_minimum_required(VERSION 2.8.12...3.22.1)
# CMake version 3.16 is the 'de-facto' minimum version for flatbuffers. If the
# current cmake is older than this, warn the user and include the legacy file to
# provide some level of support.
if(CMAKE_VERSION VERSION_LESS 3.16)
message(WARNING "Using cmake version ${CMAKE_VERSION} which is older than "
"our target version of 3.16. This will use the legacy CMakeLists.txt that "
"supports version 2.8.12 and higher, but not actively maintained. Consider "
"upgrading cmake to a newer version, as this may become a fatal error in the "
"future.")
# Use the legacy version of CMakeLists.txt
include(CMake/CMakeLists_legacy.cmake.in)
return()
endif()
cmake_minimum_required(VERSION 3.8...3.25.2)
# Attempt to read the current version of flatbuffers by looking at the latest tag.
include(CMake/Version.cmake)
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
project(FlatBuffers
DESCRIPTION "Flatbuffers serialization library"
project(FlatBuffers
VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
LANGUAGES CXX)
else()
project(FlatBuffers)
endif (POLICY CMP0048)
# generate compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
@@ -87,6 +67,12 @@ if(MSVC OR CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
set(MSVC_LIKE ON)
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(IS_CLANG ON)
else()
set(IS_CLANG OFF)
endif()
if(DEFINED FLATBUFFERS_COMPILATION_TIMINGS)
message("Recording Compilation Timings to ${FLATBUFFERS_COMPILATION_TIMINGS}")
file(REMOVE ${FLATBUFFERS_COMPILATION_TIMINGS})
@@ -136,7 +122,6 @@ set(FlatBuffers_Library_SRCS
include/flatbuffers/allocator.h
include/flatbuffers/array.h
include/flatbuffers/base.h
include/flatbuffers/bfbs_generator.h
include/flatbuffers/buffer.h
include/flatbuffers/buffer_ref.h
include/flatbuffers/default_allocator.h
@@ -168,6 +153,8 @@ set(FlatBuffers_Library_SRCS
set(FlatBuffers_Compiler_SRCS
${FlatBuffers_Library_SRCS}
src/idl_gen_binary.cpp
src/idl_gen_text.cpp
src/idl_gen_cpp.cpp
src/idl_gen_csharp.cpp
src/idl_gen_dart.cpp
@@ -323,7 +310,7 @@ set(FlatBuffers_GRPCTest_SRCS
# TODO(dbaileychess): Figure out how this would now work. I posted a question on
# https://stackoverflow.com/questions/71772330/override-target-compile-options-via-cmake-command-line.
# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
if(DEFINED FLATBUFFERS_CXX_FLAGS)
message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}")
endif()
@@ -336,9 +323,7 @@ function(add_fsanitize_to_target _target _sanitizer)
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"))
)
if(IS_CLANG OR (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 4.9))
set(_sanitizer_flags "=address,undefined")
if(_sanitizer MATCHES "=.*")
# override default by user-defined sanitizer list
@@ -349,13 +334,14 @@ function(add_fsanitize_to_target _target _sanitizer)
"-fsanitize${_sanitizer_flags}")
target_link_libraries(${_target} PRIVATE
"-fsanitize${_sanitizer_flags}")
set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON)
set_target_properties(${_target} PROPERTIES POSITION_INDEPENDENT_CODE ON)
message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}")
endif()
endif()
endfunction()
function(add_pch_to_target _target _pch_header)
# the command is available since cmake 3.16
if(COMMAND target_precompile_headers)
target_precompile_headers(${_target} PRIVATE ${_pch_header})
if(NOT MSVC)
@@ -399,11 +385,6 @@ if(MSVC_LIKE)
>
)
else()
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
set(IS_CLANG ON)
else()
set(IS_CLANG OFF)
endif()
target_compile_options(ProjectConfig
INTERFACE
-Wall
@@ -500,7 +481,7 @@ if(FLATBUFFERS_BUILD_FLATC)
target_link_libraries(flatc PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_compile_options(flatc
PUBLIC
PRIVATE
$<$<AND:$<BOOL:${MSVC_LIKE}>,$<CONFIG:Release>>:
/MT
>
@@ -529,7 +510,8 @@ if(FLATBUFFERS_BUILD_SHAREDLIB)
# stability guarantees. Therefore, always use the full version as SOVERSION
# in order to avoid breaking reverse dependencies on upgrades.
set(FlatBuffers_Library_SONAME_FULL "${PROJECT_VERSION}")
set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
set_target_properties(flatbuffers_shared PROPERTIES
OUTPUT_NAME flatbuffers
SOVERSION "${FlatBuffers_Library_SONAME_FULL}"
VERSION "${FlatBuffers_Library_SONAME_FULL}")
if(FLATBUFFERS_ENABLE_PCH)
@@ -676,7 +658,7 @@ if(FLATBUFFERS_BUILD_TESTS)
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
add_dependencies(flattests_cpp17 generated_code)
target_link_libraries(flattests_cpp17 PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) # requires cmake 3.8
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})

View File

@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'FlatBuffers'
s.version = '23.1.20'
s.version = '23.3.3'
s.summary = 'FlatBuffers: Memory Efficient Serialization Library'
s.description = "FlatBuffers is a cross platform serialization library architected for

View File

@@ -94,8 +94,12 @@ yarn_install(
name = "npm",
exports_directories_only = False,
# Unfreeze to add/remove packages.
frozen_lockfile = True,
frozen_lockfile = False,
package_json = "//:package.json",
symlink_node_modules = False,
yarn_lock = "//:yarn.lock",
)
load("@build_bazel_rules_nodejs//toolchains/esbuild:esbuild_repositories.bzl", "esbuild_repositories")
esbuild_repositories(npm_repository = "npm")

View File

@@ -1,20 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2014 Google, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-->
<projectDescription>
<name>FlatBufferTest</name>
<name>FlatBufferTest</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
<filteredResources>
<filter>
<id>1677235311958</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View File

@@ -1,15 +1,13 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
compileSdk 33
defaultConfig {
applicationId "com.flatbuffers.app"
minSdkVersion 26
targetSdkVersion 30
targetSdkVersion 33
versionCode 1
versionName "1.0"
@@ -113,13 +111,13 @@ android {
dependsOn(generateFbsCpp)
}
}
namespace 'com.flatbuffers.app'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
// If you using java runtime you can add its dependency as the example below
// implementation 'com.google.flatbuffers:flatbuffers-java:$latest_version'

View File

@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.flatbuffers.app">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
@@ -9,7 +8,8 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

View File

@@ -18,7 +18,6 @@ set(FlatBuffers_Library_SRCS
${FLATBUFFERS_SRC}/include/flatbuffers/allocator.h
${FLATBUFFERS_SRC}/include/flatbuffers/array.h
${FLATBUFFERS_SRC}/include/flatbuffers/base.h
${FLATBUFFERS_SRC}/include/flatbuffers/bfbs_generator.h
${FLATBUFFERS_SRC}/include/flatbuffers/buffer.h
${FLATBUFFERS_SRC}/include/flatbuffers/buffer_ref.h
${FLATBUFFERS_SRC}/include/flatbuffers/default_allocator.h

View File

@@ -8,9 +8,9 @@
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 2 &&
FLATBUFFERS_VERSION_MINOR == 0 &&
FLATBUFFERS_VERSION_REVISION == 8,
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 1 &&
FLATBUFFERS_VERSION_REVISION == 21,
"Non-compatible flatbuffers version included");
namespace com {
@@ -20,23 +20,23 @@ namespace app {
struct Animal;
struct AnimalBuilder;
struct Animal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
struct Animal FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
typedef AnimalBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_SOUND = 6,
VT_WEIGHT = 8
};
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
const ::flatbuffers::String *name() const {
return GetPointer<const ::flatbuffers::String *>(VT_NAME);
}
const flatbuffers::String *sound() const {
return GetPointer<const flatbuffers::String *>(VT_SOUND);
const ::flatbuffers::String *sound() const {
return GetPointer<const ::flatbuffers::String *>(VT_SOUND);
}
uint16_t weight() const {
return GetField<uint16_t>(VT_WEIGHT, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
@@ -49,32 +49,32 @@ struct Animal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
struct AnimalBuilder {
typedef Animal Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
::flatbuffers::FlatBufferBuilder &fbb_;
::flatbuffers::uoffset_t start_;
void add_name(::flatbuffers::Offset<::flatbuffers::String> name) {
fbb_.AddOffset(Animal::VT_NAME, name);
}
void add_sound(flatbuffers::Offset<flatbuffers::String> sound) {
void add_sound(::flatbuffers::Offset<::flatbuffers::String> sound) {
fbb_.AddOffset(Animal::VT_SOUND, sound);
}
void add_weight(uint16_t weight) {
fbb_.AddElement<uint16_t>(Animal::VT_WEIGHT, weight, 0);
}
explicit AnimalBuilder(flatbuffers::FlatBufferBuilder &_fbb)
explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
flatbuffers::Offset<Animal> Finish() {
::flatbuffers::Offset<Animal> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<Animal>(end);
auto o = ::flatbuffers::Offset<Animal>(end);
return o;
}
};
inline flatbuffers::Offset<Animal> CreateAnimal(
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::String> name = 0,
flatbuffers::Offset<flatbuffers::String> sound = 0,
inline ::flatbuffers::Offset<Animal> CreateAnimal(
::flatbuffers::FlatBufferBuilder &_fbb,
::flatbuffers::Offset<::flatbuffers::String> name = 0,
::flatbuffers::Offset<::flatbuffers::String> sound = 0,
uint16_t weight = 0) {
AnimalBuilder builder_(_fbb);
builder_.add_sound(sound);
@@ -83,8 +83,8 @@ inline flatbuffers::Offset<Animal> CreateAnimal(
return builder_.Finish();
}
inline flatbuffers::Offset<Animal> CreateAnimalDirect(
flatbuffers::FlatBufferBuilder &_fbb,
inline ::flatbuffers::Offset<Animal> CreateAnimalDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
const char *sound = nullptr,
uint16_t weight = 0) {
@@ -98,32 +98,32 @@ inline flatbuffers::Offset<Animal> CreateAnimalDirect(
}
inline const com::fbs::app::Animal *GetAnimal(const void *buf) {
return flatbuffers::GetRoot<com::fbs::app::Animal>(buf);
return ::flatbuffers::GetRoot<com::fbs::app::Animal>(buf);
}
inline const com::fbs::app::Animal *GetSizePrefixedAnimal(const void *buf) {
return flatbuffers::GetSizePrefixedRoot<com::fbs::app::Animal>(buf);
return ::flatbuffers::GetSizePrefixedRoot<com::fbs::app::Animal>(buf);
}
inline bool VerifyAnimalBuffer(
flatbuffers::Verifier &verifier) {
::flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<com::fbs::app::Animal>(nullptr);
}
inline bool VerifySizePrefixedAnimalBuffer(
flatbuffers::Verifier &verifier) {
::flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<com::fbs::app::Animal>(nullptr);
}
inline void FinishAnimalBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::Offset<com::fbs::app::Animal> root) {
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<com::fbs::app::Animal> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedAnimalBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::Offset<com::fbs::app::Animal> root) {
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<com::fbs::app::Animal> root) {
fbb.FinishSizePrefixed(root);
}

View File

@@ -19,6 +19,7 @@ import java.nio.ByteOrder
import kotlin.math.sign
@Suppress("unused")
@kotlin.ExperimentalUnsignedTypes
class Animal : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -31,14 +32,22 @@ class Animal : Table() {
val name : String?
get() {
val o = __offset(4)
return if (o != 0) __string(o + bb_pos) else null
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
val nameAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1)
fun nameInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1)
val sound : String?
get() {
val o = __offset(6)
return if (o != 0) __string(o + bb_pos) else null
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
val soundAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(6, 1)
fun soundInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1)
@@ -48,7 +57,7 @@ class Animal : Table() {
return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_23_1_20()
fun validateVersion() = Constants.FLATBUFFERS_23_3_3()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)

View File

@@ -1,12 +1,12 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.10"
ext.kotlin_version = "1.7.21"
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath 'com.android.tools.build:gradle:7.4.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
@@ -17,7 +17,7 @@ buildscript {
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,8 +1,9 @@
# Setup for running Google Benchmarks (https://github.com/google/benchmark) on
# flatbuffers. This requires both that benchmark library and its depenency gtest
# flatbuffers. This requires both that benchmark library and its dependency gtest
# to build. Instead of including them here or doing a submodule, this uses
# FetchContent (https://cmake.org/cmake/help/latest/module/FetchContent.html) to
# grab the dependencies at config time. This requires CMake 3.14 or higher.
cmake_minimum_required(VERSION 3.14)
include(FetchContent)
@@ -62,8 +63,8 @@ add_custom_command(
add_executable(flatbenchmark ${FlatBenchmark_SRCS})
# Benchmark requires C++11
target_compile_features(flatbenchmark PUBLIC
cxx_std_11
target_compile_features(flatbenchmark PRIVATE
cxx_std_11 # requires cmake 3.8
)
target_compile_options(flatbenchmark
@@ -81,7 +82,7 @@ set_target_properties(flatbenchmark
# The includes of the benchmark files are fully qualified from flatbuffers root.
target_include_directories(flatbenchmark PUBLIC ${CMAKE_SOURCE_DIR})
target_link_libraries(flatbenchmark
target_link_libraries(flatbenchmark PRIVATE
benchmark::benchmark_main # _main to use their entry point
gtest # Link to gtest so we can also assert in the benchmarks
)

View File

@@ -7,7 +7,7 @@ Rules for building C++ flatbuffers with Bazel.
load("@rules_cc//cc:defs.bzl", "cc_library")
flatc_path = "@com_github_google_flatbuffers//:flatc"
TRUE_FLATC_PATH = "@com_github_google_flatbuffers//:flatc"
DEFAULT_INCLUDE_PATHS = [
"./",
@@ -16,6 +16,14 @@ DEFAULT_INCLUDE_PATHS = [
"$(execpath @com_github_google_flatbuffers//:flatc).runfiles/com_github_google_flatbuffers",
]
def default_include_paths(flatc_path):
return [
"./",
"$(GENDIR)",
"$(BINDIR)",
"$(execpath %s).runfiles/com_github_google_flatbuffers" % (flatc_path),
]
DEFAULT_FLATC_ARGS = [
"--gen-object-api",
"--gen-compare",
@@ -32,13 +40,14 @@ def flatbuffer_library_public(
language_flag,
out_prefix = "",
includes = [],
include_paths = DEFAULT_INCLUDE_PATHS,
include_paths = None,
flatc_args = DEFAULT_FLATC_ARGS,
reflection_name = "",
reflection_visibility = None,
compatible_with = None,
restricted_to = None,
target_compatible_with = None,
flatc_path = "@com_github_google_flatbuffers//:flatc",
output_to_bindir = False):
"""Generates code files for reading/writing the given flatbuffers in the requested language using the public compiler.
@@ -62,6 +71,7 @@ def flatbuffer_library_public(
for, instead of default-supported environments.
target_compatible_with: Optional, The list of target platform constraints
to use.
flatc_path: Bazel target corresponding to the flatc compiler to use.
output_to_bindir: Passed to genrule for output to bin directory.
@@ -69,6 +79,8 @@ def flatbuffer_library_public(
optionally a Fileset([reflection_name]) with all generated reflection
binaries.
"""
if include_paths == None:
include_paths = default_include_paths(flatc_path)
include_paths_cmd = ["-I %s" % (s) for s in include_paths]
# '$(@D)' when given a single source target will give the appropriate
@@ -80,7 +92,7 @@ def flatbuffer_library_public(
genrule_cmd = " ".join([
"SRCS=($(SRCS));",
"for f in $${SRCS[@]:0:%s}; do" % len(srcs),
"$(location %s)" % (flatc_path),
"OUTPUT_FILE=\"$(OUTS)\" $(location %s)" % (flatc_path),
" ".join(include_paths_cmd),
" ".join(flatc_args),
language_flag,
@@ -104,7 +116,7 @@ def flatbuffer_library_public(
reflection_genrule_cmd = " ".join([
"SRCS=($(SRCS));",
"for f in $${SRCS[@]:0:%s}; do" % len(srcs),
"$(location %s)" % (flatc_path),
"$(location %s)" % (TRUE_FLATC_PATH),
"-b --schema",
" ".join(flatc_args),
" ".join(include_paths_cmd),
@@ -122,7 +134,7 @@ def flatbuffer_library_public(
srcs = srcs + includes,
outs = reflection_outs,
output_to_bindir = output_to_bindir,
tools = [flatc_path],
tools = [TRUE_FLATC_PATH],
compatible_with = compatible_with,
restricted_to = restricted_to,
target_compatible_with = target_compatible_with,
@@ -145,7 +157,7 @@ def flatbuffer_cc_library(
out_prefix = "",
deps = [],
includes = [],
include_paths = DEFAULT_INCLUDE_PATHS,
include_paths = None,
cc_include_paths = [],
flatc_args = DEFAULT_FLATC_ARGS,
visibility = None,

View File

@@ -1,5 +1,5 @@
name: flat_buffers
version: 23.1.20
version: 23.3.3
description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team.
homepage: https://github.com/google/flatbuffers
documentation: https://google.github.io/flatbuffers/index.html

View File

@@ -321,9 +321,8 @@ Please be aware of the difference between `flatc` and `flatcc` tools.
<div class="language-javascript">
~~~{.sh}
cd flatbuffers/samples
./../flatc --ts monster.fbs
# customize your TS -> JS transpilation
tsc monster_generated.ts
./../flatc --ts-flat-files --ts monster.fbs
# produces ts/js modules and js bundle monster_generated.js
~~~
</div>
<div class="language-typescript">
@@ -2241,7 +2240,7 @@ before:
~~~{.ts}
// note: import flatbuffers with your desired import method
// note: the `./monster_generated.ts` file was previously generated by `flatc` above using the `monster.fbs` schema
// note: the `./monster_generated.js` file was previously generated by `flatc` above using the `monster.fbs` schema
import { MyGame } from './monster_generated';
~~~
</div>

View File

@@ -6,7 +6,7 @@ import FlatBuffers
public struct models_HelloReply: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_1_20() }
static func validateVersion() { FlatBuffersVersion_23_3_3() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
@@ -53,7 +53,7 @@ extension models_HelloReply: Encodable {
public struct models_HelloRequest: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_1_20() }
static func validateVersion() { FlatBuffersVersion_23_3_3() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table

View File

@@ -1,2 +1,3 @@
export { HelloReply } from './models/hello-reply';
export { HelloRequest } from './models/hello-request';
// automatically generated by the FlatBuffers compiler, do not modify
export * as models from './models.js';

View File

@@ -0,0 +1,4 @@
// automatically generated by the FlatBuffers compiler, do not modify
export { HelloReply } from './models/hello-reply.js';
export { HelloRequest } from './models/hello-request.js';

View File

@@ -139,8 +139,8 @@
#endif // !defined(FLATBUFFERS_LITTLEENDIAN)
#define FLATBUFFERS_VERSION_MAJOR 23
#define FLATBUFFERS_VERSION_MINOR 1
#define FLATBUFFERS_VERSION_REVISION 20
#define FLATBUFFERS_VERSION_MINOR 3
#define FLATBUFFERS_VERSION_REVISION 3
#define FLATBUFFERS_STRING_EXPAND(X) #X
#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
namespace flatbuffers {
@@ -233,7 +233,7 @@ namespace flatbuffers {
}
#define FLATBUFFERS_HAS_STRING_VIEW 1
// Check for absl::string_view
#elif __has_include("absl/strings/string_view.h")
#elif __has_include("absl/strings/string_view.h") && (__cplusplus >= 201411)
#include "absl/strings/string_view.h"
namespace flatbuffers {
typedef absl::string_view string_view;

View File

@@ -23,7 +23,7 @@
namespace flatbuffers {
// An code generator interface for producing converting flatbuffer schema into
// A code generator interface for producing converting flatbuffer schema into
// code.
class CodeGenerator {
public:
@@ -32,7 +32,8 @@ class CodeGenerator {
enum Status {
OK = 0,
ERROR = 1,
NOT_IMPLEMENTED = 2,
FAILED_VERIFICATION = 2,
NOT_IMPLEMENTED = 3
};
// Generate code from the provided `parser`.
@@ -52,11 +53,17 @@ class CodeGenerator {
virtual Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) = 0;
virtual Status GenerateRootFile(const Parser &parser,
const std::string &path) = 0;
virtual bool IsSchemaOnly() const = 0;
virtual bool SupportsBfbsGeneration() const = 0;
virtual bool SupportsRootFileGeneration() const = 0;
virtual IDLOptions::Language Language() const = 0;
virtual std::string LanguageName() const = 0;
protected:

View File

@@ -23,7 +23,6 @@
#include <memory>
#include <string>
#include "flatbuffers/bfbs_generator.h"
#include "flatbuffers/code_generator.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
@@ -31,10 +30,6 @@
namespace flatbuffers {
// TODO(derekbailey): It would be better to define these as normal includes and
// not as extern functions. But this can be done at a later time.
extern std::unique_ptr<flatbuffers::CodeGenerator> NewCppCodeGenerator();
extern void LogCompilerWarn(const std::string &warn);
extern void LogCompilerError(const std::string &err);
@@ -54,6 +49,7 @@ struct FlatCOptions {
size_t binary_files_from = std::numeric_limits<size_t>::max();
std::string conform_to_schema;
std::string annotate_schema;
bool annotate_include_vector_contents = true;
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
@@ -73,29 +69,6 @@ struct FlatCOption {
class FlatCompiler {
public:
// Output generator for the various programming languages and formats we
// support.
struct Generator {
typedef bool (*GenerateFn)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
typedef std::string (*MakeRuleFn)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
typedef bool (*ParsingCompletedFn)(const flatbuffers::Parser &parser,
const std::string &output_path);
GenerateFn generate;
const char *lang_name;
bool schema_only;
GenerateFn generateGRPC;
flatbuffers::IDLOptions::Language lang;
FlatCOption option;
MakeRuleFn make_rule;
BfbsGenerator *bfbs_generator;
ParsingCompletedFn parsing_completed;
};
typedef void (*WarnFn)(const FlatCompiler *flatc, const std::string &warn,
bool show_exe_name);
@@ -104,21 +77,15 @@ class FlatCompiler {
// Parameters required to initialize the FlatCompiler.
struct InitParams {
InitParams()
: generators(nullptr),
num_generators(0),
warn_fn(nullptr),
error_fn(nullptr) {}
InitParams() : warn_fn(nullptr), error_fn(nullptr) {}
const Generator *generators;
size_t num_generators;
WarnFn warn_fn;
ErrorFn error_fn;
};
explicit FlatCompiler(const InitParams &params) : params_(params) {}
bool RegisterCodeGenerator(const std::string& flag,
bool RegisterCodeGenerator(const FlatCOption &option,
std::shared_ptr<CodeGenerator> code_generator);
int Compile(const FlatCOptions &options);
@@ -144,8 +111,7 @@ class FlatCompiler {
void AnnotateBinaries(const uint8_t *binary_schema,
uint64_t binary_schema_size,
const std::string &schema_filename,
const std::vector<std::string> &binary_files);
const FlatCOptions &options);
void ValidateOptions(const FlatCOptions &options);

View File

@@ -45,26 +45,26 @@ namespace flatbuffers {
// of type tokens.
// clang-format off
#define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
TD(NONE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) \
TD(UTYPE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) /* begin scalar/int */ \
TD(BOOL, "bool", uint8_t, boolean,bool, bool, bool, bool, Boolean, Bool) \
TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8, i8, Byte, Int8) \
TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) \
TD(SHORT, "short", int16_t, short, int16, short, int16, i16, Short, Int16) \
TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16, u16, UShort, UInt16) \
TD(INT, "int", int32_t, int, int32, int, int32, i32, Int, Int32) \
TD(UINT, "uint", uint32_t, int, uint32, uint, uint32, u32, UInt, UInt32) \
TD(LONG, "long", int64_t, long, int64, long, int64, i64, Long, Int64) \
TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64, u64, ULong, UInt64) /* end int */ \
TD(FLOAT, "float", float, float, float32, float, float32, f32, Float, Float32) /* begin float */ \
TD(DOUBLE, "double", double, double, float64, double, float64, f64, Double, Double) /* end float/scalar */
TD(NONE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 0) \
TD(UTYPE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 1) /* begin scalar/int */ \
TD(BOOL, "bool", uint8_t, boolean,bool, bool, bool, bool, Boolean, Bool, 2) \
TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8, i8, Byte, Int8, 3) \
TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 4) \
TD(SHORT, "short", int16_t, short, int16, short, int16, i16, Short, Int16, 5) \
TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16, u16, UShort, UInt16, 6) \
TD(INT, "int", int32_t, int, int32, int, int32, i32, Int, Int32, 7) \
TD(UINT, "uint", uint32_t, int, uint32, uint, uint32, u32, UInt, UInt32, 8) \
TD(LONG, "long", int64_t, long, int64, long, int64, i64, Long, Int64, 9) \
TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64, u64, ULong, UInt64, 10) /* end int */ \
TD(FLOAT, "float", float, float, float32, float, float32, f32, Float, Float32, 11) /* begin float */ \
TD(DOUBLE, "double", double, double, float64, double, float64, f64, Double, Double, 12) /* end float/scalar */
#define FLATBUFFERS_GEN_TYPES_POINTER(TD) \
TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused, Int, Offset<String>) \
TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int, unused, Int, Offset<UOffset>) \
TD(STRUCT, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>) \
TD(UNION, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>)
TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused, Int, Offset<String>, 13) \
TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int, unused, Int, Offset<UOffset>, 14) \
TD(STRUCT, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>, 15) \
TD(UNION, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>, 16)
#define FLATBUFFERS_GEN_TYPE_ARRAY(TD) \
TD(ARRAY, "", int, int, int, int, int, unused, Int, Offset<UOffset>)
TD(ARRAY, "", int, int, int, int, int, unused, Int, Offset<UOffset>, 17)
// The fields are:
// - enum
// - FlatBuffers schema type.
@@ -75,13 +75,15 @@ namespace flatbuffers {
// - Python type.
// - Kotlin type.
// - Rust type.
// - Swift type.
// - enum value (matches the reflected values)
// using these macros, we can now write code dealing with types just once, e.g.
/*
switch (type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
RTYPE, KTYPE) \
RTYPE, KTYPE, STYPE, ...) \
case BASE_TYPE_ ## ENUM: \
// do something specific to CTYPE here
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
@@ -113,8 +115,9 @@ switch (type) {
__extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
#endif
enum BaseType {
#define FLATBUFFERS_TD(ENUM, ...) \
BASE_TYPE_ ## ENUM,
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE, STYPE, ENUM_VALUE) \
BASE_TYPE_ ## ENUM = ENUM_VALUE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
@@ -143,13 +146,41 @@ inline bool IsUnsigned(BaseType t) {
(t == BASE_TYPE_ULONG);
}
inline size_t SizeOf(const BaseType t) {
switch (t) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
case BASE_TYPE_##ENUM: return sizeof(CTYPE);
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
default: FLATBUFFERS_ASSERT(0);
}
return 0;
}
inline const char* TypeName(const BaseType t) {
switch (t) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, ...) \
case BASE_TYPE_##ENUM: return IDLTYPE;
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
default: FLATBUFFERS_ASSERT(0);
}
return nullptr;
}
inline const char* StringOf(const BaseType t) {
switch (t) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
case BASE_TYPE_##ENUM: return #CTYPE;
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
default: FLATBUFFERS_ASSERT(0);
}
return "";
}
// clang-format on
extern const char *const kTypeNames[];
extern const char kTypeSizes[];
inline size_t SizeOf(BaseType t) { return kTypeSizes[t]; }
struct StructDef;
struct EnumDef;
class Parser;
@@ -381,6 +412,7 @@ struct StructDef : public Definition {
size_t bytesize; // Size if fixed.
flatbuffers::unique_ptr<std::string> original_location;
std::vector<voffset_t> reserved_ids;
};
struct EnumDef;
@@ -594,7 +626,7 @@ inline bool operator<(const IncludedFile &a, const IncludedFile &b) {
struct IDLOptions {
// field case style options for C++
enum CaseStyle { CaseStyle_Unchanged = 0, CaseStyle_Upper, CaseStyle_Lower };
enum class ProtoIdGapAction { NO_OP, WARNING, ERROR };
bool gen_jvmstatic;
// Use flexbuffers instead for binary and text generation
bool use_flexbuffers;
@@ -623,6 +655,7 @@ struct IDLOptions {
CaseStyle cpp_object_api_field_case_style;
bool cpp_direct_copy;
bool gen_nullable;
std::string java_package_prefix;
bool java_checkerframework;
bool gen_generated;
bool gen_json_coders;
@@ -658,10 +691,13 @@ struct IDLOptions {
bool json_nested_flatbuffers;
bool json_nested_flexbuffers;
bool json_nested_legacy_flatbuffers;
bool ts_flat_file;
bool ts_flat_files;
bool ts_entry_points;
bool ts_no_import_ext;
bool no_leak_private_annotations;
bool require_json_eof;
bool keep_proto_id;
ProtoIdGapAction proto_id_gap_action;
// Possible options for the more general generator below.
enum Language {
@@ -682,6 +718,7 @@ struct IDLOptions {
kKotlin = 1 << 15,
kSwift = 1 << 16,
kNim = 1 << 17,
kProto = 1 << 18,
kMAX
};
@@ -763,10 +800,13 @@ struct IDLOptions {
json_nested_flatbuffers(true),
json_nested_flexbuffers(true),
json_nested_legacy_flatbuffers(false),
ts_flat_file(false),
ts_flat_files(false),
ts_entry_points(false),
ts_no_import_ext(false),
no_leak_private_annotations(false),
require_json_eof(true),
keep_proto_id(false),
proto_id_gap_action(ProtoIdGapAction::WARNING),
mini_reflect(IDLOptions::kNone),
require_explicit_ids(false),
rust_serialize(false),

View File

@@ -9,8 +9,8 @@
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 1 &&
FLATBUFFERS_VERSION_REVISION == 20,
FLATBUFFERS_VERSION_MINOR == 3 &&
FLATBUFFERS_VERSION_REVISION == 3,
"Non-compatible flatbuffers version included");
namespace reflection {

View File

@@ -41,15 +41,18 @@
#include <optional>
#endif
// The __cpp_lib_span is the predefined feature macro.
#if defined(FLATBUFFERS_USE_STD_SPAN)
#include <span>
#elif defined(__cpp_lib_span) && defined(__has_include)
#if __has_include(<span>)
#include <array>
#include <span>
#define FLATBUFFERS_USE_STD_SPAN
#ifndef FLATBUFFERS_USE_STD_SPAN
// Testing __cpp_lib_span requires including either <version> or <span>,
// both of which were added in C++20.
// See: https://en.cppreference.com/w/cpp/utility/feature_test
#if defined(__cplusplus) && __cplusplus >= 202002L
#define FLATBUFFERS_USE_STD_SPAN 1
#endif
#endif // FLATBUFFERS_USE_STD_SPAN
#if defined(FLATBUFFERS_USE_STD_SPAN)
#include <array>
#include <span>
#else
// Disable non-trivial ctors if FLATBUFFERS_SPAN_MINIMAL defined.
#if !defined(FLATBUFFERS_TEMPLATES_ALIASES)

View File

@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-java</artifactId>
<version>23.1.4</version>
<version>23.3.3</version>
<packaging>bundle</packaging>
<name>FlatBuffers Java API</name>
<description>
@@ -25,7 +25,7 @@
<licenses>
<license>
<name>Apache License V2.0</name>
<url>https://raw.githubusercontent.com/google/flatbuffers/master/LICENSE.txt</url>
<url>https://raw.githubusercontent.com/google/flatbuffers/master/LICENSE</url>
<distribution>repo</distribution>
</license>
</licenses>

View File

@@ -46,7 +46,7 @@ public class Constants {
Changes to the Java implementation need to be sure to change
the version here and in the code generator on every possible
incompatible change */
public static void FLATBUFFERS_23_1_20() {}
public static void FLATBUFFERS_23_3_3() {}
}
/// @endcond

View File

@@ -0,0 +1,16 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
/**
* New schema language features that are not supported by old code generators.
*/
@SuppressWarnings("unused")
public final class AdvancedFeatures {
private AdvancedFeatures() { }
public static final long AdvancedArrayFeatures = 1L;
public static final long AdvancedUnionFeatures = 2L;
public static final long OptionalScalars = 4L;
public static final long DefaultVectorsAndStrings = 8L;
}

View File

@@ -0,0 +1,32 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
@SuppressWarnings("unused")
public final class BaseType {
private BaseType() { }
public static final byte None = 0;
public static final byte UType = 1;
public static final byte Bool = 2;
public static final byte Byte = 3;
public static final byte UByte = 4;
public static final byte Short = 5;
public static final byte UShort = 6;
public static final byte Int = 7;
public static final byte UInt = 8;
public static final byte Long = 9;
public static final byte ULong = 10;
public static final byte Float = 11;
public static final byte Double = 12;
public static final byte String = 13;
public static final byte Vector = 14;
public static final byte Obj = 15;
public static final byte Union = 16;
public static final byte Array = 17;
public static final byte MaxBaseType = 18;
public static final String[] names = { "None", "UType", "Bool", "Byte", "UByte", "Short", "UShort", "Int", "UInt", "Long", "ULong", "Float", "Double", "String", "Vector", "Obj", "Union", "Array", "MaxBaseType", };
public static String name(int e) { return names[e]; }
}

View File

@@ -0,0 +1,135 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class Enum extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static Enum getRootAsEnum(ByteBuffer _bb) { return getRootAsEnum(_bb, new Enum()); }
public static Enum getRootAsEnum(ByteBuffer _bb, Enum obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Enum __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public com.google.flatbuffers.reflection.EnumVal values(int j) { return values(new com.google.flatbuffers.reflection.EnumVal(), j); }
public com.google.flatbuffers.reflection.EnumVal values(com.google.flatbuffers.reflection.EnumVal obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int valuesLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.EnumVal valuesByKey(long key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.EnumVal.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.EnumVal valuesByKey(com.google.flatbuffers.reflection.EnumVal obj, long key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.EnumVal.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.EnumVal.Vector valuesVector() { return valuesVector(new com.google.flatbuffers.reflection.EnumVal.Vector()); }
public com.google.flatbuffers.reflection.EnumVal.Vector valuesVector(com.google.flatbuffers.reflection.EnumVal.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public boolean isUnion() { int o = __offset(8); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
public com.google.flatbuffers.reflection.Type underlyingType() { return underlyingType(new com.google.flatbuffers.reflection.Type()); }
public com.google.flatbuffers.reflection.Type underlyingType(com.google.flatbuffers.reflection.Type obj) { int o = __offset(10); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); }
public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(12); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int attributesLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(12); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(12); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public String documentation(int j) { int o = __offset(14); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int documentationLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; }
public StringVector documentationVector() { return documentationVector(new StringVector()); }
public StringVector documentationVector(StringVector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
/**
* File that this Enum is declared in.
*/
public String declarationFile() { int o = __offset(16); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer declarationFileAsByteBuffer() { return __vector_as_bytebuffer(16, 1); }
public ByteBuffer declarationFileInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 16, 1); }
public static int createEnum(FlatBufferBuilder builder,
int nameOffset,
int valuesOffset,
boolean isUnion,
int underlyingTypeOffset,
int attributesOffset,
int documentationOffset,
int declarationFileOffset) {
builder.startTable(7);
Enum.addDeclarationFile(builder, declarationFileOffset);
Enum.addDocumentation(builder, documentationOffset);
Enum.addAttributes(builder, attributesOffset);
Enum.addUnderlyingType(builder, underlyingTypeOffset);
Enum.addValues(builder, valuesOffset);
Enum.addName(builder, nameOffset);
Enum.addIsUnion(builder, isUnion);
return Enum.endEnum(builder);
}
public static void startEnum(FlatBufferBuilder builder) { builder.startTable(7); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); }
public static void addValues(FlatBufferBuilder builder, int valuesOffset) { builder.addOffset(1, valuesOffset, 0); }
public static int createValuesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startValuesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addIsUnion(FlatBufferBuilder builder, boolean isUnion) { builder.addBoolean(2, isUnion, false); }
public static void addUnderlyingType(FlatBufferBuilder builder, int underlyingTypeOffset) { builder.addOffset(3, underlyingTypeOffset, 0); }
public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(4, attributesOffset, 0); }
public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(5, documentationOffset, 0); }
public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addDeclarationFile(FlatBufferBuilder builder, int declarationFileOffset) { builder.addOffset(6, declarationFileOffset, 0); }
public static int endEnum(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // name
builder.required(o, 6); // values
builder.required(o, 10); // underlying_type
return o;
}
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); }
public static Enum __lookup_by_key(Enum obj, int vectorLocation, String key, ByteBuffer bb) {
byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8);
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb);
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return (obj == null ? new Enum() : obj).__assign(tableOffset, bb);
}
}
return null;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Enum get(int j) { return get(new Enum(), j); }
public Enum get(Enum obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
public Enum getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); }
public Enum getByKey(Enum obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
}

View File

@@ -0,0 +1,116 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class EnumVal extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static EnumVal getRootAsEnumVal(ByteBuffer _bb) { return getRootAsEnumVal(_bb, new EnumVal()); }
public static EnumVal getRootAsEnumVal(ByteBuffer _bb, EnumVal obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public EnumVal __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public long value() { int o = __offset(6); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public com.google.flatbuffers.reflection.Type unionType() { return unionType(new com.google.flatbuffers.reflection.Type()); }
public com.google.flatbuffers.reflection.Type unionType(com.google.flatbuffers.reflection.Type obj) { int o = __offset(10); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public String documentation(int j) { int o = __offset(12); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int documentationLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; }
public StringVector documentationVector() { return documentationVector(new StringVector()); }
public StringVector documentationVector(StringVector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); }
public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(14); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int attributesLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public static int createEnumVal(FlatBufferBuilder builder,
int nameOffset,
long value,
int unionTypeOffset,
int documentationOffset,
int attributesOffset) {
builder.startTable(6);
EnumVal.addValue(builder, value);
EnumVal.addAttributes(builder, attributesOffset);
EnumVal.addDocumentation(builder, documentationOffset);
EnumVal.addUnionType(builder, unionTypeOffset);
EnumVal.addName(builder, nameOffset);
return EnumVal.endEnumVal(builder);
}
public static void startEnumVal(FlatBufferBuilder builder) { builder.startTable(6); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(0, nameOffset, 0); }
public static void addValue(FlatBufferBuilder builder, long value) { builder.addLong(value); builder.slot(1); }
public static void addUnionType(FlatBufferBuilder builder, int unionTypeOffset) { builder.addOffset(3, unionTypeOffset, 0); }
public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(4, documentationOffset, 0); }
public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(5, attributesOffset, 0); }
public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static int endEnumVal(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // name
return o;
}
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) {
long val_1 = _bb.getLong(__offset(6, o1, _bb));
long val_2 = _bb.getLong(__offset(6, o2, _bb));
return val_1 > val_2 ? 1 : val_1 < val_2 ? -1 : 0;
}
public static EnumVal __lookup_by_key(EnumVal obj, int vectorLocation, long key, ByteBuffer bb) {
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
long val = bb.getLong(__offset(6, bb.capacity() - tableOffset, bb));
int comp = val > key ? 1 : val < key ? -1 : 0;
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return (obj == null ? new EnumVal() : obj).__assign(tableOffset, bb);
}
}
return null;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public EnumVal get(int j) { return get(new EnumVal(), j); }
public EnumVal get(EnumVal obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
public EnumVal getByKey(long key) { return __lookup_by_key(null, __vector(), key, bb); }
public EnumVal getByKey(EnumVal obj, long key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
}

View File

@@ -0,0 +1,148 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class Field extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static Field getRootAsField(ByteBuffer _bb) { return getRootAsField(_bb, new Field()); }
public static Field getRootAsField(ByteBuffer _bb, Field obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Field __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public com.google.flatbuffers.reflection.Type type() { return type(new com.google.flatbuffers.reflection.Type()); }
public com.google.flatbuffers.reflection.Type type(com.google.flatbuffers.reflection.Type obj) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public int id() { int o = __offset(8); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; }
public int offset() { int o = __offset(10); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; }
public long defaultInteger() { int o = __offset(12); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public double defaultReal() { int o = __offset(14); return o != 0 ? bb.getDouble(o + bb_pos) : 0.0; }
public boolean deprecated() { int o = __offset(16); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
public boolean required() { int o = __offset(18); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
public boolean key() { int o = __offset(20); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); }
public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(22); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int attributesLength() { int o = __offset(22); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(22); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(22); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(22); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public String documentation(int j) { int o = __offset(24); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int documentationLength() { int o = __offset(24); return o != 0 ? __vector_len(o) : 0; }
public StringVector documentationVector() { return documentationVector(new StringVector()); }
public StringVector documentationVector(StringVector obj) { int o = __offset(24); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public boolean optional() { int o = __offset(26); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
/**
* Number of padding octets to always add after this field. Structs only.
*/
public int padding() { int o = __offset(28); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; }
public static int createField(FlatBufferBuilder builder,
int nameOffset,
int typeOffset,
int id,
int offset,
long defaultInteger,
double defaultReal,
boolean deprecated,
boolean required,
boolean key,
int attributesOffset,
int documentationOffset,
boolean optional,
int padding) {
builder.startTable(13);
Field.addDefaultReal(builder, defaultReal);
Field.addDefaultInteger(builder, defaultInteger);
Field.addDocumentation(builder, documentationOffset);
Field.addAttributes(builder, attributesOffset);
Field.addType(builder, typeOffset);
Field.addName(builder, nameOffset);
Field.addPadding(builder, padding);
Field.addOffset(builder, offset);
Field.addId(builder, id);
Field.addOptional(builder, optional);
Field.addKey(builder, key);
Field.addRequired(builder, required);
Field.addDeprecated(builder, deprecated);
return Field.endField(builder);
}
public static void startField(FlatBufferBuilder builder) { builder.startTable(13); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); }
public static void addType(FlatBufferBuilder builder, int typeOffset) { builder.addOffset(1, typeOffset, 0); }
public static void addId(FlatBufferBuilder builder, int id) { builder.addShort(2, (short) id, (short) 0); }
public static void addOffset(FlatBufferBuilder builder, int offset) { builder.addShort(3, (short) offset, (short) 0); }
public static void addDefaultInteger(FlatBufferBuilder builder, long defaultInteger) { builder.addLong(4, defaultInteger, 0L); }
public static void addDefaultReal(FlatBufferBuilder builder, double defaultReal) { builder.addDouble(5, defaultReal, 0.0); }
public static void addDeprecated(FlatBufferBuilder builder, boolean deprecated) { builder.addBoolean(6, deprecated, false); }
public static void addRequired(FlatBufferBuilder builder, boolean required) { builder.addBoolean(7, required, false); }
public static void addKey(FlatBufferBuilder builder, boolean key) { builder.addBoolean(8, key, false); }
public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(9, attributesOffset, 0); }
public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(10, documentationOffset, 0); }
public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addOptional(FlatBufferBuilder builder, boolean optional) { builder.addBoolean(11, optional, false); }
public static void addPadding(FlatBufferBuilder builder, int padding) { builder.addShort(12, (short) padding, (short) 0); }
public static int endField(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // name
builder.required(o, 6); // type
return o;
}
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); }
public static Field __lookup_by_key(Field obj, int vectorLocation, String key, ByteBuffer bb) {
byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8);
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb);
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return (obj == null ? new Field() : obj).__assign(tableOffset, bb);
}
}
return null;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Field get(int j) { return get(new Field(), j); }
public Field get(Field obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
public Field getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); }
public Field getByKey(Field obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
}

View File

@@ -0,0 +1,88 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class KeyValue extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static KeyValue getRootAsKeyValue(ByteBuffer _bb) { return getRootAsKeyValue(_bb, new KeyValue()); }
public static KeyValue getRootAsKeyValue(ByteBuffer _bb, KeyValue obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public KeyValue __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public String key() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer keyAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer keyInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public String value() { int o = __offset(6); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer valueAsByteBuffer() { return __vector_as_bytebuffer(6, 1); }
public ByteBuffer valueInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 6, 1); }
public static int createKeyValue(FlatBufferBuilder builder,
int keyOffset,
int valueOffset) {
builder.startTable(2);
KeyValue.addValue(builder, valueOffset);
KeyValue.addKey(builder, keyOffset);
return KeyValue.endKeyValue(builder);
}
public static void startKeyValue(FlatBufferBuilder builder) { builder.startTable(2); }
public static void addKey(FlatBufferBuilder builder, int keyOffset) { builder.addOffset(keyOffset); builder.slot(0); }
public static void addValue(FlatBufferBuilder builder, int valueOffset) { builder.addOffset(1, valueOffset, 0); }
public static int endKeyValue(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // key
return o;
}
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); }
public static KeyValue __lookup_by_key(KeyValue obj, int vectorLocation, String key, ByteBuffer bb) {
byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8);
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb);
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return (obj == null ? new KeyValue() : obj).__assign(tableOffset, bb);
}
}
return null;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public KeyValue get(int j) { return get(new KeyValue(), j); }
public KeyValue get(KeyValue obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
public KeyValue getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); }
public KeyValue getByKey(KeyValue obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
}

View File

@@ -0,0 +1,137 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class Object extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static Object getRootAsObject(ByteBuffer _bb) { return getRootAsObject(_bb, new Object()); }
public static Object getRootAsObject(ByteBuffer _bb, Object obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Object __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public com.google.flatbuffers.reflection.Field fields(int j) { return fields(new com.google.flatbuffers.reflection.Field(), j); }
public com.google.flatbuffers.reflection.Field fields(com.google.flatbuffers.reflection.Field obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int fieldsLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.Field fieldsByKey(String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.Field.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.Field fieldsByKey(com.google.flatbuffers.reflection.Field obj, String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.Field.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.Field.Vector fieldsVector() { return fieldsVector(new com.google.flatbuffers.reflection.Field.Vector()); }
public com.google.flatbuffers.reflection.Field.Vector fieldsVector(com.google.flatbuffers.reflection.Field.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public boolean isStruct() { int o = __offset(8); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
public int minalign() { int o = __offset(10); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
public int bytesize() { int o = __offset(12); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); }
public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(14); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int attributesLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public String documentation(int j) { int o = __offset(16); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int documentationLength() { int o = __offset(16); return o != 0 ? __vector_len(o) : 0; }
public StringVector documentationVector() { return documentationVector(new StringVector()); }
public StringVector documentationVector(StringVector obj) { int o = __offset(16); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
/**
* File that this Object is declared in.
*/
public String declarationFile() { int o = __offset(18); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer declarationFileAsByteBuffer() { return __vector_as_bytebuffer(18, 1); }
public ByteBuffer declarationFileInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 18, 1); }
public static int createObject(FlatBufferBuilder builder,
int nameOffset,
int fieldsOffset,
boolean isStruct,
int minalign,
int bytesize,
int attributesOffset,
int documentationOffset,
int declarationFileOffset) {
builder.startTable(8);
Object.addDeclarationFile(builder, declarationFileOffset);
Object.addDocumentation(builder, documentationOffset);
Object.addAttributes(builder, attributesOffset);
Object.addBytesize(builder, bytesize);
Object.addMinalign(builder, minalign);
Object.addFields(builder, fieldsOffset);
Object.addName(builder, nameOffset);
Object.addIsStruct(builder, isStruct);
return Object.endObject(builder);
}
public static void startObject(FlatBufferBuilder builder) { builder.startTable(8); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); }
public static void addFields(FlatBufferBuilder builder, int fieldsOffset) { builder.addOffset(1, fieldsOffset, 0); }
public static int createFieldsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startFieldsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addIsStruct(FlatBufferBuilder builder, boolean isStruct) { builder.addBoolean(2, isStruct, false); }
public static void addMinalign(FlatBufferBuilder builder, int minalign) { builder.addInt(3, minalign, 0); }
public static void addBytesize(FlatBufferBuilder builder, int bytesize) { builder.addInt(4, bytesize, 0); }
public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(5, attributesOffset, 0); }
public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(6, documentationOffset, 0); }
public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addDeclarationFile(FlatBufferBuilder builder, int declarationFileOffset) { builder.addOffset(7, declarationFileOffset, 0); }
public static int endObject(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // name
builder.required(o, 6); // fields
return o;
}
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); }
public static Object __lookup_by_key(Object obj, int vectorLocation, String key, ByteBuffer bb) {
byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8);
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb);
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return (obj == null ? new Object() : obj).__assign(tableOffset, bb);
}
}
return null;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Object get(int j) { return get(new Object(), j); }
public Object get(Object obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
public Object getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); }
public Object getByKey(Object obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
}

View File

@@ -0,0 +1,115 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class RPCCall extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static RPCCall getRootAsRPCCall(ByteBuffer _bb) { return getRootAsRPCCall(_bb, new RPCCall()); }
public static RPCCall getRootAsRPCCall(ByteBuffer _bb, RPCCall obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public RPCCall __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public com.google.flatbuffers.reflection.Object request() { return request(new com.google.flatbuffers.reflection.Object()); }
public com.google.flatbuffers.reflection.Object request(com.google.flatbuffers.reflection.Object obj) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public com.google.flatbuffers.reflection.Object response() { return response(new com.google.flatbuffers.reflection.Object()); }
public com.google.flatbuffers.reflection.Object response(com.google.flatbuffers.reflection.Object obj) { int o = __offset(8); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); }
public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(10); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int attributesLength() { int o = __offset(10); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(10); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(10); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(10); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public String documentation(int j) { int o = __offset(12); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int documentationLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; }
public StringVector documentationVector() { return documentationVector(new StringVector()); }
public StringVector documentationVector(StringVector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public static int createRPCCall(FlatBufferBuilder builder,
int nameOffset,
int requestOffset,
int responseOffset,
int attributesOffset,
int documentationOffset) {
builder.startTable(5);
RPCCall.addDocumentation(builder, documentationOffset);
RPCCall.addAttributes(builder, attributesOffset);
RPCCall.addResponse(builder, responseOffset);
RPCCall.addRequest(builder, requestOffset);
RPCCall.addName(builder, nameOffset);
return RPCCall.endRPCCall(builder);
}
public static void startRPCCall(FlatBufferBuilder builder) { builder.startTable(5); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); }
public static void addRequest(FlatBufferBuilder builder, int requestOffset) { builder.addOffset(1, requestOffset, 0); }
public static void addResponse(FlatBufferBuilder builder, int responseOffset) { builder.addOffset(2, responseOffset, 0); }
public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(3, attributesOffset, 0); }
public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(4, documentationOffset, 0); }
public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static int endRPCCall(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // name
builder.required(o, 6); // request
builder.required(o, 8); // response
return o;
}
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); }
public static RPCCall __lookup_by_key(RPCCall obj, int vectorLocation, String key, ByteBuffer bb) {
byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8);
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb);
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return (obj == null ? new RPCCall() : obj).__assign(tableOffset, bb);
}
}
return null;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public RPCCall get(int j) { return get(new RPCCall(), j); }
public RPCCall get(RPCCall obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
public RPCCall getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); }
public RPCCall getByKey(RPCCall obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
}

View File

@@ -0,0 +1,127 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class Schema extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static Schema getRootAsSchema(ByteBuffer _bb) { return getRootAsSchema(_bb, new Schema()); }
public static Schema getRootAsSchema(ByteBuffer _bb, Schema obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean SchemaBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "BFBS"); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Schema __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public com.google.flatbuffers.reflection.Object objects(int j) { return objects(new com.google.flatbuffers.reflection.Object(), j); }
public com.google.flatbuffers.reflection.Object objects(com.google.flatbuffers.reflection.Object obj, int j) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int objectsLength() { int o = __offset(4); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.Object objectsByKey(String key) { int o = __offset(4); return o != 0 ? com.google.flatbuffers.reflection.Object.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.Object objectsByKey(com.google.flatbuffers.reflection.Object obj, String key) { int o = __offset(4); return o != 0 ? com.google.flatbuffers.reflection.Object.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.Object.Vector objectsVector() { return objectsVector(new com.google.flatbuffers.reflection.Object.Vector()); }
public com.google.flatbuffers.reflection.Object.Vector objectsVector(com.google.flatbuffers.reflection.Object.Vector obj) { int o = __offset(4); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public com.google.flatbuffers.reflection.Enum enums(int j) { return enums(new com.google.flatbuffers.reflection.Enum(), j); }
public com.google.flatbuffers.reflection.Enum enums(com.google.flatbuffers.reflection.Enum obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int enumsLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.Enum enumsByKey(String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.Enum.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.Enum enumsByKey(com.google.flatbuffers.reflection.Enum obj, String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.Enum.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.Enum.Vector enumsVector() { return enumsVector(new com.google.flatbuffers.reflection.Enum.Vector()); }
public com.google.flatbuffers.reflection.Enum.Vector enumsVector(com.google.flatbuffers.reflection.Enum.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public String fileIdent() { int o = __offset(8); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer fileIdentAsByteBuffer() { return __vector_as_bytebuffer(8, 1); }
public ByteBuffer fileIdentInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 8, 1); }
public String fileExt() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer fileExtAsByteBuffer() { return __vector_as_bytebuffer(10, 1); }
public ByteBuffer fileExtInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 10, 1); }
public com.google.flatbuffers.reflection.Object rootTable() { return rootTable(new com.google.flatbuffers.reflection.Object()); }
public com.google.flatbuffers.reflection.Object rootTable(com.google.flatbuffers.reflection.Object obj) { int o = __offset(12); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public com.google.flatbuffers.reflection.Service services(int j) { return services(new com.google.flatbuffers.reflection.Service(), j); }
public com.google.flatbuffers.reflection.Service services(com.google.flatbuffers.reflection.Service obj, int j) { int o = __offset(14); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int servicesLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.Service servicesByKey(String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.Service.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.Service servicesByKey(com.google.flatbuffers.reflection.Service obj, String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.Service.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.Service.Vector servicesVector() { return servicesVector(new com.google.flatbuffers.reflection.Service.Vector()); }
public com.google.flatbuffers.reflection.Service.Vector servicesVector(com.google.flatbuffers.reflection.Service.Vector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public long advancedFeatures() { int o = __offset(16); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
/**
* All the files used in this compilation. Files are relative to where
* flatc was invoked.
*/
public com.google.flatbuffers.reflection.SchemaFile fbsFiles(int j) { return fbsFiles(new com.google.flatbuffers.reflection.SchemaFile(), j); }
public com.google.flatbuffers.reflection.SchemaFile fbsFiles(com.google.flatbuffers.reflection.SchemaFile obj, int j) { int o = __offset(18); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int fbsFilesLength() { int o = __offset(18); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.SchemaFile fbsFilesByKey(String key) { int o = __offset(18); return o != 0 ? com.google.flatbuffers.reflection.SchemaFile.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.SchemaFile fbsFilesByKey(com.google.flatbuffers.reflection.SchemaFile obj, String key) { int o = __offset(18); return o != 0 ? com.google.flatbuffers.reflection.SchemaFile.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.SchemaFile.Vector fbsFilesVector() { return fbsFilesVector(new com.google.flatbuffers.reflection.SchemaFile.Vector()); }
public com.google.flatbuffers.reflection.SchemaFile.Vector fbsFilesVector(com.google.flatbuffers.reflection.SchemaFile.Vector obj) { int o = __offset(18); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public static int createSchema(FlatBufferBuilder builder,
int objectsOffset,
int enumsOffset,
int fileIdentOffset,
int fileExtOffset,
int rootTableOffset,
int servicesOffset,
long advancedFeatures,
int fbsFilesOffset) {
builder.startTable(8);
Schema.addAdvancedFeatures(builder, advancedFeatures);
Schema.addFbsFiles(builder, fbsFilesOffset);
Schema.addServices(builder, servicesOffset);
Schema.addRootTable(builder, rootTableOffset);
Schema.addFileExt(builder, fileExtOffset);
Schema.addFileIdent(builder, fileIdentOffset);
Schema.addEnums(builder, enumsOffset);
Schema.addObjects(builder, objectsOffset);
return Schema.endSchema(builder);
}
public static void startSchema(FlatBufferBuilder builder) { builder.startTable(8); }
public static void addObjects(FlatBufferBuilder builder, int objectsOffset) { builder.addOffset(0, objectsOffset, 0); }
public static int createObjectsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startObjectsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addEnums(FlatBufferBuilder builder, int enumsOffset) { builder.addOffset(1, enumsOffset, 0); }
public static int createEnumsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startEnumsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addFileIdent(FlatBufferBuilder builder, int fileIdentOffset) { builder.addOffset(2, fileIdentOffset, 0); }
public static void addFileExt(FlatBufferBuilder builder, int fileExtOffset) { builder.addOffset(3, fileExtOffset, 0); }
public static void addRootTable(FlatBufferBuilder builder, int rootTableOffset) { builder.addOffset(4, rootTableOffset, 0); }
public static void addServices(FlatBufferBuilder builder, int servicesOffset) { builder.addOffset(5, servicesOffset, 0); }
public static int createServicesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startServicesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addAdvancedFeatures(FlatBufferBuilder builder, long advancedFeatures) { builder.addLong(6, advancedFeatures, 0L); }
public static void addFbsFiles(FlatBufferBuilder builder, int fbsFilesOffset) { builder.addOffset(7, fbsFilesOffset, 0); }
public static int createFbsFilesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startFbsFilesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static int endSchema(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // objects
builder.required(o, 6); // enums
return o;
}
public static void finishSchemaBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset, "BFBS"); }
public static void finishSizePrefixedSchemaBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset, "BFBS"); }
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Schema get(int j) { return get(new Schema(), j); }
public Schema get(Schema obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
}

View File

@@ -0,0 +1,102 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* File specific information.
* Symbols declared within a file may be recovered by iterating over all
* symbols and examining the `declaration_file` field.
*/
@SuppressWarnings("unused")
public final class SchemaFile extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static SchemaFile getRootAsSchemaFile(ByteBuffer _bb) { return getRootAsSchemaFile(_bb, new SchemaFile()); }
public static SchemaFile getRootAsSchemaFile(ByteBuffer _bb, SchemaFile obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public SchemaFile __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
/**
* Filename, relative to project root.
*/
public String filename() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer filenameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer filenameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
/**
* Names of included files, relative to project root.
*/
public String includedFilenames(int j) { int o = __offset(6); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int includedFilenamesLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; }
public StringVector includedFilenamesVector() { return includedFilenamesVector(new StringVector()); }
public StringVector includedFilenamesVector(StringVector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public static int createSchemaFile(FlatBufferBuilder builder,
int filenameOffset,
int includedFilenamesOffset) {
builder.startTable(2);
SchemaFile.addIncludedFilenames(builder, includedFilenamesOffset);
SchemaFile.addFilename(builder, filenameOffset);
return SchemaFile.endSchemaFile(builder);
}
public static void startSchemaFile(FlatBufferBuilder builder) { builder.startTable(2); }
public static void addFilename(FlatBufferBuilder builder, int filenameOffset) { builder.addOffset(filenameOffset); builder.slot(0); }
public static void addIncludedFilenames(FlatBufferBuilder builder, int includedFilenamesOffset) { builder.addOffset(1, includedFilenamesOffset, 0); }
public static int createIncludedFilenamesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startIncludedFilenamesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static int endSchemaFile(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // filename
return o;
}
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); }
public static SchemaFile __lookup_by_key(SchemaFile obj, int vectorLocation, String key, ByteBuffer bb) {
byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8);
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb);
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return (obj == null ? new SchemaFile() : obj).__assign(tableOffset, bb);
}
}
return null;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public SchemaFile get(int j) { return get(new SchemaFile(), j); }
public SchemaFile get(SchemaFile obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
public SchemaFile getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); }
public SchemaFile getByKey(SchemaFile obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
}

View File

@@ -0,0 +1,124 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class Service extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static Service getRootAsService(ByteBuffer _bb) { return getRootAsService(_bb, new Service()); }
public static Service getRootAsService(ByteBuffer _bb, Service obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Service __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public com.google.flatbuffers.reflection.RPCCall calls(int j) { return calls(new com.google.flatbuffers.reflection.RPCCall(), j); }
public com.google.flatbuffers.reflection.RPCCall calls(com.google.flatbuffers.reflection.RPCCall obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int callsLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.RPCCall callsByKey(String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.RPCCall.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.RPCCall callsByKey(com.google.flatbuffers.reflection.RPCCall obj, String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.RPCCall.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.RPCCall.Vector callsVector() { return callsVector(new com.google.flatbuffers.reflection.RPCCall.Vector()); }
public com.google.flatbuffers.reflection.RPCCall.Vector callsVector(com.google.flatbuffers.reflection.RPCCall.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); }
public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(8); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int attributesLength() { int o = __offset(8); return o != 0 ? __vector_len(o) : 0; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(8); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(8); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); }
public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(8); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public String documentation(int j) { int o = __offset(10); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int documentationLength() { int o = __offset(10); return o != 0 ? __vector_len(o) : 0; }
public StringVector documentationVector() { return documentationVector(new StringVector()); }
public StringVector documentationVector(StringVector obj) { int o = __offset(10); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
/**
* File that this Service is declared in.
*/
public String declarationFile() { int o = __offset(12); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer declarationFileAsByteBuffer() { return __vector_as_bytebuffer(12, 1); }
public ByteBuffer declarationFileInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 12, 1); }
public static int createService(FlatBufferBuilder builder,
int nameOffset,
int callsOffset,
int attributesOffset,
int documentationOffset,
int declarationFileOffset) {
builder.startTable(5);
Service.addDeclarationFile(builder, declarationFileOffset);
Service.addDocumentation(builder, documentationOffset);
Service.addAttributes(builder, attributesOffset);
Service.addCalls(builder, callsOffset);
Service.addName(builder, nameOffset);
return Service.endService(builder);
}
public static void startService(FlatBufferBuilder builder) { builder.startTable(5); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); }
public static void addCalls(FlatBufferBuilder builder, int callsOffset) { builder.addOffset(1, callsOffset, 0); }
public static int createCallsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startCallsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(2, attributesOffset, 0); }
public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(3, documentationOffset, 0); }
public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addDeclarationFile(FlatBufferBuilder builder, int declarationFileOffset) { builder.addOffset(4, declarationFileOffset, 0); }
public static int endService(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 4); // name
return o;
}
@Override
protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); }
public static Service __lookup_by_key(Service obj, int vectorLocation, String key, ByteBuffer bb) {
byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8);
int span = bb.getInt(vectorLocation - 4);
int start = 0;
while (span != 0) {
int middle = span / 2;
int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb);
if (comp > 0) {
span = middle;
} else if (comp < 0) {
middle++;
start += middle;
span -= middle;
} else {
return (obj == null ? new Service() : obj).__assign(tableOffset, bb);
}
}
return null;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Service get(int j) { return get(new Service(), j); }
public Service get(Service obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
public Service getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); }
public Service getByKey(Service obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
}

View File

@@ -0,0 +1,79 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.google.flatbuffers.reflection;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class Type extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_3_3(); }
public static Type getRootAsType(ByteBuffer _bb) { return getRootAsType(_bb, new Type()); }
public static Type getRootAsType(ByteBuffer _bb, Type obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Type __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public byte baseType() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) : 0; }
public byte element() { int o = __offset(6); return o != 0 ? bb.get(o + bb_pos) : 0; }
public int index() { int o = __offset(8); return o != 0 ? bb.getInt(o + bb_pos) : -1; }
public int fixedLength() { int o = __offset(10); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; }
/**
* The size (octets) of the `base_type` field.
*/
public long baseSize() { int o = __offset(12); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 4L; }
/**
* The size (octets) of the `element` field, if present.
*/
public long elementSize() { int o = __offset(14); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; }
public static int createType(FlatBufferBuilder builder,
byte baseType,
byte element,
int index,
int fixedLength,
long baseSize,
long elementSize) {
builder.startTable(6);
Type.addElementSize(builder, elementSize);
Type.addBaseSize(builder, baseSize);
Type.addIndex(builder, index);
Type.addFixedLength(builder, fixedLength);
Type.addElement(builder, element);
Type.addBaseType(builder, baseType);
return Type.endType(builder);
}
public static void startType(FlatBufferBuilder builder) { builder.startTable(6); }
public static void addBaseType(FlatBufferBuilder builder, byte baseType) { builder.addByte(0, baseType, 0); }
public static void addElement(FlatBufferBuilder builder, byte element) { builder.addByte(1, element, 0); }
public static void addIndex(FlatBufferBuilder builder, int index) { builder.addInt(2, index, -1); }
public static void addFixedLength(FlatBufferBuilder builder, int fixedLength) { builder.addShort(3, (short) fixedLength, (short) 0); }
public static void addBaseSize(FlatBufferBuilder builder, long baseSize) { builder.addInt(4, (int) baseSize, (int) 4L); }
public static void addElementSize(FlatBufferBuilder builder, long elementSize) { builder.addInt(5, (int) elementSize, (int) 0L); }
public static int endType(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Type get(int j) { return get(new Type(), j); }
public Type get(Type obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
}

View File

@@ -2,18 +2,11 @@ import org.jetbrains.kotlin.ir.backend.js.compile
plugins {
kotlin("multiplatform")
id("org.jetbrains.kotlin.plugin.allopen") version "1.4.20"
id("org.jetbrains.kotlinx.benchmark") version "0.4.2"
id("io.morethan.jmhreport") version "0.9.0"
id("org.jetbrains.kotlinx.benchmark")
id("io.morethan.jmhreport")
id("de.undercouch.download")
}
// allOpen plugin is needed for the benchmark annotations.
// for more information, see https://github.com/Kotlin/kotlinx-benchmark#gradle-plugin
allOpen {
annotation("org.openjdk.jmh.annotations.State")
}
group = "com.google.flatbuffers.jmh"
version = "2.0.0-SNAPSHOT"
@@ -34,7 +27,7 @@ benchmark {
iterationTime = 300
iterationTimeUnit = "ms"
// uncomment for benchmarking JSON op only
// include(".*JsonBenchmark.*")
include(".*JsonBenchmark.*")
}
}
targets {
@@ -43,9 +36,7 @@ benchmark {
}
kotlin {
jvm {
withJava()
}
jvm()
sourceSets {
@@ -58,7 +49,7 @@ kotlin {
implementation(kotlin("stdlib-common"))
implementation(project(":flatbuffers-kotlin"))
implementation(libs.kotlinx.benchmark.runtime)
implementation("com.google.flatbuffers:flatbuffers-java:2.0.3")
// json serializers
implementation(libs.moshi.kotlin)
implementation(libs.gson)

View File

@@ -14,7 +14,6 @@
* limitations under the License.
*/
package com.google.flatbuffers.kotlin.benchmark
import com.google.flatbuffers.ArrayReadWriteBuf
import com.google.flatbuffers.FlexBuffers
import com.google.flatbuffers.FlexBuffersBuilder.BUILDER_FLAG_SHARE_ALL
@@ -35,7 +34,7 @@ import java.util.concurrent.TimeUnit
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Measurement(iterations = 20, time = 1, timeUnit = TimeUnit.NANOSECONDS)
class FlexBuffersBenchmark {
open class FlexBuffersBenchmark {
var initialCapacity = 1024
var value: Double = 0.0
@@ -49,7 +48,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun mapKotlin(blackhole: Blackhole) {
open fun mapKotlin(blackhole: Blackhole) {
val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
kBuilder.putMap {
this["hello"] = "world"
@@ -72,7 +71,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun mapJava(blackhole: Blackhole) {
open fun mapJava(blackhole: Blackhole) {
val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL)
val startMap = jBuilder.startMap()
jBuilder.putString("hello", "world")
@@ -102,7 +101,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun intArrayKotlin(blackhole: Blackhole) {
open fun intArrayKotlin(blackhole: Blackhole) {
val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
kBuilder.put(bigIntArray)
val root = getRoot(kBuilder.finish())
@@ -110,7 +109,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun intArrayJava(blackhole: Blackhole) {
open fun intArrayJava(blackhole: Blackhole) {
val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL)
val v = jBuilder.startVector()
bigIntArray.forEach { jBuilder.putInt(it) }
@@ -126,7 +125,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun stringArrayKotlin(blackhole: Blackhole) {
open fun stringArrayKotlin(blackhole: Blackhole) {
val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
kBuilder.putVector { stringValue.forEach { kBuilder.put(it) } }
kBuilder.finish()
@@ -136,7 +135,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun stringArrayJava(blackhole: Blackhole) {
open fun stringArrayJava(blackhole: Blackhole) {
val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL)
val v = jBuilder.startVector()
stringValue.forEach { jBuilder.putString(it) }
@@ -148,7 +147,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun stringMapKotlin(blackhole: Blackhole) {
open fun stringMapKotlin(blackhole: Blackhole) {
val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
val pos = kBuilder.startMap()
for (i in stringKey.indices) {
@@ -165,7 +164,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun stringMapBytIndexKotlin(blackhole: Blackhole) {
open fun stringMapBytIndexKotlin(blackhole: Blackhole) {
val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
val pos = kBuilder.startMap()
for (i in stringKey.indices) {
@@ -180,7 +179,7 @@ class FlexBuffersBenchmark {
}
@Benchmark
fun stringMapJava(blackhole: Blackhole) {
open fun stringMapJava(blackhole: Blackhole) {
val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL)
val v = jBuilder.startMap()
for (i in stringKey.indices) {

View File

@@ -41,7 +41,7 @@ import java.util.concurrent.TimeUnit
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Measurement(iterations = 100, time = 1, timeUnit = TimeUnit.MICROSECONDS)
class JsonBenchmark {
open class JsonBenchmark {
final val moshi = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
@@ -76,46 +76,46 @@ class JsonBenchmark {
// TWITTER
@Benchmark
fun readTwitterFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(twitterData))
open fun readTwitterFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(twitterData))
@Benchmark
fun readTwitterMoshi(hole: Blackhole?) = hole?.consume(readMoshi(twitterData))
open fun readTwitterMoshi(hole: Blackhole?) = hole?.consume(readMoshi(twitterData))
@Benchmark
fun readTwitterGson(hole: Blackhole?) = hole?.consume(readGson(twitterData))
open fun readTwitterGson(hole: Blackhole?) = hole?.consume(readGson(twitterData))
@Benchmark
fun roundTripTwitterFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(twitterData).toJson())
open fun roundTripTwitterFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(twitterData).toJson())
@Benchmark
fun roundTripTwitterMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(twitterData)))
open fun roundTripTwitterMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(twitterData)))
@Benchmark
fun roundTripTwitterGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(twitterData)))
open fun roundTripTwitterGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(twitterData)))
// CITM
@Benchmark
fun readCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(citmData))
open fun readCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(citmData))
@Benchmark
fun readCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(citmData)))
open fun readCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(citmData)))
@Benchmark
fun readCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(citmData)))
open fun readCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(citmData)))
@Benchmark
fun roundTripCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(citmData).toJson())
open fun roundTripCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(citmData).toJson())
@Benchmark
fun roundTripCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(citmData)))
open fun roundTripCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(citmData)))
@Benchmark
fun roundTripCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(citmData)))
open fun roundTripCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(citmData)))
@Benchmark
fun writeCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(fbCitmRef.toJson())
open fun writeCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(fbCitmRef.toJson())
@Benchmark
fun writeCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(moshiCitmRef))
open fun writeCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(moshiCitmRef))
@Benchmark
fun writeCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(gsonCitmRef))
open fun writeCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(gsonCitmRef))
// CANADA
@Benchmark
fun readCanadaFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(canadaData))
open fun readCanadaFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(canadaData))
@Benchmark
fun readCanadaMoshi(hole: Blackhole?) = hole?.consume(readMoshi(canadaData))
open fun readCanadaMoshi(hole: Blackhole?) = hole?.consume(readMoshi(canadaData))
@Benchmark
fun readCanadaGson(hole: Blackhole?) = hole?.consume(readGson(canadaData))
open fun readCanadaGson(hole: Blackhole?) = hole?.consume(readGson(canadaData))
}

View File

@@ -1,7 +1,3 @@
plugins {
id("com.diffplug.spotless") version "6.3.0"
}
group = "com.google.flatbuffers"
version = "2.0.0-SNAPSHOT"
@@ -12,7 +8,10 @@ buildscript {
mavenCentral()
}
dependencies {
classpath(libs.bundles.plugins)
classpath(libs.plugin.kotlin.gradle)
classpath(libs.plugin.kotlinx.benchmark)
classpath(libs.plugin.jmhreport)
classpath(libs.plugin.download)
}
}
@@ -22,21 +21,3 @@ allprojects {
mavenCentral()
}
}
// plugin used to enforce code style
spotless {
val klintConfig = mapOf("indent_size" to "2", "continuation_indent_size" to "2")
kotlin {
target("**/*.kt")
ktlint("0.40.0").userData(klintConfig)
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
licenseHeaderFile("$rootDir/spotless/spotless.kt").updateYearWithLatest(false)
targetExclude("**/spotless.kt", "**/build/**")
}
kotlinGradle {
target("*.gradle.kts")
ktlint().userData(klintConfig)
}
}

View File

@@ -1,20 +1,19 @@
[versions]
plugin-kotlin = "1.6.10"
kotlin = "1.7.21"
plugin-gver = "0.42.0"
kotlinx-benchmark-runtime = "0.4.2"
kotlinx-benchmark = "0.4.6"
junit = "4.12"
gson = "2.8.5"
moshi-kotlin = "1.11.0"
[libraries]
kotlin-compiler = { module = "org.jetbrains.kotlin:kotlin-compiler", version.ref = "kotlin" }
moshi-kotlin = { module = "com.squareup.moshi:moshi-kotlin", version.ref = "moshi-kotlin" }
gson = { module = "com.google.code.gson:gson", version.ref = "gson" }
kotlinx-benchmark-runtime = { module = "org.jetbrains.kotlinx:kotlinx-benchmark-runtime", version.ref = "kotlinx-benchmark-runtime" }
plugin-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "plugin-kotlin" }
plugin-kotlin-serialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "plugin-kotlin" }
kotlinx-benchmark-runtime = { module = "org.jetbrains.kotlinx:kotlinx-benchmark-runtime", version.ref = "kotlinx-benchmark" }
plugin-gver = { module = "com.github.ben-manes:gradle-versions-plugin", version.ref = "plugin-gver" }
plugin-kotlin-gradle = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
plugin-kotlinx-benchmark = { module="org.jetbrains.kotlinx:kotlinx-benchmark-plugin", version.ref="kotlinx-benchmark"}
plugin-jmhreport = { module = "gradle.plugin.io.morethan.jmhreport:gradle-jmh-report", version="0.9.0" }
plugin-download = { module = "de.undercouch:gradle-download-task", version = "5.3.0"}
junit = { module="junit:junit", version.ref="junit"}
[bundles]
plugins = ["plugin-kotlin", "plugin-kotlin-serialization", "plugin-gver"]

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -32,6 +32,6 @@ namespace Google.FlatBuffers
Changes to the C# implementation need to be sure to change
the version here and in the code generator on every possible
incompatible change */
public static void FLATBUFFERS_23_1_20() {}
public static void FLATBUFFERS_23_3_3() {}
}
}

View File

@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard2.1;netstandard2.0;net46</TargetFrameworks>
<Description>A cross-platform memory efficient serialization library</Description>
<PackageVersion>23.1.20</PackageVersion>
<PackageVersion>23.3.3</PackageVersion>
<Authors>Google LLC</Authors>
<PackageProjectUrl>https://github.com/google/flatbuffers</PackageProjectUrl>
<RepositoryUrl>https://github.com/google/flatbuffers</RepositoryUrl>

View File

@@ -1,6 +1,6 @@
{
"name": "flatbuffers",
"version": "23.1.20",
"version": "23.3.3",
"description": "Memory Efficient Serialization Library",
"files": [
"js/**/*.js",
@@ -9,8 +9,8 @@
"mjs/**/*.d.ts",
"ts/**/*.ts"
],
"main": "js/index.js",
"module": "mjs/index.js",
"main": "js/flatbuffers.js",
"module": "mjs/flatbuffers.js",
"directories": {
"doc": "docs",
"test": "tests"
@@ -18,7 +18,7 @@
"scripts": {
"test": "npm run compile && cd tests/ts && python3 ./TypeScriptTest.py",
"lint": "eslint ts",
"compile": "tsc && tsc -p tsconfig.mjs.json && rollup -c",
"compile": "tsc && tsc -p tsconfig.mjs.json && esbuild js/flatbuffers.js --minify --global-name=flatbuffers --bundle --outfile=js/flatbuffers.min.js",
"prepublishOnly": "npm install --only=dev && npm run compile"
},
"repository": {
@@ -38,10 +38,10 @@
"devDependencies": {
"@bazel/typescript": "5.2.0",
"@types/node": "18.7.16",
"@typescript-eslint/eslint-plugin": "^5.36.2",
"@typescript-eslint/parser": "^5.36.2",
"eslint": "^8.23.1",
"rollup": "^2.79.0",
"@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
"esbuild": "^0.16.4",
"eslint": "^8.29.0",
"typescript": "^4.8.3"
}
}

View File

@@ -14,4 +14,4 @@
# Placeholder, to be updated during the release process
# by the setup.py
__version__ = u"23.1.20"
__version__ = u"23.3.3"

View File

@@ -16,7 +16,7 @@ from setuptools import setup
setup(
name='flatbuffers',
version='23.1.20',
version='23.3.3',
license='Apache 2.0',
license_files='../LICENSE.txt',
author='Derek Bailey',

View File

@@ -77,4 +77,4 @@ Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities.
[FlatBuffers Issues Tracker]: http://github.com/google/flatbuffers/issues
[stackoverflow.com]: http://stackoverflow.com/search?q=flatbuffers
[landing page]: https://google.github.io/flatbuffers
[LICENSE]: https://github.com/google/flatbuffers/blob/master/LICENSE.txt
[LICENSE]: https://github.com/google/flatbuffers/blob/master/LICENSE

View File

@@ -11,6 +11,5 @@ flatbuffer_ts_library(
name = "reflection_ts_fbs",
package_name = "flatbuffers_reflection",
srcs = [":reflection.fbs"],
include_reflection = False,
visibility = ["//visibility:public"],
)

View File

@@ -1,8 +0,0 @@
export default {
input: 'mjs/index.js',
output: {
file: 'flatbuffers.js',
format: 'iife',
name: 'flatbuffers'
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "flatbuffers"
version = "23.1.20"
version = "23.3.3"
edition = "2018"
authors = ["Robert Winslow <hello@rwinslow.com>", "FlatBuffers Maintainers"]
license = "Apache-2.0"

View File

@@ -9,8 +9,8 @@
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 1 &&
FLATBUFFERS_VERSION_REVISION == 20,
FLATBUFFERS_VERSION_MINOR == 3 &&
FLATBUFFERS_VERSION_REVISION == 3,
"Non-compatible flatbuffers version included");
namespace MyGame {

View File

@@ -36,7 +36,7 @@ public enum MyGame_Sample_Equipment: UInt8, UnionEnum {
public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable {
static func validateVersion() { FlatBuffersVersion_23_1_20() }
static func validateVersion() { FlatBuffersVersion_23_3_3() }
private var _x: Float32
private var _y: Float32
@@ -72,7 +72,7 @@ public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializ
public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_23_1_20() }
static func validateVersion() { FlatBuffersVersion_23_3_3() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct
@@ -88,7 +88,7 @@ public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_1_20() }
static func validateVersion() { FlatBuffersVersion_23_3_3() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
@@ -200,7 +200,7 @@ public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable {
public struct MyGame_Sample_Weapon: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_1_20() }
static func validateVersion() { FlatBuffersVersion_23_3_3() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table

View File

@@ -99,20 +99,20 @@ def main():
# Note: We did not set the `Mana` field explicitly, so we get a default value.
assert monster.Mana() == 150
assert monster.Hp() == 300
assert monster.Name() == 'Orc'
assert monster.Name() == b'Orc'
assert monster.Color() == MyGame.Sample.Color.Color().Red
assert monster.Pos().X() == 1.0
assert monster.Pos().Y() == 2.0
assert monster.Pos().Z() == 3.0
# Get and test the `inventory` FlatBuffer `vector`.
for i in xrange(monster.InventoryLength()):
for i in range(monster.InventoryLength()):
assert monster.Inventory(i) == i
# Get and test the `weapons` FlatBuffer `vector` of `table`s.
expected_weapon_names = ['Sword', 'Axe']
expected_weapon_names = [b'Sword', b'Axe']
expected_weapon_damages = [3, 5]
for i in xrange(monster.WeaponsLength()):
for i in range(monster.WeaponsLength()):
assert monster.Weapons(i).Name() == expected_weapon_names[i]
assert monster.Weapons(i).Damage() == expected_weapon_damages[i]
@@ -128,10 +128,10 @@ def main():
union_weapon = MyGame.Sample.Weapon.Weapon()
union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos)
assert union_weapon.Name() == "Axe"
assert union_weapon.Name() == b"Axe"
assert union_weapon.Damage() == 5
print 'The FlatBuffer was successfully created and verified!'
print('The FlatBuffer was successfully created and verified!')
if __name__ == '__main__':
main()

View File

@@ -24,6 +24,7 @@ from util import flatc, root_path, tests_path, args, flatc_path
# Specify the other paths that will be referenced
swift_code_gen = Path(root_path, "tests/swift/tests/CodeGenerationTests")
ts_code_gen = Path(root_path, "tests/ts")
samples_path = Path(root_path, "samples")
reflection_path = Path(root_path, "reflection")
@@ -104,6 +105,7 @@ PHP_OPTS = ["--php"]
DART_OPTS = ["--dart"]
PYTHON_OPTS = ["--python"]
BINARY_OPTS = ["-b", "--schema", "--bfbs-comments", "--bfbs-builtins"]
PROTO_OPTS = ["--proto"]
# Basic Usage
@@ -142,10 +144,10 @@ flatc(
flatc(
NO_INCL_OPTS
+ TS_OPTS,
schema="monster_test.fbs",
prefix="ts",
include="include_test",
data="monsterdata_test.json",
cwd=ts_code_gen,
schema="../monster_test.fbs",
include="../include_test",
data="../monsterdata_test.json",
)
flatc(
@@ -191,6 +193,11 @@ flatc(
data="monsterdata_test.json",
)
flatc(
PROTO_OPTS,
schema="prototest/test.proto",
)
# For Rust we currently generate two independent schemas, with namespace_test2
# duplicating the types in namespace_test1
flatc(
@@ -210,37 +217,31 @@ flatc(
flatc(
BASE_OPTS + TS_OPTS,
prefix="ts/union_vector",
schema="union_vector/union_vector.fbs",
cwd=ts_code_gen,
prefix="union_vector",
schema="../union_vector/union_vector.fbs",
)
flatc(
BASE_OPTS + TS_OPTS + ["--gen-name-strings", "--gen-mutable"],
include="include_test",
prefix="ts",
schema="monster_test.fbs",
)
# Generate the complete flat file TS of monster.
flatc(
["--ts", "--gen-all", "--ts-flat-files"],
include="include_test",
schema="monster_test.fbs",
prefix="ts/ts-flat-files"
cwd=ts_code_gen,
include="../include_test",
schema="../monster_test.fbs",
)
flatc(
BASE_OPTS + TS_OPTS + ["-b"],
include="include_test",
prefix="ts",
schema="monster_test.fbs",
data="unicode_test.json",
cwd=ts_code_gen,
include="../include_test",
schema="../monster_test.fbs",
data="../unicode_test.json",
)
flatc(
BASE_OPTS + TS_OPTS + ["--gen-name-strings"],
prefix="ts/union_vector",
schema="union_vector/union_vector.fbs",
cwd=ts_code_gen,
prefix="union_vector",
schema="../union_vector/union_vector.fbs",
)
flatc(
@@ -340,7 +341,7 @@ flatc(
# Optional Scalars
optional_scalars_schema = "optional_scalars.fbs"
flatc(["--java", "--kotlin", "--lobster"], schema=optional_scalars_schema)
flatc(TS_OPTS, schema=optional_scalars_schema, prefix="ts")
flatc(TS_OPTS, cwd=ts_code_gen, schema="../optional_scalars.fbs")
flatc(["--csharp", "--python", "--gen-object-api"], schema=optional_scalars_schema)
@@ -506,6 +507,12 @@ if not args.skip_gen_reflection:
# Python Reflection
flatc_reflection(["-p"], "python/flatbuffers", "reflection")
# Java Reflection
flatc_reflection(
["-j", "--java-package-prefix", "com.google.flatbuffers"],
"java/src/main/java", "com/google/flatbuffers/reflection"
)
# Annotation

View File

@@ -11,7 +11,9 @@ cc_library(
srcs = [
"code_generators.cpp",
"idl_gen_fbs.cpp",
"idl_gen_fbs.h",
"idl_gen_text.cpp",
"idl_gen_text.h",
"idl_parser.cpp",
"reflection.cpp",
"util.cpp",
@@ -68,22 +70,39 @@ cc_library(
"bfbs_gen_nim.h",
"bfbs_namer.h",
"flatc_main.cpp",
"idl_gen_binary.cpp",
"idl_gen_binary.h",
"idl_gen_cpp.cpp",
"idl_gen_cpp.h",
"idl_gen_csharp.cpp",
"idl_gen_csharp.h",
"idl_gen_dart.cpp",
"idl_gen_dart.h",
"idl_gen_go.cpp",
"idl_gen_go.h",
"idl_gen_grpc.cpp",
"idl_gen_java.cpp",
"idl_gen_java.h",
"idl_gen_json_schema.cpp",
"idl_gen_json_schema.h",
"idl_gen_kotlin.cpp",
"idl_gen_kotlin.h",
"idl_gen_lobster.cpp",
"idl_gen_lobster.h",
"idl_gen_lua.cpp",
"idl_gen_lua.h",
"idl_gen_php.cpp",
"idl_gen_php.h",
"idl_gen_python.cpp",
"idl_gen_python.h",
"idl_gen_rust.cpp",
"idl_gen_rust.h",
"idl_gen_swift.cpp",
"idl_gen_swift.h",
"idl_gen_text.cpp",
"idl_gen_text.h",
"idl_gen_ts.cpp",
"idl_gen_ts.h",
"idl_namer.h",
"namer.h",
"util.cpp",

View File

@@ -1,6 +1,8 @@
#include "annotated_binary_text_gen.h"
#include <algorithm>
#include <fstream>
#include <ostream>
#include <sstream>
#include <string>
@@ -21,6 +23,8 @@ struct OutputConfig {
size_t offset_max_char = 4;
char delimiter = '|';
bool include_vector_contents = true;
};
static std::string ToString(const BinarySectionType type) {
@@ -83,7 +87,7 @@ static std::string ToValueString(const BinaryRegion &region,
if (region.array_length) {
if (region.type == BinaryRegionType::Uint8 ||
region.type == BinaryRegionType::Unknown) {
// Interpet each value as a ASCII to aid debugging
// Interpret each value as a ASCII to aid debugging
for (uint64_t i = 0; i < region.array_length; ++i) {
const uint8_t c = *(binary + region.offset + i);
s += isprint(c) ? static_cast<char>(c & 0x7F) : '.';
@@ -131,7 +135,7 @@ static std::string ToValueString(const BinaryRegion &region,
// value.
// TODO(dbaileychess): It might be nicer to put this in the comment field.
if (IsOffset(region.type)) {
s += " Loc: +0x";
s += " Loc: 0x";
s += ToHex(region.points_to_offset, output_config.offset_max_char);
}
return s;
@@ -257,84 +261,74 @@ static std::string GenerateComment(const BinaryRegionComment &comment,
return s;
}
static std::string GenerateDocumentation(const BinaryRegion &region,
const BinarySection &section,
const uint8_t *binary,
DocContinuation &continuation,
const OutputConfig &output_config) {
std::string s;
static void GenerateDocumentation(std::ostream &os, const BinaryRegion &region,
const BinarySection &section,
const uint8_t *binary,
DocContinuation &continuation,
const OutputConfig &output_config) {
// Check if there is a doc continuation that should be prioritized.
if (continuation.value_start_column) {
s += std::string(continuation.value_start_column - 2, ' ');
s += output_config.delimiter;
s += " ";
os << std::string(continuation.value_start_column - 2, ' ');
os << output_config.delimiter << " ";
s += continuation.value.substr(0, output_config.max_bytes_per_line);
os << continuation.value.substr(0, output_config.max_bytes_per_line);
continuation.value = continuation.value.substr(
std::min(output_config.max_bytes_per_line, continuation.value.size()));
return s;
return;
}
size_t size_of = 0;
{
std::stringstream ss;
ss << std::setw(static_cast<int>(output_config.largest_type_string)) << std::left;
ss << std::setw(static_cast<int>(output_config.largest_type_string))
<< std::left;
ss << GenerateTypeString(region);
s += ss.str();
os << ss.str();
size_of = ss.str().size();
}
s += " ";
s += output_config.delimiter;
s += " ";
os << " " << output_config.delimiter << " ";
if (region.array_length) {
// Record where the value is first being outputted.
continuation.value_start_column = s.size();
continuation.value_start_column = 3 + size_of;
// Get the full-length value, which we will chunk below.
const std::string value = ToValueString(region, binary, output_config);
std::stringstream ss;
ss << std::setw(static_cast<int>(output_config.largest_value_string)) << std::left;
ss << std::setw(static_cast<int>(output_config.largest_value_string))
<< std::left;
ss << value.substr(0, output_config.max_bytes_per_line);
s += ss.str();
os << ss.str();
continuation.value =
value.substr(std::min(output_config.max_bytes_per_line, value.size()));
} else {
std::stringstream ss;
ss << std::setw(static_cast<int>(output_config.largest_value_string)) << std::left;
ss << std::setw(static_cast<int>(output_config.largest_value_string))
<< std::left;
ss << ToValueString(region, binary, output_config);
s += ss.str();
os << ss.str();
}
s += " ";
s += output_config.delimiter;
s += " ";
s += GenerateComment(region.comment, section);
return s;
os << " " << output_config.delimiter << " ";
os << GenerateComment(region.comment, section);
}
static std::string GenerateRegion(const BinaryRegion &region,
const BinarySection &section,
const uint8_t *binary,
const OutputConfig &output_config) {
std::string s;
static void GenerateRegion(std::ostream &os, const BinaryRegion &region,
const BinarySection &section, const uint8_t *binary,
const OutputConfig &output_config) {
bool doc_generated = false;
DocContinuation doc_continuation;
for (uint64_t i = 0; i < region.length; ++i) {
if ((i % output_config.max_bytes_per_line) == 0) {
// Start a new line of output
s += '\n';
s += " ";
s += "+0x";
s += ToHex(region.offset + i, output_config.offset_max_char);
s += " ";
s += output_config.delimiter;
os << std::endl;
os << " +0x" << ToHex(region.offset + i, output_config.offset_max_char);
os << " " << output_config.delimiter;
}
// Add each byte
s += " ";
s += ToHex(binary[region.offset + i]);
os << " " << ToHex(binary[region.offset + i]);
// Check for end of line or end of region conditions.
if (((i + 1) % output_config.max_bytes_per_line == 0) ||
@@ -344,17 +338,16 @@ static std::string GenerateRegion(const BinaryRegion &region,
// zero those out to align everything globally.
for (uint64_t j = i + 1; (j % output_config.max_bytes_per_line) != 0;
++j) {
s += " ";
os << " ";
}
}
s += " ";
s += output_config.delimiter;
os << " " << output_config.delimiter;
// This is the end of the first line or its the last byte of the region,
// generate the end-of-line documentation.
if (!doc_generated) {
s += " ";
s += GenerateDocumentation(region, section, binary, doc_continuation,
output_config);
os << " ";
GenerateDocumentation(os, region, section, binary, doc_continuation,
output_config);
// If we have a value in the doc continuation, that means the doc is
// being printed on multiple lines.
@@ -362,22 +355,41 @@ static std::string GenerateRegion(const BinaryRegion &region,
}
}
}
return s;
}
static std::string GenerateSection(const BinarySection &section,
const uint8_t *binary,
const OutputConfig &output_config) {
std::string s;
s += "\n";
s += ToString(section.type);
if (!section.name.empty()) { s += " (" + section.name + ")"; }
s += ":";
for (const BinaryRegion &region : section.regions) {
s += GenerateRegion(region, section, binary, output_config);
static void GenerateSection(std::ostream &os, const BinarySection &section,
const uint8_t *binary,
const OutputConfig &output_config) {
os << std::endl;
os << ToString(section.type);
if (!section.name.empty()) { os << " (" + section.name + ")"; }
os << ":";
// As a space saving measure, skip generating every vector element, just put
// the first and last elements in the output. Skip the whole thing if there
// are only three or fewer elements, as it doesn't save space.
if (section.type == BinarySectionType::Vector &&
!output_config.include_vector_contents && section.regions.size() > 4) {
// Generate the length region which should be first.
GenerateRegion(os, section.regions[0], section, binary, output_config);
// Generate the first element.
GenerateRegion(os, section.regions[1], section, binary, output_config);
// Indicate that we omitted elements.
os << std::endl
<< " <" << section.regions.size() - 3 << " regions omitted>";
// Generate the last element.
GenerateRegion(os, section.regions.back(), section, binary, output_config);
os << std::endl;
return;
}
return s;
for (const BinaryRegion &region : section.regions) {
GenerateRegion(os, region, section, binary, output_config);
}
os << std::endl;
}
} // namespace
@@ -385,6 +397,7 @@ bool AnnotatedBinaryTextGenerator::Generate(
const std::string &filename, const std::string &schema_filename) {
OutputConfig output_config;
output_config.max_bytes_per_line = options_.max_bytes_per_line;
output_config.include_vector_contents = options_.include_vector_contents;
// Given the length of the binary, we can calculate the maximum number of
// characters to display in the offset hex: (i.e. 2 would lead to 0XFF being
@@ -414,19 +427,6 @@ bool AnnotatedBinaryTextGenerator::Generate(
}
}
// Generate each of the binary sections
std::string s;
s += "// Annotated Flatbuffer Binary\n";
s += "//\n";
s += "// Schema file: " + schema_filename + "\n";
s += "// Binary file: " + filename + "\n";
for (const auto &section : annotations_) {
s += GenerateSection(section.second, binary_, output_config);
s += "\n";
}
// Modify the output filename.
std::string output_filename = StripExtension(filename);
output_filename += options_.output_postfix;
@@ -434,7 +434,20 @@ bool AnnotatedBinaryTextGenerator::Generate(
"." + (options_.output_extension.empty() ? GetExtension(filename)
: options_.output_extension);
return SaveFile(output_filename.c_str(), s, false);
std::ofstream ofs(output_filename.c_str());
ofs << "// Annotated Flatbuffer Binary" << std::endl;
ofs << "//" << std::endl;
ofs << "// Schema file: " << schema_filename << std::endl;
ofs << "// Binary file: " << filename << std::endl;
// Generate each of the binary sections
for (const auto &section : annotations_) {
GenerateSection(ofs, section.second, binary_, output_config);
}
ofs.close();
return true;
}
} // namespace flatbuffers

View File

@@ -41,6 +41,9 @@ class AnnotatedBinaryTextGenerator {
//
// Example: binary1.bin -> binary1.afb
std::string output_extension = "afb";
// Controls.
bool include_vector_contents = true;
};
explicit AnnotatedBinaryTextGenerator(

View File

@@ -19,7 +19,7 @@
#include <cstdint>
#include "flatbuffers/bfbs_generator.h"
#include "flatbuffers/code_generator.h"
#include "flatbuffers/reflection_generated.h"
namespace flatbuffers {
@@ -96,20 +96,19 @@ static bool IsVector(const reflection::BaseType base_type) {
// A concrete base Flatbuffer Generator that specific language generators can
// derive from.
class BaseBfbsGenerator : public BfbsGenerator {
class BaseBfbsGenerator : public CodeGenerator {
public:
virtual ~BaseBfbsGenerator() {}
BaseBfbsGenerator() : schema_(nullptr) {}
virtual GeneratorStatus GenerateFromSchema(
virtual Status GenerateFromSchema(
const reflection::Schema *schema) = 0;
//
virtual uint64_t SupportedAdvancedFeatures() const = 0;
// Override of the Generator::generate method that does the initial
// Override of the Generator::GenerateCode method that does the initial
// deserialization and verification steps.
GeneratorStatus Generate(const uint8_t *buffer,
Status GenerateCode(const uint8_t *buffer,
int64_t length) FLATBUFFERS_OVERRIDE {
flatbuffers::Verifier verifier(buffer, static_cast<size_t>(length));
if (!reflection::VerifySchemaBuffer(verifier)) {
@@ -125,7 +124,7 @@ class BaseBfbsGenerator : public BfbsGenerator {
return FAILED_VERIFICATION;
}
GeneratorStatus status = GenerateFromSchema(schema_);
Status status = GenerateFromSchema(schema_);
schema_ = nullptr;
return status;
}

View File

@@ -26,7 +26,6 @@
// Ensure no includes to flatc internals. bfbs_gen.h and generator.h are OK.
#include "bfbs_gen.h"
#include "bfbs_namer.h"
#include "flatbuffers/bfbs_generator.h"
// The intermediate representation schema.
#include "flatbuffers/reflection.h"
@@ -79,15 +78,57 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
flatc_version_(flatc_version),
namer_(LuaDefaultConfig(), LuaKeywords()) {}
GeneratorStatus GenerateFromSchema(const r::Schema *schema)
FLATBUFFERS_OVERRIDE {
if (!GenerateEnums(schema->enums())) { return FAILED; }
Status GenerateFromSchema(const r::Schema *schema) FLATBUFFERS_OVERRIDE {
if (!GenerateEnums(schema->enums())) { return ERROR; }
if (!GenerateObjects(schema->objects(), schema->root_table())) {
return FAILED;
return ERROR;
}
return OK;
}
using BaseBfbsGenerator::GenerateCode;
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) FLATBUFFERS_OVERRIDE {
if (!GenerateLua(parser, path, filename)) { return ERROR; }
return OK;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return true; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kLua; }
std::string LanguageName() const override { return "Lua"; }
uint64_t SupportedAdvancedFeatures() const FLATBUFFERS_OVERRIDE {
return 0xF;
}
@@ -625,7 +666,7 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
};
} // namespace
std::unique_ptr<BfbsGenerator> NewLuaBfbsGenerator(
std::unique_ptr<CodeGenerator> NewLuaBfbsGenerator(
const std::string &flatc_version) {
return std::unique_ptr<LuaBfbsGenerator>(new LuaBfbsGenerator(flatc_version));
}

View File

@@ -20,12 +20,12 @@
#include <memory>
#include <string>
#include "flatbuffers/bfbs_generator.h"
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Lua Code generator.
std::unique_ptr<BfbsGenerator> NewLuaBfbsGenerator(
std::unique_ptr<CodeGenerator> NewLuaBfbsGenerator(
const std::string &flatc_version);
} // namespace flatbuffers

View File

@@ -26,7 +26,6 @@
// Ensure no includes to flatc internals. bfbs_gen.h and generator.h are OK.
#include "bfbs_gen.h"
#include "bfbs_namer.h"
#include "flatbuffers/bfbs_generator.h"
// The intermediate representation schema.
#include "flatbuffers/reflection.h"
@@ -96,8 +95,7 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
flatc_version_(flatc_version),
namer_(NimDefaultConfig(), NimKeywords()) {}
GeneratorStatus GenerateFromSchema(const r::Schema *schema)
FLATBUFFERS_OVERRIDE {
Status GenerateFromSchema(const r::Schema *schema) FLATBUFFERS_OVERRIDE {
ForAllEnums(schema->enums(), [&](const r::Enum *enum_def) {
StartCodeBlock(enum_def);
GenerateEnum(enum_def);
@@ -109,6 +107,51 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
return OK;
}
using BaseBfbsGenerator::GenerateCode;
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return true; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kNim; }
std::string LanguageName() const override { return "Nim"; }
uint64_t SupportedAdvancedFeatures() const FLATBUFFERS_OVERRIDE {
return r::AdvancedArrayFeatures | r::AdvancedUnionFeatures |
r::OptionalScalars | r::DefaultVectorsAndStrings;
@@ -472,9 +515,11 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
if (IsFloatingPoint(base_type)) {
if (field->default_real() != field->default_real()) {
return "NaN";
} else if (field->default_real() == std::numeric_limits<double>::infinity()) {
} else if (field->default_real() ==
std::numeric_limits<double>::infinity()) {
return "Inf";
} else if (field->default_real() == -std::numeric_limits<double>::infinity()) {
} else if (field->default_real() ==
-std::numeric_limits<double>::infinity()) {
return "-Inf";
}
return NumToString(field->default_real());
@@ -639,7 +684,7 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
};
} // namespace
std::unique_ptr<BfbsGenerator> NewNimBfbsGenerator(
std::unique_ptr<CodeGenerator> NewNimBfbsGenerator(
const std::string &flatc_version) {
return std::unique_ptr<NimBfbsGenerator>(new NimBfbsGenerator(flatc_version));
}

View File

@@ -20,12 +20,12 @@
#include <memory>
#include <string>
#include "flatbuffers/bfbs_generator.h"
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Nim Code generator.
std::unique_ptr<BfbsGenerator> NewNimBfbsGenerator(
std::unique_ptr<CodeGenerator> NewNimBfbsGenerator(
const std::string &flatc_version);
} // namespace flatbuffers

View File

@@ -196,14 +196,22 @@ uint64_t BinaryAnnotator::BuildHeader(const uint64_t header_offset) {
return root_table_offset.value();
}
void BinaryAnnotator::BuildVTable(const uint64_t vtable_offset,
const reflection::Object *const table,
const uint64_t offset_of_referring_table) {
// First see if we have used this vtable before, if so skip building it again.
auto it = vtables_.find(vtable_offset);
if (it != vtables_.end()) { return; }
BinaryAnnotator::VTable *BinaryAnnotator::GetOrBuildVTable(
const uint64_t vtable_offset, const reflection::Object *const table,
const uint64_t offset_of_referring_table) {
// Get a list of vtables (if any) already defined at this offset.
std::list<VTable> &vtables = vtables_[vtable_offset];
if (ContainsSection(vtable_offset)) { return; }
// See if this vtable for the table type has been generated before.
for (VTable &vtable : vtables) {
if (vtable.referring_table == table) { return &vtable; }
}
// If we are trying to make a new vtable and it is already encompassed by
// another binary section, something is corrupted.
if (vtables.empty() && ContainsSection(vtable_offset)) { return nullptr; }
const std::string referring_table_name = table->name()->str();
BinaryRegionComment vtable_size_comment;
vtable_size_comment.type = BinaryRegionCommentType::VTableSize;
@@ -217,11 +225,11 @@ void BinaryAnnotator::BuildVTable(const uint64_t vtable_offset,
AddSection(vtable_offset,
MakeSingleRegionBinarySection(
table->name()->str(), BinarySectionType::VTable,
referring_table_name, BinarySectionType::VTable,
MakeBinaryRegion(vtable_offset, remaining,
BinaryRegionType::Unknown, remaining, 0,
vtable_size_comment)));
return;
return nullptr;
}
// Vtables start with the size of the vtable
@@ -232,23 +240,23 @@ void BinaryAnnotator::BuildVTable(const uint64_t vtable_offset,
// The vtable_size points to off the end of the binary.
AddSection(vtable_offset,
MakeSingleRegionBinarySection(
table->name()->str(), BinarySectionType::VTable,
referring_table_name, BinarySectionType::VTable,
MakeBinaryRegion(vtable_offset, sizeof(uint16_t),
BinaryRegionType::Uint16, 0, 0,
vtable_size_comment)));
return;
return nullptr;
} else if (vtable_size < 2 * sizeof(uint16_t)) {
SetError(vtable_size_comment, BinaryRegionStatus::ERROR_LENGTH_TOO_SHORT,
"4");
// The size includes itself and the table size which are both uint16_t.
AddSection(vtable_offset,
MakeSingleRegionBinarySection(
table->name()->str(), BinarySectionType::VTable,
referring_table_name, BinarySectionType::VTable,
MakeBinaryRegion(vtable_offset, sizeof(uint16_t),
BinaryRegionType::Uint16, 0, 0,
vtable_size_comment)));
return;
return nullptr;
}
std::vector<BinaryRegion> regions;
@@ -272,11 +280,11 @@ void BinaryAnnotator::BuildVTable(const uint64_t vtable_offset,
"2");
AddSection(offset, MakeSingleRegionBinarySection(
table->name()->str(), BinarySectionType::VTable,
referring_table_name, BinarySectionType::VTable,
MakeBinaryRegion(
offset, remaining, BinaryRegionType::Unknown,
remaining, 0, ref_table_len_comment)));
return;
return nullptr;
}
// Then they have the size of the table they reference.
@@ -395,7 +403,7 @@ void BinaryAnnotator::BuildVTable(const uint64_t vtable_offset,
(vtable_size - sizeof(uint16_t) - sizeof(uint16_t)) / sizeof(uint16_t);
// Prevent a bad binary from declaring a really large vtable_size, that we can
// not indpendently verify.
// not independently verify.
expectant_vtable_fields = std::min(
static_cast<uint16_t>(fields_processed * 3), expectant_vtable_fields);
@@ -427,15 +435,26 @@ void BinaryAnnotator::BuildVTable(const uint64_t vtable_offset,
field_comment));
}
sections_[vtable_offset] = MakeBinarySection(
table->name()->str(), BinarySectionType::VTable, std::move(regions));
// If we have never added this vtable before record the Binary section.
if (vtables.empty()) {
sections_[vtable_offset] = MakeBinarySection(
referring_table_name, BinarySectionType::VTable, std::move(regions));
} else {
// Add the current table name to the name of the section.
sections_[vtable_offset].name += ", " + referring_table_name;
}
VTable vtable;
vtable.referring_table = table;
vtable.fields = std::move(fields);
vtable.table_size = table_size;
vtable.vtable_size = vtable_size;
vtables_[vtable_offset] = vtable;
// Add this vtable to the collection of vtables at this offset.
vtables.push_back(std::move(vtable));
// Return the vtable we just added.
return &vtables.back();
}
void BinaryAnnotator::BuildTable(const uint64_t table_offset,
@@ -491,19 +510,17 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
// Parse the vtable first so we know what the rest of the fields in the table
// are.
BuildVTable(vtable_offset, table, table_offset);
const VTable *const vtable =
GetOrBuildVTable(vtable_offset, table, table_offset);
auto vtable_entry = vtables_.find(vtable_offset);
if (vtable_entry == vtables_.end()) {
if (vtable == nullptr) {
// There is no valid vtable for this table, so we cannot process the rest of
// the table entries.
return;
}
const VTable &vtable = vtable_entry->second;
// This is the size and length of this table.
const uint16_t table_size = vtable.table_size;
const uint16_t table_size = vtable->table_size;
uint64_t table_end_offset = table_offset + table_size;
if (!IsValidOffset(table_end_offset - 1)) {
@@ -516,7 +533,7 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
// not by their IDs. So copy them over to another vector that we can sort on
// the offset_from_table property.
std::vector<VTable::Entry> fields;
for (const auto &vtable_field : vtable.fields) {
for (const auto &vtable_field : vtable->fields) {
fields.push_back(vtable_field.second);
}
@@ -707,7 +724,8 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
regions.push_back(MakeBinaryRegion(
field_offset, sizeof(uint32_t), BinaryRegionType::UOffset, 0,
offset_of_next_item, offset_field_comment));
BuildVector(offset_of_next_item, table, field, table_offset, vtable);
BuildVector(offset_of_next_item, table, field, table_offset,
vtable->fields);
} break;
case reflection::BaseType::Union: {
@@ -716,8 +734,8 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
// The union type field is always one less than the union itself.
const uint16_t union_type_id = field->id() - 1;
auto vtable_field = vtable.fields.find(union_type_id);
if (vtable_field == vtable.fields.end()) {
auto vtable_field = vtable->fields.find(union_type_id);
if (vtable_field == vtable->fields.end()) {
// TODO(dbaileychess): need to capture this error condition.
break;
}
@@ -959,11 +977,10 @@ void BinaryAnnotator::BuildString(const uint64_t string_offset,
BinarySectionType::String, std::move(regions)));
}
void BinaryAnnotator::BuildVector(const uint64_t vector_offset,
const reflection::Object *const table,
const reflection::Field *const field,
const uint64_t parent_table_offset,
const VTable &vtable) {
void BinaryAnnotator::BuildVector(
const uint64_t vector_offset, const reflection::Object *const table,
const reflection::Field *const field, const uint64_t parent_table_offset,
const std::map<uint16_t, VTable::Entry> vtable_fields) {
if (ContainsSection(vector_offset)) { return; }
BinaryRegionComment vector_length_comment;
@@ -1011,7 +1028,7 @@ void BinaryAnnotator::BuildVector(const uint64_t vector_offset,
regions.push_back(MakeBinaryRegion(vector_offset, sizeof(uint32_t),
BinaryRegionType::Uint32, 0, 0,
vector_length_comment));
// Consume the vector length offset.
uint64_t offset = vector_offset + sizeof(uint32_t);
switch (field->type()->element()) {
@@ -1079,6 +1096,7 @@ void BinaryAnnotator::BuildVector(const uint64_t vector_offset,
offset, sizeof(uint32_t), BinaryRegionType::UOffset, 0,
table_offset, vector_object_comment));
// Consume the offset to the table.
offset += sizeof(uint32_t);
BuildTable(table_offset, BinarySectionType::Table, object);
@@ -1135,8 +1153,8 @@ void BinaryAnnotator::BuildVector(const uint64_t vector_offset,
// location.
const uint16_t union_type_vector_id = field->id() - 1;
auto vtable_entry = vtable.fields.find(union_type_vector_id);
if (vtable_entry == vtable.fields.end()) {
auto vtable_entry = vtable_fields.find(union_type_vector_id);
if (vtable_entry == vtable_fields.end()) {
// TODO(dbaileychess): need to capture this error condition.
break;
}

View File

@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_BINARY_ANNOTATOR_H_
#define FLATBUFFERS_BINARY_ANNOTATOR_H_
#include <list>
#include <map>
#include <string>
#include <vector>
@@ -52,8 +53,8 @@ enum class BinaryRegionType {
template<typename T>
static inline std::string ToHex(T i, size_t width = sizeof(T)) {
std::stringstream stream;
stream << std::hex << std::uppercase << std::setfill('0') << std::setw(static_cast<int>(width))
<< i;
stream << std::hex << std::uppercase << std::setfill('0')
<< std::setw(static_cast<int>(width)) << i;
return stream.str();
}
@@ -257,6 +258,8 @@ class BinaryAnnotator {
uint16_t offset_from_table = 0;
};
const reflection::Object *referring_table;
// Field ID -> {field def, offset from table}
std::map<uint16_t, Entry> fields;
@@ -266,8 +269,12 @@ class BinaryAnnotator {
uint64_t BuildHeader(uint64_t offset);
void BuildVTable(uint64_t offset, const reflection::Object *table,
uint64_t offset_of_referring_table);
// VTables can be shared across instances or even across objects. This
// attempts to get an existing vtable given the offset and table type,
// otherwise it will built the vtable, memorize it, and return the built
// VTable. Returns nullptr if building the VTable fails.
VTable *GetOrBuildVTable(uint64_t offset, const reflection::Object *table,
uint64_t offset_of_referring_table);
void BuildTable(uint64_t offset, const BinarySectionType type,
const reflection::Object *table);
@@ -281,7 +288,7 @@ class BinaryAnnotator {
void BuildVector(uint64_t offset, const reflection::Object *table,
const reflection::Field *field, uint64_t parent_table_offset,
const VTable &vtable);
const std::map<uint16_t, VTable::Entry> vtable_fields);
std::string BuildUnion(uint64_t offset, uint8_t realized_type,
const reflection::Field *field);
@@ -382,7 +389,7 @@ class BinaryAnnotator {
const uint64_t binary_length_;
// Map of binary offset to vtables, to dedupe vtables.
std::map<uint64_t, VTable> vtables_;
std::map<uint64_t, std::list<VTable>> vtables_;
// The annotated binary sections, index by their absolute offset.
std::map<uint64_t, BinarySection> sections_;

View File

@@ -115,6 +115,8 @@ const static FlatCOption flatc_options[] = {
{ "", "gen-compare", "", "Generate operator== for object-based API types." },
{ "", "gen-nullable", "",
"Add Clang _Nullable for C++ pointer. or @Nullable for Java" },
{ "", "java-package-prefix", "",
"Add a prefix to the generated package name for Java." },
{ "", "java-checkerframe", "", "Add @Pure for Java." },
{ "", "gen-generated", "", "Add @Generated annotation for Java." },
{ "", "gen-jvmstatic", "",
@@ -166,10 +168,18 @@ const static FlatCOption flatc_options[] = {
"Allow binaries without file_identifier to be read. This may crash flatc "
"given a mismatched schema." },
{ "", "size-prefixed", "", "Input binaries are size prefixed buffers." },
{ "", "proto", "", "Input is a .proto, translate to .fbs." },
{ "", "proto-namespace-suffix", "SUFFIX",
"Add this namespace to any flatbuffers generated from protobufs." },
{ "", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions." },
{ "", "keep-proto-id", "", "Keep protobuf field ids in generated fbs file." },
{ "", "proto-id-gap", "",
"Action that should be taken when a gap between protobuf ids found. "
"Supported values: * "
"'nop' - do not care about gap * 'warn' - A warning message will be shown "
"about the gap in protobuf ids"
"(default) "
"* 'error' - An error message will be shown and the fbs generation will be "
"interrupted." },
{ "", "grpc", "", "Generate GRPC interfaces for the specified languages." },
{ "", "schema", "", "Serialize schemas instead of JSON (use with -b)." },
{ "", "bfbs-filenames", "PATH",
@@ -230,7 +240,11 @@ const static FlatCOption flatc_options[] = {
"Allow a nested_flatbuffer field to be parsed as a vector of bytes "
"in JSON, which is unsafe unless checked by a verifier afterwards." },
{ "", "ts-flat-files", "",
"Only generated one typescript file per .fbs file." },
"Generate a single typescript file per .fbs file. Implies "
"ts_entry_points." },
{ "", "ts-entry-points", "",
"Generate entry point typescript per namespace. Implies gen-all." },
{ "", "annotate-sparse-vectors", "", "Don't annotate every vector element." },
{ "", "annotate", "SCHEMA",
"Annotate the provided BINARY_FILE with the specified SCHEMA file." },
{ "", "no-leak-private-annotation", "",
@@ -238,6 +252,9 @@ const static FlatCOption flatc_options[] = {
"Currently this is required to generate private types in Rust" },
};
auto cmp = [](FlatCOption a, FlatCOption b) { return a.long_opt < b.long_opt; };
static std::set<FlatCOption, decltype(cmp)> language_options(cmp);
static void AppendTextWrappedString(std::stringstream &ss, std::string &text,
size_t max_col, size_t start_col) {
size_t max_line_length = max_col - start_col;
@@ -309,16 +326,17 @@ std::string FlatCompiler::GetShortUsageString(
const std::string &program_name) const {
std::stringstream ss;
ss << "Usage: " << program_name << " [";
// TODO(derekbailey): These should be generated from this.generators
for (size_t i = 0; i < params_.num_generators; ++i) {
const Generator &g = params_.generators[i];
AppendShortOption(ss, g.option);
for (const FlatCOption &option : language_options) {
AppendShortOption(ss, option);
ss << ", ";
}
for (const FlatCOption &option : flatc_options) {
AppendShortOption(ss, option);
ss << ", ";
}
ss.seekp(-2, ss.cur);
ss << "]... FILE... [-- BINARY_FILE...]";
std::string help = ss.str();
@@ -332,13 +350,12 @@ std::string FlatCompiler::GetUsageString(
std::stringstream ss;
ss << "Usage: " << program_name
<< " [OPTION]... FILE... [-- BINARY_FILE...]\n";
// TODO(derekbailey): These should be generated from this.generators
for (size_t i = 0; i < params_.num_generators; ++i) {
const Generator &g = params_.generators[i];
AppendOption(ss, g.option, 80, 25);
}
for (const FlatCOption &option : language_options) {
AppendOption(ss, option, 80, 25);
}
ss << "\n";
for (const FlatCOption &option : flatc_options) {
AppendOption(ss, option, 80, 25);
}
@@ -356,11 +373,12 @@ std::string FlatCompiler::GetUsageString(
return ss.str();
}
void FlatCompiler::AnnotateBinaries(
const uint8_t *binary_schema, const uint64_t binary_schema_size,
const std::string &schema_filename,
const std::vector<std::string> &binary_files) {
for (const std::string &filename : binary_files) {
void FlatCompiler::AnnotateBinaries(const uint8_t *binary_schema,
const uint64_t binary_schema_size,
const FlatCOptions &options) {
const std::string &schema_filename = options.annotate_schema;
for (const std::string &filename : options.filenames) {
std::string binary_contents;
if (!flatbuffers::LoadFile(filename.c_str(), true, &binary_contents)) {
Warn("unable to load binary file: " + filename);
@@ -376,13 +394,16 @@ void FlatCompiler::AnnotateBinaries(
auto annotations = binary_annotator.Annotate();
flatbuffers::AnnotatedBinaryTextGenerator::Options text_gen_opts;
text_gen_opts.include_vector_contents =
options.annotate_include_vector_contents;
// TODO(dbaileychess): Right now we just support a single text-based
// output of the annotated binary schema, which we generate here. We
// could output the raw annotations instead and have third-party tools
// use them to generate their own output.
flatbuffers::AnnotatedBinaryTextGenerator text_generator(
flatbuffers::AnnotatedBinaryTextGenerator::Options{}, annotations,
binary, binary_size);
text_gen_opts, annotations, binary, binary_size);
text_generator.Generate(filename, schema_filename);
}
@@ -394,9 +415,6 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
FlatCOptions options;
// Default all generates to disabled.
options.generator_enabled.resize(params_.num_generators, false);
options.program_name = std::string(argv[0]);
IDLOptions &opts = options.opts;
@@ -500,6 +518,9 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
Error("unknown case style: " + std::string(argv[argi]), true);
} else if (arg == "--gen-nullable") {
opts.gen_nullable = true;
} else if (arg == "--java-package-prefix") {
if (++argi >= argc) Error("missing prefix following: " + arg, true);
opts.java_package_prefix = argv[argi];
} else if (arg == "--java-checkerframework") {
opts.java_checkerframework = true;
} else if (arg == "--gen-generated") {
@@ -531,13 +552,23 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
opts.size_prefixed = true;
} else if (arg == "--") { // Separator between text and binary inputs.
options.binary_files_from = options.filenames.size();
} else if (arg == "--proto") {
opts.proto_mode = true;
} else if (arg == "--proto-namespace-suffix") {
if (++argi >= argc) Error("missing namespace suffix" + arg, true);
opts.proto_namespace_suffix = argv[argi];
} else if (arg == "--oneof-union") {
opts.proto_oneof_union = true;
} else if (arg == "--keep-proto-id") {
opts.keep_proto_id = true;
} else if (arg == "--proto-id-gap") {
if (++argi >= argc) Error("missing case style following: " + arg, true);
if (!strcmp(argv[argi], "nop"))
opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP;
else if (!strcmp(argv[argi], "warn"))
opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::WARNING;
else if (!strcmp(argv[argi], "error"))
opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::ERROR;
else
Error("unknown case style: " + std::string(argv[argi]), true);
} else if (arg == "--schema") {
options.schema_binary = true;
} else if (arg == "-M") {
@@ -607,52 +638,42 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
} else if (arg == "--json-nested-bytes") {
opts.json_nested_legacy_flatbuffers = true;
} else if (arg == "--ts-flat-files") {
opts.ts_flat_file = true;
opts.ts_flat_files = true;
opts.ts_entry_points = true;
opts.generate_all = true;
} else if (arg == "--ts-entry-points") {
opts.ts_entry_points = true;
opts.generate_all = true;
} else if (arg == "--ts-no-import-ext") {
opts.ts_no_import_ext = true;
} else if (arg == "--no-leak-private-annotation") {
opts.no_leak_private_annotations = true;
} else if (arg == "--annotate-sparse-vectors") {
options.annotate_include_vector_contents = false;
} else if (arg == "--annotate") {
if (++argi >= argc) Error("missing path following: " + arg, true);
options.annotate_schema = flatbuffers::PosixPath(argv[argi]);
} else {
// Look up if the command line argument refers to a code generator.
if (arg == "--proto") { opts.proto_mode = true; }
auto code_generator_it = code_generators_.find(arg);
if (code_generator_it != code_generators_.end()) {
std::shared_ptr<CodeGenerator> code_generator =
code_generator_it->second;
// TODO(derekbailey): remove in favor of just checking if
// generators.empty().
options.any_generator = true;
opts.lang_to_generate |= code_generator->Language();
if (code_generator->SupportsBfbsGeneration()) {
opts.binary_schema_comments = true;
options.requires_bfbs = true;
}
options.generators.push_back(std::move(code_generator));
} else {
// TODO(derekbailey): deprecate the following logic in favor of the
// code generator map above.
for (size_t i = 0; i < params_.num_generators; ++i) {
if (arg == "--" + params_.generators[i].option.long_opt ||
arg == "-" + params_.generators[i].option.short_opt) {
options.generator_enabled[i] = true;
options.any_generator = true;
opts.lang_to_generate |= params_.generators[i].lang;
if (params_.generators[i].bfbs_generator) {
opts.binary_schema_comments = true;
options.requires_bfbs = true;
}
goto found;
}
}
if (code_generator_it == code_generators_.end()) {
Error("unknown commandline argument: " + arg, true);
return options;
}
found:;
std::shared_ptr<CodeGenerator> code_generator =
code_generator_it->second;
// TODO(derekbailey): remove in favor of just checking if
// generators.empty().
options.any_generator = true;
opts.lang_to_generate |= code_generator->Language();
auto is_binary_schema = code_generator->SupportsBfbsGeneration();
opts.binary_schema_comments = is_binary_schema;
options.requires_bfbs = is_binary_schema;
options.generators.push_back(std::move(code_generator));
}
} else {
options.filenames.push_back(flatbuffers::PosixPath(argv[argi]));
@@ -863,58 +884,6 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
}
}
// TODO(derekbailey): Deprecate the following in favor to the above.
for (size_t i = 0; i < params_.num_generators; ++i) {
if (options.generator_enabled[i]) {
if (!options.print_make_rules) {
flatbuffers::EnsureDirExists(options.output_path);
// Prefer bfbs generators if present.
if (params_.generators[i].bfbs_generator) {
const GeneratorStatus status =
params_.generators[i].bfbs_generator->Generate(bfbs_buffer,
bfbs_length);
if (status != OK) {
Error(std::string("Unable to generate ") +
params_.generators[i].lang_name + " for " + filebase +
" using bfbs generator.");
}
} else {
if ((!params_.generators[i].schema_only ||
(is_schema || is_binary_schema)) &&
!params_.generators[i].generate(*parser, options.output_path,
filebase)) {
Error(std::string("Unable to generate ") +
params_.generators[i].lang_name + " for " + filebase);
}
}
} else {
if (params_.generators[i].make_rule == nullptr) {
Error(std::string("Cannot generate make rule for ") +
params_.generators[i].lang_name);
} else {
std::string make_rule = params_.generators[i].make_rule(
*parser, options.output_path, filename);
if (!make_rule.empty())
printf("%s\n",
flatbuffers::WordWrap(make_rule, 80, " ", " \\").c_str());
}
}
if (options.grpc_enabled) {
if (params_.generators[i].generateGRPC != nullptr) {
if (!params_.generators[i].generateGRPC(
*parser, options.output_path, filebase)) {
Error(std::string("Unable to generate GRPC interface for ") +
params_.generators[i].lang_name);
}
} else {
Warn(std::string("GRPC interface generator not implemented for ") +
params_.generators[i].lang_name);
}
}
}
}
if (!opts.root_type.empty()) {
if (!parser->SetRootType(opts.root_type.c_str()))
Error("unknown root type: " + opts.root_type);
@@ -922,8 +891,6 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
Error("root type must be a table");
}
if (opts.proto_mode) GenerateFBS(*parser, options.output_path, filebase);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
@@ -933,10 +900,6 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
}
int FlatCompiler::Compile(const FlatCOptions &options) {
if (params_.generators == nullptr || params_.num_generators == 0) {
return 0;
}
// TODO(derekbailey): change to std::optional<Parser>
Parser conform_parser = GetConformParser(options);
@@ -984,25 +947,22 @@ int FlatCompiler::Compile(const FlatCOptions &options) {
}
// Annotate the provided files with the binary_schema.
AnnotateBinaries(binary_schema, binary_schema_size, options.annotate_schema,
options.filenames);
AnnotateBinaries(binary_schema, binary_schema_size, options);
// We don't support doing anything else after annotating a binary.
return 0;
}
if (options.generators.empty()) {
Error("No generator registered");
return -1;
}
std::unique_ptr<Parser> parser = GenerateCode(options, conform_parser);
// Once all the files have been parsed, run any generators Parsing Completed
// function for final generation.
for (size_t i = 0; i < params_.num_generators; ++i) {
if (options.generator_enabled[i] &&
params_.generators[i].parsing_completed != nullptr) {
if (!params_.generators[i].parsing_completed(*parser,
options.output_path)) {
Error("failed running parsing completed for " +
std::string(params_.generators[i].lang_name));
}
for (const auto &code_generator : options.generators) {
if (code_generator->SupportsRootFileGeneration()) {
code_generator->GenerateRootFile(*parser, options.output_path);
}
}
@@ -1010,12 +970,31 @@ int FlatCompiler::Compile(const FlatCOptions &options) {
}
bool FlatCompiler::RegisterCodeGenerator(
const std::string &flag, std::shared_ptr<CodeGenerator> code_generator) {
if (code_generators_.find(flag) != code_generators_.end()) {
Error("multiple generators registered under: " + flag, false, false);
const FlatCOption &option, std::shared_ptr<CodeGenerator> code_generator) {
if (!option.short_opt.empty() &&
code_generators_.find("-" + option.short_opt) != code_generators_.end()) {
Error("multiple generators registered under: -" + option.short_opt, false,
false);
return false;
}
code_generators_[flag] = std::move(code_generator);
if (!option.short_opt.empty()) {
code_generators_["-" + option.short_opt] = code_generator;
}
if (!option.long_opt.empty() &&
code_generators_.find("--" + option.long_opt) != code_generators_.end()) {
Error("multiple generators registered under: --" + option.long_opt, false,
false);
return false;
}
if (!option.long_opt.empty()) {
code_generators_["--" + option.long_opt] = code_generator;
}
language_options.insert(option);
return true;
}

View File

@@ -23,8 +23,22 @@
#include "flatbuffers/code_generator.h"
#include "flatbuffers/flatc.h"
#include "flatbuffers/util.h"
#include "idl_gen_binary.h"
#include "idl_gen_cpp.h"
#include "idl_gen_csharp.h"
#include "idl_gen_dart.h"
#include "idl_gen_fbs.h"
#include "idl_gen_go.h"
#include "idl_gen_java.h"
#include "idl_gen_json_schema.h"
#include "idl_gen_kotlin.h"
#include "idl_gen_lobster.h"
#include "idl_gen_php.h"
#include "idl_gen_python.h"
#include "idl_gen_rust.h"
#include "idl_gen_swift.h"
#include "idl_gen_text.h"
#include "idl_gen_ts.h"
static const char *g_program_name = nullptr;
@@ -58,115 +72,103 @@ void LogCompilerError(const std::string &err) {
int main(int argc, const char *argv[]) {
const std::string flatbuffers_version(flatbuffers::FLATBUFFERS_VERSION());
std::unique_ptr<flatbuffers::BfbsGenerator> bfbs_gen_lua =
flatbuffers::NewLuaBfbsGenerator(flatbuffers_version);
std::unique_ptr<flatbuffers::BfbsGenerator> bfbs_gen_nim =
flatbuffers::NewNimBfbsGenerator(flatbuffers_version);
g_program_name = argv[0];
const flatbuffers::FlatCompiler::Generator generators[] = {
{ flatbuffers::GenerateBinary, "binary", false, nullptr,
flatbuffers::IDLOptions::kBinary,
flatbuffers::FlatCOption{
"b", "binary", "",
"Generate wire format binaries for any data definitions" },
flatbuffers::BinaryMakeRule, nullptr, nullptr },
{ flatbuffers::GenerateTextFile, "text", false, nullptr,
flatbuffers::IDLOptions::kJson,
flatbuffers::FlatCOption{
"t", "json", "", "Generate text output for any data definitions" },
flatbuffers::TextMakeRule, nullptr, nullptr },
{ flatbuffers::GenerateCPP, "C++", true, flatbuffers::GenerateCppGRPC,
flatbuffers::IDLOptions::kCpp,
flatbuffers::FlatCOption{ "c", "cpp", "",
"Generate C++ headers for tables/structs" },
flatbuffers::CPPMakeRule, nullptr, nullptr },
{ flatbuffers::GenerateGo, "Go", true, flatbuffers::GenerateGoGRPC,
flatbuffers::IDLOptions::kGo,
flatbuffers::FlatCOption{ "g", "go", "",
"Generate Go files for tables/structs" },
nullptr, nullptr, nullptr },
{ flatbuffers::GenerateJava, "Java", true, flatbuffers::GenerateJavaGRPC,
flatbuffers::IDLOptions::kJava,
flatbuffers::FlatCOption{ "j", "java", "",
"Generate Java classes for tables/structs" },
flatbuffers::JavaMakeRule, nullptr, nullptr },
{ flatbuffers::GenerateDart, "Dart", true, nullptr,
flatbuffers::IDLOptions::kDart,
flatbuffers::FlatCOption{ "d", "dart", "",
"Generate Dart classes for tables/structs" },
flatbuffers::DartMakeRule, nullptr, nullptr },
{ flatbuffers::GenerateTS, "TypeScript", true, flatbuffers::GenerateTSGRPC,
flatbuffers::IDLOptions::kTs,
flatbuffers::FlatCOption{ "T", "ts", "",
"Generate TypeScript code for tables/structs" },
flatbuffers::TSMakeRule, nullptr, nullptr },
{ flatbuffers::GenerateCSharp, "C#", true, nullptr,
flatbuffers::IDLOptions::kCSharp,
flatbuffers::FlatCOption{ "n", "csharp", "",
"Generate C# classes for tables/structs" },
flatbuffers::CSharpMakeRule, nullptr, nullptr },
{ flatbuffers::GeneratePython, "Python", true,
flatbuffers::GeneratePythonGRPC, flatbuffers::IDLOptions::kPython,
flatbuffers::FlatCOption{ "p", "python", "",
"Generate Python files for tables/structs" },
nullptr, nullptr, nullptr },
{ flatbuffers::GenerateLobster, "Lobster", true, nullptr,
flatbuffers::IDLOptions::kLobster,
flatbuffers::FlatCOption{ "", "lobster", "",
"Generate Lobster files for tables/structs" },
nullptr, nullptr, nullptr },
{ flatbuffers::GenerateLua, "Lua", true, nullptr,
flatbuffers::IDLOptions::kLua,
flatbuffers::FlatCOption{ "l", "lua", "",
"Generate Lua files for tables/structs" },
nullptr, bfbs_gen_lua.get(), nullptr },
{ flatbuffers::GenerateRust, "Rust", true, nullptr,
flatbuffers::IDLOptions::kRust,
flatbuffers::FlatCOption{ "r", "rust", "",
"Generate Rust files for tables/structs" },
flatbuffers::RustMakeRule, nullptr,
flatbuffers::GenerateRustModuleRootFile },
{ flatbuffers::GeneratePhp, "PHP", true, nullptr,
flatbuffers::IDLOptions::kPhp,
flatbuffers::FlatCOption{ "", "php", "",
"Generate PHP files for tables/structs" },
nullptr, nullptr, nullptr },
{ flatbuffers::GenerateKotlin, "Kotlin", true, nullptr,
flatbuffers::IDLOptions::kKotlin,
flatbuffers::FlatCOption{ "", "kotlin", "",
"Generate Kotlin classes for tables/structs" },
nullptr, nullptr, nullptr },
{ flatbuffers::GenerateJsonSchema, "JsonSchema", true, nullptr,
flatbuffers::IDLOptions::kJsonSchema,
flatbuffers::FlatCOption{ "", "jsonschema", "", "Generate Json schema" },
nullptr, nullptr, nullptr },
{ flatbuffers::GenerateSwift, "swift", true, flatbuffers::GenerateSwiftGRPC,
flatbuffers::IDLOptions::kSwift,
flatbuffers::FlatCOption{ "", "swift", "",
"Generate Swift files for tables/structs" },
nullptr, nullptr, nullptr },
{ nullptr, "Nim", true, nullptr, flatbuffers::IDLOptions::kNim,
flatbuffers::FlatCOption{ "", "nim", "",
"Generate Nim files for tables/structs" },
nullptr, bfbs_gen_nim.get(), nullptr },
};
flatbuffers::FlatCompiler::InitParams params;
params.generators = generators;
params.num_generators = sizeof(generators) / sizeof(generators[0]);
params.warn_fn = Warn;
params.error_fn = Error;
flatbuffers::FlatCompiler flatc(params);
std::shared_ptr<flatbuffers::CodeGenerator> cpp_generator =
flatbuffers::NewCppCodeGenerator();
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{
"b", "binary", "",
"Generate wire format binaries for any data definitions" },
flatbuffers::NewBinaryCodeGenerator());
flatc.RegisterCodeGenerator("--cpp", cpp_generator);
flatc.RegisterCodeGenerator("-c", cpp_generator);
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "c", "cpp", "",
"Generate C++ headers for tables/structs" },
flatbuffers::NewCppCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "n", "csharp", "",
"Generate C# classes for tables/structs" },
flatbuffers::NewCSharpCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "d", "dart", "",
"Generate Dart classes for tables/structs" },
flatbuffers::NewDartCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "proto", "",
"Input is a .proto, translate to .fbs" },
flatbuffers::NewFBSCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "g", "go", "",
"Generate Go files for tables/structs" },
flatbuffers::NewGoCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "j", "java", "",
"Generate Java classes for tables/structs" },
flatbuffers::NewJavaCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "jsonschema", "", "Generate Json schema" },
flatbuffers::NewJsonSchemaCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "kotlin", "",
"Generate Kotlin classes for tables/structs" },
flatbuffers::NewKotlinCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "lobster", "",
"Generate Lobster files for tables/structs" },
flatbuffers::NewLobsterCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "l", "lua", "",
"Generate Lua files for tables/structs" },
flatbuffers::NewLuaBfbsGenerator(flatbuffers_version));
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "nim", "",
"Generate Nim files for tables/structs" },
flatbuffers::NewNimBfbsGenerator(flatbuffers_version));
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "p", "python", "",
"Generate Python files for tables/structs" },
flatbuffers::NewPythonCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "php", "",
"Generate PHP files for tables/structs" },
flatbuffers::NewPhpCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "r", "rust", "",
"Generate Rust files for tables/structs" },
flatbuffers::NewRustCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{
"t", "json", "", "Generate text output for any data definitions" },
flatbuffers::NewTextCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "", "swift", "",
"Generate Swift files for tables/structs" },
flatbuffers::NewSwiftCodeGenerator());
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{ "T", "ts", "",
"Generate TypeScript code for tables/structs" },
flatbuffers::NewTsCodeGenerator());
// Create the FlatC options by parsing the command line arguments.
const flatbuffers::FlatCOptions &options =

92
src/idl_gen_binary.cpp Normal file
View File

@@ -0,0 +1,92 @@
/*
* 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.
*/
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_binary.h"
#include <limits>
#include <memory>
#include <string>
#include <unordered_set>
#include "flatbuffers/base.h"
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/flatc.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
namespace {
class BinaryCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateBinary(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
output = BinaryMakeRule(parser, path, filename);
return Status::OK;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return false; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kBinary; }
std::string LanguageName() const override { return "binary"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewBinaryCodeGenerator() {
return std::unique_ptr<BinaryCodeGenerator>(new BinaryCodeGenerator());
}
} // namespace flatbuffers

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2021 Google Inc. All rights reserved.
* Copyright 2023 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.
@@ -14,30 +14,19 @@
* limitations under the License.
*/
#ifndef FLATBUFFERS_BFBS_GENERATOR_H_
#define FLATBUFFERS_BFBS_GENERATOR_H_
#ifndef FLATBUFFERS_IDL_GEN_BINARY_H_
#define FLATBUFFERS_IDL_GEN_BINARY_H_
#include <cstdint>
#include <memory>
#include <string>
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
enum GeneratorStatus {
OK,
FAILED,
FAILED_VERIFICATION,
};
// A Flatbuffer Code Generator that receives a binary serialized reflection.fbs
// and generates code from it.
class BfbsGenerator {
public:
virtual ~BfbsGenerator() {}
// Generate code from the provided `buffer` of given `length`. The buffer is
// a serialized reflection.fbs.
virtual GeneratorStatus Generate(const uint8_t *buffer, int64_t length) = 0;
};
// Constructs a new Binary code generator.
std::unique_ptr<CodeGenerator> NewBinaryCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_BFBS_GENERATOR_H_
#endif // FLATBUFFERS_IDL_GEN_BINARY_H_

View File

@@ -16,6 +16,8 @@
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_cpp.h"
#include <limits>
#include <memory>
#include <string>
@@ -719,19 +721,11 @@ class CppGenerator : public BaseGenerator {
// Return a C++ type from the table in idl.h
std::string GenTypeBasic(const Type &type, bool user_facing_type) const {
// clang-format off
static const char *const ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
#CTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
// clang-format on
if (user_facing_type) {
if (type.enum_def) return WrapInNameSpace(*type.enum_def);
if (type.base_type == BASE_TYPE_BOOL) return "bool";
}
return ctypename[type.base_type];
return StringOf(type.base_type);
}
// Return a C++ pointer type, specialized to the actual struct/table types,
@@ -2245,54 +2239,153 @@ class CppGenerator : public BaseGenerator {
}
}
void GenComparatorForStruct(const StructDef &struct_def, size_t space_size,
const std::string lhs_struct_literal,
const std::string rhs_struct_literal) {
code_.SetValue("LHS_PREFIX", lhs_struct_literal);
code_.SetValue("RHS_PREFIX", rhs_struct_literal);
std::string space(space_size, ' ');
for (const auto &curr_field : struct_def.fields.vec) {
const auto curr_field_name = Name(*curr_field);
code_.SetValue("CURR_FIELD_NAME", curr_field_name);
code_.SetValue("LHS", lhs_struct_literal + "_" + curr_field_name);
code_.SetValue("RHS", rhs_struct_literal + "_" + curr_field_name);
const bool is_scalar = IsScalar(curr_field->value.type.base_type);
const bool is_array = IsArray(curr_field->value.type);
const bool is_struct = IsStruct(curr_field->value.type);
// If encouter a key field, call KeyCompareWithValue to compare this
// field.
if (curr_field->key) {
code_ += space +
"const auto {{RHS}} = {{RHS_PREFIX}}.{{CURR_FIELD_NAME}}();";
code_ += space +
"const auto {{CURR_FIELD_NAME}}_compare_result = "
"{{LHS_PREFIX}}.KeyCompareWithValue({{RHS}});";
code_ += space + "if ({{CURR_FIELD_NAME}}_compare_result != 0)";
code_ += space + " return {{CURR_FIELD_NAME}}_compare_result;";
continue;
}
code_ +=
space + "const auto {{LHS}} = {{LHS_PREFIX}}.{{CURR_FIELD_NAME}}();";
code_ +=
space + "const auto {{RHS}} = {{RHS_PREFIX}}.{{CURR_FIELD_NAME}}();";
if (is_scalar) {
code_ += space + "if ({{LHS}} != {{RHS}})";
code_ += space +
" return static_cast<int>({{LHS}} > {{RHS}}) - "
"static_cast<int>({{LHS}} < {{RHS}});";
} else if (is_array) {
const auto &elem_type = curr_field->value.type.VectorType();
code_ +=
space +
"for (::flatbuffers::uoffset_t i = 0; i < {{LHS}}->size(); i++) {";
code_ += space + " const auto {{LHS}}_elem = {{LHS}}->Get(i);";
code_ += space + " const auto {{RHS}}_elem = {{RHS}}->Get(i);";
if (IsScalar(elem_type.base_type)) {
code_ += space + " if ({{LHS}}_elem != {{RHS}}_elem)";
code_ += space +
" return static_cast<int>({{LHS}}_elem > {{RHS}}_elem) - "
"static_cast<int>({{LHS}}_elem < {{RHS}}_elem);";
code_ += space + "}";
} else if (IsStruct(elem_type)) {
if (curr_field->key) {
code_ += space +
"const auto {{CURR_FIELD_NAME}}_compare_result = "
"{{LHS_PREFIX}}.KeyCompareWithValue({{RHS}});";
code_ += space + "if ({{CURR_FIELD_NAME}}_compare_result != 0)";
code_ += space + " return {{CURR_FIELD_NAME}}_compare_result;";
continue;
}
GenComparatorForStruct(
*curr_field->value.type.struct_def, space_size + 2,
code_.GetValue("LHS") + "_elem", code_.GetValue("RHS") + "_elem");
code_ += space + "}";
}
} else if (is_struct) {
GenComparatorForStruct(*curr_field->value.type.struct_def, space_size,
code_.GetValue("LHS"), code_.GetValue("RHS"));
}
}
}
// Generate CompareWithValue method for a key field.
void GenKeyFieldMethods(const FieldDef &field) {
FLATBUFFERS_ASSERT(field.key);
const bool is_string = IsString(field.value.type);
const bool is_array = IsArray(field.value.type);
const bool is_struct = IsStruct(field.value.type);
// Generate KeyCompareLessThan function
code_ +=
" bool KeyCompareLessThan(const {{STRUCT_NAME}} * const o) const {";
if (is_string) {
// use operator< of ::flatbuffers::String
code_ += " return *{{FIELD_NAME}}() < *o->{{FIELD_NAME}}();";
} else if (is_array) {
const auto &elem_type = field.value.type.VectorType();
if (IsScalar(elem_type.base_type)) {
code_ += " return KeyCompareWithValue(o->{{FIELD_NAME}}()) < 0;";
}
} else if (is_array || is_struct) {
code_ += " return KeyCompareWithValue(o->{{FIELD_NAME}}()) < 0;";
} else {
code_ += " return {{FIELD_NAME}}() < o->{{FIELD_NAME}}();";
}
code_ += " }";
// Generate KeyCompareWithValue function
if (is_string) {
code_ += " int KeyCompareWithValue(const char *_{{FIELD_NAME}}) const {";
code_ += " return strcmp({{FIELD_NAME}}()->c_str(), _{{FIELD_NAME}});";
} else if (is_array) {
const auto &elem_type = field.value.type.VectorType();
std::string input_type = "::flatbuffers::Array<" +
GenTypeGet(elem_type, "", "", "", false) + ", " +
NumToString(elem_type.fixed_length) + ">";
code_.SetValue("INPUT_TYPE", input_type);
code_ +=
" int KeyCompareWithValue(const {{INPUT_TYPE}} *_{{FIELD_NAME}}"
") const {";
code_ +=
" const {{INPUT_TYPE}} *curr_{{FIELD_NAME}} = {{FIELD_NAME}}();";
code_ +=
" for (::flatbuffers::uoffset_t i = 0; i < "
"curr_{{FIELD_NAME}}->size(); i++) {";
if (IsScalar(elem_type.base_type)) {
std::string input_type = "::flatbuffers::Array<" +
GenTypeBasic(elem_type, false) + ", " +
NumToString(elem_type.fixed_length) + ">";
code_.SetValue("INPUT_TYPE", input_type);
code_ +=
" int KeyCompareWithValue(const {{INPUT_TYPE}} *_{{FIELD_NAME}}"
") const {";
code_ +=
" const {{INPUT_TYPE}} *curr_{{FIELD_NAME}} = {{FIELD_NAME}}();";
code_ +=
" for (::flatbuffers::uoffset_t i = 0; i < "
"curr_{{FIELD_NAME}}->size(); i++) {";
code_ += " const auto lhs = curr_{{FIELD_NAME}}->Get(i);";
code_ += " const auto rhs = _{{FIELD_NAME}}->Get(i);";
code_ += " if(lhs != rhs)";
code_ += " if (lhs != rhs)";
code_ +=
" return static_cast<int>(lhs > rhs)"
" - static_cast<int>(lhs < rhs);";
code_ += " }";
code_ += " return 0;";
} else if (IsStruct(elem_type)) {
code_ +=
" const auto &lhs_{{FIELD_NAME}} = "
"*(curr_{{FIELD_NAME}}->Get(i));";
code_ +=
" const auto &rhs_{{FIELD_NAME}} = "
"*(_{{FIELD_NAME}}->Get(i));";
GenComparatorForStruct(*elem_type.struct_def, 6,
"lhs_" + code_.GetValue("FIELD_NAME"),
"rhs_" + code_.GetValue("FIELD_NAME"));
}
code_ += " }";
code_ += " return 0;";
} else if (is_struct) {
const auto *struct_def = field.value.type.struct_def;
code_.SetValue("INPUT_TYPE",
GenTypeGet(field.value.type, "", "", "", false));
code_ +=
" int KeyCompareWithValue(const {{INPUT_TYPE}} &_{{FIELD_NAME}}) "
"const {";
code_ += " const auto &lhs_{{FIELD_NAME}} = {{FIELD_NAME}}();";
code_ += " const auto &rhs_{{FIELD_NAME}} = _{{FIELD_NAME}};";
GenComparatorForStruct(*struct_def, 4,
"lhs_" + code_.GetValue("FIELD_NAME"),
"rhs_" + code_.GetValue("FIELD_NAME"));
code_ += " return 0;";
} else {
FLATBUFFERS_ASSERT(IsScalar(field.value.type.base_type));
auto type = GenTypeBasic(field.value.type, false);
@@ -3885,8 +3978,8 @@ class CppCodeGenerator : public CodeGenerator {
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void) buffer;
(void) length;
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
@@ -3903,10 +3996,19 @@ class CppCodeGenerator : public CodeGenerator {
return Status::OK;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kCpp; }
std::string LanguageName() const override { return "C++"; }

29
src/idl_gen_cpp.h Normal file
View File

@@ -0,0 +1,29 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_CPP_H_
#define FLATBUFFERS_IDL_GEN_CPP_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Cpp code generator.
std::unique_ptr<CodeGenerator> NewCppCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_CPP_H_

View File

@@ -16,6 +16,8 @@
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_csharp.h"
#include <unordered_set>
#include "flatbuffers/code_generators.h"
@@ -475,8 +477,9 @@ class CSharpGenerator : public BaseGenerator {
const std::string &offset) const {
// Use the generated type directly, to properly handle default values that
// might not be written to the buffer.
return GetObjectConstructor(struct_def, data_buffer, offset) + "." +
Name(*key_field);
auto name = Name(*key_field);
if (name == struct_def.name) { name += "_"; }
return GetObjectConstructor(struct_def, data_buffer, offset) + "." + name;
}
// Direct mutation is only allowed for scalar fields.
@@ -655,7 +658,7 @@ class CSharpGenerator : public BaseGenerator {
// Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {";
code += " FlatBufferConstants.";
code += "FLATBUFFERS_23_1_20(); ";
code += "FLATBUFFERS_23_3_3(); ";
code += "}\n";
// Generate a special accessor for the table that when used as the root
@@ -1301,6 +1304,8 @@ class CSharpGenerator : public BaseGenerator {
// because `key_field` is not set for struct
if (struct_def.has_key && !struct_def.fixed) {
FLATBUFFERS_ASSERT(key_field);
auto name = Name(*key_field);
if (name == struct_def.name) { name += "_"; }
code += "\n public static VectorOffset ";
code += "CreateSortedVectorOf" + struct_def.name;
code += "(FlatBufferBuilder builder, ";
@@ -1330,8 +1335,7 @@ class CSharpGenerator : public BaseGenerator {
"(start + middle), bb);\n";
code += " obj_.__assign(tableOffset, bb);\n";
code +=
" int comp = obj_." + Name(*key_field) + ".CompareTo(key);\n";
code += " int comp = obj_." + name + ".CompareTo(key);\n";
code += " if (comp > 0) {\n";
code += " span = middle;\n";
code += " } else if (comp < 0) {\n";
@@ -2256,4 +2260,58 @@ bool GenerateCSharp(const Parser &parser, const std::string &path,
return generator.generate();
}
namespace {
class CSharpCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateCSharp(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
output = CSharpMakeRule(parser, path, filename);
return Status::OK;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kCSharp; }
std::string LanguageName() const override { return "CSharp"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewCSharpCodeGenerator() {
return std::unique_ptr<CSharpCodeGenerator>(new CSharpCodeGenerator());
}
} // namespace flatbuffers

29
src/idl_gen_csharp.h Normal file
View File

@@ -0,0 +1,29 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_CSHARP_H_
#define FLATBUFFERS_IDL_GEN_CSHARP_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new CSharp code generator.
std::unique_ptr<CodeGenerator> NewCSharpCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_CSHARP_H_

View File

@@ -15,6 +15,8 @@
*/
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_dart.h"
#include <cassert>
#include <cmath>
@@ -1142,4 +1144,58 @@ std::string DartMakeRule(const Parser &parser, const std::string &path,
return make_rule;
}
namespace {
class DartCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateDart(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
output = DartMakeRule(parser, path, filename);
return Status::OK;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kDart; }
std::string LanguageName() const override { return "Dart"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewDartCodeGenerator() {
return std::unique_ptr<DartCodeGenerator>(new DartCodeGenerator());
}
} // namespace flatbuffers

29
src/idl_gen_dart.h Normal file
View File

@@ -0,0 +1,29 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_DART_H_
#define FLATBUFFERS_IDL_GEN_DART_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Dart code generator.
std::unique_ptr<CodeGenerator> NewDartCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_DART_H_

View File

@@ -15,7 +15,13 @@
*/
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_fbs.h"
#include <unordered_map>
#include <utility>
#include <vector>
#include "flatbuffers/code_generator.h"
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
@@ -34,11 +40,191 @@ static std::string GenType(const Type &type, bool underlying = false) {
return type.enum_def->defined_namespace->GetFullyQualifiedName(
type.enum_def->name);
} else {
return kTypeNames[type.base_type];
return TypeName(type.base_type);
}
}
}
static bool HasFieldWithId(const std::vector<FieldDef *> &fields) {
static const std::string ID = "id";
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
return true;
}
}
return false;
}
static bool HasNonPositiveFieldId(const std::vector<FieldDef *> &fields) {
static const std::string ID = "id";
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
if (!done) { return true; }
}
}
return false;
}
static bool HasFieldIdFromReservedIds(
const std::vector<FieldDef *> &fields,
const std::vector<voffset_t> &reserved_ids) {
static const std::string ID = "id";
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
if (!done) { return true; }
auto id_it =
std::find(std::begin(reserved_ids), std::end(reserved_ids), proto_id);
if (id_it != reserved_ids.end()) { return true; }
}
}
return false;
}
static std::vector<voffset_t> ExtractProtobufIds(
const std::vector<FieldDef *> &fields) {
static const std::string ID = "id";
std::vector<voffset_t> used_proto_ids;
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
if (done) { used_proto_ids.push_back(proto_id); }
}
}
return used_proto_ids;
}
static bool HasTwiceUsedId(const std::vector<FieldDef *> &fields) {
std::vector<voffset_t> used_proto_ids = ExtractProtobufIds(fields);
std::sort(std::begin(used_proto_ids), std::end(used_proto_ids));
for (auto it = std::next(std::begin(used_proto_ids));
it != std::end(used_proto_ids); it++) {
if (*it == *std::prev(it)) { return true; }
}
return false;
}
static bool HasGapInProtoId(const std::vector<FieldDef *> &fields) {
std::vector<voffset_t> used_proto_ids = ExtractProtobufIds(fields);
std::sort(std::begin(used_proto_ids), std::end(used_proto_ids));
for (auto it = std::next(std::begin(used_proto_ids));
it != std::end(used_proto_ids); it++) {
if (*it != *std::prev(it) + 1) { return true; }
}
return false;
}
static bool ProtobufIdSanityCheck(const StructDef &struct_def,
IDLOptions::ProtoIdGapAction gap_action) {
const auto &fields = struct_def.fields.vec;
if (HasNonPositiveFieldId(fields)) {
// TODO: Use LogCompilerWarn
fprintf(stderr, "Field id in struct %s has a non positive number value\n",
struct_def.name.c_str());
return false;
}
if (HasTwiceUsedId(fields)) {
// TODO: Use LogCompilerWarn
fprintf(stderr, "Fields in struct %s have used an id twice\n",
struct_def.name.c_str());
return false;
}
if (HasFieldIdFromReservedIds(fields, struct_def.reserved_ids)) {
// TODO: Use LogCompilerWarn
fprintf(stderr, "Fields in struct %s use id from reserved ids\n",
struct_def.name.c_str());
return false;
}
if (gap_action != IDLOptions::ProtoIdGapAction::NO_OP) {
if (HasGapInProtoId(fields)) {
// TODO: Use LogCompilerWarn
fprintf(stderr, "Fields in struct %s have gap between ids\n",
struct_def.name.c_str());
if (gap_action == IDLOptions::ProtoIdGapAction::ERROR) { return false; }
}
}
return true;
}
struct ProtobufToFbsIdMap {
using FieldName = std::string;
using FieldID = voffset_t;
using FieldNameToIdMap = std::unordered_map<FieldName, FieldID>;
FieldNameToIdMap field_to_id;
bool successful = false;
};
static ProtobufToFbsIdMap MapProtoIdsToFieldsId(
const StructDef &struct_def, IDLOptions::ProtoIdGapAction gap_action) {
const auto &fields = struct_def.fields.vec;
if (!HasFieldWithId(fields)) {
ProtobufToFbsIdMap result;
result.successful = true;
return result;
}
if (!ProtobufIdSanityCheck(struct_def, gap_action)) { return {}; }
static constexpr int UNION_ID = -1;
using ProtoIdFieldNamePair = std::pair<int, std::string>;
std::vector<ProtoIdFieldNamePair> proto_ids;
for (const auto *field : fields) {
const auto *id_attribute = field->attributes.Lookup("id");
if (id_attribute != nullptr) {
// When we have union but do not use union flag to keep them
if (id_attribute->constant.empty() &&
field->value.type.base_type == BASE_TYPE_UNION) {
proto_ids.emplace_back(UNION_ID, field->name);
} else {
voffset_t proto_id = 0;
StringToNumber(id_attribute->constant.c_str(), &proto_id);
proto_ids.emplace_back(proto_id, field->name);
}
} else {
// TODO: Use LogCompilerWarn
fprintf(stderr, "Fields id in struct %s is missing\n",
struct_def.name.c_str());
return {};
}
}
std::sort(
std::begin(proto_ids), std::end(proto_ids),
[](const ProtoIdFieldNamePair &rhs, const ProtoIdFieldNamePair &lhs) {
return rhs.first < lhs.first;
});
struct ProtobufToFbsIdMap proto_to_fbs;
voffset_t id = 0;
for (const auto &element : proto_ids) {
if (element.first == UNION_ID) { id++; }
proto_to_fbs.field_to_id.emplace(element.second, id++);
}
proto_to_fbs.successful = true;
return proto_to_fbs;
}
static void GenNameSpace(const Namespace &name_space, std::string *_schema,
const Namespace **last_namespace) {
if (*last_namespace == &name_space) return;
@@ -79,8 +265,9 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
int num_includes = 0;
for (auto it = parser.included_files_.begin();
it != parser.included_files_.end(); ++it) {
if (it->second.empty())
if (it->second.empty()) {
continue;
}
std::string basename;
if(parser.opts.keep_prefix) {
basename = flatbuffers::StripExtension(it->second);
@@ -94,6 +281,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
if (num_includes) schema += "\n";
// clang-format on
}
// Generate code for all the enum declarations.
const Namespace *last_namespace = nullptr;
for (auto enum_def_it = parser.enums_.vec.begin();
@@ -104,18 +292,22 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
}
GenNameSpace(*enum_def.defined_namespace, &schema, &last_namespace);
GenComment(enum_def.doc_comment, &schema, nullptr);
if (enum_def.is_union)
if (enum_def.is_union) {
schema += "union " + enum_def.name;
else
} else {
schema += "enum " + enum_def.name + " : ";
}
schema += GenType(enum_def.underlying_type, true) + " {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
GenComment(ev.doc_comment, &schema, nullptr, " ");
if (enum_def.is_union)
if (enum_def.is_union) {
schema += " " + GenType(ev.union_type) + ",\n";
else
} else {
schema += " " + ev.name + " = " + enum_def.ToString(ev) + ",\n";
}
}
schema += "}\n\n";
}
@@ -123,9 +315,14 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
++it) {
StructDef &struct_def = **it;
const auto proto_fbs_ids =
MapProtoIdsToFieldsId(struct_def, parser.opts.proto_id_gap_action);
if (!proto_fbs_ids.successful) { return {}; }
if (parser.opts.include_dependence_headers && struct_def.generated) {
continue;
}
GenNameSpace(*struct_def.defined_namespace, &schema, &last_namespace);
GenComment(struct_def.doc_comment, &schema, nullptr);
schema += "table " + struct_def.name + " {\n";
@@ -136,8 +333,26 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
GenComment(field.doc_comment, &schema, nullptr, " ");
schema += " " + field.name + ":" + GenType(field.value.type);
if (field.value.constant != "0") schema += " = " + field.value.constant;
if (field.IsRequired()) schema += " (required)";
if (field.key) schema += " (key)";
std::vector<std::string> attributes;
if (field.IsRequired()) attributes.push_back("required");
if (field.key) attributes.push_back("key");
if (parser.opts.keep_proto_id) {
auto it = proto_fbs_ids.field_to_id.find(field.name);
if (it != proto_fbs_ids.field_to_id.end()) {
attributes.push_back("id: " + NumToString(it->second));
} // If not found it means we do not have any ids
}
if (!attributes.empty()) {
schema += " (";
for (const auto &attribute : attributes) {
schema += attribute + ",";
}
schema.pop_back();
schema += ")";
}
schema += ";\n";
}
}
@@ -148,8 +363,73 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &file_name) {
return SaveFile((path + file_name + ".fbs").c_str(),
GenerateFBS(parser, file_name), false);
const std::string fbs = GenerateFBS(parser, file_name);
if (fbs.empty()) { return false; }
// TODO: Use LogCompilerWarn
fprintf(stderr,
"When you use --proto, that you should check for conformity "
"yourself, using the existing --conform");
return SaveFile((path + file_name + ".fbs").c_str(), fbs, false);
}
namespace {
class FBSCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateFBS(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return false; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kProto; }
std::string LanguageName() const override { return "proto"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewFBSCodeGenerator() {
return std::unique_ptr<FBSCodeGenerator>(new FBSCodeGenerator());
}
} // namespace flatbuffers

28
src/idl_gen_fbs.h Normal file
View File

@@ -0,0 +1,28 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_FBS_H_
#define FLATBUFFERS_IDL_GEN_FBS_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
std::unique_ptr<CodeGenerator> NewFBSCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_FBS_H_

View File

@@ -16,6 +16,8 @@
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_go.h"
#include <algorithm>
#include <cmath>
#include <sstream>
@@ -1581,4 +1583,59 @@ bool GenerateGo(const Parser &parser, const std::string &path,
return generator.generate();
}
namespace {
class GoCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateGo(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateGoGRPC(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kGo; }
std::string LanguageName() const override { return "Go"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewGoCodeGenerator() {
return std::unique_ptr<GoCodeGenerator>(new GoCodeGenerator());
}
} // namespace flatbuffers

29
src/idl_gen_go.h Normal file
View File

@@ -0,0 +1,29 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_GO_H_
#define FLATBUFFERS_IDL_GEN_GO_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Go code generator.
std::unique_ptr<CodeGenerator> NewGoCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_GO_H_

View File

@@ -16,6 +16,8 @@
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_java.h"
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
@@ -87,11 +89,21 @@ class JavaGenerator : public BaseGenerator {
public:
JavaGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
const std::string &file_name,
const std::string &package_prefix)
: BaseGenerator(parser, path, file_name, "", ".", "java"),
cur_name_space_(nullptr),
cur_name_space_(nullptr),
namer_(WithFlagOptions(JavaDefaultConfig(), parser.opts, path),
JavaKeywords()) {}
JavaKeywords()) {
if (!package_prefix.empty()) {
std::istringstream iss(package_prefix);
std::string component;
while(std::getline(iss, component, '.')) {
package_prefix_ns_.components.push_back(component);
}
package_prefix_ = package_prefix_ns_.GetFullyQualifiedName("") + ".";
}
}
JavaGenerator &operator=(const JavaGenerator &);
bool generate() {
@@ -171,7 +183,13 @@ class JavaGenerator : public BaseGenerator {
std::string code;
code = "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
const std::string namespace_name = FullNamespace(".", ns);
Namespace combined_ns = package_prefix_ns_;
std::copy(
ns.components.begin(),
ns.components.end(),
std::back_inserter(combined_ns.components));
const std::string namespace_name = FullNamespace(".", combined_ns);
if (!namespace_name.empty()) {
code += "package " + namespace_name + ";";
code += "\n\n";
@@ -205,7 +223,7 @@ class JavaGenerator : public BaseGenerator {
code += classcode;
if (!namespace_name.empty()) code += "";
const std::string dirs = namer_.Directories(ns);
const std::string dirs = namer_.Directories(combined_ns);
EnsureDirExists(dirs);
const std::string filename =
dirs + namer_.File(defname, /*skips=*/SkipFile::Suffix);
@@ -245,7 +263,8 @@ class JavaGenerator : public BaseGenerator {
switch (type.base_type) {
case BASE_TYPE_STRING: return "String";
case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
case BASE_TYPE_STRUCT: return namer_.NamespacedType(*type.struct_def);
case BASE_TYPE_STRUCT:
return Prefixed(namer_.NamespacedType(*type.struct_def));
case BASE_TYPE_UNION: FLATBUFFERS_FALLTHROUGH(); // else fall thru
default: return "Table";
}
@@ -349,8 +368,9 @@ class JavaGenerator : public BaseGenerator {
FLATBUFFERS_ASSERT(value.type.enum_def);
auto &enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
return enum_val ? namer_.NamespacedEnumVariant(enum_def, *enum_val)
: value.constant;
return
enum_val ? Prefixed(namer_.NamespacedEnumVariant(enum_def, *enum_val))
: value.constant;
}
std::string GenDefaultValue(const FieldDef &field) const {
@@ -683,7 +703,7 @@ class JavaGenerator : public BaseGenerator {
// Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {";
code += " Constants.";
code += "FLATBUFFERS_23_1_20(); ";
code += "FLATBUFFERS_23_3_3(); ";
code += "}\n";
// Generate a special accessor for the table that when used as the root
@@ -877,7 +897,7 @@ class JavaGenerator : public BaseGenerator {
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
auto &key_field = **kit;
if (key_field.key) {
auto qualified_name = namer_.NamespacedType(sd);
auto qualified_name = Prefixed(namer_.NamespacedType(sd));
code += " public " + qualified_name + " ";
code += namer_.Method(field) + "ByKey(";
code += GenTypeNameDest(key_field.value.type) + " key)";
@@ -955,7 +975,8 @@ class JavaGenerator : public BaseGenerator {
}
// generate object accessors if is nested_flatbuffer
if (field.nested_flatbuffer) {
auto nested_type_name = namer_.NamespacedType(*field.nested_flatbuffer);
auto nested_type_name =
Prefixed(namer_.NamespacedType(*field.nested_flatbuffer));
auto nested_method_name =
namer_.Field(field) + "As" + field.nested_flatbuffer->name;
auto get_nested_method_name = nested_method_name;
@@ -1435,7 +1456,7 @@ class JavaGenerator : public BaseGenerator {
// deleted when issue #6561 is fixed.
}
code += indent + " case " +
namer_.NamespacedEnumVariant(enum_def, ev) + ":\n";
Prefixed(namer_.NamespacedEnumVariant(enum_def, ev)) + ":\n";
auto actual_type = GenTypeGet(ev.union_type);
code += indent + " " + variable_name + "Value = " + field_name +
"(new " + actual_type + "()" + value_params + ");\n";
@@ -1633,7 +1654,8 @@ class JavaGenerator : public BaseGenerator {
case BASE_TYPE_UNION:
array_type = "int";
element_type =
namer_.NamespacedType(*field.value.type.enum_def) + "Union";
Prefixed(namer_.NamespacedType(*field.value.type.enum_def))
+ "Union";
to_array = element_type + ".pack(builder, _o." +
namer_.Method("get", property_name) + "()[_j])";
break;
@@ -1718,11 +1740,11 @@ class JavaGenerator : public BaseGenerator {
field.value.type.enum_def->underlying_type, false)) +
" _" + field_name + "Type = _o." + get_field +
"() == null ? " +
namer_.NamespacedType(*field.value.type.enum_def) +
Prefixed(namer_.NamespacedType(*field.value.type.enum_def)) +
".NONE : " + "_o." + get_field + "().getType();\n";
code += " " + GenOffsetType() + " _" + field_name + " = _o." +
get_field + "() == null ? 0 : " +
namer_.NamespacedType(*field.value.type.enum_def) +
Prefixed(namer_.NamespacedType(*field.value.type.enum_def)) +
"Union.pack(builder, _o." + get_field + "());\n";
break;
}
@@ -1974,7 +1996,8 @@ class JavaGenerator : public BaseGenerator {
type_name_length, new_type_name);
} else if (type.element == BASE_TYPE_UNION) {
if (wrap_in_namespace) {
type_name = namer_.NamespacedType(*type.enum_def) + "Union";
type_name =
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
} else {
type_name = namer_.Type(*type.enum_def) + "Union";
}
@@ -1984,7 +2007,8 @@ class JavaGenerator : public BaseGenerator {
case BASE_TYPE_UNION: {
if (wrap_in_namespace) {
type_name = namer_.NamespacedType(*type.enum_def) + "Union";
type_name =
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
} else {
type_name = namer_.Type(*type.enum_def) + "Union";
}
@@ -2018,13 +2042,15 @@ class JavaGenerator : public BaseGenerator {
type_name.replace(type_name.length() - type_name_length,
type_name_length, new_type_name);
} else if (type.element == BASE_TYPE_UNION) {
type_name = namer_.NamespacedType(*type.enum_def) + "Union";
type_name =
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
}
break;
}
case BASE_TYPE_UNION: {
type_name = namer_.NamespacedType(*type.enum_def) + "Union";
type_name =
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
break;
}
default: break;
@@ -2158,13 +2184,75 @@ class JavaGenerator : public BaseGenerator {
// prefixed by its namespace
const Namespace *cur_name_space_;
const IdlNamer namer_;
private:
std::string Prefixed(const std::string &str) const {
return package_prefix_ + str;
}
std::string package_prefix_;
Namespace package_prefix_ns_;
};
} // namespace java
bool GenerateJava(const Parser &parser, const std::string &path,
const std::string &file_name) {
java::JavaGenerator generator(parser, path, file_name);
java::JavaGenerator generator(parser, path, file_name,
parser.opts.java_package_prefix);
return generator.generate();
}
namespace {
class JavaCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateJava(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
output = JavaMakeRule(parser, path, filename);
return Status::OK;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateJavaGRPC(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kJava; }
std::string LanguageName() const override { return "Java"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewJavaCodeGenerator() {
return std::unique_ptr<JavaCodeGenerator>(new JavaCodeGenerator());
}
} // namespace flatbuffers

29
src/idl_gen_java.h Normal file
View File

@@ -0,0 +1,29 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_JAVA_H_
#define FLATBUFFERS_IDL_GEN_JAVA_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Java code generator.
std::unique_ptr<CodeGenerator> NewJavaCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_JAVA_H_

View File

@@ -14,6 +14,8 @@
* limitations under the License.
*/
#include "idl_gen_json_schema.h"
#include <algorithm>
#include <iostream>
#include <limits>
@@ -330,4 +332,63 @@ bool GenerateJsonSchema(const Parser &parser, std::string *json) {
*json = generator.getJson();
return true;
}
namespace {
class JsonSchemaCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateJsonSchema(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override {
return IDLOptions::kJsonSchema;
}
std::string LanguageName() const override { return "JsonSchema"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewJsonSchemaCodeGenerator() {
return std::unique_ptr<JsonSchemaCodeGenerator>(
new JsonSchemaCodeGenerator());
}
} // namespace flatbuffers

32
src/idl_gen_json_schema.h Normal file
View File

@@ -0,0 +1,32 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_JSON_SCHEMA_H_
#define FLATBUFFERS_IDL_GEN_JSON_SCHEMA_H_
#include <memory>
#include <string>
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new JsonSchema Code generator.
std::unique_ptr<CodeGenerator> NewJsonSchemaCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_JSON_SCHEMA_H_

View File

@@ -16,6 +16,8 @@
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_kotlin.h"
#include <functional>
#include <unordered_set>
@@ -524,7 +526,7 @@ class KotlinGenerator : public BaseGenerator {
// runtime.
GenerateFunOneLine(
writer, "validateVersion", "", "",
[&]() { writer += "Constants.FLATBUFFERS_23_1_20()"; },
[&]() { writer += "Constants.FLATBUFFERS_23_3_3()"; },
options.gen_jvmstatic);
GenerateGetRootAsAccessors(namer_.Type(struct_def), writer, options);
@@ -1595,4 +1597,61 @@ bool GenerateKotlin(const Parser &parser, const std::string &path,
kotlin::KotlinGenerator generator(parser, path, file_name);
return generator.generate();
}
namespace {
class KotlinCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateKotlin(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kKotlin; }
std::string LanguageName() const override { return "Kotlin"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewKotlinCodeGenerator() {
return std::unique_ptr<KotlinCodeGenerator>(new KotlinCodeGenerator());
}
} // namespace flatbuffers

29
src/idl_gen_kotlin.h Normal file
View File

@@ -0,0 +1,29 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_KOTLIN_H_
#define FLATBUFFERS_IDL_GEN_KOTLIN_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Kotlin code generator.
std::unique_ptr<CodeGenerator> NewKotlinCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_KOTLIN_H_

View File

@@ -14,6 +14,8 @@
* limitations under the License.
*/
#include "idl_gen_lobster.h"
#include <string>
#include <unordered_set>
@@ -402,4 +404,63 @@ bool GenerateLobster(const Parser &parser, const std::string &path,
return generator.generate();
}
namespace {
class LobsterCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateLobster(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return false; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override {
return IDLOptions::kLobster;
}
std::string LanguageName() const override { return "Lobster"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewLobsterCodeGenerator() {
return std::unique_ptr<LobsterCodeGenerator>(new LobsterCodeGenerator());
}
} // namespace flatbuffers

29
src/idl_gen_lobster.h Normal file
View File

@@ -0,0 +1,29 @@
/*
* Copyright 2023 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.
*/
#ifndef FLATBUFFERS_IDL_GEN_LOBSTER_H_
#define FLATBUFFERS_IDL_GEN_LOBSTER_H_
#include "flatbuffers/code_generator.h"
namespace flatbuffers {
// Constructs a new Lobster code generator.
std::unique_ptr<CodeGenerator> NewLobsterCodeGenerator();
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_GEN_LOBSTER_H_

View File

@@ -16,6 +16,8 @@
// independent from idl_parser, since this code is not needed for most clients
#include "idl_gen_lua.h"
#include <string>
#include <unordered_set>
@@ -744,4 +746,61 @@ bool GenerateLua(const Parser &parser, const std::string &path,
return generator.generate();
}
namespace {
class LuaCodeGenerator : public CodeGenerator {
public:
Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
if (!GenerateLua(parser, path, filename)) { return Status::ERROR; }
return Status::OK;
}
Status GenerateCode(const uint8_t *buffer, int64_t length) override {
(void)buffer;
(void)length;
return Status::NOT_IMPLEMENTED;
}
Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) override {
(void)parser;
(void)path;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
Status GenerateRootFile(const Parser &parser,
const std::string &path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
}
bool IsSchemaOnly() const override { return true; }
bool SupportsBfbsGeneration() const override { return true; }
bool SupportsRootFileGeneration() const override { return false; }
IDLOptions::Language Language() const override { return IDLOptions::kLua; }
std::string LanguageName() const override { return "Lua"; }
};
} // namespace
std::unique_ptr<CodeGenerator> NewLuaCodeGenerator() {
return std::unique_ptr<LuaCodeGenerator>(new LuaCodeGenerator());
}
} // namespace flatbuffers

Some files were not shown because too many files have changed in this diff Show More