Squashed 'third_party/flatbuffers/' changes from acc9990ab..d6a8dbd26
d6a8dbd26 Experimental fix for failing oss-fuzz coverage build (#6259)
ed391e177 BREAKING: Rust flexbuffers serde human readable set to false (#6257)
a49531414 Update to flags in fuzzing-cmake file (#6256)
de1f0342c Remove _POSIX_C_SOURCE and _XOPEN_SOURCE definitions when compiling o… (#6205)
d0d51e2a5 flatc should support --binary --schema with optional scalar fields. (#6252)
33ab26017 Bump version of rules_go to 0.24.5 (#6234)
febb9d87c Union As Accessors for C# (#6251)
8778dc7c2 Resets buffer without deallocating current pointer (#6247)
aae376e9a Add GetBufferSpan() function to bufferbuilder (#6235)
0ff047148 Modernize android build and sample (#6229)
46a8c7e95 Added required-nested-flatbuffer to monster_test and fixed rust (#6236)
bc56c553e Notify based on Labelling issues and PR (#6241)
07d7cd78a Converted globs to use single quotes (#6240)
cdef70e24 More adjustments to the auto labeler (#6239)
9dd44df35 Updated Lua labeller glob (#6238)
c9b29d088 Support size-prefixed buffers and add tests for size-prefixed messages (#6232)
fba93e0ab Removes duplicate swift in labeler (#6228)
d1a545b1f Added more labels for auto labeler (#6227)
ea92a668d [C#] Optional Scalars (#6217)
6034de286 [Label Bot] Add Java and Kotlin support for the label bot (#6226)
b08b0a440 Implement `Debug` trait for Rust flatbuffers. (#6207)
17ae48dec [Label Bot] Adds some languages to labeler bot (#6222)
fc8097925 Auto Labeler Setup, Just C# for now (#6221)
55658f523 Auto Labeler Setup, Just C# for now (#6218)
14ecfe423 Updated comments and fixed a fundamental type error. (#6214)
a0182cdb1 optional scalars for ts/js (#6215)
0dfcc0a37 Adds NetTest.bat to run .NET Core tests on Windows (#6216)
f9a18ea63 [Java] Implement optional scalars (#6212)
c7586e85a Empties the sharedString map on reset on go and csharp (#6187)
914c64601 Removed C# references from java generator. Move annotations closer to definitions (#6204)
42d7c7997 Adds readable size to asserts in read functions (#6210)
e68e8d7de Refactor idl_gen_rust (#6206)
84809be7e Fix typo in flatbuffers::span declaration. (#6202)
1606fb637 Kotlin test optional enum (#6201)
fe8e3c7e5 Mass Refactoring to use `IsString` and other BASE_TYPE helpers (#6193)
8f6fa4b71 Updated SupportsAdvancedUnionFeatures to look out for string (#6190)
b46db38f5 [JS/TS] Rewrite flexbuffers JS to TS (#6148)
9fa1d2705 Rework enums in rust. (#6098)
a402b3aba idl_gen_json_schema Fix generation of arrays of enums (#6184)
0e1415b99 fix(go_test): remove deprecated grpc call (#6183)
5cd713710 Add generation of JSON Schema to library (#6165)
5be777e1d Bump junit from 4.12 to 4.13.1 in /grpc/tests (#6173)
a49d440ec Bump junit from 4.12 to 4.13.1 in /grpc (#6172)
4ec5e8db9 [C++] Add option to not generate direct copy methods. (#6166)
04bec23a3 Add Array initialization from struct constructor (#5865) (#6147)
77d57fd07 Cast to right type for reserved_ subtraction (#6167)
543c1bbeb Fixed rust nested flatbuffers for tables other than self (#6062)
cb971eece [C++] Fix -Wnarrowing and -Woverflow due to signed bitfields on G++ ARM (#6163)
7b9e61fcc [TS] GRPC Implementation (#6141)
3359e3042 Moved C++ to optional_scalars2 and added some tests. (#6162)
187a4787f [Rust] Upgrade flatbuffers library to 2018 edition (#6159)
08943aa26 Flatbuffer C++ UnpackTo optimization for vectors of non-bool bytes. (#6154)
5975658eb Enables optional enums in swift (#6160)
5d3cf440e Updated Lobster test for optional bools/enums
8ec8322f0 Ruopt enum (#6156)
bbcc85fd4 Fix generation of C++ code with Optional<Enum> (#6155)
0bdf2fa15 [C#] Fix and improve project files (#6142)
2eedc769d possibility to create a vector from an iterator (#6135)
ab01ae162 flatc should output a warning, when an attribute is attached more than once (#6146)
689bfafa7 [Python/JS/TS] Codegen SizeOf method for structs (#6136)
641309a5b unix2dos on tests/FlatBuffers.Test/FlatBuffers.Core.Test.csproj (#6133)
52e362879 SpanT is available in .Net Standard 2.0. (#6137)
dca12522a Add static cast to avoid implicit double promotion. (#6132)
e0bbaa6f9 [C#]Change to ENABLE_SPAN_T that doesn't require UNSAFE_BYTEBUFFER. (#6073)
ab139d6be Revert "[C#] Fix and improve project files (#6116)" (#6130)
34d67b425 Minireflect fixed array (#6129)
96d5e3597 [JS/TS] fix flatbuffers default export (#6123)
eb686a86f Add missed file generated by optional_scalar.fbs (#6125)
750281630 [C#] Fix and improve project files (#6116)
fb4e1c34f Add CharToLower and CharToUpper into util.s (#6126)
8c67b5b12 Add support of Optional<T> scalars to C++ code generator (#6092)
6228b66d3 [Kotlin] Support for optional scalars. (#6115)
e1be8aaad Bump version for latest swift version (#6121)
94873e595 [JS/TS] Modernize TypeScript / JavaScript flatbuffers support (#6095)
b8e87fafe [JS] Add getFullyQualifiedName() (#6119)
f96d1ef74 [Java] allowing larger buffer sizes when growing a byte buffer (#6118)
89435303b [Swift] Migrates struct write APIS to write directly to the buffer (#6093)
c75ae2429 Optional-ness in reflection (#6097)
338944d3d Rename Nullable scalars to Optional scalars (#6112)
f5ab24bc4 Avoid memcpy call for empty vectors (#6111)
92a8c1a0f [JS] FlexBuffers Fix for wrong type of offset and length values (#6107)
6cea45dcd fix c# json serializer commandline argument docs (#6104)
fec58aa12 Fix for issue 6100: incorrect shrinking logic in ResizeContext() (#6102)
71aca81ff [JS] FlexBuffers Support (#5973)
04d87ffec [C++] Small refactoring of the C++ code generator (#6091)
bb25956f0 Wrap verify file id condition in Check call (#6085)
49f4948f0 + Add `removable-media` plug to the snapcraft config (#6083)
eeacc53d2 Adds proper access types for swift object api & flatbuffers & grpc (#6081)
f3003e08d [Lobster] missed a test
d713a0084 [CMake] enabled multi-core builds in VS projects
77f966f89 [Lobster] optional scalars support
e86d5b8e9 [Kotlin] Attach JvmStatic annotation to each method in companion object (#6052)
db2aa9b4e [C#] Cleaned up .NET testing script for Mono (#6016)
63cc0eec4 Adds a serialize helper function to native table (#6059)
c30a87de6 [TS] Fix four bugs with imported types in TypeScript. (#6054)
a0fb30575 [Swift] Append namespace for Swift Grpc implementation (#6049)
77c18c1d6 export a __version__ variable for python module (#5309)
f1f23d08e adding fb import when no other imports are present (#6030)
f1025b284 [Feature] Checks for Nullable strings (#6050)
5d052f4e5 [Swift] RFC: Switch Swift namespace from public enum to ordinary concat with _ (#6045)
18b015d25 Rust codegen improvements and lint fixes (#6046)
d76e93f27 adds code gen for optional scalars in swift (#6038)
82fac326c [C++] Fix compiler error from deleted assignment operator (#6036) (#6047)
043b52bd4 Optional Scalars support for Rust (#6034)
c8fa0afdf Allow to run cpp tests under grpc/tests/ using bazel. (#6040)
6d0aae73c Fix git command executed in wrong folder when doing cmake superbuild (#6039)
ff1b73128 [Swift] Optional Scalars Preparation (#6028)
2e48c8dd3 tests: Check for both quiet and signaling NaN on mipsel/hppa (#6029)
6942704f2 support deprecated flag in json schema (#6022)
9ecd2e16c Flatc parser support for nullable scalars (#6026)
33e2d8079 [Dart] Generate constant values map for enums (#6025)
969d0f7a6 Using proper symbol name for reexport (#6021)
515a4052a Silence false positive "-Wstringop-overflow" on GCC 10.0 to 11.0 (#6020)
36fbe6f13 Updated FB import (#6019)
b69fc8cc9 [Java] Add support for shared strings on FlatBufferBuilder. (#6012)
ab6af18d9 Not using non-existent create method for obj api (#6015)
37a5dee10 Code cleanup + updates test and readme (#6004)
8a721f69a Serde with bytes maps to Blob (#6009)
e810635ea [Swift] FlatBuffers createMonster method doesn't treat struct properly (#5992)
4995e1527 Manage grpc dependency in Bazel's WORKSPACE file. (#5995)
60b6066fe Add warning to schema parser if field name is not snake_case. (#6005)
35d45cac7 [Rust] Flexbuffers dependency cleanup and fixes (#5998)
165a6e3d1 Re-added Evolution Schema Code Generation Command (#5999)
13d3fb2ea Fix RPM install conflict (#6003)
d64078eb2 [Swift] Initialize memory when clear ByteBuffer (#5982)
ca1190a3d [TS] Use proper TypedArray in create*Vector (#5991)
7571b2ac5 [C++] Updates real_path to be truly portable (#5787)
e5a8f76a4 [C++] Generate default member initializers for >= C++11 (#5989)
413bb9b55 [Kotlin] Fix Access to union of vector element (#5994)
f35184aef [Swift] Add parsing from unowned UnsafeMutableRawPointer for ByteBuffer (#5981)
b124b7625 Removed requirement that enums be declared in ascending order. (#5887)
0ec7600c6 Do not remove the last digit from float values (#5974)
14baf45c9 Mark GetBufferMinAlignment() const (#5985)
9abb2ec2c TypeScript/JavaScript docs improvements (#5984)
2e57d80b1 [Swift] Internal library improvements (#5965)
cfc7753a4 [Doc] Added missing letters to compiler options (#5976)
12ddc8a92 Rust Flexbuffers Documentation update (#5979)
24ad35709 [docs] typo: updates monsterdata.json to be valid json (#5978)
cc44a4442 [idl_parser] Mark typefield as deprecated (#5958)
9ab4a5c0e Deleted old stale bot
6682cfe87 Increased Operations per run in stale.yml
64922904b Adding Stale Action to clean up PR and Issues
8e505cb67 [C++] Fixed/Enabled --cpp-ptr-type std::shared_ptr [#5813] (#5959)
a28357d7a Propagate boolean default values from proto to fbs (#5964)
7cb4762a6 [Swift] Improving reallocation time by using memcpy and moving reallocation code to storage (#5960)
4e45f7c9e Fix error in SimpleQSort (#5955)
7ac026405 fix error on GRPC Python - ignore namespace tree if not specified (#5862) (#5922)
108e981db Required is now implemented in swift (#5952)
94a78e385 Fixed: Access violation and ASAN/UNSAN failures with sorted tables
53fb453e0 [rust] Add FlatBufferBuilder::force_defaults API (#5946)
17c1f35fa [FlexBuffer][Java] ReadWriteBuf and ReadBuf interface public (#5948)
2eaf57778 [Java] Grow ArrayReadWriteBuf enough to match requested capacity. (#5921)
666800da3 Adds bool support in structs + updates grpc support + CI upgrades (#5943)
38ed69eb3 fixed mutating inline values (#5942)
d026e6f07 Add static asserts to ensure that reflection API arrays are kept in sync (#5934)
988164f6e [C++] Got rid of memset's in constructors (#5938)
7179a5a8b General Codebase clean up (#5939)
a0da0c08c Add GetStringView like GetString, GetCstring (#5937)
ac203b209 [C#] Add file identifier to ObjectAPI Serialization Utility. (#5920)
8dd1bf25b not creating creation methods when using structs (#5919)
5aa443d98 [Dart] Adding FlexBuffers support (#5853)
0fa087657 [Dart] Getting tests/DartTest.sh to work on master. (#5915)
424a473e1 Schema parser: prohibit declaration of an array of pointers inside structs (#5907)
c3faa8346 Fix Cargo.toml dependencies (#5911)
91399ad05 fix union type names (#5902)
32782e4ad Update Rust Flexbuffers metadata before publishing (#5905)
e7f3b1690 [TS] Make Obj-API work with --short-names (#5898)
12ed1fe4a fixed invalid imports with --gen-all (#5895)
85ee4df7a [C#] Thread safe reads of Double and Float values from a ByteBuffer (#5900)
de89bd193 Implement flexbuffers in python (#5880)
8be05f6bd Rust Flexbuffers (#5669)
870ecbc09 [swift] Moves code to use VTablesStorage (#5888)
c2da8d5d8 [Java][FlexBuffers] Make FlexBuffersBuilder reusable by adding clear() (#5889) (#5890)
e84cbff67 Align package name to FindFlatBuffers.cmake (#5899)
f94e6c84e Small tutorial improvements - documentation only (#5894)
f12cca8bc Attempt at adding Github Actions CI
7e4124d6e Handle git program or .git folder absence (#5878)
a875d247a only add native_include_files if object based api is enabled (#5886)
6e9f5d981 Respect shared attribute in Parser (#5885)
ff1c78233 include/flatbuffers: typo fixes in comments (#5884)
2e9a19673 Updates swift docs for package management (#5883)
e3cb07d32 [Rust] idl_gen_rust.cpp: (Option/required-aware codegen for unions) (#5850)
712866d57 Propagate use_string_pooling in CopyTable (#5879)
44c919a9e Not using reexports with --gen-all (#5873)
99aa1ef21 Added INCLUDE_PREFIX option for flatbuffers_generate_headers (#5866)
40ba170c9 Fixed text in internals doc that implied structs can be root
cb4d0f72e [Swift] Object API support (#5826)
003e16405 [TS] Add Obj API (#5788)
21cf300f4 fix cpp usage markdown error (#5845)
9655e12d6 Upgraded swift implementation for grpc (#5843)
fb96fadc2 [C#] Fix nested structs and arrays in Object API (#5765)
408f11fbd [ts] Fix empty source/dest namespaces when reexporting. (#5841)
a83caf591 Improves performance for the swift library by using structs + a storage class (#5835)
925fab6b1 [Java][FlexBuffers] Optimize Map access (#5735)
d9fecc332 [CMake] : Add precompiled header support with FLATBUFFERS_ENABLE_PCH (#5827)
e9d453240 Added flatbuffers_generate_headers and flatbuffers_generate_binary_files cmake functions. (#5830)
c37c989ed Correct calculation of vector element size (#5831)
6b271b7ec Fix Clang-trunk warnings about special members deprecated in C++20. (#5829)
90f3b8e8c Fix `float_constant` definition in './doc/Grammar.md` (#5828)
3af735934 [csharp] flatc should generate a 'Create…' method for tables with struct field… (#5818)
c4231c3cb Updated doxyfile - added missing files (#5824)
9657df184 Update Grammar.md (#5820)
97ffc590e Include CPack only when explictly packaging (#5817)
8b52af65b [C++] Add max_depth and max_tables parameters to reflection::Verify (#5815)
9b034eee1 Fix interpretation of 'nan(number)' by the idl_parser (#5810)
3e9ac3cff [Scripts] Adds swift to generated code (#5806)
697147a2e updated maven build files
6df40a247 pre-tag version bump for 1.12
0dba63909 Removes the inner loop in the endtable check written tables (#5803)
0e3fdd0ee Escape characters in jsonschema descriptions (#5644)
45a2b07cb Remove `noexcept` qualifier copy-ctor of `union` type (#5800) (#5802)
d10c16314 Replace 'assert' by 'FLATBUFFERS_ASSERT' inside idl_parser.cpp (#5799)
35abb7f89 Add non-nullable modifier to return type of functions never returning null (#5797)
9954e09ab [C++] Generate code for vector force_align attribute. (#5796)
95a21327f rust: pub export the VectorIter type (#5736)
89b6183ee Fix Python min alignment
5a98d65e8 [Rust] Add gen-name-strings for Rust (#5757)
f73d205bc Removed assert that wasn't backwards compatible.
7c37abe92 [C#] add ObjectAPI Serialization Utility (#5785)
4749e77b0 Fixed docs on how to obtain parser error.
6ff189841 Added --filename-suffix and --filename-ext to flatc (#5778)
c9a30c9ca Fixed refractoring issue in reflection/generate_code.sh. Also, mv deletes the original file, so I don't need to clean it up manually in that case. (#5777)
8c02d17be Skip writing reflection_generated.h if not changed (#5776)
34305c4ce [Swift] Adds GRPC to Swift (#5758)
cd88e6b2a [Java][FlexBuffers] Abstract buffer access from ByteBuffer (#5743)
3ec7a53c6 Adds cocoapods and a readme of how to get the package (#5771)
6d44cede7 [snap] Fix versioning (#5727)
cc08c0835 [Python] Fixed potential allignment issue (#5768)
54f8b787c Fix memory leak on cpp object api (#5761)
17557f913 [Python] Fixed issue #5499 (#5764)
d54af8cd4 [C++] Use strong enum type for vectors when scoped-enums is on. (#5750)
173e10fdf [C#] support Json Serialization (#5752)
8f56990f6 FlexBuffers: C++: scalar-only typed vectors were not aligned.
6400c9b05 Bump Rust port to 0.6.1 (#5747)
7418d8587 [C#] support Object API (#5710)
c580fa284 Adds min and max, comments, and all of swift's keywords + fix docs (#5737)
f2a127230 Use VS 2017 and 2019 on CI, fix cast issue in dart_idl (#5740)
316d7c208 Creates a flatbuffers validation function + small fix (#5725)
47026ea6b Added the code to embed the binary schema to the source (--bfbs-gen-embed). (#5701)
3f677f241 [Java][FlexBuffers] Deprecate typed vector strings due to design flaw (#5722)
a593a11e5 [Go] Implements a SharedStrings function (#5733)
7cdfc8475 [Swift] Fix padding function overflow when bufSize is 0 (#5721)
bab2b0db4 Add vcpkg installation instructions (#5732)
89418eb84 [Dart] Fix deprecated field support, inf/nan (#5724)
9cadf05d8 [typescript] Size-prefixed root accessors not taking into account size prefix (#5717)
6da1cf79d [rust] Add use declarations to Rust-generated bindings for imported FB definitions (#5645)
bee1df96d [Go] Replace references to hardcoded ”Monster" etc with idiomatic go wherever possible (#5716)
01189d7ed [C++] Fix for printing of enum in case output_enum_identifiers=1. (#5706)
c4b2b0a25 [Swift] Support create long string (#5709)
a4b2884e4 Added create function for swift (#5707)
04d80f255 [Swift] Swift implementation 🎉🎉 (#5603)
55686100a Changed direct calls to strtod to use StringToNumber
718351831 Document JSON compatibility guarantees. (#5704)
d1b34f0f2 Add CMake 'generated_code' target to simplify resolution of build dependencies (#5697)
21b706196 (Optionally) add an additional suffix namespace to generated fbs files. (#5698)
35daaf83d [Java] Replace Table.UTF8_CHARSET with StandardCharsets.UTF_8 (#5696)
3b458f7a1 Rust: Temporarily disable 2 endianness unit tests (#5695)
a5d9d0f7d [C++17] Add Traits class for Tables and Factory function within it. (#5678)
3cd9b6434 Removed code_generators.cpp from library targets
355dfd48d [rust] Make enum names public (#5690)
bcd58a159 Correct inverted logic around include prefixes. (#5689)
a2c12900a Optimize Pack method using numpy (#5662)
901b89e73 [C++] Add Builder and Table typedefs (#5685)
31f879908 Minor doc updates: FlexBuffers C#, Discord, CppUsage.
8023d99e2 Upgrade rules_go (#5684)
b4154405d Fix --incompatible_load_cc_rules_from_bzl (#5683)
04c17c7a7 Add support for absl::string_view when available (#5682)
62ec7d52c [Bazel] Add support for compatible_with and restricted_to (#5681)
7de668053 CI: New Docker tests for Python with numpy (#5677)
3a70e0b30 Fixed struct initialization error on older versions of C#
9b1320135 Fixed warnings in FlexBuffers.java
5e3916050 Fixed out of date licenses on gRPC Python files.
c95755051 Removed test proto output.
44bf71988 Add flatc '--cpp_std' switch (#5656)
3e8f15df9 Fix for FlexBuffers FBT_VECTOR_STRING size bit-width.
602721a73 Added Check to VerifyAlignment (#5675)
13c05f4da Improve import handling for proto conversion (#5673)
ce3a1c43a [Dart] Fix prepare space for writeListInt64 and writeListUint64 (#5654)
aa75e5734 Make Rust constants public (#5659)
2790fee25 Add namespace qualification to union types (#5666)
eddebec1b Bugfix for Rust generation of union fields named with language keywords (#5592)
030fee36a wrap multiple statements in do {} while(!IsConstTrue(true)) (#5655)
f9724d1bd [gRPC] Uncomment MessageBuilder (#5658)
b20801ca4 Supress unsigned-integer-overflow for PaddingBytes (#5647)
a8e800bd7 Add --force-empty-vectors option (#5653)
d7530ae96 Fixed enum min/max values not properly escaped.
99d11e279 Split Bazel targets into multiple packages (#5640)
4fd8eb214 Remove a static_assert (#5643)
65f870357 Flatbuffers Python Object API (#5616)
75823cc27 [Clang 10]: definition of implicit copy constructor for 'TableKeyComparatoris deprecated #5649 (#5650)
58e279244 [docs]: add missing semicolon (#5648)
3c964e10a [GO] Fix support for enums with underscores and Unions with imported members (#5600)
c3c32ec94 Fix ambiguity of a type deduction in TEST_EQ macro if arguments have `enum class` type. (#5630)
075e8d676 Simplify declarations of x-macro FLATBUFFERS_TD (#5638)
bcf1bd5c9 read vtable size through ReadScalar() (#5636)
136d75fa6 Changed null checks in test. Removed verifier pointer usage (#5634)
091fa1fd1 Add testing of C++ with sanitizers (CI-Docker) (#5631)
ff3781dc2 add namespace prefix in FLATBUFFERS_MAX_BUFFER_SIZE (#5629)
6beb9f49c Support for python grpc - continuing the work from the pull request #4270 #4705 (#5613)
80988ea86 Removed idl_gen_general.cpp and move contents to code_generators.cpp (#5625)
0f2ff7eaa Lua cleanup (#5624)
dda095023 [C++] Adds basic schema evolution tests (#5611)
adbcbba5d [C++, C#, Java] Separated C# and Java generators into their own classes (#5618)
cbbd6aca0 add check for root_type specified for json schema generation (#5622)
405c64e07 [Rust] Bump smallvec version to 1.0 (#5621)
42c08cbca Ran src/clang-format-all.sh (#5617)
33d5dd9bd Improved pull request & clang-format instructions.
105dd528e Change monster_extra generation to use flatbuffers::unique_ptr (#5612)
f0f0efe7b [C++] Refactor to conform to Google C++ style guide (#5608)
e837d5a29 Fixed deprecated method in GRPC Java test.
9834ee978 Fixed Apache license not using canonical version.
44b2ab087 include/flatbuffers/base.h: fix no_sanitize issue with old clang (#5610)
46ae3f80a [C++, Java, C#, TypeScript, JavaScript] Skip generation of mutable union types (#5599)
7b38aa71e flatbuffers.h: fix documentation warning (#5607)
661bedd83 Add Lua FlatbufferBuilder Clean() method to enable reuseable builders (#5606)
8526e12d7 [Kotlin] Fix union vector accessor after change in Java API (#5605)
3c7b660d6 [flatc] Remove an always true condition for flexbuffers (#5604)
964365ba6 [Go] Add UnPackTo functions (#5598)
32254b7ac [Go] Object API support (#5339)
521e255ad Rust: Add idiomatic iterator for Vector type (#5579)
1b85292fd Fix typos in comments (#5590)
480815447 C++ verifier for evolved union fields should return true (#5586)
8d5e424c6 Add ByteBuffer copy for vector of bytes in Java (#5587)
b4774d235 Rust: Fix Copy and Clone impls for a few generic types (#5577)
26f238c24 Add `--clean-first` to the cmake-build command (travis) (#5574)
e93c8c46e Fix Follow implementation for bool (#5554)
e21516b9d Fix issue #5557 (#5573)
fbc11e8ae Avoid intentional unsigned integer overflow getting caught by sanitizers (#5572)
e9d29c21a Python: Add forceDefaults opt to python Builder (#5564)
8bfafc76d Java: Don't annotate vector-of-tables item getters with @nullable. (#5562)
df3e8bf4a Fixed warnings generated by recent JSON sorting feature.
5665cfe49 [Java] byte buffer factory returned buffer capcity is used instead of the requested size (#5558)
5797540ed #5544 Fix of Array of table is not sorted if Create<type>Direct() is used (#5546)
7f1af7cb0 Fix build with gcc version 7.4.0 (#5570)
32f47ad24 Fixed JSON parser not sorting vectors of tables/structs with key.
842f672ba [FlexBuffers][Java] Cache size of Sized objects in FlexBuffers (#5551)
d4cae0a62 Fix issue #5542 (#5543)
f1147f65b Fixed Android STLPort related error.
69d3fec48 Fix namespaced struct/field name collision detection (#5540) (#5545)
cfb4ecf6f [flac] Add FlexBuffers option for generating data (#5519)
a92039687 Update Rust versions under test from 1.30.1 to 1.37.0 (#5538)
625338d09 Adds XOPEN_SOURCE for PATH_MAX and POSIX 1993 for stat (#5529)
3f8ce99c5 [FlexBuffers][Java] Add override Key::toString (#5533)
0798b7b69 [FlexBuffers][Java] Fix wrong access to a string using Reference::asString(). (#5532)
cbdf82e2f Fix Mutate() methods of Array<scalar/struct> (override 5508) (#5526)
e365c502f Java: Added access object for vector of struct and vector of tables. (#5233)
97f3aa917 Fixed DetachedBuffer self move assignment (#5521)
2f5bb2eec Fix buildifier warnings found in new bazel (#5517)
917687c7a Fixed Reflection Verifier not handling vectors of unions.
f9277e691 Fixed GenerateText not handling vectors of unions.
2706381ee Add element size parameter to __vector_as_arraysegment [c#] (#5512)
b5560fcd5 [Java][FlexBuffers] Improve documentation for FlexBuffers in Java. (#5506)
782b865c5 Annotate getters with @Pure when --java-checkerframework is specified. (#5510)
3bfc86eaf [Dart]fix: segment fault with empty namespace when generating dart file (#5507)
c0282873f Rust: Fixed cargo clippy on non-generated code (#5485)
4b870aca9 [Javascript] Fix syntax error for signed enum (#5503)
d0e3870c0 [C#] Fix retrieving enumeration vectors as arrays (#5457)
fb25eb87f Doc typo fixes (#5505)
cb35d3a0e Use all of the available space in the buffer returned by ByteBufferFactory to allow the factory to keep a pool of larger than initialsize sized buffers. (#5500)
8e6cabb31 [FlexBuffers][Java] Implementation of FlexBuffers API (#5476)
bd31dd242 Clarified value reuse in FlexBuffers
65b67d213 Fixed test build invocation of arrays_test.fbs
1fbb71132 FlexBuffers: allow any values to be shared.
cd75a3658 Android: remove app_dummy() calls
ec6b0bf29 Fixed STLPort Android compile error
c11b5d744 [bugfix]flexbuffers isvector bugfix (#5488)
4525c91be Fix incorrect padding in arrays of structs (Issue #5484) (#5491)
b97b342f5 Fixed missing generated code.
c1058a903 C++ IDL generation adds superfluous semicolon in GenTablePost, causing (#5483)
303044934 [go]add Name() for ForceCodec interface (#5486)
a2485d4ec reflection: check for valid union enum value during object verification (#5475)
a20e71ac9 has_method support for primitive fields in java runtime. Changed: idl.h, FlatBufferBuilder.java , idl_gen_general.cpp, idl_parser.cpp, flatc.cpp (#5468)
Change-Id: I836f4b43e6818bb16425a87899e6234ac86242aa
git-subtree-dir: third_party/flatbuffers
git-subtree-split: d6a8dbd26ff08a8868e0d0c1b4b67d31b40e4a7f
diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp
index 936ac83..3995a7f 100644
--- a/src/idl_gen_rust.cpp
+++ b/src/idl_gen_rust.cpp
@@ -23,27 +23,20 @@
namespace flatbuffers {
-static std::string GeneratedFileName(const std::string &path,
- const std::string &file_name) {
- return path + file_name + "_generated.rs";
-}
-
// Convert a camelCaseIdentifier or CamelCaseIdentifier to a
// snake_case_indentifier.
std::string MakeSnakeCase(const std::string &in) {
std::string s;
for (size_t i = 0; i < in.length(); i++) {
if (i == 0) {
- s += static_cast<char>(tolower(in[0]));
+ s += CharToLower(in[0]);
} else if (in[i] == '_') {
s += '_';
} else if (!islower(in[i])) {
// Prevent duplicate underscores for Upper_Snake_Case strings
// and UPPERCASE strings.
- if (islower(in[i - 1])) {
- s += '_';
- }
- s += static_cast<char>(tolower(in[i]));
+ if (islower(in[i - 1])) { s += '_'; }
+ s += CharToLower(in[i]);
} else {
s += in[i];
}
@@ -54,9 +47,7 @@
// Convert a string to all uppercase.
std::string MakeUpper(const std::string &in) {
std::string s;
- for (size_t i = 0; i < in.length(); i++) {
- s += static_cast<char>(toupper(in[i]));
- }
+ for (size_t i = 0; i < in.length(); i++) { s += CharToUpper(in[i]); }
return s;
}
@@ -96,7 +87,7 @@
FullType GetFullType(const Type &type) {
// N.B. The order of these conditionals matters for some types.
- if (type.base_type == BASE_TYPE_STRING) {
+ if (IsString(type)) {
return ftString;
} else if (type.base_type == BASE_TYPE_STRUCT) {
if (type.struct_def->fixed) {
@@ -104,7 +95,7 @@
} else {
return ftTable;
}
- } else if (type.base_type == BASE_TYPE_VECTOR) {
+ } else if (IsVector(type)) {
switch (GetFullType(type.VectorType())) {
case ftInteger: {
return ftVectorOfInteger;
@@ -184,13 +175,21 @@
}
}
+bool IsBitFlagsEnum(const EnumDef &enum_def) {
+ return enum_def.attributes.Lookup("bit_flags") != nullptr;
+}
+bool IsBitFlagsEnum(const FieldDef &field) {
+ EnumDef* ed = field.value.type.enum_def;
+ return ed && IsBitFlagsEnum(*ed);
+}
+
namespace rust {
class RustGenerator : public BaseGenerator {
public:
RustGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
- : BaseGenerator(parser, path, file_name, "", "::"),
+ : BaseGenerator(parser, path, file_name, "", "::", "rs"),
cur_name_space_(nullptr) {
const char *keywords[] = {
// list taken from:
@@ -200,77 +199,19 @@
// changes to that webpage in the future.
// currently-used keywords
- "as",
- "break",
- "const",
- "continue",
- "crate",
- "else",
- "enum",
- "extern",
- "false",
- "fn",
- "for",
- "if",
- "impl",
- "in",
- "let",
- "loop",
- "match",
- "mod",
- "move",
- "mut",
- "pub",
- "ref",
- "return",
- "Self",
- "self",
- "static",
- "struct",
- "super",
- "trait",
- "true",
- "type",
- "unsafe",
- "use",
- "where",
- "while",
+ "as", "break", "const", "continue", "crate", "else", "enum", "extern",
+ "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
+ "move", "mut", "pub", "ref", "return", "Self", "self", "static", "struct",
+ "super", "trait", "true", "type", "unsafe", "use", "where", "while",
// future possible keywords
- "abstract",
- "alignof",
- "become",
- "box",
- "do",
- "final",
- "macro",
- "offsetof",
- "override",
- "priv",
- "proc",
- "pure",
- "sizeof",
- "typeof",
- "unsized",
- "virtual",
- "yield",
+ "abstract", "alignof", "become", "box", "do", "final", "macro",
+ "offsetof", "override", "priv", "proc", "pure", "sizeof", "typeof",
+ "unsized", "virtual", "yield",
// other rust terms we should not use
- "std",
- "usize",
- "isize",
- "u8",
- "i8",
- "u16",
- "i16",
- "u32",
- "i32",
- "u64",
- "i64",
- "u128",
- "i128",
- "f32",
- "f64",
+ "std", "usize", "isize", "u8", "i8", "u16", "i16", "u32", "i32", "u64",
+ "i64", "u128", "i128", "f32", "f64",
// These are terms the code generator can implement on types.
//
@@ -281,13 +222,12 @@
// implementation detail, and how we implement methods could change in
// the future. as a result, we proactively block these out as reserved
// words.
- "follow",
- "push",
- "size",
- "alignment",
- "to_little_endian",
- "from_little_endian",
- nullptr };
+ "follow", "push", "size", "alignment", "to_little_endian",
+ "from_little_endian", nullptr,
+
+ // used by Enum constants
+ "ENUM_MAX", "ENUM_MIN", "ENUM_VALUES",
+ };
for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
}
@@ -310,8 +250,7 @@
// TODO(rw): Use a set data structure to reduce namespace evaluations from
// O(n**2) to O(n).
for (auto ns_it = parser_.namespaces_.begin();
- ns_it != parser_.namespaces_.end();
- ++ns_it) {
+ ns_it != parser_.namespaces_.end(); ++ns_it) {
const auto &ns = *ns_it;
// Generate code for all the enum declarations.
@@ -357,7 +296,7 @@
}
if (cur_name_space_) SetNameSpace(nullptr);
- const auto file_path = GeneratedFileName(path_, file_name_);
+ const auto file_path = GeneratedFileName(path_, file_name_, parser_.opts);
const auto final_code = code_.ToString();
return SaveFile(file_path.c_str(), final_code, false);
}
@@ -381,8 +320,12 @@
case ftBool:
case ftEnumKey:
case ftUnionKey:
- case ftUnionValue: { return false; }
- default: { return true; }
+ case ftUnionValue: {
+ return false;
+ }
+ default: {
+ return true;
+ }
}
}
@@ -393,35 +336,14 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (field.deprecated) {
- continue;
- }
+ if (field.deprecated) { continue; }
- if (TableBuilderTypeNeedsLifetime(field.value.type)) {
- return true;
- }
+ if (TableBuilderTypeNeedsLifetime(field.value.type)) { return true; }
}
return false;
}
- // Determine if a Type needs to be copied (for endian safety) when used in a
- // Struct.
- bool StructMemberAccessNeedsCopy(const Type &type) const {
- switch (GetFullType(type)) {
- case ftInteger: // requires endian swap
- case ftFloat: // requires endian swap
- case ftBool: // no endian-swap, but do the copy for UX consistency
- case ftEnumKey: { return true; } // requires endian swap
- case ftStruct: { return false; } // no endian swap
- default: {
- // logic error: no other types can be struct members.
- FLATBUFFERS_ASSERT(false && "invalid struct member type");
- return false; // only to satisfy compiler's return analysis
- }
- }
- }
-
std::string EscapeKeyword(const std::string &name) const {
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}
@@ -477,7 +399,7 @@
auto s = src->components.begin();
auto d = dst->components.begin();
- for(;;) {
+ for (;;) {
if (s == src->components.end()) { break; }
if (d == dst->components.end()) { break; }
if (*s != *d) { break; }
@@ -486,9 +408,7 @@
++i;
}
- for (; s != src->components.end(); ++s) {
- stream << "super::";
- }
+ for (; s != src->components.end(); ++s) { stream << "super::"; }
for (; d != dst->components.end(); ++d) {
stream << MakeSnakeCase(*d) + "::";
}
@@ -509,19 +429,23 @@
case ftFloat:
case ftBool:
case ftEnumKey:
- case ftUnionKey: { break; }
- default: { FLATBUFFERS_ASSERT(false && "incorrect type given");}
+ case ftUnionKey: {
+ break;
+ }
+ default: {
+ FLATBUFFERS_ASSERT(false && "incorrect type given");
+ }
}
// clang-format off
static const char * const ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
- RTYPE, KTYPE) \
- #RTYPE,
- FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
+ RTYPE, ...) \
+ #RTYPE,
+ FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
- // clang-format on
};
+ // clang-format on
if (type.enum_def) { return WrapInNameSpace(*type.enum_def); }
return ctypename[type.base_type];
@@ -535,15 +459,15 @@
FLATBUFFERS_ASSERT(false && "precondition failed in GetEnumTypeForDecl");
}
- static const char *ctypename[] = {
// clang-format off
+ static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
- RTYPE, KTYPE) \
- #RTYPE,
- FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
+ RTYPE, ...) \
+ #RTYPE,
+ FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
- // clang-format on
};
+ // clang-format on
// Enums can be bools, but their Rust representation must be a u8, as used
// in the repr attribute (#[repr(bool)] is an invalid attribute).
@@ -560,21 +484,42 @@
case ftBool:
case ftEnumKey:
case ftUnionKey: {
- return GetTypeBasic(type); }
+ return GetTypeBasic(type);
+ }
case ftTable: {
return WrapInNameSpace(type.struct_def->defined_namespace,
- type.struct_def->name) + "<'a>"; }
+ type.struct_def->name) +
+ "<'a>";
+ }
default: {
return WrapInNameSpace(type.struct_def->defined_namespace,
- type.struct_def->name); }
+ type.struct_def->name);
+ }
}
}
- std::string GetEnumValUse(const EnumDef &enum_def,
+ std::string GetEnumValue(const EnumDef &enum_def,
const EnumVal &enum_val) const {
return Name(enum_def) + "::" + Name(enum_val);
}
+ // 1 suffix since old C++ can't figure out the overload.
+ void ForAllEnumValues1(const EnumDef &enum_def,
+ std::function<void(const EnumVal&)> cb) {
+ for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
+ const auto &ev = **it;
+ code_.SetValue("VARIANT", Name(ev));
+ code_.SetValue("VALUE", enum_def.ToString(ev));
+ cb(ev);
+ }
+ }
+ void ForAllEnumValues(const EnumDef &enum_def, std::function<void()> cb) {
+ std::function<void(const EnumVal&)> wrapped = [&](const EnumVal& unused) {
+ (void) unused;
+ cb();
+ };
+ ForAllEnumValues1(enum_def, wrapped);
+ }
// Generate an enum declaration,
// an enum string lookup table,
// an enum match function,
@@ -582,61 +527,139 @@
void GenEnum(const EnumDef &enum_def) {
code_.SetValue("ENUM_NAME", Name(enum_def));
code_.SetValue("BASE_TYPE", GetEnumTypeForDecl(enum_def.underlying_type));
-
- GenComment(enum_def.doc_comment);
- code_ += "#[allow(non_camel_case_types)]";
- code_ += "#[repr({{BASE_TYPE}})]";
- code_ += "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]";
- code_ += "pub enum " + Name(enum_def) + " {";
-
- for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const auto &ev = **it;
-
- GenComment(ev.doc_comment, " ");
- code_.SetValue("KEY", Name(ev));
- code_.SetValue("VALUE", enum_def.ToString(ev));
- code_ += " {{KEY}} = {{VALUE}},";
- }
+ code_.SetValue("ENUM_NAME_SNAKE", MakeSnakeCase(Name(enum_def)));
+ code_.SetValue("ENUM_NAME_CAPS", MakeUpper(MakeSnakeCase(Name(enum_def))));
const EnumVal *minv = enum_def.MinValue();
const EnumVal *maxv = enum_def.MaxValue();
FLATBUFFERS_ASSERT(minv && maxv);
-
- code_ += "";
- code_ += "}";
- code_ += "";
-
- code_.SetValue("ENUM_NAME", Name(enum_def));
- code_.SetValue("ENUM_NAME_SNAKE", MakeSnakeCase(Name(enum_def)));
- code_.SetValue("ENUM_NAME_CAPS", MakeUpper(MakeSnakeCase(Name(enum_def))));
code_.SetValue("ENUM_MIN_BASE_VALUE", enum_def.ToString(*minv));
code_.SetValue("ENUM_MAX_BASE_VALUE", enum_def.ToString(*maxv));
- // Generate enum constants, and impls for Follow, EndianScalar, and Push.
- code_ += "const ENUM_MIN_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}} = \\";
- code_ += "{{ENUM_MIN_BASE_VALUE}};";
- code_ += "const ENUM_MAX_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}} = \\";
- code_ += "{{ENUM_MAX_BASE_VALUE}};";
+ if (IsBitFlagsEnum(enum_def)) {
+ // Defer to the convenient and canonical bitflags crate. We declare it in a
+ // module to #allow camel case constants in a smaller scope. This matches
+ // Flatbuffers c-modeled enums where variants are associated constants but
+ // in camel case.
+ code_ += "#[allow(non_upper_case_globals)]";
+ code_ += "mod bitflags_{{ENUM_NAME_SNAKE}} {";
+ code_ += " flatbuffers::bitflags::bitflags! {";
+ GenComment(enum_def.doc_comment, " ");
+ code_ += " pub struct {{ENUM_NAME}}: {{BASE_TYPE}} {";
+ ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
+ this->GenComment(ev.doc_comment, " ");
+ code_ += " const {{VARIANT}} = {{VALUE}};";
+ });
+ code_ += " }";
+ code_ += " }";
+ code_ += "}";
+ code_ += "pub use self::bitflags_{{ENUM_NAME_SNAKE}}::{{ENUM_NAME}};";
+ code_ += "";
+
+ // Generate Follow and Push so we can serialize and stuff.
+ code_ += "impl<'a> flatbuffers::Follow<'a> for {{ENUM_NAME}} {";
+ code_ += " type Inner = Self;";
+ code_ += " #[inline]";
+ code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
+ code_ += " let bits = flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc);";
+ code_ += " unsafe { Self::from_bits_unchecked(bits) }";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ code_ += "impl flatbuffers::Push for {{ENUM_NAME}} {";
+ code_ += " type Output = {{ENUM_NAME}};";
+ code_ += " #[inline]";
+ code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
+ code_ += " flatbuffers::emplace_scalar::<{{BASE_TYPE}}>"
+ "(dst, self.bits());";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ code_ += "impl flatbuffers::EndianScalar for {{ENUM_NAME}} {";
+ code_ += " #[inline]";
+ code_ += " fn to_little_endian(self) -> Self {";
+ code_ += " let bits = {{BASE_TYPE}}::to_le(self.bits());";
+ code_ += " unsafe { Self::from_bits_unchecked(bits) }";
+ code_ += " }";
+ code_ += " #[inline]";
+ code_ += " fn from_little_endian(self) -> Self {";
+ code_ += " let bits = {{BASE_TYPE}}::from_le(self.bits());";
+ code_ += " unsafe { Self::from_bits_unchecked(bits) }";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ return;
+ }
+
+ // Deprecated associated constants;
+ code_ += "#[deprecated(since = \"1.13\", note = \"Use associated constants"
+ " instead. This will no longer be generated in 2021.\")]";
+ code_ += "pub const ENUM_MIN_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}}"
+ " = {{ENUM_MIN_BASE_VALUE}};";
+ code_ += "#[deprecated(since = \"1.13\", note = \"Use associated constants"
+ " instead. This will no longer be generated in 2021.\")]";
+ code_ += "pub const ENUM_MAX_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}}"
+ " = {{ENUM_MAX_BASE_VALUE}};";
+ auto num_fields = NumToString(enum_def.size());
+ code_ += "#[deprecated(since = \"1.13\", note = \"Use associated constants"
+ " instead. This will no longer be generated in 2021.\")]";
+ code_ += "#[allow(non_camel_case_types)]";
+ code_ += "pub const ENUM_VALUES_{{ENUM_NAME_CAPS}}: [{{ENUM_NAME}}; " +
+ num_fields + "] = [";
+ ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
+ code_ += " " + GetEnumValue(enum_def, ev) + ",";
+ });
+ code_ += "];";
code_ += "";
+
+ GenComment(enum_def.doc_comment);
+ code_ +=
+ "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]";
+ code_ += "#[repr(transparent)]";
+ code_ += "pub struct {{ENUM_NAME}}(pub {{BASE_TYPE}});";
+ code_ += "#[allow(non_upper_case_globals)]";
+ code_ += "impl {{ENUM_NAME}} {";
+ ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
+ this->GenComment(ev.doc_comment, " ");
+ code_ += " pub const {{VARIANT}}: Self = Self({{VALUE}});";
+ });
+ code_ += "";
+ // Generate Associated constants
+ code_ += " pub const ENUM_MIN: {{BASE_TYPE}} = {{ENUM_MIN_BASE_VALUE}};";
+ code_ += " pub const ENUM_MAX: {{BASE_TYPE}} = {{ENUM_MAX_BASE_VALUE}};";
+ code_ += " pub const ENUM_VALUES: &'static [Self] = &[";
+ ForAllEnumValues(enum_def, [&](){
+ code_ += " Self::{{VARIANT}},";
+ });
+ code_ += " ];";
+ code_ += " /// Returns the variant's name or \"\" if unknown.";
+ code_ += " pub fn variant_name(self) -> Option<&'static str> {";
+ code_ += " match self {";
+ ForAllEnumValues(enum_def, [&](){
+ code_ += " Self::{{VARIANT}} => Some(\"{{VARIANT}}\"),";
+ });
+ code_ += " _ => None,";
+ code_ += " }";
+ code_ += " }";
+ code_ += "}";
+
+ // Generate Debug. Unknown variants are printed like "<UNKNOWN 42>".
+ code_ += "impl std::fmt::Debug for {{ENUM_NAME}} {";
+ code_ += " fn fmt(&self, f: &mut std::fmt::Formatter) ->"
+ " std::fmt::Result {";
+ code_ += " if let Some(name) = self.variant_name() {";
+ code_ += " f.write_str(name)";
+ code_ += " } else {";
+ code_ += " f.write_fmt(format_args!(\"<UNKNOWN {:?}>\", self.0))";
+ code_ += " }";
+ code_ += " }";
+ code_ += "}";
+
+ // Generate Follow and Push so we can serialize and stuff.
code_ += "impl<'a> flatbuffers::Follow<'a> for {{ENUM_NAME}} {";
code_ += " type Inner = Self;";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
- code_ += " flatbuffers::read_scalar_at::<Self>(buf, loc)";
- code_ += " }";
- code_ += "}";
- code_ += "";
- code_ += "impl flatbuffers::EndianScalar for {{ENUM_NAME}} {";
- code_ += " #[inline]";
- code_ += " fn to_little_endian(self) -> Self {";
- code_ += " let n = {{BASE_TYPE}}::to_le(self as {{BASE_TYPE}});";
- code_ += " let p = &n as *const {{BASE_TYPE}} as *const {{ENUM_NAME}};";
- code_ += " unsafe { *p }";
- code_ += " }";
- code_ += " #[inline]";
- code_ += " fn from_little_endian(self) -> Self {";
- code_ += " let n = {{BASE_TYPE}}::from_le(self as {{BASE_TYPE}});";
- code_ += " let p = &n as *const {{BASE_TYPE}} as *const {{ENUM_NAME}};";
- code_ += " unsafe { *p }";
+ code_ += " Self(flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc))";
code_ += " }";
code_ += "}";
code_ += "";
@@ -644,69 +667,23 @@
code_ += " type Output = {{ENUM_NAME}};";
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
- code_ += " flatbuffers::emplace_scalar::<{{ENUM_NAME}}>"
- "(dst, *self);";
+ code_ += " flatbuffers::emplace_scalar::<{{BASE_TYPE}}>"
+ "(dst, self.0);";
code_ += " }";
code_ += "}";
code_ += "";
-
- // Generate an array of all enumeration values.
- auto num_fields = NumToString(enum_def.size());
- code_ += "#[allow(non_camel_case_types)]";
- code_ += "const ENUM_VALUES_{{ENUM_NAME_CAPS}}:[{{ENUM_NAME}}; " +
- num_fields + "] = [";
- for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const auto &ev = **it;
- auto value = GetEnumValUse(enum_def, ev);
- auto suffix = *it != enum_def.Vals().back() ? "," : "";
- code_ += " " + value + suffix;
- }
- code_ += "];";
+ code_ += "impl flatbuffers::EndianScalar for {{ENUM_NAME}} {";
+ code_ += " #[inline]";
+ code_ += " fn to_little_endian(self) -> Self {";
+ code_ += " Self({{BASE_TYPE}}::to_le(self.0))";
+ code_ += " }";
+ code_ += " #[inline]";
+ code_ += " fn from_little_endian(self) -> Self {";
+ code_ += " Self({{BASE_TYPE}}::from_le(self.0))";
+ code_ += " }";
+ code_ += "}";
code_ += "";
- // Generate a string table for enum values.
- // Problem is, if values are very sparse that could generate really big
- // tables. Ideally in that case we generate a map lookup instead, but for
- // the moment we simply don't output a table at all.
- auto range = enum_def.Distance();
- // Average distance between values above which we consider a table
- // "too sparse". Change at will.
- static const uint64_t kMaxSparseness = 5;
- if (range / static_cast<uint64_t>(enum_def.size()) < kMaxSparseness) {
- code_ += "#[allow(non_camel_case_types)]";
- code_ += "const ENUM_NAMES_{{ENUM_NAME_CAPS}}:[&'static str; " +
- NumToString(range + 1) + "] = [";
-
- auto val = enum_def.Vals().front();
- for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
- ++it) {
- auto ev = *it;
- for (auto k = enum_def.Distance(val, ev); k > 1; --k) {
- code_ += " \"\",";
- }
- val = ev;
- auto suffix = *it != enum_def.Vals().back() ? "," : "";
- code_ += " \"" + Name(*ev) + "\"" + suffix;
- }
- code_ += "];";
- code_ += "";
-
- code_ +=
- "pub fn enum_name_{{ENUM_NAME_SNAKE}}(e: {{ENUM_NAME}}) -> "
- "&'static str {";
-
- code_ += " let index = e as {{BASE_TYPE}}\\";
- if (enum_def.MinValue()->IsNonZero()) {
- auto vals = GetEnumValUse(enum_def, *enum_def.MinValue());
- code_ += " - " + vals + " as {{BASE_TYPE}}\\";
- }
- code_ += ";";
-
- code_ += " ENUM_NAMES_{{ENUM_NAME_CAPS}}[index as usize]";
- code_ += "}";
- code_ += "";
- }
-
if (enum_def.is_union) {
// Generate tyoesafe offset(s) for unions
code_.SetValue("NAME", Name(enum_def));
@@ -719,30 +696,32 @@
return "VT_" + MakeUpper(Name(field));
}
- std::string GetDefaultConstant(const FieldDef &field) {
- return field.value.type.base_type == BASE_TYPE_FLOAT
- ? field.value.constant + ""
- : field.value.constant;
- }
-
std::string GetDefaultScalarValue(const FieldDef &field) {
switch (GetFullType(field.value.type)) {
- case ftInteger: { return GetDefaultConstant(field); }
- case ftFloat: { return GetDefaultConstant(field); }
+ case ftInteger:
+ case ftFloat: {
+ return field.optional ? "None" : field.value.constant;
+ }
case ftBool: {
- return field.value.constant == "0" ? "false" : "true";
+ return field.optional ? "None"
+ : field.value.constant == "0" ? "false" : "true";
}
case ftUnionKey:
case ftEnumKey: {
+ if (field.optional) {
+ return "None";
+ }
auto ev = field.value.type.enum_def->FindByValue(field.value.constant);
assert(ev);
return WrapInNameSpace(field.value.type.enum_def->defined_namespace,
- GetEnumValUse(*field.value.type.enum_def, *ev));
+ GetEnumValue(*field.value.type.enum_def, *ev));
}
// All pointer-ish types have a default value of None, because they are
// wrapped in Option.
- default: { return "None"; }
+ default: {
+ return "None";
+ }
}
}
@@ -759,14 +738,14 @@
// 3) return a hardcoded value because the vtable field value is set to zero.
std::string TableBuilderArgsDefnType(const FieldDef &field,
const std::string &lifetime) {
- const Type& type = field.value.type;
+ const Type &type = field.value.type;
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool: {
const auto typname = GetTypeBasic(type);
- return typname;
+ return field.optional ? "Option<" + typname + ">" : typname;
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
@@ -774,7 +753,7 @@
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime + \
+ return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime +
">>>";
}
case ftString: {
@@ -783,109 +762,87 @@
case ftEnumKey:
case ftUnionKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
- return typname;
+ return field.optional ? "Option<" + typname + ">" : typname;
}
case ftUnionValue: {
return "Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>";
}
case ftVectorOfInteger:
+ case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \
- lifetime + ", " + typname + ">>>";
- }
- case ftVectorOfBool: {
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \
- lifetime + ", bool>>>";
+ return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
+ ", " + typname + ">>>";
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \
- lifetime + ", " + typname + ">>>";
+ return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
+ ", " + typname + ">>>";
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \
- lifetime + ", " + typname + ">>>";
+ return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
+ ", " + typname + ">>>";
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \
- lifetime + ", flatbuffers::ForwardsUOffset<" + typname + \
- "<" + lifetime + ">>>>>";
+ return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime +
+ ">>>>>";
}
case ftVectorOfString: {
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \
- lifetime + ", flatbuffers::ForwardsUOffset<&" + lifetime + \
- " str>>>>";
+ return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>>";
}
case ftVectorOfUnionValue: {
- const auto typname = WrapInNameSpace(*type.enum_def) + \
- "UnionTableOffset";
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \
- lifetime + ", flatbuffers::ForwardsUOffset<"
- "flatbuffers::Table<" + lifetime + ">>>>";
+ const auto typname =
+ WrapInNameSpace(*type.enum_def) + "UnionTableOffset";
+ return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<"
+ "flatbuffers::Table<" +
+ lifetime + ">>>>";
}
}
- return "INVALID_CODE_GENERATION"; // for return analysis
- }
-
- std::string TableBuilderArgsDefaultValue(const FieldDef &field) {
- return GetDefaultScalarValue(field);
- }
- std::string TableBuilderAddFuncDefaultValue(const FieldDef &field) {
- // All branches of switch do the same action!
- switch (GetFullType(field.value.type)) {
- case ftUnionKey:
- case ftEnumKey: {
- const std::string basetype = GetTypeBasic(field.value.type); //<- never used
- return GetDefaultScalarValue(field);
- }
-
- default: { return GetDefaultScalarValue(field); }
- }
+ return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string TableBuilderArgsAddFuncType(const FieldDef &field,
const std::string &lifetime) {
- const Type& type = field.value.type;
+ const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \
- ", " + typname + ">>";
+ return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
+ typname + ">>";
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \
- ", flatbuffers::ForwardsUOffset<" + typname + \
- "<" + lifetime + ">>>>";
+ return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime +
+ ">>>>";
}
case ftVectorOfInteger:
+ case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
- return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \
- ", " + typname + ">>";
- }
- case ftVectorOfBool: {
- return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \
- ", bool>>";
+ return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
+ typname + ">>";
}
case ftVectorOfString: {
- return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \
+ return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>";
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
- return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \
- ", " + typname + ">>";
+ return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
+ typname + ">>";
}
case ftVectorOfUnionValue: {
- return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \
- ", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + \
- lifetime + ">>>";
+ return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + lifetime +
+ ">>>";
}
case ftEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
@@ -893,19 +850,16 @@
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "&" + lifetime + " " + typname + "";
+ return "&" + typname + "";
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "flatbuffers::WIPOffset<" + typname + "<" + lifetime + ">>";
}
case ftInteger:
+ case ftBool:
case ftFloat: {
- const auto typname = GetTypeBasic(type);
- return typname;
- }
- case ftBool: {
- return "bool";
+ return GetTypeBasic(type);
}
case ftString: {
return "flatbuffers::WIPOffset<&" + lifetime + " str>";
@@ -919,26 +873,27 @@
}
}
- return "INVALID_CODE_GENERATION"; // for return analysis
+ return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string TableBuilderArgsAddFuncBody(const FieldDef &field) {
- const Type& type = field.value.type;
+ const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftInteger:
+ case ftBool:
case ftFloat: {
const auto typname = GetTypeBasic(field.value.type);
- return "self.fbb_.push_slot::<" + typname + ">";
+ return (field.optional ? "self.fbb_.push_slot_always::<"
+ : "self.fbb_.push_slot::<") +
+ typname + ">";
}
- case ftBool: {
- return "self.fbb_.push_slot::<bool>";
- }
-
case ftEnumKey:
case ftUnionKey: {
const auto underlying_typname = GetTypeBasic(type);
- return "self.fbb_.push_slot::<" + underlying_typname + ">";
+ return (field.optional ?
+ "self.fbb_.push_slot_always::<" :
+ "self.fbb_.push_slot::<") + underlying_typname + ">";
}
case ftStruct: {
@@ -947,8 +902,8 @@
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" + \
- typname + ">>";
+ return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" +
+ typname + ">>";
}
case ftUnionValue:
@@ -964,183 +919,265 @@
return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>";
}
}
- return "INVALID_CODE_GENERATION"; // for return analysis
+ return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string GenTableAccessorFuncReturnType(const FieldDef &field,
const std::string &lifetime) {
- const Type& type = field.value.type;
-
- switch (GetFullType(field.value.type)) {
- case ftInteger:
- case ftFloat: {
- const auto typname = GetTypeBasic(type);
- return typname;
- }
- case ftBool: {
- return "bool";
- }
- case ftStruct: {
- const auto typname = WrapInNameSpace(*type.struct_def);
- return WrapInOptionIfNotRequired("&" + lifetime + " " + typname, field.required);
- }
- case ftTable: {
- const auto typname = WrapInNameSpace(*type.struct_def);
- return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">", field.required);
- }
- case ftEnumKey:
- case ftUnionKey: {
- const auto typname = WrapInNameSpace(*type.enum_def);
- return typname;
- }
-
- case ftUnionValue: {
- return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">", field.required);
- }
- case ftString: {
- return WrapInOptionIfNotRequired("&" + lifetime + " str", field.required);
- }
- case ftVectorOfInteger:
- case ftVectorOfFloat: {
- const auto typname = GetTypeBasic(type.VectorType());
- if (IsOneByte(type.VectorType().base_type)) {
- return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", field.required);
- }
- return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", " + typname + ">", field.required);
- }
- case ftVectorOfBool: {
- return WrapInOptionIfNotRequired("&" + lifetime + " [bool]", field.required);
- }
- case ftVectorOfEnumKey: {
- const auto typname = WrapInNameSpace(*type.enum_def);
- return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", " + typname + ">", field.required);
- }
- case ftVectorOfStruct: {
- const auto typname = WrapInNameSpace(*type.struct_def);
- return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", field.required);
- }
- case ftVectorOfTable: {
- const auto typname = WrapInNameSpace(*type.struct_def);
- return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<" + \
- typname + "<" + lifetime + ">>>", field.required);
- }
- case ftVectorOfString: {
- return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<&" + \
- lifetime + " str>>", field.required);
- }
- case ftVectorOfUnionValue: {
- FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
- // TODO(rw): when we do support these, we should consider using the
- // Into trait to convert tables to typesafe union values.
- return "INVALID_CODE_GENERATION"; // for return analysis
- }
- }
- return "INVALID_CODE_GENERATION"; // for return analysis
- }
-
- std::string GenTableAccessorFuncBody(const FieldDef &field,
- const std::string &lifetime,
- const std::string &offset_prefix) {
- const std::string offset_name = offset_prefix + "::" + \
- GetFieldOffsetName(field);
- const Type& type = field.value.type;
+ const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat:
case ftBool: {
const auto typname = GetTypeBasic(type);
- const auto default_value = GetDefaultScalarValue(field);
- return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + \
- default_value + ")).unwrap()";
+ return field.optional ? "Option<" + typname + ">" : typname;
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return AddUnwrapIfRequired("self._tab.get::<" + typname + ">(" + offset_name + ", None)", field.required);
+ return WrapInOptionIfNotRequired("&" + lifetime + " " + typname,
+ field.required);
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" + \
- typname + "<" + lifetime + ">>>(" + offset_name + ", None)", field.required);
+ return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">",
+ field.required);
+ }
+ case ftEnumKey:
+ case ftUnionKey: {
+ const auto typname = WrapInNameSpace(*type.enum_def);
+ return field.optional ? "Option<" + typname + ">" : typname;
+ }
+
+ case ftUnionValue: {
+ return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">",
+ field.required);
+ }
+ case ftString: {
+ return WrapInOptionIfNotRequired("&" + lifetime + " str",
+ field.required);
+ }
+ case ftVectorOfInteger:
+ case ftVectorOfBool:
+ case ftVectorOfFloat: {
+ const auto typname = GetTypeBasic(type.VectorType());
+ if (IsOneByte(type.VectorType().base_type)) {
+ return WrapInOptionIfNotRequired(
+ "&" + lifetime + " [" + typname + "]", field.required);
+ }
+ return WrapInOptionIfNotRequired(
+ "flatbuffers::Vector<" + lifetime + ", " + typname + ">",
+ field.required);
+ }
+ case ftVectorOfEnumKey: {
+ const auto typname = WrapInNameSpace(*type.enum_def);
+ return WrapInOptionIfNotRequired(
+ "flatbuffers::Vector<" + lifetime + ", " + typname + ">",
+ field.required);
+ }
+ case ftVectorOfStruct: {
+ const auto typname = WrapInNameSpace(*type.struct_def);
+ return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]",
+ field.required);
+ }
+ case ftVectorOfTable: {
+ const auto typname = WrapInNameSpace(*type.struct_def);
+ return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<" +
+ typname + "<" + lifetime + ">>>",
+ field.required);
+ }
+ case ftVectorOfString: {
+ return WrapInOptionIfNotRequired(
+ "flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>",
+ field.required);
+ }
+ case ftVectorOfUnionValue: {
+ FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
+ // TODO(rw): when we do support these, we should consider using the
+ // Into trait to convert tables to typesafe union values.
+ return "INVALID_CODE_GENERATION"; // for return analysis
+ }
+ }
+ return "INVALID_CODE_GENERATION"; // for return analysis
+ }
+
+ std::string GenTableAccessorFuncBody(const FieldDef &field,
+ const std::string &lifetime,
+ const std::string &offset_prefix) {
+ const std::string offset_name =
+ offset_prefix + "::" + GetFieldOffsetName(field);
+ const Type &type = field.value.type;
+
+ switch (GetFullType(field.value.type)) {
+ case ftInteger:
+ case ftFloat:
+ case ftBool: {
+ const auto typname = GetTypeBasic(type);
+ if (field.optional) {
+ return "self._tab.get::<" + typname + ">(" + offset_name + ", None)";
+ } else {
+ const auto default_value = GetDefaultScalarValue(field);
+ return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" +
+ default_value + ")).unwrap()";
+ }
+ }
+ case ftStruct: {
+ const auto typname = WrapInNameSpace(*type.struct_def);
+ return AddUnwrapIfRequired(
+ "self._tab.get::<" + typname + ">(" + offset_name + ", None)",
+ field.required);
+ }
+ case ftTable: {
+ const auto typname = WrapInNameSpace(*type.struct_def);
+ return AddUnwrapIfRequired(
+ "self._tab.get::<flatbuffers::ForwardsUOffset<" + typname + "<" +
+ lifetime + ">>>(" + offset_name + ", None)",
+ field.required);
}
case ftUnionValue: {
- return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Table<" + lifetime + ">>>(" + offset_name + \
- ", None)", field.required);
+ return AddUnwrapIfRequired(
+ "self._tab.get::<flatbuffers::ForwardsUOffset<"
+ "flatbuffers::Table<" +
+ lifetime + ">>>(" + offset_name + ", None)",
+ field.required);
}
case ftUnionKey:
case ftEnumKey: {
- const auto underlying_typname = GetTypeBasic(type); //<- never used
- const auto typname = WrapInNameSpace(*type.enum_def);
- const auto default_value = GetDefaultScalarValue(field);
- return "self._tab.get::<" + typname + ">(" + offset_name + \
- ", Some(" + default_value + ")).unwrap()";
+ const std::string typname = WrapInNameSpace(*type.enum_def);
+ const std::string default_value = GetDefaultScalarValue(field);
+ if (field.optional) {
+ return "self._tab.get::<" + typname + ">(" + offset_name + ", None)";
+ } else {
+ return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" +
+ default_value + ")).unwrap()";
+ }
}
case ftString: {
- return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" + \
- offset_name + ", None)", field.required);
+ return AddUnwrapIfRequired(
+ "self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" +
+ offset_name + ", None)",
+ field.required);
}
case ftVectorOfInteger:
+ case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
- std::string s = "self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<" + lifetime + ", " + typname + \
- ">>>(" + offset_name + ", None)";
+ std::string s =
+ "self._tab.get::<flatbuffers::ForwardsUOffset<"
+ "flatbuffers::Vector<" +
+ lifetime + ", " + typname + ">>>(" + offset_name + ", None)";
// single-byte values are safe to slice
if (IsOneByte(type.VectorType().base_type)) {
s += ".map(|v| v.safe_slice())";
}
return AddUnwrapIfRequired(s, field.required);
}
- case ftVectorOfBool: {
- return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<" + lifetime + ", bool>>>(" + \
- offset_name + ", None).map(|v| v.safe_slice())", field.required);
- }
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
- return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<" + lifetime + ", " + typname + ">>>(" + \
- offset_name + ", None)", field.required);
+ return AddUnwrapIfRequired(
+ "self._tab.get::<flatbuffers::ForwardsUOffset<"
+ "flatbuffers::Vector<" +
+ lifetime + ", " + typname + ">>>(" + offset_name + ", None)",
+ field.required);
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<" + typname + ">>>(" + \
- offset_name + ", None).map(|v| v.safe_slice() )", field.required);
+ return AddUnwrapIfRequired(
+ "self._tab.get::<flatbuffers::ForwardsUOffset<"
+ "flatbuffers::Vector<" +
+ typname + ">>>(" + offset_name +
+ ", None).map(|v| v.safe_slice() )",
+ field.required);
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" + typname + \
- "<" + lifetime + ">>>>>(" + offset_name + ", None)", field.required);
+ return AddUnwrapIfRequired(
+ "self._tab.get::<flatbuffers::ForwardsUOffset<"
+ "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" +
+ typname + "<" + lifetime + ">>>>>(" + offset_name + ", None)",
+ field.required);
}
case ftVectorOfString: {
- return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" + \
- lifetime + " str>>>>(" + offset_name + ", None)", field.required);
+ return AddUnwrapIfRequired(
+ "self._tab.get::<flatbuffers::ForwardsUOffset<"
+ "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" +
+ lifetime + " str>>>>(" + offset_name + ", None)",
+ field.required);
}
case ftVectorOfUnionValue: {
FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
- return "INVALID_CODE_GENERATION"; // for return analysis
+ return "INVALID_CODE_GENERATION"; // for return analysis
}
}
- return "INVALID_CODE_GENERATION"; // for return analysis
+ return "INVALID_CODE_GENERATION"; // for return analysis
}
- bool TableFieldReturnsOption(const Type& type) {
- switch (GetFullType(type)) {
+ bool TableFieldReturnsOption(const FieldDef &field) {
+ if (field.optional) return true;
+ switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat:
case ftBool:
case ftEnumKey:
- case ftUnionKey:
- return false;
+ case ftUnionKey: return false;
default: return true;
}
}
+ // Generates a fully-qualified name getter for use with --gen-name-strings
+ void GenFullyQualifiedNameGetter(const StructDef &struct_def,
+ const std::string &name) {
+ code_ += " pub const fn get_fully_qualified_name() -> &'static str {";
+ code_ += " \"" +
+ struct_def.defined_namespace->GetFullyQualifiedName(name) + "\"";
+ code_ += " }";
+ code_ += "";
+ }
+
+ void ForAllUnionVariantsBesidesNone(
+ const EnumDef &def,
+ std::function<void(const EnumVal &ev)> cb
+ ) {
+ FLATBUFFERS_ASSERT(def.is_union);
+
+ for (auto it = def.Vals().begin(); it != def.Vals().end(); ++it) {
+ const EnumVal & ev = **it;
+ // TODO(cneo): Can variants be deprecated, should we skip them?
+ if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ code_.SetValue(
+ "U_ELEMENT_ENUM_TYPE",
+ WrapInNameSpace(def.defined_namespace, GetEnumValue(def, ev)));
+ code_.SetValue("U_ELEMENT_TABLE_TYPE",
+ WrapInNameSpace(ev.union_type.struct_def->defined_namespace,
+ ev.union_type.struct_def->name));
+ code_.SetValue("U_ELEMENT_NAME", MakeSnakeCase(Name(ev)));
+ cb(ev);
+ }
+ }
+
+ void ForAllTableFields(
+ const StructDef &struct_def,
+ std::function<void(const FieldDef&)> cb, bool reversed=false) {
+ // TODO(cneo): Remove `reversed` overload. It's only here to minimize the
+ // diff when refactoring to the `ForAllX` helper functions.
+ auto go = [&](const FieldDef& field) {
+ if (field.deprecated) return;
+ code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field));
+ code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset));
+ code_.SetValue("FIELD_NAME", Name(field));
+ code_.SetValue("DEFAULT_VALUE", GetDefaultScalarValue(field));
+ cb(field);
+ };
+ const auto &fields = struct_def.fields.vec;
+ if (reversed) {
+ for (auto it = fields.rbegin(); it != fields.rend(); ++it) go(**it);
+ } else {
+ for (auto it = fields.begin(); it != fields.end(); ++it) go(**it);
+ }
+ }
// Generate an accessor struct, builder struct, and create function for a
// table.
void GenTable(const StructDef &struct_def) {
@@ -1151,7 +1188,7 @@
// Generate an offset type, the base type, the Follow impl, and the
// init_from_table impl.
code_ += "pub enum {{OFFSET_TYPELABEL}} {}";
- code_ += "#[derive(Copy, Clone, Debug, PartialEq)]";
+ code_ += "#[derive(Copy, Clone, PartialEq)]";
code_ += "";
GenComment(struct_def.doc_comment);
@@ -1164,16 +1201,20 @@
code_ += " type Inner = {{STRUCT_NAME}}<'a>;";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
- code_ += " Self {";
- code_ += " _tab: flatbuffers::Table { buf: buf, loc: loc },";
- code_ += " }";
+ code_ += " Self { _tab: flatbuffers::Table { buf, loc } }";
code_ += " }";
code_ += "}";
code_ += "";
code_ += "impl<'a> {{STRUCT_NAME}}<'a> {";
+
+ if (parser_.opts.generate_name_strings) {
+ GenFullyQualifiedNameGetter(struct_def, struct_def.name);
+ }
+
code_ += " #[inline]";
- code_ += " pub fn init_from_table(table: flatbuffers::Table<'a>) -> "
- "Self {";
+ code_ +=
+ " pub fn init_from_table(table: flatbuffers::Table<'a>) -> "
+ "Self {";
code_ += " {{STRUCT_NAME}} {";
code_ += " _tab: table,";
code_ += " }";
@@ -1181,57 +1222,44 @@
// Generate a convenient create* function that uses the above builder
// to create a table in one function call.
- code_.SetValue("MAYBE_US",
- struct_def.fields.vec.size() == 0 ? "_" : "");
+ code_.SetValue("MAYBE_US", struct_def.fields.vec.size() == 0 ? "_" : "");
code_.SetValue("MAYBE_LT",
- TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : "");
+ TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : "");
code_ += " #[allow(unused_mut)]";
code_ += " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(";
- code_ += " _fbb: "
- "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,";
- code_ += " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})"
- " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {";
+ code_ +=
+ " _fbb: "
+ "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,";
+ code_ +=
+ " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})"
+ " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {";
code_ += " let mut builder = {{STRUCT_NAME}}Builder::new(_fbb);";
for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
size; size /= 2) {
- for (auto it = struct_def.fields.vec.rbegin();
- it != struct_def.fields.vec.rend(); ++it) {
- const auto &field = **it;
- // TODO(rw): fully understand this sortbysize usage
- if (!field.deprecated && (!struct_def.sortbysize ||
- size == SizeOf(field.value.type.base_type))) {
- code_.SetValue("FIELD_NAME", Name(field));
- if (TableFieldReturnsOption(field.value.type)) {
- code_ += " if let Some(x) = args.{{FIELD_NAME}} "
- "{ builder.add_{{FIELD_NAME}}(x); }";
- } else {
- code_ += " builder.add_{{FIELD_NAME}}(args.{{FIELD_NAME}});";
- }
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ if (struct_def.sortbysize && size != SizeOf(field.value.type.base_type))
+ return;
+ if (TableFieldReturnsOption(field)) {
+ code_ +=
+ " if let Some(x) = args.{{FIELD_NAME}} "
+ "{ builder.add_{{FIELD_NAME}}(x); }";
+ } else {
+ code_ += " builder.add_{{FIELD_NAME}}(args.{{FIELD_NAME}});";
}
- }
+ }, /*reverse=*/true);
}
code_ += " builder.finish()";
code_ += " }";
code_ += "";
// Generate field id constants.
- if (struct_def.fields.vec.size() > 0) {
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated) {
- // Deprecated fields won't be accessible.
- continue;
- }
-
- code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field));
- code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset));
- code_ += " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = "
- "{{OFFSET_VALUE}};";
- }
- code_ += "";
- }
+ ForAllTableFields(struct_def, [&](const FieldDef &unused){
+ (void) unused;
+ code_ += " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = "
+ "{{OFFSET_VALUE}};";
+ });
+ if (struct_def.fields.vec.size() > 0) code_ += "";
// Generate the accessors. Each has one of two forms:
//
@@ -1245,30 +1273,20 @@
// self._tab.get::<internal_type>(offset, defaultval).unwrap()
// }
const auto offset_prefix = Name(struct_def);
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated) {
- // Deprecated fields won't be accessible.
- continue;
- }
-
- code_.SetValue("FIELD_NAME", Name(field));
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
code_.SetValue("RETURN_TYPE",
GenTableAccessorFuncReturnType(field, "'a"));
code_.SetValue("FUNC_BODY",
GenTableAccessorFuncBody(field, "'a", offset_prefix));
- GenComment(field.doc_comment, " ");
+ this->GenComment(field.doc_comment, " ");
code_ += " #[inline]";
code_ += " pub fn {{FIELD_NAME}}(&self) -> {{RETURN_TYPE}} {";
code_ += " {{FUNC_BODY}}";
code_ += " }";
// Generate a comparison function for this field if it is a key.
- if (field.key) {
- GenKeyFieldMethods(field);
- }
+ if (field.key) { GenKeyFieldMethods(field); }
// Generate a nested flatbuffer field, if applicable.
auto nested = field.attributes.Lookup("nested_flatbuffer");
@@ -1281,80 +1299,84 @@
nested_root = parser_.LookupStruct(qualified_name);
}
FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
- (void)nested_root;
- code_.SetValue("OFFSET_NAME",
- offset_prefix + "::" + GetFieldOffsetName(field));
- code_ += " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> "
- " Option<{{STRUCT_NAME}}<'a>> {";
- code_ += " match self.{{FIELD_NAME}}() {";
- code_ += " None => { None }";
- code_ += " Some(data) => {";
- code_ += " use self::flatbuffers::Follow;";
- code_ += " Some(<flatbuffers::ForwardsUOffset"
- "<{{STRUCT_NAME}}<'a>>>::follow(data, 0))";
- code_ += " },";
- code_ += " }";
+ code_.SetValue("NESTED", WrapInNameSpace(*nested_root));
+ code_ +=
+ " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> \\";
+ if (field.required) {
+ code_ += "{{NESTED}}<'a> {";
+ code_ += " let data = self.{{FIELD_NAME}}();";
+ code_ += " use flatbuffers::Follow;";
+ code_ += " <flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>"
+ "::follow(data, 0)";
+ } else {
+ code_ += "Option<{{NESTED}}<'a>> {";
+ code_ += " self.{{FIELD_NAME}}().map(|data| {";
+ code_ += " use flatbuffers::Follow;";
+ code_ += " <flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>"
+ "::follow(data, 0)";
+ code_ += " })";
+ }
code_ += " }";
}
- }
+ });
// Explicit specializations for union accessors
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated || field.value.type.base_type != BASE_TYPE_UNION) {
- continue;
- }
-
- auto u = field.value.type.enum_def;
-
- code_.SetValue("FIELD_NAME", Name(field));
-
- for (auto u_it = u->Vals().begin(); u_it != u->Vals().end(); ++u_it) {
- auto &ev = **u_it;
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
-
- auto table_init_type = WrapInNameSpace(
- ev.union_type.struct_def->defined_namespace,
- ev.union_type.struct_def->name);
-
- code_.SetValue("U_ELEMENT_ENUM_TYPE",
- WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev)));
- code_.SetValue("U_ELEMENT_TABLE_TYPE", table_init_type);
- code_.SetValue("U_ELEMENT_NAME", MakeSnakeCase(Name(ev)));
-
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ if (field.value.type.base_type != BASE_TYPE_UNION) return;
+ code_.SetValue("FIELD_TYPE_FIELD_NAME", field.name);
+ ForAllUnionVariantsBesidesNone(
+ *field.value.type.enum_def, [&](const EnumVal &unused){
+ (void) unused;
code_ += " #[inline]";
code_ += " #[allow(non_snake_case)]";
- code_ += " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> "
- "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {";
- code_ += " if self.{{FIELD_NAME}}_type() == {{U_ELEMENT_ENUM_TYPE}} {";
- code_ += " self.{{FIELD_NAME}}().map(|u| "
- "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
+ code_ +=
+ " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> "
+ "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {";
+ // If the user defined schemas name a field that clashes with a
+ // language reserved word, flatc will try to escape the field name by
+ // appending an underscore. This works well for most cases, except
+ // one. When generating union accessors (and referring to them
+ // internally within the code generated here), an extra underscore
+ // will be appended to the name, causing build failures.
+ //
+ // This only happens when unions have members that overlap with
+ // language reserved words.
+ //
+ // To avoid this problem the type field name is used unescaped here:
+ code_ +=
+ " if self.{{FIELD_TYPE_FIELD_NAME}}_type() == "
+ "{{U_ELEMENT_ENUM_TYPE}} {";
+
+ // The following logic is not tested in the integration test,
+ // as of April 10, 2020
+ if (field.required) {
+ code_ += " let u = self.{{FIELD_NAME}}();";
+ code_ += " Some({{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
+ } else {
+ code_ +=
+ " self.{{FIELD_NAME}}().map("
+ "{{U_ELEMENT_TABLE_TYPE}}::init_from_table)";
+ }
code_ += " } else {";
code_ += " None";
code_ += " }";
code_ += " }";
code_ += "";
- }
- }
+ });
+ });
code_ += "}"; // End of table impl.
code_ += "";
// Generate an args struct:
code_.SetValue("MAYBE_LT",
- TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : "");
+ TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : "");
code_ += "pub struct {{STRUCT_NAME}}Args{{MAYBE_LT}} {";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (!field.deprecated) {
- code_.SetValue("PARAM_NAME", Name(field));
- code_.SetValue("PARAM_TYPE", TableBuilderArgsDefnType(field, "'a "));
- code_ += " pub {{PARAM_NAME}}: {{PARAM_TYPE}},";
- }
- }
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ code_.SetValue("PARAM_TYPE", TableBuilderArgsDefnType(field, "'a"));
+ code_ += " pub {{FIELD_NAME}}: {{PARAM_TYPE}},";
+ });
code_ += "}";
// Generate an impl of Default for the *Args type:
@@ -1362,16 +1384,10 @@
code_ += " #[inline]";
code_ += " fn default() -> Self {";
code_ += " {{STRUCT_NAME}}Args {";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (!field.deprecated) {
- code_.SetValue("PARAM_VALUE", TableBuilderArgsDefaultValue(field));
- code_.SetValue("REQ", field.required ? " // required field" : "");
- code_.SetValue("PARAM_NAME", Name(field));
- code_ += " {{PARAM_NAME}}: {{PARAM_VALUE}},{{REQ}}";
- }
- }
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ code_ += " {{FIELD_NAME}}: {{DEFAULT_VALUE}},\\";
+ code_ += field.required ? " // required field" : "";
+ });
code_ += " }";
code_ += " }";
code_ += "}";
@@ -1379,49 +1395,42 @@
// Generate a builder struct:
code_ += "pub struct {{STRUCT_NAME}}Builder<'a: 'b, 'b> {";
code_ += " fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,";
- code_ += " start_: flatbuffers::WIPOffset<"
- "flatbuffers::TableUnfinishedWIPOffset>,";
+ code_ +=
+ " start_: flatbuffers::WIPOffset<"
+ "flatbuffers::TableUnfinishedWIPOffset>,";
code_ += "}";
// Generate builder functions:
code_ += "impl<'a: 'b, 'b> {{STRUCT_NAME}}Builder<'a, 'b> {";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (!field.deprecated) {
- const bool is_scalar = IsScalar(field.value.type.base_type);
-
- std::string offset = GetFieldOffsetName(field);
-
- // Generate functions to add data, which take one of two forms.
- //
- // If a value has a default:
- // fn add_x(x_: type) {
- // fbb_.push_slot::<type>(offset, x_, Some(default));
- // }
- //
- // If a value does not have a default:
- // fn add_x(x_: type) {
- // fbb_.push_slot_always::<type>(offset, x_);
- // }
- code_.SetValue("FIELD_NAME", Name(field));
- code_.SetValue("FIELD_OFFSET", Name(struct_def) + "::" + offset);
- code_.SetValue("FIELD_TYPE", TableBuilderArgsAddFuncType(field, "'b "));
- code_.SetValue("FUNC_BODY", TableBuilderArgsAddFuncBody(field));
- code_ += " #[inline]";
- code_ += " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: "
- "{{FIELD_TYPE}}) {";
- if (is_scalar) {
- code_.SetValue("FIELD_DEFAULT_VALUE",
- TableBuilderAddFuncDefaultValue(field));
- code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, "
- "{{FIELD_DEFAULT_VALUE}});";
- } else {
- code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}});";
- }
- code_ += " }";
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ const bool is_scalar = IsScalar(field.value.type.base_type);
+ std::string offset = GetFieldOffsetName(field);
+ // Generate functions to add data, which take one of two forms.
+ //
+ // If a value has a default:
+ // fn add_x(x_: type) {
+ // fbb_.push_slot::<type>(offset, x_, Some(default));
+ // }
+ //
+ // If a value does not have a default:
+ // fn add_x(x_: type) {
+ // fbb_.push_slot_always::<type>(offset, x_);
+ // }
+ code_.SetValue("FIELD_OFFSET", Name(struct_def) + "::" + offset);
+ code_.SetValue("FIELD_TYPE", TableBuilderArgsAddFuncType(field, "'b "));
+ code_.SetValue("FUNC_BODY", TableBuilderArgsAddFuncBody(field));
+ code_ += " #[inline]";
+ code_ += " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: "
+ "{{FIELD_TYPE}}) {";
+ if (is_scalar && !field.optional) {
+ code_ +=
+ " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, "
+ "{{DEFAULT_VALUE}});";
+ } else {
+ code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}});";
}
- }
+ code_ += " }";
+ });
// Struct initializer (all fields required);
code_ += " #[inline]";
@@ -1438,24 +1447,60 @@
// finish() function.
code_ += " #[inline]";
- code_ += " pub fn finish(self) -> "
- "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {";
+ code_ +=
+ " pub fn finish(self) -> "
+ "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {";
code_ += " let o = self.fbb_.end_table(self.start_);";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (!field.deprecated && field.required) {
- code_.SetValue("FIELD_NAME", MakeSnakeCase(Name(field)));
- code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field));
- code_ += " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}},"
- "\"{{FIELD_NAME}}\");";
- }
- }
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ if (!field.required) return;
+ code_ +=
+ " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}},"
+ "\"{{FIELD_NAME}}\");";
+ });
code_ += " flatbuffers::WIPOffset::new(o.value())";
code_ += " }";
code_ += "}";
code_ += "";
+
+ code_ += "impl std::fmt::Debug for {{STRUCT_NAME}}<'_> {";
+ code_ += " fn fmt(&self, f: &mut std::fmt::Formatter<'_>"
+ ") -> std::fmt::Result {";
+ code_ += " let mut ds = f.debug_struct(\"{{STRUCT_NAME}}\");";
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ if (GetFullType(field.value.type) == ftUnionValue) {
+ // Generate a match statement to handle unions properly.
+ code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, ""));
+ code_.SetValue("FIELD_TYPE_FIELD_NAME", field.name);
+ code_.SetValue("UNION_ERR", "&\"InvalidFlatbuffer: Union discriminant"
+ " does not match value.\"");
+
+ code_ += " match self.{{FIELD_NAME}}_type() {";
+ ForAllUnionVariantsBesidesNone(*field.value.type.enum_def,
+ [&](const EnumVal &unused){
+ (void) unused;
+ code_ += " {{U_ELEMENT_ENUM_TYPE}} => {";
+ code_ += " if let Some(x) = self.{{FIELD_TYPE_FIELD_NAME}}_as_"
+ "{{U_ELEMENT_NAME}}() {";
+ code_ += " ds.field(\"{{FIELD_NAME}}\", &x)";
+ code_ += " } else {";
+ code_ += " ds.field(\"{{FIELD_NAME}}\", {{UNION_ERR}})";
+ code_ += " }";
+ code_ += " },";
+ });
+ code_ += " _ => { ";
+ code_ += " let x: Option<()> = None;";
+ code_ += " ds.field(\"{{FIELD_NAME}}\", &x)";
+ code_ += " },";
+ code_ += " };";
+ } else {
+ // Most fields.
+ code_ += " ds.field(\"{{FIELD_NAME}}\", &self.{{FIELD_NAME}}());";
+ }
+ });
+ code_ += " ds.finish()";
+ code_ += " }";
+ code_ += "}";
}
// Generate functions to compare tables and structs by key. This function
@@ -1466,14 +1511,16 @@
code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, ""));
code_ += " #[inline]";
- code_ += " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> "
- " bool {";
+ code_ +=
+ " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> "
+ " bool {";
code_ += " self.{{FIELD_NAME}}() < o.{{FIELD_NAME}}()";
code_ += " }";
code_ += "";
code_ += " #[inline]";
- code_ += " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> "
- " ::std::cmp::Ordering {";
+ code_ +=
+ " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> "
+ " ::std::cmp::Ordering {";
code_ += " let key = self.{{FIELD_NAME}}();";
code_ += " key.cmp(&val)";
code_ += " }";
@@ -1499,16 +1546,19 @@
code_ += "";
code_ += "#[inline]";
- code_ += "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}"
- "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {";
- code_ += " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>"
- "(buf)";
+ code_ +=
+ "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}"
+ "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {";
+ code_ +=
+ " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>"
+ "(buf)";
code_ += "}";
code_ += "";
if (parser_.file_identifier_.length()) {
// Declare the identifier
- code_ += "pub const {{STRUCT_NAME_CAPS}}_IDENTIFIER: &'static str\\";
+ // (no lifetime needed as constants have static lifetimes by default)
+ code_ += "pub const {{STRUCT_NAME_CAPS}}_IDENTIFIER: &str\\";
code_ += " = \"" + parser_.file_identifier_ + "\";";
code_ += "";
@@ -1516,22 +1566,22 @@
code_ += "#[inline]";
code_ += "pub fn {{STRUCT_NAME_SNAKECASE}}_buffer_has_identifier\\";
code_ += "(buf: &[u8]) -> bool {";
- code_ += " return flatbuffers::buffer_has_identifier(buf, \\";
- code_ += "{{STRUCT_NAME_CAPS}}_IDENTIFIER, false);";
+ code_ += " flatbuffers::buffer_has_identifier(buf, \\";
+ code_ += "{{STRUCT_NAME_CAPS}}_IDENTIFIER, false)";
code_ += "}";
code_ += "";
code_ += "#[inline]";
code_ += "pub fn {{STRUCT_NAME_SNAKECASE}}_size_prefixed\\";
code_ += "_buffer_has_identifier(buf: &[u8]) -> bool {";
- code_ += " return flatbuffers::buffer_has_identifier(buf, \\";
- code_ += "{{STRUCT_NAME_CAPS}}_IDENTIFIER, true);";
+ code_ += " flatbuffers::buffer_has_identifier(buf, \\";
+ code_ += "{{STRUCT_NAME_CAPS}}_IDENTIFIER, true)";
code_ += "}";
code_ += "";
}
if (parser_.file_extension_.length()) {
// Return the extension
- code_ += "pub const {{STRUCT_NAME_CAPS}}_EXTENSION: &'static str = \\";
+ code_ += "pub const {{STRUCT_NAME_CAPS}}_EXTENSION: &str = \\";
code_ += "\"" + parser_.file_extension_ + "\";";
code_ += "";
}
@@ -1550,13 +1600,15 @@
code_ += "}";
code_ += "";
code_ += "#[inline]";
- code_ += "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer"
- "<'a, 'b>("
- "fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, "
- "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {";
+ code_ +=
+ "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer"
+ "<'a, 'b>("
+ "fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, "
+ "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {";
if (parser_.file_identifier_.length()) {
- code_ += " fbb.finish_size_prefixed(root, "
- "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));";
+ code_ +=
+ " fbb.finish_size_prefixed(root, "
+ "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));";
} else {
code_ += " fbb.finish_size_prefixed(root, None);";
}
@@ -1577,8 +1629,8 @@
}
static void PaddingDefinition(int bits, std::string *code_ptr, int *id) {
- *code_ptr += " padding" + NumToString((*id)++) + "__: u" + \
- NumToString(bits) + ",";
+ *code_ptr +=
+ " padding" + NumToString((*id)++) + "__: u" + NumToString(bits) + ",";
}
static void PaddingInitializer(int bits, std::string *code_ptr, int *id) {
@@ -1586,6 +1638,18 @@
*code_ptr += "padding" + NumToString((*id)++) + "__: 0,";
}
+ void ForAllStructFields(
+ const StructDef &struct_def,
+ std::function<void(const FieldDef &field)> cb
+ ) {
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ code_.SetValue("FIELD_TYPE", GetTypeGet(field.value.type));
+ code_.SetValue("FIELD_NAME", Name(field));
+ cb(field);
+ }
+ }
// Generate an accessor struct with constructor for a flatbuffers struct.
void GenStruct(const StructDef &struct_def) {
// Generates manual padding and alignment.
@@ -1601,26 +1665,35 @@
// PartialEq is useful to derive because we can correctly compare structs
// for equality by just comparing their underlying byte data. This doesn't
// hold for PartialOrd/Ord.
- code_ += "#[derive(Clone, Copy, Debug, PartialEq)]";
+ code_ += "#[derive(Clone, Copy, PartialEq)]";
code_ += "pub struct {{STRUCT_NAME}} {";
int padding_id = 0;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- code_.SetValue("FIELD_TYPE", GetTypeGet(field.value.type));
- code_.SetValue("FIELD_NAME", Name(field));
+ ForAllStructFields(struct_def, [&](const FieldDef &field) {
code_ += " {{FIELD_NAME}}_: {{FIELD_TYPE}},";
-
if (field.padding) {
std::string padding;
GenPadding(field, &padding, &padding_id, PaddingDefinition);
code_ += padding;
}
- }
-
+ });
code_ += "} // pub struct {{STRUCT_NAME}}";
+ // Debug for structs.
+ code_ += "impl std::fmt::Debug for {{STRUCT_NAME}} {";
+ code_ += " fn fmt(&self, f: &mut std::fmt::Formatter"
+ ") -> std::fmt::Result {";
+ code_ += " f.debug_struct(\"{{STRUCT_NAME}}\")";
+ ForAllStructFields(struct_def, [&](const FieldDef &unused) {
+ (void) unused;
+ code_ += " .field(\"{{FIELD_NAME}}\", &self.{{FIELD_NAME}}())";
+ });
+ code_ += " .finish()";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+
+
// Generate impls for SafeSliceAccess (because all structs are endian-safe),
// Follow for the value type, Follow for the reference type, Push for the
// value type, and Push for the reference type.
@@ -1644,8 +1717,9 @@
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
code_ += " let src = unsafe {";
- code_ += " ::std::slice::from_raw_parts("
- "self as *const {{STRUCT_NAME}} as *const u8, Self::size())";
+ code_ +=
+ " ::std::slice::from_raw_parts("
+ "self as *const {{STRUCT_NAME}} as *const u8, Self::size())";
code_ += " };";
code_ += " dst.copy_from_slice(src);";
code_ += " }";
@@ -1656,8 +1730,9 @@
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
code_ += " let src = unsafe {";
- code_ += " ::std::slice::from_raw_parts("
- "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())";
+ code_ +=
+ " ::std::slice::from_raw_parts("
+ "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())";
code_ += " };";
code_ += " dst.copy_from_slice(src);";
code_ += " }";
@@ -1667,86 +1742,81 @@
// Generate a constructor that takes all fields as arguments.
code_ += "impl {{STRUCT_NAME}} {";
- std::string arg_list;
- std::string init_list;
- padding_id = 0;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- const auto member_name = Name(field) + "_";
- const auto reference = StructMemberAccessNeedsCopy(field.value.type)
- ? "" : "&'a ";
- const auto arg_name = "_" + Name(field);
- const auto arg_type = reference + GetTypeGet(field.value.type);
-
- if (it != struct_def.fields.vec.begin()) {
- arg_list += ", ";
- }
- arg_list += arg_name + ": ";
- arg_list += arg_type;
- init_list += " " + member_name;
- if (StructMemberAccessNeedsCopy(field.value.type)) {
- init_list += ": " + arg_name + ".to_little_endian(),\n";
- } else {
- init_list += ": *" + arg_name + ",\n";
- }
- }
-
- code_.SetValue("ARG_LIST", arg_list);
- code_.SetValue("INIT_LIST", init_list);
- code_ += " pub fn new<'a>({{ARG_LIST}}) -> Self {";
+ // TODO(cneo): Stop generating args on one line. Make it simpler.
+ bool first_arg = true;
+ code_ += " pub fn new(\\";
+ ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ if (first_arg) first_arg = false; else code_ += ", \\";
+ code_.SetValue("REF", IsStruct(field.value.type) ? "&" : "");
+ code_ += "_{{FIELD_NAME}}: {{REF}}{{FIELD_TYPE}}\\";
+ });
+ code_ += ") -> Self {";
code_ += " {{STRUCT_NAME}} {";
- code_ += "{{INIT_LIST}}";
+
+ ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ const bool is_struct = IsStruct(field.value.type);
+ code_.SetValue("DEREF", is_struct ? "*" : "");
+ code_.SetValue("TO_LE", is_struct ? "" : ".to_little_endian()");
+ code_ += " {{FIELD_NAME}}_: {{DEREF}}_{{FIELD_NAME}}{{TO_LE}},";
+ });
+ code_ += "";
+
+ // TODO(cneo): Does this padding even work? Why after all the fields?
padding_id = 0;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ ForAllStructFields(struct_def, [&](const FieldDef &field) {
if (field.padding) {
std::string padding;
GenPadding(field, &padding, &padding_id, PaddingInitializer);
code_ += " " + padding;
}
- }
+ });
code_ += " }";
code_ += " }";
+ if (parser_.opts.generate_name_strings) {
+ GenFullyQualifiedNameGetter(struct_def, struct_def.name);
+ }
+
// Generate accessor methods for the struct.
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ const bool is_struct = IsStruct(field.value.type);
+ code_.SetValue("REF", is_struct ? "&" : "");
+ code_.SetValue("FROM_LE", is_struct ? "" : ".from_little_endian()");
- auto field_type = TableBuilderArgsAddFuncType(field, "'a");
- auto member = "self." + Name(field) + "_";
- auto value = StructMemberAccessNeedsCopy(field.value.type) ?
- member + ".from_little_endian()" : member;
-
- code_.SetValue("FIELD_NAME", Name(field));
- code_.SetValue("FIELD_TYPE", field_type);
- code_.SetValue("FIELD_VALUE", value);
- code_.SetValue("REF", IsStruct(field.value.type) ? "&" : "");
-
- GenComment(field.doc_comment, " ");
- code_ += " pub fn {{FIELD_NAME}}<'a>(&'a self) -> {{FIELD_TYPE}} {";
- code_ += " {{REF}}{{FIELD_VALUE}}";
+ this->GenComment(field.doc_comment, " ");
+ code_ += " pub fn {{FIELD_NAME}}(&self) -> {{REF}}{{FIELD_TYPE}} {";
+ code_ += " {{REF}}self.{{FIELD_NAME}}_{{FROM_LE}}";
code_ += " }";
// Generate a comparison function for this field if it is a key.
- if (field.key) {
- GenKeyFieldMethods(field);
- }
- }
+ if (field.key) { GenKeyFieldMethods(field); }
+ });
code_ += "}";
code_ += "";
}
void GenNamespaceImports(const int white_spaces) {
- std::string indent = std::string(white_spaces, ' ');
- code_ += "";
- code_ += indent + "use std::mem;";
- code_ += indent + "use std::cmp::Ordering;";
- code_ += "";
- code_ += indent + "extern crate flatbuffers;";
- code_ += indent + "use self::flatbuffers::EndianScalar;";
+ if (white_spaces == 0) {
+ code_ += "#![allow(unused_imports, dead_code)]";
+ }
+ std::string indent = std::string(white_spaces, ' ');
+ code_ += "";
+ if (!parser_.opts.generate_all) {
+ for (auto it = parser_.included_files_.begin();
+ it != parser_.included_files_.end(); ++it) {
+ if (it->second.empty()) continue;
+ auto noext = flatbuffers::StripExtension(it->second);
+ auto basename = flatbuffers::StripPath(noext);
+
+ code_ += indent + "use crate::" + basename + "_generated::*;";
+ }
+ }
+
+ code_ += indent + "use std::mem;";
+ code_ += indent + "use std::cmp::Ordering;";
+ code_ += "";
+ code_ += indent + "extern crate flatbuffers;";
+ code_ += indent + "use self::flatbuffers::EndianScalar;";
}
// Set up the correct namespace. This opens a namespace if the current
@@ -1805,7 +1875,9 @@
const std::string &file_name) {
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
- std::string make_rule = GeneratedFileName(path, filebase) + ": ";
+ rust::RustGenerator generator(parser, path, file_name);
+ std::string make_rule =
+ generator.GeneratedFileName(path, filebase, parser.opts) + ": ";
auto included_files = parser.GetIncludedFilesRecursive(file_name);
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
@@ -1823,3 +1895,10 @@
// TODO(rw): Generated code should generate endian-safe Debug impls.
// TODO(rw): Generated code could use a Rust-only enum type to access unions,
// instead of making the user use _type() to manually switch.
+// TODO(maxburke): There should be test schemas added that use language
+// keywords as fields of structs, tables, unions, enums, to make sure
+// that internal code generated references escaped names correctly.
+// TODO(maxburke): We should see if there is a more flexible way of resolving
+// module paths for use declarations. Right now if schemas refer to
+// other flatbuffer files, the include paths in emitted Rust bindings
+// are crate-relative which may undesirable.