From f42cc54c0d75d99a312db4835f435751152e7b1c Mon Sep 17 00:00:00 2001 From: Alexander Farber Date: Sun, 7 Sep 2025 10:24:04 +0200 Subject: [PATCH 01/10] Update FLATBUFFERS_TAG and package.json to 25.2.10 --- package-lock.json | 8 ++++---- package.json | 2 +- scripts/update_dependencies.sh | 3 ++- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 02b4c3fe3f9..da298023504 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,7 +36,7 @@ "documentation": "^14.0.2", "eslint": "9.26.0", "faucet": "^0.0.4", - "flatbuffers": "24.3.25", + "flatbuffers": "25.2.10", "husky": "^9.1.7", "jsonpath": "^1.1.1", "lint-staged": "^16.1.6", @@ -13120,9 +13120,9 @@ } }, "node_modules/flatbuffers": { - "version": "24.3.25", - "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-24.3.25.tgz", - "integrity": "sha512-3HDgPbgiwWMI9zVB7VYBHaMrbOO7Gm0v+yD2FV/sCKj+9NDeVL7BOBYUuhWAQGKWOzBo8S9WdMvV0eixO233XQ==", + "version": "25.2.10", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.2.10.tgz", + "integrity": "sha512-7JlN9ZvLDG1McO3kbX0k4v+SUAg48L1rIwEvN6ZQl/eCtgJz9UylTMzE9wrmYrcorgxm3CX/3T/w5VAub99UUw==", "dev": true, "license": "Apache-2.0" }, diff --git a/package.json b/package.json index 51893bc223e..d0ac939bbd0 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "documentation": "^14.0.2", "eslint": "9.26.0", "faucet": "^0.0.4", - "flatbuffers": "24.3.25", + "flatbuffers": "25.2.10", "husky": "^9.1.7", "jsonpath": "^1.1.1", "lint-staged": "^16.1.6", diff --git a/scripts/update_dependencies.sh b/scripts/update_dependencies.sh index 8a9137dc62d..f5c7042e866 100755 --- a/scripts/update_dependencies.sh +++ b/scripts/update_dependencies.sh @@ -31,8 +31,9 @@ FMT_PATH="fmtlib/fmt" FMT_TAG=v10.2.1 FLATBUFFERS_PATH="google/flatbuffers" -FLATBUFFERS_TAG=v24.3.25 +FLATBUFFERS_TAG=v25.2.10 +# Updates a git subtree dependency by pulling/adding the specified tag from GitHub function update_subtree () { name=$(echo "$1" | tr '[:lower:]' '[:upper:]') path=$(tmpvar=${name}_PATH && echo ${!tmpvar}) From 52c75e8e1555c755c158954337ab617ed866d6f2 Mon Sep 17 00:00:00 2001 From: Alexander Farber Date: Sun, 7 Sep 2025 10:51:31 +0200 Subject: [PATCH 02/10] Temporarily comment out other deps --- scripts/update_dependencies.sh | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/scripts/update_dependencies.sh b/scripts/update_dependencies.sh index f5c7042e866..37d4905680b 100755 --- a/scripts/update_dependencies.sh +++ b/scripts/update_dependencies.sh @@ -57,6 +57,16 @@ function update_subtree () { } ## Update dependencies -for dep in osmium sol rapidjson microtar protozero vtzero fmt flatbuffers; do +# for dep in osmium sol rapidjson microtar protozero vtzero fmt flatbuffers; do +for dep in flatbuffers; do update_subtree $dep done + +## Update npm package.json to match FLATBUFFERS_TAG +echo "Updating package.json flatbuffers version to match ${FLATBUFFERS_TAG}..." +FLATBUFFERS_VERSION=${FLATBUFFERS_TAG#v} # Remove 'v' prefix +npm install flatbuffers@${FLATBUFFERS_VERSION} + +## Regenerate FlatBuffers JavaScript bindings after update +echo "Regenerating FlatBuffers JavaScript bindings..." +flatc --ts --gen-name-strings -o features/support/ include/engine/api/flatbuffers/fbresult.fbs From 61126b67bc71ba931f3a32debfbdfef128b2df92 Mon Sep 17 00:00:00 2001 From: Alexander Farber Date: Sun, 7 Sep 2025 11:05:56 +0200 Subject: [PATCH 03/10] Remove flatbuffers directory to prepare for proper subtree add --- .../flatbuffers/.bazelci/presubmit.yml | 38 - third_party/flatbuffers/.bazelignore | 1 - third_party/flatbuffers/.bazelrc | 4 - third_party/flatbuffers/.clang-format | 13 - third_party/flatbuffers/.clang-tidy | 347 -- third_party/flatbuffers/.editorconfig | 8 - third_party/flatbuffers/.eslintrc.js | 13 - third_party/flatbuffers/.gitattributes | 2 - third_party/flatbuffers/.gitignore | 155 - third_party/flatbuffers/.npmrc | 1 - third_party/flatbuffers/BUILD.bazel | 139 - third_party/flatbuffers/CHANGELOG.md | 168 - .../flatbuffers/CMake/BuildFlatBuffers.cmake | 449 -- third_party/flatbuffers/CMake/DESCRIPTION.txt | 4 - .../flatbuffers/CMake/FindFlatBuffers.cmake | 61 - .../flatbuffers/CMake/PackageDebian.cmake | 25 - .../flatbuffers/CMake/PackageRedhat.cmake | 44 - third_party/flatbuffers/CMake/Version.cmake | 39 - .../CMake/flatbuffers-config-version.cmake.in | 11 - .../CMake/flatbuffers-config.cmake | 4 - .../flatbuffers/CMake/flatbuffers.pc.in | 9 - third_party/flatbuffers/CMakeLists.txt | 718 --- third_party/flatbuffers/CONTRIBUTING.md | 42 - third_party/flatbuffers/FlatBuffers.podspec | 21 - third_party/flatbuffers/Formatters.md | 22 - third_party/flatbuffers/LICENSE | 202 - third_party/flatbuffers/Package.swift | 36 - .../flatbuffers/Package@swift-5.5.swift | 37 - third_party/flatbuffers/README.md | 118 - third_party/flatbuffers/SECURITY.md | 11 - third_party/flatbuffers/WORKSPACE | 169 - third_party/flatbuffers/build_defs.bzl | 284 -- third_party/flatbuffers/composer.json | 18 - third_party/flatbuffers/conan/CMakeLists.txt | 12 - third_party/flatbuffers/conan/build.py | 50 - .../conan/test_package/CMakeLists.txt | 9 - .../conan/test_package/conanfile.py | 21 - .../conan/test_package/test_package.cpp | 35 - third_party/flatbuffers/conanfile.py | 75 - third_party/flatbuffers/grpc/BUILD.bazel | 0 third_party/flatbuffers/grpc/README.md | 42 - third_party/flatbuffers/grpc/boringssl.patch | 13 - third_party/flatbuffers/grpc/build_grpc.sh | 24 - .../grpc/build_grpc_with_cxx14.patch | 10 - .../flatbuffers/grpc/examples/README.md | 35 - .../flatbuffers/grpc/examples/go/format.sh | 36 - .../grpc/examples/go/greeter/.gitignore | 2 - .../grpc/examples/go/greeter/README.md | 25 - .../grpc/examples/go/greeter/client/go.mod | 11 - .../grpc/examples/go/greeter/client/main.go | 78 - .../go/greeter/models/Greeter_grpc.go | 158 - .../examples/go/greeter/models/HelloReply.go | 60 - .../go/greeter/models/HelloRequest.go | 60 - .../grpc/examples/go/greeter/models/go.mod | 8 - .../grpc/examples/go/greeter/server/go.mod | 11 - .../grpc/examples/go/greeter/server/main.go | 77 - .../flatbuffers/grpc/examples/greeter.fbs | 14 - .../grpc/examples/python/greeter/README.md | 12 - .../grpc/examples/python/greeter/client.py | 40 - .../python/greeter/models/HelloReply.py | 50 - .../python/greeter/models/HelloRequest.py | 50 - .../python/greeter/models/__init__.py | 0 .../python/greeter/models/greeter_grpc_fb.py | 52 - .../grpc/examples/python/greeter/server.py | 57 - .../grpc/examples/swift/Greeter/Package.swift | 58 - .../grpc/examples/swift/Greeter/README.md | 7 - .../Greeter/Sources/Model/greeter.grpc.swift | 145 - .../Sources/Model/greeter_generated.swift | 100 - .../swift/Greeter/Sources/client/main.swift | 107 - .../swift/Greeter/Sources/server/main.swift | 96 - .../grpc/examples/ts/greeter/README.md | 13 - .../grpc/examples/ts/greeter/package.json | 14 - .../grpc/examples/ts/greeter/src/client.ts | 34 - .../grpc/examples/ts/greeter/src/greeter.ts | 5 - .../ts/greeter/src/greeter_generated.ts | 4 - .../examples/ts/greeter/src/greeter_grpc.d.ts | 56 - .../examples/ts/greeter/src/greeter_grpc.js | 56 - .../grpc/examples/ts/greeter/src/models.ts | 6 - .../ts/greeter/src/models/hello-reply.ts | 60 - .../ts/greeter/src/models/hello-request.ts | 60 - .../grpc/examples/ts/greeter/src/server.ts | 49 - .../grpc/examples/ts/greeter/tsconfig.json | 17 - .../grpc/flatbuffers-java-grpc/pom.xml | 42 - .../flatbuffers/grpc/FlatbuffersUtils.java | 117 - third_party/flatbuffers/grpc/pom.xml | 219 - .../flatbuffers/grpc/samples/greeter/Makefile | 14 - .../grpc/samples/greeter/client.cpp | 85 - .../grpc/samples/greeter/greeter.fbs | 17 - .../grpc/samples/greeter/server.cpp | 81 - .../flatbuffers/grpc/src/compiler/BUILD.bazel | 131 - .../grpc/src/compiler/cpp_generator.cc | 1766 ------- .../grpc/src/compiler/cpp_generator.h | 106 - .../grpc/src/compiler/go_generator.cc | 507 -- .../grpc/src/compiler/go_generator.h | 33 - .../grpc/src/compiler/java_generator.cc | 1123 ----- .../grpc/src/compiler/java_generator.h | 85 - .../grpc/src/compiler/python_generator.cc | 151 - .../grpc/src/compiler/python_generator.h | 32 - .../grpc/src/compiler/schema_interface.h | 119 - .../grpc/src/compiler/swift_generator.cc | 440 -- .../grpc/src/compiler/swift_generator.h | 37 - .../grpc/src/compiler/ts_generator.cc | 523 -- .../grpc/src/compiler/ts_generator.h | 26 - third_party/flatbuffers/grpc/tests/BUILD | 17 - .../flatbuffers/grpc/tests/GameFactory.java | 42 - .../flatbuffers/grpc/tests/JavaGrpcTest.java | 242 - third_party/flatbuffers/grpc/tests/go_test.go | 102 - .../flatbuffers/grpc/tests/grpctest.cpp | 193 - .../flatbuffers/grpc/tests/grpctest.py | 174 - .../flatbuffers/grpc/tests/java-grpc-test.sh | 4 - .../grpc/tests/message_builder_test.cpp | 368 -- third_party/flatbuffers/grpc/tests/pom.xml | 73 - .../include/flatbuffers/allocator.h | 68 - .../flatbuffers/include/flatbuffers/array.h | 256 - .../flatbuffers/include/flatbuffers/base.h | 496 -- .../flatbuffers/include/flatbuffers/buffer.h | 199 - .../include/flatbuffers/buffer_ref.h | 53 - .../include/flatbuffers/code_generator.h | 97 - .../include/flatbuffers/code_generators.h | 238 - .../include/flatbuffers/default_allocator.h | 64 - .../include/flatbuffers/detached_buffer.h | 114 - .../include/flatbuffers/file_manager.h | 48 - .../include/flatbuffers/flatbuffer_builder.h | 1478 ------ .../include/flatbuffers/flatbuffers.h | 284 -- .../flatbuffers/include/flatbuffers/flatc.h | 131 - .../include/flatbuffers/flex_flat_util.h | 36 - .../include/flatbuffers/flexbuffers.h | 1938 ------- .../flatbuffers/include/flatbuffers/grpc.h | 299 -- .../flatbuffers/include/flatbuffers/hash.h | 127 - .../flatbuffers/include/flatbuffers/idl.h | 1272 ----- .../include/flatbuffers/minireflect.h | 421 -- .../include/flatbuffers/pch/flatc_pch.h | 39 - .../flatbuffers/include/flatbuffers/pch/pch.h | 38 - .../include/flatbuffers/reflection.h | 523 -- .../flatbuffers/reflection_generated.h | 1529 ------ .../include/flatbuffers/registry.h | 130 - .../include/flatbuffers/stl_emulation.h | 514 -- .../flatbuffers/include/flatbuffers/string.h | 69 - .../flatbuffers/include/flatbuffers/struct.h | 53 - .../flatbuffers/include/flatbuffers/table.h | 188 - .../flatbuffers/include/flatbuffers/util.h | 737 --- .../flatbuffers/include/flatbuffers/vector.h | 397 -- .../include/flatbuffers/vector_downward.h | 289 -- .../include/flatbuffers/verifier.h | 332 -- .../flatbuffers/lobster/flatbuffers.lobster | 312 -- third_party/flatbuffers/lua/flatbuffers.lua | 8 - .../lua/flatbuffers/binaryarray.lua | 128 - .../flatbuffers/lua/flatbuffers/builder.lua | 385 -- .../flatbuffers/lua/flatbuffers/compat.lua | 15 - .../lua/flatbuffers/compat_5_1.lua | 21 - .../lua/flatbuffers/compat_5_3.lua | 14 - .../lua/flatbuffers/compat_luajit.lua | 213 - .../flatbuffers/lua/flatbuffers/numTypes.lua | 219 - .../flatbuffers/lua/flatbuffers/view.lua | 124 - third_party/flatbuffers/mjs/README.md | 1 - .../flatbuffers/net/FlatBuffers/ByteBuffer.cs | 1041 ---- .../net/FlatBuffers/ByteBufferUtil.cs | 39 - .../net/FlatBuffers/FlatBufferBuilder.cs | 1023 ---- .../net/FlatBuffers/FlatBufferConstants.cs | 37 - .../net/FlatBuffers/FlatBufferVerify.cs | 822 --- .../net/FlatBuffers/Google.FlatBuffers.csproj | 42 - .../net/FlatBuffers/IFlatbufferObject.cs | 28 - .../flatbuffers/net/FlatBuffers/Offset.cs | 48 - .../flatbuffers/net/FlatBuffers/Struct.cs | 34 - .../flatbuffers/net/FlatBuffers/Table.cs | 212 - .../net/FlatBuffers/flatbuffers.png | Bin 5073 -> 0 bytes .../net/FlatBuffers/flatbuffers.snk | Bin 596 -> 0 bytes third_party/flatbuffers/package.json | 45 - third_party/flatbuffers/pnpm-lock.yaml | 1182 ----- .../flatbuffers/reflection/BUILD.bazel | 14 - .../flatbuffers/reflection/reflection.fbs | 156 - .../flatbuffers/reflection/ts/BUILD.bazel | 15 - .../flatbuffers/samples/SampleBinary.cs | 134 - .../flatbuffers/samples/SampleBinary.java | 112 - .../flatbuffers/samples/SampleBinary.kt | 109 - .../flatbuffers/samples/SampleBinary.php | 115 - .../flatbuffers/samples/csharp_sample.sh | 50 - .../flatbuffers/samples/dart_sample.sh | 49 - third_party/flatbuffers/samples/go.mod | 7 - third_party/flatbuffers/samples/go_sample.sh | 58 - .../flatbuffers/samples/java_sample.sh | 51 - .../flatbuffers/samples/javascript_sample.sh | 48 - .../flatbuffers/samples/kotlin_sample.sh | 60 - .../samples/lua/MyGame/Sample/Color.lua | 11 - .../samples/lua/MyGame/Sample/Equipment.lua | 10 - .../samples/lua/MyGame/Sample/Monster.lua | 122 - .../samples/lua/MyGame/Sample/Vec3.lua | 35 - .../samples/lua/MyGame/Sample/Weapon.lua | 42 - third_party/flatbuffers/samples/monster.bfbs | Bin 1888 -> 0 bytes third_party/flatbuffers/samples/monster.fbs | 33 - .../flatbuffers/samples/monster_generated.h | 923 ---- .../samples/monster_generated.lobster | 143 - .../samples/monster_generated.swift | 243 - .../flatbuffers/samples/monsterdata.json | 24 - third_party/flatbuffers/samples/php_sample.sh | 48 - .../flatbuffers/samples/python_sample.sh | 48 - .../flatbuffers/samples/rust_generated/mod.rs | 18 - .../my_game/sample/color_generated.rs | 100 - .../my_game/sample/equipment_generated.rs | 145 - .../my_game/sample/monster_generated.rs | 473 -- .../my_game/sample/vec_3_generated.rs | 194 - .../my_game/sample/weapon_generated.rs | 168 - .../flatbuffers/samples/sample_bfbs.cpp | 78 - .../flatbuffers/samples/sample_binary.cpp | 104 - .../flatbuffers/samples/sample_binary.go | 165 - .../flatbuffers/samples/sample_binary.lobster | 100 - .../flatbuffers/samples/sample_binary.lua | 107 - .../flatbuffers/samples/sample_binary.py | 137 - .../flatbuffers/samples/sample_binary.rs | 159 - .../flatbuffers/samples/sample_binary.swift | 83 - .../flatbuffers/samples/sample_flexbuffers.rs | 166 - .../samples/sample_flexbuffers_serde.rs | 81 - .../flatbuffers/samples/sample_text.cpp | 58 - .../flatbuffers/samples/sample_text.lobster | 43 - .../scripts/check-grpc-generated-code.py | 45 - .../scripts/check_generate_code.py | 63 - .../flatbuffers/scripts/clang-format-all.sh | 6 - .../flatbuffers/scripts/clang-format-git.sh | 6 - .../flatbuffers/scripts/clang-tidy-git.sh | 1 - .../flatbuffers/scripts/generate_code.py | 560 --- .../scripts/generate_grpc_examples.py | 70 - third_party/flatbuffers/scripts/release.sh | 86 - third_party/flatbuffers/scripts/util.py | 70 - third_party/flatbuffers/snap/snapcraft.yaml | 49 - third_party/flatbuffers/src/BUILD.bazel | 159 - .../src/annotated_binary_text_gen.cpp | 461 -- .../src/annotated_binary_text_gen.h | 75 - third_party/flatbuffers/src/bfbs_gen.h | 206 - third_party/flatbuffers/src/bfbs_gen_lua.cpp | 680 --- third_party/flatbuffers/src/bfbs_gen_lua.h | 33 - third_party/flatbuffers/src/bfbs_gen_nim.cpp | 698 --- third_party/flatbuffers/src/bfbs_gen_nim.h | 33 - third_party/flatbuffers/src/bfbs_namer.h | 51 - .../flatbuffers/src/binary_annotator.cpp | 1519 ------ .../flatbuffers/src/binary_annotator.h | 406 -- .../flatbuffers/src/code_generators.cpp | 339 -- .../flatbuffers/src/file_binary_writer.cpp | 49 - .../src/file_name_saving_file_manager.cpp | 49 - third_party/flatbuffers/src/file_writer.cpp | 47 - third_party/flatbuffers/src/flatc.cpp | 1031 ---- third_party/flatbuffers/src/flatc_main.cpp | 184 - third_party/flatbuffers/src/flathash.cpp | 116 - .../flatbuffers/src/idl_gen_binary.cpp | 128 - third_party/flatbuffers/src/idl_gen_binary.h | 32 - third_party/flatbuffers/src/idl_gen_cpp.cpp | 4196 ---------------- third_party/flatbuffers/src/idl_gen_cpp.h | 29 - .../flatbuffers/src/idl_gen_csharp.cpp | 2582 ---------- third_party/flatbuffers/src/idl_gen_csharp.h | 29 - third_party/flatbuffers/src/idl_gen_dart.cpp | 1198 ----- third_party/flatbuffers/src/idl_gen_dart.h | 29 - third_party/flatbuffers/src/idl_gen_fbs.cpp | 460 -- third_party/flatbuffers/src/idl_gen_fbs.h | 28 - third_party/flatbuffers/src/idl_gen_go.cpp | 1694 ------- third_party/flatbuffers/src/idl_gen_go.h | 29 - third_party/flatbuffers/src/idl_gen_grpc.cpp | 560 --- third_party/flatbuffers/src/idl_gen_java.cpp | 2251 --------- third_party/flatbuffers/src/idl_gen_java.h | 29 - .../flatbuffers/src/idl_gen_json_schema.cpp | 384 -- .../flatbuffers/src/idl_gen_json_schema.h | 32 - .../flatbuffers/src/idl_gen_kotlin.cpp | 1657 ------ third_party/flatbuffers/src/idl_gen_kotlin.h | 31 - .../flatbuffers/src/idl_gen_kotlin_kmp.cpp | 1619 ------ .../flatbuffers/src/idl_gen_lobster.cpp | 480 -- third_party/flatbuffers/src/idl_gen_lobster.h | 29 - third_party/flatbuffers/src/idl_gen_php.cpp | 1004 ---- third_party/flatbuffers/src/idl_gen_php.h | 29 - .../flatbuffers/src/idl_gen_python.cpp | 2212 -------- third_party/flatbuffers/src/idl_gen_python.h | 29 - third_party/flatbuffers/src/idl_gen_rust.cpp | 3121 ------------ third_party/flatbuffers/src/idl_gen_rust.h | 29 - third_party/flatbuffers/src/idl_gen_swift.cpp | 1966 -------- third_party/flatbuffers/src/idl_gen_swift.h | 29 - third_party/flatbuffers/src/idl_gen_text.cpp | 523 -- third_party/flatbuffers/src/idl_gen_text.h | 29 - third_party/flatbuffers/src/idl_gen_ts.cpp | 2249 --------- third_party/flatbuffers/src/idl_gen_ts.h | 32 - third_party/flatbuffers/src/idl_namer.h | 179 - third_party/flatbuffers/src/idl_parser.cpp | 4466 ----------------- third_party/flatbuffers/src/namer.h | 270 - third_party/flatbuffers/src/reflection.cpp | 768 --- third_party/flatbuffers/src/util.cpp | 475 -- third_party/flatbuffers/swift.swiftformat | 27 - third_party/flatbuffers/tsconfig.json | 15 - third_party/flatbuffers/tsconfig.mjs.json | 16 - third_party/flatbuffers/typescript.bzl | 90 - 285 files changed, 77741 deletions(-) delete mode 100644 third_party/flatbuffers/.bazelci/presubmit.yml delete mode 100644 third_party/flatbuffers/.bazelignore delete mode 100644 third_party/flatbuffers/.bazelrc delete mode 100644 third_party/flatbuffers/.clang-format delete mode 100644 third_party/flatbuffers/.clang-tidy delete mode 100644 third_party/flatbuffers/.editorconfig delete mode 100644 third_party/flatbuffers/.eslintrc.js delete mode 100644 third_party/flatbuffers/.gitattributes delete mode 100644 third_party/flatbuffers/.gitignore delete mode 100644 third_party/flatbuffers/.npmrc delete mode 100644 third_party/flatbuffers/BUILD.bazel delete mode 100644 third_party/flatbuffers/CHANGELOG.md delete mode 100644 third_party/flatbuffers/CMake/BuildFlatBuffers.cmake delete mode 100644 third_party/flatbuffers/CMake/DESCRIPTION.txt delete mode 100644 third_party/flatbuffers/CMake/FindFlatBuffers.cmake delete mode 100644 third_party/flatbuffers/CMake/PackageDebian.cmake delete mode 100644 third_party/flatbuffers/CMake/PackageRedhat.cmake delete mode 100644 third_party/flatbuffers/CMake/Version.cmake delete mode 100644 third_party/flatbuffers/CMake/flatbuffers-config-version.cmake.in delete mode 100644 third_party/flatbuffers/CMake/flatbuffers-config.cmake delete mode 100644 third_party/flatbuffers/CMake/flatbuffers.pc.in delete mode 100644 third_party/flatbuffers/CMakeLists.txt delete mode 100644 third_party/flatbuffers/CONTRIBUTING.md delete mode 100644 third_party/flatbuffers/FlatBuffers.podspec delete mode 100644 third_party/flatbuffers/Formatters.md delete mode 100644 third_party/flatbuffers/LICENSE delete mode 100644 third_party/flatbuffers/Package.swift delete mode 100644 third_party/flatbuffers/Package@swift-5.5.swift delete mode 100644 third_party/flatbuffers/README.md delete mode 100644 third_party/flatbuffers/SECURITY.md delete mode 100644 third_party/flatbuffers/WORKSPACE delete mode 100644 third_party/flatbuffers/build_defs.bzl delete mode 100644 third_party/flatbuffers/composer.json delete mode 100644 third_party/flatbuffers/conan/CMakeLists.txt delete mode 100644 third_party/flatbuffers/conan/build.py delete mode 100644 third_party/flatbuffers/conan/test_package/CMakeLists.txt delete mode 100644 third_party/flatbuffers/conan/test_package/conanfile.py delete mode 100644 third_party/flatbuffers/conan/test_package/test_package.cpp delete mode 100644 third_party/flatbuffers/conanfile.py delete mode 100644 third_party/flatbuffers/grpc/BUILD.bazel delete mode 100644 third_party/flatbuffers/grpc/README.md delete mode 100644 third_party/flatbuffers/grpc/boringssl.patch delete mode 100755 third_party/flatbuffers/grpc/build_grpc.sh delete mode 100644 third_party/flatbuffers/grpc/build_grpc_with_cxx14.patch delete mode 100644 third_party/flatbuffers/grpc/examples/README.md delete mode 100644 third_party/flatbuffers/grpc/examples/go/format.sh delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/.gitignore delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/README.md delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/client/go.mod delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/client/main.go delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/models/Greeter_grpc.go delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/models/HelloReply.go delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/models/HelloRequest.go delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/models/go.mod delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/server/go.mod delete mode 100644 third_party/flatbuffers/grpc/examples/go/greeter/server/main.go delete mode 100644 third_party/flatbuffers/grpc/examples/greeter.fbs delete mode 100644 third_party/flatbuffers/grpc/examples/python/greeter/README.md delete mode 100644 third_party/flatbuffers/grpc/examples/python/greeter/client.py delete mode 100644 third_party/flatbuffers/grpc/examples/python/greeter/models/HelloReply.py delete mode 100644 third_party/flatbuffers/grpc/examples/python/greeter/models/HelloRequest.py delete mode 100644 third_party/flatbuffers/grpc/examples/python/greeter/models/__init__.py delete mode 100644 third_party/flatbuffers/grpc/examples/python/greeter/models/greeter_grpc_fb.py delete mode 100644 third_party/flatbuffers/grpc/examples/python/greeter/server.py delete mode 100644 third_party/flatbuffers/grpc/examples/swift/Greeter/Package.swift delete mode 100644 third_party/flatbuffers/grpc/examples/swift/Greeter/README.md delete mode 100644 third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift delete mode 100644 third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift delete mode 100644 third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/client/main.swift delete mode 100644 third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/server/main.swift delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/README.md delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/package.json delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/client.ts delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter.ts delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_generated.ts delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_grpc.d.ts delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_grpc.js delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/models.ts delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/models/hello-reply.ts delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/models/hello-request.ts delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/src/server.ts delete mode 100644 third_party/flatbuffers/grpc/examples/ts/greeter/tsconfig.json delete mode 100644 third_party/flatbuffers/grpc/flatbuffers-java-grpc/pom.xml delete mode 100644 third_party/flatbuffers/grpc/flatbuffers-java-grpc/src/main/java/com/google/flatbuffers/grpc/FlatbuffersUtils.java delete mode 100644 third_party/flatbuffers/grpc/pom.xml delete mode 100644 third_party/flatbuffers/grpc/samples/greeter/Makefile delete mode 100644 third_party/flatbuffers/grpc/samples/greeter/client.cpp delete mode 100644 third_party/flatbuffers/grpc/samples/greeter/greeter.fbs delete mode 100644 third_party/flatbuffers/grpc/samples/greeter/server.cpp delete mode 100644 third_party/flatbuffers/grpc/src/compiler/BUILD.bazel delete mode 100644 third_party/flatbuffers/grpc/src/compiler/cpp_generator.cc delete mode 100644 third_party/flatbuffers/grpc/src/compiler/cpp_generator.h delete mode 100644 third_party/flatbuffers/grpc/src/compiler/go_generator.cc delete mode 100644 third_party/flatbuffers/grpc/src/compiler/go_generator.h delete mode 100644 third_party/flatbuffers/grpc/src/compiler/java_generator.cc delete mode 100644 third_party/flatbuffers/grpc/src/compiler/java_generator.h delete mode 100644 third_party/flatbuffers/grpc/src/compiler/python_generator.cc delete mode 100644 third_party/flatbuffers/grpc/src/compiler/python_generator.h delete mode 100644 third_party/flatbuffers/grpc/src/compiler/schema_interface.h delete mode 100644 third_party/flatbuffers/grpc/src/compiler/swift_generator.cc delete mode 100644 third_party/flatbuffers/grpc/src/compiler/swift_generator.h delete mode 100644 third_party/flatbuffers/grpc/src/compiler/ts_generator.cc delete mode 100644 third_party/flatbuffers/grpc/src/compiler/ts_generator.h delete mode 100644 third_party/flatbuffers/grpc/tests/BUILD delete mode 100644 third_party/flatbuffers/grpc/tests/GameFactory.java delete mode 100644 third_party/flatbuffers/grpc/tests/JavaGrpcTest.java delete mode 100644 third_party/flatbuffers/grpc/tests/go_test.go delete mode 100644 third_party/flatbuffers/grpc/tests/grpctest.cpp delete mode 100644 third_party/flatbuffers/grpc/tests/grpctest.py delete mode 100755 third_party/flatbuffers/grpc/tests/java-grpc-test.sh delete mode 100644 third_party/flatbuffers/grpc/tests/message_builder_test.cpp delete mode 100644 third_party/flatbuffers/grpc/tests/pom.xml delete mode 100644 third_party/flatbuffers/include/flatbuffers/allocator.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/array.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/base.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/buffer.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/buffer_ref.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/code_generator.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/code_generators.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/default_allocator.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/detached_buffer.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/file_manager.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/flatbuffers.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/flatc.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/flex_flat_util.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/flexbuffers.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/grpc.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/hash.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/idl.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/minireflect.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/pch/flatc_pch.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/pch/pch.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/reflection.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/reflection_generated.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/registry.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/stl_emulation.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/string.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/struct.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/table.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/util.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/vector.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/vector_downward.h delete mode 100644 third_party/flatbuffers/include/flatbuffers/verifier.h delete mode 100644 third_party/flatbuffers/lobster/flatbuffers.lobster delete mode 100644 third_party/flatbuffers/lua/flatbuffers.lua delete mode 100644 third_party/flatbuffers/lua/flatbuffers/binaryarray.lua delete mode 100644 third_party/flatbuffers/lua/flatbuffers/builder.lua delete mode 100644 third_party/flatbuffers/lua/flatbuffers/compat.lua delete mode 100644 third_party/flatbuffers/lua/flatbuffers/compat_5_1.lua delete mode 100644 third_party/flatbuffers/lua/flatbuffers/compat_5_3.lua delete mode 100644 third_party/flatbuffers/lua/flatbuffers/compat_luajit.lua delete mode 100644 third_party/flatbuffers/lua/flatbuffers/numTypes.lua delete mode 100644 third_party/flatbuffers/lua/flatbuffers/view.lua delete mode 100644 third_party/flatbuffers/mjs/README.md delete mode 100644 third_party/flatbuffers/net/FlatBuffers/ByteBuffer.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/ByteBufferUtil.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/FlatBufferBuilder.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/FlatBufferConstants.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/FlatBufferVerify.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/Google.FlatBuffers.csproj delete mode 100644 third_party/flatbuffers/net/FlatBuffers/IFlatbufferObject.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/Offset.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/Struct.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/Table.cs delete mode 100644 third_party/flatbuffers/net/FlatBuffers/flatbuffers.png delete mode 100644 third_party/flatbuffers/net/FlatBuffers/flatbuffers.snk delete mode 100644 third_party/flatbuffers/package.json delete mode 100644 third_party/flatbuffers/pnpm-lock.yaml delete mode 100644 third_party/flatbuffers/reflection/BUILD.bazel delete mode 100644 third_party/flatbuffers/reflection/reflection.fbs delete mode 100644 third_party/flatbuffers/reflection/ts/BUILD.bazel delete mode 100644 third_party/flatbuffers/samples/SampleBinary.cs delete mode 100644 third_party/flatbuffers/samples/SampleBinary.java delete mode 100644 third_party/flatbuffers/samples/SampleBinary.kt delete mode 100644 third_party/flatbuffers/samples/SampleBinary.php delete mode 100755 third_party/flatbuffers/samples/csharp_sample.sh delete mode 100755 third_party/flatbuffers/samples/dart_sample.sh delete mode 100644 third_party/flatbuffers/samples/go.mod delete mode 100755 third_party/flatbuffers/samples/go_sample.sh delete mode 100755 third_party/flatbuffers/samples/java_sample.sh delete mode 100755 third_party/flatbuffers/samples/javascript_sample.sh delete mode 100755 third_party/flatbuffers/samples/kotlin_sample.sh delete mode 100644 third_party/flatbuffers/samples/lua/MyGame/Sample/Color.lua delete mode 100644 third_party/flatbuffers/samples/lua/MyGame/Sample/Equipment.lua delete mode 100644 third_party/flatbuffers/samples/lua/MyGame/Sample/Monster.lua delete mode 100644 third_party/flatbuffers/samples/lua/MyGame/Sample/Vec3.lua delete mode 100644 third_party/flatbuffers/samples/lua/MyGame/Sample/Weapon.lua delete mode 100644 third_party/flatbuffers/samples/monster.bfbs delete mode 100644 third_party/flatbuffers/samples/monster.fbs delete mode 100644 third_party/flatbuffers/samples/monster_generated.h delete mode 100644 third_party/flatbuffers/samples/monster_generated.lobster delete mode 100644 third_party/flatbuffers/samples/monster_generated.swift delete mode 100644 third_party/flatbuffers/samples/monsterdata.json delete mode 100755 third_party/flatbuffers/samples/php_sample.sh delete mode 100755 third_party/flatbuffers/samples/python_sample.sh delete mode 100644 third_party/flatbuffers/samples/rust_generated/mod.rs delete mode 100644 third_party/flatbuffers/samples/rust_generated/my_game/sample/color_generated.rs delete mode 100644 third_party/flatbuffers/samples/rust_generated/my_game/sample/equipment_generated.rs delete mode 100644 third_party/flatbuffers/samples/rust_generated/my_game/sample/monster_generated.rs delete mode 100644 third_party/flatbuffers/samples/rust_generated/my_game/sample/vec_3_generated.rs delete mode 100644 third_party/flatbuffers/samples/rust_generated/my_game/sample/weapon_generated.rs delete mode 100644 third_party/flatbuffers/samples/sample_bfbs.cpp delete mode 100644 third_party/flatbuffers/samples/sample_binary.cpp delete mode 100644 third_party/flatbuffers/samples/sample_binary.go delete mode 100644 third_party/flatbuffers/samples/sample_binary.lobster delete mode 100644 third_party/flatbuffers/samples/sample_binary.lua delete mode 100644 third_party/flatbuffers/samples/sample_binary.py delete mode 100644 third_party/flatbuffers/samples/sample_binary.rs delete mode 100644 third_party/flatbuffers/samples/sample_binary.swift delete mode 100644 third_party/flatbuffers/samples/sample_flexbuffers.rs delete mode 100644 third_party/flatbuffers/samples/sample_flexbuffers_serde.rs delete mode 100644 third_party/flatbuffers/samples/sample_text.cpp delete mode 100644 third_party/flatbuffers/samples/sample_text.lobster delete mode 100755 third_party/flatbuffers/scripts/check-grpc-generated-code.py delete mode 100755 third_party/flatbuffers/scripts/check_generate_code.py delete mode 100755 third_party/flatbuffers/scripts/clang-format-all.sh delete mode 100755 third_party/flatbuffers/scripts/clang-format-git.sh delete mode 100755 third_party/flatbuffers/scripts/clang-tidy-git.sh delete mode 100755 third_party/flatbuffers/scripts/generate_code.py delete mode 100755 third_party/flatbuffers/scripts/generate_grpc_examples.py delete mode 100755 third_party/flatbuffers/scripts/release.sh delete mode 100644 third_party/flatbuffers/scripts/util.py delete mode 100644 third_party/flatbuffers/snap/snapcraft.yaml delete mode 100644 third_party/flatbuffers/src/BUILD.bazel delete mode 100644 third_party/flatbuffers/src/annotated_binary_text_gen.cpp delete mode 100644 third_party/flatbuffers/src/annotated_binary_text_gen.h delete mode 100644 third_party/flatbuffers/src/bfbs_gen.h delete mode 100644 third_party/flatbuffers/src/bfbs_gen_lua.cpp delete mode 100644 third_party/flatbuffers/src/bfbs_gen_lua.h delete mode 100644 third_party/flatbuffers/src/bfbs_gen_nim.cpp delete mode 100644 third_party/flatbuffers/src/bfbs_gen_nim.h delete mode 100644 third_party/flatbuffers/src/bfbs_namer.h delete mode 100644 third_party/flatbuffers/src/binary_annotator.cpp delete mode 100644 third_party/flatbuffers/src/binary_annotator.h delete mode 100644 third_party/flatbuffers/src/code_generators.cpp delete mode 100644 third_party/flatbuffers/src/file_binary_writer.cpp delete mode 100644 third_party/flatbuffers/src/file_name_saving_file_manager.cpp delete mode 100644 third_party/flatbuffers/src/file_writer.cpp delete mode 100644 third_party/flatbuffers/src/flatc.cpp delete mode 100644 third_party/flatbuffers/src/flatc_main.cpp delete mode 100644 third_party/flatbuffers/src/flathash.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_binary.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_binary.h delete mode 100644 third_party/flatbuffers/src/idl_gen_cpp.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_cpp.h delete mode 100644 third_party/flatbuffers/src/idl_gen_csharp.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_csharp.h delete mode 100644 third_party/flatbuffers/src/idl_gen_dart.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_dart.h delete mode 100644 third_party/flatbuffers/src/idl_gen_fbs.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_fbs.h delete mode 100644 third_party/flatbuffers/src/idl_gen_go.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_go.h delete mode 100644 third_party/flatbuffers/src/idl_gen_grpc.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_java.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_java.h delete mode 100644 third_party/flatbuffers/src/idl_gen_json_schema.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_json_schema.h delete mode 100644 third_party/flatbuffers/src/idl_gen_kotlin.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_kotlin.h delete mode 100644 third_party/flatbuffers/src/idl_gen_kotlin_kmp.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_lobster.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_lobster.h delete mode 100644 third_party/flatbuffers/src/idl_gen_php.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_php.h delete mode 100644 third_party/flatbuffers/src/idl_gen_python.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_python.h delete mode 100644 third_party/flatbuffers/src/idl_gen_rust.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_rust.h delete mode 100644 third_party/flatbuffers/src/idl_gen_swift.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_swift.h delete mode 100644 third_party/flatbuffers/src/idl_gen_text.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_text.h delete mode 100644 third_party/flatbuffers/src/idl_gen_ts.cpp delete mode 100644 third_party/flatbuffers/src/idl_gen_ts.h delete mode 100644 third_party/flatbuffers/src/idl_namer.h delete mode 100644 third_party/flatbuffers/src/idl_parser.cpp delete mode 100644 third_party/flatbuffers/src/namer.h delete mode 100644 third_party/flatbuffers/src/reflection.cpp delete mode 100644 third_party/flatbuffers/src/util.cpp delete mode 100644 third_party/flatbuffers/swift.swiftformat delete mode 100644 third_party/flatbuffers/tsconfig.json delete mode 100644 third_party/flatbuffers/tsconfig.mjs.json delete mode 100644 third_party/flatbuffers/typescript.bzl diff --git a/third_party/flatbuffers/.bazelci/presubmit.yml b/third_party/flatbuffers/.bazelci/presubmit.yml deleted file mode 100644 index bcab65430d6..00000000000 --- a/third_party/flatbuffers/.bazelci/presubmit.yml +++ /dev/null @@ -1,38 +0,0 @@ ---- -buildifier: latest -bazel: 6.4.0 -platforms: - ubuntu1804: - environment: - CC: clang - SWIFT_VERSION: "5.5.3" - SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION" - PATH: "$PATH:$SWIFT_HOME/usr/bin" - shell_commands: - - "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME" - - "mkdir $SWIFT_HOME" - - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu1804/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu18.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" - build_targets: - - "//..." - test_targets: - - "//..." - ubuntu2004: - environment: - CC: clang - SWIFT_VERSION: "5.5.3" - SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION" - PATH: "$PATH:$SWIFT_HOME/usr/bin" - shell_commands: - - "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME" - - "mkdir $SWIFT_HOME" - - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" - build_targets: - - "//..." - test_targets: - - "//..." - macos: - xcode_version: "14.2" - build_targets: - - "//..." - test_targets: - - "//..." diff --git a/third_party/flatbuffers/.bazelignore b/third_party/flatbuffers/.bazelignore deleted file mode 100644 index 3c3629e647f..00000000000 --- a/third_party/flatbuffers/.bazelignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/third_party/flatbuffers/.bazelrc b/third_party/flatbuffers/.bazelrc deleted file mode 100644 index f9f47a74237..00000000000 --- a/third_party/flatbuffers/.bazelrc +++ /dev/null @@ -1,4 +0,0 @@ -# We cannot use "common" here because the "version" command doesn't support -# --deleted_packages. We need to specify it for both build and query instead. -build --deleted_packages=tests/ts/bazel_repository_test_dir -query --deleted_packages=tests/ts/bazel_repository_test_dir diff --git a/third_party/flatbuffers/.clang-format b/third_party/flatbuffers/.clang-format deleted file mode 100644 index 7da2b4389e5..00000000000 --- a/third_party/flatbuffers/.clang-format +++ /dev/null @@ -1,13 +0,0 @@ ---- -Language: Cpp -BasedOnStyle: Google -DerivePointerAlignment: false -PointerAlignment: Right -IndentPPDirectives: AfterHash -Cpp11BracedListStyle: false -AlwaysBreakTemplateDeclarations: false -AllowShortCaseLabelsOnASingleLine: true -SpaceAfterTemplateKeyword: false -AllowShortBlocksOnASingleLine: true -... - diff --git a/third_party/flatbuffers/.clang-tidy b/third_party/flatbuffers/.clang-tidy deleted file mode 100644 index 7e9c1b7c7d6..00000000000 --- a/third_party/flatbuffers/.clang-tidy +++ /dev/null @@ -1,347 +0,0 @@ ---- -FormatStyle: "file" -WarningsAsErrors: "*" -HeaderFilterRegex: ".*" -Checks: "google-build-explicit-make-pair, - google-build-namespaces, - google-build-using-namespace, - google-default-arguments, - google-explicit-constructor, - google-global-names-in-headers, - google-objc-avoid-nsobject-new, - google-objc-avoid-throwing-exception, - google-objc-function-naming, - google-objc-global-variable-declaration, - google-readability-avoid-underscore-in-googletest-name, - google-readability-braces-around-statements, - google-readability-casting, - google-readability-function-size, - google-readability-namespace-comments, - google-runtime-int, - google-runtime-operator, - google-upgrade-googletest-case, - clang-analyzer-apiModeling.StdCLibraryFunctions, - clang-analyzer-apiModeling.TrustNonnull, - clang-analyzer-apiModeling.google.GTest, - clang-analyzer-apiModeling.llvm.CastValue, - clang-analyzer-apiModeling.llvm.ReturnValue, - clang-analyzer-core.CallAndMessage, - clang-analyzer-core.CallAndMessageModeling, - clang-analyzer-core.DivideZero, - clang-analyzer-core.DynamicTypePropagation, - clang-analyzer-core.NonNullParamChecker, - clang-analyzer-core.NonnilStringConstants, - clang-analyzer-core.NullDereference, - clang-analyzer-core.StackAddrEscapeBase, - clang-analyzer-core.StackAddressEscape, - clang-analyzer-core.UndefinedBinaryOperatorResult, - clang-analyzer-core.VLASize, - clang-analyzer-core.builtin.BuiltinFunctions, - clang-analyzer-core.builtin.NoReturnFunctions, - clang-analyzer-core.uninitialized.ArraySubscript, - clang-analyzer-core.uninitialized.Assign, - clang-analyzer-core.uninitialized.Branch, - clang-analyzer-core.uninitialized.CapturedBlockVariable, - clang-analyzer-core.uninitialized.UndefReturn, - clang-analyzer-cplusplus.InnerPointer, - clang-analyzer-cplusplus.Move, - clang-analyzer-cplusplus.NewDelete, - clang-analyzer-cplusplus.NewDeleteLeaks, - clang-analyzer-cplusplus.PlacementNew, - clang-analyzer-cplusplus.PureVirtualCall, - clang-analyzer-cplusplus.SelfAssignment, - clang-analyzer-cplusplus.SmartPtrModeling, - clang-analyzer-cplusplus.StringChecker, - clang-analyzer-cplusplus.VirtualCallModeling, - clang-analyzer-deadcode.DeadStores, - clang-analyzer-fuchsia.HandleChecker, - clang-analyzer-nullability.NullPassedToNonnull, - clang-analyzer-nullability.NullReturnedFromNonnull, - clang-analyzer-nullability.NullabilityBase, - clang-analyzer-nullability.NullableDereferenced, - clang-analyzer-nullability.NullablePassedToNonnull, - clang-analyzer-nullability.NullableReturnedFromNonnull, - clang-analyzer-optin.cplusplus.UninitializedObject, - clang-analyzer-optin.cplusplus.VirtualCall, - clang-analyzer-optin.mpi.MPI-Checker, - clang-analyzer-optin.osx.OSObjectCStyleCast, - clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker, - clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker, - clang-analyzer-optin.performance.GCDAntipattern, - clang-analyzer-optin.performance.Padding, - clang-analyzer-optin.portability.UnixAPI, - clang-analyzer-osx.API, - clang-analyzer-osx.MIG, - clang-analyzer-osx.NSOrCFErrorDerefChecker, - clang-analyzer-osx.NumberObjectConversion, - clang-analyzer-osx.OSObjectRetainCount, - clang-analyzer-osx.ObjCProperty, - clang-analyzer-osx.SecKeychainAPI, - clang-analyzer-osx.cocoa.AtSync, - clang-analyzer-osx.cocoa.AutoreleaseWrite, - clang-analyzer-osx.cocoa.ClassRelease, - clang-analyzer-osx.cocoa.Dealloc, - clang-analyzer-osx.cocoa.IncompatibleMethodTypes, - clang-analyzer-osx.cocoa.Loops, - clang-analyzer-osx.cocoa.MissingSuperCall, - clang-analyzer-osx.cocoa.NSAutoreleasePool, - clang-analyzer-osx.cocoa.NSError, - clang-analyzer-osx.cocoa.NilArg, - clang-analyzer-osx.cocoa.NonNilReturnValue, - clang-analyzer-osx.cocoa.ObjCGenerics, - clang-analyzer-osx.cocoa.RetainCount, - clang-analyzer-osx.cocoa.RetainCountBase, - clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak, - clang-analyzer-osx.cocoa.SelfInit, - clang-analyzer-osx.cocoa.SuperDealloc, - clang-analyzer-osx.cocoa.UnusedIvars, - clang-analyzer-osx.cocoa.VariadicMethodTypes, - clang-analyzer-osx.coreFoundation.CFError, - clang-analyzer-osx.coreFoundation.CFNumber, - clang-analyzer-osx.coreFoundation.CFRetainRelease, - clang-analyzer-osx.coreFoundation.containers.OutOfBounds, - clang-analyzer-osx.coreFoundation.containers.PointerSizedValues, - clang-analyzer-security.FloatLoopCounter, - clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, - clang-analyzer-security.insecureAPI.SecuritySyntaxChecker, - clang-analyzer-security.insecureAPI.UncheckedReturn, - clang-analyzer-security.insecureAPI.bcmp, - clang-analyzer-security.insecureAPI.bcopy, - clang-analyzer-security.insecureAPI.bzero, - clang-analyzer-security.insecureAPI.decodeValueOfObjCType, - clang-analyzer-security.insecureAPI.getpw, - clang-analyzer-security.insecureAPI.gets, - clang-analyzer-security.insecureAPI.mkstemp, - clang-analyzer-security.insecureAPI.mktemp, - clang-analyzer-security.insecureAPI.rand, - clang-analyzer-security.insecureAPI.strcpy, - clang-analyzer-security.insecureAPI.vfork, - clang-analyzer-unix.API, - clang-analyzer-unix.DynamicMemoryModeling, - clang-analyzer-unix.Malloc, - clang-analyzer-unix.MallocSizeof, - clang-analyzer-unix.MismatchedDeallocator, - clang-analyzer-unix.Vfork, - clang-analyzer-unix.cstring.BadSizeArg, - clang-analyzer-unix.cstring.CStringModeling, - clang-analyzer-unix.cstring.NullArg, - clang-analyzer-valist.CopyToSelf, - clang-analyzer-valist.Uninitialized, - clang-analyzer-valist.Unterminated, - clang-analyzer-valist.ValistBase, - clang-analyzer-webkit.NoUncountedMemberChecker, - clang-analyzer-webkit.RefCntblBaseVirtualDtor, - clang-analyzer-webkit.UncountedLambdaCapturesChecker, - -################################################ Optional checks ################################################ - - #google-readability-todo, - #bugprone-argument-comment, - #bugprone-assert-side-effect, - #bugprone-bad-signal-to-kill-thread, - #bugprone-bool-pointer-implicit-conversion, - #bugprone-branch-clone, - #bugprone-copy-constructor-init, - #bugprone-dangling-handle, - #bugprone-dynamic-static-initializers, - #bugprone-easily-swappable-parameters, - #bugprone-exception-escape, - #bugprone-fold-init-type, - #bugprone-forward-declaration-namespace, - #bugprone-forwarding-reference-overload, - #bugprone-implicit-widening-of-multiplication-result, - #bugprone-inaccurate-erase, - #bugprone-incorrect-roundings, - #bugprone-infinite-loop, - #bugprone-integer-division, - #bugprone-lambda-function-name, - #bugprone-macro-parentheses, - #bugprone-macro-repeated-side-effects, - #bugprone-misplaced-operator-in-strlen-in-alloc, - #bugprone-misplaced-pointer-arithmetic-in-alloc, - #bugprone-misplaced-widening-cast, - #bugprone-move-forwarding-reference, - #bugprone-multiple-statement-macro, - #bugprone-narrowing-conversions, - #bugprone-no-escape, - #bugprone-not-null-terminated-result, - #bugprone-parent-virtual-call, - #bugprone-posix-return, - #bugprone-redundant-branch-condition, - #bugprone-reserved-identifier, - #bugprone-signal-handler, - #bugprone-signed-char-misuse, - #bugprone-sizeof-container, - #bugprone-sizeof-expression, - #bugprone-spuriously-wake-up-functions, - #bugprone-string-constructor, - #bugprone-string-integer-assignment, - #bugprone-string-literal-with-embedded-nul, - #bugprone-stringview-nullptr, - #bugprone-suspicious-enum-usage, - #bugprone-suspicious-include, - #bugprone-suspicious-memory-comparison, - #bugprone-suspicious-memset-usage, - #bugprone-suspicious-missing-comma, - #bugprone-suspicious-semicolon, - #bugprone-suspicious-string-compare, - #bugprone-swapped-arguments, - #bugprone-terminating-continue, - #bugprone-throw-keyword-missing, - #bugprone-too-small-loop-variable, - #bugprone-undefined-memory-manipulation, - #bugprone-undelegated-constructor, - #bugprone-unhandled-exception-at-new, - #bugprone-unhandled-self-assignment, - #bugprone-unused-raii, - #bugprone-unused-return-value, - #bugprone-use-after-move, - #bugprone-virtual-near-miss, - #cppcoreguidelines-avoid-c-arrays, - #cppcoreguidelines-avoid-goto, - #cppcoreguidelines-avoid-magic-numbers, - #cppcoreguidelines-avoid-non-const-global-variables, - #cppcoreguidelines-c-copy-assignment-signature, - #cppcoreguidelines-explicit-virtual-functions, - #cppcoreguidelines-init-variables, - #cppcoreguidelines-interfaces-global-init, - #cppcoreguidelines-macro-usage, - #cppcoreguidelines-narrowing-conversions, - #cppcoreguidelines-no-malloc, - #cppcoreguidelines-non-private-member-variables-in-classes, - #cppcoreguidelines-owning-memory, - #cppcoreguidelines-prefer-member-initializer, - #cppcoreguidelines-pro-bounds-array-to-pointer-decay, - #cppcoreguidelines-pro-bounds-constant-array-index, - #cppcoreguidelines-pro-bounds-pointer-arithmetic, - #cppcoreguidelines-pro-type-const-cast, - #cppcoreguidelines-pro-type-cstyle-cast, - #cppcoreguidelines-pro-type-member-init, - #cppcoreguidelines-pro-type-reinterpret-cast, - #cppcoreguidelines-pro-type-static-cast-downcast, - #cppcoreguidelines-pro-type-union-access, - #cppcoreguidelines-pro-type-vararg, - #cppcoreguidelines-slicing, - #cppcoreguidelines-special-member-functions, - #cppcoreguidelines-virtual-class-destructor, - #hicpp-avoid-c-arrays, - #hicpp-avoid-goto, - #hicpp-braces-around-statements, - #hicpp-deprecated-headers, - #hicpp-exception-baseclass, - #hicpp-explicit-conversions, - #hicpp-function-size, - #hicpp-invalid-access-moved, - #hicpp-member-init, - #hicpp-move-const-arg, - #hicpp-multiway-paths-covered, - #hicpp-named-parameter, - #hicpp-new-delete-operators, - #hicpp-no-array-decay, - #hicpp-no-assembler, - #hicpp-no-malloc, - #hicpp-noexcept-move, - #hicpp-signed-bitwise, - #hicpp-special-member-functions, - #hicpp-static-assert, - #hicpp-undelegated-constructor, - #hicpp-uppercase-literal-suffix, - #hicpp-use-auto, - #hicpp-use-emplace, - #hicpp-use-equals-default, - #hicpp-use-equals-delete, - #hicpp-use-noexcept, - #hicpp-use-nullptr, - #hicpp-use-override, - #hicpp-vararg, - #modernize-avoid-bind, - #modernize-avoid-c-arrays, - #modernize-concat-nested-namespaces, - #modernize-deprecated-headers, - #modernize-deprecated-ios-base-aliases, - #modernize-loop-convert, - #modernize-make-shared, - #modernize-make-unique, - #modernize-pass-by-value, - #modernize-raw-string-literal, - #modernize-redundant-void-arg, - #modernize-replace-auto-ptr, - #modernize-replace-disallow-copy-and-assign-macro, - #modernize-replace-random-shuffle, - #modernize-return-braced-init-list, - #modernize-shrink-to-fit, - #modernize-unary-static-assert, - #modernize-use-auto, - #modernize-use-bool-literals, - #modernize-use-default-member-init, - #modernize-use-emplace, - #modernize-use-equals-default, - #modernize-use-equals-delete, - #modernize-use-nodiscard, - #modernize-use-noexcept, - #modernize-use-nullptr, - #modernize-use-override, - #modernize-use-trailing-return-type, - #modernize-use-transparent-functors, - #modernize-use-uncaught-exceptions, - #modernize-use-using, - #performance-faster-string-find, - #performance-for-range-copy, - #performance-implicit-conversion-in-loop, - #performance-inefficient-algorithm, - #performance-inefficient-string-concatenation, - #performance-inefficient-vector-operation, - #performance-move-const-arg, - #performance-move-constructor-init, - #performance-no-automatic-move, - #performance-no-int-to-ptr, - #performance-noexcept-move-constructor, - #performance-trivially-destructible, - #performance-type-promotion-in-math-fn, - #performance-unnecessary-copy-initialization, - #performance-unnecessary-value-param, - #portability-restrict-system-includes, - #portability-simd-intrinsics, - #readability-avoid-const-params-in-decls, - #readability-braces-around-statements, - #readability-const-return-type, - #readability-container-contains, - #readability-container-data-pointer, - #readability-container-size-empty, - #readability-convert-member-functions-to-static, - #readability-delete-null-pointer, - #readability-duplicate-include, - #readability-else-after-return, - #readability-function-cognitive-complexity, - #readability-function-size, - #readability-identifier-length, - #readability-identifier-naming, - #readability-implicit-bool-conversion, - #readability-inconsistent-declaration-parameter-name, - #readability-isolate-declaration, - #readability-magic-numbers, - #readability-make-member-function-const, - #readability-misleading-indentation, - #readability-misplaced-array-index, - #readability-named-parameter, - #readability-non-const-parameter, - #readability-qualified-auto, - #readability-redundant-access-specifiers, - #readability-redundant-control-flow, - #readability-redundant-declaration, - #readability-redundant-function-ptr-dereference, - #readability-redundant-member-init, - #readability-redundant-preprocessor, - #readability-redundant-smartptr-get, - #readability-redundant-string-cstr, - #readability-redundant-string-init, - #readability-simplify-boolean-expr, - #readability-simplify-subscript-expr, - #readability-static-accessed-through-instance, - #readability-static-definition-in-anonymous-namespace, - #readability-string-compare, - #readability-suspicious-call-argument, - #readability-uniqueptr-delete-release, - #readability-uppercase-literal-suffix, - #readability-use-anyofallof - " diff --git a/third_party/flatbuffers/.editorconfig b/third_party/flatbuffers/.editorconfig deleted file mode 100644 index 6689bab2314..00000000000 --- a/third_party/flatbuffers/.editorconfig +++ /dev/null @@ -1,8 +0,0 @@ -root = true -# Don't set line endings to avoid conflict with core.autocrlf flag. -# Line endings on checkout/checkin are controlled by .gitattributes file. -[*] -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true diff --git a/third_party/flatbuffers/.eslintrc.js b/third_party/flatbuffers/.eslintrc.js deleted file mode 100644 index 321169b07c0..00000000000 --- a/third_party/flatbuffers/.eslintrc.js +++ /dev/null @@ -1,13 +0,0 @@ -/* eslint-env node */ - -module.exports = { - root: true, - parser: '@typescript-eslint/parser', - plugins: [ - '@typescript-eslint', - ], - extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - ] -}; \ No newline at end of file diff --git a/third_party/flatbuffers/.gitattributes b/third_party/flatbuffers/.gitattributes deleted file mode 100644 index 4cab1f4d267..00000000000 --- a/third_party/flatbuffers/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Set the default behavior, in case people don't have core.autocrlf set. -* text=auto diff --git a/third_party/flatbuffers/.gitignore b/third_party/flatbuffers/.gitignore deleted file mode 100644 index 828ca1d618e..00000000000 --- a/third_party/flatbuffers/.gitignore +++ /dev/null @@ -1,155 +0,0 @@ -*_wire.txt -*_wire.bin -.DS_Store -**/.build -build -**/Packages -/*.xcodeproj -**/xcuserdata/ -**/xcshareddata/ -**/.swiftpm/ -*.o -*.o.d -*.class -*.a -*.swp -*~ -*.vcxproj -*.vcxproj.filters -*.vcxproj.user -*.sln -*.suo -*.opendb -*.keystore -**/.vs/** -**/bin/** -!tests/rust_usage_test/bin/** -**/gen/** -**/libs/** -**/obj/** -**/*.dir/** -**/CMakeFiles/** -**/cmake_install.cmake -**/install_manifest.txt -**/CMakeCache.txt -**/CMakeTestfile.cmake -**/CPackConfig.cmake -**/CPackSourceConfig.cmake -**/compile_commands.json -**/Debug/** -**/Release/** -**/RelWithDebInfo/** -**/x64/ #build artifacts from VS -build.xml -local.properties -project.properties -proguard-project.txt -linklint_results -Makefile -flatbenchmark -flatbenchmark.exe -flatc -flatc.exe -flathash -flathash.exe -flattests -flattests.exe -flattests_cpp17 -flattests_cpp17.exe -flatsamplebinary -flatsamplebinary.exe -flatsampletext -flatsampletext.exe -flatsamplebfbs -flatsamplebfbs.exe -grpctest -grpctest.exe -snapshot.sh -tags -tests/dart_gen -tests/go_gen -tests/monsterdata_java_wire.mon -tests/monsterdata_java_wire_sp.mon -tests/monsterdata_go_wire.mon -tests/monsterdata_javascript_wire.mon -tests/monsterdata_lobster_wire.mon -tests/monsterdata_rust_wire.mon -tests/php/ -CMakeLists.txt.user -CMakeScripts/** -CTestTestfile.cmake -flatbuffers-config-version.cmake -FlatBuffers.cbp -build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/** -build/Xcode/FlatBuffers.xcodeproj/xcuserdata/** -FlatBuffers.xcodeproj/ -java/.idea -java/*.iml -.idea -*.iml -target -java/target -**/*.pyc -build/VS2010/FlatBuffers.sdf -build/VS2010/FlatBuffers.opensdf -build/VS2010/ipch/**/*.ipch -*.so -Testing/Temporary -.cproject -.settings/ -.project -net/**/obj -node_modules/ -android/.externalNativeBuild/ -android/.gradle/ -android/build/ -samples/android/.externalNativeBuild/ -samples/android/.gradle/ -samples/android/build/ -js/**/*.js -js/**/*.d.ts -mjs/**/*.js -mjs/**/*.d.ts -/bazel-bin -/bazel-flatbuffers -/bazel-genfiles -/bazel-out -/bazel-testlogs -.ninja_deps -.ninja_log -build.ninja -rules.ninja -.vscode -dart/.pub/ -dart/.packages -dart/pubspec.lock -dart/.dart_tool/ -dart/build/ -dart/doc/api/ -Cargo.lock -.corpus** -.seed** -.crash** -grpc/google/ -**/Package.resolved -.clangd/** -package-lock.json -/*.ilk -/*.pdb -.clwb -yarn-error.log -.cache/ -/flatbuffers.lib -.cmake/ -**/dist -**/vendor -**/go.sum -flatbuffers.pc -**/FlatBuffers.Test.Swift.xcodeproj -**/html/** -**/latex/** -# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_BASE_DIR -cmake-build-debug/ -_deps/ -**/.gradle/** -kotlin/**/generated diff --git a/third_party/flatbuffers/.npmrc b/third_party/flatbuffers/.npmrc deleted file mode 100644 index 84ff0791f0d..00000000000 --- a/third_party/flatbuffers/.npmrc +++ /dev/null @@ -1 +0,0 @@ -hoist=false diff --git a/third_party/flatbuffers/BUILD.bazel b/third_party/flatbuffers/BUILD.bazel deleted file mode 100644 index b4f015a0e29..00000000000 --- a/third_party/flatbuffers/BUILD.bazel +++ /dev/null @@ -1,139 +0,0 @@ -load("@aspect_rules_js//npm:defs.bzl", "npm_link_package") -load("@npm//:defs.bzl", "npm_link_all_packages") -load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") - -licenses(["notice"]) - -package( - default_visibility = ["//visibility:public"], -) - -npm_link_all_packages(name = "node_modules") - -npm_link_package( - name = "node_modules/flatbuffers", - src = "//ts:flatbuffers", -) - -exports_files([ - "LICENSE", - "tsconfig.json", -]) - -config_setting( - name = "platform_freebsd", - constraint_values = [ - "@platforms//os:freebsd", - ], -) - -config_setting( - name = "platform_openbsd", - constraint_values = [ - "@platforms//os:openbsd", - ], -) - -filegroup( - name = "distribution", - srcs = [ - "BUILD.bazel", - "WORKSPACE", - "build_defs.bzl", - "typescript.bzl", - "//grpc/src/compiler:distribution", - "//reflection:distribution", - "//src:distribution", - "//ts:distribution", - ] + glob([ - "include/flatbuffers/*.h", - ]), - visibility = ["//visibility:public"], -) - -# Public flatc library to compile flatbuffer files at runtime. -cc_library( - name = "flatbuffers", - hdrs = ["//:public_headers"], - linkstatic = 1, - strip_include_prefix = "/include", - deps = ["//src:flatbuffers"], -) - -# Public C++ headers for the Flatbuffers library. -filegroup( - name = "public_headers", - srcs = [ - "include/flatbuffers/allocator.h", - "include/flatbuffers/array.h", - "include/flatbuffers/base.h", - "include/flatbuffers/buffer.h", - "include/flatbuffers/buffer_ref.h", - "include/flatbuffers/code_generator.h", - "include/flatbuffers/code_generators.h", - "include/flatbuffers/default_allocator.h", - "include/flatbuffers/detached_buffer.h", - "include/flatbuffers/file_manager.h", - "include/flatbuffers/flatbuffer_builder.h", - "include/flatbuffers/flatbuffers.h", - "include/flatbuffers/flex_flat_util.h", - "include/flatbuffers/flexbuffers.h", - "include/flatbuffers/grpc.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", - ], -) - -# Public flatc compiler library. -cc_library( - name = "flatc_library", - linkstatic = 1, - deps = [ - "//src:flatc_library", - ], -) - -# Public flatc compiler. -cc_binary( - name = "flatc", - data = ["//reflection:reflection_fbs_schema"], - deps = [ - "//src:flatc", - ], -) - -filegroup( - name = "flatc_headers", - srcs = [ - "include/flatbuffers/flatc.h", - ], - visibility = ["//:__subpackages__"], -) - -# Library used by flatbuffer_cc_library rules. -cc_library( - name = "runtime_cc", - hdrs = [ - "include/flatbuffers/base.h", - "include/flatbuffers/flatbuffers.h", - "include/flatbuffers/flexbuffers.h", - "include/flatbuffers/stl_emulation.h", - "include/flatbuffers/util.h", - "include/flatbuffers/vector.h", - "include/flatbuffers/verifier.h", - ], - linkstatic = 1, - strip_include_prefix = "/include", -) diff --git a/third_party/flatbuffers/CHANGELOG.md b/third_party/flatbuffers/CHANGELOG.md deleted file mode 100644 index 2b0380df6c5..00000000000 --- a/third_party/flatbuffers/CHANGELOG.md +++ /dev/null @@ -1,168 +0,0 @@ -# Flatbuffers Change Log - -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. - -## [24.3.25] (March 25 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.25) - -* Fixed license metadata parsing (#8253) -* [C++] Allow string_view in `LookUpByKey` in addition to null-terminated c-style strings (#8203) - -## [24.3.7] (March 7 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.7) - -* Just to fix some of the CI build issues from the 24.3.6 release. - -## [24.3.6] (March 6 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.6) - -* Fix typescript object API to allow 0 values for null-default scalars (#7864) - -## [23.5.26 (May 26 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.26) - -* Mostly bug fixing for 64-bit support -* Adds support for specifying underling type of unions in C++ and TS/JS (#7954) - -## [23.5.9 (May 9 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.9) - -* 64-bit support for C++ (#7935) - -## [23.5.8 (May 8 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.8) - -* add key_field to compiled tests -* Add golden language directory -* Rework cmake flatc codegeneration (#7938) -* remove defining generated files in test srcs -* Add binary schema reflection (#7932) -* Migrate from rules_nodejs to rules_js/rules_ts (take 2) (#7928) -* `flat_buffers.dart`: mark const variable finals for internal Dart linters -* fixed some windows warnings (#7929) -* inject no long for FBS generation to remove logs in flattests (#7926) -* Revert "Migrate from rules_nodejs to rules_js/rules_ts (#7923)" (#7927) -* Migrate from rules_nodejs to rules_js/rules_ts (#7923) -* Only generate @kotlin.ExperimentalUnsigned annotation on create*Vector methods having an unsigned array type parameter. (#7881) -* additional check for absl::string_view availability (#7897) -* Optionally generate Python type annotations (#7858) -* Replace deprecated command with environment file (#7921) -* drop glibc from runtime dependencies (#7906) -* Make JSON supporting advanced union features (#7869) -* Allow to use functions from `BuildFlatBuffers.cmake` from a flatbuffers installation installed with CMake. (#7912) -* TS/JS: Use TypeError instead of Error when appropriate (#7910) -* Go: make generated code more compliant to "go fmt" (#7907) -* Support file_identifier in Go (#7904) -* Optionally generate type prefixes and suffixes for python code (#7857) -* Go: add test for FinishWithFileIdentifier (#7905) -* Fix go_sample.sh (#7903) -* [TS/JS] Upgrade dependencies (#7889) -* Add a FileWriter interface (#7821) -* TS/JS: Use minvalue from enum if not found (#7888) -* [CS] Verifier (#7850) -* README.md: PyPI case typo (#7880) -* Update go documentation link to point to root module (#7879) -* use Bool for flatbuffers bool instead of Byte (#7876) -* fix using null string in vector (#7872) -* Add `flatbuffers-64` branch to CI for pushes -* made changes to the rust docs so they would compile. new_with_capacity is deprecated should use with_capacity, get_root_as_monster should be root_as_monster (#7871) -* Adding comment for code clarification (#7856) -* ToCamelCase() when kLowerCamel now converts first char to lower. (#7838) -* Fix help output for --java-checkerframework (#7854) -* Update filename to README.md and improve formatting (#7855) -* Update stale.yml -* Updated remaining usages of LICENSE.txt - -## [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). - -## [23.1.4 (Jan 4 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.4) - -* Major release! Just kidding, we are continuing the - [versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning) of - using a date to signify releases. This results in the first release of the new - year to bump the tradition major version field. - -* Go minimum version is now 1.19 (#7720) with the addition of Go modules. - -* Added CI support for Big Endian regression testing (#7707). - -* Fixed `getFullyQualifiedName` in typescript to return name delimited by '.' - instead of '_' (#7730). - -* Fixed the versioning scheme to not include leading zeros which are not - consistently handled by every package manager. Only the last release - (12.12.06) should have suffered from this. - -## [22.12.06 (Dec 06 2022)](https://github.com/google/flatbuffers/releases/tag/v22.12.06) - -* Bug fixing release, no major changes. - -## [22.10.25 (Oct 25 2022)](https://github.com/google/flatbuffers/releases/tag/v22.10.25) - -* Added Nim language support with generator and runtime libraries (#7534). - -## [22.9.29 (Sept 29 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.29) - -* Rust soundness fixes to avoid the crate from bing labelled unsafe (#7518). - -## [22.9.24 (Sept 24 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.24) - -* 20 Major releases in a row? Nope, we switched to a new - [versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning) - that is based on date. - -* Python supports fixed size arrays now (#7529). - -* Behavior change in how C++ object API uses `UnPackTo`. The original intent of - this was to reduce allocations by reusing an existing object to pack data - into. At some point, this logic started to merge the states of the two objects - instead of clearing the state of the packee. This change goes back to the - original intention, the packed object is cleared when getting data packed into - it (#7527). - -* Fixed a bug in C++ alignment that was using `sizeof()` instead of the intended - `AlignOf()` for structs (#7520). - -* C# has an - [official Nuget package](https://www.nuget.org/packages/Google.FlatBuffers) - now (#7496). - -## 2.0.8 (Aug 29 2022) - -* Fix for `--keep-prefix` the was generating the wrong include statements for - C++ (#7469). The bug was introduced in 2.0.7. - -* Added the `Verifier::Options` option struct to allow specifying runtime - configuration settings for the verifier (#7489). This allows to skip verifying - nested flatbuffers, a on-by-default change that was introduced in 2.0.7. This - deprecates the existing `Verifier` constructor, which may be removed in a - future version. - -* Refactor of `tests/test.cpp` that lead to ~10% speedup in compilation of the - entire project (#7487). - -## 2.0.7 (Aug 22 2022) - -* This is the first version with an explicit change log, so all the previous - features will not be listed. - -* Verifier now checks that buffers are at least the minimum size required to be - a flatbuffers (12 bytes). This includes nested flatbuffers, which previously - could be declared valid at size 0. - -* Annotated binaries. Given a flatbuffer binary and a schema (or binary schema) - one can generate an annotated flatbuffer (.afb) to describe each byte in the - binary with schema metadata and value. - -* First binary schema generator (Lua) to generate Lua code via a .bfbs file. - This is mostly an implementation detail of flatc internals, but will be slowly - applied to the other language generators. diff --git a/third_party/flatbuffers/CMake/BuildFlatBuffers.cmake b/third_party/flatbuffers/CMake/BuildFlatBuffers.cmake deleted file mode 100644 index 631e5adfbf3..00000000000 --- a/third_party/flatbuffers/CMake/BuildFlatBuffers.cmake +++ /dev/null @@ -1,449 +0,0 @@ -# Copyright 2015 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. - -# General function to create FlatBuffer build rules for the given list of -# schemas. -# -# flatbuffers_schemas: A list of flatbuffer schema files to process. -# -# schema_include_dirs: A list of schema file include directories, which will be -# passed to flatc via the -I parameter. -# -# custom_target_name: The generated files will be added as dependencies for a -# new custom target with this name. You should add that target as a dependency -# for your main target to ensure these files are built. You can also retrieve -# various properties from this target, such as GENERATED_INCLUDES_DIR, -# BINARY_SCHEMAS_DIR, and COPY_TEXT_SCHEMAS_DIR. -# -# additional_dependencies: A list of additional dependencies that you'd like -# all generated files to depend on. Pass in a blank string if you have none. -# -# generated_includes_dir: Where to generate the C++ header files for these -# schemas. The generated includes directory will automatically be added to -# CMake's include directories, and will be where generated header files are -# placed. This parameter is optional; pass in empty string if you don't want to -# generate include files for these schemas. -# -# binary_schemas_dir: If you specify an optional binary schema directory, binary -# schemas will be generated for these schemas as well, and placed into the given -# directory. -# -# copy_text_schemas_dir: If you want all text schemas (including schemas from -# all schema include directories) copied into a directory (for example, if you -# need them within your project to build JSON files), you can specify that -# folder here. All text schemas will be copied to that folder. -# -# IMPORTANT: Make sure you quote all list arguments you pass to this function! -# Otherwise CMake will only pass in the first element. -# Example: build_flatbuffers("${fb_files}" "${include_dirs}" target_name ...) -function(build_flatbuffers flatbuffers_schemas - schema_include_dirs - custom_target_name - additional_dependencies - generated_includes_dir - binary_schemas_dir - copy_text_schemas_dir) - - # Test if including from FindFlatBuffers - if(FLATBUFFERS_FLATC_EXECUTABLE) - set(FLATC_TARGET "") - set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) - elseif(TARGET flatbuffers::flatc) - set(FLATC_TARGET flatbuffers::flatc) - set(FLATC flatbuffers::flatc) - else() - set(FLATC_TARGET flatc) - set(FLATC flatc) - endif() - set(FLATC_SCHEMA_ARGS --gen-mutable) - if(FLATBUFFERS_FLATC_SCHEMA_EXTRA_ARGS) - set(FLATC_SCHEMA_ARGS - ${FLATBUFFERS_FLATC_SCHEMA_EXTRA_ARGS} - ${FLATC_SCHEMA_ARGS} - ) - endif() - - set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}") - - set(schema_glob "*.fbs") - # Generate the include files parameters. - set(include_params "") - set(all_generated_files "") - foreach (include_dir ${schema_include_dirs}) - set(include_params -I ${include_dir} ${include_params}) - if (NOT ${copy_text_schemas_dir} STREQUAL "") - # Copy text schemas from dependent folders. - file(GLOB_RECURSE dependent_schemas ${include_dir}/${schema_glob}) - foreach (dependent_schema ${dependent_schemas}) - file(COPY ${dependent_schema} DESTINATION ${copy_text_schemas_dir}) - endforeach() - endif() - endforeach() - - foreach(schema ${flatbuffers_schemas}) - get_filename_component(filename ${schema} NAME_WE) - # For each schema, do the things we requested. - if (NOT ${generated_includes_dir} STREQUAL "") - set(generated_include ${generated_includes_dir}/${filename}_generated.h) - add_custom_command( - OUTPUT ${generated_include} - COMMAND ${FLATC} ${FLATC_SCHEMA_ARGS} - -o ${generated_includes_dir} - ${include_params} - -c ${schema} - DEPENDS ${FLATC_TARGET} ${schema} ${additional_dependencies} - WORKING_DIRECTORY "${working_dir}") - list(APPEND all_generated_files ${generated_include}) - endif() - - if (NOT ${binary_schemas_dir} STREQUAL "") - set(binary_schema ${binary_schemas_dir}/${filename}.bfbs) - add_custom_command( - OUTPUT ${binary_schema} - COMMAND ${FLATC} -b --schema - -o ${binary_schemas_dir} - ${include_params} - ${schema} - DEPENDS ${FLATC_TARGET} ${schema} ${additional_dependencies} - WORKING_DIRECTORY "${working_dir}") - list(APPEND all_generated_files ${binary_schema}) - endif() - - if (NOT ${copy_text_schemas_dir} STREQUAL "") - file(COPY ${schema} DESTINATION ${copy_text_schemas_dir}) - endif() - endforeach() - - # Create a custom target that depends on all the generated files. - # This is the target that you can depend on to trigger all these - # to be built. - add_custom_target(${custom_target_name} - DEPENDS ${all_generated_files} ${additional_dependencies}) - - # Register the include directory we are using. - if (NOT ${generated_includes_dir} STREQUAL "") - include_directories(${generated_includes_dir}) - set_property(TARGET ${custom_target_name} - PROPERTY GENERATED_INCLUDES_DIR - ${generated_includes_dir}) - endif() - - # Register the binary schemas dir we are using. - if (NOT ${binary_schemas_dir} STREQUAL "") - set_property(TARGET ${custom_target_name} - PROPERTY BINARY_SCHEMAS_DIR - ${binary_schemas_dir}) - endif() - - # Register the text schema copy dir we are using. - if (NOT ${copy_text_schemas_dir} STREQUAL "") - set_property(TARGET ${custom_target_name} - PROPERTY COPY_TEXT_SCHEMAS_DIR - ${copy_text_schemas_dir}) - endif() -endfunction() - -# Creates a target that can be linked against that generates flatbuffer headers. -# -# This function takes a target name and a list of schemas. You can also specify -# 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_. -# -# Arguments: -# TARGET: The name of the target to generate. -# SCHEMAS: The list of schema files to generate code for. -# BINARY_SCHEMAS_DIR: Optional. The directory in which to generate binary -# schemas. Binary schemas will only be generated if a path is provided. -# INCLUDE: Optional. Search for includes in the specified paths. (Use this -# instead of "-I " and the FLAGS option so that CMake is aware of -# the directories that need to be searched). -# INCLUDE_PREFIX: Optional. The directory in which to place the generated -# files. Use this instead of the --include-prefix option. -# FLAGS: Optional. A list of any additional flags that you would like to pass -# to flatc. -# -# Example: -# -# flatbuffers_generate_headers( -# TARGET my_generated_headers_target -# INCLUDE_PREFIX ${MY_INCLUDE_PREFIX}" -# SCHEMAS ${MY_SCHEMA_FILES} -# BINARY_SCHEMAS_DIR "${MY_BINARY_SCHEMA_DIRECTORY}" -# FLAGS --gen-object-api) -# -# 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) - set(one_value_args - "TARGET" - "INCLUDE_PREFIX" - "BINARY_SCHEMAS_DIR") - set(multi_value_args - "SCHEMAS" - "INCLUDE" - "FLAGS") - cmake_parse_arguments( - PARSE_ARGV 0 - FLATBUFFERS_GENERATE_HEADERS - "${options}" - "${one_value_args}" - "${multi_value_args}") - - # Test if including from FindFlatBuffers - if(FLATBUFFERS_FLATC_EXECUTABLE) - set(FLATC_TARGET "") - set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) - elseif(TARGET flatbuffers::flatc) - set(FLATC_TARGET flatbuffers::flatc) - set(FLATC flatbuffers::flatc) - else() - set(FLATC_TARGET flatc) - set(FLATC flatc) - endif() - - set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}") - - # Generate the include files parameters. - set(include_params "") - foreach (include_dir ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE}) - set(include_params -I ${include_dir} ${include_params}) - endforeach() - - # Create a directory to place the generated code. - set(generated_target_dir "${CMAKE_CURRENT_BINARY_DIR}/${FLATBUFFERS_GENERATE_HEADERS_TARGET}") - set(generated_include_dir "${generated_target_dir}") - if (NOT ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX} STREQUAL "") - set(generated_include_dir "${generated_include_dir}/${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX}") - list(APPEND FLATBUFFERS_GENERATE_HEADERS_FLAGS - "--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) - set(generated_include "${generated_include_dir}/${filename}_generated.h") - - # Generate files for grpc if needed - set(generated_source_file) - if("${FLATBUFFERS_GENERATE_HEADERS_FLAGS}" MATCHES "--grpc") - # Check if schema file contain a rpc_service definition - file(STRINGS ${schema} has_grpc REGEX "rpc_service") - if(has_grpc) - list(APPEND generated_include "${generated_include_dir}/${filename}.grpc.fb.h") - set(generated_source_file "${generated_include_dir}/${filename}.grpc.fb.cc") - endif() - endif() - - add_custom_command( - OUTPUT ${generated_include} ${generated_source_file} - COMMAND ${FLATC} ${FLATC_ARGS} - -o ${generated_include_dir} - ${include_params} - -c ${schema} - ${FLATBUFFERS_GENERATE_HEADERS_FLAGS} - DEPENDS ${FLATC_TARGET} ${schema} - WORKING_DIRECTORY "${working_dir}" - 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 "") - set(binary_schema - "${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}/${filename}.bfbs") - add_custom_command( - OUTPUT ${binary_schema} - COMMAND ${FLATC} -b --schema - -o ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} - ${include_params} - ${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( - ${FLATBUFFERS_GENERATE_HEADERS_TARGET} - INTERFACE - ${all_generated_header_files} - ${all_generated_binary_files} - ${all_generated_source_files} - ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS}) - add_dependencies( - ${FLATBUFFERS_GENERATE_HEADERS_TARGET} - ${FLATC} - ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS}) - target_include_directories( - ${FLATBUFFERS_GENERATE_HEADERS_TARGET} - INTERFACE ${generated_target_dir}) - - # Organize file layout for IDEs. - source_group( - TREE "${generated_target_dir}" - PREFIX "Flatbuffers/Generated/Headers Files" - FILES ${all_generated_header_files}) - source_group( - TREE "${generated_target_dir}" - PREFIX "Flatbuffers/Generated/Source Files" - FILES ${all_generated_source_files}) - source_group( - TREE ${working_dir} - PREFIX "Flatbuffers/Schemas" - FILES ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS}) - if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "") - source_group( - TREE "${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}" - PREFIX "Flatbuffers/Generated/Binary Schemas" - FILES ${all_generated_binary_files}) - endif() -endfunction() - -# Creates a target that can be linked against that generates flatbuffer binaries -# from json files. -# -# This function takes a target name and a list of schemas and Json files. You -# can also specify other flagc flags and options to change the behavior of the -# flatc compiler. -# -# Adding this target to your executable ensurses that the flatbuffer binaries -# are compiled before your executable is run. -# -# Arguments: -# TARGET: The name of the target to generate. -# JSON_FILES: The list of json files to compile to flatbuffers binaries. -# SCHEMA: The flatbuffers schema of the Json files to be compiled. -# INCLUDE: Optional. Search for includes in the specified paths. (Use this -# instead of "-I " and the FLAGS option so that CMake is aware of -# the directories that need to be searched). -# OUTPUT_DIR: The directly where the generated flatbuffers binaries should be -# placed. -# FLAGS: Optional. A list of any additional flags that you would like to pass -# to flatc. -# -# Example: -# -# flatbuffers_generate_binary_files( -# TARGET my_binary_data -# SCHEMA "${MY_SCHEMA_DIR}/my_example_schema.fbs" -# JSON_FILES ${MY_JSON_FILES} -# OUTPUT_DIR "${MY_BINARY_DATA_DIRECTORY}" -# FLAGS --strict-json) -# -# target_link_libraries(MyExecutableTarget -# PRIVATE my_binary_data -# ) -function(flatbuffers_generate_binary_files) - # Parse function arguments. - set(options) - set(one_value_args - "TARGET" - "SCHEMA" - "OUTPUT_DIR") - set(multi_value_args - "JSON_FILES" - "INCLUDE" - "FLAGS") - cmake_parse_arguments( - PARSE_ARGV 0 - FLATBUFFERS_GENERATE_BINARY_FILES - "${options}" - "${one_value_args}" - "${multi_value_args}") - - # Test if including from FindFlatBuffers - if(FLATBUFFERS_FLATC_EXECUTABLE) - set(FLATC_TARGET "") - set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) - elseif(TARGET flatbuffers::flatc) - set(FLATC_TARGET flatbuffers::flatc) - set(FLATC flatbuffers::flatc) - else() - set(FLATC_TARGET flatc) - set(FLATC flatc) - endif() - - set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}") - - # Generate the include files parameters. - set(include_params "") - foreach (include_dir ${FLATBUFFERS_GENERATE_BINARY_FILES_INCLUDE}) - set(include_params -I ${include_dir} ${include_params}) - endforeach() - - # Create rules to generate the flatbuffers binary for each json file. - foreach(json_file ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES}) - get_filename_component(filename ${json_file} NAME_WE) - set(generated_binary_file "${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR}/${filename}.bin") - add_custom_command( - OUTPUT ${generated_binary_file} - COMMAND ${FLATC} ${FLATC_ARGS} - -o ${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR} - ${include_params} - -b ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA} ${json_file} - ${FLATBUFFERS_GENERATE_BINARY_FILES_FLAGS} - DEPENDS ${FLATC_TARGET} ${json_file} - WORKING_DIRECTORY "${working_dir}" - COMMENT "Building ${json_file} binary flatbuffers...") - list(APPEND all_generated_binary_files ${generated_binary_file}) - endforeach() - - # Set up interface library - add_library(${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET} INTERFACE) - target_sources( - ${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET} - INTERFACE - ${all_generated_binary_files} - ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES} - ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA}) - add_dependencies( - ${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET} - ${FLATC}) - - # Organize file layout for IDEs. - source_group( - TREE ${working_dir} - PREFIX "Flatbuffers/JSON Files" - FILES ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES}) - source_group( - TREE ${working_dir} - PREFIX "Flatbuffers/Schemas" - FILES ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA}) - source_group( - TREE ${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR} - PREFIX "Flatbuffers/Generated/Binary Files" - FILES ${all_generated_binary_files}) -endfunction() diff --git a/third_party/flatbuffers/CMake/DESCRIPTION.txt b/third_party/flatbuffers/CMake/DESCRIPTION.txt deleted file mode 100644 index 3698b034a2e..00000000000 --- a/third_party/flatbuffers/CMake/DESCRIPTION.txt +++ /dev/null @@ -1,4 +0,0 @@ -FlatBuffers is a cross platform serialization library architected for -maximum memory efficiency. It allows you to directly access serialized -data without parsing/unpacking it first, while still having great -forwards/backwards compatibility. diff --git a/third_party/flatbuffers/CMake/FindFlatBuffers.cmake b/third_party/flatbuffers/CMake/FindFlatBuffers.cmake deleted file mode 100644 index 044cf7c9d27..00000000000 --- a/third_party/flatbuffers/CMake/FindFlatBuffers.cmake +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright 2014 Stefan.Eilemann@epfl.ch -# 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. - -# Find the flatbuffers schema compiler -# -# Output Variables: -# * FLATBUFFERS_FLATC_EXECUTABLE the flatc compiler executable -# * FLATBUFFERS_FOUND -# -# Provides: -# * FLATBUFFERS_GENERATE_C_HEADERS(Name ) creates the C++ headers -# for the given flatbuffer schema files. -# Returns the header files in ${Name}_OUTPUTS - -set(FLATBUFFERS_CMAKE_DIR ${CMAKE_CURRENT_LIST_DIR}) - -find_program(FLATBUFFERS_FLATC_EXECUTABLE NAMES flatc) -find_path(FLATBUFFERS_INCLUDE_DIR NAMES flatbuffers/flatbuffers.h) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(FlatBuffers - DEFAULT_MSG FLATBUFFERS_FLATC_EXECUTABLE FLATBUFFERS_INCLUDE_DIR) - -if(FLATBUFFERS_FOUND) - function(FLATBUFFERS_GENERATE_C_HEADERS Name) - set(FLATC_OUTPUTS) - foreach(FILE ${ARGN}) - get_filename_component(FLATC_OUTPUT ${FILE} NAME_WE) - set(FLATC_OUTPUT - "${CMAKE_CURRENT_BINARY_DIR}/${FLATC_OUTPUT}_generated.h") - list(APPEND FLATC_OUTPUTS ${FLATC_OUTPUT}) - - add_custom_command(OUTPUT ${FLATC_OUTPUT} - COMMAND ${FLATBUFFERS_FLATC_EXECUTABLE} - ARGS -c -o "${CMAKE_CURRENT_BINARY_DIR}/" ${FILE} - DEPENDS ${FILE} - COMMENT "Building C++ header for ${FILE}" - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - endforeach() - set(${Name}_OUTPUTS ${FLATC_OUTPUTS} PARENT_SCOPE) - endfunction() - - set(FLATBUFFERS_INCLUDE_DIRS ${FLATBUFFERS_INCLUDE_DIR}) - include_directories(${CMAKE_BINARY_DIR}) -else() - set(FLATBUFFERS_INCLUDE_DIR) -endif() - -include("${FLATBUFFERS_CMAKE_DIR}/BuildFlatBuffers.cmake") diff --git a/third_party/flatbuffers/CMake/PackageDebian.cmake b/third_party/flatbuffers/CMake/PackageDebian.cmake deleted file mode 100644 index d8692c63d23..00000000000 --- a/third_party/flatbuffers/CMake/PackageDebian.cmake +++ /dev/null @@ -1,25 +0,0 @@ -# ------------------- Debianization --------------------- -if (UNIX) - - # Set build environment - SET(CPACK_GENERATOR "TGZ;DEB") - SET(CPACK_SOURCE_TGZ "ON") - - # Common package information - SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY - "FlatBuffers is an efficient cross platform serialization library for C++, with support for Java, C# and Go. It was created at Google specifically for game development and other performance-critical applications.") - SET(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/google/flatbuffers") - SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "Vitaly Isaev ") - - SET(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR}) - SET(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR}) - SET(CPACK_PACKAGE_VERSION_PATCH ${VERSION_PATCH}) - SET(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_COMMIT}") - SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") - - # Package name - SET(CPACK_DEBIAN_PACKAGE_NAME "flatbuffers") - SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE) - set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT") - -endif(UNIX) diff --git a/third_party/flatbuffers/CMake/PackageRedhat.cmake b/third_party/flatbuffers/CMake/PackageRedhat.cmake deleted file mode 100644 index 34302882fb3..00000000000 --- a/third_party/flatbuffers/CMake/PackageRedhat.cmake +++ /dev/null @@ -1,44 +0,0 @@ -if (UNIX) - set(CPACK_GENERATOR "RPM") - set(CPACK_SOURCE_TGZ "ON") - - set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "FlatBuffers serialization library and schema compiler.") - - set(CPACK_RPM_PACKAGE_HOMEPAGE "https://github.com/google/flatbuffers") - set(CPACK_RPM_PACKAGE_MAINTAINER "Marc Butler ") - - set(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR}) - set(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR}) - set(CPACK_PACKAGE_VERSION_PATCH ${VERSION_PATCH}) - set(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_COMMIT}") - set(CPACK_RPM_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") - - set(CPACK_RPM_PACKAGE_NAME "flatbuffers") - - # 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) - - set(CPACK_RPM_PACKAGE_VENDOR "Google, Inc.") - set(CPACK_RPM_PACKAGE_LICENSE "Apache 2.0") - set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE) - set(CPACK_PACKAGE_DESCRIPTION_FILE ${CMAKE_SOURCE_DIR}/CMake/DESCRIPTION.txt) - - # This may reduce rpm compatiblity with very old systems. - set(CPACK_RPM_COMPRESSION_TYPE lzma) - - set(CPACK_RPM_PACKAGE_NAME "flatbuffers") - set(CPACK_PACKAGE_FILE_NAME - "${CPACK_RPM_PACKAGE_NAME}_${CPACK_RPM_PACKAGE_VERSION}_${CPACK_RPM_PACKAGE_ARCHITECTURE}") - if(NOT DEFINED ${CPACK_PACKAGING_INSTALL_PREFIX}) - # Default packaging install prefix on RedHat systems is /usr. - # This is the assumed value when this variable is not defined. - # There is currently a conflict with - # /usr/${CMAKE_INSTALL_LIBDIR}/cmake which is installed by default - # by other packages on RedHat (most notably cmake-filesystem). Ensure - # that on these systems, flatbuffers does not package this path. - # This patch is required for cmake pre-3.17. - list(APPEND CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION "/usr/${CMAKE_INSTALL_LIBDIR}/cmake") - endif() -endif(UNIX) diff --git a/third_party/flatbuffers/CMake/Version.cmake b/third_party/flatbuffers/CMake/Version.cmake deleted file mode 100644 index df18fe47a08..00000000000 --- a/third_party/flatbuffers/CMake/Version.cmake +++ /dev/null @@ -1,39 +0,0 @@ -set(VERSION_MAJOR 24) -set(VERSION_MINOR 3) -set(VERSION_PATCH 25) -set(VERSION_COMMIT 0) - -if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git") - find_program(GIT git) - if(GIT) - execute_process( - COMMAND ${GIT} describe --tags - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - OUTPUT_VARIABLE GIT_DESCRIBE_DIRTY - OUTPUT_STRIP_TRAILING_WHITESPACE - RESULT_VARIABLE GIT_DESCRIBE_RESULT - ) - - if(GIT_DESCRIBE_RESULT EQUAL 0) - # Test if the most recent Git tag matches the pattern "v..*" - if(GIT_DESCRIBE_DIRTY MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+.*") - string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}") - string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}") - string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}") - string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_DESCRIBE_DIRTY}") - # If the tag points to the commit, then only the tag is shown in "git describe" - if(VERSION_COMMIT STREQUAL GIT_DESCRIBE_DIRTY) - set(VERSION_COMMIT 0) - endif() - else() - message(WARNING "\"${GIT_DESCRIBE_DIRTY}\" does not match pattern v..-") - endif() - else() - message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}\nMake sure you cloned with tags or run 'git fetch --tags'.") - endif() - else() - message(WARNING "git is not found") - endif() -endif() - -message(STATUS "Proceeding with version: ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}") diff --git a/third_party/flatbuffers/CMake/flatbuffers-config-version.cmake.in b/third_party/flatbuffers/CMake/flatbuffers-config-version.cmake.in deleted file mode 100644 index a553ab12c75..00000000000 --- a/third_party/flatbuffers/CMake/flatbuffers-config-version.cmake.in +++ /dev/null @@ -1,11 +0,0 @@ -set(PACKAGE_VERSION "@VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@") - -# Check whether the requested PACKAGE_FIND_VERSION is compatible -if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}") - set(PACKAGE_VERSION_COMPATIBLE FALSE) -else() - set(PACKAGE_VERSION_COMPATIBLE TRUE) - if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}") - set(PACKAGE_VERSION_EXACT TRUE) - endif() -endif() diff --git a/third_party/flatbuffers/CMake/flatbuffers-config.cmake b/third_party/flatbuffers/CMake/flatbuffers-config.cmake deleted file mode 100644 index 0c32c2fe2bf..00000000000 --- a/third_party/flatbuffers/CMake/flatbuffers-config.cmake +++ /dev/null @@ -1,4 +0,0 @@ -include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersTargets.cmake" OPTIONAL) -include("${CMAKE_CURRENT_LIST_DIR}/FlatcTargets.cmake" OPTIONAL) -include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersSharedTargets.cmake" OPTIONAL) -include("${CMAKE_CURRENT_LIST_DIR}/BuildFlatBuffers.cmake" OPTIONAL) \ No newline at end of file diff --git a/third_party/flatbuffers/CMake/flatbuffers.pc.in b/third_party/flatbuffers/CMake/flatbuffers.pc.in deleted file mode 100644 index 110770aba70..00000000000 --- a/third_party/flatbuffers/CMake/flatbuffers.pc.in +++ /dev/null @@ -1,9 +0,0 @@ -libdir=@CMAKE_INSTALL_FULL_LIBDIR@ -includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ - -Name: FlatBuffers -Description: Memory Efficient Serialization Library -Version: @VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@ - -Libs: -L${libdir} -lflatbuffers -Cflags: -I${includedir} diff --git a/third_party/flatbuffers/CMakeLists.txt b/third_party/flatbuffers/CMakeLists.txt deleted file mode 100644 index c03688533a7..00000000000 --- a/third_party/flatbuffers/CMakeLists.txt +++ /dev/null @@ -1,718 +0,0 @@ -# This is the legacy minimum version flatbuffers supported for a while. -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) - -project(FlatBuffers - VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH} - LANGUAGES CXX) - -# 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" OFF) -option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark." - 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_STRICT_MODE - "Build flatbuffers with all warnings as errors (-Werror or /WX)." - OFF) - -if(NOT DEFINED FLATBUFFERS_CPP_STD) - set(FLATBUFFERS_CPP_STD 11) -endif() - -set(MSVC_LIKE OFF) -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}) - set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}") - set_property(GLOBAL PROPERTY RULE_LAUNCH_CUSTOM "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}") - set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}") -endif() - -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_LIKE) - 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=$) - -if(NOT WIN32) - check_symbol_exists(realpath "stdlib.h" HAVE_REALPATH) - if(NOT HAVE_REALPATH) - add_definitions(-DFLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION) - endif() -endif() - -set(FlatBuffers_Library_SRCS - include/flatbuffers/allocator.h - include/flatbuffers/array.h - include/flatbuffers/base.h - include/flatbuffers/buffer.h - include/flatbuffers/buffer_ref.h - include/flatbuffers/default_allocator.h - include/flatbuffers/detached_buffer.h - include/flatbuffers/code_generator.h - include/flatbuffers/file_manager.h - include/flatbuffers/flatbuffer_builder.h - include/flatbuffers/flatbuffers.h - include/flatbuffers/flexbuffers.h - include/flatbuffers/flex_flat_util.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_binary.cpp - src/idl_gen_text.cpp - src/idl_gen_cpp.cpp - src/idl_gen_csharp.cpp - src/idl_gen_dart.cpp - src/idl_gen_kotlin.cpp - src/idl_gen_kotlin_kmp.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_rust.cpp - src/idl_gen_fbs.cpp - src/idl_gen_grpc.cpp - src/idl_gen_json_schema.cpp - src/idl_gen_swift.cpp - src/file_name_saving_file_manager.cpp - src/file_binary_writer.cpp - src/file_writer.cpp - src/idl_namer.h - src/namer.h - src/flatc.cpp - src/flatc_main.cpp - src/bfbs_gen.h - src/bfbs_gen_lua.h - src/bfbs_gen_nim.h - src/bfbs_namer.h - include/flatbuffers/code_generators.h - src/binary_annotator.h - src/binary_annotator.cpp - src/annotated_binary_text_gen.h - src/annotated_binary_text_gen.cpp - src/bfbs_gen_lua.cpp - src/bfbs_gen_nim.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/evolution_test.cpp - tests/flexbuffers_test.cpp - tests/fuzz_test.cpp - tests/json_test.cpp - tests/key_field_test.cpp - tests/monster_test.cpp - tests/optional_scalars_test.cpp - tests/parser_test.cpp - tests/proto_test.cpp - tests/reflection_test.cpp - tests/test.cpp - tests/test_assert.h - tests/test_assert.cpp - tests/test_builder.h - tests/test_builder.cpp - tests/util_test.cpp - tests/native_type_test_impl.h - tests/native_type_test_impl.cpp - tests/alignment_test.h - tests/alignment_test.cpp - tests/64bit/offset64_test.h - tests/64bit/offset64_test.cpp - include/flatbuffers/code_generators.h - src/code_generators.cpp -) - -set(FlatBuffers_Tests_CPP17_SRCS - ${FlatBuffers_Library_SRCS} - tests/test_assert.h - tests/test_assert.cpp - tests/cpp17/test_cpp17.cpp -) - -set(FlatBuffers_Sample_Binary_SRCS - samples/sample_binary.cpp -) - -set(FlatBuffers_Sample_Text_SRCS - ${FlatBuffers_Library_SRCS} - samples/sample_text.cpp -) - -set(FlatBuffers_Sample_BFBS_SRCS - ${FlatBuffers_Library_SRCS} - samples/sample_bfbs.cpp -) - -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 -) - -# 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) - 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}") - -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(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 - 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_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) - set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON) - endif() - endif() -endfunction() - -include_directories(include) -include_directories(grpc) - -# Creates an interface library that stores the configuration settings that each -# target links too. This is a compromise between setting configuration globally -# with add_compile_options() and the more targetted target_compile_options(). -# This way each target in this file can share settings and override them if -# needed. -add_library(ProjectConfig INTERFACE) -target_compile_features(ProjectConfig - INTERFACE - cxx_std_${FLATBUFFERS_CPP_STD} -) - -# Force the standard to be met. -set(CMAKE_CXX_STANDARD_REQUIRED ON) - -# We shouldn't rely on any compiler-extensions to make things work. -set(CMAKE_CXX_EXTENSIONS OFF) - -if(MSVC_LIKE) - target_compile_options(ProjectConfig - INTERFACE - /W4 - $<$: - /WX # Treat all compiler warnings as errors - > - /wd4512 # C4512: assignment operator could not be generated - /wd4316 # C4316: object allocated on the heap may not be aligned - /wd4456 # C4456: hides previous local declaration - $<$: - /D_CRT_SECURE_NO_WARNINGS - > - ) -else() - target_compile_options(ProjectConfig - INTERFACE - -Wall - $<$: - -Werror # Treat all compiler warnings as errors - - -fno-rtti # Disable runtime type information - - $<$: - # False positive string overflow - # https://github.com/google/flatbuffers/issues/7366 - -Wno-error=stringop-overflow - > - > - -pedantic - -Wextra - -Wno-unused-parameter - -Wold-style-cast - -fsigned-char - -Wnon-virtual-dtor - - # This isn't working for some reason: $<$: - $<$: - -Wnewline-eof - -Wno-unknown-warning-option - -Wmissing-declarations - -Wzero-as-null-pointer-constant - $<$,3.8>: - -Wimplicit-fallthrough - -Wextra-semi - $<$: - -Werror=unused-private-field - > - > - > - - $<$: - $<$,4.4>: - -Wunused-result - -Wunused-parameter - -Werror=unused-parameter - -Wmissing-declarations - > - $<$,4.7>: - -Wzero-as-null-pointer-constant - > - $<$,7.0>: - -faligned-new - $<$: - -Werror=implicit-fallthrough=2 - > - > - $<$,8.0>: - -Wextra-semi - > - > - - $<$: - -g - -fprofile-arcs - -ftest-coverage - > - ) - - if(FLATBUFFERS_CODE_COVERAGE) - target_link_options(ProjectConfig - INTERFACE - -fprofile-arcs - -ftest-coverage - ) - endif() -endif() - -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 - $ - ) - target_link_libraries(flatbuffers PRIVATE $) - - 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_link_libraries(flatc PRIVATE $) - target_compile_options(flatc - PRIVATE - $<$,$>: - /MT - > - ) - - 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 $) - 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}) - target_link_libraries(flathash PRIVATE $) -endif() - -if(FLATBUFFERS_BUILD_SHAREDLIB) - add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS}) - target_link_libraries(flatbuffers_shared PRIVATE $) - # 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() - -function(compile_schema SRC_FBS OPT OUT_GEN_FILE) - 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}" - ${OPT} - -o "${SRC_FBS_DIR}" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc ${SRC_FBS} - COMMENT "flatc generation: `${SRC_FBS}` -> `${GEN_HEADER}`" - ) - set(${OUT_GEN_FILE} ${GEN_HEADER} PARENT_SCOPE) -endfunction() - -function(compile_schema_for_test SRC_FBS OPT) - compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE) - target_sources(flattests PRIVATE ${GEN_FILE}) -endfunction() - -function(compile_schema_for_samples SRC_FBS OPT) - compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE) - target_sources(flatsample PRIVATE ${GEN_FILE}) -endfunction() - -if(FLATBUFFERS_BUILD_TESTS) - add_executable(flattests ${FlatBuffers_Tests_SRCS}) - target_link_libraries(flattests PRIVATE $) - target_include_directories(flattests PUBLIC - # Ideally everything is fully qualified from the root directories - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} - # TODO(derekbailey): update includes to fully qualify src/ and tests/ - src - tests - ${CMAKE_CURRENT_BINARY_DIR}/tests - ) - - # Have tests load data from the source directory, not the build directory. - add_definitions(-DFLATBUFFERS_TEST_PATH_PREFIX=${CMAKE_CURRENT_SOURCE_DIR}/) - - # The flattest target needs some generated files - SET(FLATC_OPT --cpp --gen-mutable --gen-object-api --reflect-names) - SET(FLATC_OPT_COMP ${FLATC_OPT};--gen-compare) - SET(FLATC_OPT_SCOPED_ENUMS ${FLATC_OPT_COMP};--scoped-enums) - - compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}") - compile_schema_for_test(tests/arrays_test.fbs "${FLATC_OPT_SCOPED_ENUMS}") - compile_schema_for_test(tests/native_inline_table_test.fbs "${FLATC_OPT_COMP}") - compile_schema_for_test(tests/native_type_test.fbs "${FLATC_OPT}") - compile_schema_for_test(tests/key_field/key_field_sample.fbs "${FLATC_OPT_COMP}") - compile_schema_for_test(tests/64bit/test_64bit.fbs "${FLATC_OPT_COMP};--bfbs-gen-embed") - compile_schema_for_test(tests/64bit/evolution/v1.fbs "${FLATC_OPT_COMP}") - compile_schema_for_test(tests/64bit/evolution/v2.fbs "${FLATC_OPT_COMP}") - compile_schema_for_test(tests/union_underlying_type_test.fbs "${FLATC_OPT_SCOPED_ENUMS}") - - if(FLATBUFFERS_CODE_SANITIZE) - add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE}) - endif() - - include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples) - - add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS}) - add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS}) - add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS}) - - # Add a library so there is a single target that the generated samples can - # link too. - if(MSVC OR ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.20.0") - add_library(flatsample INTERFACE) - else() - add_library(flatsample STATIC) - endif() - - # Since flatsample has no sources, we have to explicitly set the linker lang. - set_target_properties(flatsample PROPERTIES LINKER_LANGUAGE CXX) - - compile_schema_for_samples(samples/monster.fbs "${FLATC_OPT_COMP}") - - target_link_libraries(flatsamplebinary PRIVATE $ flatsample) - target_link_libraries(flatsampletext PRIVATE $ flatsample) - target_link_libraries(flatsamplebfbs PRIVATE $ flatsample) - - if(FLATBUFFERS_BUILD_CPP17) - add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS}) - target_link_libraries(flattests_cpp17 PRIVATE $) - target_include_directories(flattests_cpp17 PUBLIC src tests) - 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}) - endif() - endif(FLATBUFFERS_BUILD_CPP17) -endif() - -if(FLATBUFFERS_BUILD_GRPCTEST) - 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}) - target_link_libraries(grpctest - PRIVATE - $ - gRPC::grpc++_unsecure - gRPC::gpr - pthread - dl - ) -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/BuildFlatBuffers.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake" - DESTINATION ${FB_CMAKE_DIR} - ) - - if(FLATBUFFERS_BUILD_FLATLIB) - install( - TARGETS flatbuffers EXPORT FlatBuffersTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} - ) - - 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) - 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} - ) - - 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() - -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) - 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 $ - $) diff --git a/third_party/flatbuffers/CONTRIBUTING.md b/third_party/flatbuffers/CONTRIBUTING.md deleted file mode 100644 index 17428add545..00000000000 --- a/third_party/flatbuffers/CONTRIBUTING.md +++ /dev/null @@ -1,42 +0,0 @@ -Contributing {#contributing} -============ - -Want to contribute? Great! First, read this page (including the small print at -the end). - -# Before you contribute -Before we can use your code, you must sign the -[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) -(CLA), which you can do online. The CLA is necessary mainly because you own the -copyright to your changes, even after your contribution becomes part of our -codebase, so we need your permission to use and distribute your code. We also -need to be sure of various other things—for instance that you'll tell us if you -know that your code infringes on other people's patents. You don't have to sign -the CLA until after you've submitted your code for review and a member has -approved it, but you must do it before we can put your code into our codebase. -Before you start working on a larger contribution, you should get in touch with -us first through the issue tracker with your idea so that we can help out and -possibly guide you. Coordinating up front makes it much easier to avoid -frustration later on. - -# Code reviews -All submissions, including submissions by project members, require review. We -use Github pull requests for this purpose. - -Some tips for good pull requests: -* Use our code - [style guide](https://google.github.io/styleguide/cppguide.html). - When in doubt, try to stay true to the existing code of the project. -* Write a descriptive commit message. What problem are you solving and what - are the consequences? Where and what did you test? Some good tips: - [here](http://robots.thoughtbot.com/5-useful-tips-for-a-better-commit-message) - and [here](https://www.kernel.org/doc/Documentation/SubmittingPatches). -* If your PR consists of multiple commits which are successive improvements / - fixes to your first commit, consider squashing them into a single commit - (`git rebase -i`) such that your PR is a single commit on top of the current - HEAD. This make reviewing the code so much easier, and our history more - readable. - -# The small print -Contributions made by corporations are covered by a different agreement than -the one above, the Software Grant and Corporate Contributor License Agreement. diff --git a/third_party/flatbuffers/FlatBuffers.podspec b/third_party/flatbuffers/FlatBuffers.podspec deleted file mode 100644 index 2aa69e2a027..00000000000 --- a/third_party/flatbuffers/FlatBuffers.podspec +++ /dev/null @@ -1,21 +0,0 @@ -Pod::Spec.new do |s| - s.name = 'FlatBuffers' - s.version = '24.3.25' - s.summary = 'FlatBuffers: Memory Efficient Serialization Library' - - s.description = "FlatBuffers is a cross platform serialization library architected for - maximum memory efficiency. It allows you to directly access serialized - data without parsing/unpacking it first, while still having great - forwards/backwards compatibility." - - s.homepage = 'https://github.com/google/flatbuffers' - s.license = { :type => 'Apache2.0', :file => 'LICENSE' } - s.author = { 'mustii' => 'mustii@mmk.one' } - s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => s.version.to_s, :submodules => true } - - s.ios.deployment_target = '11.0' - s.osx.deployment_target = '10.14' - - s.swift_version = '5.0' - s.source_files = 'swift/Sources/Flatbuffers/*.swift' -end diff --git a/third_party/flatbuffers/Formatters.md b/third_party/flatbuffers/Formatters.md deleted file mode 100644 index 877c5f2010a..00000000000 --- a/third_party/flatbuffers/Formatters.md +++ /dev/null @@ -1,22 +0,0 @@ -# Format Guidelines - -If you are interesting in contributing to the flatbuffers project, please take a second to read this document. Each language has it's own set of rules, that are defined in their respective formatter/linter documents. - -# Notes - -- Run the linter on the language you are working on before making a Pull Request. -- DONT format/lint the generated code. - -# Languages - -## C++ - -C++ uses `clang-format` as it's formatter. Run the following script `sh scripts/clang-format-git.sh`, and it should style the C++ code according to [google style guide](https://google.github.io/styleguide/cppguide.html). - -## Swift - -Swift uses swiftformat as it's formatter. Take a look at [how to install here](https://github.com/nicklockwood/SwiftFormat/blob/master/README.md#how-do-i-install-it). Run the following command `swiftformat --config swift.swiftformat .` in the root directory of the project - -## Typescript - -Typescript uses eslint as it's linter. Take a look at [how to install here](https://eslint.org/docs/user-guide/getting-started). Run the following command `eslint ts/** --ext .ts` in the root directory of the project \ No newline at end of file diff --git a/third_party/flatbuffers/LICENSE b/third_party/flatbuffers/LICENSE deleted file mode 100644 index d6456956733..00000000000 --- a/third_party/flatbuffers/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/third_party/flatbuffers/Package.swift b/third_party/flatbuffers/Package.swift deleted file mode 100644 index 0fc26da7601..00000000000 --- a/third_party/flatbuffers/Package.swift +++ /dev/null @@ -1,36 +0,0 @@ -// swift-tools-version:5.6 -/* - * Copyright 2020 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. - */ - -import PackageDescription - -let package = Package( - name: "FlatBuffers", - platforms: [ - .iOS(.v11), - .macOS(.v10_14), - ], - products: [ - .library( - name: "FlatBuffers", - targets: ["FlatBuffers"]), - ], - targets: [ - .target( - name: "FlatBuffers", - dependencies: [], - path: "swift/Sources"), - ]) diff --git a/third_party/flatbuffers/Package@swift-5.5.swift b/third_party/flatbuffers/Package@swift-5.5.swift deleted file mode 100644 index 13313560ee0..00000000000 --- a/third_party/flatbuffers/Package@swift-5.5.swift +++ /dev/null @@ -1,37 +0,0 @@ -// swift-tools-version:5.5 -/* - * Copyright 2020 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. - */ - -import PackageDescription - -let package = Package( - name: "FlatBuffers", - platforms: [ - .iOS(.v11), - .macOS(.v10_14), - ], - products: [ - .library( - name: "FlatBuffers", - targets: ["FlatBuffers"]), - ], - targets: [ - .target( - name: "FlatBuffers", - dependencies: [], - path: "swift/Sources"), - ]) - diff --git a/third_party/flatbuffers/README.md b/third_party/flatbuffers/README.md deleted file mode 100644 index 47d506720e1..00000000000 --- a/third_party/flatbuffers/README.md +++ /dev/null @@ -1,118 +0,0 @@ -![logo](http://google.github.io/flatbuffers/fpl_logo_small.png) FlatBuffers -=========== - -![Build status](https://github.com/google/flatbuffers/actions/workflows/build.yml/badge.svg?branch=master) -[![BuildKite status](https://badge.buildkite.com/7979d93bc6279aa539971f271253c65d5e8fe2fe43c90bbb25.svg)](https://buildkite.com/bazel/flatbuffers) -[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/flatbuffers.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:flatbuffers) -[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers/badge)](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers) -[![Join the chat at https://gitter.im/google/flatbuffers](https://badges.gitter.im/google/flatbuffers.svg)](https://gitter.im/google/flatbuffers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Discord Chat](https://img.shields.io/discord/656202785926152206.svg)](https:///discord.gg/6qgKs3R) -[![Twitter Follow](https://img.shields.io/twitter/follow/wvo.svg?style=social)](https://twitter.com/wvo) -[![Twitter Follow](https://img.shields.io/twitter/follow/dbaileychess.svg?style=social)](https://twitter.com/dbaileychess) - - -**FlatBuffers** is a cross platform serialization library architected for -maximum memory efficiency. It allows you to directly access serialized data without parsing/unpacking it first, while still having great forwards/backwards compatibility. - -## Quick Start - -1. Build the compiler for flatbuffers (`flatc`) - - Use `cmake` to create the build files for your platform and then perform the compliation (Linux example). - - ``` - cmake -G "Unix Makefiles" - make -j - ``` - -2. Define your flatbuffer schema (`.fbs`) - - Write the [schema](https://flatbuffers.dev/flatbuffers_guide_writing_schema.html) to define the data you want to serialize. See [monster.fbs](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs) for an example. - -3. Generate code for your language(s) - - Use the `flatc` compiler to take your schema and generate language-specific code: - - ``` - ./flatc --cpp --rust monster.fbs - ``` - - Which generates `monster_generated.h` and `monster_generated.rs` files. - -4. Serialize data - - Use the generated code, as well as the `FlatBufferBuilder` to construct your serialized buffer. ([`C++` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp#L24-L56)) - -5. Transmit/store/save Buffer - - Use your serialized buffer however you want. Send it to someone, save it for later, etc... - -6. Read the data - - Use the generated accessors to read the data from the serialized buffer. - - It doesn't need to be the same language/schema version, FlatBuffers ensures the data is readable across languages and schema versions. See the [`Rust` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs#L92-L106) reading the data written by `C++`. - -## Documentation - -**Go to our [landing page][] to browse our documentation.** - -## Supported operating systems -- Windows -- macOS -- Linux -- Android -- And any others with a recent C++ compiler (C++ 11 and newer) - -## Supported programming languages - -Code generation and runtime libraries for many popular languages. - -1. C -1. C++ - [snapcraft.io](https://snapcraft.io/flatbuffers) -1. C# - [nuget.org](https://www.nuget.org/packages/Google.FlatBuffers) -1. Dart - [pub.dev](https://pub.dev/packages/flat_buffers) -1. Go - [go.dev](https://pkg.go.dev/github.com/google/flatbuffers) -1. Java - [Maven](https://search.maven.org/artifact/com.google.flatbuffers/flatbuffers-java) -1. JavaScript - [NPM](https://www.npmjs.com/package/flatbuffers) -1. Kotlin -1. Lobster -1. Lua -1. PHP -1. Python - [PyPI](https://pypi.org/project/flatbuffers/) -1. Rust - [crates.io](https://crates.io/crates/flatbuffers) -1. Swift - [swiftpackageindex](https://swiftpackageindex.com/google/flatbuffers) -1. TypeScript - [NPM](https://www.npmjs.com/package/flatbuffers) -1. Nim - -## Versioning - -FlatBuffers does not follow traditional SemVer versioning (see [rationale](https://github.com/google/flatbuffers/wiki/Versioning)) but rather uses a format of the date of the release. - -## Contribution - -* [FlatBuffers Issues Tracker][] to submit an issue. -* [stackoverflow.com][] with [`flatbuffers` tag][] for any questions regarding FlatBuffers. - -*To contribute to this project,* see [CONTRIBUTING][]. - -## Community - -* [Discord Server](https:///discord.gg/6qgKs3R) - -## Security - -Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities. - -## Licensing -*Flatbuffers* is licensed under the Apache License, Version 2.0. See [LICENSE][] for the full license text. - -
- - [CONTRIBUTING]: http://github.com/google/flatbuffers/blob/master/CONTRIBUTING.md - [`flatbuffers` tag]: https://stackoverflow.com/questions/tagged/flatbuffers - [FlatBuffers Google Group]: https://groups.google.com/forum/#!forum/flatbuffers - [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 diff --git a/third_party/flatbuffers/SECURITY.md b/third_party/flatbuffers/SECURITY.md deleted file mode 100644 index c61f66f84a0..00000000000 --- a/third_party/flatbuffers/SECURITY.md +++ /dev/null @@ -1,11 +0,0 @@ -# Security Policy - -## Reporting a Vulnerability - -To report a security issue, please use http://g.co/vulnz. We use -http://g.co/vulnz for our intake, and do coordination and disclosure here on -GitHub (including using GitHub Security Advisory). The Google Security Team will -respond within 5 working days of your report on g.co/vulnz. - -Select the `I want to report a technical security or an abuse risk related bug -in a Google product (SQLi, XSS, etc.)` option and complete the form. diff --git a/third_party/flatbuffers/WORKSPACE b/third_party/flatbuffers/WORKSPACE deleted file mode 100644 index e56d4ce364b..00000000000 --- a/third_party/flatbuffers/WORKSPACE +++ /dev/null @@ -1,169 +0,0 @@ -workspace(name = "com_github_google_flatbuffers") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file") - -http_archive( - name = "platforms", - sha256 = "3a561c99e7bdbe9173aa653fd579fe849f1d8d67395780ab4770b1f381431d51", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz", - "https://github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz", - ], -) - -http_archive( - name = "build_bazel_rules_apple", - sha256 = "34c41bfb59cdaea29ac2df5a2fa79e5add609c71bb303b2ebb10985f93fa20e7", - url = "https://github.com/bazelbuild/rules_apple/releases/download/3.1.1/rules_apple.3.1.1.tar.gz", -) - -load( - "@build_bazel_rules_apple//apple:repositories.bzl", - "apple_rules_dependencies", -) - -apple_rules_dependencies() - -http_archive( - name = "build_bazel_rules_swift", - sha256 = "a2fd565e527f83fb3f9eb07eb9737240e668c9242d3bc318712efa54a7deda97", - url = "https://github.com/bazelbuild/rules_swift/releases/download/0.27.0/rules_swift.0.27.0.tar.gz", -) - -load( - "@build_bazel_rules_swift//swift:repositories.bzl", - "swift_rules_dependencies", -) - -swift_rules_dependencies() - -load( - "@build_bazel_rules_swift//swift:extras.bzl", - "swift_rules_extra_dependencies", -) - -swift_rules_extra_dependencies() - -http_archive( - name = "io_bazel_rules_go", - sha256 = "278b7ff5a826f3dc10f04feaf0b70d48b68748ccd512d7f98bf442077f043fe3", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip", - "https://github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip", - ], -) - -load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies") - -go_rules_dependencies() - -##### Protobuf -_PROTOBUF_VERSION = "3.15.2" - -http_archive( - name = "com_google_protobuf", - strip_prefix = "protobuf-" + _PROTOBUF_VERSION, - urls = [ - "https://github.com/protocolbuffers/protobuf/archive/v" + _PROTOBUF_VERSION + ".tar.gz", - ], -) - -##### GRPC -_GRPC_VERSION = "1.49.0" # https://github.com/grpc/grpc/releases/tag/v1.48.0 - -http_archive( - name = "com_github_grpc_grpc", - patch_args = ["-p1"], - patches = ["//grpc:build_grpc_with_cxx14.patch"], - sha256 = "15715e1847cc9e42014f02c727dbcb48e39dbdb90f79ad3d66fe4361709ff935", - strip_prefix = "grpc-" + _GRPC_VERSION, - urls = ["https://github.com/grpc/grpc/archive/refs/tags/v" + _GRPC_VERSION + ".tar.gz"], -) - -load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps") - -grpc_deps() - -load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps") - -grpc_extra_deps() - -# rules_go from https://github.com/bazelbuild/rules_go/releases/tag/v0.34.0 - -http_archive( - name = "aspect_rules_js", - sha256 = "76a04ef2120ee00231d85d1ff012ede23963733339ad8db81f590791a031f643", - strip_prefix = "rules_js-1.34.1", - url = "https://github.com/aspect-build/rules_js/releases/download/v1.34.1/rules_js-v1.34.1.tar.gz", -) - -load("@aspect_rules_js//js:repositories.bzl", "rules_js_dependencies") - -rules_js_dependencies() - -load("@aspect_rules_js//npm:npm_import.bzl", "npm_translate_lock", "pnpm_repository") - -pnpm_repository(name = "pnpm") - -http_archive( - name = "aspect_rules_ts", - sha256 = "4c3f34fff9f96ffc9c26635d8235a32a23a6797324486c7d23c1dfa477e8b451", - strip_prefix = "rules_ts-1.4.5", - url = "https://github.com/aspect-build/rules_ts/releases/download/v1.4.5/rules_ts-v1.4.5.tar.gz", -) - -load("@aspect_rules_ts//ts:repositories.bzl", "rules_ts_dependencies") - -rules_ts_dependencies( - # Since rules_ts doesn't always have the newest integrity hashes, we - # compute it manually here. - # $ curl --silent https://registry.npmjs.org/typescript/5.3.3 | jq ._integrity - ts_integrity = "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", - ts_version_from = "//:package.json", -) - -load("@rules_nodejs//nodejs:repositories.bzl", "DEFAULT_NODE_VERSION", "nodejs_register_toolchains") - -nodejs_register_toolchains( - name = "nodejs", - node_version = DEFAULT_NODE_VERSION, -) - -npm_translate_lock( - name = "npm", - npmrc = "//:.npmrc", - pnpm_lock = "//:pnpm-lock.yaml", - # Set this to True when the lock file needs to be updated, commit the - # changes, then set to False again. - update_pnpm_lock = False, - verify_node_modules_ignored = "//:.bazelignore", -) - -load("@npm//:repositories.bzl", "npm_repositories") - -npm_repositories() - -http_archive( - name = "aspect_rules_esbuild", - sha256 = "098e38e5ee868c14a6484ba263b79e57d48afacfc361ba30137c757a9c4716d6", - strip_prefix = "rules_esbuild-0.15.0", - url = "https://github.com/aspect-build/rules_esbuild/releases/download/v0.15.0/rules_esbuild-v0.15.0.tar.gz", -) - -# Register a toolchain containing esbuild npm package and native bindings -load("@aspect_rules_esbuild//esbuild:repositories.bzl", "LATEST_ESBUILD_VERSION", "esbuild_register_toolchains") - -esbuild_register_toolchains( - name = "esbuild", - esbuild_version = LATEST_ESBUILD_VERSION, -) - -http_file( - name = "bazel_linux_x86_64", - downloaded_file_path = "bazel", - executable = True, - sha256 = "e78fc3394deae5408d6f49a15c7b1e615901969ecf6e50d55ef899996b0b8458", - urls = [ - "https://github.com/bazelbuild/bazel/releases/download/6.3.2/bazel-6.3.2-linux-x86_64", - ], -) diff --git a/third_party/flatbuffers/build_defs.bzl b/third_party/flatbuffers/build_defs.bzl deleted file mode 100644 index fff235448fd..00000000000 --- a/third_party/flatbuffers/build_defs.bzl +++ /dev/null @@ -1,284 +0,0 @@ -# Description: -# BUILD rules for generating flatbuffer files in various languages. - -""" -Rules for building C++ flatbuffers with Bazel. -""" - -load("@rules_cc//cc:defs.bzl", "cc_library") - -TRUE_FLATC_PATH = "@com_github_google_flatbuffers//:flatc" - -DEFAULT_INCLUDE_PATHS = [ - "./", - "$(GENDIR)", - "$(BINDIR)", - "$(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", - "--no-includes", - "--gen-mutable", - "--reflect-names", - "--cpp-ptr-type flatbuffers::unique_ptr", -] - -def flatbuffer_library_public( - name, - srcs, - outs, - language_flag, - out_prefix = "", - includes = [], - 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, - tools = None, - extra_env = None, - **kwargs): - """Generates code files for reading/writing the given flatbuffers in the requested language using the public compiler. - - Args: - name: Rule name. - srcs: Source .fbs files. Sent in order to the compiler. - outs: Output files from flatc. - language_flag: Target language flag. One of [-c, -j, -js]. - out_prefix: Prepend this path to the front of all generated files except on - single source targets. Usually is a directory name. - includes: Optional, list of filegroups of schemas that the srcs depend on. - include_paths: Optional, list of paths the includes files can be found in. - flatc_args: Optional, list of additional arguments to pass to flatc. - reflection_name: Optional, if set this will generate the flatbuffer - reflection binaries for the schemas. - reflection_visibility: The visibility of the generated reflection Fileset. - output_to_bindir: Passed to genrule for output to bin directory. - compatible_with: Optional, The list of environments this rule can be - built for, in addition to default-supported environments. - restricted_to: Optional, The list of environments this rule can be built - 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. - tools: Optional, passed to genrule for list of tools to make available - during the action. - extra_env: Optional, must be a string of "VAR1=VAL1 VAR2=VAL2". These get - set as environment variables that "flatc_path" sees. - **kwargs: Passed to the underlying genrule. - - - This rule creates a filegroup(name) with all generated source files, and - optionally a Fileset([reflection_name]) with all generated reflection - binaries. - """ - reflection_include_paths = include_paths - if include_paths == None: - include_paths = default_include_paths(flatc_path) - include_paths_cmd = ["-I %s" % (s) for s in include_paths] - - extra_env = extra_env or "" - - # '$(@D)' when given a single source target will give the appropriate - # directory. Appending 'out_prefix' is only necessary when given a build - # target with multiple sources. - output_directory = ( - ("-o $(@D)/%s" % (out_prefix)) if len(srcs) > 1 else ("-o $(@D)") - ) - genrule_cmd = " ".join([ - "SRCS=($(SRCS));", - "for f in $${SRCS[@]:0:%s}; do" % len(srcs), - "OUTPUT_FILE=\"$(OUTS)\" %s $(location %s)" % (extra_env, flatc_path), - " ".join(include_paths_cmd), - " ".join(flatc_args), - language_flag, - output_directory, - "$$f;", - "done", - ]) - native.genrule( - name = name, - srcs = srcs + includes, - outs = outs, - output_to_bindir = output_to_bindir, - tools = (tools or []) + [flatc_path], - cmd = genrule_cmd, - compatible_with = compatible_with, - target_compatible_with = target_compatible_with, - restricted_to = restricted_to, - message = "Generating flatbuffer files for %s:" % (name), - **kwargs - ) - if reflection_name: - if reflection_include_paths == None: - reflection_include_paths = default_include_paths(TRUE_FLATC_PATH) - reflection_include_paths_cmd = ["-I %s" % (s) for s in reflection_include_paths] - reflection_genrule_cmd = " ".join([ - "SRCS=($(SRCS));", - "for f in $${SRCS[@]:0:%s}; do" % len(srcs), - "$(location %s)" % (TRUE_FLATC_PATH), - "-b --schema", - " ".join(flatc_args), - " ".join(reflection_include_paths_cmd), - language_flag, - output_directory, - "$$f;", - "done", - ]) - reflection_outs = [ - (out_prefix + "%s.bfbs") % (s.replace(".fbs", "").split("/")[-1]) - for s in srcs - ] - native.genrule( - name = "%s_srcs" % reflection_name, - srcs = srcs + includes, - outs = reflection_outs, - output_to_bindir = output_to_bindir, - tools = [TRUE_FLATC_PATH], - compatible_with = compatible_with, - restricted_to = restricted_to, - target_compatible_with = target_compatible_with, - cmd = reflection_genrule_cmd, - message = "Generating flatbuffer reflection binary for %s:" % (name), - visibility = reflection_visibility, - ) - native.filegroup( - name = "%s_out" % reflection_name, - srcs = reflection_outs, - visibility = reflection_visibility, - compatible_with = compatible_with, - restricted_to = restricted_to, - ) - -def flatbuffer_cc_library( - name, - srcs, - srcs_filegroup_name = "", - outs = [], - out_prefix = "", - deps = [], - includes = [], - include_paths = None, - cc_include_paths = [], - flatc_args = DEFAULT_FLATC_ARGS, - visibility = None, - compatible_with = None, - restricted_to = None, - target_compatible_with = None, - srcs_filegroup_visibility = None, - gen_reflections = False): - """A cc_library with the generated reader/writers for the given flatbuffer definitions. - - Args: - name: Rule name. - srcs: Source .fbs files. Sent in order to the compiler. - srcs_filegroup_name: Name of the output filegroup that holds srcs. Pass this - filegroup into the `includes` parameter of any other - flatbuffer_cc_library that depends on this one's schemas. - outs: Additional outputs expected to be generated by flatc. - out_prefix: Prepend this path to the front of all generated files. Usually - is a directory name. - deps: Optional, list of other flatbuffer_cc_library's to depend on. Cannot be specified - alongside includes. - includes: Optional, list of filegroups of schemas that the srcs depend on. - Use of this is discouraged, and may be deprecated. - include_paths: Optional, list of paths the includes files can be found in. - cc_include_paths: Optional, list of paths to add to the cc_library includes attribute. - flatc_args: Optional list of additional arguments to pass to flatc - (e.g. --gen-mutable). - visibility: The visibility of the generated cc_library. By default, use the - default visibility of the project. - srcs_filegroup_visibility: The visibility of the generated srcs filegroup. - By default, use the value of the visibility parameter above. - gen_reflections: Optional, if true this will generate the flatbuffer - reflection binaries for the schemas. - compatible_with: Optional, The list of environments this rule can be built - for, in addition to default-supported environments. - restricted_to: Optional, The list of environments this rule can be built - for, instead of default-supported environments. - target_compatible_with: Optional, The list of target platform constraints - to use. - - This produces: - filegroup([name]_srcs): all generated .h files. - filegroup(srcs_filegroup_name if specified, or [name]_includes if not): - Other flatbuffer_cc_library's can pass this in for their `includes` - parameter, if they depend on the schemas in this library. - Fileset([name]_reflection): (Optional) all generated reflection binaries. - cc_library([name]): library with sources and flatbuffers deps. - """ - output_headers = [ - (out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1].split(":")[-1]) - for s in srcs - ] - if deps and includes: - # There is no inherent reason we couldn't support both, but this discourages - # use of includes without good reason. - fail("Cannot specify both deps and include in flatbuffer_cc_library.") - if deps: - includes = [d + "_includes" for d in deps] - reflection_name = "%s_reflection" % name if gen_reflections else "" - - srcs_lib = "%s_srcs" % (name) - flatbuffer_library_public( - name = srcs_lib, - srcs = srcs, - outs = outs + output_headers, - language_flag = "-c", - out_prefix = out_prefix, - includes = includes, - include_paths = include_paths, - flatc_args = flatc_args, - compatible_with = compatible_with, - restricted_to = restricted_to, - target_compatible_with = target_compatible_with, - reflection_name = reflection_name, - reflection_visibility = visibility, - ) - cc_library( - name = name, - hdrs = [ - ":" + srcs_lib, - ], - srcs = [ - ":" + srcs_lib, - ], - features = [ - "-parse_headers", - ], - deps = [ - "@com_github_google_flatbuffers//:runtime_cc", - "@com_github_google_flatbuffers//:flatbuffers", - ] + deps, - includes = cc_include_paths, - compatible_with = compatible_with, - restricted_to = restricted_to, - target_compatible_with = target_compatible_with, - linkstatic = 1, - visibility = visibility, - ) - - # A filegroup for the `srcs`. That is, all the schema files for this - # Flatbuffer set. - native.filegroup( - name = srcs_filegroup_name if srcs_filegroup_name else "%s_includes" % (name), - srcs = srcs + includes, - compatible_with = compatible_with, - restricted_to = restricted_to, - visibility = srcs_filegroup_visibility if srcs_filegroup_visibility != None else visibility, - ) diff --git a/third_party/flatbuffers/composer.json b/third_party/flatbuffers/composer.json deleted file mode 100644 index 807709c14df..00000000000 --- a/third_party/flatbuffers/composer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "google/flatbuffers", - "type": "library", - "description": "FlatBuffers for PHP", - "keywords": ["google", "flatbuffers", "serialization"], - "homepage": "https://github.com/google/flatbuffers", - "license": "Apache-2.0", - "require": { - "php": ">=5.4" - }, - "require-dev": { - }, - "autoload": { - "psr-4": { - "Google\\FlatBuffers\\": "php" - } - } -} \ No newline at end of file diff --git a/third_party/flatbuffers/conan/CMakeLists.txt b/third_party/flatbuffers/conan/CMakeLists.txt deleted file mode 100644 index 65f902876e1..00000000000 --- a/third_party/flatbuffers/conan/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -cmake_minimum_required(VERSION 2.8) - -message(STATUS "Conan FlatBuffers Wrapper") - -include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) -conan_basic_setup() - -if (WIN32 AND MSVC_LIKE AND FLATBUFFERS_BUILD_SHAREDLIB) - set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) -endif(WIN32 AND MSVC_LIKE AND FLATBUFFERS_BUILD_SHAREDLIB) - -include(${CMAKE_SOURCE_DIR}/CMakeListsOriginal.txt) diff --git a/third_party/flatbuffers/conan/build.py b/third_party/flatbuffers/conan/build.py deleted file mode 100644 index 62a37990794..00000000000 --- a/third_party/flatbuffers/conan/build.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -import os -import re -import subprocess -from cpt.packager import ConanMultiPackager - - - -def get_branch(): - try: - for line in subprocess.check_output("git branch", shell=True).decode().splitlines(): - line = line.strip() - if line.startswith("*") and " (HEAD detached" not in line: - return line.replace("*", "", 1).strip() - return "" - except Exception: - pass - return "" - - -def get_version(): - version = get_branch() - match = re.search(r"v(\d+\.\d+\.\d+.*)", version) - if match: - return match.group(1) - return version - - -def get_reference(username): - return "flatbuffers/{}@google/stable".format(get_version()) - - -if __name__ == "__main__": - login_username = os.getenv("CONAN_LOGIN_USERNAME", "aardappel") - username = os.getenv("CONAN_USERNAME", "google") - upload = os.getenv("CONAN_UPLOAD", "https://api.bintray.com/conan/aardappel/flatbuffers") - stable_branch_pattern = os.getenv("CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*") - test_folder = os.getenv("CPT_TEST_FOLDER", os.path.join("conan", "test_package")) - upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True) - - builder = ConanMultiPackager(reference=get_reference(username), - username=username, - login_username=login_username, - upload=upload, - stable_branch_pattern=stable_branch_pattern, - upload_only_when_stable=upload_only_when_stable, - test_folder=test_folder) - builder.add_common_builds(pure_c=False) - builder.run() diff --git a/third_party/flatbuffers/conan/test_package/CMakeLists.txt b/third_party/flatbuffers/conan/test_package/CMakeLists.txt deleted file mode 100644 index 9c1c78c582d..00000000000 --- a/third_party/flatbuffers/conan/test_package/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -project(test_package CXX) -cmake_minimum_required(VERSION 2.8.11) - -include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) -conan_basic_setup() - -add_executable(${PROJECT_NAME} test_package.cpp) -target_link_libraries(${PROJECT_NAME} ${CONAN_LIBS}) -set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 11) diff --git a/third_party/flatbuffers/conan/test_package/conanfile.py b/third_party/flatbuffers/conan/test_package/conanfile.py deleted file mode 100644 index 735e31d27bf..00000000000 --- a/third_party/flatbuffers/conan/test_package/conanfile.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from conans import ConanFile, CMake -import os - - -class TestPackageConan(ConanFile): - settings = "os", "compiler", "build_type", "arch" - generators = "cmake" - - def build(self): - cmake = CMake(self) - cmake.configure() - cmake.build() - - def test(self): - bin_path = os.path.join("bin", "test_package") - self.run(bin_path, run_environment=True) - self.run("flatc --version", run_environment=True) - self.run("flathash fnv1_16 conan", run_environment=True) diff --git a/third_party/flatbuffers/conan/test_package/test_package.cpp b/third_party/flatbuffers/conan/test_package/test_package.cpp deleted file mode 100644 index df7d577ae64..00000000000 --- a/third_party/flatbuffers/conan/test_package/test_package.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2018 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. - */ - -#include -#include -#include "flatbuffers/util.h" - -// Test to validate Conan package generated - -int main(int /*argc*/, const char * /*argv*/ []) { - - const std::string filename("conanbuildinfo.cmake"); - - if (flatbuffers::FileExists(filename.c_str())) { - std::cout << "File " << filename << " exists.\n"; - } else { - std::cout << "File " << filename << " does not exist.\n"; - return EXIT_FAILURE; - } - - return EXIT_SUCCESS; -} diff --git a/third_party/flatbuffers/conanfile.py b/third_party/flatbuffers/conanfile.py deleted file mode 100644 index 9d622908acd..00000000000 --- a/third_party/flatbuffers/conanfile.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""Conan recipe package for Google FlatBuffers -""" -import os -import shutil -from conans import ConanFile, CMake, tools - - -class FlatbuffersConan(ConanFile): - name = "flatbuffers" - license = "Apache-2.0" - url = "https://github.com/google/flatbuffers" - homepage = "http://google.github.io/flatbuffers/" - author = "Wouter van Oortmerssen" - topics = ("conan", "flatbuffers", "serialization", "rpc", "json-parser") - description = "Memory Efficient Serialization Library" - settings = "os", "compiler", "build_type", "arch" - options = {"shared": [True, False], "fPIC": [True, False]} - default_options = {"shared": False, "fPIC": True} - generators = "cmake" - exports = "LICENSE" - exports_sources = ["CMake/*", "include/*", "src/*", "grpc/*", "CMakeLists.txt", "conan/CMakeLists.txt"] - - def source(self): - """Wrap the original CMake file to call conan_basic_setup - """ - shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt") - shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt") - - def config_options(self): - """Remove fPIC option on Windows platform - """ - if self.settings.os == "Windows": - self.options.remove("fPIC") - - def configure_cmake(self): - """Create CMake instance and execute configure step - """ - cmake = CMake(self) - cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False - cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared - cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared - cmake.configure() - return cmake - - def build(self): - """Configure, build and install FlatBuffers using CMake. - """ - cmake = self.configure_cmake() - cmake.build() - - def package(self): - """Copy Flatbuffers' artifacts to package folder - """ - cmake = self.configure_cmake() - cmake.install() - self.copy(pattern="LICENSE", dst="licenses") - self.copy(pattern="FindFlatBuffers.cmake", dst=os.path.join("lib", "cmake", "flatbuffers"), src="CMake") - self.copy(pattern="flathash*", dst="bin", src="bin") - self.copy(pattern="flatc*", dst="bin", src="bin") - if self.settings.os == "Windows" and self.options.shared: - if self.settings.compiler == "Visual Studio": - shutil.move(os.path.join(self.package_folder, "lib", "%s.dll" % self.name), - os.path.join(self.package_folder, "bin", "%s.dll" % self.name)) - elif self.settings.compiler == "gcc": - shutil.move(os.path.join(self.package_folder, "lib", "lib%s.dll" % self.name), - os.path.join(self.package_folder, "bin", "lib%s.dll" % self.name)) - - def package_info(self): - """Collect built libraries names and solve flatc path. - """ - self.cpp_info.libs = tools.collect_libs(self) - self.user_info.flatc = os.path.join(self.package_folder, "bin", "flatc") diff --git a/third_party/flatbuffers/grpc/BUILD.bazel b/third_party/flatbuffers/grpc/BUILD.bazel deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/third_party/flatbuffers/grpc/README.md b/third_party/flatbuffers/grpc/README.md deleted file mode 100644 index f46258fcb16..00000000000 --- a/third_party/flatbuffers/grpc/README.md +++ /dev/null @@ -1,42 +0,0 @@ -GRPC implementation and test -============================ - -NOTE: files in `src/` are shared with the GRPC project, and maintained there -(any changes should be submitted to GRPC instead). These files are copied -from GRPC, and work with both the Protobuf and FlatBuffers code generator. - -`tests/` contains a GRPC specific test, you need to have built and installed -the GRPC libraries for this to compile. This test will build using the -`FLATBUFFERS_BUILD_GRPCTEST` option to the main FlatBuffers CMake project. - -## Building Flatbuffers with gRPC - -### Linux - -1. Download, build and install gRPC. See [instructions](https://github.com/grpc/grpc/tree/master/src/cpp). - * Lets say your gRPC clone is at `/your/path/to/grpc_repo`. - * Install gRPC in a custom directory by running `make install prefix=/your/path/to/grpc_repo/install`. -2. `export GRPC_INSTALL_PATH=/your/path/to/grpc_repo/install` -3. `export PROTOBUF_DOWNLOAD_PATH=/your/path/to/grpc_repo/third_party/protobuf` -4. `mkdir build ; cd build` -5. `cmake -DFLATBUFFERS_BUILD_GRPCTEST=ON -DGRPC_INSTALL_PATH=${GRPC_INSTALL_PATH} -DPROTOBUF_DOWNLOAD_PATH=${PROTOBUF_DOWNLOAD_PATH} ..` -6. `make` - -For Bazel users: - -```shell -$bazel test src/compiler/... -``` - -## Running FlatBuffer gRPC tests - -### Linux - -1. `export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${GRPC_INSTALL_PATH}/lib` -2. `make test ARGS=-V` - -For Bazel users: - -```shell -$bazel test tests/... -``` \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/boringssl.patch b/third_party/flatbuffers/grpc/boringssl.patch deleted file mode 100644 index 632499e2804..00000000000 --- a/third_party/flatbuffers/grpc/boringssl.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/CMakeLists.txt b/CMakeLists.txt -index 1645a264a..12f8ca999 100644 ---- a/CMakeLists.txt -+++ b/CMakeLists.txt -@@ -635,6 +635,8 @@ add_library( - src/ssl/tls_record.cc - ) - -+target_link_libraries(ssl crypto) -+ - add_executable( - bssl - diff --git a/third_party/flatbuffers/grpc/build_grpc.sh b/third_party/flatbuffers/grpc/build_grpc.sh deleted file mode 100755 index 49c5a60f0eb..00000000000 --- a/third_party/flatbuffers/grpc/build_grpc.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash - -grpc_1_39_0_githash=58602e20a3f3e48f24a4114c757099b25b947f7b - -function build_grpc () { - git clone https://github.com/grpc/grpc.git google/grpc - cd google/grpc - git checkout ${grpc_1_39_0_githash} - git submodule update --init - # Apply boringssl build patch - cd third_party/boringssl-with-bazel - git apply ../../../../grpc/boringssl.patch - cd ../.. - mkdir ../grpc_build - cd ../grpc_build - cmake ../grpc -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DABSL_ENABLE_INSTALL=ON -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=`pwd`/../grpc/install - cmake --build . --target install ${JOBS:+-j$JOBS} - cd ../.. -} - -GRPC_INSTALL_PATH=`pwd`/google/grpc/install -PROTOBUF_DOWNLOAD_PATH=`pwd`/google/grpc/third_party/protobuf - -build_grpc diff --git a/third_party/flatbuffers/grpc/build_grpc_with_cxx14.patch b/third_party/flatbuffers/grpc/build_grpc_with_cxx14.patch deleted file mode 100644 index 38cdfe9931b..00000000000 --- a/third_party/flatbuffers/grpc/build_grpc_with_cxx14.patch +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/bazel/copts.bzl b/bazel/copts.bzl -index 10be944f25..879518b92f 100644 ---- a/bazel/copts.bzl -+++ b/bazel/copts.bzl -@@ -59,4 +59,4 @@ GRPC_LLVM_WARNING_FLAGS = [ - GRPC_DEFAULT_COPTS = select({ - "//:use_strict_warning": GRPC_LLVM_WARNING_FLAGS + ["-DUSE_STRICT_WARNING=1"], - "//conditions:default": [], --}) -+}) + ["-std=c++14"] diff --git a/third_party/flatbuffers/grpc/examples/README.md b/third_party/flatbuffers/grpc/examples/README.md deleted file mode 100644 index c821218b38a..00000000000 --- a/third_party/flatbuffers/grpc/examples/README.md +++ /dev/null @@ -1,35 +0,0 @@ -## Languages known issues - -### Python - -- Assert the type required in your server/client since python is able to receive `Bytes array` or `utf8 strings`. - -```python -def SayHello(self, request, context): - # request might be a byte array or a utf8 string - - r = HelloRequest.HelloRequest().GetRootAs(request, 0) - reply = "Unknown" - if r.Name(): - reply = r.Name() - # Issues might happen if type checking isnt present. - # thus encoding it as a `reply.decode('UTF-8')` - return build_reply("welcome " + reply.decode('UTF-8')) - -``` - -This can be prevented by making sure all the requests coming to/from python are `Bytes array` - -```python -def say_hello(stub, builder): - hello_request = bytes(builder.Output()) - reply = stub.SayHello(hello_request) - r = HelloReply.HelloReply.GetRootAs(reply) - print(r.Message()) -``` - -### Go - -- Always requires the `content-type` of the payload to be set to `application/grpc+flatbuffers` - -example: `.SayHello(ctx, b, grpc.CallContentSubtype("flatbuffers"))` \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/go/format.sh b/third_party/flatbuffers/grpc/examples/go/format.sh deleted file mode 100644 index a7ee9e3156a..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/format.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash -# -# Copyright 2021 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. - -set -e - - -format_greeter() { - cd greeter - - # Format client - cd client - gofmt -w . - cd .. - - # Format server - cd server - gofmt -w . - cd .. - - cd .. -} - -format_greeter \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/.gitignore b/third_party/flatbuffers/grpc/examples/go/greeter/.gitignore deleted file mode 100644 index 535db5e315f..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -**/server -**/client \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/README.md b/third_party/flatbuffers/grpc/examples/go/greeter/README.md deleted file mode 100644 index 339050885c6..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Go Greeter example - -## Project Structure - - . - ├── server # Server module - ├── client # Client module - ├── models # Flatbuffers models & main grpc code. - └── README.md - -## How to run Server: - -- `cd server` - -- `go clean` - -- `go run main.go` - -## How to run Client: - -- `cd client` - -- `go clean` - -- `go run main.go --name NAME` \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/client/go.mod b/third_party/flatbuffers/grpc/examples/go/greeter/client/go.mod deleted file mode 100644 index d0f219855c7..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/client/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/google/flatbuffers/grpc/examples/go/greeter/client - -go 1.15 - -replace github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0 => ../models - -require ( - github.com/google/flatbuffers v2.0.8+incompatible - github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0 - google.golang.org/grpc v1.56.3 -) diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/client/main.go b/third_party/flatbuffers/grpc/examples/go/greeter/client/main.go deleted file mode 100644 index a7649126b63..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/client/main.go +++ /dev/null @@ -1,78 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "io" - "log" - "time" - - flatbuffers "github.com/google/flatbuffers/go" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - - models "github.com/google/flatbuffers/grpc/examples/go/greeter/models" -) - -var ( - addr = "3000" - name = flag.String("name", "Flatbuffers", "name to be sent to server :D") -) - -func printSayHello(client models.GreeterClient, name string) { - log.Printf("Name to be sent (%s)", name) - b := flatbuffers.NewBuilder(0) - i := b.CreateString(name) - models.HelloRequestStart(b) - models.HelloRequestAddName(b, i) - b.Finish(models.HelloRequestEnd(b)) - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - request, err := client.SayHello(ctx, b, grpc.CallContentSubtype("flatbuffers")) - if err != nil { - log.Fatalf("%v.SayHello(_) = _, %v: ", client, err) - } - log.Printf("server said %q", request.Message()) -} - -func printSayManyHello(client models.GreeterClient, name string) { - log.Printf("Name to be sent (%s)", name) - b := flatbuffers.NewBuilder(0) - i := b.CreateString(name) - models.HelloRequestStart(b) - models.HelloRequestAddName(b, i) - b.Finish(models.HelloRequestEnd(b)) - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - stream, err := client.SayManyHellos(ctx, b, grpc.CallContentSubtype("flatbuffers")) - if err != nil { - log.Fatalf("%v.SayManyHellos(_) = _, %v", client, err) - } - for { - request, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - log.Fatalf("%v.SayManyHellos(_) = _, %v", client, err) - } - log.Printf("server said %q", request.Message()) - } -} - -func main() { - flag.Parse() - conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", 3000), - grpc.WithTransportCredentials(insecure.NewCredentials()), - grpc.WithDefaultCallOptions(grpc.ForceCodec(flatbuffers.FlatbuffersCodec{}))) - if err != nil { - log.Fatalf("fail to dial: %v", err) - } - defer conn.Close() - client := models.NewGreeterClient(conn) - printSayHello(client, *name) - printSayManyHello(client, *name) -} diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/models/Greeter_grpc.go b/third_party/flatbuffers/grpc/examples/go/greeter/models/Greeter_grpc.go deleted file mode 100644 index 9a2405c765e..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/models/Greeter_grpc.go +++ /dev/null @@ -1,158 +0,0 @@ -//Generated by gRPC Go plugin -//If you make any local changes, they will be lost -//source: greeter - -package models - -import ( - context "context" - flatbuffers "github.com/google/flatbuffers/go" - grpc "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// Client API for Greeter service -type GreeterClient interface { - SayHello(ctx context.Context, in *flatbuffers.Builder, - opts ...grpc.CallOption) (*HelloReply, error) - SayManyHellos(ctx context.Context, in *flatbuffers.Builder, - opts ...grpc.CallOption) (Greeter_SayManyHellosClient, error) -} - -type greeterClient struct { - cc grpc.ClientConnInterface -} - -func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient { - return &greeterClient{cc} -} - -func (c *greeterClient) SayHello(ctx context.Context, in *flatbuffers.Builder, - opts ...grpc.CallOption) (*HelloReply, error) { - out := new(HelloReply) - err := c.cc.Invoke(ctx, "/models.Greeter/SayHello", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *greeterClient) SayManyHellos(ctx context.Context, in *flatbuffers.Builder, - opts ...grpc.CallOption) (Greeter_SayManyHellosClient, error) { - stream, err := c.cc.NewStream(ctx, &_Greeter_serviceDesc.Streams[0], "/models.Greeter/SayManyHellos", opts...) - if err != nil { - return nil, err - } - x := &greeterSayManyHellosClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Greeter_SayManyHellosClient interface { - Recv() (*HelloReply, error) - grpc.ClientStream -} - -type greeterSayManyHellosClient struct { - grpc.ClientStream -} - -func (x *greeterSayManyHellosClient) Recv() (*HelloReply, error) { - m := new(HelloReply) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for Greeter service -type GreeterServer interface { - SayHello(context.Context, *HelloRequest) (*flatbuffers.Builder, error) - SayManyHellos(*HelloRequest, Greeter_SayManyHellosServer) error - mustEmbedUnimplementedGreeterServer() -} - -type UnimplementedGreeterServer struct { -} - -func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*flatbuffers.Builder, error) { - return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") -} - -func (UnimplementedGreeterServer) SayManyHellos(*HelloRequest, Greeter_SayManyHellosServer) error { - return status.Errorf(codes.Unimplemented, "method SayManyHellos not implemented") -} - -func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {} - -type UnsafeGreeterServer interface { - mustEmbedUnimplementedGreeterServer() -} - -func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) { - s.RegisterService(&_Greeter_serviceDesc, srv) -} - -func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, - dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HelloRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(GreeterServer).SayHello(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/models.Greeter/SayHello", - } - - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) - } - return interceptor(ctx, in, info, handler) -} -func _Greeter_SayManyHellos_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(HelloRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(GreeterServer).SayManyHellos(m, &greeterSayManyHellosServer{stream}) -} - -type Greeter_SayManyHellosServer interface { - Send(*flatbuffers.Builder) error - grpc.ServerStream -} - -type greeterSayManyHellosServer struct { - grpc.ServerStream -} - -func (x *greeterSayManyHellosServer) Send(m *flatbuffers.Builder) error { - return x.ServerStream.SendMsg(m) -} - -var _Greeter_serviceDesc = grpc.ServiceDesc{ - ServiceName: "models.Greeter", - HandlerType: (*GreeterServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "SayHello", - Handler: _Greeter_SayHello_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "SayManyHellos", - Handler: _Greeter_SayManyHellos_Handler, - ServerStreams: true, - }, - }, -} diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/models/HelloReply.go b/third_party/flatbuffers/grpc/examples/go/greeter/models/HelloReply.go deleted file mode 100644 index 747db2d8725..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/models/HelloReply.go +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by the FlatBuffers compiler. DO NOT EDIT. - -package models - -import ( - flatbuffers "github.com/google/flatbuffers/go" -) - -type HelloReply struct { - _tab flatbuffers.Table -} - -func GetRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *HelloReply { - n := flatbuffers.GetUOffsetT(buf[offset:]) - x := &HelloReply{} - x.Init(buf, n+offset) - return x -} - -func FinishHelloReplyBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { - builder.Finish(offset) -} - -func GetSizePrefixedRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *HelloReply { - n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) - x := &HelloReply{} - x.Init(buf, n+offset+flatbuffers.SizeUint32) - return x -} - -func FinishSizePrefixedHelloReplyBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { - builder.FinishSizePrefixed(offset) -} - -func (rcv *HelloReply) Init(buf []byte, i flatbuffers.UOffsetT) { - rcv._tab.Bytes = buf - rcv._tab.Pos = i -} - -func (rcv *HelloReply) Table() flatbuffers.Table { - return rcv._tab -} - -func (rcv *HelloReply) Message() []byte { - o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) - if o != 0 { - return rcv._tab.ByteVector(o + rcv._tab.Pos) - } - return nil -} - -func HelloReplyStart(builder *flatbuffers.Builder) { - builder.StartObject(1) -} -func HelloReplyAddMessage(builder *flatbuffers.Builder, message flatbuffers.UOffsetT) { - builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(message), 0) -} -func HelloReplyEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { - return builder.EndObject() -} diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/models/HelloRequest.go b/third_party/flatbuffers/grpc/examples/go/greeter/models/HelloRequest.go deleted file mode 100644 index 3710cf5aafa..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/models/HelloRequest.go +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by the FlatBuffers compiler. DO NOT EDIT. - -package models - -import ( - flatbuffers "github.com/google/flatbuffers/go" -) - -type HelloRequest struct { - _tab flatbuffers.Table -} - -func GetRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT) *HelloRequest { - n := flatbuffers.GetUOffsetT(buf[offset:]) - x := &HelloRequest{} - x.Init(buf, n+offset) - return x -} - -func FinishHelloRequestBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { - builder.Finish(offset) -} - -func GetSizePrefixedRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT) *HelloRequest { - n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) - x := &HelloRequest{} - x.Init(buf, n+offset+flatbuffers.SizeUint32) - return x -} - -func FinishSizePrefixedHelloRequestBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { - builder.FinishSizePrefixed(offset) -} - -func (rcv *HelloRequest) Init(buf []byte, i flatbuffers.UOffsetT) { - rcv._tab.Bytes = buf - rcv._tab.Pos = i -} - -func (rcv *HelloRequest) Table() flatbuffers.Table { - return rcv._tab -} - -func (rcv *HelloRequest) Name() []byte { - o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) - if o != 0 { - return rcv._tab.ByteVector(o + rcv._tab.Pos) - } - return nil -} - -func HelloRequestStart(builder *flatbuffers.Builder) { - builder.StartObject(1) -} -func HelloRequestAddName(builder *flatbuffers.Builder, name flatbuffers.UOffsetT) { - builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(name), 0) -} -func HelloRequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { - return builder.EndObject() -} diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/models/go.mod b/third_party/flatbuffers/grpc/examples/go/greeter/models/go.mod deleted file mode 100644 index 31d6cdcb5e2..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/models/go.mod +++ /dev/null @@ -1,8 +0,0 @@ -module github.com/google/flatbuffers/grpc/examples/go/greeter/models - -go 1.15 - -require ( - github.com/google/flatbuffers v2.0.8+incompatible - google.golang.org/grpc v1.56.3 -) diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/server/go.mod b/third_party/flatbuffers/grpc/examples/go/greeter/server/go.mod deleted file mode 100644 index eeb9e538ae2..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/server/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/google/flatbuffers/grpc/examples/go/greeter/server - -go 1.15 - -replace github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0 => ../models - -require ( - github.com/google/flatbuffers v2.0.8+incompatible - github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0 - google.golang.org/grpc v1.56.3 -) diff --git a/third_party/flatbuffers/grpc/examples/go/greeter/server/main.go b/third_party/flatbuffers/grpc/examples/go/greeter/server/main.go deleted file mode 100644 index a5bb3a448e0..00000000000 --- a/third_party/flatbuffers/grpc/examples/go/greeter/server/main.go +++ /dev/null @@ -1,77 +0,0 @@ -package main - -import ( - "context" - "fmt" - "log" - "net" - - flatbuffers "github.com/google/flatbuffers/go" - models "github.com/google/flatbuffers/grpc/examples/go/greeter/models" - "google.golang.org/grpc" -) - -var ( - greetings = [...]string{"Hi", "Hallo", "Ciao"} -) - -type greeterServer struct { - models.UnimplementedGreeterServer -} - -func (s *greeterServer) SayHello(ctx context.Context, request *models.HelloRequest) (*flatbuffers.Builder, error) { - v := request.Name() - var m string - if v == nil { - m = "Unknown" - } else { - m = string(v) - } - b := flatbuffers.NewBuilder(0) - idx := b.CreateString("welcome " + m) - models.HelloReplyStart(b) - models.HelloReplyAddMessage(b, idx) - b.Finish(models.HelloReplyEnd(b)) - return b, nil -} - -func (s *greeterServer) SayManyHellos(request *models.HelloRequest, stream models.Greeter_SayManyHellosServer) error { - v := request.Name() - var m string - if v == nil { - m = "Unknown" - } else { - m = string(v) - } - b := flatbuffers.NewBuilder(0) - - for _, greeting := range greetings { - idx := b.CreateString(greeting + " " + m) - models.HelloReplyStart(b) - models.HelloReplyAddMessage(b, idx) - b.Finish(models.HelloReplyEnd(b)) - if err := stream.Send(b); err != nil { - return err - } - } - return nil -} - -func newServer() *greeterServer { - s := &greeterServer{} - return s -} - -func main() { - lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", 3000)) - if err != nil { - log.Fatalf("failed to listen: %v", err) - } - codec := &flatbuffers.FlatbuffersCodec{} - grpcServer := grpc.NewServer(grpc.ForceServerCodec(codec)) - models.RegisterGreeterServer(grpcServer, newServer()) - if err := grpcServer.Serve(lis); err != nil { - fmt.Print(err) - panic(err) - } -} diff --git a/third_party/flatbuffers/grpc/examples/greeter.fbs b/third_party/flatbuffers/grpc/examples/greeter.fbs deleted file mode 100644 index 651fb6773a8..00000000000 --- a/third_party/flatbuffers/grpc/examples/greeter.fbs +++ /dev/null @@ -1,14 +0,0 @@ -namespace models; - -table HelloReply { - message:string; -} - -table HelloRequest { - name:string; -} - -rpc_service Greeter { - SayHello(HelloRequest):HelloReply; - SayManyHellos(HelloRequest):HelloReply (streaming: "server"); -} diff --git a/third_party/flatbuffers/grpc/examples/python/greeter/README.md b/third_party/flatbuffers/grpc/examples/python/greeter/README.md deleted file mode 100644 index fcf310c0d6c..00000000000 --- a/third_party/flatbuffers/grpc/examples/python/greeter/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Python Greeter example - -## Prerequisite - -- You need to have grpc python installed on your device `pip install grpcio` -## How to run Server: - -- `python server.py ${PORT}` - -## How to run Client: - -- `python client.py ${PORT} ${NAME}` \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/python/greeter/client.py b/third_party/flatbuffers/grpc/examples/python/greeter/client.py deleted file mode 100644 index d2d718452f1..00000000000 --- a/third_party/flatbuffers/grpc/examples/python/greeter/client.py +++ /dev/null @@ -1,40 +0,0 @@ -import sys -import argparse -import grpc - -sys.path.insert(0, '../../../../../flatbuffers/python') - -import flatbuffers -from models import HelloReply, HelloRequest, greeter_grpc_fb - -parser = argparse.ArgumentParser() -parser.add_argument("port", help="server port to connect to", default=3000) -parser.add_argument("name", help="name to be sent to server", default="flatbuffers") - -def say_hello(stub, hello_request): - reply = stub.SayHello(hello_request) - r = HelloReply.HelloReply.GetRootAs(reply) - print(r.Message()) - -def say_many_hellos(stub, hello_request): - greetings = stub.SayManyHellos(hello_request) - for greeting in greetings: - r = HelloReply.HelloReply.GetRootAs(greeting) - print(r.Message()) - -def main(): - args = parser.parse_args() - - with grpc.insecure_channel('localhost:' + args.port) as channel: - builder = flatbuffers.Builder() - ind = builder.CreateString(args.name) - HelloRequest.HelloRequestStart(builder) - HelloRequest.HelloRequestAddName(builder, ind) - root = HelloRequest.HelloRequestEnd(builder) - builder.Finish(root) - output = bytes(builder.Output()) - stub = greeter_grpc_fb.GreeterStub(channel) - say_hello(stub, output) - say_many_hellos(stub, output) - -main() \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/python/greeter/models/HelloReply.py b/third_party/flatbuffers/grpc/examples/python/greeter/models/HelloReply.py deleted file mode 100644 index b1adc8c31a2..00000000000 --- a/third_party/flatbuffers/grpc/examples/python/greeter/models/HelloReply.py +++ /dev/null @@ -1,50 +0,0 @@ -# automatically generated by the FlatBuffers compiler, do not modify - -# namespace: models - -import flatbuffers -from flatbuffers.compat import import_numpy -np = import_numpy() - -class HelloReply(object): - __slots__ = ['_tab'] - - @classmethod - def GetRootAs(cls, buf, offset=0): - n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) - x = HelloReply() - x.Init(buf, n + offset) - return x - - @classmethod - def GetRootAsHelloReply(cls, buf, offset=0): - """This method is deprecated. Please switch to GetRootAs.""" - return cls.GetRootAs(buf, offset) - # HelloReply - def Init(self, buf, pos): - self._tab = flatbuffers.table.Table(buf, pos) - - # HelloReply - def Message(self): - o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) - if o != 0: - return self._tab.String(o + self._tab.Pos) - return None - -def HelloReplyStart(builder): - builder.StartObject(1) - -def Start(builder): - HelloReplyStart(builder) - -def HelloReplyAddMessage(builder, message): - builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(message), 0) - -def AddMessage(builder, message): - HelloReplyAddMessage(builder, message) - -def HelloReplyEnd(builder): - return builder.EndObject() - -def End(builder): - return HelloReplyEnd(builder) diff --git a/third_party/flatbuffers/grpc/examples/python/greeter/models/HelloRequest.py b/third_party/flatbuffers/grpc/examples/python/greeter/models/HelloRequest.py deleted file mode 100644 index db217dd2191..00000000000 --- a/third_party/flatbuffers/grpc/examples/python/greeter/models/HelloRequest.py +++ /dev/null @@ -1,50 +0,0 @@ -# automatically generated by the FlatBuffers compiler, do not modify - -# namespace: models - -import flatbuffers -from flatbuffers.compat import import_numpy -np = import_numpy() - -class HelloRequest(object): - __slots__ = ['_tab'] - - @classmethod - def GetRootAs(cls, buf, offset=0): - n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) - x = HelloRequest() - x.Init(buf, n + offset) - return x - - @classmethod - def GetRootAsHelloRequest(cls, buf, offset=0): - """This method is deprecated. Please switch to GetRootAs.""" - return cls.GetRootAs(buf, offset) - # HelloRequest - def Init(self, buf, pos): - self._tab = flatbuffers.table.Table(buf, pos) - - # HelloRequest - def Name(self): - o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) - if o != 0: - return self._tab.String(o + self._tab.Pos) - return None - -def HelloRequestStart(builder): - builder.StartObject(1) - -def Start(builder): - HelloRequestStart(builder) - -def HelloRequestAddName(builder, name): - builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) - -def AddName(builder, name): - HelloRequestAddName(builder, name) - -def HelloRequestEnd(builder): - return builder.EndObject() - -def End(builder): - return HelloRequestEnd(builder) diff --git a/third_party/flatbuffers/grpc/examples/python/greeter/models/__init__.py b/third_party/flatbuffers/grpc/examples/python/greeter/models/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/third_party/flatbuffers/grpc/examples/python/greeter/models/greeter_grpc_fb.py b/third_party/flatbuffers/grpc/examples/python/greeter/models/greeter_grpc_fb.py deleted file mode 100644 index b9f8a4ed233..00000000000 --- a/third_party/flatbuffers/grpc/examples/python/greeter/models/greeter_grpc_fb.py +++ /dev/null @@ -1,52 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! - -import grpc - -class GreeterStub(object): - """ Interface exported by the server. """ - - def __init__(self, channel): - """ Constructor. - - Args: - channel: A grpc.Channel. - """ - - self.SayHello = channel.unary_unary( - "/models.Greeter/SayHello" - ) - - self.SayManyHellos = channel.unary_stream( - "/models.Greeter/SayManyHellos" - ) - - -class GreeterServicer(object): - """ Interface exported by the server. """ - - def SayHello(self, request, context): - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - - def SayManyHellos(self, request, context): - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - - -def add_GreeterServicer_to_server(servicer, server): - rpc_method_handlers = { - 'SayHello': grpc.unary_unary_rpc_method_handler( - servicer.SayHello - ), - 'SayManyHellos': grpc.unary_stream_rpc_method_handler( - servicer.SayManyHellos - ), - } - generic_handler = grpc.method_handlers_generic_handler( - 'models.Greeter', rpc_method_handlers) - server.add_generic_rpc_handlers((generic_handler,)) - diff --git a/third_party/flatbuffers/grpc/examples/python/greeter/server.py b/third_party/flatbuffers/grpc/examples/python/greeter/server.py deleted file mode 100644 index acca880b562..00000000000 --- a/third_party/flatbuffers/grpc/examples/python/greeter/server.py +++ /dev/null @@ -1,57 +0,0 @@ -from concurrent import futures -import sys -import argparse -import grpc - -sys.path.insert(0, '../../../../../flatbuffers/python') - -import flatbuffers -from models import HelloReply, HelloRequest, greeter_grpc_fb - -parser = argparse.ArgumentParser() -parser.add_argument("port", help="server on port", default=3000) - -def build_reply(message): - builder = flatbuffers.Builder() - ind = builder.CreateString(message) - HelloReply.HelloReplyStart(builder) - HelloReply.HelloReplyAddMessage(builder, ind) - root = HelloReply.HelloReplyEnd(builder) - builder.Finish(root) - return bytes(builder.Output()) - -class GreeterServicer(greeter_grpc_fb.GreeterServicer): - - def __init__(self): - self.greetings = ["Hi", "Hallo", "Ciao"] - - def SayHello(self, request, context): - r = HelloRequest.HelloRequest().GetRootAs(request, 0) - reply = "Unknown" - if r.Name(): - reply = r.Name() - return build_reply("welcome " + reply.decode('UTF-8')) - - def SayManyHellos(self, request, context): - r = HelloRequest.HelloRequest().GetRootAs(request, 0) - reply = "Unknown" - if r.Name(): - reply = r.Name() - - for greeting in self.greetings: - print(type(reply)) - yield build_reply(greeting + " " + reply.decode('UTF-8')) - - -def serve(): - args = parser.parse_args() - server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) - greeter_grpc_fb.add_GreeterServicer_to_server( - GreeterServicer(), server - ) - server.add_insecure_port('[::]:' + args.port) - server.start() - server.wait_for_termination() - -if __name__ == '__main__': - serve() \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Package.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Package.swift deleted file mode 100644 index 5e6fb68cde3..00000000000 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Package.swift +++ /dev/null @@ -1,58 +0,0 @@ -// swift-tools-version:5.1 -/* - * Copyright 2020 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. - */ - -import PackageDescription - -let package = Package( - name: "Greeter", - platforms: [ - .iOS(.v11), - .macOS(.v10_14), - ], - dependencies: [ - .package(path: "../../../../swift"), - .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0"), - ], - targets: [ - // Targets are the basic building blocks of a package. A target can define a module or a test suite. - // Targets can depend on other targets in this package, and on products in packages which this package depends on. - .target( - name: "Model", - dependencies: [ - "GRPC", - "FlatBuffers", - ], - path: "Sources/Model"), - - // Client for the Greeter example - .target( - name: "Client", - dependencies: [ - "GRPC", - "Model", - ], - path: "Sources/client"), - - // Server for the Greeter example - .target( - name: "Server", - dependencies: [ - "GRPC", - "Model", - ], - path: "Sources/server"), - ]) diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/README.md b/third_party/flatbuffers/grpc/examples/swift/Greeter/README.md deleted file mode 100644 index 1632b783a5c..00000000000 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# FlatBuffers.GRPC.Swift - -The following is Swift example on how GRPC would be with Swift Flatbuffers, you can simply run the following commands: - -`swift run Server` - -`swift run Client {port} {name}` diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift deleted file mode 100644 index 0f29f1958a1..00000000000 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift +++ /dev/null @@ -1,145 +0,0 @@ -// Generated GRPC code for FlatBuffers swift! -/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-swift -/// in case of an issue please open github issue, though it would be maintained - -// swiftlint:disable all -// swiftformat:disable all - -import Foundation -import GRPC -import NIO -import NIOHTTP1 -import FlatBuffers - -public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {} -public extension GRPCFlatBufPayload { - init(serializedByteBuffer: inout NIO.ByteBuffer) throws { - self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes)) - } - func serialize(into buffer: inout NIO.ByteBuffer) throws { - let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size)) - buffer.writeBytes(buf) - } -} -extension Message: GRPCFlatBufPayload {} - -/// Usage: instantiate models_GreeterServiceClient, then call methods of this protocol to make API calls. -public protocol models_GreeterClientProtocol: GRPCClient { - - var serviceName: String { get } - - var interceptors: models_GreeterClientInterceptorFactoryProtocol? { get } - - func SayHello( - _ request: Message - , callOptions: CallOptions? - ) -> UnaryCall, Message> - - func SayManyHellos( - _ request: Message - , callOptions: CallOptions?, - handler: @escaping (Message) -> Void - ) -> ServerStreamingCall, Message> - -} - -extension models_GreeterClientProtocol { - - public var serviceName: String { "models.Greeter" } - - public func SayHello( - _ request: Message - , callOptions: CallOptions? = nil - ) -> UnaryCall, Message> { - return self.makeUnaryCall( - path: "/models.Greeter/SayHello", - request: request, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeSayHelloInterceptors() ?? [] - ) - } - - public func SayManyHellos( - _ request: Message - , callOptions: CallOptions? = nil, - handler: @escaping (Message) -> Void - ) -> ServerStreamingCall, Message> { - return self.makeServerStreamingCall( - path: "/models.Greeter/SayManyHellos", - request: request, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [], - handler: handler - ) - } -} - -public protocol models_GreeterClientInterceptorFactoryProtocol { - /// - Returns: Interceptors to use when invoking 'SayHello'. - func makeSayHelloInterceptors() -> [ClientInterceptor, Message>] - - /// - Returns: Interceptors to use when invoking 'SayManyHellos'. - func makeSayManyHellosInterceptors() -> [ClientInterceptor, Message>] - -} - -public final class models_GreeterServiceClient: models_GreeterClientProtocol { - public let channel: GRPCChannel - public var defaultCallOptions: CallOptions - public var interceptors: models_GreeterClientInterceptorFactoryProtocol? - - public init( - channel: GRPCChannel, - defaultCallOptions: CallOptions = CallOptions(), - interceptors: models_GreeterClientInterceptorFactoryProtocol? = nil - ) { - self.channel = channel - self.defaultCallOptions = defaultCallOptions - self.interceptors = interceptors - } -} - -public protocol models_GreeterProvider: CallHandlerProvider { - var interceptors: models_GreeterServerInterceptorFactoryProtocol? { get } - func SayHello(request: Message, context: StatusOnlyCallContext) -> EventLoopFuture> - func SayManyHellos(request: Message, context: StreamingResponseCallContext>) -> EventLoopFuture -} - -public extension models_GreeterProvider { - - var serviceName: Substring { return "models.Greeter" } - - func handle(method name: Substring, context: CallHandlerContext) -> GRPCServerHandlerProtocol? { - switch name { - case "SayHello": - return UnaryServerHandler( - context: context, - requestDeserializer: GRPCPayloadDeserializer>(), - responseSerializer: GRPCPayloadSerializer>(), - interceptors: self.interceptors?.makeSayHelloInterceptors() ?? [], - userFunction: self.SayHello(request:context:)) - - case "SayManyHellos": - return ServerStreamingServerHandler( - context: context, - requestDeserializer: GRPCPayloadDeserializer>(), - responseSerializer: GRPCPayloadSerializer>(), - interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [], - userFunction: self.SayManyHellos(request:context:)) - - default: return nil; - } - } - -} - -public protocol models_GreeterServerInterceptorFactoryProtocol { - /// - Returns: Interceptors to use when handling 'SayHello'. - /// Defaults to calling `self.makeInterceptors()`. - func makeSayHelloInterceptors() -> [ServerInterceptor, Message>] - - /// - Returns: Interceptors to use when handling 'SayManyHellos'. - /// Defaults to calling `self.makeInterceptors()`. - func makeSayManyHellosInterceptors() -> [ServerInterceptor, Message>] - -} diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift deleted file mode 100644 index 81ffe48f857..00000000000 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift +++ /dev/null @@ -1,100 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// swiftlint:disable all -// swiftformat:disable all - -import FlatBuffers - -public struct models_HelloReply: FlatBufferObject, Verifiable { - - static func validateVersion() { FlatBuffersVersion_24_3_25() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table - - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - - private enum VTOFFSET: VOffset { - case message = 4 - var v: Int32 { Int32(self.rawValue) } - var p: VOffset { self.rawValue } - } - - public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) } - public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) } - public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(message: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) } - public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } - public static func createHelloReply( - _ fbb: inout FlatBufferBuilder, - messageOffset message: Offset = Offset() - ) -> Offset { - let __start = models_HelloReply.startHelloReply(&fbb) - models_HelloReply.add(message: message, &fbb) - return models_HelloReply.endHelloReply(&fbb, start: __start) - } - - public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { - var _v = try verifier.visitTable(at: position) - try _v.visit(field: VTOFFSET.message.p, fieldName: "message", required: false, type: ForwardOffset.self) - _v.finish() - } -} - -extension models_HelloReply: Encodable { - - enum CodingKeys: String, CodingKey { - case message = "message" - } - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(message, forKey: .message) - } -} - -public struct models_HelloRequest: FlatBufferObject, Verifiable { - - static func validateVersion() { FlatBuffersVersion_24_3_25() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table - - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - - private enum VTOFFSET: VOffset { - case name = 4 - var v: Int32 { Int32(self.rawValue) } - var p: VOffset { self.rawValue } - } - - public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) } - public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) } - public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } - public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } - public static func createHelloRequest( - _ fbb: inout FlatBufferBuilder, - nameOffset name: Offset = Offset() - ) -> Offset { - let __start = models_HelloRequest.startHelloRequest(&fbb) - models_HelloRequest.add(name: name, &fbb) - return models_HelloRequest.endHelloRequest(&fbb, start: __start) - } - - public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { - var _v = try verifier.visitTable(at: position) - try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset.self) - _v.finish() - } -} - -extension models_HelloRequest: Encodable { - - enum CodingKeys: String, CodingKey { - case name = "name" - } - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(name, forKey: .name) - } -} - diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/client/main.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/client/main.swift deleted file mode 100644 index a4b2a675c70..00000000000 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/client/main.swift +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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. - */ - -import FlatBuffers -import GRPC -import Logging -import Model -import NIO - -// Quieten the logs. -LoggingSystem.bootstrap { - var handler = StreamLogHandler.standardOutput(label: $0) - handler.logLevel = .critical - return handler -} - -func greet(name: String, client greeter: models_GreeterServiceClient) { - // Form the request with the name, if one was provided. - var builder = FlatBufferBuilder() - let nameOff = builder.create(string: name) - let root = models_HelloRequest.createHelloRequest( - &builder, - nameOffset: nameOff) - builder.finish(offset: root) - - // Make the RPC call to the server. - let sayHello = greeter - .SayHello(Message(builder: &builder)) - - // wait() on the response to stop the program from exiting before the response is received. - do { - let response = try sayHello.response.wait() - print("Greeter SayHello received: \(response.object.message ?? "Unknown")") - } catch { - print("Greeter failed: \(error)") - } - - let surname = builder.create(string: name) - let manyRoot = models_HelloRequest.createHelloRequest( - &builder, - nameOffset: surname) - builder.finish(offset: manyRoot) - - let call = greeter.SayManyHellos(Message(builder: &builder)) { message in - print( - "Greeter SayManyHellos received: \(message.object.message ?? "Unknown")") - } - - let status = try! call.status.recover { _ in .processingError }.wait() - if status.code != .ok { - print("RPC failed: \(status)") - } -} - -func main(args: [String]) { - // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be - // the name sent in the request. - let arg1 = args.dropFirst(1).first - let arg2 = args.dropFirst(2).first - - switch (arg1.flatMap(Int.init), arg2) { - case (.none, _): - print("Usage: PORT [NAME]") - exit(1) - - case let (.some(port), name): - // Setup an `EventLoopGroup` for the connection to run on. - // - // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups - let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) - - // Make sure the group is shutdown when we're done with it. - defer { - try! group.syncShutdownGracefully() - } - - // Configure the channel, we're not using TLS so the connection is `insecure`. - let channel = ClientConnection.insecure(group: group) - .connect(host: "localhost", port: port) - - // Close the connection when we're done with it. - defer { - try! channel.close().wait() - } - - // Provide the connection to the generated client. - let greeter = models_GreeterServiceClient(channel: channel) - - // Do the greeting. - greet(name: name ?? "FlatBuffers!", client: greeter) - } -} - -main(args: CommandLine.arguments) diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/server/main.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/server/main.swift deleted file mode 100644 index 62286c4759f..00000000000 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/server/main.swift +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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. - */ - -import FlatBuffers -import GRPC -import Logging -import Model -import NIO - -class Greeter: models_GreeterProvider { - - var interceptors: models_GreeterServerInterceptorFactoryProtocol? - - let greetings: [String] - - init() { - greetings = ["Hi", "Hallo", "Ciao"] - } - - func SayHello( - request: Message, - context: StatusOnlyCallContext) - -> EventLoopFuture> - { - let recipient = request.object.name ?? "Stranger" - - var builder = FlatBufferBuilder() - let off = builder.create(string: "Hello \(recipient)") - let root = models_HelloReply.createHelloReply(&builder, messageOffset: off) - builder.finish(offset: root) - return context.eventLoop - .makeSucceededFuture(Message(builder: &builder)) - } - - func SayManyHellos( - request: Message, - context: StreamingResponseCallContext>) - -> EventLoopFuture - { - for name in greetings { - var builder = FlatBufferBuilder() - let off = builder - .create(string: "\(name) \(request.object.name ?? "Unknown")") - let root = models_HelloReply.createHelloReply( - &builder, - messageOffset: off) - builder.finish(offset: root) - _ = context.sendResponse(Message(builder: &builder)) - } - return context.eventLoop.makeSucceededFuture(.ok) - } -} - -// Quieten the logs. -LoggingSystem.bootstrap { - var handler = StreamLogHandler.standardOutput(label: $0) - handler.logLevel = .critical - return handler -} - -let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) -defer { - try! group.syncShutdownGracefully() -} - -// Create some configuration for the server: -let configuration = Server.Configuration( - target: .hostAndPort("localhost", 0), - eventLoopGroup: group, - serviceProviders: [Greeter()]) - -// Start the server and print its address once it has started. -let server = Server.start(configuration: configuration) -server.map { - $0.channel.localAddress -}.whenSuccess { address in - print("server started on port \(address!.port!)") -} - -// Wait on the server's `onClose` future to stop the program from exiting. -_ = try server.flatMap { - $0.onClose -}.wait() diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/README.md b/third_party/flatbuffers/grpc/examples/ts/greeter/README.md deleted file mode 100644 index 5c7b380fd97..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# TS Greeter example - -The following is an example on how to run the TS grpc server. Make sure that you have `Typescript` installed - -you would need to run `npm run build` or simply use `npm install && tsc` - -## How to run Server: - -- `npm run server` - -## How to run Client: - -- `npm run client 3000` \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/package.json b/third_party/flatbuffers/grpc/examples/ts/greeter/package.json deleted file mode 100644 index 324bd3891aa..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "flatbuffers-js-grpc", - "version": "1.0.0", - "author": "mustii@mmk.one", - "scripts": { - "build": "npm install && tsc", - "client": "node dist/client.js", - "server": "node dist/server.js" - }, - "dependencies": { - "@grpc/grpc-js": "^1.3.2", - "flatbuffers": "^2.0.0" - } -} diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/client.ts b/third_party/flatbuffers/grpc/examples/ts/greeter/src/client.ts deleted file mode 100644 index 62444f1ebc3..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/client.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as grpc from '@grpc/grpc-js'; -import * as flatbuffers from 'flatbuffers'; -import { HelloReply } from './models/hello-reply'; -import { HelloRequest } from './models/hello-request'; -import { GreeterClient } from './greeter_grpc'; - -async function main(PORT: Number, name: string) { - const client = new GreeterClient(`localhost:${PORT}`, grpc.credentials.createInsecure()); - const builder = new flatbuffers.Builder(); - const offset = builder.createString(name); - const root = HelloRequest.createHelloRequest(builder, offset); - builder.finish(root); - const buffer = HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(builder.asUint8Array())); - - client.SayHello(buffer, (err, response) => { - console.log(response.message()); - }); - - const data = client.SayManyHellos(buffer, null); - - data.on('data', (data) => { - console.log(data.message()); - }); -} - -const args = process.argv.slice(2) -const PORT = Number(args[0]); -const name: string = args[1] ?? "flatbuffers"; - -if (PORT) { - main(PORT, name); -} else { - throw new Error("Requires a valid port number.") -} \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter.ts b/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter.ts deleted file mode 100644 index b6acab01fe2..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter.ts +++ /dev/null @@ -1,5 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify - -/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ - -export * as models from './models.js'; diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_generated.ts b/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_generated.ts deleted file mode 100644 index c48afe53845..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_generated.ts +++ /dev/null @@ -1,4 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify - -export { HelloReply } from './models/hello-reply.js'; -export { HelloRequest } from './models/hello-request.js'; diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_grpc.d.ts b/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_grpc.d.ts deleted file mode 100644 index 657df5bbfbe..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_grpc.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT *** -import * as flatbuffers from 'flatbuffers'; -import { HelloReply as models_HelloReply } from './models/hello-reply'; -import { HelloRequest as models_HelloRequest } from './models/hello-request'; - -import * as grpc from '@grpc/grpc-js'; - -interface IGreeterService extends grpc.ServiceDefinition { - SayHello: IGreeterService_ISayHello; - SayManyHellos: IGreeterService_ISayManyHellos; -} -interface IGreeterService_ISayHello extends grpc.MethodDefinition { - path: string; // /models.Greeter/SayHello - requestStream: boolean; // false - responseStream: boolean; // false - requestSerialize: grpc.serialize; - requestDeserialize: grpc.deserialize; - responseSerialize: grpc.serialize; - responseDeserialize: grpc.deserialize; -} - -interface IGreeterService_ISayManyHellos extends grpc.MethodDefinition { - path: string; // /models.Greeter/SayManyHellos - requestStream: boolean; // false - responseStream: boolean; // true - requestSerialize: grpc.serialize; - requestDeserialize: grpc.deserialize; - responseSerialize: grpc.serialize; - responseDeserialize: grpc.deserialize; -} - - -export const GreeterService: IGreeterService; - -export interface IGreeterServer extends grpc.UntypedServiceImplementation { - SayHello: grpc.handleUnaryCall; - SayManyHellos: grpc.handleServerStreamingCall; -} - -export interface IGreeterClient { - SayHello(request: models_HelloRequest, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall; - SayHello(request: models_HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall; - SayHello(request: models_HelloRequest, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall; - SayManyHellos(request: models_HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream; - SayManyHellos(request: models_HelloRequest, options: Partial): grpc.ClientReadableStream; -} - -export class GreeterClient extends grpc.Client implements IGreeterClient { - constructor(address: string, credentials: grpc.ChannelCredentials, options?: object); - public SayHello(request: models_HelloRequest, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall; - public SayHello(request: models_HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall; - public SayHello(request: models_HelloRequest, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall; - public SayManyHellos(request: models_HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream; - public SayManyHellos(request: models_HelloRequest, options: Partial): grpc.ClientReadableStream; -} - diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_grpc.js b/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_grpc.js deleted file mode 100644 index 242e6862a91..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/greeter_grpc.js +++ /dev/null @@ -1,56 +0,0 @@ -// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT *** -import * as flatbuffers from 'flatbuffers'; -import { HelloReply as models_HelloReply } from './models/hello-reply'; -import { HelloRequest as models_HelloRequest } from './models/hello-request'; - -var grpc = require('@grpc/grpc-js'); - -function serialize_models_HelloReply(buffer_args) { - if (!(buffer_args instanceof models_HelloReply)) { - throw new Error('Expected argument of type HelloReply'); - } - return Buffer.from(buffer_args.serialize()); -} - -function deserialize_models_HelloReply(buffer) { - return models_HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer)) -} - - -function serialize_models_HelloRequest(buffer_args) { - if (!(buffer_args instanceof models_HelloRequest)) { - throw new Error('Expected argument of type HelloRequest'); - } - return Buffer.from(buffer_args.serialize()); -} - -function deserialize_models_HelloRequest(buffer) { - return models_HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer)) -} - - -var GreeterService = exports.GreeterService = { - SayHello: { - path: '/models.Greeter/SayHello', - requestStream: false, - responseStream: false, - requestType: flatbuffers.ByteBuffer, - responseType: models_HelloReply, - requestSerialize: serialize_models_HelloRequest, - requestDeserialize: deserialize_models_HelloRequest, - responseSerialize: serialize_models_HelloReply, - responseDeserialize: deserialize_models_HelloReply, - }, - SayManyHellos: { - path: '/models.Greeter/SayManyHellos', - requestStream: false, - responseStream: true, - requestType: flatbuffers.ByteBuffer, - responseType: models_HelloReply, - requestSerialize: serialize_models_HelloRequest, - requestDeserialize: deserialize_models_HelloRequest, - responseSerialize: serialize_models_HelloReply, - responseDeserialize: deserialize_models_HelloReply, - }, -}; -exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService); diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/models.ts b/third_party/flatbuffers/grpc/examples/ts/greeter/src/models.ts deleted file mode 100644 index 61d4731e3d1..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/models.ts +++ /dev/null @@ -1,6 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify - -/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ - -export { HelloReply } from './models/hello-reply.js'; -export { HelloRequest } from './models/hello-request.js'; diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/models/hello-reply.ts b/third_party/flatbuffers/grpc/examples/ts/greeter/src/models/hello-reply.ts deleted file mode 100644 index c9dd72c2c93..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/models/hello-reply.ts +++ /dev/null @@ -1,60 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify - -/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ - -import * as flatbuffers from 'flatbuffers'; - - - -export class HelloReply { - bb: flatbuffers.ByteBuffer|null = null; - bb_pos = 0; - __init(i:number, bb:flatbuffers.ByteBuffer):HelloReply { - this.bb_pos = i; - this.bb = bb; - return this; -} - -static getRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply { - return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb); -} - -static getSizePrefixedRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply { - bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); - return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb); -} - -message():string|null -message(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null -message(optionalEncoding?:any):string|Uint8Array|null { - const offset = this.bb!.__offset(this.bb_pos, 4); - return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; -} - -static startHelloReply(builder:flatbuffers.Builder) { - builder.startObject(1); -} - -static addMessage(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset) { - builder.addFieldOffset(0, messageOffset, 0); -} - -static endHelloReply(builder:flatbuffers.Builder):flatbuffers.Offset { - const offset = builder.endObject(); - return offset; -} - -static createHelloReply(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset):flatbuffers.Offset { - HelloReply.startHelloReply(builder); - HelloReply.addMessage(builder, messageOffset); - return HelloReply.endHelloReply(builder); -} - -serialize():Uint8Array { - return this.bb!.bytes(); -} - -static deserialize(buffer: Uint8Array):HelloReply { - return HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer)) -} -} diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/models/hello-request.ts b/third_party/flatbuffers/grpc/examples/ts/greeter/src/models/hello-request.ts deleted file mode 100644 index fb52399388b..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/models/hello-request.ts +++ /dev/null @@ -1,60 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify - -/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ - -import * as flatbuffers from 'flatbuffers'; - - - -export class HelloRequest { - bb: flatbuffers.ByteBuffer|null = null; - bb_pos = 0; - __init(i:number, bb:flatbuffers.ByteBuffer):HelloRequest { - this.bb_pos = i; - this.bb = bb; - return this; -} - -static getRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest { - return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb); -} - -static getSizePrefixedRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest { - bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); - return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb); -} - -name():string|null -name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null -name(optionalEncoding?:any):string|Uint8Array|null { - const offset = this.bb!.__offset(this.bb_pos, 4); - return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; -} - -static startHelloRequest(builder:flatbuffers.Builder) { - builder.startObject(1); -} - -static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { - builder.addFieldOffset(0, nameOffset, 0); -} - -static endHelloRequest(builder:flatbuffers.Builder):flatbuffers.Offset { - const offset = builder.endObject(); - return offset; -} - -static createHelloRequest(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset):flatbuffers.Offset { - HelloRequest.startHelloRequest(builder); - HelloRequest.addName(builder, nameOffset); - return HelloRequest.endHelloRequest(builder); -} - -serialize():Uint8Array { - return this.bb!.bytes(); -} - -static deserialize(buffer: Uint8Array):HelloRequest { - return HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer)) -} -} diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/src/server.ts b/third_party/flatbuffers/grpc/examples/ts/greeter/src/server.ts deleted file mode 100644 index a3f2eeec2ec..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/src/server.ts +++ /dev/null @@ -1,49 +0,0 @@ -import * as grpc from '@grpc/grpc-js'; -import * as flatbuffers from 'flatbuffers'; -import { HelloReply } from './models/hello-reply'; -import { HelloRequest } from './models/hello-request'; -import { IGreeterServer, GreeterService } from './greeter_grpc'; - -const greeter: IGreeterServer = { - SayHello(call: grpc.ServerUnaryCall, callback: grpc.sendUnaryData): void { - console.log(`SayHello ${call.request.name()}`); - const builder = new flatbuffers.Builder(); - const offset = builder.createString(`welcome ${call.request.name()}`); - const root = HelloReply.createHelloReply(builder, offset); - builder.finish(root); - callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array()))); - }, - async SayManyHellos(call: grpc.ServerWritableStream): Promise { - const name = call.request.name(); - console.log(`${call.request.name()} saying hi in different langagues`); - ['Hi', 'Hallo', 'Ciao'].forEach(element => { - const builder = new flatbuffers.Builder(); - const offset = builder.createString(`${element} ${name}`); - const root = HelloReply.createHelloReply(builder, offset); - builder.finish(root); - call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array()))) - }); - call.end(); - } -} - -function serve(): void { - const PORT = 3000; - const server = new grpc.Server(); - server.addService(GreeterService, greeter); - console.log(`Listening on ${PORT}`); - server.bindAsync( - `localhost:${PORT}`, - grpc.ServerCredentials.createInsecure(), - (err: Error | null, port: number) => { - if (err) { - console.error(`Server error: ${err.message}`); - } else { - console.log(`Server bound on port: ${port}`); - server.start(); - } - } - ); -} - -serve(); \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/examples/ts/greeter/tsconfig.json b/third_party/flatbuffers/grpc/examples/ts/greeter/tsconfig.json deleted file mode 100644 index 70763787b49..00000000000 --- a/third_party/flatbuffers/grpc/examples/ts/greeter/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "compilerOptions": { - "target": "es5", - "module": "commonjs", - "outDir": "./dist", - "allowJs": true, - "sourceMap": true, - "strict": true, - "noImplicitAny": false, - "strictNullChecks": false, - "esModuleInterop": true, - "baseUrl": "./", - "typeRoots": ["node_modules/@types"], - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true - } - } \ No newline at end of file diff --git a/third_party/flatbuffers/grpc/flatbuffers-java-grpc/pom.xml b/third_party/flatbuffers/grpc/flatbuffers-java-grpc/pom.xml deleted file mode 100644 index f7d41763747..00000000000 --- a/third_party/flatbuffers/grpc/flatbuffers-java-grpc/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - - com.google.flatbuffers - flatbuffers-parent - 2.0.3 - - flatbuffers-java-grpc - ${project.artifactId} - bundle - - Utilities supporting generated code for GRPC - - - - Wouter van Oortmerssen - - - Yuri Finkelstein - https://github.com/yfinkelstein - - - - 1.36.0 - - - - com.google.flatbuffers - flatbuffers-java - ${project.parent.version} - - - io.grpc - grpc-core - ${gRPC.version} - - - - diff --git a/third_party/flatbuffers/grpc/flatbuffers-java-grpc/src/main/java/com/google/flatbuffers/grpc/FlatbuffersUtils.java b/third_party/flatbuffers/grpc/flatbuffers-java-grpc/src/main/java/com/google/flatbuffers/grpc/FlatbuffersUtils.java deleted file mode 100644 index 768708b111e..00000000000 --- a/third_party/flatbuffers/grpc/flatbuffers-java-grpc/src/main/java/com/google/flatbuffers/grpc/FlatbuffersUtils.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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. - */ -package com.google.flatbuffers.grpc; - -import com.google.flatbuffers.Table; -import io.grpc.Drainable; -import io.grpc.KnownLength; -import io.grpc.MethodDescriptor; - -import javax.annotation.Nullable; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; - -public class FlatbuffersUtils { - abstract public static class FBExtactor { - T extract (InputStream stream) throws IOException { - if (stream instanceof KnownLength) { - int size = stream.available(); - ByteBuffer buffer = ByteBuffer.allocate(size); - stream.read(buffer.array()); - return extract(buffer); - } else - throw new RuntimeException("The class " + stream.getClass().getCanonicalName() + " does not extend from KnownLength "); - } - - public abstract T extract(ByteBuffer buffer); - - } - - static class FBInputStream extends InputStream implements Drainable, KnownLength { - private final ByteBuffer buffer; - private final int size; - @Nullable private ByteArrayInputStream inputStream; - - FBInputStream(ByteBuffer buffer) { - this.buffer = buffer; - this.size = buffer.remaining(); - } - - private void makeStreamIfNotAlready() { - if (inputStream == null) - inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), size); - } - - @Override - public int drainTo(OutputStream target) throws IOException { - target.write(buffer.array(), buffer.position(), size); - return size; - } - - @Override - public int read() throws IOException { - makeStreamIfNotAlready(); - return inputStream.read(); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - makeStreamIfNotAlready(); - if (inputStream == null) { - if (len >= size) { - System.arraycopy(buffer.array(), buffer.position(), b, off, size); - return size; - } else { - makeStreamIfNotAlready(); - return inputStream.read(b, off, len); - } - } else - return inputStream.read(b, off, len); - } - - @Override - public int available() throws IOException { - return inputStream == null ? size : inputStream.available(); - } - - } - - public static MethodDescriptor.Marshaller marshaller(final Class clazz, final FBExtactor extractor) { - return new MethodDescriptor.ReflectableMarshaller() { - @Override - public Class getMessageClass() { - return clazz; - } - - @Override - public InputStream stream(T value) { - return new FBInputStream (value.getByteBuffer()); - } - - @Override - public T parse(InputStream stream) { - try { - return extractor.extract(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - } -} diff --git a/third_party/flatbuffers/grpc/pom.xml b/third_party/flatbuffers/grpc/pom.xml deleted file mode 100644 index a0608ae8ae1..00000000000 --- a/third_party/flatbuffers/grpc/pom.xml +++ /dev/null @@ -1,219 +0,0 @@ - - 4.0.0 - com.google.flatbuffers - flatbuffers-parent - pom - 2.0.3 - flatbuffers-parent - parent pom for flatbuffers java artifacts - - https://github.com/google/flatbuffers - scm:git:${scm.url}.git - UTF-8 - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - GitHub - https://github.com/google/flatbuffers/issues - - - - - Wouter van Oortmerssen - - - - ${scm.url} - - - ${scm.connection} - ${scm.connection} - ${scm.url} - HEAD - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - - - - junit - junit - 4.13.1 - test - - - - - - - - kr.motd.maven - os-maven-plugin - 1.5.0.Final - - - - - - maven-compiler-plugin - 3.6.1 - - - maven-jar-plugin - 3.0.2 - - - maven-source-plugin - 3.0.1 - - - maven-surefire-plugin - 2.19.1 - - - maven-javadoc-plugin - 2.10.4 - - - org.codehaus.mojo - build-helper-maven-plugin - 1.12 - - - maven-dependency-plugin - 2.8 - - - maven-deploy-plugin - 2.7 - - - maven-gpg-plugin - 1.5 - - - maven-release-plugin - 2.5.3 - - - - org.codehaus.mojo - exec-maven-plugin - 1.5.0 - - - - - - - maven-compiler-plugin - - 1.6 - 1.6 - - - - maven-surefire-plugin - - - **/*Test.java - - - - - maven-source-plugin - - - attach-sources - - jar - - - - - - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - org.apache.felix - maven-bundle-plugin - 3.0.1 - true - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - true - - - - maven-gpg-plugin - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - maven-release-plugin - - true - false - release - deploy - - - - - - - - flatbuffers-java-grpc - - - diff --git a/third_party/flatbuffers/grpc/samples/greeter/Makefile b/third_party/flatbuffers/grpc/samples/greeter/Makefile deleted file mode 100644 index 910483cac55..00000000000 --- a/third_party/flatbuffers/grpc/samples/greeter/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -CXXFLAGS ?= -I../../../include -LDFLAGS ?= - -.PHONY: all -all: server client - -greeter_generated: greeter.fbs - flatc --grpc --cpp $< - -server: greeter_generated server.cpp greeter.grpc.fb.cc greeter.grpc.fb.h - g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ server.cpp greeter.grpc.fb.cc -o $@ - -client: greeter_generated client.cpp greeter.grpc.fb.cc greeter.grpc.fb.h - g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ client.cpp greeter.grpc.fb.cc -o $@ diff --git a/third_party/flatbuffers/grpc/samples/greeter/client.cpp b/third_party/flatbuffers/grpc/samples/greeter/client.cpp deleted file mode 100644 index 0e4f34814aa..00000000000 --- a/third_party/flatbuffers/grpc/samples/greeter/client.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "greeter.grpc.fb.h" -#include "greeter_generated.h" - -#include - -#include -#include -#include - -class GreeterClient { - public: - GreeterClient(std::shared_ptr channel) - : stub_(Greeter::NewStub(channel)) {} - - std::string SayHello(const std::string &name) { - flatbuffers::grpc::MessageBuilder mb; - auto name_offset = mb.CreateString(name); - auto request_offset = CreateHelloRequest(mb, name_offset); - mb.Finish(request_offset); - auto request_msg = mb.ReleaseMessage(); - - flatbuffers::grpc::Message response_msg; - - grpc::ClientContext context; - - auto status = stub_->SayHello(&context, request_msg, &response_msg); - if (status.ok()) { - const HelloReply *response = response_msg.GetRoot(); - return response->message()->str(); - } else { - std::cerr << status.error_code() << ": " << status.error_message() - << std::endl; - return "RPC failed"; - } - } - - void SayManyHellos(const std::string &name, int num_greetings, - std::function callback) { - flatbuffers::grpc::MessageBuilder mb; - auto name_offset = mb.CreateString(name); - auto request_offset = - CreateManyHellosRequest(mb, name_offset, num_greetings); - mb.Finish(request_offset); - auto request_msg = mb.ReleaseMessage(); - - flatbuffers::grpc::Message response_msg; - - grpc::ClientContext context; - - auto stream = stub_->SayManyHellos(&context, request_msg); - while (stream->Read(&response_msg)) { - const HelloReply *response = response_msg.GetRoot(); - callback(response->message()->str()); - } - auto status = stream->Finish(); - if (!status.ok()) { - std::cerr << status.error_code() << ": " << status.error_message() - << std::endl; - callback("RPC failed"); - } - } - - private: - std::unique_ptr stub_; -}; - -int main(int argc, char **argv) { - std::string server_address("localhost:50051"); - - auto channel = - grpc::CreateChannel(server_address, grpc::InsecureChannelCredentials()); - GreeterClient greeter(channel); - - std::string name("world"); - - std::string message = greeter.SayHello(name); - std::cerr << "Greeter received: " << message << std::endl; - - int num_greetings = 10; - greeter.SayManyHellos(name, num_greetings, [](const std::string &message) { - std::cerr << "Greeter received: " << message << std::endl; - }); - - return 0; -} diff --git a/third_party/flatbuffers/grpc/samples/greeter/greeter.fbs b/third_party/flatbuffers/grpc/samples/greeter/greeter.fbs deleted file mode 100644 index 811303c9364..00000000000 --- a/third_party/flatbuffers/grpc/samples/greeter/greeter.fbs +++ /dev/null @@ -1,17 +0,0 @@ -table HelloReply { - message:string; -} - -table HelloRequest { - name:string; -} - -table ManyHellosRequest { - name:string; - num_greetings:int; -} - -rpc_service Greeter { - SayHello(HelloRequest):HelloReply; - SayManyHellos(ManyHellosRequest):HelloReply (streaming: "server"); -} diff --git a/third_party/flatbuffers/grpc/samples/greeter/server.cpp b/third_party/flatbuffers/grpc/samples/greeter/server.cpp deleted file mode 100644 index ac38fa969d0..00000000000 --- a/third_party/flatbuffers/grpc/samples/greeter/server.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include "greeter.grpc.fb.h" -#include "greeter_generated.h" - -#include - -#include -#include -#include - -class GreeterServiceImpl final : public Greeter::Service { - virtual grpc::Status SayHello( - grpc::ServerContext *context, - const flatbuffers::grpc::Message *request_msg, - flatbuffers::grpc::Message *response_msg) override { - flatbuffers::grpc::MessageBuilder mb_; - - // We call GetRoot to "parse" the message. Verification is already - // performed by default. See the notes below for more details. - const HelloRequest *request = request_msg->GetRoot(); - - // Fields are retrieved as usual with FlatBuffers - const std::string &name = request->name()->str(); - - // `flatbuffers::grpc::MessageBuilder` is a `FlatBufferBuilder` with a - // special allocator for efficient gRPC buffer transfer, but otherwise - // usage is the same as usual. - auto msg_offset = mb_.CreateString("Hello, " + name); - auto hello_offset = CreateHelloReply(mb_, msg_offset); - mb_.Finish(hello_offset); - - // The `ReleaseMessage()` function detaches the message from the - // builder, so we can transfer the resopnse to gRPC while simultaneously - // detaching that memory buffer from the builer. - *response_msg = mb_.ReleaseMessage(); - assert(response_msg->Verify()); - - // Return an OK status. - return grpc::Status::OK; - } - - virtual grpc::Status SayManyHellos( - grpc::ServerContext *context, - const flatbuffers::grpc::Message *request_msg, - grpc::ServerWriter> *writer) - override { - // The streaming usage below is simply a combination of standard gRPC - // streaming with the FlatBuffers usage shown above. - const ManyHellosRequest *request = request_msg->GetRoot(); - const std::string &name = request->name()->str(); - int num_greetings = request->num_greetings(); - - for (int i = 0; i < num_greetings; i++) { - auto msg_offset = mb_.CreateString("Many hellos, " + name); - auto hello_offset = CreateHelloReply(mb_, msg_offset); - mb_.Finish(hello_offset); - writer->Write(mb_.ReleaseMessage()); - } - - return grpc::Status::OK; - } - - flatbuffers::grpc::MessageBuilder mb_; -}; - -void RunServer() { - std::string server_address("0.0.0.0:50051"); - GreeterServiceImpl service; - - grpc::ServerBuilder builder; - builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); - builder.RegisterService(&service); - std::unique_ptr server(builder.BuildAndStart()); - std::cerr << "Server listening on " << server_address << std::endl; - - server->Wait(); -} - -int main(int argc, const char *argv[]) { - RunServer(); - return 0; -} diff --git a/third_party/flatbuffers/grpc/src/compiler/BUILD.bazel b/third_party/flatbuffers/grpc/src/compiler/BUILD.bazel deleted file mode 100644 index 0efa9560c2d..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/BUILD.bazel +++ /dev/null @@ -1,131 +0,0 @@ -load("@rules_cc//cc:defs.bzl", "cc_library") - -package( - default_visibility = ["//visibility:public"], -) - -filegroup( - name = "distribution", - srcs = [ - "BUILD.bazel", - ] + glob([ - "*.cc", - "*.h", - ]), -) - -filegroup( - name = "common_headers", - srcs = [ - "schema_interface.h", - ], -) - -cc_library( - name = "cpp_generator", - srcs = [ - "cpp_generator.cc", - ], - hdrs = [ - "cpp_generator.h", - ":common_headers", - ], - include_prefix = "src/compiler", - strip_include_prefix = "/grpc/src/compiler", - deps = [ - "//:flatbuffers", - ], -) - -cc_library( - name = "go_generator", - srcs = [ - "go_generator.cc", - ], - hdrs = [ - "go_generator.h", - ":common_headers", - ], - include_prefix = "src/compiler", - strip_include_prefix = "/grpc/src/compiler", - deps = [ - "//:flatbuffers", - ], -) - -cc_library( - name = "java_generator", - srcs = [ - "java_generator.cc", - ], - hdrs = [ - "java_generator.h", - ":common_headers", - ], - include_prefix = "src/compiler", - strip_include_prefix = "/grpc/src/compiler", - deps = [ - "//:flatbuffers", - ], -) - -cc_library( - name = "python_generator", - hdrs = [ - "python_generator.h", - ], - include_prefix = "src/compiler", - strip_include_prefix = "/grpc/src/compiler", - deps = [ - ":python_generator_private", - ], -) - -cc_library( - name = "python_generator_private", - srcs = [ - "python_generator.cc", - ], - hdrs = [ - "python_generator.h", - ":common_headers", - ], - include_prefix = "src/compiler", - strip_include_prefix = "/grpc/src/compiler", - visibility = ["//visibility:private"], - deps = [ - "//:flatbuffers", - ], -) - -cc_library( - name = "swift_generator", - srcs = [ - "swift_generator.cc", - ], - hdrs = [ - "swift_generator.h", - ":common_headers", - ], - include_prefix = "src/compiler", - strip_include_prefix = "/grpc/src/compiler", - deps = [ - "//:flatbuffers", - ], -) - -cc_library( - name = "ts_generator", - srcs = [ - "ts_generator.cc", - ], - hdrs = [ - "ts_generator.h", - ":common_headers", - ], - include_prefix = "src/compiler", - strip_include_prefix = "/grpc/src/compiler", - deps = [ - "//:flatbuffers", - ], -) diff --git a/third_party/flatbuffers/grpc/src/compiler/cpp_generator.cc b/third_party/flatbuffers/grpc/src/compiler/cpp_generator.cc deleted file mode 100644 index fd635f2fa5e..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/cpp_generator.cc +++ /dev/null @@ -1,1766 +0,0 @@ -#include "src/compiler/cpp_generator.h" - -#include -#include - -#include "flatbuffers/util.h" - -namespace grpc_cpp_generator { -namespace { - -static grpc::string service_header_ext() { return ".grpc.fb.h"; } - -template -static grpc::string as_string(T x) { - std::ostringstream out; - out << x; - return out.str(); -} - -static inline bool ClientOnlyStreaming(const grpc_generator::Method *method) { - return method->ClientStreaming() && !method->ServerStreaming(); -} - -static inline bool ServerOnlyStreaming(const grpc_generator::Method *method) { - return !method->ClientStreaming() && method->ServerStreaming(); -} - -static grpc::string FilenameIdentifier(const grpc::string &filename) { - grpc::string result; - for (unsigned i = 0; i < filename.size(); i++) { - char c = filename[i]; - if (isalnum(c)) { - result.push_back(c); - } else { - static char hex[] = "0123456789abcdef"; - result.push_back('_'); - result.push_back(hex[(c >> 4) & 0xf]); - result.push_back(hex[c & 0xf]); - } - } - return result; -} - -template -static T *array_end(T (&array)[N]) { return array + N; } - -static void PrintIncludes(grpc_generator::Printer *printer, - const std::vector &headers, - const Parameters ¶ms) { - std::map vars; - - vars["l"] = params.use_system_headers ? '<' : '"'; - vars["r"] = params.use_system_headers ? '>' : '"'; - - auto &s = params.grpc_search_path; - if (!s.empty()) { - vars["l"] += s; - if (s[s.size() - 1] != '/') { vars["l"] += '/'; } - } - - for (auto i = headers.begin(); i != headers.end(); i++) { - vars["h"] = *i; - printer->Print(vars, "#include $l$$h$$r$\n"); - } -} - -} // namespace - -grpc::string GetHeaderPrologue(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - - vars["filename"] = file->filename(); - vars["filename_identifier"] = FilenameIdentifier(file->filename()); - vars["filename_base"] = file->filename_without_ext(); - vars["message_header_ext"] = params.message_header_extension; - - printer->Print(vars, "// Generated by the gRPC C++ plugin.\n"); - printer->Print(vars, - "// If you make any local change, they will be lost.\n"); - printer->Print(vars, "// source: $filename$\n"); - grpc::string leading_comments = file->GetLeadingComments("//"); - if (!leading_comments.empty()) { - printer->Print(vars, "// Original file comments:\n"); - printer->Print(leading_comments.c_str()); - } - printer->Print(vars, "#ifndef GRPC_$filename_identifier$__INCLUDED\n"); - printer->Print(vars, "#define GRPC_$filename_identifier$__INCLUDED\n"); - printer->Print(vars, "\n"); - printer->Print(vars, "#include \"$filename_base$$message_header_ext$\"\n"); - printer->Print(vars, file->additional_headers().c_str()); - printer->Print(vars, "\n"); - } - return output; -} - -grpc::string GetHeaderIncludes(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - - static const char *headers_strs[] = { - "grpcpp/impl/codegen/async_stream.h", - "grpcpp/impl/codegen/async_unary_call.h", - "grpcpp/impl/codegen/method_handler.h", - "grpcpp/impl/codegen/proto_utils.h", - "grpcpp/impl/codegen/rpc_method.h", - "grpcpp/impl/codegen/service_type.h", - "grpcpp/impl/codegen/status.h", - "grpcpp/impl/codegen/stub_options.h", - "grpcpp/impl/codegen/sync_stream.h" - }; - std::vector headers(headers_strs, array_end(headers_strs)); - PrintIncludes(printer.get(), headers, params); - printer->Print(vars, "\n"); - printer->Print(vars, "namespace grpc {\n"); - printer->Print(vars, "class CompletionQueue;\n"); - printer->Print(vars, "class Channel;\n"); - printer->Print(vars, "class ServerCompletionQueue;\n"); - printer->Print(vars, "class ServerContext;\n"); - printer->Print(vars, "} // namespace grpc\n\n"); - - if (!file->package().empty()) { - std::vector parts = file->package_parts(); - - for (auto part = parts.begin(); part != parts.end(); part++) { - vars["part"] = *part; - printer->Print(vars, "namespace $part$ {\n"); - } - printer->Print(vars, "\n"); - } - } - return output; -} - - -namespace { - -static void PrintHeaderClientMethodInterfaces( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars, bool is_public) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - - struct { - grpc::string prefix; - grpc::string method_params; // extra arguments to method - grpc::string raw_args; // extra arguments to raw version of method - } async_prefixes[] = { { "Async", ", void* tag", ", tag" }, - { "PrepareAsync", "", "" } }; - - if (is_public) { - if (method->NoStreaming()) { - printer->Print( - *vars, - "virtual ::grpc::Status $Method$(::grpc::ClientContext* context, " - "const $Request$& request, $Response$* response) = 0;\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "std::unique_ptr< " - "::grpc::ClientAsyncResponseReaderInterface< $Response$>> " - "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncResponseReaderInterface< $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, request, cq));\n"); - printer->Outdent(); - printer->Print("}\n"); - } - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientWriterInterface< $Request$>>" - " $Method$(" - "::grpc::ClientContext* context, $Response$* response) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< ::grpc::ClientWriterInterface< $Request$>>" - "($Method$Raw(context, response));\n"); - printer->Outdent(); - printer->Print("}\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientAsyncWriterInterface< $Request$>>" - " $AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "$Response$* " - "response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print(*vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncWriterInterface< $Request$>>(" - "$AsyncPrefix$$Method$Raw(context, response, " - "cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); - } - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientReaderInterface< $Response$>>" - " $Method$(::grpc::ClientContext* context, const $Request$& request)" - " {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< ::grpc::ClientReaderInterface< $Response$>>" - "($Method$Raw(context, request));\n"); - printer->Outdent(); - printer->Print("}\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientAsyncReaderInterface< $Response$>> " - "$AsyncPrefix$$Method$(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncReaderInterface< $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, request, cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); - } - } else if (method->BidiStreaming()) { - printer->Print(*vars, - "std::unique_ptr< ::grpc::ClientReaderWriterInterface< " - "$Request$, $Response$>> " - "$Method$(::grpc::ClientContext* context) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientReaderWriterInterface< $Request$, $Response$>>(" - "$Method$Raw(context));\n"); - printer->Outdent(); - printer->Print("}\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "std::unique_ptr< " - "::grpc::ClientAsyncReaderWriterInterface< $Request$, $Response$>> " - "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncReaderWriterInterface< $Request$, $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); - } - } - } else { - if (method->NoStreaming()) { - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "virtual ::grpc::ClientAsyncResponseReaderInterface< $Response$>* " - "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) = 0;\n"); - } - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "virtual ::grpc::ClientWriterInterface< $Request$>*" - " $Method$Raw(" - "::grpc::ClientContext* context, $Response$* response) = 0;\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - printer->Print( - *vars, - "virtual ::grpc::ClientAsyncWriterInterface< $Request$>*" - " $AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "$Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); - } - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "virtual ::grpc::ClientReaderInterface< $Response$>* " - "$Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request) = 0;\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - printer->Print( - *vars, - "virtual ::grpc::ClientAsyncReaderInterface< $Response$>* " - "$AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); - } - } else if (method->BidiStreaming()) { - printer->Print(*vars, - "virtual ::grpc::ClientReaderWriterInterface< $Request$, " - "$Response$>* " - "$Method$Raw(::grpc::ClientContext* context) = 0;\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - printer->Print( - *vars, - "virtual ::grpc::ClientAsyncReaderWriterInterface< " - "$Request$, $Response$>* " - "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n"); - } - } - } -} - - - -static void PrintHeaderClientMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars, - bool is_public) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - struct { - grpc::string prefix; - grpc::string method_params; // extra arguments to method - grpc::string raw_args; // extra arguments to raw version of method - } async_prefixes[] = { { "Async", ", void* tag", ", tag" }, - { "PrepareAsync", "", "" } }; - - if (is_public) { - if (method->NoStreaming()) { - printer->Print( - *vars, - "::grpc::Status $Method$(::grpc::ClientContext* context, " - "const $Request$& request, $Response$* response) override;\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> " - "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) {\n"); - printer->Indent(); - printer->Print(*vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncResponseReader< $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, request, cq));\n"); - printer->Outdent(); - printer->Print("}\n"); - } - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientWriter< $Request$>>" - " $Method$(" - "::grpc::ClientContext* context, $Response$* response) {\n"); - printer->Indent(); - printer->Print(*vars, - "return std::unique_ptr< ::grpc::ClientWriter< $Request$>>" - "($Method$Raw(context, response));\n"); - printer->Outdent(); - printer->Print("}\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print(*vars, - "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>" - " $AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "$Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>(" - "$AsyncPrefix$$Method$Raw(context, response, " - "cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); - } - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientReader< $Response$>>" - " $Method$(::grpc::ClientContext* context, const $Request$& request)" - " {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< ::grpc::ClientReader< $Response$>>" - "($Method$Raw(context, request));\n"); - printer->Outdent(); - printer->Print("}\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> " - "$AsyncPrefix$$Method$(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, request, cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); - } - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "std::unique_ptr< ::grpc::ClientReaderWriter< $Request$, $Response$>>" - " $Method$(::grpc::ClientContext* context) {\n"); - printer->Indent(); - printer->Print(*vars, - "return std::unique_ptr< " - "::grpc::ClientReaderWriter< $Request$, $Response$>>(" - "$Method$Raw(context));\n"); - printer->Outdent(); - printer->Print("}\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print(*vars, - "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " - "$Request$, $Response$>> " - "$AsyncPrefix$$Method$(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Indent(); - printer->Print( - *vars, - "return std::unique_ptr< " - "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>>(" - "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n"); - printer->Outdent(); - printer->Print("}\n"); - } - } - } else { - if (method->NoStreaming()) { - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "::grpc::ClientAsyncResponseReader< $Response$>* " - "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) override;\n"); - } - } else if (ClientOnlyStreaming(method)) { - printer->Print(*vars, - "::grpc::ClientWriter< $Request$>* $Method$Raw(" - "::grpc::ClientContext* context, $Response$* response) " - "override;\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "::grpc::ClientAsyncWriter< $Request$>* $AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, $Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); - } - } else if (ServerOnlyStreaming(method)) { - printer->Print(*vars, - "::grpc::ClientReader< $Response$>* $Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request)" - " override;\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "::grpc::ClientAsyncReader< $Response$>* $AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); - } - } else if (method->BidiStreaming()) { - printer->Print(*vars, - "::grpc::ClientReaderWriter< $Request$, $Response$>* " - "$Method$Raw(::grpc::ClientContext* context) override;\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncRawArgs"] = async_prefix.raw_args; - printer->Print( - *vars, - "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* " - "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n"); - } - } - } -} - -static void PrintHeaderClientMethodData(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - printer->Print(*vars, - "const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n"); -} - -static void PrintHeaderServerMethodSync(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - printer->Print(method->GetLeadingComments("//").c_str()); - if (method->NoStreaming()) { - printer->Print(*vars, - "virtual ::grpc::Status $Method$(" - "::grpc::ServerContext* context, const $Request$* request, " - "$Response$* response);\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print(*vars, - "virtual ::grpc::Status $Method$(" - "::grpc::ServerContext* context, " - "::grpc::ServerReader< $Request$>* reader, " - "$Response$* response);\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print(*vars, - "virtual ::grpc::Status $Method$(" - "::grpc::ServerContext* context, const $Request$* request, " - "::grpc::ServerWriter< $Response$>* writer);\n"); - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "virtual ::grpc::Status $Method$(" - "::grpc::ServerContext* context, " - "::grpc::ServerReaderWriter< $Response$, $Request$>* stream);" - "\n"); - } - printer->Print(method->GetTrailingComments("//").c_str()); -} - -static void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - printer->Print(*vars, "template \n"); - printer->Print(*vars, - "class WithAsyncMethod_$Method$ : public BaseClass {\n"); - printer->Print( - " private:\n" - " void BaseClassMustBeDerivedFromService(const Service */*service*/) " - "{}\n"); - printer->Print(" public:\n"); - printer->Indent(); - printer->Print(*vars, - "WithAsyncMethod_$Method$() {\n" - " ::grpc::Service::MarkMethodAsync($Idx$);\n" - "}\n"); - printer->Print(*vars, - "~WithAsyncMethod_$Method$() override {\n" - " BaseClassMustBeDerivedFromService(this);\n" - "}\n"); - if (method->NoStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "$Response$* /*response*/) final override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - printer->Print( - *vars, - "void Request$Method$(" - "::grpc::ServerContext* context, $Request$* request, " - "::grpc::ServerAsyncResponseWriter< $Response$>* response, " - "::grpc::CompletionQueue* new_call_cq, " - "::grpc::ServerCompletionQueue* notification_cq, void *tag) {\n"); - printer->Print(*vars, - " ::grpc::Service::RequestAsyncUnary($Idx$, context, " - "request, response, new_call_cq, notification_cq, tag);\n"); - printer->Print("}\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReader< $Request$>* /*reader*/, " - "$Response$* /*response*/) final override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - printer->Print( - *vars, - "void Request$Method$(" - "::grpc::ServerContext* context, " - "::grpc::ServerAsyncReader< $Response$, $Request$>* reader, " - "::grpc::CompletionQueue* new_call_cq, " - "::grpc::ServerCompletionQueue* notification_cq, void *tag) {\n"); - printer->Print(*vars, - " ::grpc::Service::RequestAsyncClientStreaming($Idx$, " - "context, reader, new_call_cq, notification_cq, tag);\n"); - printer->Print("}\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "::grpc::ServerWriter< $Response$>* /*writer*/) final override " - "{\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - printer->Print( - *vars, - "void Request$Method$(" - "::grpc::ServerContext* context, $Request$* request, " - "::grpc::ServerAsyncWriter< $Response$>* writer, " - "::grpc::CompletionQueue* new_call_cq, " - "::grpc::ServerCompletionQueue* notification_cq, void *tag) {\n"); - printer->Print( - *vars, - " ::grpc::Service::RequestAsyncServerStreaming($Idx$, " - "context, request, writer, new_call_cq, notification_cq, tag);\n"); - printer->Print("}\n"); - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " - "final override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - printer->Print( - *vars, - "void Request$Method$(" - "::grpc::ServerContext* context, " - "::grpc::ServerAsyncReaderWriter< $Response$, $Request$>* stream, " - "::grpc::CompletionQueue* new_call_cq, " - "::grpc::ServerCompletionQueue* notification_cq, void *tag) {\n"); - printer->Print(*vars, - " ::grpc::Service::RequestAsyncBidiStreaming($Idx$, " - "context, stream, new_call_cq, notification_cq, tag);\n"); - printer->Print("}\n"); - } - printer->Outdent(); - printer->Print(*vars, "};\n"); -} - -static void PrintHeaderServerMethodStreamedUnary( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - if (method->NoStreaming()) { - printer->Print(*vars, "template \n"); - printer->Print(*vars, - "class WithStreamedUnaryMethod_$Method$ : " - "public BaseClass {\n"); - printer->Print( - " private:\n" - " void BaseClassMustBeDerivedFromService(const Service */*service*/) " - "{}\n"); - printer->Print(" public:\n"); - printer->Indent(); - printer->Print(*vars, - "WithStreamedUnaryMethod_$Method$() {\n" - " ::grpc::Service::MarkMethodStreamed($Idx$,\n" - " new ::grpc::internal::StreamedUnaryHandler< $Request$, " - "$Response$>(std::bind" - "(&WithStreamedUnaryMethod_$Method$::" - "Streamed$Method$, this, std::placeholders::_1, " - "std::placeholders::_2)));\n" - "}\n"); - printer->Print(*vars, - "~WithStreamedUnaryMethod_$Method$() override {\n" - " BaseClassMustBeDerivedFromService(this);\n" - "}\n"); - printer->Print( - *vars, - "// disable regular version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "$Response$* /*response*/) final override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - printer->Print(*vars, - "// replace default version of method with streamed unary\n" - "virtual ::grpc::Status Streamed$Method$(" - "::grpc::ServerContext* context, " - "::grpc::ServerUnaryStreamer< " - "$Request$,$Response$>* server_unary_streamer)" - " = 0;\n"); - printer->Outdent(); - printer->Print(*vars, "};\n"); - } -} - -static void PrintHeaderServerMethodSplitStreaming( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - if (ServerOnlyStreaming(method)) { - printer->Print(*vars, "template \n"); - printer->Print(*vars, - "class WithSplitStreamingMethod_$Method$ : " - "public BaseClass {\n"); - printer->Print( - " private:\n" - " void BaseClassMustBeDerivedFromService(const Service */*service*/) " - "{ }\n"); - printer->Print(" public:\n"); - printer->Indent(); - printer->Print( - *vars, - "WithSplitStreamingMethod_$Method$() {\n" - " ::grpc::Service::MarkMethodStreamed($Idx$,\n" - " new ::grpc::internal::SplitServerStreamingHandler< $Request$, " - "$Response$>(std::bind" - "(&WithSplitStreamingMethod_$Method$::" - "Streamed$Method$, this, std::placeholders::_1, " - "std::placeholders::_2)));\n" - "}\n"); - printer->Print(*vars, - "~WithSplitStreamingMethod_$Method$() override {\n" - " BaseClassMustBeDerivedFromService(this);\n" - "}\n"); - printer->Print( - *vars, - "// disable regular version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "::grpc::ServerWriter< $Response$>* /*writer*/) final override " - "{\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - printer->Print(*vars, - "// replace default version of method with split streamed\n" - "virtual ::grpc::Status Streamed$Method$(" - "::grpc::ServerContext* context, " - "::grpc::ServerSplitStreamer< " - "$Request$,$Response$>* server_split_streamer)" - " = 0;\n"); - printer->Outdent(); - printer->Print(*vars, "};\n"); - } -} - -static void PrintHeaderServerMethodGeneric( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - printer->Print(*vars, "template \n"); - printer->Print(*vars, - "class WithGenericMethod_$Method$ : public BaseClass {\n"); - printer->Print( - " private:\n" - " void BaseClassMustBeDerivedFromService(const Service */*service*/) " - "{}\n"); - printer->Print(" public:\n"); - printer->Indent(); - printer->Print(*vars, - "WithGenericMethod_$Method$() {\n" - " ::grpc::Service::MarkMethodGeneric($Idx$);\n" - "}\n"); - printer->Print(*vars, - "~WithGenericMethod_$Method$() override {\n" - " BaseClassMustBeDerivedFromService(this);\n" - "}\n"); - if (method->NoStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "$Response$* /*response*/) final override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReader< $Request$>* /*reader*/, " - "$Response$* /*response*/) final override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " - "::grpc::ServerWriter< $Response$>* /*writer*/) final override " - "{\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " - "final override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - } - printer->Outdent(); - printer->Print(*vars, "};\n"); -} - -static void PrintHeaderService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { - (*vars)["Service"] = service->name(); - - printer->Print(service->GetLeadingComments("//").c_str()); - printer->Print(*vars, - "class $Service$ final {\n" - " public:\n"); - printer->Indent(); - - // Service metadata - printer->Print(*vars, - "static constexpr char const* service_full_name() {\n" - " return \"$Package$$Service$\";\n" - "}\n"); - - // Client side - printer->Print( - "class StubInterface {\n" - " public:\n"); - printer->Indent(); - printer->Print("virtual ~StubInterface() {}\n"); - for (int i = 0; i < service->method_count(); ++i) { - printer->Print(service->method(i)->GetLeadingComments("//").c_str()); - PrintHeaderClientMethodInterfaces(printer, service->method(i).get(), vars, - true); - printer->Print(service->method(i)->GetTrailingComments("//").c_str()); - } - printer->Outdent(); - printer->Print("private:\n"); - printer->Indent(); - for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderClientMethodInterfaces(printer, service->method(i).get(), vars, - false); - } - printer->Outdent(); - printer->Print("};\n"); - printer->Print( - "class Stub final : public StubInterface" - " {\n public:\n"); - printer->Indent(); - printer->Print( - "Stub(const std::shared_ptr< ::grpc::ChannelInterface>& " - "channel);\n"); - for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderClientMethod(printer, service->method(i).get(), vars, true); - } - printer->Outdent(); - printer->Print("\n private:\n"); - printer->Indent(); - printer->Print("std::shared_ptr< ::grpc::ChannelInterface> channel_;\n"); - for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderClientMethod(printer, service->method(i).get(), vars, false); - } - for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderClientMethodData(printer, service->method(i).get(), vars); - } - printer->Outdent(); - printer->Print("};\n"); - printer->Print( - "static std::unique_ptr NewStub(const std::shared_ptr< " - "::grpc::ChannelInterface>& channel, " - "const ::grpc::StubOptions& options = ::grpc::StubOptions());\n"); - - printer->Print("\n"); - - // Server side - base - printer->Print( - "class Service : public ::grpc::Service {\n" - " public:\n"); - printer->Indent(); - printer->Print("Service();\n"); - printer->Print("virtual ~Service();\n"); - for (int i = 0; i < service->method_count(); ++i) { - PrintHeaderServerMethodSync(printer, service->method(i).get(), vars); - } - printer->Outdent(); - printer->Print("};\n"); - - // Server side - Asynchronous - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodAsync(printer, service->method(i).get(), vars); - } - - printer->Print("typedef "); - - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i).get()->name(); - printer->Print(*vars, "WithAsyncMethod_$method_name$<"); - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { printer->Print(" >"); } - printer->Print(" AsyncService;\n"); - - // Server side - Generic - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodGeneric(printer, service->method(i).get(), vars); - } - - // Server side - Streamed Unary - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodStreamedUnary(printer, service->method(i).get(), - vars); - } - - printer->Print("typedef "); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i).get()->name(); - if (service->method(i)->NoStreaming()) { - printer->Print(*vars, "WithStreamedUnaryMethod_$method_name$<"); - } - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { - if (service->method(i)->NoStreaming()) { printer->Print(" >"); } - } - printer->Print(" StreamedUnaryService;\n"); - - // Server side - controlled server-side streaming - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodSplitStreaming(printer, service->method(i).get(), - vars); - } - - printer->Print("typedef "); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i).get()->name(); - auto method = service->method(i); - if (ServerOnlyStreaming(method.get())) { - printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<"); - } - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - if (ServerOnlyStreaming(method.get())) { printer->Print(" >"); } - } - printer->Print(" SplitStreamedService;\n"); - - // Server side - typedef for controlled both unary and server-side streaming - printer->Print("typedef "); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i).get()->name(); - auto method = service->method(i); - if (ServerOnlyStreaming(method.get())) { - printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<"); - } - if (service->method(i)->NoStreaming()) { - printer->Print(*vars, "WithStreamedUnaryMethod_$method_name$<"); - } - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - if (service->method(i)->NoStreaming() || - ServerOnlyStreaming(method.get())) { - printer->Print(" >"); - } - } - printer->Print(" StreamedService;\n"); - - printer->Outdent(); - printer->Print("};\n"); - printer->Print(service->GetTrailingComments("//").c_str()); -} - -} // namespace - -grpc::string GetHeaderServices(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - // Package string is empty or ends with a dot. It is used to fully qualify - // method names. - vars["Package"] = file->package(); - if (!file->package().empty()) { vars["Package"].append("."); } - - if (!params.services_namespace.empty()) { - vars["services_namespace"] = params.services_namespace; - printer->Print(vars, "\nnamespace $services_namespace$ {\n\n"); - } - - for (int i = 0; i < file->service_count(); ++i) { - PrintHeaderService(printer.get(), file->service(i).get(), &vars); - printer->Print("\n"); - } - - if (!params.services_namespace.empty()) { - printer->Print(vars, "} // namespace $services_namespace$\n\n"); - } - } - return output; -} - -grpc::string GetHeaderEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - - vars["filename"] = file->filename(); - vars["filename_identifier"] = FilenameIdentifier(file->filename()); - - if (!file->package().empty()) { - std::vector parts = file->package_parts(); - - for (auto part = parts.rbegin(); part != parts.rend(); part++) { - vars["part"] = *part; - printer->Print(vars, "} // namespace $part$\n"); - } - printer->Print(vars, "\n"); - } - - printer->Print(vars, "\n"); - printer->Print(vars, "#endif // GRPC_$filename_identifier$__INCLUDED\n"); - - printer->Print(file->GetTrailingComments("//").c_str()); - } - return output; -} - -grpc::string GetSourcePrologue(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - - vars["filename"] = file->filename(); - vars["filename_base"] = file->filename_without_ext(); - vars["message_header_ext"] = params.message_header_extension; - vars["service_header_ext"] = service_header_ext(); - - printer->Print(vars, "// Generated by the gRPC C++ plugin.\n"); - printer->Print(vars, - "// If you make any local change, they will be lost.\n"); - printer->Print(vars, "// source: $filename$\n\n"); - - printer->Print(vars, "#include \"$filename_base$$message_header_ext$\"\n"); - printer->Print(vars, "#include \"$filename_base$$service_header_ext$\"\n"); - printer->Print(vars, "\n"); - } - return output; -} - -grpc::string GetSourceIncludes(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - - static const char *headers_strs[] = { - "grpcpp/impl/codegen/async_stream.h", - "grpcpp/impl/codegen/async_unary_call.h", - "grpcpp/impl/codegen/channel_interface.h", - "grpcpp/impl/codegen/client_unary_call.h", - "grpcpp/impl/codegen/method_handler.h", - "grpcpp/impl/codegen/rpc_service_method.h", - "grpcpp/impl/codegen/service_type.h", - "grpcpp/impl/codegen/sync_stream.h" - }; - std::vector headers(headers_strs, array_end(headers_strs)); - PrintIncludes(printer.get(), headers, params); - - if (!file->package().empty()) { - std::vector parts = file->package_parts(); - - for (auto part = parts.begin(); part != parts.end(); part++) { - vars["part"] = *part; - printer->Print(vars, "namespace $part$ {\n"); - } - } - - printer->Print(vars, "\n"); - } - return output; -} - - -namespace { - -static void PrintSourceClientMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - struct { - grpc::string prefix; - grpc::string start; // bool literal expressed as string - grpc::string method_params; // extra arguments to method - grpc::string create_args; // extra arguments to creator - } async_prefixes[] = { { "Async", "true", ", void* tag", ", tag" }, - { "PrepareAsync", "false", "", ", nullptr" } }; - if (method->NoStreaming()) { - printer->Print(*vars, - "::grpc::Status $ns$$Service$::Stub::$Method$(" - "::grpc::ClientContext* context, " - "const $Request$& request, $Response$* response) {\n"); - printer->Print(*vars, - " return ::grpc::internal::BlockingUnaryCall" - "(channel_.get(), rpcmethod_$Method$_, " - "context, request, response);\n}\n\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncStart"] = async_prefix.start; - printer->Print(*vars, - "::grpc::ClientAsyncResponseReader< $Response$>* " - "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(::grpc::" - "ClientContext* context, " - "const $Request$& request, " - "::grpc::CompletionQueue* cq) {\n"); - printer->Print( - *vars, - " return " - "::grpc::internal::ClientAsyncResponseReaderFactory< $Response$>" - "::Create(channel_.get(), cq, " - "rpcmethod_$Method$_, " - "context, request, $AsyncStart$);\n" - "}\n\n"); - } - } else if (ClientOnlyStreaming(method)) { - printer->Print(*vars, - "::grpc::ClientWriter< $Request$>* " - "$ns$$Service$::Stub::$Method$Raw(" - "::grpc::ClientContext* context, $Response$* response) {\n"); - printer->Print( - *vars, - " return ::grpc::internal::ClientWriterFactory< $Request$>::Create(" - "channel_.get(), " - "rpcmethod_$Method$_, " - "context, response);\n" - "}\n\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncStart"] = async_prefix.start; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncCreateArgs"] = async_prefix.create_args; - printer->Print(*vars, - "::grpc::ClientAsyncWriter< $Request$>* " - "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, $Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Print( - *vars, - " return ::grpc::internal::ClientAsyncWriterFactory< $Request$>" - "::Create(channel_.get(), cq, " - "rpcmethod_$Method$_, " - "context, response, $AsyncStart$$AsyncCreateArgs$);\n" - "}\n\n"); - } - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "::grpc::ClientReader< $Response$>* " - "$ns$$Service$::Stub::$Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request) {\n"); - printer->Print( - *vars, - " return ::grpc::internal::ClientReaderFactory< $Response$>::Create(" - "channel_.get(), " - "rpcmethod_$Method$_, " - "context, request);\n" - "}\n\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncStart"] = async_prefix.start; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncCreateArgs"] = async_prefix.create_args; - printer->Print( - *vars, - "::grpc::ClientAsyncReader< $Response$>* " - "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(" - "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Print( - *vars, - " return ::grpc::internal::ClientAsyncReaderFactory< $Response$>" - "::Create(channel_.get(), cq, " - "rpcmethod_$Method$_, " - "context, request, $AsyncStart$$AsyncCreateArgs$);\n" - "}\n\n"); - } - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "::grpc::ClientReaderWriter< $Request$, $Response$>* " - "$ns$$Service$::Stub::$Method$Raw(::grpc::ClientContext* context) {\n"); - printer->Print(*vars, - " return ::grpc::internal::ClientReaderWriterFactory< " - "$Request$, $Response$>::Create(" - "channel_.get(), " - "rpcmethod_$Method$_, " - "context);\n" - "}\n\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncStart"] = async_prefix.start; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["AsyncCreateArgs"] = async_prefix.create_args; - printer->Print(*vars, - "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* " - "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(::grpc::" - "ClientContext* context, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n"); - printer->Print(*vars, - " return " - "::grpc::internal::ClientAsyncReaderWriterFactory< " - "$Request$, $Response$>::Create(" - "channel_.get(), cq, " - "rpcmethod_$Method$_, " - "context, $AsyncStart$$AsyncCreateArgs$);\n" - "}\n\n"); - } - } -} - -static void PrintSourceServerMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - if (method->NoStreaming()) { - printer->Print( - *vars, - "::grpc::Status $ns$$Service$::Service::$Method$(" - "::grpc::ServerContext* /*context*/, " - "const $Request$* /*request*/, $Response$* /*response*/) {\n"); - printer->Print( - " return ::grpc::Status(" - "::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"); - printer->Print("}\n\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print(*vars, - "::grpc::Status $ns$$Service$::Service::$Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReader< $Request$>* /*reader*/, " - "$Response$* /*response*/) {\n"); - printer->Print( - " return ::grpc::Status(" - "::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"); - printer->Print("}\n\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print(*vars, - "::grpc::Status $ns$$Service$::Service::$Method$(" - "::grpc::ServerContext* /*context*/, " - "const $Request$* /*request*/, " - "::grpc::ServerWriter< $Response$>* /*writer*/) {\n"); - printer->Print( - " return ::grpc::Status(" - "::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"); - printer->Print("}\n\n"); - } else if (method->BidiStreaming()) { - printer->Print(*vars, - "::grpc::Status $ns$$Service$::Service::$Method$(" - "::grpc::ServerContext* /*context*/, " - "::grpc::ServerReaderWriter< $Response$, $Request$>* " - "/*stream*/) {\n"); - printer->Print( - " return ::grpc::Status(" - "::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"); - printer->Print("}\n\n"); - } -} - -static void PrintSourceService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { - (*vars)["Service"] = service->name(); - - if (service->method_count() > 0) { - printer->Print(*vars, - "static const char* $prefix$$Service$_method_names[] = {\n"); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Method"] = service->method(i).get()->name(); - printer->Print(*vars, " \"/$Package$$Service$/$Method$\",\n"); - } - printer->Print(*vars, "};\n\n"); - } - - printer->Print(*vars, - "std::unique_ptr< $ns$$Service$::Stub> $ns$$Service$::NewStub(" - "const std::shared_ptr< ::grpc::ChannelInterface>& channel, " - "const ::grpc::StubOptions& /*options*/) {\n" - " std::unique_ptr< $ns$$Service$::Stub> stub(new " - "$ns$$Service$::Stub(channel));\n" - " return stub;\n" - "}\n\n"); - printer->Print(*vars, - "$ns$$Service$::Stub::Stub(const std::shared_ptr< " - "::grpc::ChannelInterface>& channel)\n"); - printer->Indent(); - printer->Print(": channel_(channel)"); - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - (*vars)["Method"] = method->name(); - (*vars)["Idx"] = as_string(i); - if (method->NoStreaming()) { - (*vars)["StreamingType"] = "NORMAL_RPC"; - // NOTE: There is no reason to consider streamed-unary as a separate - // category here since this part is setting up the client-side stub - // and this appears as a NORMAL_RPC from the client-side. - } else if (ClientOnlyStreaming(method.get())) { - (*vars)["StreamingType"] = "CLIENT_STREAMING"; - } else if (ServerOnlyStreaming(method.get())) { - (*vars)["StreamingType"] = "SERVER_STREAMING"; - } else { - (*vars)["StreamingType"] = "BIDI_STREAMING"; - } - printer->Print(*vars, - ", rpcmethod_$Method$_(" - "$prefix$$Service$_method_names[$Idx$], " - "::grpc::internal::RpcMethod::$StreamingType$, " - "channel" - ")\n"); - } - printer->Print("{}\n\n"); - printer->Outdent(); - - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintSourceClientMethod(printer, service->method(i).get(), vars); - } - - printer->Print(*vars, "$ns$$Service$::Service::Service() {\n"); - printer->Indent(); - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - (*vars)["Idx"] = as_string(i); - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - if (method->NoStreaming()) { - printer->Print( - *vars, - "AddMethod(new ::grpc::internal::RpcServiceMethod(\n" - " $prefix$$Service$_method_names[$Idx$],\n" - " ::grpc::internal::RpcMethod::NORMAL_RPC,\n" - " new ::grpc::internal::RpcMethodHandler< $ns$$Service$::Service, " - "$Request$, " - "$Response$>(\n" - " std::mem_fn(&$ns$$Service$::Service::$Method$), this)));\n"); - } else if (ClientOnlyStreaming(method.get())) { - printer->Print( - *vars, - "AddMethod(new ::grpc::internal::RpcServiceMethod(\n" - " $prefix$$Service$_method_names[$Idx$],\n" - " ::grpc::internal::RpcMethod::CLIENT_STREAMING,\n" - " new ::grpc::internal::ClientStreamingHandler< " - "$ns$$Service$::Service, $Request$, $Response$>(\n" - " std::mem_fn(&$ns$$Service$::Service::$Method$), this)));\n"); - } else if (ServerOnlyStreaming(method.get())) { - printer->Print( - *vars, - "AddMethod(new ::grpc::internal::RpcServiceMethod(\n" - " $prefix$$Service$_method_names[$Idx$],\n" - " ::grpc::internal::RpcMethod::SERVER_STREAMING,\n" - " new ::grpc::internal::ServerStreamingHandler< " - "$ns$$Service$::Service, $Request$, $Response$>(\n" - " std::mem_fn(&$ns$$Service$::Service::$Method$), this)));\n"); - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "AddMethod(new ::grpc::internal::RpcServiceMethod(\n" - " $prefix$$Service$_method_names[$Idx$],\n" - " ::grpc::internal::RpcMethod::BIDI_STREAMING,\n" - " new ::grpc::internal::BidiStreamingHandler< " - "$ns$$Service$::Service, $Request$, $Response$>(\n" - " std::mem_fn(&$ns$$Service$::Service::$Method$), this)));\n"); - } - } - printer->Outdent(); - printer->Print(*vars, "}\n\n"); - printer->Print(*vars, - "$ns$$Service$::Service::~Service() {\n" - "}\n\n"); - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintSourceServerMethod(printer, service->method(i).get(), vars); - } -} - -} // namespace - -grpc::string GetSourceServices(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - // Package string is empty or ends with a dot. It is used to fully qualify - // method names. - vars["Package"] = file->package(); - if (!file->package().empty()) { vars["Package"].append("."); } - if (!params.services_namespace.empty()) { - vars["ns"] = params.services_namespace + "::"; - vars["prefix"] = params.services_namespace; - } else { - vars["ns"] = ""; - vars["prefix"] = ""; - } - - for (int i = 0; i < file->service_count(); ++i) { - PrintSourceService(printer.get(), file->service(i).get(), &vars); - printer->Print("\n"); - } - } - return output; -} - -grpc::string GetSourceEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { - grpc::string temp; - - if (!file->package().empty()) { - std::vector parts = file->package_parts(); - - for (auto part = parts.begin(); part != parts.end(); part++) { - temp.append("} // namespace "); - temp.append(*part); - temp.append("\n"); - } - temp.append("\n"); - } - - return temp; -} - -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - - vars["filename"] = file->filename(); - vars["filename_base"] = file->filename_without_ext(); - vars["message_header_ext"] = params.message_header_extension; - vars["service_header_ext"] = service_header_ext(); - - printer->Print(vars, "// Generated by the gRPC C++ plugin.\n"); - printer->Print(vars, - "// If you make any local change, they will be lost.\n"); - printer->Print(vars, "// source: $filename$\n\n"); - - printer->Print(vars, "#include \"$filename_base$$message_header_ext$\"\n"); - printer->Print(vars, "#include \"$filename_base$$service_header_ext$\"\n"); - printer->Print(vars, file->additional_headers().c_str()); - printer->Print(vars, "\n"); - } - return output; -} - -// TODO(mmukhi): Add client-stream and completion-queue headers. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - - static const char *headers_strs[] = { - "grpcpp/impl/codegen/async_stream.h", - "grpcpp/impl/codegen/sync_stream.h", - "gmock/gmock.h", - }; - std::vector headers(headers_strs, array_end(headers_strs)); - PrintIncludes(printer.get(), headers, params); - - if (!file->package().empty()) { - std::vector parts = file->package_parts(); - - for (auto part = parts.begin(); part != parts.end(); part++) { - vars["part"] = *part; - printer->Print(vars, "namespace $part$ {\n"); - } - } - - printer->Print(vars, "\n"); - } - return output; -} - - -namespace { - -static void PrintMockClientMethods(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - - struct { - grpc::string prefix; - grpc::string method_params; // extra arguments to method - int extra_method_param_count; - } async_prefixes[] = { { "Async", ", void* tag", 1 }, - { "PrepareAsync", "", 0 } }; - - if (method->NoStreaming()) { - printer->Print( - *vars, - "MOCK_METHOD3($Method$, ::grpc::Status(::grpc::ClientContext* context, " - "const $Request$& request, $Response$* response));\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - printer->Print( - *vars, - "MOCK_METHOD3($AsyncPrefix$$Method$Raw, " - "::grpc::ClientAsyncResponseReaderInterface< $Response$>*" - "(::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq));\n"); - } - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "MOCK_METHOD2($Method$Raw, " - "::grpc::ClientWriterInterface< $Request$>*" - "(::grpc::ClientContext* context, $Response$* response));\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["MockArgs"] = - flatbuffers::NumToString(3 + async_prefix.extra_method_param_count); - printer->Print(*vars, - "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " - "::grpc::ClientAsyncWriterInterface< $Request$>*" - "(::grpc::ClientContext* context, $Response$* response, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n"); - } - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "MOCK_METHOD2($Method$Raw, " - "::grpc::ClientReaderInterface< $Response$>*" - "(::grpc::ClientContext* context, const $Request$& request));\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["MockArgs"] = - flatbuffers::NumToString(3 + async_prefix.extra_method_param_count); - printer->Print( - *vars, - "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " - "::grpc::ClientAsyncReaderInterface< $Response$>*" - "(::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n"); - } - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "MOCK_METHOD1($Method$Raw, " - "::grpc::ClientReaderWriterInterface< $Request$, $Response$>*" - "(::grpc::ClientContext* context));\n"); - for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); - i++) { - auto &async_prefix = async_prefixes[i]; - (*vars)["AsyncPrefix"] = async_prefix.prefix; - (*vars)["AsyncMethodParams"] = async_prefix.method_params; - (*vars)["MockArgs"] = - flatbuffers::NumToString(2 + async_prefix.extra_method_param_count); - printer->Print( - *vars, - "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, " - "::grpc::ClientAsyncReaderWriterInterface<$Request$, $Response$>*" - "(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq" - "$AsyncMethodParams$));\n"); - } - } -} - -static void PrintMockService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { - (*vars)["Service"] = service->name(); - - printer->Print(*vars, - "class Mock$Service$Stub : public $Service$::StubInterface {\n" - " public:\n"); - printer->Indent(); - for (int i = 0; i < service->method_count(); ++i) { - PrintMockClientMethods(printer, service->method(i).get(), vars); - } - printer->Outdent(); - printer->Print("};\n"); -} - -} // namespace - -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms) { - grpc::string output; - { - // Scope the output stream so it closes and finalizes output to the string. - auto printer = file->CreatePrinter(&output); - std::map vars; - // Package string is empty or ends with a dot. It is used to fully qualify - // method names. - vars["Package"] = file->package(); - if (!file->package().empty()) { vars["Package"].append("."); } - - if (!params.services_namespace.empty()) { - vars["services_namespace"] = params.services_namespace; - printer->Print(vars, "\nnamespace $services_namespace$ {\n\n"); - } - - for (int i = 0; i < file->service_count(); i++) { - PrintMockService(printer.get(), file->service(i).get(), &vars); - printer->Print("\n"); - } - - if (!params.services_namespace.empty()) { - printer->Print(vars, "} // namespace $services_namespace$\n\n"); - } - } - return output; -} - -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { - grpc::string temp; - - if (!file->package().empty()) { - std::vector parts = file->package_parts(); - - for (auto part = parts.begin(); part != parts.end(); part++) { - temp.append("} // namespace "); - temp.append(*part); - temp.append("\n"); - } - temp.append("\n"); - } - - return temp; -} - -} // namespace grpc_cpp_generator diff --git a/third_party/flatbuffers/grpc/src/compiler/cpp_generator.h b/third_party/flatbuffers/grpc/src/compiler/cpp_generator.h deleted file mode 100644 index a9af1a6794f..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/cpp_generator.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H -#define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H - -// cpp_generator.h/.cc do not directly depend on GRPC/ProtoBuf, such that they -// can be used to generate code for other serialization systems, such as -// FlatBuffers. - -#include -#include - -#include "src/compiler/schema_interface.h" - -#ifndef GRPC_CUSTOM_STRING -# include -# define GRPC_CUSTOM_STRING std::string -#endif - -namespace grpc { - -typedef GRPC_CUSTOM_STRING string; - -} // namespace grpc - -namespace grpc_cpp_generator { - -// Contains all the parameters that are parsed from the command line. -struct Parameters { - // Puts the service into a namespace - grpc::string services_namespace; - // Use system includes (<>) or local includes ("") - bool use_system_headers; - // Prefix to any grpc include - grpc::string grpc_search_path; - // Generate GMOCK code to facilitate unit testing. - bool generate_mock_code; - // By default, use "_generated.h" - std::string message_header_extension; -}; - -// Return the prologue of the generated header file. -grpc::string GetHeaderPrologue(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the includes needed for generated header file. -grpc::string GetHeaderIncludes(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the includes needed for generated source file. -grpc::string GetSourceIncludes(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the epilogue of the generated header file. -grpc::string GetHeaderEpilogue(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the prologue of the generated source file. -grpc::string GetSourcePrologue(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the services for generated header file. -grpc::string GetHeaderServices(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the services for generated source file. -grpc::string GetSourceServices(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the epilogue of the generated source file. -grpc::string GetSourceEpilogue(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the prologue of the generated mock file. -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the includes needed for generated mock file. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the services for generated mock file. -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the epilogue of generated mock file. -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the prologue of the generated mock file. -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the includes needed for generated mock file. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the services for generated mock file. -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms); - -// Return the epilogue of generated mock file. -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters ¶ms); - -} // namespace grpc_cpp_generator - -#endif // GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H diff --git a/third_party/flatbuffers/grpc/src/compiler/go_generator.cc b/third_party/flatbuffers/grpc/src/compiler/go_generator.cc deleted file mode 100644 index ad4694b107f..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/go_generator.cc +++ /dev/null @@ -1,507 +0,0 @@ -#include "src/compiler/go_generator.h" - -#include -#include -#include - -template grpc::string as_string(T x) { - std::ostringstream out; - out << x; - return out.str(); -} - -inline bool ClientOnlyStreaming(const grpc_generator::Method *method) { - return method->ClientStreaming() && !method->ServerStreaming(); -} - -inline bool ServerOnlyStreaming(const grpc_generator::Method *method) { - return !method->ClientStreaming() && method->ServerStreaming(); -} - -namespace grpc_go_generator { -namespace { - -// Returns string with first letter to lowerCase -static grpc::string unexportName(grpc::string s) { - if (s.empty()) return s; - s[0] = static_cast(std::tolower(s[0])); - return s; -} - -// Returns string with first letter to uppercase -static grpc::string exportName(grpc::string s) { - if (s.empty()) return s; - s[0] = static_cast(std::toupper(s[0])); - return s; -} - -static void GenerateError(grpc_generator::Printer *printer, - std::map vars, - const bool multiple_return = true) { - printer->Print(vars, "if $Error_Check$ {\n"); - printer->Indent(); - vars["Return"] = multiple_return ? "nil, err" : "err"; - printer->Print(vars, "return $Return$\n"); - printer->Outdent(); - printer->Print("}\n"); -} - -// Generates imports for the service -static void GenerateImports(grpc_generator::File *file, - grpc_generator::Printer *printer, - std::map vars) { - vars["filename"] = file->filename(); - printer->Print("//Generated by gRPC Go plugin\n"); - printer->Print("//If you make any local changes, they will be lost\n"); - printer->Print(vars, "//source: $filename$\n\n"); - printer->Print(vars, "package $Package$\n\n"); - printer->Print("import (\n"); - printer->Indent(); - printer->Print(vars, "$context$ \"context\"\n"); - printer->Print("flatbuffers \"github.com/google/flatbuffers/go\"\n"); - printer->Print(vars, "$grpc$ \"google.golang.org/grpc\"\n"); - printer->Print("\"google.golang.org/grpc/codes\"\n"); - printer->Print("\"google.golang.org/grpc/status\"\n"); - printer->Outdent(); - printer->Print(")\n\n"); -} - -// Generates Server method signature source -static void GenerateServerMethodSignature(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map vars) { - vars["Method"] = exportName(method->name()); - vars["Request"] = method->get_input_type_name(); - vars["Response"] = (vars["CustomMethodIO"] == "") - ? method->get_output_type_name() - : vars["CustomMethodIO"]; - if (method->NoStreaming()) { - printer->Print( - vars, - "$Method$($context$.Context, *$Request$) (*$Response$, error)$Ending$"); - } else if (ServerOnlyStreaming(method)) { - printer->Print( - vars, "$Method$(*$Request$, $Service$_$Method$Server) error$Ending$"); - } else { - printer->Print(vars, "$Method$($Service$_$Method$Server) error$Ending$"); - } -} - -static void GenerateServerMethod(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map vars) { - vars["Method"] = exportName(method->name()); - vars["Request"] = method->get_input_type_name(); - vars["Response"] = (vars["CustomMethodIO"] == "") - ? method->get_output_type_name() - : vars["CustomMethodIO"]; - vars["FullMethodName"] = - "/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"]; - vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler"; - if (method->NoStreaming()) { - printer->Print( - vars, - "func $Handler$(srv interface{}, ctx $context$.Context,\n\tdec " - "func(interface{}) error, interceptor $grpc$.UnaryServerInterceptor) " - "(interface{}, error) {\n"); - printer->Indent(); - printer->Print(vars, "in := new($Request$)\n"); - vars["Error_Check"] = "err := dec(in); err != nil"; - GenerateError(printer, vars); - printer->Print("if interceptor == nil {\n"); - printer->Indent(); - printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, in)\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Print(vars, "info := &$grpc$.UnaryServerInfo{\n"); - printer->Indent(); - printer->Print("Server: srv,\n"); - printer->Print(vars, "FullMethod: \"$FullMethodName$\",\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("\n"); - printer->Indent(); - printer->Print(vars, - "handler := func(ctx $context$.Context, req interface{}) " - "(interface{}, error) {\n"); - printer->Indent(); - printer->Print( - vars, "return srv.($Service$Server).$Method$(ctx, req.(*$Request$))\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Print("return interceptor(ctx, in, info, handler)\n"); - printer->Outdent(); - printer->Print("}\n"); - return; - } - vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Server"; - printer->Print( - vars, - "func $Handler$(srv interface{}, stream $grpc$.ServerStream) error {\n"); - printer->Indent(); - if (ServerOnlyStreaming(method)) { - printer->Print(vars, "m := new($Request$)\n"); - vars["Error_Check"] = "err := stream.RecvMsg(m); err != nil"; - GenerateError(printer, vars, false); - printer->Print( - vars, - "return srv.($Service$Server).$Method$(m, &$StreamType${stream})\n"); - } else { - printer->Print( - vars, "return srv.($Service$Server).$Method$(&$StreamType${stream})\n"); - } - printer->Outdent(); - printer->Print("}\n\n"); - - bool genSend = method->BidiStreaming() || ServerOnlyStreaming(method); - bool genRecv = method->BidiStreaming() || ClientOnlyStreaming(method); - bool genSendAndClose = ClientOnlyStreaming(method); - - printer->Print(vars, "type $Service$_$Method$Server interface {\n"); - printer->Indent(); - if (genSend) { printer->Print(vars, "Send(*$Response$) error\n"); } - if (genRecv) { printer->Print(vars, "Recv() (*$Request$, error)\n"); } - if (genSendAndClose) { - printer->Print(vars, "SendAndClose(*$Response$) error\n"); - } - printer->Print(vars, "$grpc$.ServerStream\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - printer->Print(vars, "type $StreamType$ struct {\n"); - printer->Indent(); - printer->Print(vars, "$grpc$.ServerStream\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - if (genSend) { - printer->Print(vars, - "func (x *$StreamType$) Send(m *$Response$) error {\n"); - printer->Indent(); - printer->Print("return x.ServerStream.SendMsg(m)\n"); - printer->Outdent(); - printer->Print("}\n\n"); - } - if (genRecv) { - printer->Print(vars, - "func (x *$StreamType$) Recv() (*$Request$, error) {\n"); - printer->Indent(); - printer->Print(vars, "m := new($Request$)\n"); - vars["Error_Check"] = "err := x.ServerStream.RecvMsg(m); err != nil"; - GenerateError(printer, vars); - printer->Print("return m, nil\n"); - printer->Outdent(); - printer->Print("}\n\n"); - } - if (genSendAndClose) { - printer->Print( - vars, "func (x *$StreamType$) SendAndClose(m *$Response$) error {\n"); - printer->Indent(); - printer->Print("return x.ServerStream.SendMsg(m)\n"); - printer->Outdent(); - printer->Print("}\n\n"); - } -} - -// Generates Client method signature source -static void GenerateClientMethodSignature(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map vars) { - vars["Method"] = exportName(method->name()); - vars["Request"] = - ", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name() - : vars["CustomMethodIO"]); - if (ClientOnlyStreaming(method) || method->BidiStreaming()) { - vars["Request"] = ""; - } - vars["Response"] = "*" + method->get_output_type_name(); - if (ClientOnlyStreaming(method) || method->BidiStreaming() || - ServerOnlyStreaming(method)) { - vars["Response"] = vars["Service"] + "_" + vars["Method"] + "Client"; - } - printer->Print(vars, - "$Method$(ctx $context$.Context$Request$,\n\topts " - "...$grpc$.CallOption) ($Response$, error)$Ending$"); -} - -// Generates Client method source -static void GenerateClientMethod(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map vars) { - printer->Print(vars, "func (c *$ServiceUnexported$Client) "); - vars["Ending"] = " {\n"; - GenerateClientMethodSignature(method, printer, vars); - printer->Indent(); - vars["Method"] = exportName(method->name()); - vars["Request"] = (vars["CustomMethodIO"] == "") - ? method->get_input_type_name() - : vars["CustomMethodIO"]; - vars["Response"] = method->get_output_type_name(); - vars["FullMethodName"] = - "/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"]; - if (method->NoStreaming()) { - printer->Print(vars, "out := new($Response$)\n"); - printer->Print( - vars, - "err := c.cc.Invoke(ctx, \"$FullMethodName$\", in, out, opts...)\n"); - vars["Error_Check"] = "err != nil"; - GenerateError(printer, vars); - printer->Print("return out, nil\n"); - printer->Outdent(); - printer->Print("}\n\n"); - return; - } - vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Client"; - printer->Print(vars, - "stream, err := c.cc.NewStream(ctx, &$MethodDesc$, " - "\"$FullMethodName$\", opts...)\n"); - vars["Error_Check"] = "err != nil"; - GenerateError(printer, vars); - - printer->Print(vars, "x := &$StreamType${stream}\n"); - if (ServerOnlyStreaming(method)) { - vars["Error_Check"] = "err := x.ClientStream.SendMsg(in); err != nil"; - GenerateError(printer, vars); - vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil"; - GenerateError(printer, vars); - } - printer->Print("return x, nil\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - bool genSend = method->BidiStreaming() || ClientOnlyStreaming(method); - bool genRecv = method->BidiStreaming() || ServerOnlyStreaming(method); - bool genCloseAndRecv = ClientOnlyStreaming(method); - - // Stream interface - printer->Print(vars, "type $Service$_$Method$Client interface {\n"); - printer->Indent(); - if (genSend) { printer->Print(vars, "Send(*$Request$) error\n"); } - if (genRecv) { printer->Print(vars, "Recv() (*$Response$, error)\n"); } - if (genCloseAndRecv) { - printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n"); - } - printer->Print(vars, "$grpc$.ClientStream\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - // Stream Client - printer->Print(vars, "type $StreamType$ struct {\n"); - printer->Indent(); - printer->Print(vars, "$grpc$.ClientStream\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - if (genSend) { - printer->Print(vars, "func (x *$StreamType$) Send(m *$Request$) error {\n"); - printer->Indent(); - printer->Print("return x.ClientStream.SendMsg(m)\n"); - printer->Outdent(); - printer->Print("}\n\n"); - } - - if (genRecv) { - printer->Print(vars, - "func (x *$StreamType$) Recv() (*$Response$, error) {\n"); - printer->Indent(); - printer->Print(vars, "m := new($Response$)\n"); - vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil"; - GenerateError(printer, vars); - printer->Print("return m, nil\n"); - printer->Outdent(); - printer->Print("}\n\n"); - } - - if (genCloseAndRecv) { - printer->Print( - vars, "func (x *$StreamType$) CloseAndRecv() (*$Response$, error) {\n"); - printer->Indent(); - vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil"; - GenerateError(printer, vars); - printer->Print(vars, "m := new($Response$)\n"); - vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil"; - GenerateError(printer, vars); - printer->Print("return m, nil\n"); - printer->Outdent(); - printer->Print("}\n\n"); - } -} - -// Generates client API for the service -void GenerateService(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map vars) { - vars["Service"] = exportName(service->name()); - // Client Interface - printer->Print(vars, "// Client API for $Service$ service\n"); - printer->Print(vars, "type $Service$Client interface {\n"); - printer->Indent(); - vars["Ending"] = "\n"; - for (int i = 0; i < service->method_count(); i++) { - GenerateClientMethodSignature(service->method(i).get(), printer, vars); - } - printer->Outdent(); - printer->Print("}\n\n"); - - // Client structure - vars["ServiceUnexported"] = unexportName(vars["Service"]); - printer->Print(vars, "type $ServiceUnexported$Client struct {\n"); - printer->Indent(); - printer->Print(vars, "cc $grpc$.ClientConnInterface\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - // NewClient - printer->Print(vars, - "func New$Service$Client(cc $grpc$.ClientConnInterface) " - "$Service$Client {\n"); - printer->Indent(); - printer->Print(vars, "return &$ServiceUnexported$Client{cc}"); - printer->Outdent(); - printer->Print("\n}\n\n"); - - int unary_methods = 0, streaming_methods = 0; - vars["ServiceDesc"] = "_" + vars["Service"] + "_serviceDesc"; - for (int i = 0; i < service->method_count(); i++) { - auto method = service->method(i); - if (method->NoStreaming()) { - vars["MethodDesc"] = - vars["ServiceDesc"] + ".Method[" + as_string(unary_methods) + "]"; - unary_methods++; - } else { - vars["MethodDesc"] = vars["ServiceDesc"] + ".Streams[" + - as_string(streaming_methods) + "]"; - streaming_methods++; - } - GenerateClientMethod(method.get(), printer, vars); - } - - // Server Interface - printer->Print(vars, "// Server API for $Service$ service\n"); - printer->Print(vars, "type $Service$Server interface {\n"); - printer->Indent(); - vars["Ending"] = "\n"; - for (int i = 0; i < service->method_count(); i++) { - GenerateServerMethodSignature(service->method(i).get(), printer, vars); - } - printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - printer->Print(vars, "type Unimplemented$Service$Server struct {\n"); - printer->Print("}\n\n"); - - vars["Ending"] = " {\n"; - for (int i = 0; i < service->method_count(); i++) { - auto method = service->method(i); - vars["Method"] = exportName(method->name()); - vars["Nil"] = method->NoStreaming() ? "nil, " : ""; - printer->Print(vars, "func (Unimplemented$Service$Server) "); - GenerateServerMethodSignature(method.get(), printer, vars); - printer->Indent(); - printer->Print(vars, - "return $Nil$status.Errorf(codes.Unimplemented, \"method " - "$Method$ not implemented\")\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); - } - - printer->Print(vars, - "func (Unimplemented$Service$Server) " - "mustEmbedUnimplemented$Service$Server() {}"); - printer->Print("\n\n"); - - printer->Print(vars, "type Unsafe$Service$Server interface {\n"); - printer->Indent(); - printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n"); - printer->Outdent(); - printer->Print("}\n\n"); - // Server registration. - printer->Print(vars, - "func Register$Service$Server(s $grpc$.ServiceRegistrar, srv " - "$Service$Server) {\n"); - printer->Indent(); - printer->Print(vars, "s.RegisterService(&$ServiceDesc$, srv)\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - for (int i = 0; i < service->method_count(); i++) { - GenerateServerMethod(service->method(i).get(), printer, vars); - } - - // Service Descriptor - printer->Print(vars, "var $ServiceDesc$ = $grpc$.ServiceDesc{\n"); - printer->Indent(); - printer->Print(vars, "ServiceName: \"$ServicePrefix$$Service$\",\n"); - printer->Print(vars, "HandlerType: (*$Service$Server)(nil),\n"); - printer->Print(vars, "Methods: []$grpc$.MethodDesc{\n"); - printer->Indent(); - for (int i = 0; i < service->method_count(); i++) { - auto method = service->method(i); - vars["Method"] = exportName(method->name()); - vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler"; - if (method->NoStreaming()) { - printer->Print("{\n"); - printer->Indent(); - printer->Print(vars, "MethodName: \"$Method$\",\n"); - printer->Print(vars, "Handler: $Handler$,\n"); - printer->Outdent(); - printer->Print("},\n"); - } - } - printer->Outdent(); - printer->Print("},\n"); - printer->Print(vars, "Streams: []$grpc$.StreamDesc{\n"); - printer->Indent(); - for (int i = 0; i < service->method_count(); i++) { - auto method = service->method(i); - vars["Method"] = exportName(method->name()); - vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler"; - if (!method->NoStreaming()) { - printer->Print("{\n"); - printer->Indent(); - printer->Print(vars, "StreamName: \"$Method$\",\n"); - printer->Print(vars, "Handler: $Handler$,\n"); - if (ClientOnlyStreaming(method.get())) { - printer->Print("ClientStreams: true,\n"); - } else if (ServerOnlyStreaming(method.get())) { - printer->Print("ServerStreams: true,\n"); - } else { - printer->Print("ServerStreams: true,\n"); - printer->Print("ClientStreams: true,\n"); - } - printer->Outdent(); - printer->Print("},\n"); - } - } - printer->Outdent(); - printer->Print("},\n"); - printer->Outdent(); - printer->Print("}\n"); -} -} // namespace - -// Returns source for the service -grpc::string GenerateServiceSource(grpc_generator::File *file, - const grpc_generator::Service *service, - grpc_go_generator::Parameters *parameters) { - grpc::string out; - auto p = file->CreatePrinter(&out, '\t'); - p->SetIndentationSize(1); - auto printer = p.get(); - std::map vars; - vars["Package"] = parameters->package_name; - vars["ServicePrefix"] = parameters->service_prefix; - if (!parameters->service_prefix.empty()) vars["ServicePrefix"].append("."); - vars["grpc"] = "grpc"; - vars["context"] = "context"; - GenerateImports(file, printer, vars); - if (parameters->custom_method_io_type != "") { - vars["CustomMethodIO"] = parameters->custom_method_io_type; - } - GenerateService(service, printer, vars); - return out; -} -} // Namespace grpc_go_generator diff --git a/third_party/flatbuffers/grpc/src/compiler/go_generator.h b/third_party/flatbuffers/grpc/src/compiler/go_generator.h deleted file mode 100644 index 766e100c584..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/go_generator.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef GRPC_INTERNAL_COMPILER_GO_GENERATOR_H -#define GRPC_INTERNAL_COMPILER_GO_GENERATOR_H - -// go generator is used to generate GRPC code for serialization system, such as -// flatbuffers -#include -#include - -#include "src/compiler/schema_interface.h" - -namespace grpc_go_generator { - -struct Parameters { - // Defines the custom parameter types for methods - // eg: flatbuffers uses flatbuffers.Builder as input for the client and output - // for the server - grpc::string custom_method_io_type; - - // Package name for the service - grpc::string package_name; - - // Prefix for RPC Calls - grpc::string service_prefix; -}; - -// Return the source of the generated service file. -grpc::string GenerateServiceSource(grpc_generator::File *file, - const grpc_generator::Service *service, - grpc_go_generator::Parameters *parameters); - -} // namespace grpc_go_generator - -#endif // GRPC_INTERNAL_COMPILER_GO_GENERATOR_H diff --git a/third_party/flatbuffers/grpc/src/compiler/java_generator.cc b/third_party/flatbuffers/grpc/src/compiler/java_generator.cc deleted file mode 100644 index bfe2b111dbb..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/java_generator.cc +++ /dev/null @@ -1,1123 +0,0 @@ -/* - * Copyright 2016 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. - */ - -#include "src/compiler/java_generator.h" - -#include -#include -#include -#include -#include -#include - -#include "flatbuffers/util.h" -#define to_string flatbuffers::NumToString - -// Stringify helpers used solely to cast GRPC_VERSION -#ifndef STR -# define STR(s) # s -#endif - -#ifndef XSTR -# define XSTR(s) STR(s) -#endif - -typedef grpc_generator::Printer Printer; -typedef std::map VARS; -typedef grpc_generator::Service ServiceDescriptor; -typedef grpc_generator::CommentHolder - DescriptorType; // base class of all 'descriptors' -typedef grpc_generator::Method MethodDescriptor; - -namespace grpc_java_generator { -typedef std::string string; -namespace { -// Generates imports for the service -static void GenerateImports(grpc_generator::File *file, - grpc_generator::Printer *printer, VARS &vars) { - vars["filename"] = file->filename(); - printer->Print(vars, - "//Generated by flatc compiler (version $flatc_version$)\n"); - printer->Print("//If you make any local changes, they will be lost\n"); - printer->Print(vars, "//source: $filename$.fbs\n\n"); - printer->Print(vars, "package $Package$;\n\n"); - vars["Package"] = vars["Package"] + "."; - if (!file->additional_headers().empty()) { - printer->Print(file->additional_headers().c_str()); - printer->Print("\n\n"); - } -} - -// Adjust a method name prefix identifier to follow the JavaBean spec: -// - decapitalize the first letter -// - remove embedded underscores & capitalize the following letter -static string MixedLower(const string &word) { - string w; - w += static_cast(tolower(word[0])); - bool after_underscore = false; - for (size_t i = 1; i < word.length(); ++i) { - if (word[i] == '_') { - after_underscore = true; - } else { - w += after_underscore ? static_cast(toupper(word[i])) - : word[i]; - after_underscore = false; - } - } - return w; -} - -// Converts to the identifier to the ALL_UPPER_CASE format. -// - An underscore is inserted where a lower case letter is followed by an -// upper case letter. -// - All letters are converted to upper case -static string ToAllUpperCase(const string &word) { - string w; - for (size_t i = 0; i < word.length(); ++i) { - w += static_cast(toupper(word[i])); - if ((i < word.length() - 1) && islower(word[i]) && isupper(word[i + 1])) { - w += '_'; - } - } - return w; -} - -static inline string LowerMethodName(const MethodDescriptor *method) { - return MixedLower(method->name()); -} - -static inline string MethodPropertiesFieldName(const MethodDescriptor *method) { - return "METHOD_" + ToAllUpperCase(method->name()); -} - -static inline string MethodPropertiesGetterName( - const MethodDescriptor *method) { - return MixedLower("get_" + method->name() + "_method"); -} - -static inline string MethodIdFieldName(const MethodDescriptor *method) { - return "METHODID_" + ToAllUpperCase(method->name()); -} - -static inline string JavaClassName(VARS &vars, const string &name) { - // string name = google::protobuf::compiler::java::ClassName(desc); - return vars["Package"] + name; -} - -static inline string ServiceClassName(const string &service_name) { - return service_name + "Grpc"; -} - -// TODO(nmittler): Remove once protobuf includes javadoc methods in -// distribution. -template -static void GrpcSplitStringToIteratorUsing(const string &full, - const char *delim, ITR &result) { - // Optimize the common case where delim is a single character. - if (delim[0] != '\0' && delim[1] == '\0') { - char c = delim[0]; - const char *p = full.data(); - const char *end = p + full.size(); - while (p != end) { - if (*p == c) { - ++p; - } else { - const char *start = p; - while (++p != end && *p != c) - ; - *result++ = string(start, p - start); - } - } - return; - } - - string::size_type begin_index, end_index; - begin_index = full.find_first_not_of(delim); - while (begin_index != string::npos) { - end_index = full.find_first_of(delim, begin_index); - if (end_index == string::npos) { - *result++ = full.substr(begin_index); - return; - } - *result++ = full.substr(begin_index, (end_index - begin_index)); - begin_index = full.find_first_not_of(delim, end_index); - } -} - -static void GrpcSplitStringUsing(const string &full, const char *delim, - std::vector *result) { - std::back_insert_iterator> it(*result); - GrpcSplitStringToIteratorUsing(full, delim, it); -} - -static std::vector GrpcSplit(const string &full, const char *delim) { - std::vector result; - GrpcSplitStringUsing(full, delim, &result); - return result; -} - -// TODO(nmittler): Remove once protobuf includes javadoc methods in -// distribution. -static string GrpcEscapeJavadoc(const string &input) { - string result; - result.reserve(input.size() * 2); - - char prev = '*'; - - for (string::size_type i = 0; i < input.size(); i++) { - char c = input[i]; - switch (c) { - case '*': - // Avoid "/*". - if (prev == '/') { - result.append("*"); - } else { - result.push_back(c); - } - break; - case '/': - // Avoid "*/". - if (prev == '*') { - result.append("/"); - } else { - result.push_back(c); - } - break; - case '@': - // '@' starts javadoc tags including the @deprecated tag, which will - // cause a compile-time error if inserted before a declaration that - // does not have a corresponding @Deprecated annotation. - result.append("@"); - break; - case '<': - // Avoid interpretation as HTML. - result.append("<"); - break; - case '>': - // Avoid interpretation as HTML. - result.append(">"); - break; - case '&': - // Avoid interpretation as HTML. - result.append("&"); - break; - case '\\': - // Java interprets Unicode escape sequences anywhere! - result.append("\"); - break; - default: result.push_back(c); break; - } - - prev = c; - } - - return result; -} - -static std::vector GrpcGetDocLines(const string &comments) { - if (!comments.empty()) { - // TODO(kenton): Ideally we should parse the comment text as Markdown and - // write it back as HTML, but this requires a Markdown parser. For now - // we just use
 to get fixed-width text formatting.
-
-    // If the comment itself contains block comment start or end markers,
-    // HTML-escape them so that they don't accidentally close the doc comment.
-    string escapedComments = GrpcEscapeJavadoc(comments);
-
-    std::vector lines = GrpcSplit(escapedComments, "\n");
-    while (!lines.empty() && lines.back().empty()) { lines.pop_back(); }
-    return lines;
-  }
-  return std::vector();
-}
-
-static std::vector GrpcGetDocLinesForDescriptor(
-    const DescriptorType *descriptor) {
-  return descriptor->GetAllComments();
-  // return GrpcGetDocLines(descriptor->GetLeadingComments("///"));
-}
-
-static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
-                                    const std::vector &lines,
-                                    bool surroundWithPreTag) {
-  if (!lines.empty()) {
-    if (surroundWithPreTag) { printer->Print(" * 
\n"); }
-
-    for (size_t i = 0; i < lines.size(); i++) {
-      // Most lines should start with a space.  Watch out for lines that start
-      // with a /, since putting that right after the leading asterisk will
-      // close the comment.
-      vars["line"] = lines[i];
-      if (!lines[i].empty() && lines[i][0] == '/') {
-        printer->Print(vars, " * $line$\n");
-      } else {
-        printer->Print(vars, " *$line$\n");
-      }
-    }
-
-    if (surroundWithPreTag) { printer->Print(" * 
\n"); } - } -} - -static void GrpcWriteDocComment(Printer *printer, VARS &vars, - const string &comments) { - printer->Print("/**\n"); - std::vector lines = GrpcGetDocLines(comments); - GrpcWriteDocCommentBody(printer, vars, lines, false); - printer->Print(" */\n"); -} - -static void GrpcWriteServiceDocComment(Printer *printer, VARS &vars, - const ServiceDescriptor *service) { - printer->Print("/**\n"); - std::vector lines = GrpcGetDocLinesForDescriptor(service); - GrpcWriteDocCommentBody(printer, vars, lines, true); - printer->Print(" */\n"); -} - -static void GrpcWriteMethodDocComment(Printer *printer, VARS &vars, - const MethodDescriptor *method) { - printer->Print("/**\n"); - std::vector lines = GrpcGetDocLinesForDescriptor(method); - GrpcWriteDocCommentBody(printer, vars, lines, true); - printer->Print(" */\n"); -} - -// outputs static singleton extractor for type stored in "extr_type" and -// "extr_type_name" vars -static void PrintTypeExtractor(Printer *p, VARS &vars) { - p->Print(vars, - "private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> " - "extractorOf$extr_type_name$;\n" - "private static FlatbuffersUtils.FBExtactor<$extr_type$> " - "getExtractorOf$extr_type_name$() {\n" - " if (extractorOf$extr_type_name$ != null) return " - "extractorOf$extr_type_name$;\n" - " synchronized ($service_class_name$.class) {\n" - " if (extractorOf$extr_type_name$ != null) return " - "extractorOf$extr_type_name$;\n" - " extractorOf$extr_type_name$ = new " - "FlatbuffersUtils.FBExtactor<$extr_type$>() {\n" - " public $extr_type$ extract (ByteBuffer buffer) {\n" - " return " - "$extr_type$.getRootAs$extr_type_name$(buffer);\n" - " }\n" - " };\n" - " return extractorOf$extr_type_name$;\n" - " }\n" - "}\n\n"); -} -static void PrintMethodFields(Printer *p, VARS &vars, - const ServiceDescriptor *service) { - p->Print("// Static method descriptors that strictly reflect the proto.\n"); - vars["service_name"] = service->name(); - - // set of names of rpc input- and output- types that were already encountered. - // this is needed to avoid duplicating type extractor since it's possible that - // the same type is used as an input or output type of more than a single RPC - // method - std::set encounteredTypes; - - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - vars["arg_in_id"] = to_string(2L * i); // trying to make msvc 10 happy - vars["arg_out_id"] = to_string(2L * i + 1); - vars["method_name"] = method->name(); - vars["input_type_name"] = method->get_input_type_name(); - vars["output_type_name"] = method->get_output_type_name(); - vars["input_type"] = JavaClassName(vars, method->get_input_type_name()); - vars["output_type"] = JavaClassName(vars, method->get_output_type_name()); - vars["method_field_name"] = MethodPropertiesFieldName(method.get()); - vars["method_new_field_name"] = MethodPropertiesGetterName(method.get()); - vars["method_method_name"] = MethodPropertiesGetterName(method.get()); - bool client_streaming = - method->ClientStreaming() || method->BidiStreaming(); - bool server_streaming = - method->ServerStreaming() || method->BidiStreaming(); - if (client_streaming) { - if (server_streaming) { - vars["method_type"] = "BIDI_STREAMING"; - } else { - vars["method_type"] = "CLIENT_STREAMING"; - } - } else { - if (server_streaming) { - vars["method_type"] = "SERVER_STREAMING"; - } else { - vars["method_type"] = "UNARY"; - } - } - - p->Print( - vars, - "@$ExperimentalApi$(\"https://github.com/grpc/grpc-java/issues/" - "1901\")\n" - "@$Deprecated$ // Use {@link #$method_method_name$()} instead. \n" - "public static final $MethodDescriptor$<$input_type$,\n" - " $output_type$> $method_field_name$ = $method_method_name$();\n" - "\n" - "private static volatile $MethodDescriptor$<$input_type$,\n" - " $output_type$> $method_new_field_name$;\n" - "\n"); - - if (encounteredTypes.insert(vars["input_type_name"]).second) { - vars["extr_type"] = vars["input_type"]; - vars["extr_type_name"] = vars["input_type_name"]; - PrintTypeExtractor(p, vars); - } - - if (encounteredTypes.insert(vars["output_type_name"]).second) { - vars["extr_type"] = vars["output_type"]; - vars["extr_type_name"] = vars["output_type_name"]; - PrintTypeExtractor(p, vars); - } - - p->Print( - vars, - "@$ExperimentalApi$(\"https://github.com/grpc/grpc-java/issues/" - "1901\")\n" - "public static $MethodDescriptor$<$input_type$,\n" - " $output_type$> $method_method_name$() {\n" - " $MethodDescriptor$<$input_type$, $output_type$> " - "$method_new_field_name$;\n" - " if (($method_new_field_name$ = " - "$service_class_name$.$method_new_field_name$) == null) {\n" - " synchronized ($service_class_name$.class) {\n" - " if (($method_new_field_name$ = " - "$service_class_name$.$method_new_field_name$) == null) {\n" - " $service_class_name$.$method_new_field_name$ = " - "$method_new_field_name$ = \n" - " $MethodDescriptor$.<$input_type$, " - "$output_type$>newBuilder()\n" - " .setType($MethodType$.$method_type$)\n" - " .setFullMethodName(generateFullMethodName(\n" - " \"$Package$$service_name$\", \"$method_name$\"))\n" - " .setSampledToLocalTracing(true)\n" - " .setRequestMarshaller(FlatbuffersUtils.marshaller(\n" - " $input_type$.class, " - "getExtractorOf$input_type_name$()))\n" - " .setResponseMarshaller(FlatbuffersUtils.marshaller(\n" - " $output_type$.class, " - "getExtractorOf$output_type_name$()))\n"); - - // vars["proto_method_descriptor_supplier"] = service->name() + - // "MethodDescriptorSupplier"; - p->Print(vars, " .setSchemaDescriptor(null)\n"); - //" .setSchemaDescriptor(new - //$proto_method_descriptor_supplier$(\"$method_name$\"))\n"); - - p->Print(vars, " .build();\n"); - p->Print(vars, - " }\n" - " }\n" - " }\n" - " return $method_new_field_name$;\n" - "}\n"); - - p->Print("\n"); - } -} -enum StubType { - ASYNC_INTERFACE = 0, - BLOCKING_CLIENT_INTERFACE = 1, - FUTURE_CLIENT_INTERFACE = 2, - BLOCKING_SERVER_INTERFACE = 3, - ASYNC_CLIENT_IMPL = 4, - BLOCKING_CLIENT_IMPL = 5, - FUTURE_CLIENT_IMPL = 6, - ABSTRACT_CLASS = 7, -}; - -enum CallType { ASYNC_CALL = 0, BLOCKING_CALL = 1, FUTURE_CALL = 2 }; - -static void PrintBindServiceMethodBody(Printer *p, VARS &vars, - const ServiceDescriptor *service); - -// Prints a client interface or implementation class, or a server interface. -static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service, - StubType type) { - const string service_name = service->name(); - vars["service_name"] = service_name; - vars["abstract_name"] = service_name + "ImplBase"; - string stub_name = service_name; - string client_name = service_name; - CallType call_type = ASYNC_CALL; - bool impl_base = false; - bool interface = false; - switch (type) { - case ABSTRACT_CLASS: - call_type = ASYNC_CALL; - impl_base = true; - break; - case ASYNC_CLIENT_IMPL: - call_type = ASYNC_CALL; - stub_name += "Stub"; - break; - case BLOCKING_CLIENT_INTERFACE: - interface = true; - FLATBUFFERS_FALLTHROUGH(); // fall thru - case BLOCKING_CLIENT_IMPL: - call_type = BLOCKING_CALL; - stub_name += "BlockingStub"; - client_name += "BlockingClient"; - break; - case FUTURE_CLIENT_INTERFACE: - interface = true; - FLATBUFFERS_FALLTHROUGH(); // fall thru - case FUTURE_CLIENT_IMPL: - call_type = FUTURE_CALL; - stub_name += "FutureStub"; - client_name += "FutureClient"; - break; - case ASYNC_INTERFACE: - call_type = ASYNC_CALL; - interface = true; - break; - default: - GRPC_CODEGEN_FAIL << "Cannot determine class name for StubType: " << type; - } - vars["stub_name"] = stub_name; - vars["client_name"] = client_name; - - // Class head - if (!interface) { GrpcWriteServiceDocComment(p, vars, service); } - if (impl_base) { - p->Print(vars, - "public static abstract class $abstract_name$ implements " - "$BindableService$ {\n"); - } else { - p->Print(vars, - "public static final class $stub_name$ extends " - "$AbstractStub$<$stub_name$> {\n"); - } - p->Indent(); - - // Constructor and build() method - if (!impl_base && !interface) { - p->Print(vars, "private $stub_name$($Channel$ channel) {\n"); - p->Indent(); - p->Print("super(channel);\n"); - p->Outdent(); - p->Print("}\n\n"); - p->Print(vars, - "private $stub_name$($Channel$ channel,\n" - " $CallOptions$ callOptions) {\n"); - p->Indent(); - p->Print("super(channel, callOptions);\n"); - p->Outdent(); - p->Print("}\n\n"); - p->Print(vars, - "@$Override$\n" - "protected $stub_name$ build($Channel$ channel,\n" - " $CallOptions$ callOptions) {\n"); - p->Indent(); - p->Print(vars, "return new $stub_name$(channel, callOptions);\n"); - p->Outdent(); - p->Print("}\n"); - } - - // RPC methods - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - vars["input_type"] = JavaClassName(vars, method->get_input_type_name()); - vars["output_type"] = JavaClassName(vars, method->get_output_type_name()); - vars["lower_method_name"] = LowerMethodName(&*method); - vars["method_method_name"] = MethodPropertiesGetterName(&*method); - bool client_streaming = - method->ClientStreaming() || method->BidiStreaming(); - bool server_streaming = - method->ServerStreaming() || method->BidiStreaming(); - - if (call_type == BLOCKING_CALL && client_streaming) { - // Blocking client interface with client streaming is not available - continue; - } - - if (call_type == FUTURE_CALL && (client_streaming || server_streaming)) { - // Future interface doesn't support streaming. - continue; - } - - // Method signature - p->Print("\n"); - // TODO(nmittler): Replace with WriteMethodDocComment once included by the - // protobuf distro. - if (!interface) { GrpcWriteMethodDocComment(p, vars, &*method); } - p->Print("public "); - switch (call_type) { - case BLOCKING_CALL: - GRPC_CODEGEN_CHECK(!client_streaming) - << "Blocking client interface with client streaming is unavailable"; - if (server_streaming) { - // Server streaming - p->Print(vars, - "$Iterator$<$output_type$> $lower_method_name$(\n" - " $input_type$ request)"); - } else { - // Simple RPC - p->Print(vars, - "$output_type$ $lower_method_name$($input_type$ request)"); - } - break; - case ASYNC_CALL: - if (client_streaming) { - // Bidirectional streaming or client streaming - p->Print(vars, - "$StreamObserver$<$input_type$> $lower_method_name$(\n" - " $StreamObserver$<$output_type$> responseObserver)"); - } else { - // Server streaming or simple RPC - p->Print(vars, - "void $lower_method_name$($input_type$ request,\n" - " $StreamObserver$<$output_type$> responseObserver)"); - } - break; - case FUTURE_CALL: - GRPC_CODEGEN_CHECK(!client_streaming && !server_streaming) - << "Future interface doesn't support streaming. " - << "client_streaming=" << client_streaming << ", " - << "server_streaming=" << server_streaming; - p->Print(vars, - "$ListenableFuture$<$output_type$> $lower_method_name$(\n" - " $input_type$ request)"); - break; - } - - if (interface) { - p->Print(";\n"); - continue; - } - // Method body. - p->Print(" {\n"); - p->Indent(); - if (impl_base) { - switch (call_type) { - // NB: Skipping validation of service methods. If something is wrong, - // we wouldn't get to this point as compiler would return errors when - // generating service interface. - case ASYNC_CALL: - if (client_streaming) { - p->Print(vars, - "return " - "asyncUnimplementedStreamingCall($method_method_name$(), " - "responseObserver);\n"); - } else { - p->Print(vars, - "asyncUnimplementedUnaryCall($method_method_name$(), " - "responseObserver);\n"); - } - break; - default: break; - } - } else if (!interface) { - switch (call_type) { - case BLOCKING_CALL: - GRPC_CODEGEN_CHECK(!client_streaming) - << "Blocking client streaming interface is not available"; - if (server_streaming) { - vars["calls_method"] = "blockingServerStreamingCall"; - vars["params"] = "request"; - } else { - vars["calls_method"] = "blockingUnaryCall"; - vars["params"] = "request"; - } - p->Print(vars, - "return $calls_method$(\n" - " getChannel(), $method_method_name$(), " - "getCallOptions(), $params$);\n"); - break; - case ASYNC_CALL: - if (server_streaming) { - if (client_streaming) { - vars["calls_method"] = "asyncBidiStreamingCall"; - vars["params"] = "responseObserver"; - } else { - vars["calls_method"] = "asyncServerStreamingCall"; - vars["params"] = "request, responseObserver"; - } - } else { - if (client_streaming) { - vars["calls_method"] = "asyncClientStreamingCall"; - vars["params"] = "responseObserver"; - } else { - vars["calls_method"] = "asyncUnaryCall"; - vars["params"] = "request, responseObserver"; - } - } - vars["last_line_prefix"] = client_streaming ? "return " : ""; - p->Print(vars, - "$last_line_prefix$$calls_method$(\n" - " getChannel().newCall($method_method_name$(), " - "getCallOptions()), $params$);\n"); - break; - case FUTURE_CALL: - GRPC_CODEGEN_CHECK(!client_streaming && !server_streaming) - << "Future interface doesn't support streaming. " - << "client_streaming=" << client_streaming << ", " - << "server_streaming=" << server_streaming; - vars["calls_method"] = "futureUnaryCall"; - p->Print(vars, - "return $calls_method$(\n" - " getChannel().newCall($method_method_name$(), " - "getCallOptions()), request);\n"); - break; - } - } - p->Outdent(); - p->Print("}\n"); - } - - if (impl_base) { - p->Print("\n"); - p->Print( - vars, - "@$Override$ public final $ServerServiceDefinition$ bindService() {\n"); - vars["instance"] = "this"; - PrintBindServiceMethodBody(p, vars, service); - p->Print("}\n"); - } - - p->Outdent(); - p->Print("}\n\n"); -} - -static bool CompareMethodClientStreaming( - const std::unique_ptr &method1, - const std::unique_ptr &method2) { - return method1->ClientStreaming() < method2->ClientStreaming(); -} - -// Place all method invocations into a single class to reduce memory footprint -// on Android. -static void PrintMethodHandlerClass(Printer *p, VARS &vars, - const ServiceDescriptor *service) { - // Sort method ids based on ClientStreaming() so switch tables are compact. - std::vector> sorted_methods( - service->method_count()); - for (int i = 0; i < service->method_count(); ++i) { - sorted_methods[i] = service->method(i); - } - stable_sort(sorted_methods.begin(), sorted_methods.end(), - CompareMethodClientStreaming); - for (size_t i = 0; i < sorted_methods.size(); i++) { - auto &method = sorted_methods[i]; - vars["method_id"] = to_string(i); - vars["method_id_name"] = MethodIdFieldName(&*method); - p->Print(vars, - "private static final int $method_id_name$ = $method_id$;\n"); - } - p->Print("\n"); - vars["service_name"] = service->name() + "ImplBase"; - p->Print(vars, - "private static final class MethodHandlers implements\n" - " io.grpc.stub.ServerCalls.UnaryMethod,\n" - " io.grpc.stub.ServerCalls.ServerStreamingMethod,\n" - " io.grpc.stub.ServerCalls.ClientStreamingMethod,\n" - " io.grpc.stub.ServerCalls.BidiStreamingMethod {\n" - " private final $service_name$ serviceImpl;\n" - " private final int methodId;\n" - "\n" - " MethodHandlers($service_name$ serviceImpl, int methodId) {\n" - " this.serviceImpl = serviceImpl;\n" - " this.methodId = methodId;\n" - " }\n\n"); - p->Indent(); - p->Print(vars, - "@$Override$\n" - "@java.lang.SuppressWarnings(\"unchecked\")\n" - "public void invoke(Req request, $StreamObserver$ " - "responseObserver) {\n" - " switch (methodId) {\n"); - p->Indent(); - p->Indent(); - - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - if (method->ClientStreaming() || method->BidiStreaming()) { continue; } - vars["method_id_name"] = MethodIdFieldName(&*method); - vars["lower_method_name"] = LowerMethodName(&*method); - vars["input_type"] = JavaClassName(vars, method->get_input_type_name()); - vars["output_type"] = JavaClassName(vars, method->get_output_type_name()); - p->Print(vars, - "case $method_id_name$:\n" - " serviceImpl.$lower_method_name$(($input_type$) request,\n" - " ($StreamObserver$<$output_type$>) responseObserver);\n" - " break;\n"); - } - p->Print( - "default:\n" - " throw new AssertionError();\n"); - - p->Outdent(); - p->Outdent(); - p->Print( - " }\n" - "}\n\n"); - - p->Print(vars, - "@$Override$\n" - "@java.lang.SuppressWarnings(\"unchecked\")\n" - "public $StreamObserver$ invoke(\n" - " $StreamObserver$ responseObserver) {\n" - " switch (methodId) {\n"); - p->Indent(); - p->Indent(); - - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - if (!(method->ClientStreaming() || method->BidiStreaming())) { continue; } - vars["method_id_name"] = MethodIdFieldName(&*method); - vars["lower_method_name"] = LowerMethodName(&*method); - vars["input_type"] = JavaClassName(vars, method->get_input_type_name()); - vars["output_type"] = JavaClassName(vars, method->get_output_type_name()); - p->Print( - vars, - "case $method_id_name$:\n" - " return ($StreamObserver$) serviceImpl.$lower_method_name$(\n" - " ($StreamObserver$<$output_type$>) responseObserver);\n"); - } - p->Print( - "default:\n" - " throw new AssertionError();\n"); - - p->Outdent(); - p->Outdent(); - p->Print( - " }\n" - "}\n"); - - p->Outdent(); - p->Print("}\n\n"); -} - -static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars, - const ServiceDescriptor *service) { - vars["service_name"] = service->name(); - // vars["proto_base_descriptor_supplier"] = service->name() + - // "BaseDescriptorSupplier"; vars["proto_file_descriptor_supplier"] = - // service->name() + "FileDescriptorSupplier"; - // vars["proto_method_descriptor_supplier"] = service->name() + - // "MethodDescriptorSupplier"; vars["proto_class_name"] = - // google::protobuf::compiler::java::ClassName(service->file()); - // p->Print( - // vars, - // "private static abstract class - // $proto_base_descriptor_supplier$\n" " implements - // $ProtoFileDescriptorSupplier$, - // $ProtoServiceDescriptorSupplier$ {\n" " - // $proto_base_descriptor_supplier$() {}\n" - // "\n" - // " @$Override$\n" - // " public com.google.protobuf.Descriptors.FileDescriptor - // getFileDescriptor() {\n" " return - // $proto_class_name$.getDescriptor();\n" " }\n" - // "\n" - // " @$Override$\n" - // " public com.google.protobuf.Descriptors.ServiceDescriptor - // getServiceDescriptor() {\n" " return - // getFileDescriptor().findServiceByName(\"$service_name$\");\n" - // " }\n" - // "}\n" - // "\n" - // "private static final class - // $proto_file_descriptor_supplier$\n" " extends - // $proto_base_descriptor_supplier$ {\n" " - // $proto_file_descriptor_supplier$() {}\n" - // "}\n" - // "\n" - // "private static final class - // $proto_method_descriptor_supplier$\n" " extends - // $proto_base_descriptor_supplier$\n" " implements - // $ProtoMethodDescriptorSupplier$ {\n" " private final - // String methodName;\n" - // "\n" - // " $proto_method_descriptor_supplier$(String methodName) - // {\n" " this.methodName = methodName;\n" " }\n" - // "\n" - // " @$Override$\n" - // " public com.google.protobuf.Descriptors.MethodDescriptor - // getMethodDescriptor() {\n" " return - // getServiceDescriptor().findMethodByName(methodName);\n" " - // }\n" - // "}\n\n"); - - p->Print( - vars, - "private static volatile $ServiceDescriptor$ serviceDescriptor;\n\n"); - - p->Print(vars, - "public static $ServiceDescriptor$ getServiceDescriptor() {\n"); - p->Indent(); - p->Print(vars, "$ServiceDescriptor$ result = serviceDescriptor;\n"); - p->Print("if (result == null) {\n"); - p->Indent(); - p->Print(vars, "synchronized ($service_class_name$.class) {\n"); - p->Indent(); - p->Print("result = serviceDescriptor;\n"); - p->Print("if (result == null) {\n"); - p->Indent(); - - p->Print(vars, - "serviceDescriptor = result = " - "$ServiceDescriptor$.newBuilder(SERVICE_NAME)"); - p->Indent(); - p->Indent(); - p->Print(vars, "\n.setSchemaDescriptor(null)"); - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - vars["method_method_name"] = MethodPropertiesGetterName(&*method); - p->Print(vars, "\n.addMethod($method_method_name$())"); - } - p->Print("\n.build();\n"); - p->Outdent(); - p->Outdent(); - - p->Outdent(); - p->Print("}\n"); - p->Outdent(); - p->Print("}\n"); - p->Outdent(); - p->Print("}\n"); - p->Print("return result;\n"); - p->Outdent(); - p->Print("}\n"); -} - -static void PrintBindServiceMethodBody(Printer *p, VARS &vars, - const ServiceDescriptor *service) { - vars["service_name"] = service->name(); - p->Indent(); - p->Print(vars, - "return " - "$ServerServiceDefinition$.builder(getServiceDescriptor())\n"); - p->Indent(); - p->Indent(); - for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - vars["lower_method_name"] = LowerMethodName(&*method); - vars["method_method_name"] = MethodPropertiesGetterName(&*method); - vars["input_type"] = JavaClassName(vars, method->get_input_type_name()); - vars["output_type"] = JavaClassName(vars, method->get_output_type_name()); - vars["method_id_name"] = MethodIdFieldName(&*method); - bool client_streaming = - method->ClientStreaming() || method->BidiStreaming(); - bool server_streaming = - method->ServerStreaming() || method->BidiStreaming(); - if (client_streaming) { - if (server_streaming) { - vars["calls_method"] = "asyncBidiStreamingCall"; - } else { - vars["calls_method"] = "asyncClientStreamingCall"; - } - } else { - if (server_streaming) { - vars["calls_method"] = "asyncServerStreamingCall"; - } else { - vars["calls_method"] = "asyncUnaryCall"; - } - } - p->Print(vars, ".addMethod(\n"); - p->Indent(); - p->Print(vars, - "$method_method_name$(),\n" - "$calls_method$(\n"); - p->Indent(); - p->Print(vars, - "new MethodHandlers<\n" - " $input_type$,\n" - " $output_type$>(\n" - " $instance$, $method_id_name$)))\n"); - p->Outdent(); - p->Outdent(); - } - p->Print(".build();\n"); - p->Outdent(); - p->Outdent(); - p->Outdent(); -} - -static void PrintService(Printer *p, VARS &vars, - const ServiceDescriptor *service, - bool disable_version) { - vars["service_name"] = service->name(); - vars["service_class_name"] = ServiceClassName(service->name()); - vars["grpc_version"] = ""; -#ifdef GRPC_VERSION - if (!disable_version) { - vars["grpc_version"] = " (version " XSTR(GRPC_VERSION) ")"; - } -#else - (void)disable_version; -#endif - // TODO(nmittler): Replace with WriteServiceDocComment once included by - // protobuf distro. - GrpcWriteServiceDocComment(p, vars, service); - p->Print(vars, - "@$Generated$(\n" - " value = \"by gRPC proto compiler$grpc_version$\",\n" - " comments = \"Source: $file_name$.fbs\")\n" - "public final class $service_class_name$ {\n\n"); - p->Indent(); - p->Print(vars, "private $service_class_name$() {}\n\n"); - - p->Print(vars, - "public static final String SERVICE_NAME = " - "\"$Package$$service_name$\";\n\n"); - - PrintMethodFields(p, vars, service); - - // TODO(nmittler): Replace with WriteDocComment once included by protobuf - // distro. - GrpcWriteDocComment( - p, vars, - " Creates a new async stub that supports all call types for the service"); - p->Print(vars, - "public static $service_name$Stub newStub($Channel$ channel) {\n"); - p->Indent(); - p->Print(vars, "return new $service_name$Stub(channel);\n"); - p->Outdent(); - p->Print("}\n\n"); - - // TODO(nmittler): Replace with WriteDocComment once included by protobuf - // distro. - GrpcWriteDocComment( - p, vars, - " Creates a new blocking-style stub that supports unary and streaming " - "output calls on the service"); - p->Print(vars, - "public static $service_name$BlockingStub newBlockingStub(\n" - " $Channel$ channel) {\n"); - p->Indent(); - p->Print(vars, "return new $service_name$BlockingStub(channel);\n"); - p->Outdent(); - p->Print("}\n\n"); - - // TODO(nmittler): Replace with WriteDocComment once included by protobuf - // distro. - GrpcWriteDocComment( - p, vars, - " Creates a new ListenableFuture-style stub that supports unary calls " - "on the service"); - p->Print(vars, - "public static $service_name$FutureStub newFutureStub(\n" - " $Channel$ channel) {\n"); - p->Indent(); - p->Print(vars, "return new $service_name$FutureStub(channel);\n"); - p->Outdent(); - p->Print("}\n\n"); - - PrintStub(p, vars, service, ABSTRACT_CLASS); - PrintStub(p, vars, service, ASYNC_CLIENT_IMPL); - PrintStub(p, vars, service, BLOCKING_CLIENT_IMPL); - PrintStub(p, vars, service, FUTURE_CLIENT_IMPL); - - PrintMethodHandlerClass(p, vars, service); - PrintGetServiceDescriptorMethod(p, vars, service); - p->Outdent(); - p->Print("}\n"); -} - -static void PrintStaticImports(Printer *p) { - p->Print( - "import java.nio.ByteBuffer;\n" - "import static " - "io.grpc.MethodDescriptor.generateFullMethodName;\n" - "import static " - "io.grpc.stub.ClientCalls.asyncBidiStreamingCall;\n" - "import static " - "io.grpc.stub.ClientCalls.asyncClientStreamingCall;\n" - "import static " - "io.grpc.stub.ClientCalls.asyncServerStreamingCall;\n" - "import static " - "io.grpc.stub.ClientCalls.asyncUnaryCall;\n" - "import static " - "io.grpc.stub.ClientCalls.blockingServerStreamingCall;\n" - "import static " - "io.grpc.stub.ClientCalls.blockingUnaryCall;\n" - "import static " - "io.grpc.stub.ClientCalls.futureUnaryCall;\n" - "import static " - "io.grpc.stub.ServerCalls.asyncBidiStreamingCall;\n" - "import static " - "io.grpc.stub.ServerCalls.asyncClientStreamingCall;\n" - "import static " - "io.grpc.stub.ServerCalls.asyncServerStreamingCall;\n" - "import static " - "io.grpc.stub.ServerCalls.asyncUnaryCall;\n" - "import static " - "io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;\n" - "import static " - "io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;\n\n"); -} - -static void GenerateService(const grpc_generator::Service *service, - grpc_generator::Printer *printer, VARS &vars, - bool disable_version) { - // All non-generated classes must be referred by fully qualified names to - // avoid collision with generated classes. - vars["String"] = "java.lang.String"; - vars["Deprecated"] = "java.lang.Deprecated"; - vars["Override"] = "java.lang.Override"; - vars["Channel"] = "io.grpc.Channel"; - vars["CallOptions"] = "io.grpc.CallOptions"; - vars["MethodType"] = "io.grpc.MethodDescriptor.MethodType"; - vars["ServerMethodDefinition"] = "io.grpc.ServerMethodDefinition"; - vars["BindableService"] = "io.grpc.BindableService"; - vars["ServerServiceDefinition"] = "io.grpc.ServerServiceDefinition"; - vars["ServiceDescriptor"] = "io.grpc.ServiceDescriptor"; - vars["ProtoFileDescriptorSupplier"] = - "io.grpc.protobuf.ProtoFileDescriptorSupplier"; - vars["ProtoServiceDescriptorSupplier"] = - "io.grpc.protobuf.ProtoServiceDescriptorSupplier"; - vars["ProtoMethodDescriptorSupplier"] = - "io.grpc.protobuf.ProtoMethodDescriptorSupplier"; - vars["AbstractStub"] = "io.grpc.stub.AbstractStub"; - vars["MethodDescriptor"] = "io.grpc.MethodDescriptor"; - vars["NanoUtils"] = "io.grpc.protobuf.nano.NanoUtils"; - vars["StreamObserver"] = "io.grpc.stub.StreamObserver"; - vars["Iterator"] = "java.util.Iterator"; - vars["Generated"] = "javax.annotation.Generated"; - vars["ListenableFuture"] = - "com.google.common.util.concurrent.ListenableFuture"; - vars["ExperimentalApi"] = "io.grpc.ExperimentalApi"; - - PrintStaticImports(printer); - - PrintService(printer, vars, service, disable_version); -} -} // namespace - -grpc::string GenerateServiceSource( - grpc_generator::File *file, const grpc_generator::Service *service, - grpc_java_generator::Parameters *parameters) { - grpc::string out; - auto printer = file->CreatePrinter(&out); - VARS vars; - vars["flatc_version"] = grpc::string( - FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "." FLATBUFFERS_STRING( - FLATBUFFERS_VERSION_MINOR) "." FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION)); - - vars["file_name"] = file->filename(); - - if (!parameters->package_name.empty()) { - vars["Package"] = parameters->package_name; // ServiceJavaPackage(service); - } - GenerateImports(file, &*printer, vars); - GenerateService(service, &*printer, vars, false); - return out; -} - -} // namespace grpc_java_generator diff --git a/third_party/flatbuffers/grpc/src/compiler/java_generator.h b/third_party/flatbuffers/grpc/src/compiler/java_generator.h deleted file mode 100644 index b101fbf565e..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/java_generator.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2016 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 NET_GRPC_COMPILER_JAVA_GENERATOR_H_ -#define NET_GRPC_COMPILER_JAVA_GENERATOR_H_ - -#include // for abort() -#include -#include -#include - -#include "src/compiler/schema_interface.h" - -class LogMessageVoidify { - public: - LogMessageVoidify() {} - // This has to be an operator with a precedence lower than << but - // higher than ?: - void operator&(std::ostream&) {} -}; - -class LogHelper { - std::ostream* os_; - - public: - LogHelper(std::ostream* os) : os_(os) {} -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning( \ - disable : 4722) // the flow of control terminates in a destructor - // (needed to compile ~LogHelper where destructor emits abort intentionally - - // inherited from grpc/java code generator). -#endif - ~LogHelper() { - *os_ << std::endl; - ::abort(); - } -#if defined(_MSC_VER) -#pragma warning(pop) -#endif - std::ostream& get_os() const { return *os_; } -}; - -// Abort the program after logging the mesage if the given condition is not -// true. Otherwise, do nothing. -#define GRPC_CODEGEN_CHECK(x) \ - (x) ? (void)0 \ - : LogMessageVoidify() & LogHelper(&std::cerr).get_os() \ - << "CHECK FAILED: " << __FILE__ << ":" \ - << __LINE__ << ": " - -// Abort the program after logging the mesage. -#define GRPC_CODEGEN_FAIL GRPC_CODEGEN_CHECK(false) - -namespace grpc_java_generator { -struct Parameters { - // //Defines the custom parameter types for methods - // //eg: flatbuffers uses flatbuffers.Builder as input for the client - // and output for the server grpc::string custom_method_io_type; - - // Package name for the service - grpc::string package_name; -}; - -// Return the source of the generated service file. -grpc::string GenerateServiceSource(grpc_generator::File* file, - const grpc_generator::Service* service, - grpc_java_generator::Parameters* parameters); - -} // namespace grpc_java_generator - -#endif // NET_GRPC_COMPILER_JAVA_GENERATOR_H_ diff --git a/third_party/flatbuffers/grpc/src/compiler/python_generator.cc b/third_party/flatbuffers/grpc/src/compiler/python_generator.cc deleted file mode 100644 index d5f69e20e71..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/python_generator.cc +++ /dev/null @@ -1,151 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * 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. - * - */ - -#include -#include - -#include "flatbuffers/util.h" -#include "src/compiler/python_generator.h" - -namespace grpc_python_generator { -namespace { - -static grpc::string GenerateMethodType(const grpc_generator::Method *method) { - - if (method->NoStreaming()) - return "unary_unary"; - - if (method->ServerStreaming()) - return "unary_stream"; - - if (method->ClientStreaming()) - return "stream_unary"; - - return "stream_stream"; -} - -grpc::string GenerateMethodInput(const grpc_generator::Method *method) { - - if (method->NoStreaming() || method->ServerStreaming()) - return "self, request, context"; - - return "self, request_iterator, context"; -} - -void GenerateStub(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "class $ServiceName$Stub(object):\n"); - printer->Indent(); - printer->Print("\"\"\" Interface exported by the server. \"\"\""); - printer->Print("\n\n"); - printer->Print("def __init__(self, channel):\n"); - printer->Indent(); - printer->Print("\"\"\" Constructor. \n\n"); - printer->Print("Args: \n"); - printer->Print("channel: A grpc.Channel. \n"); - printer->Print("\"\"\"\n\n"); - - for (int j = 0; j < service->method_count(); j++) { - auto method = service->method(j); - vars["MethodName"] = method->name(); - vars["MethodType"] = GenerateMethodType(&*method); - printer->Print(vars, "self.$MethodName$ = channel.$MethodType$(\n"); - printer->Indent(); - printer->Print(vars, "\"/$PATH$$ServiceName$/$MethodName$\"\n"); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("\n"); - } - printer->Outdent(); - printer->Outdent(); - printer->Print("\n"); -} - -void GenerateServicer(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "class $ServiceName$Servicer(object):\n"); - printer->Indent(); - printer->Print("\"\"\" Interface exported by the server. \"\"\""); - printer->Print("\n\n"); - - for (int j = 0; j < service->method_count(); j++) { - auto method = service->method(j); - vars["MethodName"] = method->name(); - vars["MethodInput"] = GenerateMethodInput(&*method); - printer->Print(vars, "def $MethodName$($MethodInput$):\n"); - printer->Indent(); - printer->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n"); - printer->Print("context.set_details('Method not implemented!')\n"); - printer->Print("raise NotImplementedError('Method not implemented!')\n"); - printer->Outdent(); - printer->Print("\n\n"); - } - printer->Outdent(); - printer->Print("\n"); - -} - -void GenerateRegister(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "def add_$ServiceName$Servicer_to_server(servicer, server):\n"); - printer->Indent(); - printer->Print("rpc_method_handlers = {\n"); - printer->Indent(); - for (int j = 0; j < service->method_count(); j++) { - auto method = service->method(j); - vars["MethodName"] = method->name(); - vars["MethodType"] = GenerateMethodType(&*method); - printer->Print(vars, "'$MethodName$': grpc.$MethodType$_rpc_method_handler(\n"); - printer->Indent(); - printer->Print(vars, "servicer.$MethodName$\n"); - printer->Outdent(); - printer->Print("),\n"); - } - printer->Outdent(); - printer->Print("}\n"); - printer->Print(vars, "generic_handler = grpc.method_handlers_generic_handler(\n"); - printer->Indent(); - printer->Print(vars, "'$PATH$$ServiceName$', rpc_method_handlers)\n"); - printer->Outdent(); - printer->Print("server.add_generic_rpc_handlers((generic_handler,))"); - printer->Outdent(); - printer->Print("\n"); -} -} // namespace - -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service) { - grpc::string output; - std::map vars; - vars["PATH"] = file->package(); - if (!file->package().empty()) { vars["PATH"].append("."); } - vars["ServiceName"] = service->name(); - auto printer = file->CreatePrinter(&output); - GenerateStub(service, &*printer, &vars); - GenerateServicer(service, &*printer, &vars); - GenerateRegister(service, &*printer, &vars); - return output; -} - -} // namespace grpc_python_generator diff --git a/third_party/flatbuffers/grpc/src/compiler/python_generator.h b/third_party/flatbuffers/grpc/src/compiler/python_generator.h deleted file mode 100644 index 40d29aada55..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/python_generator.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * 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 GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H -#define GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H - -#include - -#include "src/compiler/schema_interface.h" - -namespace grpc_python_generator { - -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service); -} // namespace grpc_python_generator - -#endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H diff --git a/third_party/flatbuffers/grpc/src/compiler/schema_interface.h b/third_party/flatbuffers/grpc/src/compiler/schema_interface.h deleted file mode 100644 index f89288d7560..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/schema_interface.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * 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 GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H -#define GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H - -#include -#include -#include - -#ifndef GRPC_CUSTOM_STRING -# include -# define GRPC_CUSTOM_STRING std::string -#endif - -namespace grpc { - -typedef GRPC_CUSTOM_STRING string; - -} // namespace grpc - -namespace grpc_generator { - -// A common interface for objects having comments in the source. -// Return formatted comments to be inserted in generated code. -struct CommentHolder { - virtual ~CommentHolder() {} - virtual grpc::string GetLeadingComments(const grpc::string prefix) const = 0; - virtual grpc::string GetTrailingComments(const grpc::string prefix) const = 0; - virtual std::vector GetAllComments() const = 0; -}; - -// An abstract interface representing a method. -struct Method : public CommentHolder { - virtual ~Method() {} - - virtual grpc::string name() const = 0; - - virtual grpc::string input_type_name() const = 0; - virtual grpc::string output_type_name() const = 0; - - virtual bool get_module_and_message_path_input( - grpc::string *str, grpc::string generator_file_name, - bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0; - virtual bool get_module_and_message_path_output( - grpc::string *str, grpc::string generator_file_name, - bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0; - - virtual std::vector get_input_namespace_parts() const = 0; - virtual grpc::string get_input_type_name() const = 0; - virtual std::vector get_output_namespace_parts() const = 0; - virtual grpc::string get_output_type_name() const = 0; - - virtual grpc::string get_fb_builder() const = 0; - - virtual bool NoStreaming() const = 0; - virtual bool ClientStreaming() const = 0; - virtual bool ServerStreaming() const = 0; - virtual bool BidiStreaming() const = 0; -}; - -// An abstract interface representing a service. -struct Service : public CommentHolder { - virtual ~Service() {} - - virtual std::vector namespace_parts() const = 0; - virtual grpc::string name() const = 0; - virtual bool is_internal() const = 0; - - virtual int method_count() const = 0; - virtual std::unique_ptr method(int i) const = 0; -}; - -struct Printer { - virtual ~Printer() {} - - virtual void Print(const std::map &vars, - const char *template_string) = 0; - virtual void Print(const char *string) = 0; - virtual void SetIndentationSize(const size_t size) = 0; - virtual void Indent() = 0; - virtual void Outdent() = 0; -}; - -// An interface that allows the source generated to be output using various -// libraries/idls/serializers. -struct File : public CommentHolder { - virtual ~File() {} - - virtual grpc::string filename() const = 0; - virtual grpc::string filename_without_ext() const = 0; - virtual grpc::string package() const = 0; - virtual std::vector package_parts() const = 0; - virtual grpc::string additional_headers() const = 0; - - virtual int service_count() const = 0; - virtual std::unique_ptr service(int i) const = 0; - - virtual std::unique_ptr CreatePrinter( - grpc::string *str, const char indentation_type = ' ') const = 0; -}; -} // namespace grpc_generator - -#endif // GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H diff --git a/third_party/flatbuffers/grpc/src/compiler/swift_generator.cc b/third_party/flatbuffers/grpc/src/compiler/swift_generator.cc deleted file mode 100644 index b0a96d869ac..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/swift_generator.cc +++ /dev/null @@ -1,440 +0,0 @@ -/* - * Copyright 2020 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. - */ - -/* - * NOTE: The following implementation is a translation for the Swift-grpc - * generator since flatbuffers doesnt allow plugins for now. if an issue arises - * please open an issue in the flatbuffers repository. This file should always - * be maintained according to the Swift-grpc repository - */ -#include -#include - -#include "flatbuffers/util.h" -#include "src/compiler/schema_interface.h" -#include "src/compiler/swift_generator.h" - -namespace grpc_swift_generator { -namespace { - -static std::string WrapInNameSpace(const std::vector &components, - const grpc::string &name) { - std::string qualified_name; - for (auto it = components.begin(); it != components.end(); ++it) - qualified_name += *it + "_"; - return qualified_name + name; -} - -static grpc::string GenerateMessage(const std::vector &components, - const grpc::string &name) { - return "Message<" + WrapInNameSpace(components, name) + ">"; -} - -// MARK: - Client - -static void GenerateClientFuncName(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - if (method->NoStreaming()) { - printer->Print(vars, - " $GenAccess$func $MethodName$(\n" - " _ request: $Input$\n" - " , callOptions: CallOptions?$isNil$\n" - " ) -> UnaryCall<$Input$, $Output$>"); - return; - } - - if (method->ServerStreaming()) { - printer->Print(vars, - " $GenAccess$func $MethodName$(\n" - " _ request: $Input$\n" - " , callOptions: CallOptions?$isNil$,\n" - " handler: @escaping ($Output$) -> Void\n" - " ) -> ServerStreamingCall<$Input$, $Output$>"); - return; - } - - if (method->ClientStreaming()) { - printer->Print(vars, - " $GenAccess$func $MethodName$(\n" - " callOptions: CallOptions?$isNil$\n" - " ) -> ClientStreamingCall<$Input$, $Output$>"); - return; - } - - printer->Print(vars, - " $GenAccess$func $MethodName$(\n" - " callOptions: CallOptions?$isNil$,\n" - " handler: @escaping ($Output$ ) -> Void\n" - " ) -> BidirectionalStreamingCall<$Input$, $Output$>"); -} - -static void GenerateClientFuncBody(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - vars["Interceptor"] = - "interceptors: self.interceptors?.make$MethodName$Interceptors() ?? []"; - if (method->NoStreaming()) { - printer->Print( - vars, - " return self.makeUnaryCall(\n" - " path: \"/$PATH$$ServiceName$/$MethodName$\",\n" - " request: request,\n" - " callOptions: callOptions ?? self.defaultCallOptions,\n" - " $Interceptor$\n" - " )\n"); - return; - } - - if (method->ServerStreaming()) { - printer->Print( - vars, - " return self.makeServerStreamingCall(\n" - " path: \"/$PATH$$ServiceName$/$MethodName$\",\n" - " request: request,\n" - " callOptions: callOptions ?? self.defaultCallOptions,\n" - " $Interceptor$,\n" - " handler: handler\n" - " )\n"); - return; - } - - if (method->ClientStreaming()) { - printer->Print( - vars, - " return self.makeClientStreamingCall(\n" - " path: \"/$PATH$$ServiceName$/$MethodName$\",\n" - " callOptions: callOptions ?? self.defaultCallOptions,\n" - " $Interceptor$\n" - " )\n"); - return; - } - printer->Print(vars, - " return self.makeBidirectionalStreamingCall(\n" - " path: \"/$PATH$$ServiceName$/$MethodName$\",\n" - " callOptions: callOptions ?? self.defaultCallOptions,\n" - " $Interceptor$,\n" - " handler: handler\n" - " )\n"); -} - -void GenerateClientProtocol(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print( - vars, - "$ACCESS$ protocol $ServiceQualifiedName$ClientProtocol: GRPCClient {"); - printer->Print("\n\n"); - printer->Print(" var serviceName: String { get }"); - printer->Print("\n\n"); - printer->Print( - vars, - " var interceptors: " - "$ServiceQualifiedName$ClientInterceptorFactoryProtocol? { get }"); - printer->Print("\n\n"); - - vars["GenAccess"] = ""; - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), - method->get_input_type_name()); - vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), - method->get_output_type_name()); - vars["MethodName"] = method->name(); - vars["isNil"] = ""; - GenerateClientFuncName(method.get(), &*printer, &vars); - printer->Print("\n\n"); - } - printer->Print("}\n\n"); - - printer->Print(vars, "extension $ServiceQualifiedName$ClientProtocol {"); - printer->Print("\n\n"); - printer->Print(vars, - " $ACCESS$ var serviceName: String { " - "\"$PATH$$ServiceName$\" }\n"); - - vars["GenAccess"] = service->is_internal() ? "internal " : "public "; - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), - method->get_input_type_name()); - vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), - method->get_output_type_name()); - vars["MethodName"] = method->name(); - vars["isNil"] = " = nil"; - printer->Print("\n"); - GenerateClientFuncName(method.get(), &*printer, &vars); - printer->Print(" {\n"); - GenerateClientFuncBody(method.get(), &*printer, &vars); - printer->Print(" }\n"); - } - printer->Print("}\n\n"); - - printer->Print(vars, - "$ACCESS$ protocol " - "$ServiceQualifiedName$ClientInterceptorFactoryProtocol {\n"); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), - method->get_input_type_name()); - vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), - method->get_output_type_name()); - vars["MethodName"] = method->name(); - printer->Print( - vars, - " /// - Returns: Interceptors to use when invoking '$MethodName$'.\n"); - printer->Print(vars, - " func make$MethodName$Interceptors() -> " - "[ClientInterceptor<$Input$, $Output$>]\n\n"); - } - printer->Print("}\n\n"); -} - -void GenerateClientClass(grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, - "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: " - "$ServiceQualifiedName$ClientProtocol {\n"); - printer->Print(vars, " $ACCESS$ let channel: GRPCChannel\n"); - printer->Print(vars, " $ACCESS$ var defaultCallOptions: CallOptions\n"); - printer->Print(vars, - " $ACCESS$ var interceptors: " - "$ServiceQualifiedName$ClientInterceptorFactoryProtocol?\n"); - printer->Print("\n"); - printer->Print( - vars, - " $ACCESS$ init(\n" - " channel: GRPCChannel,\n" - " defaultCallOptions: CallOptions = CallOptions(),\n" - " interceptors: " - "$ServiceQualifiedName$ClientInterceptorFactoryProtocol? = nil\n" - " ) {\n"); - printer->Print(" self.channel = channel\n"); - printer->Print(" self.defaultCallOptions = defaultCallOptions\n"); - printer->Print(" self.interceptors = interceptors\n"); - printer->Print(" }"); - printer->Print("\n"); - printer->Print("}\n"); -} - -// MARK: - Server - -grpc::string GenerateServerFuncName(const grpc_generator::Method *method) { - if (method->NoStreaming()) { - return "func $MethodName$(request: $Input$" - ", context: StatusOnlyCallContext) -> EventLoopFuture<$Output$>"; - } - - if (method->ClientStreaming()) { - return "func $MethodName$(context: UnaryResponseCallContext<$Output$>) -> " - "EventLoopFuture<(StreamEvent<$Input$" - ">) -> Void>"; - } - - if (method->ServerStreaming()) { - return "func $MethodName$(request: $Input$" - ", context: StreamingResponseCallContext<$Output$>) -> " - "EventLoopFuture"; - } - return "func $MethodName$(context: StreamingResponseCallContext<$Output$>) " - "-> EventLoopFuture<(StreamEvent<$Input$>) -> Void>"; -} - -grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) { - grpc::string start = " case \"$MethodName$\":\n "; - grpc::string interceptors = - " interceptors: self.interceptors?.make$MethodName$Interceptors() " - "?? [],\n"; - if (method->NoStreaming()) { - return start + - "return UnaryServerHandler(\n" - " context: context,\n" - " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n" - " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" + - interceptors + - " userFunction: self.$MethodName$(request:context:))\n"; - } - if (method->ServerStreaming()) { - return start + - "return ServerStreamingServerHandler(\n" - " context: context,\n" - " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n" - " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" + - interceptors + - " userFunction: self.$MethodName$(request:context:))\n"; - } - if (method->ClientStreaming()) { - return start + - "return ClientStreamingServerHandler(\n" - " context: context,\n" - " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n" - " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" + - interceptors + - " observerFactory: self.$MethodName$(context:))\n"; - } - if (method->BidiStreaming()) { - return start + - "return BidirectionalStreamingServerHandler(\n" - " context: context,\n" - " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n" - " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" + - interceptors + - " observerFactory: self.$MethodName$(context:))\n"; - } - return ""; -} - -void GenerateServerProtocol(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, - "$ACCESS$ protocol $ServiceQualifiedName$Provider: " - "CallHandlerProvider {\n"); - printer->Print( - vars, - " var interceptors: " - "$ServiceQualifiedName$ServerInterceptorFactoryProtocol? { get }\n"); - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), - method->get_input_type_name()); - vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), - method->get_output_type_name()); - vars["MethodName"] = method->name(); - printer->Print(" "); - auto func = GenerateServerFuncName(method.get()); - printer->Print(vars, func.c_str()); - printer->Print("\n"); - } - printer->Print("}\n\n"); - - printer->Print(vars, "$ACCESS$ extension $ServiceQualifiedName$Provider {\n"); - printer->Print("\n"); - printer->Print(vars, - " var serviceName: Substring { return " - "\"$PATH$$ServiceName$\" }\n"); - printer->Print("\n"); - printer->Print( - " func handle(method name: Substring, context: " - "CallHandlerContext) -> GRPCServerHandlerProtocol? {\n"); - printer->Print(" switch name {\n"); - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), - method->get_input_type_name()); - vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), - method->get_output_type_name()); - vars["MethodName"] = method->name(); - auto body = GenerateServerExtensionBody(method.get()); - printer->Print(vars, body.c_str()); - printer->Print("\n"); - } - printer->Print(" default: return nil;\n"); - printer->Print(" }\n"); - printer->Print(" }\n\n"); - printer->Print("}\n\n"); - - printer->Print(vars, - "$ACCESS$ protocol " - "$ServiceQualifiedName$ServerInterceptorFactoryProtocol {\n"); - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), - method->get_input_type_name()); - vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), - method->get_output_type_name()); - vars["MethodName"] = method->name(); - printer->Print( - vars, - " /// - Returns: Interceptors to use when handling '$MethodName$'.\n" - " /// Defaults to calling `self.makeInterceptors()`.\n"); - printer->Print(vars, - " func make$MethodName$Interceptors() -> " - "[ServerInterceptor<$Input$, $Output$>]\n\n"); - } - printer->Print("}"); -} -} // namespace - -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service) { - grpc::string output; - std::map vars; - vars["PATH"] = file->package(); - if (!file->package().empty()) { vars["PATH"].append("."); } - vars["ServiceQualifiedName"] = - WrapInNameSpace(service->namespace_parts(), service->name()); - vars["ServiceName"] = service->name(); - vars["ACCESS"] = service->is_internal() ? "internal" : "public"; - auto printer = file->CreatePrinter(&output); - printer->Print( - vars, - "/// Usage: instantiate $ServiceQualifiedName$ServiceClient, then call " - "methods of this protocol to make API calls.\n"); - GenerateClientProtocol(service, &*printer, &vars); - GenerateClientClass(&*printer, &vars); - printer->Print("\n"); - GenerateServerProtocol(service, &*printer, &vars); - return output; -} - -grpc::string GenerateHeader() { - grpc::string code; - code += - "/// The following code is generated by the Flatbuffers library which " - "might not be in sync with grpc-swift\n"; - code += - "/// in case of an issue please open github issue, though it would be " - "maintained\n"; - code += "\n"; - code += "// swiftlint:disable all\n"; - code += "// swiftformat:disable all\n"; - code += "\n"; - code += "import Foundation\n"; - code += "import GRPC\n"; - code += "import NIO\n"; - code += "import NIOHTTP1\n"; - code += "import FlatBuffers\n"; - code += "\n"; - code += - "public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage " - "{}\n"; - - code += "public extension GRPCFlatBufPayload {\n"; - code += " init(serializedByteBuffer: inout NIO.ByteBuffer) throws {\n"; - code += - " self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: " - "serializedByteBuffer.readableBytesView, count: " - "serializedByteBuffer.readableBytes))\n"; - code += " }\n"; - - code += " func serialize(into buffer: inout NIO.ByteBuffer) throws {\n"; - code += - " let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: " - "Int(self.size))\n"; - code += " buffer.writeBytes(buf)\n"; - code += " }\n"; - code += "}\n"; - code += "extension Message: GRPCFlatBufPayload {}\n"; - return code; -} -} // namespace grpc_swift_generator diff --git a/third_party/flatbuffers/grpc/src/compiler/swift_generator.h b/third_party/flatbuffers/grpc/src/compiler/swift_generator.h deleted file mode 100644 index 2a226fa9409..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/swift_generator.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2020 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. - */ - -#include -#include - -#include "src/compiler/schema_interface.h" - -#ifndef GRPC_CUSTOM_STRING -# include -# define GRPC_CUSTOM_STRING std::string -#endif - -namespace grpc { - -typedef GRPC_CUSTOM_STRING string; - -} // namespace grpc - -namespace grpc_swift_generator { -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service); -grpc::string GenerateHeader(); -} // namespace grpc_swift_generator diff --git a/third_party/flatbuffers/grpc/src/compiler/ts_generator.cc b/third_party/flatbuffers/grpc/src/compiler/ts_generator.cc deleted file mode 100644 index ff362b774a1..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/ts_generator.cc +++ /dev/null @@ -1,523 +0,0 @@ -/* - * Copyright 2020 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. - */ - -/* - * NOTE: The following implementation is a translation for the Swift-grpc - * generator since flatbuffers doesnt allow plugins for now. if an issue arises - * please open an issue in the flatbuffers repository. This file should always - * be maintained according to the Swift-grpc repository - */ - -#include "src/compiler/ts_generator.h" - -#include -#include - -#include "flatbuffers/util.h" -#include "src/compiler/schema_interface.h" - -namespace grpc_ts_generator { -namespace { - -static grpc::string GenerateNamespace(const std::vector ns, - const std::string filename, - const bool include_separator) { - grpc::string path = ""; - if (include_separator) path += "."; - - for (auto it = ns.begin(); it < ns.end(); it++) { - if (include_separator) path += "/"; - path += include_separator - ? flatbuffers::ConvertCase(*it, flatbuffers::Case::kDasher, - flatbuffers::Case::kUpperCamel) - : *it + "_"; - } - - if (include_separator) path += "/"; - path += include_separator - ? flatbuffers::ConvertCase(filename, flatbuffers::Case::kDasher, - flatbuffers::Case::kUpperCamel) - : filename; - return path; -} - -// MARK: - Shared code - -static void GenerateImports(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary, - const bool grpc_var_import) { - auto vars = *dictonary; - printer->Print( - "// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***\n"); - printer->Print("import * as flatbuffers from 'flatbuffers';\n"); - - std::set generated_imports; - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - auto output = method->get_output_type_name(); - auto input = method->get_input_type_name(); - auto input_namespace = method->get_input_namespace_parts(); - - vars["OUTPUT"] = output; - vars["INPUT"] = input; - - if (generated_imports.find(output) == generated_imports.end()) { - generated_imports.insert(output); - vars["OUTPUT_DIR"] = - GenerateNamespace(method->get_output_namespace_parts(), output, true); - vars["Output_alias"] = GenerateNamespace( - method->get_output_namespace_parts(), output, false); - printer->Print( - vars, "import { $OUTPUT$ as $Output_alias$ } from '$OUTPUT_DIR$';\n"); - } - if (generated_imports.find(input) == generated_imports.end()) { - generated_imports.insert(input); - vars["INPUT_DIR"] = - GenerateNamespace(method->get_output_namespace_parts(), input, true); - vars["Input_alias"] = - GenerateNamespace(method->get_output_namespace_parts(), input, false); - printer->Print( - vars, "import { $INPUT$ as $Input_alias$ } from '$INPUT_DIR$';\n"); - } - } - printer->Print("\n"); - if (grpc_var_import) - printer->Print("var grpc = require('@grpc/grpc-js');\n"); - else - printer->Print("import * as grpc from '@grpc/grpc-js';\n"); - printer->Print("\n"); -} - -// MARK: - Generate Main GRPC Code - -static void GetStreamType(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *dictonary) { - auto vars = *dictonary; - auto client_streaming = method->ClientStreaming() || method->BidiStreaming(); - auto server_streaming = method->ServerStreaming() || method->BidiStreaming(); - vars["ClientStreaming"] = client_streaming ? "true" : "false"; - vars["ServerStreaming"] = server_streaming ? "true" : "false"; - printer->Print(vars, "requestStream: $ClientStreaming$,\n"); - printer->Print(vars, "responseStream: $ServerStreaming$,\n"); -} - -static void GenerateSerializeMethod(grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "function serialize_$Type$(buffer_args) {\n"); - printer->Indent(); - printer->Print(vars, "if (!(buffer_args instanceof $Type$)) {\n"); - printer->Indent(); - printer->Print(vars, - "throw new Error('Expected argument of type $VALUE$');\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Print(vars, "return Buffer.from(buffer_args.serialize());\n"); - printer->Outdent(); - printer->Print("}\n\n"); -} - -static void GenerateDeserializeMethod( - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "function deserialize_$Type$(buffer) {\n"); - printer->Indent(); - printer->Print(vars, - "return $Type$.getRootAs$VALUE$(new " - "flatbuffers.ByteBuffer(buffer))\n"); - printer->Outdent(); - printer->Print("}\n\n"); -} - -static void GenerateMethods(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - - std::set generated_functions; - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - auto output = method->get_output_type_name(); - auto input = method->get_input_type_name(); - - if (generated_functions.find(output) == generated_functions.end()) { - generated_functions.insert(output); - vars["VALUE"] = output; - vars["Type"] = GenerateNamespace(method->get_output_namespace_parts(), - output, false); - GenerateSerializeMethod(printer, &vars); - GenerateDeserializeMethod(printer, &vars); - } - printer->Print("\n"); - if (generated_functions.find(input) == generated_functions.end()) { - generated_functions.insert(input); - vars["VALUE"] = input; - vars["Type"] = - GenerateNamespace(method->get_input_namespace_parts(), input, false); - GenerateSerializeMethod(printer, &vars); - GenerateDeserializeMethod(printer, &vars); - } - } -} - -static void GenerateService(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - vars["NAME"] = service->name() + "Service"; - - printer->Print(vars, "var $NAME$ = exports.$NAME$ = {\n"); - printer->Indent(); - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["MethodName"] = method->name(); - vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(), - method->get_output_type_name(), false); - vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(), - method->get_input_type_name(), false); - printer->Print(vars, "$MethodName$: {\n"); - printer->Indent(); - printer->Print(vars, "path: '/$PATH$$ServiceName$/$MethodName$',\n"); - GetStreamType(printer, &*method, &vars); - printer->Print(vars, "requestType: flatbuffers.ByteBuffer,\n"); - printer->Print(vars, "responseType: $OUTPUT$,\n"); - printer->Print(vars, "requestSerialize: serialize_$INPUT$,\n"); - printer->Print(vars, "requestDeserialize: deserialize_$INPUT$,\n"); - printer->Print(vars, "responseSerialize: serialize_$OUTPUT$,\n"); - printer->Print(vars, "responseDeserialize: deserialize_$OUTPUT$,\n"); - printer->Outdent(); - printer->Print("},\n"); - } - printer->Outdent(); - printer->Print("};\n"); - printer->Print(vars, - "exports.$ServiceName$Client = " - "grpc.makeGenericClientConstructor($NAME$);"); -} - -} // namespace - -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service, - const grpc::string &filename) { - grpc::string output; - std::map vars; - - vars["PATH"] = file->package(); - - if (!file->package().empty()) { vars["PATH"].append("."); } - - vars["ServiceName"] = service->name(); - vars["FBSFile"] = service->name() + "_fbs"; - vars["Filename"] = filename; - auto printer = file->CreatePrinter(&output); - - GenerateImports(service, &*printer, &vars, true); - GenerateMethods(service, &*printer, &vars); - GenerateService(service, &*printer, &vars); - return output; -} - -namespace { - -// MARK: - Generate Interface - -static void FillInterface(grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, - "interface I$ServiceName$Service_I$MethodName$ extends " - "grpc.MethodDefinition<$INPUT$, $OUTPUT$> {\n"); - printer->Indent(); - printer->Print(vars, "path: string; // /$PATH$$ServiceName$/$MethodName$\n"); - printer->Print(vars, "requestStream: boolean; // $ClientStreaming$\n"); - printer->Print(vars, "responseStream: boolean; // $ServerStreaming$\n"); - printer->Print(vars, "requestSerialize: grpc.serialize<$INPUT$>;\n"); - printer->Print(vars, "requestDeserialize: grpc.deserialize<$INPUT$>;\n"); - printer->Print(vars, "responseSerialize: grpc.serialize<$OUTPUT$>;\n"); - printer->Print(vars, "responseDeserialize: grpc.deserialize<$OUTPUT$>;\n"); - printer->Outdent(); - printer->Print("}\n"); -} - -static void GenerateInterfaces(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - auto client_streaming = - method->ClientStreaming() || method->BidiStreaming(); - auto server_streaming = - method->ServerStreaming() || method->BidiStreaming(); - vars["ClientStreaming"] = client_streaming ? "true" : "false"; - vars["ServerStreaming"] = server_streaming ? "true" : "false"; - vars["MethodName"] = method->name(); - vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(), - method->get_output_type_name(), false); - vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(), - method->get_input_type_name(), false); - FillInterface(printer, &vars); - printer->Print("\n"); - } -} - -static void GenerateExportedInterface( - const grpc_generator::Service *service, grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, - "export interface I$ServiceName$Server extends " - "grpc.UntypedServiceImplementation {\n"); - printer->Indent(); - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Name"] = method->name(); - vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(), - method->get_output_type_name(), false); - vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(), - method->get_input_type_name(), false); - if (method->BidiStreaming()) { - printer->Print(vars, - "$Name$: grpc.handleBidiStreamingCall<$INPUT$, " - "$OUTPUT$>;\n"); - continue; - } - if (method->NoStreaming()) { - printer->Print(vars, - "$Name$: grpc.handleUnaryCall<$INPUT$, " - "$OUTPUT$>;\n"); - continue; - } - if (method->ClientStreaming()) { - printer->Print(vars, - "$Name$: grpc.handleClientStreamingCall<$INPUT$, " - "$OUTPUT$>;\n"); - continue; - } - if (method->ServerStreaming()) { - printer->Print(vars, - "$Name$: grpc.handleServerStreamingCall<$INPUT$, " - "$OUTPUT$>;\n"); - continue; - } - } - printer->Outdent(); - printer->Print("}\n"); -} - -static void GenerateMainInterface(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print( - vars, - "interface I$ServiceName$Service extends " - "grpc.ServiceDefinition {\n"); - printer->Indent(); - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["MethodName"] = method->name(); - printer->Print(vars, - "$MethodName$: I$ServiceName$Service_I$MethodName$;\n"); - } - printer->Outdent(); - printer->Print("}\n"); - GenerateInterfaces(service, printer, &vars); - printer->Print("\n"); - printer->Print(vars, - "export const $ServiceName$Service: I$ServiceName$Service;\n"); - printer->Print("\n"); - GenerateExportedInterface(service, printer, &vars); -} - -static grpc::string GenerateMetaData() { return "metadata: grpc.Metadata"; } - -static grpc::string GenerateOptions() { return "options: Partial"; } - -static void GenerateUnaryClientInterface( - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, "; - grpc::string callback = - "callback: (error: grpc.ServiceError | null, response: " - "$OUTPUT$) => void): grpc.ClientUnaryCall;\n"; - auto meta_data = GenerateMetaData() + ", "; - auto options = GenerateOptions() + ", "; - printer->Print(vars, (main + callback).c_str()); - printer->Print(vars, (main + meta_data + callback).c_str()); - printer->Print(vars, (main + meta_data + options + callback).c_str()); -} - -static void GenerateClientWriteStreamInterface( - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - grpc::string main = "$ISPUBLIC$$MethodName$("; - grpc::string callback = - "callback: (error: grpc.ServiceError | null, response: " - "$INPUT$) => void): " - "grpc.ClientWritableStream<$OUTPUT$>;\n"; - auto meta_data = GenerateMetaData() + ", "; - auto options = GenerateOptions() + ", "; - printer->Print(vars, (main + callback).c_str()); - printer->Print(vars, (main + meta_data + callback).c_str()); - printer->Print(vars, (main + options + callback).c_str()); - printer->Print(vars, (main + meta_data + options + callback).c_str()); -} - -static void GenerateClientReadableStreamInterface( - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, "; - grpc::string end_function = "): grpc.ClientReadableStream<$OUTPUT$>;\n"; - auto meta_data = GenerateMetaData(); - auto options = GenerateOptions(); - printer->Print(vars, (main + meta_data + end_function).c_str()); - printer->Print(vars, (main + options + end_function).c_str()); -} - -static void GenerateDepluxStreamInterface( - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - grpc::string main = "$ISPUBLIC$$MethodName$("; - grpc::string end_function = - "): grpc.ClientDuplexStream<$INPUT$, $OUTPUT$>;\n"; - auto meta_data = GenerateMetaData(); - auto options = GenerateOptions(); - printer->Print(vars, (main + end_function).c_str()); - printer->Print(vars, (main + options + end_function).c_str()); - printer->Print(vars, (main + meta_data + - ", options?: Partial" + end_function) - .c_str()); -} - -static void GenerateClientInterface(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "export interface I$ServiceName$Client {\n"); - printer->Indent(); - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["MethodName"] = method->name(); - vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(), - method->get_output_type_name(), false); - vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(), - method->get_input_type_name(), false); - vars["ISPUBLIC"] = ""; - - if (method->NoStreaming()) { - GenerateUnaryClientInterface(printer, &vars); - continue; - } - if (method->BidiStreaming()) { - GenerateDepluxStreamInterface(printer, &vars); - continue; - } - - if (method->ClientStreaming()) { - GenerateClientWriteStreamInterface(printer, &vars); - continue; - } - - if (method->ServerStreaming()) { - GenerateClientReadableStreamInterface(printer, &vars); - continue; - } - } - printer->Outdent(); - printer->Print("}\n"); -} - -static void GenerateClientClassInterface( - const grpc_generator::Service *service, grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, - "export class $ServiceName$Client extends grpc.Client " - "implements I$ServiceName$Client {\n"); - printer->Indent(); - printer->Print( - "constructor(address: string, credentials: grpc.ChannelCredentials, " - "options?: object);\n"); - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["MethodName"] = method->name(); - vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(), - method->get_output_type_name(), false); - vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(), - method->get_input_type_name(), false); - vars["ISPUBLIC"] = "public "; - if (method->NoStreaming()) { - GenerateUnaryClientInterface(printer, &vars); - continue; - } - if (method->BidiStreaming()) { - GenerateDepluxStreamInterface(printer, &vars); - continue; - } - - if (method->ClientStreaming()) { - GenerateClientWriteStreamInterface(printer, &vars); - continue; - } - - if (method->ServerStreaming()) { - GenerateClientReadableStreamInterface(printer, &vars); - continue; - } - } - printer->Outdent(); - printer->Print("}\n"); -} -} // namespace - - -grpc::string GenerateInterface(grpc_generator::File *file, - const grpc_generator::Service *service, - const grpc::string &filename) { - grpc::string output; - - std::set generated_functions; - std::map vars; - - vars["PATH"] = file->package(); - - if (!file->package().empty()) { vars["PATH"].append("."); } - - vars["ServiceName"] = service->name(); - vars["FBSFile"] = service->name() + "_fbs"; - vars["Filename"] = filename; - auto printer = file->CreatePrinter(&output); - - GenerateImports(service, &*printer, &vars, false); - GenerateMainInterface(service, &*printer, &vars); - printer->Print("\n"); - GenerateClientInterface(service, &*printer, &vars); - printer->Print("\n"); - GenerateClientClassInterface(service, &*printer, &vars); - return output; -} -} // namespace grpc_ts_generator diff --git a/third_party/flatbuffers/grpc/src/compiler/ts_generator.h b/third_party/flatbuffers/grpc/src/compiler/ts_generator.h deleted file mode 100644 index a356659daac..00000000000 --- a/third_party/flatbuffers/grpc/src/compiler/ts_generator.h +++ /dev/null @@ -1,26 +0,0 @@ -#include -#include -#include - -#include "src/compiler/schema_interface.h" - -#ifndef GRPC_CUSTOM_STRING -# include -# define GRPC_CUSTOM_STRING std::string -#endif - -namespace grpc { - -typedef GRPC_CUSTOM_STRING string; - -} // namespace grpc - -namespace grpc_ts_generator { -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service, - const grpc::string &filename); - -grpc::string GenerateInterface(grpc_generator::File *file, - const grpc_generator::Service *service, - const grpc::string &filename); -} // namespace grpc_ts_generator diff --git a/third_party/flatbuffers/grpc/tests/BUILD b/third_party/flatbuffers/grpc/tests/BUILD deleted file mode 100644 index 5d4023ec752..00000000000 --- a/third_party/flatbuffers/grpc/tests/BUILD +++ /dev/null @@ -1,17 +0,0 @@ -cc_test( - name = "grpc_test", - srcs = [ - "grpctest.cpp", - "message_builder_test.cpp", - ], - copts = ["-Itests"], - # This is required. - linkstatic = 1, - deps = [ - "//tests:monster_test_cc_fbs", - "//tests:monster_test_grpc", - "//tests:test_assert", - "//tests:test_builder", - "@com_github_grpc_grpc//:grpc++", - ], -) diff --git a/third_party/flatbuffers/grpc/tests/GameFactory.java b/third_party/flatbuffers/grpc/tests/GameFactory.java deleted file mode 100644 index 520ae392090..00000000000 --- a/third_party/flatbuffers/grpc/tests/GameFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -import java.nio.ByteBuffer; -import MyGame.Example.Monster; -import MyGame.Example.Stat; -import com.google.flatbuffers.FlatBufferBuilder; - -class GameFactory { - public static Monster createMonster(String monsterName, short nestedMonsterHp, short nestedMonsterMana) { - FlatBufferBuilder builder = new FlatBufferBuilder(); - - int name_offset = builder.createString(monsterName); - Monster.startMonster(builder); - Monster.addName(builder, name_offset); - Monster.addHp(builder, nestedMonsterHp); - Monster.addMana(builder, nestedMonsterMana); - int monster_offset = Monster.endMonster(builder); - Monster.finishMonsterBuffer(builder, monster_offset); - - ByteBuffer buffer = builder.dataBuffer(); - Monster monster = Monster.getRootAsMonster(buffer); - return monster; - } - - public static Monster createMonsterFromStat(Stat stat, int seqNo) { - FlatBufferBuilder builder = new FlatBufferBuilder(); - int name_offset = builder.createString(stat.id() + " No." + seqNo); - Monster.startMonster(builder); - Monster.addName(builder, name_offset); - int monster_offset = Monster.endMonster(builder); - Monster.finishMonsterBuffer(builder, monster_offset); - Monster monster = Monster.getRootAsMonster(builder.dataBuffer()); - return monster; - } - - public static Stat createStat(String greeting, long val, int count) { - FlatBufferBuilder builder = new FlatBufferBuilder(); - int statOffset = Stat.createStat(builder, builder.createString(greeting), val, count); - builder.finish(statOffset); - Stat stat = Stat.getRootAsStat(builder.dataBuffer()); - return stat; - } - -} diff --git a/third_party/flatbuffers/grpc/tests/JavaGrpcTest.java b/third_party/flatbuffers/grpc/tests/JavaGrpcTest.java deleted file mode 100644 index 27329116171..00000000000 --- a/third_party/flatbuffers/grpc/tests/JavaGrpcTest.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * 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. - */ - -import MyGame.Example.Monster; -import MyGame.Example.MonsterStorageGrpc; -import MyGame.Example.Stat; -import com.google.flatbuffers.FlatBufferBuilder; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Server; -import io.grpc.ServerBuilder; -import io.grpc.stub.StreamObserver; -import org.junit.Assert; - -import java.io.IOException; -import java.lang.InterruptedException; -import java.nio.ByteBuffer; -import java.util.Iterator; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.CountDownLatch; - - -/** - * Demonstrates basic client-server interaction using grpc-java over netty. - */ -public class JavaGrpcTest { - static final String BIG_MONSTER_NAME = "Cyberdemon"; - static final short nestedMonsterHp = 600; - static final short nestedMonsterMana = 1024; - static final int numStreamedMsgs = 10; - static final int timeoutMs = 3000; - static Server server; - static ManagedChannel channel; - static MonsterStorageGrpc.MonsterStorageBlockingStub blockingStub; - static MonsterStorageGrpc.MonsterStorageStub asyncStub; - - static class MyService extends MonsterStorageGrpc.MonsterStorageImplBase { - @Override - public void store(Monster request, io.grpc.stub.StreamObserver responseObserver) { - Assert.assertEquals(request.name(), BIG_MONSTER_NAME); - Assert.assertEquals(request.hp(), nestedMonsterHp); - Assert.assertEquals(request.mana(), nestedMonsterMana); - System.out.println("Received store request from " + request.name()); - // Create a response from the incoming request name. - Stat stat = GameFactory.createStat("Hello " + request.name(), 100, 10); - responseObserver.onNext(stat); - responseObserver.onCompleted(); - } - - @Override - public void retrieve(Stat request, io.grpc.stub.StreamObserver responseObserver) { - // Create 10 monsters for streaming response. - for (int i=0; i getMaxHitPoint(final StreamObserver responseObserver) { - return computeMinMax(responseObserver, false); - } - - @Override - public StreamObserver getMinMaxHitPoints(final StreamObserver responseObserver) { - return computeMinMax(responseObserver, true); - } - - private StreamObserver computeMinMax(final StreamObserver responseObserver, final boolean includeMin) { - final AtomicInteger maxHp = new AtomicInteger(Integer.MIN_VALUE); - final AtomicReference maxHpMonsterName = new AtomicReference(); - final AtomicInteger maxHpCount = new AtomicInteger(); - - final AtomicInteger minHp = new AtomicInteger(Integer.MAX_VALUE); - final AtomicReference minHpMonsterName = new AtomicReference(); - final AtomicInteger minHpCount = new AtomicInteger(); - - return new StreamObserver() { - public void onNext(Monster monster) { - if (monster.hp() > maxHp.get()) { - // Found a monster of higher hit points. - maxHp.set(monster.hp()); - maxHpMonsterName.set(monster.name()); - maxHpCount.set(1); - } - else if (monster.hp() == maxHp.get()) { - // Count how many times we saw a monster of current max hit points. - maxHpCount.getAndIncrement(); - } - - if (monster.hp() < minHp.get()) { - // Found a monster of a lower hit points. - minHp.set(monster.hp()); - minHpMonsterName.set(monster.name()); - minHpCount.set(1); - } - else if (monster.hp() == minHp.get()) { - // Count how many times we saw a monster of current min hit points. - minHpCount.getAndIncrement(); - } - } - public void onCompleted() { - Stat maxHpStat = GameFactory.createStat(maxHpMonsterName.get(), maxHp.get(), maxHpCount.get()); - // Send max hit points first. - responseObserver.onNext(maxHpStat); - if (includeMin) { - // Send min hit points. - Stat minHpStat = GameFactory.createStat(minHpMonsterName.get(), minHp.get(), minHpCount.get()); - responseObserver.onNext(minHpStat); - } - responseObserver.onCompleted(); - } - public void onError(Throwable t) { - // Not expected - Assert.fail(); - }; - }; - } - } - - @org.junit.BeforeClass - public static void startServer() throws IOException { - server = ServerBuilder.forPort(0).addService(new MyService()).build().start(); - int port = server.getPort(); - channel = ManagedChannelBuilder.forAddress("localhost", port) - // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid - // needing certificates. - .usePlaintext() - .directExecutor() - .build(); - blockingStub = MonsterStorageGrpc.newBlockingStub(channel); - asyncStub = MonsterStorageGrpc.newStub(channel); - } - - @org.junit.Test - public void testUnary() throws IOException { - Monster monsterRequest = GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana); - Stat stat = blockingStub.store(monsterRequest); - Assert.assertEquals(stat.id(), "Hello " + BIG_MONSTER_NAME); - System.out.println("Received stat response from service: " + stat.id()); - } - - @org.junit.Test - public void testServerStreaming() throws IOException { - Monster monsterRequest = GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana); - Stat stat = blockingStub.store(monsterRequest); - Iterator iterator = blockingStub.retrieve(stat); - int counter = 0; - while(iterator.hasNext()) { - Monster m = iterator.next(); - System.out.println("Received monster " + m.name()); - counter ++; - } - Assert.assertEquals(counter, numStreamedMsgs); - System.out.println("FlatBuffers GRPC client/server test: completed successfully"); - } - - @org.junit.Test - public void testClientStreaming() throws IOException, InterruptedException { - final AtomicReference maxHitStat = new AtomicReference(); - final CountDownLatch streamAlive = new CountDownLatch(1); - - StreamObserver statObserver = new StreamObserver() { - public void onCompleted() { - streamAlive.countDown(); - } - public void onError(Throwable ex) { } - public void onNext(Stat stat) { - maxHitStat.set(stat); - } - }; - StreamObserver monsterStream = asyncStub.getMaxHitPoint(statObserver); - short count = 10; - for (short i = 0;i < count; ++i) { - Monster monster = GameFactory.createMonster(BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana); - monsterStream.onNext(monster); - } - monsterStream.onCompleted(); - // Wait a little bit for the server to send the stats of the monster with the max hit-points. - streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS); - Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1)); - Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1)); - Assert.assertEquals(maxHitStat.get().count(), 1); - } - - @org.junit.Test - public void testBiDiStreaming() throws IOException, InterruptedException { - final AtomicReference maxHitStat = new AtomicReference(); - final AtomicReference minHitStat = new AtomicReference(); - final CountDownLatch streamAlive = new CountDownLatch(1); - - StreamObserver statObserver = new StreamObserver() { - public void onCompleted() { - streamAlive.countDown(); - } - public void onError(Throwable ex) { } - public void onNext(Stat stat) { - // We expect the server to send the max stat first and then the min stat. - if (maxHitStat.get() == null) { - maxHitStat.set(stat); - } - else { - minHitStat.set(stat); - } - } - }; - StreamObserver monsterStream = asyncStub.getMinMaxHitPoints(statObserver); - short count = 10; - for (short i = 0;i < count; ++i) { - Monster monster = GameFactory.createMonster(BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana); - monsterStream.onNext(monster); - } - monsterStream.onCompleted(); - - // Wait a little bit for the server to send the stats of the monster with the max and min hit-points. - streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS); - - Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1)); - Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1)); - Assert.assertEquals(maxHitStat.get().count(), 1); - - Assert.assertEquals(minHitStat.get().id(), BIG_MONSTER_NAME + 0); - Assert.assertEquals(minHitStat.get().val(), nestedMonsterHp * 0); - Assert.assertEquals(minHitStat.get().count(), 1); - } -} diff --git a/third_party/flatbuffers/grpc/tests/go_test.go b/third_party/flatbuffers/grpc/tests/go_test.go deleted file mode 100644 index 7c94feb8fda..00000000000 --- a/third_party/flatbuffers/grpc/tests/go_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package testing - -import ( - flatbuffers "github.com/google/flatbuffers/go" - "github.com/google/flatbuffers/tests/MyGame/Example" - - "context" - "net" - "testing" - - "google.golang.org/grpc" - "google.golang.org/grpc/encoding" -) - -type server struct { - Example.UnimplementedMonsterStorageServer -} - -// test used to send and receive in grpc methods -var test = "Flatbuffers" -var addr = "0.0.0.0:50051" - -// gRPC server store method -func (s *server) Store(context context.Context, in *Example.Monster) (*flatbuffers.Builder, error) { - b := flatbuffers.NewBuilder(0) - i := b.CreateString(test) - Example.StatStart(b) - Example.StatAddId(b, i) - b.Finish(Example.StatEnd(b)) - return b, nil - -} - -// gRPC server retrieve method -func (s *server) Retrieve(context context.Context, in *Example.Stat) (*flatbuffers.Builder, error) { - b := flatbuffers.NewBuilder(0) - i := b.CreateString(test) - Example.MonsterStart(b) - Example.MonsterAddName(b, i) - b.Finish(Example.MonsterEnd(b)) - return b, nil -} - -func StoreClient(c Example.MonsterStorageClient, t *testing.T) { - b := flatbuffers.NewBuilder(0) - i := b.CreateString(test) - Example.MonsterStart(b) - Example.MonsterAddName(b, i) - b.Finish(Example.MonsterEnd(b)) - out, err := c.Store(context.Background(), b) - if err != nil { - t.Fatalf("Store client failed: %v", err) - } - if string(out.Id()) != test { - t.Errorf("StoreClient failed: expected=%s, got=%s\n", test, out.Id()) - t.Fail() - } -} - -func RetrieveClient(c Example.MonsterStorageClient, t *testing.T) { - b := flatbuffers.NewBuilder(0) - i := b.CreateString(test) - Example.StatStart(b) - Example.StatAddId(b, i) - b.Finish(Example.StatEnd(b)) - out, err := c.Retrieve(context.Background(), b) - if err != nil { - t.Fatalf("Retrieve client failed: %v", err) - } - monster, err := out.Recv() - if err != nil { - t.Fatalf("Recv failed: %v", err) - } - if string(monster.Name()) != test { - t.Errorf("RetrieveClient failed: expected=%s, got=%s\n", test, monster.Name()) - t.Fail() - } -} - -func TestGRPC(t *testing.T) { - lis, err := net.Listen("tcp", addr) - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - ser := grpc.NewServer() - encoding.RegisterCodec(flatbuffers.FlatbuffersCodec{}) - Example.RegisterMonsterStorageServer(ser, &server{}) - go func() { - if err := ser.Serve(lis); err != nil { - t.Fatalf("Failed to serve: %v", err) - t.FailNow() - } - }() - conn, err := grpc.Dial(addr, grpc.WithInsecure(), grpc.WithCodec(flatbuffers.FlatbuffersCodec{})) - if err != nil { - t.Fatalf("Failed to connect: %v", err) - } - defer conn.Close() - client := Example.NewMonsterStorageClient(conn) - StoreClient(client, t) - RetrieveClient(client, t) -} diff --git a/third_party/flatbuffers/grpc/tests/grpctest.cpp b/third_party/flatbuffers/grpc/tests/grpctest.cpp deleted file mode 100644 index 6991b7ebb87..00000000000 --- a/third_party/flatbuffers/grpc/tests/grpctest.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/* - * 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. - */ - -#include - -#include -#include - -#include "monster_test.grpc.fb.h" -#include "monster_test_generated.h" -#include "test_assert.h" - -using namespace MyGame::Example; -using flatbuffers::FlatBufferBuilder; -using flatbuffers::grpc::MessageBuilder; - -void message_builder_tests(); - -// The callback implementation of our server, that derives from the generated -// code. It implements all rpcs specified in the FlatBuffers schema. -class ServiceImpl final : public MyGame::Example::MonsterStorage::Service { - virtual ::grpc::Status Store( - ::grpc::ServerContext *context, - const flatbuffers::grpc::Message *request, - flatbuffers::grpc::Message *response) override { - // Create a response from the incoming request name. - fbb_.Clear(); - auto stat_offset = CreateStat( - fbb_, fbb_.CreateString("Hello, " + request->GetRoot()->name()->str())); - fbb_.Finish(stat_offset); - // Transfer ownership of the message to gRPC - *response = fbb_.ReleaseMessage(); - return grpc::Status::OK; - } - virtual ::grpc::Status Retrieve( - ::grpc::ServerContext *context, - const flatbuffers::grpc::Message *request, - ::grpc::ServerWriter> *writer) - override { - for (int i = 0; i < 5; i++) { - fbb_.Clear(); - // Create 5 monsters for resposne. - auto monster_offset = - CreateMonster(fbb_, 0, 0, 0, - fbb_.CreateString(request->GetRoot()->id()->str() + - " No." + std::to_string(i))); - fbb_.Finish(monster_offset); - - flatbuffers::grpc::Message monster = - fbb_.ReleaseMessage(); - - // Send monster to client using streaming. - writer->Write(monster); - } - return grpc::Status::OK; - } - - private: - flatbuffers::grpc::MessageBuilder fbb_; -}; - -// Track the server instance, so we can terminate it later. -grpc::Server *server_instance = nullptr; -// Mutex to protec this variable. -std::mutex wait_for_server; -std::condition_variable server_instance_cv; - -// This function implements the server thread. -void RunServer() { - auto server_address = "0.0.0.0:50051"; - // Callback interface we implemented above. - ServiceImpl service; - grpc::ServerBuilder builder; - builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); - builder.RegisterService(&service); - - // Start the server. Lock to change the variable we're changing. - wait_for_server.lock(); - server_instance = builder.BuildAndStart().release(); - wait_for_server.unlock(); - server_instance_cv.notify_one(); - - std::cout << "Server listening on " << server_address << std::endl; - // This will block the thread and serve requests. - server_instance->Wait(); -} - -template void StoreRPC(MonsterStorage::Stub *stub) { - Builder fbb; - grpc::ClientContext context; - // Build a request with the name set. - auto monster_offset = CreateMonster(fbb, 0, 0, 0, fbb.CreateString("Fred")); - MessageBuilder mb(std::move(fbb)); - mb.Finish(monster_offset); - auto request = mb.ReleaseMessage(); - flatbuffers::grpc::Message response; - - // The actual RPC. - auto status = stub->Store(&context, request, &response); - - if (status.ok()) { - auto resp = response.GetRoot()->id(); - std::cout << "RPC response: " << resp->str() << std::endl; - } else { - std::cout << "RPC failed" << std::endl; - } -} - -template void RetrieveRPC(MonsterStorage::Stub *stub) { - Builder fbb; - grpc::ClientContext context; - fbb.Clear(); - auto stat_offset = CreateStat(fbb, fbb.CreateString("Fred")); - fbb.Finish(stat_offset); - auto request = MessageBuilder(std::move(fbb)).ReleaseMessage(); - - flatbuffers::grpc::Message response; - auto stream = stub->Retrieve(&context, request); - while (stream->Read(&response)) { - auto resp = response.GetRoot()->name(); - std::cout << "RPC Streaming response: " << resp->str() << std::endl; - } -} - -int grpc_server_test() { - // Launch server. - std::thread server_thread(RunServer); - - // wait for server to spin up. - std::unique_lock lock(wait_for_server); - while (!server_instance) server_instance_cv.wait(lock); - - // Now connect the client. - auto channel = grpc::CreateChannel("localhost:50051", - grpc::InsecureChannelCredentials()); - auto stub = MyGame::Example::MonsterStorage::NewStub(channel); - - StoreRPC(stub.get()); - StoreRPC(stub.get()); - - RetrieveRPC(stub.get()); - RetrieveRPC(stub.get()); - -#if !FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION - { - // Test that an invalid request errors out correctly - grpc::ClientContext context; - flatbuffers::grpc::Message request; // simulate invalid message - flatbuffers::grpc::Message response; - auto status = stub->Store(&context, request, &response); - // The rpc status should be INTERNAL to indicate a verification error. This - // matches the protobuf gRPC status code for an unparseable message. - assert(!status.ok()); - assert(status.error_code() == ::grpc::StatusCode::INTERNAL); - assert(strcmp(status.error_message().c_str(), - "Message verification failed") == 0); - } -#endif - - server_instance->Shutdown(); - - server_thread.join(); - - delete server_instance; - - return 0; -} - -int main(int /*argc*/, const char * /*argv*/[]) { - message_builder_tests(); - grpc_server_test(); - - if (!testing_fails) { - TEST_OUTPUT_LINE("ALL TESTS PASSED"); - return 0; - } else { - TEST_OUTPUT_LINE("%d FAILED TESTS", testing_fails); - return 1; - } -} diff --git a/third_party/flatbuffers/grpc/tests/grpctest.py b/third_party/flatbuffers/grpc/tests/grpctest.py deleted file mode 100644 index 9cfeda6891b..00000000000 --- a/third_party/flatbuffers/grpc/tests/grpctest.py +++ /dev/null @@ -1,174 +0,0 @@ -from __future__ import print_function - -import os -import sys -import grpc -import flatbuffers - -from concurrent import futures - -sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'tests')) -import MyGame.Example.Monster as Monster -import MyGame.Example.Stat as Stat -import MyGame.Example.Vec3 as Vec3 -import MyGame.Example.Test as Test -import MyGame.Example.monster_test_grpc_fb as monster_grpc_fb - - -test_stat_id = "test_stat_id" -test_stat_val = 8 -test_stat_count = 1 - -test_monster_name1 = "test_monster_name1" -test_monster_name2 = "test_monster_name2" -test_string = "test_string" -test_color = 2 -test_X = 3.0 -test_Y = 2.0 -test_Z = 6.0 -test_test1 = 4.0 -test_a = 8 -test_b = 5 -test_hp = 67 -test_inventory = [1, 1, 2, 3, 5, 8] -test_testtype = 4 - -test_monsters_name_retrieve = ["big_monster", "small_monster"] -test_no_of_monsters = 2 - - -class MonsterStorage(monster_grpc_fb.MonsterStorageServicer): - - def Store(self, request, context): - - m = Monster.Monster().GetRootAsMonster(request, 0) - - assert m.Name().decode("utf-8") == test_monster_name1 - - assert m.Pos().X() == test_X - assert m.Pos().Y() == test_Y - assert m.Pos().Z() == test_Z - assert m.Pos().Test1() == test_test1 - assert m.Pos().Test2() == test_color - test3 = Test.Test() - assert m.Pos().Test3(test3).A() == test_a - assert m.Pos().Test3(test3).B() == test_b - - assert m.Hp() == test_hp - - assert m.Color() == test_color - - assert m.InventoryLength() == len(test_inventory) - for i in range(0, len(test_inventory)): - assert m.Inventory(i) == test_inventory[len(test_inventory)-i -1] - - assert m.TestType() == test_testtype - - assert m.Test() is not None - table = m.Test() - - m2 = Monster.Monster() - m2.Init(table.Bytes, table.Pos) - assert m2.Name().decode("utf-8") == test_monster_name2 - - m3 = m.Enemy() - assert m3.Name().decode("utf-8") == test_monster_name2 - - assert m.Testarrayofstring(0).decode("utf-8") == test_string - - b = flatbuffers.Builder(0) - i = b.CreateString(test_stat_id) - Stat.StatStart(b) - Stat.StatAddId(b, i) - Stat.StatAddVal(b, test_stat_val) - Stat.StatAddCount(b, test_stat_count) - b.Finish(Stat.StatEnd(b)) - return bytes(b.Output()) - - def Retrieve(self, request, context): - - s = Stat.Stat().GetRootAsStat(request, 0) - - no_of_monsters = test_no_of_monsters - for i in range(0, no_of_monsters): - b = flatbuffers.Builder(0) - i = b.CreateString(test_monsters_name_retrieve[i]) - Monster.MonsterStart(b) - Monster.MonsterAddName(b, i) - b.Finish(Monster.MonsterEnd(b)) - yield bytes(b.Output()) - - -def serve(): - - server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) - monster_grpc_fb.add_MonsterStorageServicer_to_server(MonsterStorage(), server) - server.add_insecure_port('[::]:50051') - - server.start() - - run() - - -def run(): - - channel = grpc.insecure_channel('127.0.0.1:50051') - stub = monster_grpc_fb.MonsterStorageStub(channel) - - b = flatbuffers.Builder(0) - name2 = b.CreateString(test_monster_name2) - name1 = b.CreateString(test_monster_name1) - Monster.MonsterStart(b) - Monster.MonsterAddName(b, name2) - monster2 = Monster.MonsterEnd(b) - test1 = b.CreateString(test_string) - - Monster.MonsterStartInventoryVector(b, len(test_inventory)) - for i in range(0, len(test_inventory)): - b.PrependByte(test_inventory[i]) - inv = b.EndVector() - - Monster.MonsterStartTest4Vector(b, 2) - Test.CreateTest(b, 10, 20) - Test.CreateTest(b, 30, 40) - test4 = b.EndVector() - - Monster.MonsterStartTestarrayofstringVector(b, 1) - b.PrependUOffsetTRelative(test1) - test_array_of_string = b.EndVector() - - Monster.MonsterStart(b) - - Monster.MonsterAddHp(b, test_hp) - Monster.MonsterAddName(b, name1) - Monster.MonsterAddColor(b, test_color) - pos = Vec3.CreateVec3(b, test_X, test_Y, test_Z, test_test1, test_color, test_a, test_b) - Monster.MonsterAddPos(b, pos) - Monster.MonsterAddInventory(b, inv) - Monster.MonsterAddTestType(b, test_testtype) - Monster.MonsterAddTest(b, monster2) - Monster.MonsterAddTest4(b, test4) - Monster.MonsterAddEnemy(b, monster2) - Monster.MonsterAddTestarrayofstring(b, test_array_of_string) - monster = Monster.MonsterEnd(b) - - b.Finish(monster) - - stat_response = stub.Store(bytes(b.Output())) - - s = Stat.Stat().GetRootAsStat(stat_response, 0) - - assert s.Id().decode("utf-8") == test_stat_id - assert s.Val() == test_stat_val - assert s.Count() == test_stat_count - - monster_reponses = stub.Retrieve(stat_response) - count = 0 - for monster_reponse in monster_reponses: - m = Monster.Monster().GetRootAsMonster(monster_reponse, 0) - assert m.Name().decode("utf-8") == test_monsters_name_retrieve[count] - count = count + 1 - - -if __name__ == '__main__': - serve() diff --git a/third_party/flatbuffers/grpc/tests/java-grpc-test.sh b/third_party/flatbuffers/grpc/tests/java-grpc-test.sh deleted file mode 100755 index ec429605596..00000000000 --- a/third_party/flatbuffers/grpc/tests/java-grpc-test.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -# NOTE: make sure `mvn install` in /gprc is executed before running this test -mvn test diff --git a/third_party/flatbuffers/grpc/tests/message_builder_test.cpp b/third_party/flatbuffers/grpc/tests/message_builder_test.cpp deleted file mode 100644 index 8af0c2141b9..00000000000 --- a/third_party/flatbuffers/grpc/tests/message_builder_test.cpp +++ /dev/null @@ -1,368 +0,0 @@ -#include "flatbuffers/grpc.h" -#include "monster_test_generated.h" -#include "test_assert.h" -#include "test_builder.h" - -using MyGame::Example::Any_NONE; -using MyGame::Example::CreateStat; -using MyGame::Example::Vec3; - -bool verify(flatbuffers::grpc::Message &msg, - const std::string &expected_name, Color expected_color) { - const Monster *monster = msg.GetRoot(); - const auto name = monster->name()->str(); - const auto color = monster->color(); - TEST_EQ(name, expected_name); - TEST_EQ(color, expected_color); - return (name == expected_name) && (color == expected_color); -} - -bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb, - const std::string &expected_name, Color expected_color) { - flatbuffers::grpc::Message msg = mbb.ReleaseMessage(); - return verify(msg, expected_name, expected_color); -} - -void builder_move_assign_after_releaseraw_test( - flatbuffers::grpc::MessageBuilder dst) { - auto root_offset1 = populate1(dst); - dst.Finish(root_offset1); - size_t size, offset; - ::grpc::Slice slice; - dst.ReleaseRaw(size, offset, slice); - flatbuffers::FlatBufferBuilder src; - auto root_offset2 = populate2(src); - src.Finish(root_offset2); - auto src_size = src.GetSize(); - // Move into a released builder. - dst = std::move(src); - TEST_EQ(dst.GetSize(), src_size); - TEST_ASSERT(release_n_verify(dst, m2_name(), m2_color())); - TEST_EQ(src.GetSize(), 0); -} - -template -struct BuilderReuseTests { - static void builder_reusable_after_release_message_test( - TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_MESSAGE)) { return; } - - flatbuffers::grpc::MessageBuilder mb; - std::vector> buffers; - for (int i = 0; i < 5; ++i) { - auto root_offset1 = populate1(mb); - mb.Finish(root_offset1); - buffers.push_back(mb.ReleaseMessage()); - TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color())); - } - } - - static void builder_reusable_after_release_test(TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE)) { return; } - - // FIXME: Populate-Release loop fails assert(GRPC_SLICE_IS_EMPTY(slice_)) in - // SliceAllocator::allocate in the second iteration. - - flatbuffers::grpc::MessageBuilder mb; - std::vector buffers; - for (int i = 0; i < 2; ++i) { - auto root_offset1 = populate1(mb); - mb.Finish(root_offset1); - buffers.push_back(mb.Release()); - TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color())); - } - } - - static void builder_reusable_after_releaseraw_test(TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_RAW)) { return; } - - flatbuffers::grpc::MessageBuilder mb; - for (int i = 0; i < 5; ++i) { - auto root_offset1 = populate1(mb); - mb.Finish(root_offset1); - size_t size, offset; - ::grpc::Slice slice; - const uint8_t *buf = mb.ReleaseRaw(size, offset, slice); - TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color())); - } - } - - static void builder_reusable_after_release_and_move_assign_test( - TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) { return; } - - // FIXME: Release-move_assign loop fails assert(p == - // GRPC_SLICE_START_PTR(slice_)) in DetachedBuffer destructor after all the - // iterations - - flatbuffers::grpc::MessageBuilder dst; - std::vector buffers; - - for (int i = 0; i < 2; ++i) { - auto root_offset1 = populate1(dst); - dst.Finish(root_offset1); - buffers.push_back(dst.Release()); - TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color())); - - // bring dst back to life. - SrcBuilder src; - dst = std::move(src); - TEST_EQ_FUNC(dst.GetSize(), 0); - TEST_EQ_FUNC(src.GetSize(), 0); - } - } - - static void builder_reusable_after_release_message_and_move_assign_test( - TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_MESSAGE_AND_MOVE_ASSIGN)) { - return; - } - - flatbuffers::grpc::MessageBuilder dst; - std::vector> buffers; - - for (int i = 0; i < 5; ++i) { - auto root_offset1 = populate1(dst); - dst.Finish(root_offset1); - buffers.push_back(dst.ReleaseMessage()); - TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color())); - - // bring dst back to life. - SrcBuilder src; - dst = std::move(src); - TEST_EQ_FUNC(dst.GetSize(), 0); - TEST_EQ_FUNC(src.GetSize(), 0); - } - } - - static void builder_reusable_after_releaseraw_and_move_assign_test( - TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN)) { return; } - - flatbuffers::grpc::MessageBuilder dst; - for (int i = 0; i < 5; ++i) { - auto root_offset1 = populate1(dst); - dst.Finish(root_offset1); - size_t size, offset; - ::grpc::Slice slice; - const uint8_t *buf = dst.ReleaseRaw(size, offset, slice); - TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color())); - - SrcBuilder src; - dst = std::move(src); - TEST_EQ_FUNC(dst.GetSize(), 0); - TEST_EQ_FUNC(src.GetSize(), 0); - } - } - - static void run_tests(TestSelector selector) { - builder_reusable_after_release_test(selector); - builder_reusable_after_release_message_test(selector); - builder_reusable_after_releaseraw_test(selector); - builder_reusable_after_release_and_move_assign_test(selector); - builder_reusable_after_releaseraw_and_move_assign_test(selector); - builder_reusable_after_release_message_and_move_assign_test(selector); - } -}; - -void slice_allocator_tests() { - // move-construct no-delete test - { - size_t size = 2048; - flatbuffers::grpc::SliceAllocator sa1; - uint8_t *buf = sa1.allocate(size); - TEST_ASSERT_FUNC(buf != 0); - buf[0] = 100; - buf[size - 1] = 200; - flatbuffers::grpc::SliceAllocator sa2(std::move(sa1)); - // buf should not be deleted after move-construct - TEST_EQ_FUNC(buf[0], 100); - TEST_EQ_FUNC(buf[size - 1], 200); - // buf is freed here - } - - // move-assign test - { - flatbuffers::grpc::SliceAllocator sa1, sa2; - uint8_t *buf = sa1.allocate(2048); - sa1 = std::move(sa2); - // sa1 deletes previously allocated memory in move-assign. - // So buf is no longer usable here. - TEST_ASSERT_FUNC(buf != 0); - } -} - -/// This function does not populate exactly the first half of the table. But it -/// could. -void populate_first_half(MyGame::Example::MonsterBuilder &wrapper, - flatbuffers::Offset name_offset) { - wrapper.add_name(name_offset); - wrapper.add_color(m1_color()); -} - -/// This function does not populate exactly the second half of the table. But it -/// could. -void populate_second_half(MyGame::Example::MonsterBuilder &wrapper) { - wrapper.add_hp(77); - wrapper.add_mana(88); - Vec3 vec3; - wrapper.add_pos(&vec3); -} - -/// This function is a hack to update the FlatBufferBuilder reference (fbb_) in -/// the MonsterBuilder object. This function will break if fbb_ is not the first -/// member in MonsterBuilder. In that case, some offset must be added. This -/// function is used exclusively for testing correctness of move operations -/// between FlatBufferBuilders. If MonsterBuilder had a fbb_ pointer, this hack -/// would be unnecessary. That involves a code-generator change though. -void test_only_hack_update_fbb_reference( - MyGame::Example::MonsterBuilder &monsterBuilder, - flatbuffers::grpc::MessageBuilder &mb) { - *reinterpret_cast(&monsterBuilder) = &mb; -} - -/// This test validates correctness of move conversion of FlatBufferBuilder to a -/// MessageBuilder DURING a table construction. Half of the table is constructed -/// using FlatBufferBuilder and the other half of the table is constructed using -/// a MessageBuilder. -void builder_move_ctor_conversion_before_finish_half_n_half_table_test() { - for (size_t initial_size = 4; initial_size <= 2048; initial_size *= 2) { - flatbuffers::FlatBufferBuilder fbb(initial_size); - auto name_offset = fbb.CreateString(m1_name()); - MyGame::Example::MonsterBuilder monsterBuilder( - fbb); // starts a table in FlatBufferBuilder - populate_first_half(monsterBuilder, name_offset); - flatbuffers::grpc::MessageBuilder mb(std::move(fbb)); - test_only_hack_update_fbb_reference(monsterBuilder, mb); // hack - populate_second_half(monsterBuilder); - mb.Finish(monsterBuilder.Finish()); // ends the table in MessageBuilder - TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color())); - TEST_EQ_FUNC(fbb.GetSize(), 0); - } -} - -/// This test populates a COMPLETE inner table before move conversion and later -/// populates more members in the outer table. -void builder_move_ctor_conversion_before_finish_test() { - for (size_t initial_size = 1; initial_size <= 2048; initial_size += 1) { - flatbuffers::FlatBufferBuilder fbb(initial_size); - auto stat_offset = CreateStat(fbb, fbb.CreateString("SomeId"), 0, 0); - flatbuffers::grpc::MessageBuilder mb(std::move(fbb)); - auto monster_offset = - CreateMonster(mb, 0, 150, 100, mb.CreateString(m1_name()), 0, - m1_color(), Any_NONE, 0, 0, 0, 0, 0, 0, stat_offset); - mb.Finish(monster_offset); - { - auto mon = flatbuffers::GetRoot(mb.GetBufferPointer()); - TEST_NOTNULL(mon); - TEST_NOTNULL(mon->name()); - TEST_EQ_STR(mon->name()->c_str(), m1_name().c_str()); - TEST_EQ(mon->color(), m1_color()); - } - TEST_EQ(1, MyGame::Example::Color_Red); - TEST_EQ(1, m1_color()); - TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color())); - TEST_EQ_FUNC(fbb.GetSize(), 0); - } -} - -/// This test validates correctness of move conversion of FlatBufferBuilder to a -/// MessageBuilder DURING a table construction. Half of the table is constructed -/// using FlatBufferBuilder and the other half of the table is constructed using -/// a MessageBuilder. -void builder_move_assign_conversion_before_finish_half_n_half_table_test() { - flatbuffers::FlatBufferBuilder fbb; - flatbuffers::grpc::MessageBuilder mb; - - for (int i = 0; i < 5; ++i) { - flatbuffers::FlatBufferBuilder fbb; - auto name_offset = fbb.CreateString(m1_name()); - MyGame::Example::MonsterBuilder monsterBuilder( - fbb); // starts a table in FlatBufferBuilder - populate_first_half(monsterBuilder, name_offset); - mb = std::move(fbb); - test_only_hack_update_fbb_reference(monsterBuilder, mb); // hack - populate_second_half(monsterBuilder); - mb.Finish(monsterBuilder.Finish()); // ends the table in MessageBuilder - TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color())); - TEST_EQ_FUNC(fbb.GetSize(), 0); - } -} - -/// This test populates a COMPLETE inner table before move conversion and later -/// populates more members in the outer table. -void builder_move_assign_conversion_before_finish_test() { - flatbuffers::FlatBufferBuilder fbb; - flatbuffers::grpc::MessageBuilder mb; - - for (int i = 0; i < 5; ++i) { - auto stat_offset = CreateStat(fbb, fbb.CreateString("SomeId"), 0, 0); - mb = std::move(fbb); - auto monster_offset = - CreateMonster(mb, 0, 150, 100, mb.CreateString(m1_name()), 0, - m1_color(), Any_NONE, 0, 0, 0, 0, 0, 0, stat_offset); - mb.Finish(monster_offset); - TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color())); - TEST_EQ_FUNC(fbb.GetSize(), 0); - } -} - -/// This test populates data, finishes the buffer, and does move conversion -/// after. -void builder_move_ctor_conversion_after_finish_test() { - flatbuffers::FlatBufferBuilder fbb; - fbb.Finish(populate1(fbb)); - flatbuffers::grpc::MessageBuilder mb(std::move(fbb)); - TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color())); - TEST_EQ_FUNC(fbb.GetSize(), 0); -} - -/// This test populates data, finishes the buffer, and does move conversion -/// after. -void builder_move_assign_conversion_after_finish_test() { - flatbuffers::FlatBufferBuilder fbb; - flatbuffers::grpc::MessageBuilder mb; - - for (int i = 0; i < 5; ++i) { - fbb.Finish(populate1(fbb)); - mb = std::move(fbb); - TEST_ASSERT_FUNC(release_n_verify(mb, m1_name(), m1_color())); - TEST_EQ_FUNC(fbb.GetSize(), 0); - } -} - -void message_builder_tests() { - using flatbuffers::FlatBufferBuilder; - using flatbuffers::grpc::MessageBuilder; - - slice_allocator_tests(); - -#ifndef __APPLE__ - builder_move_ctor_conversion_before_finish_half_n_half_table_test(); - builder_move_assign_conversion_before_finish_half_n_half_table_test(); -#endif // __APPLE__ - builder_move_ctor_conversion_before_finish_test(); - builder_move_assign_conversion_before_finish_test(); - - builder_move_ctor_conversion_after_finish_test(); - builder_move_assign_conversion_after_finish_test(); - - BuilderTests::all_tests(); - BuilderTests::all_tests(); - - BuilderReuseTestSelector tests[6] = { - // REUSABLE_AFTER_RELEASE, // Assertion failed: - // (GRPC_SLICE_IS_EMPTY(slice_)) - // REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN, // Assertion failed: (p == - // GRPC_SLICE_START_PTR(slice_) - - REUSABLE_AFTER_RELEASE_RAW, REUSABLE_AFTER_RELEASE_MESSAGE, - REUSABLE_AFTER_RELEASE_MESSAGE_AND_MOVE_ASSIGN, - REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN - }; - - BuilderReuseTests::run_tests( - TestSelector(tests, tests + 6)); - BuilderReuseTests::run_tests( - TestSelector(tests, tests + 6)); -} diff --git a/third_party/flatbuffers/grpc/tests/pom.xml b/third_party/flatbuffers/grpc/tests/pom.xml deleted file mode 100644 index 5aca387bfdd..00000000000 --- a/third_party/flatbuffers/grpc/tests/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - 4.0.0 - - com.google.flatbuffers - flatbuffers-parent - 2.0.3 - - grpc-test - Example/Test project demonstrating usage of flatbuffers with GRPC-Java instead of protobufs - - - 2.0.3 - - - - com.google.flatbuffers - flatbuffers-java - ${project.parent.version} - test - - - com.google.flatbuffers - flatbuffers-java-grpc - ${project.parent.version} - test - - - io.grpc - grpc-stub - ${gRPC.version} - test - - - io.grpc - grpc-netty - ${gRPC.version} - test - - - junit - junit - 4.13.1 - test - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - add-source - generate-sources - - add-test-source - - - - ${project.basedir} - ${project.basedir}/../../tests - - - - - - - - - - diff --git a/third_party/flatbuffers/include/flatbuffers/allocator.h b/third_party/flatbuffers/include/flatbuffers/allocator.h deleted file mode 100644 index 30427190b6c..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/allocator.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2021 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_ALLOCATOR_H_ -#define FLATBUFFERS_ALLOCATOR_H_ - -#include "flatbuffers/base.h" - -namespace flatbuffers { - -// Allocator interface. This is flatbuffers-specific and meant only for -// `vector_downward` usage. -class Allocator { - public: - virtual ~Allocator() {} - - // Allocate `size` bytes of memory. - virtual uint8_t *allocate(size_t size) = 0; - - // Deallocate `size` bytes of memory at `p` allocated by this allocator. - virtual void deallocate(uint8_t *p, size_t size) = 0; - - // Reallocate `new_size` bytes of memory, replacing the old region of size - // `old_size` at `p`. In contrast to a normal realloc, this grows downwards, - // and is intended specifcally for `vector_downward` use. - // `in_use_back` and `in_use_front` indicate how much of `old_size` is - // actually in use at each end, and needs to be copied. - virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size, - size_t new_size, size_t in_use_back, - size_t in_use_front) { - FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows - uint8_t *new_p = allocate(new_size); - memcpy_downward(old_p, old_size, new_p, new_size, in_use_back, - in_use_front); - deallocate(old_p, old_size); - return new_p; - } - - protected: - // Called by `reallocate_downward` to copy memory from `old_p` of `old_size` - // to `new_p` of `new_size`. Only memory of size `in_use_front` and - // `in_use_back` will be copied from the front and back of the old memory - // allocation. - void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p, - size_t new_size, size_t in_use_back, - size_t in_use_front) { - memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back, - in_use_back); - memcpy(new_p, old_p, in_use_front); - } -}; - -} // namespace flatbuffers - -#endif // FLATBUFFERS_ALLOCATOR_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/array.h b/third_party/flatbuffers/include/flatbuffers/array.h deleted file mode 100644 index f4bfbf054c4..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/array.h +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright 2021 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_ARRAY_H_ -#define FLATBUFFERS_ARRAY_H_ - -#include -#include - -#include "flatbuffers/base.h" -#include "flatbuffers/stl_emulation.h" -#include "flatbuffers/vector.h" - -namespace flatbuffers { - -// This is used as a helper type for accessing arrays. -template class Array { - // Array can carry only POD data types (scalars or structs). - typedef typename flatbuffers::bool_constant::value> - scalar_tag; - typedef - typename flatbuffers::conditional::type - IndirectHelperType; - - public: - typedef uint16_t size_type; - typedef typename IndirectHelper::return_type return_type; - typedef VectorConstIterator const_iterator; - typedef VectorReverseIterator const_reverse_iterator; - - // If T is a LE-scalar or a struct (!scalar_tag::value). - static FLATBUFFERS_CONSTEXPR bool is_span_observable = - (scalar_tag::value && (FLATBUFFERS_LITTLEENDIAN || sizeof(T) == 1)) || - !scalar_tag::value; - - FLATBUFFERS_CONSTEXPR uint16_t size() const { return length; } - - return_type Get(uoffset_t i) const { - FLATBUFFERS_ASSERT(i < size()); - return IndirectHelper::Read(Data(), i); - } - - return_type operator[](uoffset_t i) const { return Get(i); } - - // If this is a Vector of enums, T will be its storage type, not the enum - // type. This function makes it convenient to retrieve value with enum - // type E. - template E GetEnum(uoffset_t i) const { - return static_cast(Get(i)); - } - - const_iterator begin() const { return const_iterator(Data(), 0); } - const_iterator end() const { return const_iterator(Data(), size()); } - - const_reverse_iterator rbegin() const { - return const_reverse_iterator(end()); - } - const_reverse_iterator rend() const { - return const_reverse_iterator(begin()); - } - - const_iterator cbegin() const { return begin(); } - const_iterator cend() const { return end(); } - - const_reverse_iterator crbegin() const { return rbegin(); } - const_reverse_iterator crend() const { return rend(); } - - // Get a mutable pointer to elements inside this array. - // This method used to mutate arrays of structs followed by a @p Mutate - // operation. For primitive types use @p Mutate directly. - // @warning Assignments and reads to/from the dereferenced pointer are not - // automatically converted to the correct endianness. - typename flatbuffers::conditional::type - GetMutablePointer(uoffset_t i) const { - FLATBUFFERS_ASSERT(i < size()); - return const_cast(&data()[i]); - } - - // Change elements if you have a non-const pointer to this object. - void Mutate(uoffset_t i, const T &val) { MutateImpl(scalar_tag(), i, val); } - - // The raw data in little endian format. Use with care. - const uint8_t *Data() const { return data_; } - - uint8_t *Data() { return data_; } - - // Similarly, but typed, much like std::vector::data - const T *data() const { return reinterpret_cast(Data()); } - T *data() { return reinterpret_cast(Data()); } - - // Copy data from a span with endian conversion. - // If this Array and the span overlap, the behavior is undefined. - void CopyFromSpan(flatbuffers::span src) { - const auto p1 = reinterpret_cast(src.data()); - const auto p2 = Data(); - FLATBUFFERS_ASSERT(!(p1 >= p2 && p1 < (p2 + length)) && - !(p2 >= p1 && p2 < (p1 + length))); - (void)p1; - (void)p2; - CopyFromSpanImpl(flatbuffers::bool_constant(), src); - } - - protected: - void MutateImpl(flatbuffers::true_type, uoffset_t i, const T &val) { - FLATBUFFERS_ASSERT(i < size()); - WriteScalar(data() + i, val); - } - - void MutateImpl(flatbuffers::false_type, uoffset_t i, const T &val) { - *(GetMutablePointer(i)) = val; - } - - void CopyFromSpanImpl(flatbuffers::true_type, - flatbuffers::span src) { - // Use std::memcpy() instead of std::copy() to avoid performance degradation - // due to aliasing if T is char or unsigned char. - // The size is known at compile time, so memcpy would be inlined. - std::memcpy(data(), src.data(), length * sizeof(T)); - } - - // Copy data from flatbuffers::span with endian conversion. - void CopyFromSpanImpl(flatbuffers::false_type, - flatbuffers::span src) { - for (size_type k = 0; k < length; k++) { Mutate(k, src[k]); } - } - - // This class is only used to access pre-existing data. Don't ever - // try to construct these manually. - // 'constexpr' allows us to use 'size()' at compile time. - // @note Must not use 'FLATBUFFERS_CONSTEXPR' here, as const is not allowed on - // a constructor. -#if defined(__cpp_constexpr) - constexpr Array(); -#else - Array(); -#endif - - uint8_t data_[length * sizeof(T)]; - - private: - // This class is a pointer. Copying will therefore create an invalid object. - // Private and unimplemented copy constructor. - Array(const Array &); - Array &operator=(const Array &); -}; - -// Specialization for Array[struct] with access using Offset pointer. -// This specialization used by idl_gen_text.cpp. -template class OffsetT> -class Array, length> { - static_assert(flatbuffers::is_same::value, "unexpected type T"); - - public: - typedef const void *return_type; - typedef uint16_t size_type; - - const uint8_t *Data() const { return data_; } - - // Make idl_gen_text.cpp::PrintContainer happy. - return_type operator[](uoffset_t) const { - FLATBUFFERS_ASSERT(false); - return nullptr; - } - - private: - // This class is only used to access pre-existing data. - Array(); - Array(const Array &); - Array &operator=(const Array &); - - uint8_t data_[1]; -}; - -template -FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span make_span(Array &arr) - FLATBUFFERS_NOEXCEPT { - static_assert( - Array::is_span_observable, - "wrong type U, only plain struct, LE-scalar, or byte types are allowed"); - return span(arr.data(), N); -} - -template -FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span make_span( - const Array &arr) FLATBUFFERS_NOEXCEPT { - static_assert( - Array::is_span_observable, - "wrong type U, only plain struct, LE-scalar, or byte types are allowed"); - return span(arr.data(), N); -} - -template -FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span -make_bytes_span(Array &arr) FLATBUFFERS_NOEXCEPT { - static_assert(Array::is_span_observable, - "internal error, Array might hold only scalars or structs"); - return span(arr.Data(), sizeof(U) * N); -} - -template -FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span -make_bytes_span(const Array &arr) FLATBUFFERS_NOEXCEPT { - static_assert(Array::is_span_observable, - "internal error, Array might hold only scalars or structs"); - return span(arr.Data(), sizeof(U) * N); -} - -// Cast a raw T[length] to a raw flatbuffers::Array -// without endian conversion. Use with care. -// TODO: move these Cast-methods to `internal` namespace. -template -Array &CastToArray(T (&arr)[length]) { - return *reinterpret_cast *>(arr); -} - -template -const Array &CastToArray(const T (&arr)[length]) { - return *reinterpret_cast *>(arr); -} - -template -Array &CastToArrayOfEnum(T (&arr)[length]) { - static_assert(sizeof(E) == sizeof(T), "invalid enum type E"); - return *reinterpret_cast *>(arr); -} - -template -const Array &CastToArrayOfEnum(const T (&arr)[length]) { - static_assert(sizeof(E) == sizeof(T), "invalid enum type E"); - return *reinterpret_cast *>(arr); -} - -template -bool operator==(const Array &lhs, - const Array &rhs) noexcept { - return std::addressof(lhs) == std::addressof(rhs) || - (lhs.size() == rhs.size() && - std::memcmp(lhs.Data(), rhs.Data(), rhs.size() * sizeof(T)) == 0); -} - -} // namespace flatbuffers - -#endif // FLATBUFFERS_ARRAY_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/base.h b/third_party/flatbuffers/include/flatbuffers/base.h deleted file mode 100644 index 1c19dde98f3..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/base.h +++ /dev/null @@ -1,496 +0,0 @@ -#ifndef FLATBUFFERS_BASE_H_ -#define FLATBUFFERS_BASE_H_ - -// clang-format off - -// If activate should be declared and included first. -#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && \ - defined(_MSC_VER) && defined(_DEBUG) - // The _CRTDBG_MAP_ALLOC inside will replace - // calloc/free (etc) to its debug version using #define directives. - #define _CRTDBG_MAP_ALLOC - #include - #include - // Replace operator new by trace-enabled version. - #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) - #define new DEBUG_NEW -#endif - -#if !defined(FLATBUFFERS_ASSERT) -#include -#define FLATBUFFERS_ASSERT assert -#elif defined(FLATBUFFERS_ASSERT_INCLUDE) -// Include file with forward declaration -#include FLATBUFFERS_ASSERT_INCLUDE -#endif - -#ifndef ARDUINO -#include -#endif - -#include -#include -#include - -#if defined(ARDUINO) && !defined(ARDUINOSTL_M_H) && defined(__AVR__) - #include -#else - #include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(__unix__) && !defined(FLATBUFFERS_LOCALE_INDEPENDENT) - #include -#endif - -#ifdef __ANDROID__ - #include -#endif - -#if defined(__ICCARM__) -#include -#endif - -// Note the __clang__ check is needed, because clang presents itself -// as an older GNUC compiler (4.2). -// Clang 3.3 and later implement all of the ISO C++ 2011 standard. -// Clang 3.4 and later implement all of the ISO C++ 2014 standard. -// http://clang.llvm.org/cxx_status.html - -// Note the MSVC value '__cplusplus' may be incorrect: -// The '__cplusplus' predefined macro in the MSVC stuck at the value 199711L, -// indicating (erroneously!) that the compiler conformed to the C++98 Standard. -// This value should be correct starting from MSVC2017-15.7-Preview-3. -// The '__cplusplus' will be valid only if MSVC2017-15.7-P3 and the `/Zc:__cplusplus` switch is set. -// Workaround (for details see MSDN): -// Use the _MSC_VER and _MSVC_LANG definition instead of the __cplusplus for compatibility. -// The _MSVC_LANG macro reports the Standard version regardless of the '/Zc:__cplusplus' switch. - -#if defined(__GNUC__) && !defined(__clang__) - #define FLATBUFFERS_GCC (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) -#else - #define FLATBUFFERS_GCC 0 -#endif - -#if defined(__clang__) - #define FLATBUFFERS_CLANG (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) -#else - #define FLATBUFFERS_CLANG 0 -#endif - -/// @cond FLATBUFFERS_INTERNAL -#if __cplusplus <= 199711L && \ - (!defined(_MSC_VER) || _MSC_VER < 1600) && \ - (!defined(__GNUC__) || \ - (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ < 40400)) - #error A C++11 compatible compiler with support for the auto typing is \ - required for FlatBuffers. - #error __cplusplus _MSC_VER __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__ -#endif - -#if !defined(__clang__) && \ - defined(__GNUC__) && \ - (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ < 40600) - // Backwards compatibility for g++ 4.4, and 4.5 which don't have the nullptr - // and constexpr keywords. Note the __clang__ check is needed, because clang - // presents itself as an older GNUC compiler. - #ifndef nullptr_t - const class nullptr_t { - public: - template inline operator T*() const { return 0; } - private: - void operator&() const; - } nullptr = {}; - #endif - #ifndef constexpr - #define constexpr const - #endif -#endif - -// The wire format uses a little endian encoding (since that's efficient for -// the common platforms). -#if defined(__s390x__) - #define FLATBUFFERS_LITTLEENDIAN 0 -#endif // __s390x__ -#if !defined(FLATBUFFERS_LITTLEENDIAN) - #if defined(__GNUC__) || defined(__clang__) || defined(__ICCARM__) - #if (defined(__BIG_ENDIAN__) || \ - (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) - #define FLATBUFFERS_LITTLEENDIAN 0 - #else - #define FLATBUFFERS_LITTLEENDIAN 1 - #endif // __BIG_ENDIAN__ - #elif defined(_MSC_VER) - #if defined(_M_PPC) - #define FLATBUFFERS_LITTLEENDIAN 0 - #else - #define FLATBUFFERS_LITTLEENDIAN 1 - #endif - #else - #error Unable to determine endianness, define FLATBUFFERS_LITTLEENDIAN. - #endif -#endif // !defined(FLATBUFFERS_LITTLEENDIAN) - -#define FLATBUFFERS_VERSION_MAJOR 24 -#define FLATBUFFERS_VERSION_MINOR 3 -#define FLATBUFFERS_VERSION_REVISION 25 -#define FLATBUFFERS_STRING_EXPAND(X) #X -#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X) -namespace flatbuffers { - // Returns version as string "MAJOR.MINOR.REVISION". - const char* FLATBUFFERS_VERSION(); -} - -#if (!defined(_MSC_VER) || _MSC_VER > 1600) && \ - (!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 407)) || \ - defined(__clang__) - #define FLATBUFFERS_FINAL_CLASS final - #define FLATBUFFERS_OVERRIDE override - #define FLATBUFFERS_EXPLICIT_CPP11 explicit - #define FLATBUFFERS_VTABLE_UNDERLYING_TYPE : ::flatbuffers::voffset_t -#else - #define FLATBUFFERS_FINAL_CLASS - #define FLATBUFFERS_OVERRIDE - #define FLATBUFFERS_EXPLICIT_CPP11 - #define FLATBUFFERS_VTABLE_UNDERLYING_TYPE -#endif - -#if (!defined(_MSC_VER) || _MSC_VER >= 1900) && \ - (!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 406)) || \ - (defined(__cpp_constexpr) && __cpp_constexpr >= 200704) - #define FLATBUFFERS_CONSTEXPR constexpr - #define FLATBUFFERS_CONSTEXPR_CPP11 constexpr - #define FLATBUFFERS_CONSTEXPR_DEFINED -#else - #define FLATBUFFERS_CONSTEXPR const - #define FLATBUFFERS_CONSTEXPR_CPP11 -#endif - -#if (defined(__cplusplus) && __cplusplus >= 201402L) || \ - (defined(__cpp_constexpr) && __cpp_constexpr >= 201304) - #define FLATBUFFERS_CONSTEXPR_CPP14 FLATBUFFERS_CONSTEXPR_CPP11 -#else - #define FLATBUFFERS_CONSTEXPR_CPP14 -#endif - -#if (defined(__GXX_EXPERIMENTAL_CXX0X__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 406)) || \ - (defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 190023026)) || \ - defined(__clang__) - #define FLATBUFFERS_NOEXCEPT noexcept -#else - #define FLATBUFFERS_NOEXCEPT -#endif - -// NOTE: the FLATBUFFERS_DELETE_FUNC macro may change the access mode to -// private, so be sure to put it at the end or reset access mode explicitly. -#if (!defined(_MSC_VER) || _MSC_FULL_VER >= 180020827) && \ - (!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 404)) || \ - defined(__clang__) - #define FLATBUFFERS_DELETE_FUNC(func) func = delete -#else - #define FLATBUFFERS_DELETE_FUNC(func) private: func -#endif - -#if (!defined(_MSC_VER) || _MSC_VER >= 1900) && \ - (!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 409)) || \ - defined(__clang__) - #define FLATBUFFERS_DEFAULT_DECLARATION -#endif - -// Check if we can use template aliases -// Not possible if Microsoft Compiler before 2012 -// Possible is the language feature __cpp_alias_templates is defined well -// Or possible if the C++ std is C+11 or newer -#if (defined(_MSC_VER) && _MSC_VER > 1700 /* MSVC2012 */) \ - || (defined(__cpp_alias_templates) && __cpp_alias_templates >= 200704) \ - || (defined(__cplusplus) && __cplusplus >= 201103L) - #define FLATBUFFERS_TEMPLATES_ALIASES -#endif - -#ifndef FLATBUFFERS_HAS_STRING_VIEW - // Only provide flatbuffers::string_view if __has_include can be used - // to detect a header that provides an implementation - #if defined(__has_include) - // Check for std::string_view (in c++17) - #if __has_include() && (__cplusplus >= 201606 || (defined(_HAS_CXX17) && _HAS_CXX17)) - #include - namespace flatbuffers { - typedef std::string_view string_view; - } - #define FLATBUFFERS_HAS_STRING_VIEW 1 - // Check for std::experimental::string_view (in c++14, compiler-dependent) - #elif __has_include() && (__cplusplus >= 201411) - #include - namespace flatbuffers { - typedef std::experimental::string_view string_view; - } - #define FLATBUFFERS_HAS_STRING_VIEW 1 - // Check for absl::string_view - #elif __has_include("absl/strings/string_view.h") && \ - __has_include("absl/base/config.h") && \ - (__cplusplus >= 201411) - #include "absl/base/config.h" - #if !defined(ABSL_USES_STD_STRING_VIEW) - #include "absl/strings/string_view.h" - namespace flatbuffers { - typedef absl::string_view string_view; - } - #define FLATBUFFERS_HAS_STRING_VIEW 1 - #endif - #endif - #endif // __has_include -#endif // !FLATBUFFERS_HAS_STRING_VIEW - -#ifndef FLATBUFFERS_GENERAL_HEAP_ALLOC_OK - // Allow heap allocations to be used - #define FLATBUFFERS_GENERAL_HEAP_ALLOC_OK 1 -#endif // !FLATBUFFERS_GENERAL_HEAP_ALLOC_OK - -#ifndef FLATBUFFERS_HAS_NEW_STRTOD - // Modern (C++11) strtod and strtof functions are available for use. - // 1) nan/inf strings as argument of strtod; - // 2) hex-float as argument of strtod/strtof. - #if (defined(_MSC_VER) && _MSC_VER >= 1900) || \ - (defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 409)) || \ - (defined(__clang__)) - #define FLATBUFFERS_HAS_NEW_STRTOD 1 - #endif -#endif // !FLATBUFFERS_HAS_NEW_STRTOD - -#ifndef FLATBUFFERS_LOCALE_INDEPENDENT - // Enable locale independent functions {strtof_l, strtod_l,strtoll_l, - // strtoull_l}. - #if (defined(_MSC_VER) && _MSC_VER >= 1800) || \ - (defined(__ANDROID_API__) && __ANDROID_API__>= 21) || \ - (defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 700)) && \ - (!defined(__Fuchsia__) && !defined(__ANDROID_API__)) - #define FLATBUFFERS_LOCALE_INDEPENDENT 1 - #else - #define FLATBUFFERS_LOCALE_INDEPENDENT 0 - #endif -#endif // !FLATBUFFERS_LOCALE_INDEPENDENT - -// Suppress Undefined Behavior Sanitizer (recoverable only). Usage: -// - FLATBUFFERS_SUPPRESS_UBSAN("undefined") -// - FLATBUFFERS_SUPPRESS_UBSAN("signed-integer-overflow") -#if defined(__clang__) && (__clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >=7)) - #define FLATBUFFERS_SUPPRESS_UBSAN(type) __attribute__((no_sanitize(type))) -#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 409) - #define FLATBUFFERS_SUPPRESS_UBSAN(type) __attribute__((no_sanitize_undefined)) -#else - #define FLATBUFFERS_SUPPRESS_UBSAN(type) -#endif - -namespace flatbuffers { - // This is constexpr function used for checking compile-time constants. - // Avoid `#pragma warning(disable: 4127) // C4127: expression is constant`. - template FLATBUFFERS_CONSTEXPR inline bool IsConstTrue(T t) { - return !!t; - } -} - -// Enable C++ attribute [[]] if std:c++17 or higher. -#if ((__cplusplus >= 201703L) \ - || (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L))) - // All attributes unknown to an implementation are ignored without causing an error. - #define FLATBUFFERS_ATTRIBUTE(attr) attr - - #define FLATBUFFERS_FALLTHROUGH() [[fallthrough]] -#else - #define FLATBUFFERS_ATTRIBUTE(attr) - - #if FLATBUFFERS_CLANG >= 30800 - #define FLATBUFFERS_FALLTHROUGH() [[clang::fallthrough]] - #elif FLATBUFFERS_GCC >= 70300 - #define FLATBUFFERS_FALLTHROUGH() [[gnu::fallthrough]] - #else - #define FLATBUFFERS_FALLTHROUGH() - #endif -#endif - -/// @endcond - -/// @file -namespace flatbuffers { - -/// @cond FLATBUFFERS_INTERNAL -// Our default offset / size type, 32bit on purpose on 64bit systems. -// Also, using a consistent offset type maintains compatibility of serialized -// offset values between 32bit and 64bit systems. -typedef uint32_t uoffset_t; -typedef uint64_t uoffset64_t; - -// Signed offsets for references that can go in both directions. -typedef int32_t soffset_t; -typedef int64_t soffset64_t; - -// Offset/index used in v-tables, can be changed to uint8_t in -// format forks to save a bit of space if desired. -typedef uint16_t voffset_t; - -typedef uintmax_t largest_scalar_t; - -// In 32bits, this evaluates to 2GB - 1 -#define FLATBUFFERS_MAX_BUFFER_SIZE std::numeric_limits<::flatbuffers::soffset_t>::max() -#define FLATBUFFERS_MAX_64_BUFFER_SIZE std::numeric_limits<::flatbuffers::soffset64_t>::max() - -// The minimum size buffer that can be a valid flatbuffer. -// Includes the offset to the root table (uoffset_t), the offset to the vtable -// of the root table (soffset_t), the size of the vtable (uint16_t), and the -// size of the referring table (uint16_t). -#define FLATBUFFERS_MIN_BUFFER_SIZE sizeof(uoffset_t) + sizeof(soffset_t) + \ - sizeof(uint16_t) + sizeof(uint16_t) - -// We support aligning the contents of buffers up to this size. -#ifndef FLATBUFFERS_MAX_ALIGNMENT - #define FLATBUFFERS_MAX_ALIGNMENT 32 -#endif - -/// @brief The length of a FlatBuffer file header. -static const size_t kFileIdentifierLength = 4; - -inline bool VerifyAlignmentRequirements(size_t align, size_t min_align = 1) { - return (min_align <= align) && (align <= (FLATBUFFERS_MAX_ALIGNMENT)) && - (align & (align - 1)) == 0; // must be power of 2 -} - -#if defined(_MSC_VER) - #pragma warning(push) - #pragma warning(disable: 4127) // C4127: conditional expression is constant -#endif - -template T EndianSwap(T t) { - #if defined(_MSC_VER) - #define FLATBUFFERS_BYTESWAP16 _byteswap_ushort - #define FLATBUFFERS_BYTESWAP32 _byteswap_ulong - #define FLATBUFFERS_BYTESWAP64 _byteswap_uint64 - #elif defined(__ICCARM__) - #define FLATBUFFERS_BYTESWAP16 __REV16 - #define FLATBUFFERS_BYTESWAP32 __REV - #define FLATBUFFERS_BYTESWAP64(x) \ - ((__REV(static_cast(x >> 32U))) | (static_cast(__REV(static_cast(x)))) << 32U) - #else - #if defined(__GNUC__) && __GNUC__ * 100 + __GNUC_MINOR__ < 408 && !defined(__clang__) - // __builtin_bswap16 was missing prior to GCC 4.8. - #define FLATBUFFERS_BYTESWAP16(x) \ - static_cast(__builtin_bswap32(static_cast(x) << 16)) - #else - #define FLATBUFFERS_BYTESWAP16 __builtin_bswap16 - #endif - #define FLATBUFFERS_BYTESWAP32 __builtin_bswap32 - #define FLATBUFFERS_BYTESWAP64 __builtin_bswap64 - #endif - if (sizeof(T) == 1) { // Compile-time if-then's. - return t; - } else if (sizeof(T) == 2) { - union { T t; uint16_t i; } u = { t }; - u.i = FLATBUFFERS_BYTESWAP16(u.i); - return u.t; - } else if (sizeof(T) == 4) { - union { T t; uint32_t i; } u = { t }; - u.i = FLATBUFFERS_BYTESWAP32(u.i); - return u.t; - } else if (sizeof(T) == 8) { - union { T t; uint64_t i; } u = { t }; - u.i = FLATBUFFERS_BYTESWAP64(u.i); - return u.t; - } else { - FLATBUFFERS_ASSERT(0); - return t; - } -} - -#if defined(_MSC_VER) - #pragma warning(pop) -#endif - - -template T EndianScalar(T t) { - #if FLATBUFFERS_LITTLEENDIAN - return t; - #else - return EndianSwap(t); - #endif -} - -template -// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details. -FLATBUFFERS_SUPPRESS_UBSAN("alignment") -T ReadScalar(const void *p) { - return EndianScalar(*reinterpret_cast(p)); -} - -// See https://github.com/google/flatbuffers/issues/5950 - -#if (FLATBUFFERS_GCC >= 100000) && (FLATBUFFERS_GCC < 110000) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstringop-overflow" -#endif - -template -// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details. -FLATBUFFERS_SUPPRESS_UBSAN("alignment") -void WriteScalar(void *p, T t) { - *reinterpret_cast(p) = EndianScalar(t); -} - -template struct Offset; -template FLATBUFFERS_SUPPRESS_UBSAN("alignment") void WriteScalar(void *p, Offset t) { - *reinterpret_cast(p) = EndianScalar(t.o); -} - -#if (FLATBUFFERS_GCC >= 100000) && (FLATBUFFERS_GCC < 110000) - #pragma GCC diagnostic pop -#endif - -// Computes how many bytes you'd have to pad to be able to write an -// "scalar_size" scalar if the buffer had grown to "buf_size" (downwards in -// memory). -FLATBUFFERS_SUPPRESS_UBSAN("unsigned-integer-overflow") -inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) { - return ((~buf_size) + 1) & (scalar_size - 1); -} - -// Generic 'operator==' with conditional specialisations. -// T e - new value of a scalar field. -// T def - default of scalar (is known at compile-time). -template inline bool IsTheSameAs(T e, T def) { return e == def; } - -#if defined(FLATBUFFERS_NAN_DEFAULTS) && \ - defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) -// Like `operator==(e, def)` with weak NaN if T=(float|double). -template inline bool IsFloatTheSameAs(T e, T def) { - return (e == def) || ((def != def) && (e != e)); -} -template<> inline bool IsTheSameAs(float e, float def) { - return IsFloatTheSameAs(e, def); -} -template<> inline bool IsTheSameAs(double e, double def) { - return IsFloatTheSameAs(e, def); -} -#endif - -// Check 'v' is out of closed range [low; high]. -// Workaround for GCC warning [-Werror=type-limits]: -// comparison is always true due to limited range of data type. -template -inline bool IsOutRange(const T &v, const T &low, const T &high) { - return (v < low) || (high < v); -} - -// Check 'v' is in closed range [low; high]. -template -inline bool IsInRange(const T &v, const T &low, const T &high) { - return !IsOutRange(v, low, high); -} - -} // namespace flatbuffers -#endif // FLATBUFFERS_BASE_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/buffer.h b/third_party/flatbuffers/include/flatbuffers/buffer.h deleted file mode 100644 index 94d4f7903be..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/buffer.h +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2021 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_BUFFER_H_ -#define FLATBUFFERS_BUFFER_H_ - -#include - -#include "flatbuffers/base.h" - -namespace flatbuffers { - -// Wrapper for uoffset_t to allow safe template specialization. -// Value is allowed to be 0 to indicate a null object (see e.g. AddOffset). -template struct Offset { - // The type of offset to use. - typedef uoffset_t offset_type; - - offset_type o; - Offset() : o(0) {} - Offset(const offset_type _o) : o(_o) {} - Offset<> Union() const { return o; } - bool IsNull() const { return !o; } -}; - -// Wrapper for uoffset64_t Offsets. -template struct Offset64 { - // The type of offset to use. - typedef uoffset64_t offset_type; - - offset_type o; - Offset64() : o(0) {} - Offset64(const offset_type offset) : o(offset) {} - Offset64<> Union() const { return o; } - bool IsNull() const { return !o; } -}; - -// Litmus check for ensuring the Offsets are the expected size. -static_assert(sizeof(Offset<>) == 4, "Offset has wrong size"); -static_assert(sizeof(Offset64<>) == 8, "Offset64 has wrong size"); - -inline void EndianCheck() { - int endiantest = 1; - // If this fails, see FLATBUFFERS_LITTLEENDIAN above. - FLATBUFFERS_ASSERT(*reinterpret_cast(&endiantest) == - FLATBUFFERS_LITTLEENDIAN); - (void)endiantest; -} - -template FLATBUFFERS_CONSTEXPR size_t AlignOf() { - // clang-format off - #ifdef _MSC_VER - return __alignof(T); - #else - #ifndef alignof - return __alignof__(T); - #else - return alignof(T); - #endif - #endif - // clang-format on -} - -// Lexicographically compare two strings (possibly containing nulls), and -// return true if the first is less than the second. -static inline bool StringLessThan(const char *a_data, uoffset_t a_size, - const char *b_data, uoffset_t b_size) { - const auto cmp = memcmp(a_data, b_data, (std::min)(a_size, b_size)); - return cmp == 0 ? a_size < b_size : cmp < 0; -} - -// When we read serialized data from memory, in the case of most scalars, -// we want to just read T, but in the case of Offset, we want to actually -// perform the indirection and return a pointer. -// The template specialization below does just that. -// It is wrapped in a struct since function templates can't overload on the -// return type like this. -// The typedef is for the convenience of callers of this function -// (avoiding the need for a trailing return decltype) -template struct IndirectHelper { - typedef T return_type; - typedef T mutable_return_type; - static const size_t element_stride = sizeof(T); - - static return_type Read(const uint8_t *p, const size_t i) { - return EndianScalar((reinterpret_cast(p))[i]); - } - static mutable_return_type Read(uint8_t *p, const size_t i) { - return reinterpret_cast( - Read(const_cast(p), i)); - } -}; - -// For vector of Offsets. -template class OffsetT> -struct IndirectHelper> { - typedef const T *return_type; - typedef T *mutable_return_type; - typedef typename OffsetT::offset_type offset_type; - static const offset_type element_stride = sizeof(offset_type); - - static return_type Read(const uint8_t *const p, const offset_type i) { - // Offsets are relative to themselves, so first update the pointer to - // point to the offset location. - const uint8_t *const offset_location = p + i * element_stride; - - // Then read the scalar value of the offset (which may be 32 or 64-bits) and - // then determine the relative location from the offset location. - return reinterpret_cast( - offset_location + ReadScalar(offset_location)); - } - static mutable_return_type Read(uint8_t *const p, const offset_type i) { - // Offsets are relative to themselves, so first update the pointer to - // point to the offset location. - uint8_t *const offset_location = p + i * element_stride; - - // Then read the scalar value of the offset (which may be 32 or 64-bits) and - // then determine the relative location from the offset location. - return reinterpret_cast( - offset_location + ReadScalar(offset_location)); - } -}; - -// For vector of structs. -template struct IndirectHelper { - typedef const T *return_type; - typedef T *mutable_return_type; - static const size_t element_stride = sizeof(T); - - static return_type Read(const uint8_t *const p, const size_t i) { - // Structs are stored inline, relative to the first struct pointer. - return reinterpret_cast(p + i * element_stride); - } - static mutable_return_type Read(uint8_t *const p, const size_t i) { - // Structs are stored inline, relative to the first struct pointer. - return reinterpret_cast(p + i * element_stride); - } -}; - -/// @brief Get a pointer to the file_identifier section of the buffer. -/// @return Returns a const char pointer to the start of the file_identifier -/// characters in the buffer. The returned char * has length -/// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'. -/// This function is UNDEFINED for FlatBuffers whose schema does not include -/// a file_identifier (likely points at padding or the start of a the root -/// vtable). -inline const char *GetBufferIdentifier(const void *buf, - bool size_prefixed = false) { - return reinterpret_cast(buf) + - ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t)); -} - -// Helper to see if the identifier in a buffer has the expected value. -inline bool BufferHasIdentifier(const void *buf, const char *identifier, - bool size_prefixed = false) { - return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier, - flatbuffers::kFileIdentifierLength) == 0; -} - -/// @cond FLATBUFFERS_INTERNAL -// Helpers to get a typed pointer to the root object contained in the buffer. -template T *GetMutableRoot(void *buf) { - if (!buf) return nullptr; - EndianCheck(); - return reinterpret_cast( - reinterpret_cast(buf) + - EndianScalar(*reinterpret_cast(buf))); -} - -template -T *GetMutableSizePrefixedRoot(void *buf) { - return GetMutableRoot(reinterpret_cast(buf) + sizeof(SizeT)); -} - -template const T *GetRoot(const void *buf) { - return GetMutableRoot(const_cast(buf)); -} - -template -const T *GetSizePrefixedRoot(const void *buf) { - return GetRoot(reinterpret_cast(buf) + sizeof(SizeT)); -} - -} // namespace flatbuffers - -#endif // FLATBUFFERS_BUFFER_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/buffer_ref.h b/third_party/flatbuffers/include/flatbuffers/buffer_ref.h deleted file mode 100644 index f70941fc64d..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/buffer_ref.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2021 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_BUFFER_REF_H_ -#define FLATBUFFERS_BUFFER_REF_H_ - -#include "flatbuffers/base.h" -#include "flatbuffers/verifier.h" - -namespace flatbuffers { - -// Convenient way to bundle a buffer and its length, to pass it around -// typed by its root. -// A BufferRef does not own its buffer. -struct BufferRefBase {}; // for std::is_base_of - -template struct BufferRef : BufferRefBase { - BufferRef() : buf(nullptr), len(0), must_free(false) {} - BufferRef(uint8_t *_buf, uoffset_t _len) - : buf(_buf), len(_len), must_free(false) {} - - ~BufferRef() { - if (must_free) free(buf); - } - - const T *GetRoot() const { return flatbuffers::GetRoot(buf); } - - bool Verify() { - Verifier verifier(buf, len); - return verifier.VerifyBuffer(nullptr); - } - - uint8_t *buf; - uoffset_t len; - bool must_free; -}; - -} // namespace flatbuffers - -#endif // FLATBUFFERS_BUFFER_REF_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/code_generator.h b/third_party/flatbuffers/include/flatbuffers/code_generator.h deleted file mode 100644 index 2971e556eec..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/code_generator.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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_CODE_GENERATOR_H_ -#define FLATBUFFERS_CODE_GENERATOR_H_ - -#include - -#include "flatbuffers/idl.h" - -namespace flatbuffers { - -struct CodeGenOptions { - std::string output_path; -}; - -// A code generator interface for producing converting flatbuffer schema into -// code. -class CodeGenerator { - public: - virtual ~CodeGenerator() = default; - - enum Status { - OK = 0, - ERROR = 1, - FAILED_VERIFICATION = 2, - NOT_IMPLEMENTED = 3 - }; - - std::string status_detail; - - // Generate code from the provided `parser`. - // - // DEPRECATED: prefer using the other overload of GenerateCode for bfbs. - virtual Status GenerateCode(const Parser &parser, const std::string &path, - const std::string &filename) = 0; - - // Generate code from the provided `parser` and place it in the output. - virtual Status GenerateCodeString(const Parser &parser, - const std::string &filename, - std::string &output) { - (void)parser; - (void)filename; - (void)output; - return Status::NOT_IMPLEMENTED; - } - - // Generate code from the provided `buffer` of given `length`. The buffer is a - // serialized reflection.fbs. - virtual Status GenerateCode(const uint8_t *buffer, int64_t length, - const CodeGenOptions &options) = 0; - - virtual Status GenerateMakeRule(const Parser &parser, const std::string &path, - const std::string &filename, - std::string &output) = 0; - - 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: - CodeGenerator() = default; - - private: - // Copying is not supported. - CodeGenerator(const CodeGenerator &) = delete; - CodeGenerator &operator=(const CodeGenerator &) = delete; -}; - -} // namespace flatbuffers - -#endif // FLATBUFFERS_CODE_GENERATOR_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/code_generators.h b/third_party/flatbuffers/include/flatbuffers/code_generators.h deleted file mode 100644 index fc030d43943..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/code_generators.h +++ /dev/null @@ -1,238 +0,0 @@ -/* - * 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. - */ - -#ifndef FLATBUFFERS_CODE_GENERATORS_H_ -#define FLATBUFFERS_CODE_GENERATORS_H_ - -#include -#include - -#include "flatbuffers/idl.h" - -namespace flatbuffers { - -// Utility class to assist in generating code through use of text templates. -// -// Example code: -// CodeWriter code("\t"); -// code.SetValue("NAME", "Foo"); -// code += "void {{NAME}}() { printf("%s", "{{NAME}}"); }"; -// code.SetValue("NAME", "Bar"); -// code += "void {{NAME}}() { printf("%s", "{{NAME}}"); }"; -// std::cout << code.ToString() << std::endl; -// -// Output: -// void Foo() { printf("%s", "Foo"); } -// void Bar() { printf("%s", "Bar"); } -class CodeWriter { - public: - CodeWriter(std::string pad = std::string()) - : pad_(pad), cur_ident_lvl_(0), ignore_ident_(false) {} - - // Clears the current "written" code. - void Clear() { - stream_.str(""); - stream_.clear(); - } - - // Associates a key with a value. All subsequent calls to operator+=, where - // the specified key is contained in {{ and }} delimiters will be replaced by - // the given value. - void SetValue(const std::string &key, const std::string &value) { - value_map_[key] = value; - } - - std::string GetValue(const std::string &key) const { - const auto it = value_map_.find(key); - return it == value_map_.end() ? "" : it->second; - } - - // Appends the given text to the generated code as well as a newline - // character. Any text within {{ and }} delimiters is replaced by values - // previously stored in the CodeWriter by calling SetValue above. The newline - // will be suppressed if the text ends with the \\ character. - void operator+=(std::string text); - - // Returns the current contents of the CodeWriter as a std::string. - std::string ToString() const { return stream_.str(); } - - // Increase ident level for writing code - void IncrementIdentLevel() { cur_ident_lvl_++; } - // Decrease ident level for writing code - void DecrementIdentLevel() { - if (cur_ident_lvl_) cur_ident_lvl_--; - } - - void SetPadding(const std::string &padding) { pad_ = padding; } - - private: - std::map value_map_; - std::stringstream stream_; - std::string pad_; - int cur_ident_lvl_; - bool ignore_ident_; - - // Add ident padding (tab or space) based on ident level - void AppendIdent(std::stringstream &stream); -}; - -class BaseGenerator { - public: - virtual bool generate() = 0; - - static std::string NamespaceDir(const Parser &parser, const std::string &path, - const Namespace &ns, - const bool dasherize = false); - - std::string GeneratedFileName(const std::string &path, - const std::string &file_name, - const IDLOptions &options) const; - - protected: - BaseGenerator(const Parser &parser, const std::string &path, - const std::string &file_name, std::string qualifying_start, - std::string qualifying_separator, std::string default_extension) - : parser_(parser), - path_(path), - file_name_(file_name), - qualifying_start_(qualifying_start), - qualifying_separator_(qualifying_separator), - default_extension_(default_extension) {} - virtual ~BaseGenerator() {} - - // No copy/assign. - BaseGenerator &operator=(const BaseGenerator &); - BaseGenerator(const BaseGenerator &); - - std::string NamespaceDir(const Namespace &ns, - const bool dasherize = false) const; - - static const char *FlatBuffersGeneratedWarning(); - - static std::string FullNamespace(const char *separator, const Namespace &ns); - - static std::string LastNamespacePart(const Namespace &ns); - - // tracks the current namespace for early exit in WrapInNameSpace - // c++, java and csharp returns a different namespace from - // the following default (no early exit, always fully qualify), - // which works for js and php - virtual const Namespace *CurrentNameSpace() const { return nullptr; } - - // Ensure that a type is prefixed with its namespace even within - // its own namespace to avoid conflict between generated method - // names and similarly named classes or structs - std::string WrapInNameSpace(const Namespace *ns, - const std::string &name) const; - - std::string WrapInNameSpace(const Definition &def, - const std::string &suffix = "") const; - - std::string GetNameSpace(const Definition &def) const; - - const Parser &parser_; - const std::string &path_; - const std::string &file_name_; - const std::string qualifying_start_; - const std::string qualifying_separator_; - const std::string default_extension_; -}; - -struct CommentConfig { - const char *first_line; - const char *content_line_prefix; - const char *last_line; -}; - -extern void GenComment(const std::vector &dc, - std::string *code_ptr, const CommentConfig *config, - const char *prefix = ""); - -class FloatConstantGenerator { - public: - virtual ~FloatConstantGenerator() {} - std::string GenFloatConstant(const FieldDef &field) const; - - private: - virtual std::string Value(double v, const std::string &src) const = 0; - virtual std::string Inf(double v) const = 0; - virtual std::string NaN(double v) const = 0; - - virtual std::string Value(float v, const std::string &src) const = 0; - virtual std::string Inf(float v) const = 0; - virtual std::string NaN(float v) const = 0; - - template - std::string GenFloatConstantImpl(const FieldDef &field) const; -}; - -class SimpleFloatConstantGenerator : public FloatConstantGenerator { - public: - SimpleFloatConstantGenerator(const char *nan_number, - const char *pos_inf_number, - const char *neg_inf_number); - - private: - std::string Value(double v, - const std::string &src) const FLATBUFFERS_OVERRIDE; - std::string Inf(double v) const FLATBUFFERS_OVERRIDE; - std::string NaN(double v) const FLATBUFFERS_OVERRIDE; - - std::string Value(float v, const std::string &src) const FLATBUFFERS_OVERRIDE; - std::string Inf(float v) const FLATBUFFERS_OVERRIDE; - std::string NaN(float v) const FLATBUFFERS_OVERRIDE; - - const std::string nan_number_; - const std::string pos_inf_number_; - const std::string neg_inf_number_; -}; - -// C++, C#, Java like generator. -class TypedFloatConstantGenerator : public FloatConstantGenerator { - public: - TypedFloatConstantGenerator(const char *double_prefix, - const char *single_prefix, const char *nan_number, - const char *pos_inf_number, - const char *neg_inf_number = ""); - - private: - std::string Value(double v, - const std::string &src) const FLATBUFFERS_OVERRIDE; - std::string Inf(double v) const FLATBUFFERS_OVERRIDE; - - std::string NaN(double v) const FLATBUFFERS_OVERRIDE; - - std::string Value(float v, const std::string &src) const FLATBUFFERS_OVERRIDE; - std::string Inf(float v) const FLATBUFFERS_OVERRIDE; - std::string NaN(float v) const FLATBUFFERS_OVERRIDE; - - std::string MakeNaN(const std::string &prefix) const; - std::string MakeInf(bool neg, const std::string &prefix) const; - - const std::string double_prefix_; - const std::string single_prefix_; - const std::string nan_number_; - const std::string pos_inf_number_; - const std::string neg_inf_number_; -}; - -std::string JavaCSharpMakeRule(const bool java, const Parser &parser, - const std::string &path, - const std::string &file_name); - -} // namespace flatbuffers - -#endif // FLATBUFFERS_CODE_GENERATORS_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/default_allocator.h b/third_party/flatbuffers/include/flatbuffers/default_allocator.h deleted file mode 100644 index d4724122cb5..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/default_allocator.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2021 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_DEFAULT_ALLOCATOR_H_ -#define FLATBUFFERS_DEFAULT_ALLOCATOR_H_ - -#include "flatbuffers/allocator.h" -#include "flatbuffers/base.h" - -namespace flatbuffers { - -// DefaultAllocator uses new/delete to allocate memory regions -class DefaultAllocator : public Allocator { - public: - uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE { - return new uint8_t[size]; - } - - void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; } - - static void dealloc(void *p, size_t) { delete[] static_cast(p); } -}; - -// These functions allow for a null allocator to mean use the default allocator, -// as used by DetachedBuffer and vector_downward below. -// This is to avoid having a statically or dynamically allocated default -// allocator, or having to move it between the classes that may own it. -inline uint8_t *Allocate(Allocator *allocator, size_t size) { - return allocator ? allocator->allocate(size) - : DefaultAllocator().allocate(size); -} - -inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) { - if (allocator) - allocator->deallocate(p, size); - else - DefaultAllocator().deallocate(p, size); -} - -inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p, - size_t old_size, size_t new_size, - size_t in_use_back, size_t in_use_front) { - return allocator ? allocator->reallocate_downward(old_p, old_size, new_size, - in_use_back, in_use_front) - : DefaultAllocator().reallocate_downward( - old_p, old_size, new_size, in_use_back, in_use_front); -} - -} // namespace flatbuffers - -#endif // FLATBUFFERS_DEFAULT_ALLOCATOR_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/detached_buffer.h b/third_party/flatbuffers/include/flatbuffers/detached_buffer.h deleted file mode 100644 index 5e900baeb57..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/detached_buffer.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2021 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_DETACHED_BUFFER_H_ -#define FLATBUFFERS_DETACHED_BUFFER_H_ - -#include "flatbuffers/allocator.h" -#include "flatbuffers/base.h" -#include "flatbuffers/default_allocator.h" - -namespace flatbuffers { - -// DetachedBuffer is a finished flatbuffer memory region, detached from its -// builder. The original memory region and allocator are also stored so that -// the DetachedBuffer can manage the memory lifetime. -class DetachedBuffer { - public: - DetachedBuffer() - : allocator_(nullptr), - own_allocator_(false), - buf_(nullptr), - reserved_(0), - cur_(nullptr), - size_(0) {} - - DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf, - size_t reserved, uint8_t *cur, size_t sz) - : allocator_(allocator), - own_allocator_(own_allocator), - buf_(buf), - reserved_(reserved), - cur_(cur), - size_(sz) {} - - DetachedBuffer(DetachedBuffer &&other) noexcept - : allocator_(other.allocator_), - own_allocator_(other.own_allocator_), - buf_(other.buf_), - reserved_(other.reserved_), - cur_(other.cur_), - size_(other.size_) { - other.reset(); - } - - DetachedBuffer &operator=(DetachedBuffer &&other) noexcept { - if (this == &other) return *this; - - destroy(); - - allocator_ = other.allocator_; - own_allocator_ = other.own_allocator_; - buf_ = other.buf_; - reserved_ = other.reserved_; - cur_ = other.cur_; - size_ = other.size_; - - other.reset(); - - return *this; - } - - ~DetachedBuffer() { destroy(); } - - const uint8_t *data() const { return cur_; } - - uint8_t *data() { return cur_; } - - size_t size() const { return size_; } - - // These may change access mode, leave these at end of public section - FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other)); - FLATBUFFERS_DELETE_FUNC( - DetachedBuffer &operator=(const DetachedBuffer &other)); - - protected: - Allocator *allocator_; - bool own_allocator_; - uint8_t *buf_; - size_t reserved_; - uint8_t *cur_; - size_t size_; - - inline void destroy() { - if (buf_) Deallocate(allocator_, buf_, reserved_); - if (own_allocator_ && allocator_) { delete allocator_; } - reset(); - } - - inline void reset() { - allocator_ = nullptr; - own_allocator_ = false; - buf_ = nullptr; - reserved_ = 0; - cur_ = nullptr; - size_ = 0; - } -}; - -} // namespace flatbuffers - -#endif // FLATBUFFERS_DETACHED_BUFFER_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/file_manager.h b/third_party/flatbuffers/include/flatbuffers/file_manager.h deleted file mode 100644 index 069df5b8842..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/file_manager.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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_FILE_MANAGER_H_ -#define FLATBUFFERS_FILE_MANAGER_H_ - -#include -#include - -#include "flatbuffers/util.h" - -namespace flatbuffers { - -// A File interface to write data to file by default or -// save only file names -class FileManager { - public: - FileManager() = default; - virtual ~FileManager() = default; - - virtual bool SaveFile(const std::string &absolute_file_name, - const std::string &content) = 0; - - virtual bool LoadFile(const std::string &absolute_file_name, - std::string *buf) = 0; - - private: - // Copying is not supported. - FileManager(const FileManager &) = delete; - FileManager &operator=(const FileManager &) = delete; -}; - -} // namespace flatbuffers - -#endif // FLATBUFFERS_FILE_MANAGER_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h b/third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h deleted file mode 100644 index 9a2d62541bd..00000000000 --- a/third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h +++ /dev/null @@ -1,1478 +0,0 @@ -/* - * Copyright 2021 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_FLATBUFFER_BUILDER_H_ -#define FLATBUFFERS_FLATBUFFER_BUILDER_H_ - -#include -#include -#include -#include -#include - -#include "flatbuffers/allocator.h" -#include "flatbuffers/array.h" -#include "flatbuffers/base.h" -#include "flatbuffers/buffer.h" -#include "flatbuffers/buffer_ref.h" -#include "flatbuffers/default_allocator.h" -#include "flatbuffers/detached_buffer.h" -#include "flatbuffers/stl_emulation.h" -#include "flatbuffers/string.h" -#include "flatbuffers/struct.h" -#include "flatbuffers/table.h" -#include "flatbuffers/vector.h" -#include "flatbuffers/vector_downward.h" -#include "flatbuffers/verifier.h" - -namespace flatbuffers { - -// Converts a Field ID to a virtual table offset. -inline voffset_t FieldIndexToOffset(voffset_t field_id) { - // Should correspond to what EndTable() below builds up. - const voffset_t fixed_fields = - 2 * sizeof(voffset_t); // Vtable size and Object Size. - size_t offset = fixed_fields + field_id * sizeof(voffset_t); - FLATBUFFERS_ASSERT(offset < std::numeric_limits::max()); - return static_cast(offset);} - -template> -const T *data(const std::vector &v) { - // Eventually the returned pointer gets passed down to memcpy, so - // we need it to be non-null to avoid undefined behavior. - static uint8_t t; - return v.empty() ? reinterpret_cast(&t) : &v.front(); -} -template> -T *data(std::vector &v) { - // Eventually the returned pointer gets passed down to memcpy, so - // we need it to be non-null to avoid undefined behavior. - static uint8_t t; - return v.empty() ? reinterpret_cast(&t) : &v.front(); -} - -/// @addtogroup flatbuffers_cpp_api -/// @{ -/// @class FlatBufferBuilder -/// @brief Helper class to hold data needed in creation of a FlatBuffer. -/// To serialize data, you typically call one of the `Create*()` functions in -/// the generated code, which in turn call a sequence of `StartTable`/ -/// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/ -/// `CreateVector` functions. Do this is depth-first order to build up a tree to -/// the root. `Finish()` wraps up the buffer ready for transport. -template class FlatBufferBuilderImpl { - public: - // This switches the size type of the builder, based on if its 64-bit aware - // (uoffset64_t) or not (uoffset_t). - typedef - typename std::conditional::type SizeT; - - /// @brief Default constructor for FlatBufferBuilder. - /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults - /// to `1024`. - /// @param[in] allocator An `Allocator` to use. If null will use - /// `DefaultAllocator`. - /// @param[in] own_allocator Whether the builder/vector should own the - /// allocator. Defaults to / `false`. - /// @param[in] buffer_minalign Force the buffer to be aligned to the given - /// minimum alignment upon reallocation. Only needed if you intend to store - /// types with custom alignment AND you wish to read the buffer in-place - /// directly after creation. - explicit FlatBufferBuilderImpl( - size_t initial_size = 1024, Allocator *allocator = nullptr, - bool own_allocator = false, - size_t buffer_minalign = AlignOf()) - : buf_(initial_size, allocator, own_allocator, buffer_minalign, - static_cast(Is64Aware ? FLATBUFFERS_MAX_64_BUFFER_SIZE - : FLATBUFFERS_MAX_BUFFER_SIZE)), - num_field_loc(0), - max_voffset_(0), - length_of_64_bit_region_(0), - nested(false), - finished(false), - minalign_(1), - force_defaults_(false), - dedup_vtables_(true), - string_pool(nullptr) { - EndianCheck(); - } - - /// @brief Move constructor for FlatBufferBuilder. - FlatBufferBuilderImpl(FlatBufferBuilderImpl &&other) noexcept - : buf_(1024, nullptr, false, AlignOf(), - static_cast(Is64Aware ? FLATBUFFERS_MAX_64_BUFFER_SIZE - : FLATBUFFERS_MAX_BUFFER_SIZE)), - num_field_loc(0), - max_voffset_(0), - length_of_64_bit_region_(0), - nested(false), - finished(false), - minalign_(1), - force_defaults_(false), - dedup_vtables_(true), - string_pool(nullptr) { - EndianCheck(); - // Default construct and swap idiom. - // Lack of delegating constructors in vs2010 makes it more verbose than - // needed. - Swap(other); - } - - /// @brief Move assignment operator for FlatBufferBuilder. - FlatBufferBuilderImpl &operator=(FlatBufferBuilderImpl &&other) noexcept { - // Move construct a temporary and swap idiom - FlatBufferBuilderImpl temp(std::move(other)); - Swap(temp); - return *this; - } - - void Swap(FlatBufferBuilderImpl &other) { - using std::swap; - buf_.swap(other.buf_); - swap(num_field_loc, other.num_field_loc); - swap(max_voffset_, other.max_voffset_); - swap(length_of_64_bit_region_, other.length_of_64_bit_region_); - swap(nested, other.nested); - swap(finished, other.finished); - swap(minalign_, other.minalign_); - swap(force_defaults_, other.force_defaults_); - swap(dedup_vtables_, other.dedup_vtables_); - swap(string_pool, other.string_pool); - } - - ~FlatBufferBuilderImpl() { - if (string_pool) delete string_pool; - } - - void Reset() { - Clear(); // clear builder state - buf_.reset(); // deallocate buffer - } - - /// @brief Reset all the state in this FlatBufferBuilder so it can be reused - /// to construct another buffer. - void Clear() { - ClearOffsets(); - buf_.clear(); - nested = false; - finished = false; - minalign_ = 1; - length_of_64_bit_region_ = 0; - if (string_pool) string_pool->clear(); - } - - /// @brief The current size of the serialized buffer, counting from the end. - /// @return Returns an `SizeT` with the current size of the buffer. - SizeT GetSize() const { return buf_.size(); } - - /// @brief The current size of the serialized buffer relative to the end of - /// the 32-bit region. - /// @return Returns an `uoffset_t` with the current size of the buffer. - template - // Only enable this method for the 64-bit builder, as only that builder is - // concerned with the 32/64-bit boundary, and should be the one to bare any - // run time costs. - typename std::enable_if::type GetSizeRelative32BitRegion() - const { - //[32-bit region][64-bit region] - // [XXXXXXXXXXXXXXXXXXX] GetSize() - // [YYYYYYYYYYYYY] length_of_64_bit_region_ - // [ZZZZ] return size - return static_cast(GetSize() - length_of_64_bit_region_); - } - - template - // Only enable this method for the 32-bit builder. - typename std::enable_if::type GetSizeRelative32BitRegion() - const { - return static_cast(GetSize()); - } - - /// @brief Get the serialized buffer (after you call `Finish()`). - /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the - /// buffer. - uint8_t *GetBufferPointer() const { - Finished(); - return buf_.data(); - } - - /// @brief Get the serialized buffer (after you call `Finish()`) as a span. - /// @return Returns a constructed flatbuffers::span that is a view over the - /// FlatBuffer data inside the buffer. - flatbuffers::span GetBufferSpan() const { - Finished(); - return flatbuffers::span(buf_.data(), buf_.size()); - } - - /// @brief Get a pointer to an unfinished buffer. - /// @return Returns a `uint8_t` pointer to the unfinished buffer. - uint8_t *GetCurrentBufferPointer() const { return buf_.data(); } - - /// @brief Get the released DetachedBuffer. - /// @return A `DetachedBuffer` that owns the buffer and its allocator. - DetachedBuffer Release() { - Finished(); - DetachedBuffer buffer = buf_.release(); - Clear(); - return buffer; - } - - /// @brief Get the released pointer to the serialized buffer. - /// @param size The size of the memory block containing - /// the serialized `FlatBuffer`. - /// @param offset The offset from the released pointer where the finished - /// `FlatBuffer` starts. - /// @return A raw pointer to the start of the memory block containing - /// the serialized `FlatBuffer`. - /// @remark If the allocator is owned, it gets deleted when the destructor is - /// called. - uint8_t *ReleaseRaw(size_t &size, size_t &offset) { - Finished(); - uint8_t* raw = buf_.release_raw(size, offset); - Clear(); - return raw; - } - - /// @brief get the minimum alignment this buffer needs to be accessed - /// properly. This is only known once all elements have been written (after - /// you call Finish()). You can use this information if you need to embed - /// a FlatBuffer in some other buffer, such that you can later read it - /// without first having to copy it into its own buffer. - size_t GetBufferMinAlignment() const { - Finished(); - return minalign_; - } - - /// @cond FLATBUFFERS_INTERNAL - void Finished() const { - // If you get this assert, you're attempting to get access a buffer - // which hasn't been finished yet. Be sure to call - // FlatBufferBuilder::Finish with your root table. - // If you really need to access an unfinished buffer, call - // GetCurrentBufferPointer instead. - FLATBUFFERS_ASSERT(finished); - } - /// @endcond - - /// @brief In order to save space, fields that are set to their default value - /// don't get serialized into the buffer. - /// @param[in] fd When set to `true`, always serializes default values that - /// are set. Optional fields which are not set explicitly, will still not be - /// serialized. - void ForceDefaults(bool fd) { force_defaults_ = fd; } - - /// @brief By default vtables are deduped in order to save space. - /// @param[in] dedup When set to `true`, dedup vtables. - void DedupVtables(bool dedup) { dedup_vtables_ = dedup; } - - /// @cond FLATBUFFERS_INTERNAL - void Pad(size_t num_bytes) { buf_.fill(num_bytes); } - - void TrackMinAlign(size_t elem_size) { - if (elem_size > minalign_) minalign_ = elem_size; - } - - void Align(size_t elem_size) { - TrackMinAlign(elem_size); - buf_.fill(PaddingBytes(buf_.size(), elem_size)); - } - - void PushFlatBuffer(const uint8_t *bytes, size_t size) { - PushBytes(bytes, size); - finished = true; - } - - void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); } - - void PopBytes(size_t amount) { buf_.pop(amount); } - - template void AssertScalarT() { - // The code assumes power of 2 sizes and endian-swap-ability. - static_assert(flatbuffers::is_scalar::value, "T must be a scalar type"); - } - - // Write a single aligned scalar to the buffer - template - ReturnT PushElement(T element) { - AssertScalarT(); - Align(sizeof(T)); - buf_.push_small(EndianScalar(element)); - return CalculateOffset(); - } - - template class OffsetT = Offset> - uoffset_t PushElement(OffsetT off) { - // Special case for offsets: see ReferTo below. - return PushElement(ReferTo(off.o)); - } - - // When writing fields, we track where they are, so we can create correct - // vtables later. - void TrackField(voffset_t field, uoffset_t off) { - FieldLoc fl = { off, field }; - buf_.scratch_push_small(fl); - num_field_loc++; - if (field > max_voffset_) { max_voffset_ = field; } - } - - // Like PushElement, but additionally tracks the field this represents. - template void AddElement(voffset_t field, T e, T def) { - // We don't serialize values equal to the default. - if (IsTheSameAs(e, def) && !force_defaults_) return; - TrackField(field, PushElement(e)); - } - - template void AddElement(voffset_t field, T e) { - TrackField(field, PushElement(e)); - } - - template void AddOffset(voffset_t field, Offset off) { - if (off.IsNull()) return; // Don't store. - AddElement(field, ReferTo(off.o), static_cast(0)); - } - - template void AddOffset(voffset_t field, Offset64 off) { - if (off.IsNull()) return; // Don't store. - AddElement(field, ReferTo(off.o), static_cast(0)); - } - - template void AddStruct(voffset_t field, const T *structptr) { - if (!structptr) return; // Default, don't store. - Align(AlignOf()); - buf_.push_small(*structptr); - TrackField(field, CalculateOffset()); - } - - void AddStructOffset(voffset_t field, uoffset_t off) { - TrackField(field, off); - } - - // Offsets initially are relative to the end of the buffer (downwards). - // This function converts them to be relative to the current location - // in the buffer (when stored here), pointing upwards. - uoffset_t ReferTo(uoffset_t off) { - // Align to ensure GetSizeRelative32BitRegion() below is correct. - Align(sizeof(uoffset_t)); - // 32-bit offsets are relative to the tail of the 32-bit region of the - // buffer. For most cases (without 64-bit entities) this is equivalent to - // size of the whole buffer (e.g. GetSize()) - return ReferTo(off, GetSizeRelative32BitRegion()); - } - - uoffset64_t ReferTo(uoffset64_t off) { - // Align to ensure GetSize() below is correct. - Align(sizeof(uoffset64_t)); - // 64-bit offsets are relative to tail of the whole buffer - return ReferTo(off, GetSize()); - } - - template T ReferTo(const T off, const T2 size) { - FLATBUFFERS_ASSERT(off && off <= size); - return size - off + static_cast(sizeof(T)); - } - - template T ReferTo(const T off, const T size) { - FLATBUFFERS_ASSERT(off && off <= size); - return size - off + static_cast(sizeof(T)); - } - - void NotNested() { - // If you hit this, you're trying to construct a Table/Vector/String - // during the construction of its parent table (between the MyTableBuilder - // and table.Finish(). - // Move the creation of these sub-objects to above the MyTableBuilder to - // not get this assert. - // Ignoring this assert may appear to work in simple cases, but the reason - // it is here is that storing objects in-line may cause vtable offsets - // to not fit anymore. It also leads to vtable duplication. - FLATBUFFERS_ASSERT(!nested); - // If you hit this, fields were added outside the scope of a table. - FLATBUFFERS_ASSERT(!num_field_loc); - } - - // From generated code (or from the parser), we call StartTable/EndTable - // with a sequence of AddElement calls in between. - uoffset_t StartTable() { - NotNested(); - nested = true; - return GetSizeRelative32BitRegion(); - } - - // This finishes one serialized object by generating the vtable if it's a - // table, comparing it against existing vtables, and writing the - // resulting vtable offset. - uoffset_t EndTable(uoffset_t start) { - // If you get this assert, a corresponding StartTable wasn't called. - FLATBUFFERS_ASSERT(nested); - // Write the vtable offset, which is the start of any Table. - // We fill its value later. - // This is relative to the end of the 32-bit region. - const uoffset_t vtable_offset_loc = - static_cast(PushElement(0)); - // Write a vtable, which consists entirely of voffset_t elements. - // It starts with the number of offsets, followed by a type id, followed - // by the offsets themselves. In reverse: - // Include space for the last offset and ensure empty tables have a - // minimum size. - max_voffset_ = - (std::max)(static_cast(max_voffset_ + sizeof(voffset_t)), - FieldIndexToOffset(0)); - buf_.fill_big(max_voffset_); - const uoffset_t table_object_size = vtable_offset_loc - start; - // Vtable use 16bit offsets. - FLATBUFFERS_ASSERT(table_object_size < 0x10000); - WriteScalar(buf_.data() + sizeof(voffset_t), - static_cast(table_object_size)); - WriteScalar(buf_.data(), max_voffset_); - // Write the offsets into the table - for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc); - it < buf_.scratch_end(); it += sizeof(FieldLoc)) { - auto field_location = reinterpret_cast(it); - const voffset_t pos = - static_cast(vtable_offset_loc - field_location->off); - // If this asserts, it means you've set a field twice. - FLATBUFFERS_ASSERT( - !ReadScalar(buf_.data() + field_location->id)); - WriteScalar(buf_.data() + field_location->id, pos); - } - ClearOffsets(); - auto vt1 = reinterpret_cast(buf_.data()); - auto vt1_size = ReadScalar(vt1); - auto vt_use = GetSizeRelative32BitRegion(); - // See if we already have generated a vtable with this exact same - // layout before. If so, make it point to the old one, remove this one. - if (dedup_vtables_) { - for (auto it = buf_.scratch_data(); it < buf_.scratch_end(); - it += sizeof(uoffset_t)) { - auto vt_offset_ptr = reinterpret_cast(it); - auto vt2 = reinterpret_cast(buf_.data_at(*vt_offset_ptr)); - auto vt2_size = ReadScalar(vt2); - if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue; - vt_use = *vt_offset_ptr; - buf_.pop(GetSizeRelative32BitRegion() - vtable_offset_loc); - break; - } - } - // If this is a new vtable, remember it. - if (vt_use == GetSizeRelative32BitRegion()) { - buf_.scratch_push_small(vt_use); - } - // Fill the vtable offset we created above. - // The offset points from the beginning of the object to where the vtable is - // stored. - // Offsets default direction is downward in memory for future format - // flexibility (storing all vtables at the start of the file). - WriteScalar(buf_.data_at(vtable_offset_loc + length_of_64_bit_region_), - static_cast(vt_use) - - static_cast(vtable_offset_loc)); - nested = false; - return vtable_offset_loc; - } - - FLATBUFFERS_ATTRIBUTE([[deprecated("call the version above instead")]]) - uoffset_t EndTable(uoffset_t start, voffset_t /*numfields*/) { - return EndTable(start); - } - - // This checks a required field has been set in a given table that has - // just been constructed. - template void Required(Offset table, voffset_t field) { - auto table_ptr = reinterpret_cast(buf_.data_at(table.o)); - bool ok = table_ptr->GetOptionalFieldOffset(field) != 0; - // If this fails, the caller will show what field needs to be set. - FLATBUFFERS_ASSERT(ok); - (void)ok; - } - - uoffset_t StartStruct(size_t alignment) { - Align(alignment); - return GetSizeRelative32BitRegion(); - } - - uoffset_t EndStruct() { return GetSizeRelative32BitRegion(); } - - void ClearOffsets() { - buf_.scratch_pop(num_field_loc * sizeof(FieldLoc)); - num_field_loc = 0; - max_voffset_ = 0; - } - - // Aligns such that when "len" bytes are written, an object can be written - // after it (forward in the buffer) with "alignment" without padding. - void PreAlign(size_t len, size_t alignment) { - if (len == 0) return; - TrackMinAlign(alignment); - buf_.fill(PaddingBytes(GetSize() + len, alignment)); - } - - // Aligns such than when "len" bytes are written, an object of type `AlignT` - // can be written after it (forward in the buffer) without padding. - template void PreAlign(size_t len) { - AssertScalarT(); - PreAlign(len, AlignOf()); - } - /// @endcond - - /// @brief Store a string in the buffer, which can contain any binary data. - /// @param[in] str A const char pointer to the data to be stored as a string. - /// @param[in] len The number of bytes that should be stored from `str`. - /// @return Returns the offset in the buffer where the string starts. - template class OffsetT = Offset> - OffsetT CreateString(const char *str, size_t len) { - CreateStringImpl(str, len); - return OffsetT( - CalculateOffset::offset_type>()); - } - - /// @brief Store a string in the buffer, which is null-terminated. - /// @param[in] str A const char pointer to a C-string to add to the buffer. - /// @return Returns the offset in the buffer where the string starts. - template class OffsetT = Offset> - OffsetT CreateString(const char *str) { - return CreateString(str, strlen(str)); - } - - /// @brief Store a string in the buffer, which is null-terminated. - /// @param[in] str A char pointer to a C-string to add to the buffer. - /// @return Returns the offset in the buffer where the string starts. - template class OffsetT = Offset> - OffsetT CreateString(char *str) { - return CreateString(str, strlen(str)); - } - - /// @brief Store a string in the buffer, which can contain any binary data. - /// @param[in] str A const reference to a std::string to store in the buffer. - /// @return Returns the offset in the buffer where the string starts. - template class OffsetT = Offset> - OffsetT CreateString(const std::string &str) { - return CreateString(str.c_str(), str.length()); - } - -// clang-format off - #ifdef FLATBUFFERS_HAS_STRING_VIEW - /// @brief Store a string in the buffer, which can contain any binary data. - /// @param[in] str A const string_view to copy in to the buffer. - /// @return Returns the offset in the buffer where the string starts. - template