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_js_ts.cpp b/src/idl_gen_js_ts.cpp
index 9c89c1a..0240f51 100644
--- a/src/idl_gen_js_ts.cpp
+++ b/src/idl_gen_js_ts.cpp
@@ -15,6 +15,7 @@
*/
// independent from idl_parser, since this code is not needed for most clients
+#include <algorithm>
#include <cassert>
#include <unordered_map>
#include <unordered_set>
@@ -26,8 +27,6 @@
namespace flatbuffers {
-const std::string kGeneratedFileNamePostfix = "_generated";
-
struct JsTsLanguageParameters {
IDLOptions::Language language;
std::string file_extension;
@@ -61,12 +60,6 @@
}
}
-static std::string GeneratedFileName(const std::string &path,
- const std::string &file_name,
- const JsTsLanguageParameters &lang) {
- return path + file_name + kGeneratedFileNamePostfix + lang.file_extension;
-}
-
namespace jsts {
// Iterate through all definitions we haven't generate code for (enums, structs,
// and tables) and output them to a single file.
@@ -78,7 +71,8 @@
JsTsGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
- : BaseGenerator(parser, path, file_name, "", "."),
+ : BaseGenerator(parser, path, file_name, "", ".",
+ parser.opts.lang == IDLOptions::kJs ? "js" : "ts"),
lang_(GetJsLangParams(parser_.opts.lang)) {}
// Iterate through all definitions we haven't generate code for (enums,
// structs, and tables) and output them to a single file.
@@ -87,7 +81,7 @@
reexport_map reexports;
std::string enum_code, struct_code, import_code, exports_code, code;
- generateEnums(&enum_code, &exports_code, reexports);
+ generateEnums(&enum_code, &exports_code, reexports, imported_files);
generateStructs(&struct_code, &exports_code, imported_files);
generateImportDependencies(&import_code, imported_files);
generateReexports(&import_code, reexports, imported_files);
@@ -112,8 +106,8 @@
code += exports_code;
}
- return SaveFile(GeneratedFileName(path_, file_name_, lang_).c_str(), code,
- false);
+ return SaveFile(GeneratedFileName(path_, file_name_, parser_.opts).c_str(),
+ code, false);
}
private:
@@ -127,9 +121,7 @@
const auto &file = *it;
const auto basename =
flatbuffers::StripPath(flatbuffers::StripExtension(file));
- if (basename != file_name_) {
- code += GenPrefixedImport(file, basename);
- }
+ if (basename != file_name_) { code += GenPrefixedImport(file, basename); }
}
}
@@ -142,34 +134,47 @@
return;
}
+ std::unordered_set<std::string> imported;
+
std::string &code = *code_ptr;
for (auto it = reexports.begin(); it != reexports.end(); ++it) {
const auto &file = *it;
const auto basename =
flatbuffers::StripPath(flatbuffers::StripExtension(file.first));
- if (basename != file_name_) {
+ if (basename != file_name_ &&
+ imported.find(file.second.symbol) == imported.end()) {
if (imported_files.find(file.first) == imported_files.end()) {
code += GenPrefixedImport(file.first, basename);
imported_files.emplace(file.first);
}
- code += "export namespace " + file.second.target_namespace + " { \n";
+ if (!file.second.target_namespace.empty()) {
+ code += "export namespace " + file.second.target_namespace + " { \n";
+ }
code += "export import " + file.second.symbol + " = ";
- code += GenFileNamespacePrefix(file.first) + "." +
- file.second.source_namespace + "." + file.second.symbol +
- "; }\n";
+ code += GenFileNamespacePrefix(file.first) + ".";
+ if (!file.second.source_namespace.empty()) {
+ code += file.second.source_namespace + ".";
+ }
+ code += file.second.symbol + ";\n";
+ if (!file.second.target_namespace.empty()) { code += "}\n"; }
+
+ imported.emplace(file.second.symbol);
}
}
}
// Generate code for all enums.
void generateEnums(std::string *enum_code_ptr, std::string *exports_code_ptr,
- reexport_map &reexports) {
+ reexport_map &reexports,
+ imported_fileset &imported_files) {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
- GenEnum(enum_def, enum_code_ptr, exports_code_ptr, reexports, false);
- GenEnum(enum_def, enum_code_ptr, exports_code_ptr, reexports, true);
+ GenEnum(enum_def, enum_code_ptr, exports_code_ptr, reexports,
+ imported_files, false);
+ GenEnum(enum_def, enum_code_ptr, exports_code_ptr, reexports,
+ imported_files, true);
}
}
@@ -213,13 +218,15 @@
// Emit namespaces in a form that Closure Compiler can optimize
std::string &code = *code_ptr;
std::string &exports = *exports_ptr;
+
+ if (lang_.language == IDLOptions::kTs) {
+ code += "import * as flatbuffers from 'flatbuffers';\n";
+ }
+
for (auto it = sorted_namespaces.begin(); it != sorted_namespaces.end();
++it) {
if (lang_.language == IDLOptions::kTs) {
- if (it->find('.') == std::string::npos) {
- code += "import { flatbuffers } from \"./flatbuffers\"\n";
- break;
- }
+ if (it->find('.') == std::string::npos) { break; }
} else {
code += "/**\n * @const\n * @namespace\n */\n";
if (it->find('.') == std::string::npos) {
@@ -309,14 +316,12 @@
result += " " + type_name;
break;
}
- default: { result += " {" + type_name + "}"; }
+ default: {
+ result += " {" + type_name + "}";
+ }
}
- if (!arg_name.empty()) {
- result += " " + arg_name;
- }
- if (include_newline) {
- result += "\n";
- }
+ if (!arg_name.empty()) { result += " " + arg_name; }
+ if (include_newline) { result += "\n"; }
return result;
}
@@ -324,7 +329,7 @@
// Generate an enum declaration and an enum string lookup table.
void GenEnum(EnumDef &enum_def, std::string *code_ptr,
std::string *exports_ptr, reexport_map &reexports,
- bool reverse) {
+ imported_fileset &imported_files, bool reverse) {
if (enum_def.generated) return;
if (reverse && lang_.language == IDLOptions::kTs) return; // FIXME.
std::string &code = *code_ptr;
@@ -359,7 +364,7 @@
// Generate mapping between EnumName: EnumValue(int)
if (reverse) {
- code += " " + enum_def.ToString(ev);
+ code += " '" + enum_def.ToString(ev) + "'";
code += lang_.language == IDLOptions::kTs ? "= " : ": ";
code += "'" + ev.name + "'";
} else {
@@ -371,16 +376,23 @@
code += (it + 1) != enum_def.Vals().end() ? ",\n" : "\n";
if (ev.union_type.struct_def) {
- ReexportDescription desc = { ev.name,
+ ReexportDescription desc = { ev.union_type.struct_def->name,
GetNameSpace(*ev.union_type.struct_def),
GetNameSpace(enum_def) };
reexports.insert(
std::make_pair(ev.union_type.struct_def->file, std::move(desc)));
}
}
+ code += "};";
- if (lang_.language == IDLOptions::kTs && !ns.empty()) { code += "}"; }
- code += "};\n\n";
+ if (lang_.language == IDLOptions::kTs) {
+ if (enum_def.is_union) {
+ code += GenUnionConvFunc(enum_def.underlying_type, imported_files);
+ }
+ if (!ns.empty()) { code += "\n}"; }
+ }
+
+ code += "\n\n";
}
static std::string GenType(const Type &type) {
@@ -408,7 +420,12 @@
switch (type.base_type) {
case BASE_TYPE_STRING: return GenBBAccess() + ".__string" + arguments;
case BASE_TYPE_STRUCT: return GenBBAccess() + ".__struct" + arguments;
- case BASE_TYPE_UNION: return GenBBAccess() + ".__union" + arguments;
+ case BASE_TYPE_UNION:
+ if (!UnionHasStringType(*type.enum_def) ||
+ lang_.language == IDLOptions::kJs) {
+ return GenBBAccess() + ".__union" + arguments;
+ }
+ return GenBBAccess() + ".__union_with_string" + arguments;
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType(), arguments);
default: {
auto getter =
@@ -425,12 +442,18 @@
}
}
- std::string GenBBAccess() {
+ std::string GenBBAccess() const {
return lang_.language == IDLOptions::kTs ? "this.bb!" : "this.bb";
}
- std::string GenDefaultValue(const Value &value, const std::string &context) {
- if (value.type.enum_def) {
+ std::string GenDefaultValue(const FieldDef &field, const std::string &context) {
+ if (field.IsScalarOptional()) {
+ return "null";
+ }
+
+ const auto &value = field.value;
+ if (value.type.enum_def && value.type.base_type != BASE_TYPE_UNION &&
+ value.type.base_type != BASE_TYPE_VECTOR) {
if (auto val = value.type.enum_def->FindByValue(value.constant)) {
if (lang_.language == IDLOptions::kTs) {
return GenPrefixedTypeName(WrapInNameSpace(*value.type.enum_def),
@@ -450,7 +473,13 @@
switch (value.type.base_type) {
case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
- case BASE_TYPE_STRING: return "null";
+ case BASE_TYPE_STRING:
+ case BASE_TYPE_UNION:
+ case BASE_TYPE_STRUCT: {
+ return "null";
+ }
+
+ case BASE_TYPE_VECTOR: return "[]";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: {
@@ -467,10 +496,9 @@
std::string GenTypeName(const Type &type, bool input,
bool allowNull = false) {
if (!input) {
- if (type.base_type == BASE_TYPE_STRING ||
- type.base_type == BASE_TYPE_STRUCT) {
+ if (IsString(type) || type.base_type == BASE_TYPE_STRUCT) {
std::string name;
- if (type.base_type == BASE_TYPE_STRING) {
+ if (IsString(type)) {
name = "string|Uint8Array";
} else {
name = WrapInNameSpace(*type.struct_def);
@@ -480,13 +508,17 @@
}
switch (type.base_type) {
- case BASE_TYPE_BOOL: return "boolean";
+ case BASE_TYPE_BOOL: return (allowNull) ? ("boolean|null") : ("boolean");
case BASE_TYPE_LONG:
- case BASE_TYPE_ULONG: return "flatbuffers.Long";
+ case BASE_TYPE_ULONG: return (allowNull) ? ("flatbuffers.Long|null") : ("flatbuffers.Long");
default:
if (IsScalar(type.base_type)) {
- if (type.enum_def) { return WrapInNameSpace(*type.enum_def); }
- return "number";
+ if (type.enum_def) {
+ const auto enum_name = WrapInNameSpace(*type.enum_def);
+ return (allowNull) ? (enum_name + "|null") : (enum_name);
+ }
+
+ return (allowNull) ? ("number|null") : ("number");
}
return "flatbuffers.Offset";
}
@@ -528,10 +560,10 @@
if (parser_.opts.keep_include_path) {
auto it = parser_.included_files_.find(full_file_name);
FLATBUFFERS_ASSERT(it != parser_.included_files_.end());
- path =
- flatbuffers::StripExtension(it->second) + kGeneratedFileNamePostfix;
+ path = flatbuffers::StripExtension(it->second) +
+ parser_.opts.filename_suffix;
} else {
- path = base_name + kGeneratedFileNamePostfix;
+ path = base_name + parser_.opts.filename_suffix;
}
// Add the include prefix and make the path always relative
@@ -566,11 +598,11 @@
nameprefix + field.name + "_");
} else {
*annotations +=
- GenTypeAnnotation(kParam, GenTypeName(field.value.type, true),
+ GenTypeAnnotation(kParam, GenTypeName(field.value.type, true, field.optional),
nameprefix + field.name);
if (lang_.language == IDLOptions::kTs) {
*arguments += ", " + nameprefix + field.name + ": " +
- GenTypeName(field.value.type, true);
+ GenTypeName(field.value.type, true, field.optional);
} else {
*arguments += ", " + nameprefix + field.name;
}
@@ -604,8 +636,14 @@
}
}
+ std::string GenerateNewExpression(const std::string &object_name) {
+ return "new " + object_name +
+ (lang_.language == IDLOptions::kTs ? "()" : "");
+ }
+
void GenerateRootAccessor(StructDef &struct_def, std::string *code_ptr,
- std::string &code, std::string &object_name, bool size_prefixed) {
+ std::string &code, std::string &object_name,
+ bool size_prefixed) {
if (!struct_def.fixed) {
GenDocComment(code_ptr,
GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") +
@@ -613,35 +651,43 @@
GenTypeAnnotation(kReturns, object_name, "", false));
std::string sizePrefixed("SizePrefixed");
if (lang_.language == IDLOptions::kTs) {
- code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" + Verbose(struct_def, "As");
+ code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" +
+ Verbose(struct_def, "As");
code += "(bb:flatbuffers.ByteBuffer, obj?:" + object_name +
"):" + object_name + " {\n";
} else {
- code += object_name + ".get" + (size_prefixed ? sizePrefixed : "") + "Root" + Verbose(struct_def, "As");
+ code += object_name + ".get" + (size_prefixed ? sizePrefixed : "") +
+ "Root" + Verbose(struct_def, "As");
code += " = function(bb, obj) {\n";
}
- code += " return (obj || new " + object_name;
+ if (size_prefixed) {
+ code +=
+ " bb.setPosition(bb.position() + "
+ "flatbuffers.SIZE_PREFIX_LENGTH);\n";
+ }
+ code += " return (obj || " + GenerateNewExpression(object_name);
code += ").__init(bb.readInt32(bb.position()) + bb.position(), bb);\n";
code += "};\n\n";
}
}
void GenerateFinisher(StructDef &struct_def, std::string *code_ptr,
- std::string &code, std::string &object_name, bool size_prefixed) {
+ std::string &code, std::string &object_name,
+ bool size_prefixed) {
if (parser_.root_struct_def_ == &struct_def) {
std::string sizePrefixed("SizePrefixed");
GenDocComment(
code_ptr,
GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") +
- GenTypeAnnotation(kParam, "flatbuffers.Offset", "offset",
- false));
+ GenTypeAnnotation(kParam, "flatbuffers.Offset", "offset", false));
if (lang_.language == IDLOptions::kTs) {
- code += "static finish" + (size_prefixed ? sizePrefixed : "") + Verbose(struct_def) + "Buffer";
- code +=
- "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n";
+ code += "static finish" + (size_prefixed ? sizePrefixed : "") +
+ Verbose(struct_def) + "Buffer";
+ code += "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n";
} else {
- code += object_name + ".finish" + (size_prefixed ? sizePrefixed : "") + Verbose(struct_def) + "Buffer";
+ code += object_name + ".finish" + (size_prefixed ? sizePrefixed : "") +
+ Verbose(struct_def) + "Buffer";
code += " = function(builder, offset) {\n";
}
@@ -650,9 +696,7 @@
code += ", '" + parser_.file_identifier_ + "'";
}
if (size_prefixed) {
- if (parser_.file_identifier_.empty()) {
- code += ", undefined";
- }
+ if (parser_.file_identifier_.empty()) { code += ", undefined"; }
code += ", true";
}
code += ");\n";
@@ -660,6 +704,602 @@
}
}
+ static std::string GetObjApiClassName(const StructDef &sd,
+ const IDLOptions &opts) {
+ return GetObjApiClassName(sd.name, opts);
+ }
+
+ static std::string GetObjApiClassName(const std::string &name,
+ const IDLOptions &opts) {
+ return opts.object_prefix + name + opts.object_suffix;
+ }
+
+ bool UnionHasStringType(const EnumDef &union_enum) {
+ return std::any_of(union_enum.Vals().begin(), union_enum.Vals().end(),
+ [](const EnumVal *ev) {
+ return !(ev->IsZero()) &&
+ (IsString(ev->union_type));
+ });
+ }
+
+ std::string GenUnionGenericTypeTS(const EnumDef &union_enum) {
+ return std::string("T") + (UnionHasStringType(union_enum) ? "|string" : "");
+ }
+
+ std::string GenUnionTypeTS(const EnumDef &union_enum,
+ imported_fileset &imported_files) {
+ std::string ret;
+ std::set<std::string> type_list;
+
+ for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+ if (ev.IsZero()) { continue; }
+
+ std::string type = "";
+ if (IsString(ev.union_type)) {
+ type = "string"; // no need to wrap string type in namespace
+ } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
+ if (!parser_.opts.generate_all) {
+ imported_files.insert(ev.union_type.struct_def->file);
+ }
+
+ type = GenPrefixedTypeName(WrapInNameSpace(*(ev.union_type.struct_def)),
+ ev.union_type.struct_def->file);
+ } else {
+ FLATBUFFERS_ASSERT(false);
+ }
+ type_list.insert(type);
+ }
+
+ for (auto it = type_list.begin(); it != type_list.end(); ++it) {
+ ret += *it + ((std::next(it) == type_list.end()) ? "" : "|");
+ }
+
+ return ret;
+ }
+
+ // Generate a TS union type based on a union's enum
+ std::string GenObjApiUnionTypeTS(const IDLOptions &opts,
+ const EnumDef &union_enum) {
+ std::string ret = "";
+ std::set<std::string> type_list;
+
+ for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+ if (ev.IsZero()) { continue; }
+
+ std::string type = "";
+ if (IsString(ev.union_type)) {
+ type = "string"; // no need to wrap string type in namespace
+ } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
+ type = GenPrefixedTypeName(
+ GetObjApiClassName(WrapInNameSpace(*(ev.union_type.struct_def)),
+ opts),
+ union_enum.file);
+ } else {
+ FLATBUFFERS_ASSERT(false);
+ }
+ type_list.insert(type);
+ }
+
+ size_t totalPrinted = 0;
+ for (auto it = type_list.begin(); it != type_list.end(); ++it) {
+ ++totalPrinted;
+ ret += *it + ((totalPrinted == type_list.size()) ? "" : "|");
+ }
+
+ return ret;
+ }
+
+ std::string GenUnionConvFuncName(const EnumDef &enum_def) {
+ return "unionTo" + enum_def.name;
+ }
+
+ std::string GenUnionListConvFuncName(const EnumDef &enum_def) {
+ return "unionListTo" + enum_def.name;
+ }
+
+ std::string GenUnionConvFunc(const Type &union_type,
+ imported_fileset &imported_files) {
+ if (union_type.enum_def) {
+ const auto &enum_def = *union_type.enum_def;
+
+ const auto valid_union_type = GenUnionTypeTS(enum_def, imported_files);
+ const auto valid_union_type_with_null = valid_union_type + "|null";
+
+ auto ret = "\n\nexport function " + GenUnionConvFuncName(enum_def) +
+ "(\n type: " + enum_def.name +
+ ",\n accessor: (obj:" + valid_union_type + ") => " +
+ valid_union_type_with_null +
+ "\n): " + valid_union_type_with_null + " {\n";
+
+ if (!parser_.opts.generate_all) {
+ imported_files.insert(union_type.enum_def->file);
+ }
+
+ const auto enum_type = GenPrefixedTypeName(
+ WrapInNameSpace(*(union_type.enum_def)), union_type.enum_def->file);
+ const auto &union_enum = *(union_type.enum_def);
+
+ const auto union_enum_loop = [&](const std::string &accessor_str) {
+ ret += " switch(" + enum_type + "[type]) {\n";
+ ret += " case 'NONE': return null; \n";
+
+ for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+ if (ev.IsZero()) { continue; }
+
+ ret += " case '" + ev.name + "': ";
+
+ if (IsString(ev.union_type)) {
+ ret += "return " + accessor_str + "'') as string;";
+ } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
+ const auto type = GenPrefixedTypeName(
+ WrapInNameSpace(*(ev.union_type.struct_def)),
+ ev.union_type.struct_def->file);
+ ret += "return " + accessor_str + "new " + type + "())! as " +
+ type + ";";
+ } else {
+ FLATBUFFERS_ASSERT(false);
+ }
+ ret += "\n";
+ }
+
+ ret += " default: return null;\n";
+ ret += " }\n";
+ };
+
+ union_enum_loop("accessor(");
+ ret += "}";
+
+ ret += "\n\nexport function " + GenUnionListConvFuncName(enum_def) +
+ "(\n type: " + enum_def.name +
+ ", \n accessor: (index: number, obj:" + valid_union_type +
+ ") => " + valid_union_type_with_null +
+ ", \n index: number\n): " + valid_union_type_with_null + " {\n";
+ union_enum_loop("accessor(index, ");
+ ret += "}";
+
+ return ret;
+ }
+ FLATBUFFERS_ASSERT(0);
+ return "";
+ }
+
+ // Used for generating a short function that returns the correct class
+ // based on union enum type. Assume the context is inside the non object api
+ // type
+ std::string GenUnionValTS(const std::string &field_name,
+ const Type &union_type,
+ const bool is_array = false) {
+ if (union_type.enum_def) {
+ const auto &enum_def = *union_type.enum_def;
+ const auto enum_type =
+ GenPrefixedTypeName(WrapInNameSpace(enum_def), enum_def.file);
+ const std::string union_accessor = "this." + field_name;
+
+ const auto union_has_string = UnionHasStringType(enum_def);
+ const auto field_binded_method = "this." + field_name + ".bind(this)";
+
+ std::string ret;
+
+ if (!is_array) {
+ const auto conversion_function =
+ GenPrefixedTypeName(WrapInNameSpace(enum_def.defined_namespace,
+ GenUnionConvFuncName(enum_def)),
+ enum_def.file);
+ const auto target_enum = "this." + field_name + "Type()";
+
+ ret = "(() => {\n";
+ ret += " let temp = " + conversion_function + "(" + target_enum +
+ ", " + field_binded_method + ");\n";
+ ret += " if(temp === null) { return null; }\n";
+ ret += union_has_string
+ ? " if(typeof temp === 'string') { return temp; }\n"
+ : "";
+ ret += " return temp.unpack()\n";
+ ret += " })()";
+ } else {
+ const auto conversion_function = GenPrefixedTypeName(
+ WrapInNameSpace(enum_def.defined_namespace,
+ GenUnionListConvFuncName(enum_def)),
+ enum_def.file);
+ const auto target_enum_accesor = "this." + field_name + "Type";
+ const auto target_enum_length = target_enum_accesor + "Length()";
+
+ ret = "(() => {\n";
+ ret += " let ret = [];\n";
+ ret += " for(let targetEnumIndex = 0; targetEnumIndex < " +
+ target_enum_length +
+ "; "
+ "++targetEnumIndex) {\n";
+ ret += " let targetEnum = " + target_enum_accesor +
+ "(targetEnumIndex);\n";
+ ret += " if(targetEnum === null || " + enum_type +
+ "[targetEnum!] === 'NONE') { "
+ "continue; }\n\n";
+ ret += " let temp = " + conversion_function + "(targetEnum, " +
+ field_binded_method + ", targetEnumIndex);\n";
+ ret += " if(temp === null) { continue; }\n";
+ ret += union_has_string ? " if(typeof temp === 'string') { "
+ "ret.push(temp); continue; }\n"
+ : "";
+ ret += " ret.push(temp.unpack());\n";
+ ret += " }\n";
+ ret += " return ret;\n";
+ ret += " })()";
+ }
+
+ return ret;
+ }
+
+ FLATBUFFERS_ASSERT(0);
+ return "";
+ }
+
+ static std::string GenNullCheckConditional(const std::string &nullCheckVar,
+ const std::string &trueVal,
+ const std::string &falseVal = "null") {
+ return "(" + nullCheckVar + " !== null ? " + trueVal + " : " + falseVal +
+ ")";
+ }
+
+ std::string GenStructMemberValueTS(const StructDef &struct_def,
+ const std::string &prefix,
+ const std::string &delimiter,
+ const bool nullCheck = true) {
+ std::string ret;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+
+ const auto curr_member_accessor =
+ prefix + "." + MakeCamel(field.name, false);
+ if (IsStruct(field.value.type)) {
+ ret += GenStructMemberValueTS(*field.value.type.struct_def,
+ curr_member_accessor, delimiter);
+ } else {
+ if (nullCheck) {
+ ret +=
+ "(" + prefix + " === null ? 0 : " + curr_member_accessor + "!)";
+ } else {
+ ret += curr_member_accessor;
+ }
+ }
+
+ if (std::next(it) != struct_def.fields.vec.end()) { ret += delimiter; }
+ }
+
+ return ret;
+ }
+
+ void GenObjApi(const Parser &parser, StructDef &struct_def,
+ std::string &obj_api_unpack_func, std::string &obj_api_class,
+ imported_fileset &imported_files) {
+ const auto class_name = GetObjApiClassName(struct_def, parser.opts);
+
+ std::string unpack_func =
+ "\n/**\n * " + GenTypeAnnotation(kReturns, class_name, "") +
+ " */\nunpack(): " + class_name + " {\n return new " + class_name +
+ "(" + (struct_def.fields.vec.empty() ? "" : "\n");
+ std::string unpack_to_func =
+ "/**\n * " + GenTypeAnnotation(kParam, class_name, "_o") +
+ " */\nunpackTo(_o: " + class_name + "): void {" +
+ +(struct_def.fields.vec.empty() ? "" : "\n");
+
+ std::string constructor_annotation = "/**\n * @constructor";
+ constructor_annotation += (struct_def.fields.vec.empty() ? "" : "\n");
+ std::string constructor_func = "constructor(";
+ constructor_func += (struct_def.fields.vec.empty() ? "" : "\n");
+
+ const auto has_create =
+ struct_def.fixed || CanCreateFactoryMethod(struct_def);
+
+ std::string pack_func_prototype =
+ "/**\n * " +
+ GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") + " * " +
+ GenTypeAnnotation(kReturns, "flatbuffers.Offset", "") +
+ " */\npack(builder:flatbuffers.Builder): flatbuffers.Offset {\n";
+
+ std::string pack_func_offset_decl;
+ std::string pack_func_create_call;
+
+ const auto struct_name =
+ GenPrefixedTypeName(WrapInNameSpace(struct_def), struct_def.file);
+
+ if (has_create) {
+ pack_func_create_call = " return " + struct_name + ".create" +
+ Verbose(struct_def) + "(builder" +
+ (struct_def.fields.vec.empty() ? "" : ",\n ");
+ } else {
+ pack_func_create_call = " " + struct_name + ".start(builder);\n";
+ }
+
+ if (struct_def.fixed) {
+ // when packing struct, nested struct's members instead of the struct's
+ // offset are used
+ pack_func_create_call +=
+ GenStructMemberValueTS(struct_def, "this", ",\n ", false) + "\n ";
+ }
+
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+
+ const auto field_name = MakeCamel(field.name, false);
+ const std::string field_binded_method =
+ "this." + field_name + ".bind(this)";
+
+ std::string field_val;
+ std::string field_type;
+ // a string that declares a variable containing the
+ // offset for things that can't be generated inline
+ // empty otw
+ std::string field_offset_decl;
+ // a string that contains values for things that can be created inline or
+ // the variable name from field_offset_decl
+ std::string field_offset_val;
+ const auto field_default_val =
+ GenDefaultValue(field, "flatbuffers");
+
+ // Emit a scalar field
+ const auto is_string = IsString(field.value.type);
+ if (IsScalar(field.value.type.base_type) || is_string) {
+ const auto has_null_default = is_string || HasNullDefault(field);
+
+ if (field.value.type.enum_def) {
+ if (!parser_.opts.generate_all) {
+ imported_files.insert(field.value.type.enum_def->file);
+ }
+
+ field_type +=
+ GenPrefixedTypeName(GenTypeName(field.value.type, false, has_null_default),
+ field.value.type.enum_def->file);
+ } else {
+ field_type += GenTypeName(field.value.type, false, has_null_default);
+ }
+ field_val = "this." + field_name + "()";
+
+ if (field.value.type.base_type != BASE_TYPE_STRING) {
+ field_offset_val = "this." + field_name;
+ } else {
+ field_offset_decl = GenNullCheckConditional(
+ "this." + field_name,
+ "builder.createString(this." + field_name + "!)", "0");
+ }
+ }
+
+ // Emit an object field
+ else {
+ auto is_vector = false;
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ const auto &sd = *field.value.type.struct_def;
+ field_type += GenPrefixedTypeName(
+ WrapInNameSpace(sd.defined_namespace,
+ GetObjApiClassName(sd, parser.opts)),
+ field.value.type.struct_def->file);
+
+ const std::string field_accessor = "this." + field_name + "()";
+ field_val = GenNullCheckConditional(field_accessor,
+ field_accessor + "!.unpack()");
+ field_offset_val = GenNullCheckConditional(
+ "this." + field_name, "this." + field_name + "!.pack(builder)",
+ "0");
+
+ break;
+ }
+
+ case BASE_TYPE_VECTOR: {
+ auto vectortype = field.value.type.VectorType();
+ auto vectortypename = GenTypeName(vectortype, false);
+ is_vector = true;
+
+ field_type = "(";
+
+ switch (vectortype.base_type) {
+ case BASE_TYPE_STRUCT: {
+ const auto &sd = *field.value.type.struct_def;
+ field_type += GenPrefixedTypeName(
+ WrapInNameSpace(sd.defined_namespace,
+ GetObjApiClassName(sd, parser.opts)),
+ field.value.type.struct_def->file);
+ field_type += ")[]";
+
+ field_val = GenBBAccess() + ".createObjList(" +
+ field_binded_method + ", this." + field_name +
+ "Length())";
+
+ if (sd.fixed) {
+ field_offset_decl =
+ "builder.createStructOffsetList(this." + field_name +
+ ", " +
+ GenPrefixedTypeName(WrapInNameSpace(struct_def),
+ struct_def.file) +
+ ".start" + MakeCamel(field_name) + "Vector)";
+ } else {
+ field_offset_decl =
+ GenPrefixedTypeName(WrapInNameSpace(struct_def),
+ struct_def.file) +
+ ".create" + MakeCamel(field_name) +
+ "Vector(builder, builder.createObjectOffsetList(" +
+ "this." + field_name + "))";
+ }
+
+ break;
+ }
+
+ case BASE_TYPE_STRING: {
+ field_type += "string)[]";
+ field_val = GenBBAccess() + ".createStringList(" +
+ field_binded_method + ", this." + field_name +
+ "Length())";
+ field_offset_decl =
+ GenPrefixedTypeName(WrapInNameSpace(struct_def),
+ struct_def.file) +
+ ".create" + MakeCamel(field_name) +
+ "Vector(builder, builder.createObjectOffsetList(" +
+ "this." + field_name + "))";
+ break;
+ }
+
+ case BASE_TYPE_UNION: {
+ field_type +=
+ GenObjApiUnionTypeTS(parser.opts, *(vectortype.enum_def));
+ field_type += ")[]";
+ field_val = GenUnionValTS(field_name, vectortype, true);
+
+ field_offset_decl =
+ GenPrefixedTypeName(WrapInNameSpace(struct_def),
+ struct_def.file) +
+ ".create" + MakeCamel(field_name) +
+ "Vector(builder, builder.createObjectOffsetList(" +
+ "this." + field_name + "))";
+
+ break;
+ }
+ default: {
+ if (vectortype.enum_def) {
+ if (!parser_.opts.generate_all) {
+ imported_files.insert(vectortype.enum_def->file);
+ }
+
+ field_type +=
+ GenPrefixedTypeName(GenTypeName(vectortype, false, HasNullDefault(field)),
+ vectortype.enum_def->file);
+ } else {
+ field_type += vectortypename;
+ }
+ field_type += ")[]";
+ field_val = GenBBAccess() + ".createScalarList(" +
+ field_binded_method + ", this." + field_name +
+ "Length())";
+
+ field_offset_decl =
+ GenPrefixedTypeName(WrapInNameSpace(struct_def),
+ struct_def.file) +
+ ".create" + MakeCamel(field_name) +
+ "Vector(builder, this." + field_name + ")";
+
+ break;
+ }
+ }
+
+ break;
+ }
+
+ case BASE_TYPE_UNION: {
+ if (!parser_.opts.generate_all) {
+ imported_files.insert(field.value.type.enum_def->file);
+ }
+
+ field_type +=
+ GenObjApiUnionTypeTS(parser.opts, *(field.value.type.enum_def));
+
+ field_val = GenUnionValTS(field_name, field.value.type);
+ field_offset_decl =
+ "builder.createObjectOffset(this." + field_name + ")";
+ break;
+ }
+
+ default: FLATBUFFERS_ASSERT(0); break;
+ }
+
+ // length 0 vector is simply empty instead of null
+ field_type += is_vector ? "" : "|null";
+ }
+
+ if (!field_offset_decl.empty()) {
+ field_offset_decl =
+ " const " + field_name + " = " + field_offset_decl + ";";
+ }
+ if (field_offset_val.empty()) { field_offset_val = field_name; }
+
+ unpack_func += " " + field_val;
+ unpack_to_func += " _o." + field_name + " = " + field_val + ";";
+
+ constructor_annotation +=
+ " * " + GenTypeAnnotation(kParam, field_type, field_name, false);
+ constructor_func += " public " + field_name + ": " + field_type + " = " +
+ field_default_val;
+
+ if (!struct_def.fixed) {
+ if (!field_offset_decl.empty()) {
+ pack_func_offset_decl += field_offset_decl + "\n";
+ }
+
+ if (has_create) {
+ pack_func_create_call += field_offset_val;
+ } else {
+ pack_func_create_call += " " + struct_name + ".add" +
+ MakeCamel(field.name) + "(builder, " +
+ field_offset_val + ");\n";
+ }
+ }
+
+ if (std::next(it) != struct_def.fields.vec.end()) {
+ constructor_annotation += "\n";
+ constructor_func += ",\n";
+
+ if (!struct_def.fixed && has_create) {
+ pack_func_create_call += ",\n ";
+ }
+
+ unpack_func += ",\n";
+ unpack_to_func += "\n";
+ } else {
+ constructor_func += "\n";
+ if (!struct_def.fixed) {
+ pack_func_offset_decl += (pack_func_offset_decl.empty() ? "" : "\n");
+ pack_func_create_call += "\n ";
+ }
+
+ unpack_func += "\n ";
+ unpack_to_func += "\n";
+ }
+ }
+
+ constructor_annotation += "\n */\n";
+ constructor_func += "){};\n\n";
+
+ if (has_create) {
+ pack_func_create_call += ");";
+ } else {
+ pack_func_create_call += "return " + struct_name + ".end(builder);";
+ }
+
+ obj_api_class = "\nexport class " +
+ GetObjApiClassName(struct_def, parser.opts) + " {\n";
+
+ obj_api_class += constructor_annotation + constructor_func;
+
+ obj_api_class += pack_func_prototype + pack_func_offset_decl +
+ pack_func_create_call + "\n};";
+
+ obj_api_class += "\n}\n";
+
+ unpack_func += ");\n};";
+ unpack_to_func += "};\n";
+
+ obj_api_unpack_func = unpack_func + "\n\n" + unpack_to_func;
+ }
+
+ static bool CanCreateFactoryMethod(const StructDef &struct_def) {
+ // to preserve backwards compatibility, we allow the first field to be a
+ // struct
+ return struct_def.fields.vec.size() < 2 ||
+ std::all_of(std::begin(struct_def.fields.vec) + 1,
+ std::end(struct_def.fields.vec),
+ [](const FieldDef *f) -> bool {
+ FLATBUFFERS_ASSERT(f != nullptr);
+ return f->value.type.base_type != BASE_TYPE_STRUCT;
+ });
+ }
+
// Generate an accessor struct with constructor for a flatbuffers struct.
void GenStruct(const Parser &parser, StructDef &struct_def,
std::string *code_ptr, std::string *exports_ptr,
@@ -682,7 +1322,8 @@
code += " {\n";
if (lang_.language != IDLOptions::kTs) {
code += " /**\n";
- code += " * " + GenTypeAnnotation(kType, "flatbuffers.ByteBuffer", "");
+ code +=
+ " * " + GenTypeAnnotation(kType, "flatbuffers.ByteBuffer", "");
code += " */\n";
}
code += " bb: flatbuffers.ByteBuffer|null = null;\n";
@@ -752,10 +1393,9 @@
// Generate the identifier check method
if (!struct_def.fixed && parser_.root_struct_def_ == &struct_def &&
!parser_.file_identifier_.empty()) {
- GenDocComment(
- code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") +
- GenTypeAnnotation(kReturns, "boolean", "", false));
+ GenDocComment(code_ptr,
+ GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") +
+ GenTypeAnnotation(kReturns, "boolean", "", false));
if (lang_.language == IDLOptions::kTs) {
code +=
"static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean "
@@ -778,20 +1418,22 @@
NumToString(field.value.offset) + ");\n return offset ? ";
// Emit a scalar field
- if (IsScalar(field.value.type.base_type) ||
- field.value.type.base_type == BASE_TYPE_STRING) {
+ const auto is_string = IsString(field.value.type);
+ if (IsScalar(field.value.type.base_type) || is_string) {
+ const auto has_null_default = is_string || HasNullDefault(field);
+
GenDocComment(
field.doc_comment, code_ptr,
- std::string(field.value.type.base_type == BASE_TYPE_STRING
+ std::string(is_string
? GenTypeAnnotation(kParam, "flatbuffers.Encoding=",
"optionalEncoding")
: "") +
GenTypeAnnotation(kReturns,
- GenTypeName(field.value.type, false, true),
+ GenTypeName(field.value.type, false, has_null_default),
"", false));
if (lang_.language == IDLOptions::kTs) {
std::string prefix = MakeCamel(field.name, false) + "(";
- if (field.value.type.base_type == BASE_TYPE_STRING) {
+ if (is_string) {
code += prefix + "):string|null\n";
code += prefix + "optionalEncoding:flatbuffers.Encoding" +
"):" + GenTypeName(field.value.type, false, true) + "\n";
@@ -802,7 +1444,7 @@
if (field.value.type.enum_def) {
code +=
"):" +
- GenPrefixedTypeName(GenTypeName(field.value.type, false, true),
+ GenPrefixedTypeName(GenTypeName(field.value.type, false, field.optional),
field.value.type.enum_def->file) +
" {\n";
@@ -810,12 +1452,12 @@
imported_files.insert(field.value.type.enum_def->file);
}
} else {
- code += "):" + GenTypeName(field.value.type, false, true) + " {\n";
+ code += "):" + GenTypeName(field.value.type, false, has_null_default) + " {\n";
}
} else {
code += object_name + ".prototype." + MakeCamel(field.name, false);
code += " = function(";
- if (field.value.type.base_type == BASE_TYPE_STRING) {
+ if (is_string) {
code += "optionalEncoding";
}
code += ") {\n";
@@ -829,12 +1471,12 @@
";\n";
} else {
std::string index = "this.bb_pos + offset";
- if (field.value.type.base_type == BASE_TYPE_STRING) {
+ if (is_string) {
index += ", optionalEncoding";
}
code += offset_prefix +
GenGetter(field.value.type, "(" + index + ")") + " : " +
- GenDefaultValue(field.value, GenBBAccess());
+ GenDefaultValue(field, GenBBAccess());
code += ";\n";
}
}
@@ -860,19 +1502,21 @@
}
if (struct_def.fixed) {
- code += " return (obj || new " + type;
+ code += " return (obj || " + GenerateNewExpression(type);
code += ").__init(this.bb_pos";
code +=
MaybeAdd(field.value.offset) + ", " + GenBBAccess() + ");\n";
} else {
- code += offset_prefix + "(obj || new " + type + ").__init(";
+ code += offset_prefix + "(obj || " + GenerateNewExpression(type) +
+ ").__init(";
code += field.value.type.struct_def->fixed
? "this.bb_pos + offset"
: GenBBAccess() + ".__indirect(this.bb_pos + offset)";
code += ", " + GenBBAccess() + ") : null;\n";
}
- if (lang_.language == IDLOptions::kTs && !parser_.opts.generate_all) {
+ if (lang_.language == IDLOptions::kTs &&
+ !parser_.opts.generate_all) {
imported_files.insert(field.value.type.struct_def->file);
}
@@ -882,6 +1526,12 @@
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
auto vectortypename = GenTypeName(vectortype, false);
+
+ if (vectortype.enum_def) {
+ vectortypename = GenPrefixedTypeName(vectortypename,
+ vectortype.enum_def->file);
+ }
+
auto inline_size = InlineSize(vectortype);
auto index = GenBBAccess() +
".__vector(this.bb_pos + offset) + index" +
@@ -914,8 +1564,11 @@
if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
prefix += "(index: number";
if (is_union) {
- vectortypename = "T";
- code += prefix + ", obj:T";
+ const auto union_type =
+ GenUnionGenericTypeTS(*(field.value.type.enum_def));
+
+ vectortypename = union_type;
+ code += prefix + ", obj:" + union_type;
} else if (vectortype.base_type == BASE_TYPE_STRUCT) {
vectortypename = GenPrefixedTypeName(
vectortypename, vectortype.struct_def->file);
@@ -924,13 +1577,17 @@
if (!parser_.opts.generate_all) {
imported_files.insert(vectortype.struct_def->file);
}
- } else if (vectortype.base_type == BASE_TYPE_STRING) {
+ } else if (IsString(vectortype)) {
code += prefix + "):string\n";
code += prefix + ",optionalEncoding:flatbuffers.Encoding" +
"):" + vectortypename + "\n";
code += prefix + ",optionalEncoding?:any";
} else {
code += prefix;
+
+ if (vectortype.enum_def && !parser_.opts.generate_all) {
+ imported_files.insert(vectortype.enum_def->file);
+ }
}
code += "):" + vectortypename + "|null {\n";
} else {
@@ -939,14 +1596,15 @@
code += " = function(index";
if (vectortype.base_type == BASE_TYPE_STRUCT || is_union) {
code += ", obj";
- } else if (vectortype.base_type == BASE_TYPE_STRING) {
+ } else if (IsString(vectortype)) {
code += ", optionalEncoding";
}
code += ") {\n";
}
if (vectortype.base_type == BASE_TYPE_STRUCT) {
- code += offset_prefix + "(obj || new " + vectortypename;
+ code += offset_prefix + "(obj || " +
+ GenerateNewExpression(vectortypename);
code += ").__init(";
code += vectortype.struct_def->fixed
? index
@@ -955,7 +1613,7 @@
} else {
if (is_union) {
index = "obj, " + index;
- } else if (vectortype.base_type == BASE_TYPE_STRING) {
+ } else if (IsString(vectortype)) {
index += ", optionalEncoding";
}
code += offset_prefix + GenGetter(vectortype, "(" + index + ")");
@@ -991,7 +1649,13 @@
false));
if (lang_.language == IDLOptions::kTs) {
code += MakeCamel(field.name, false);
- code += "<T extends flatbuffers.Table>(obj:T):T|null {\n";
+
+ const auto &union_enum = *(field.value.type.enum_def);
+ const auto union_type = GenUnionGenericTypeTS(union_enum);
+ code += "<T extends flatbuffers.Table>(obj:" + union_type +
+ "):" + union_type +
+ "|null "
+ "{\n";
} else {
code +=
object_name + ".prototype." + MakeCamel(field.name, false);
@@ -1015,7 +1679,8 @@
}
// Adds the mutable scalar value to the output
- if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer) {
+ if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer &&
+ !IsUnion(field.value.type)) {
std::string annotations = GenTypeAnnotation(
kParam, GenTypeName(field.value.type, true), "value");
GenDocComment(
@@ -1025,6 +1690,10 @@
if (lang_.language == IDLOptions::kTs) {
std::string type;
if (field.value.type.enum_def) {
+ if (!parser_.opts.generate_all) {
+ imported_files.insert(field.value.type.enum_def->file);
+ }
+
type = GenPrefixedTypeName(GenTypeName(field.value.type, true),
field.value.type.enum_def->file);
} else {
@@ -1037,19 +1706,26 @@
" = function(value) {\n";
}
- code += " var offset = " + GenBBAccess() + ".__offset(this.bb_pos, " +
- NumToString(field.value.offset) + ");\n\n";
- code += " if (offset === 0) {\n";
- code += " return false;\n";
- code += " }\n\n";
+ if (struct_def.fixed) {
+ code += " " + GenBBAccess() + ".write" +
+ MakeCamel(GenType(field.value.type)) + "(this.bb_pos + " +
+ NumToString(field.value.offset) + ", ";
+ } else {
+ code += " var offset = " + GenBBAccess() +
+ ".__offset(this.bb_pos, " + NumToString(field.value.offset) +
+ ");\n\n";
+ code += " if (offset === 0) {\n";
+ code += " return false;\n";
+ code += " }\n\n";
- // special case for bools, which are treated as uint8
- code += " " + GenBBAccess() + ".write" +
- MakeCamel(GenType(field.value.type)) +
- "(this.bb_pos + offset, ";
- if (field.value.type.base_type == BASE_TYPE_BOOL &&
- lang_.language == IDLOptions::kTs) {
- code += "+";
+ // special case for bools, which are treated as uint8
+ code += " " + GenBBAccess() + ".write" +
+ MakeCamel(GenType(field.value.type)) +
+ "(this.bb_pos + offset, ";
+ if (field.value.type.base_type == BASE_TYPE_BOOL &&
+ lang_.language == IDLOptions::kTs) {
+ code += "+";
+ }
}
code += "value);\n";
@@ -1064,7 +1740,7 @@
}
// Emit vector helpers
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ if (IsVector(field.value.type)) {
// Emit a length helper
GenDocComment(code_ptr,
GenTypeAnnotation(kReturns, "number", "", false));
@@ -1118,6 +1794,30 @@
}
}
+ // Emit the fully qualified name
+ if (parser_.opts.generate_name_strings) {
+ GenDocComment(code_ptr, GenTypeAnnotation(kReturns, "string", "", false));
+ if (lang_.language == IDLOptions::kTs) {
+ code += "static getFullyQualifiedName():string {\n";
+ } else {
+ code += object_name + ".getFullyQualifiedName = function() {\n";
+ }
+ code += " return '" + WrapInNameSpace(struct_def) + "';\n";
+ code += "}\n\n";
+ }
+
+ // Emit the size of the struct.
+ if (struct_def.fixed) {
+ GenDocComment(code_ptr, GenTypeAnnotation(kReturns, "number", "", false));
+ if (lang_.language == IDLOptions::kTs) {
+ code += "static sizeOf():number {\n";
+ } else {
+ code += object_name + ".sizeOf = function() {\n";
+ }
+ code += " return " + NumToString(struct_def.bytesize) + ";\n";
+ code += "}\n\n";
+ }
+
// Emit a factory constructor
if (struct_def.fixed) {
std::string annotations =
@@ -1174,7 +1874,7 @@
if (lang_.language == IDLOptions::kTs) {
code += "static add" + MakeCamel(field.name);
code += "(builder:flatbuffers.Builder, " + argname + ":" +
- GetArgType(field) + ") {\n";
+ GetArgType(field, false) + ") {\n";
} else {
code += object_name + ".add" + MakeCamel(field.name);
code += " = function(builder, " + argname + ") {\n";
@@ -1186,13 +1886,19 @@
code += argname + ", ";
if (!IsScalar(field.value.type.base_type)) {
code += "0";
+ } else if (HasNullDefault(field)) {
+ if (IsLong(field.value.type.base_type)) {
+ code += "builder.createLong(0, 0)";
+ } else {
+ code += "0";
+ }
} else {
if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
- code += GenDefaultValue(field.value, "builder");
+ code += GenDefaultValue(field, "builder");
}
code += ");\n};\n\n";
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ if (IsVector(field.value.type)) {
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
auto elem_size = InlineSize(vector_type);
@@ -1210,11 +1916,37 @@
false));
if (lang_.language == IDLOptions::kTs) {
- code += "static create" + MakeCamel(field.name);
+ const std::string sig_begin =
+ "static create" + MakeCamel(field.name) +
+ "Vector(builder:flatbuffers.Builder, data:";
+ const std::string sig_end = "):flatbuffers.Offset";
std::string type = GenTypeName(vector_type, true) + "[]";
- if (type == "number[]") { type += " | Uint8Array"; }
- code += "Vector(builder:flatbuffers.Builder, data:" + type +
- "):flatbuffers.Offset {\n";
+ if (type == "number[]") {
+ const auto &array_type = GenType(vector_type);
+ // the old type should be deprecated in the future
+ std::string type_old = "number[]|Uint8Array";
+ std::string type_new = "number[]|" + array_type + "Array";
+ if (type_old == type_new) {
+ type = type_new;
+ } else {
+ // add function overloads
+ code += sig_begin + type_new + sig_end + ";\n";
+ code +=
+ "/**\n * @deprecated This Uint8Array overload will "
+ "be removed in the future.\n */\n";
+ code += sig_begin + type_old + sig_end + ";\n";
+ type = type_new + "|Uint8Array";
+ }
+ } else {
+ if (vector_type.enum_def) {
+ if (!parser_.opts.generate_all) {
+ imported_files.insert(vector_type.enum_def->file);
+ }
+
+ type = GenPrefixedTypeName(type, vector_type.enum_def->file);
+ }
+ }
+ code += sig_begin + type + sig_end + " {\n";
} else {
code += object_name + ".create" + MakeCamel(field.name);
code += "Vector = function(builder, data) {\n";
@@ -1284,85 +2016,120 @@
GenerateFinisher(struct_def, code_ptr, code, object_name, true);
// Generate a convenient CreateX function
- if (lang_.language == IDLOptions::kJs) {
- std::string paramDoc =
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder");
+ if (CanCreateFactoryMethod(struct_def)) {
+ if (lang_.language == IDLOptions::kJs) {
+ std::string paramDoc =
+ GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder");
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ if (field.deprecated) continue;
+ paramDoc +=
+ GenTypeAnnotation(kParam, GetArgType(field, true), GetArgName(field));
+ }
+ paramDoc +=
+ GenTypeAnnotation(kReturns, "flatbuffers.Offset", "", false);
+
+ GenDocComment(code_ptr, paramDoc);
+ }
+
+ if (lang_.language == IDLOptions::kTs) {
+ code += "static create" + Verbose(struct_def);
+ code += "(builder:flatbuffers.Builder";
+ } else {
+ code += object_name + ".create" + Verbose(struct_def);
+ code += " = function(builder";
+ }
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (field.deprecated)
- continue;
- paramDoc +=
- GenTypeAnnotation(kParam, GetArgType(field), GetArgName(field));
+ if (field.deprecated) continue;
+
+ if (lang_.language == IDLOptions::kTs) {
+ code += ", " + GetArgName(field) + ":" + GetArgType(field, true);
+ } else {
+ code += ", " + GetArgName(field);
+ }
}
- paramDoc +=
- GenTypeAnnotation(kReturns, "flatbuffers.Offset", "", false);
-
- GenDocComment(code_ptr, paramDoc);
- }
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static create" + Verbose(struct_def);
- code += "(builder:flatbuffers.Builder";
- } else {
- code += object_name + ".create" + Verbose(struct_def);
- code += " = function(builder";
- }
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated)
- continue;
if (lang_.language == IDLOptions::kTs) {
- code += ", " + GetArgName(field) + ":" + GetArgType(field);
+ code += "):flatbuffers.Offset {\n";
+ code += " " + struct_def.name + ".start" + Verbose(struct_def) +
+ "(builder);\n";
} else {
- code += ", " + GetArgName(field);
+ code += ") {\n";
+ code += " " + object_name + ".start" + Verbose(struct_def) +
+ "(builder);\n";
}
- }
- if (lang_.language == IDLOptions::kTs) {
- code += "):flatbuffers.Offset {\n";
- code += " " + struct_def.name + ".start" + Verbose(struct_def) +
+ std::string methodPrefix =
+ lang_.language == IDLOptions::kTs ? struct_def.name : object_name;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ if (field.deprecated) continue;
+
+ const auto arg_name = GetArgName(field);
+
+ if (field.IsScalarOptional()) {
+ code += " if (" + arg_name + " !== null)\n ";
+ }
+
+ code += " " + methodPrefix + ".add" + MakeCamel(field.name) + "(";
+ code += "builder, " + arg_name + ");\n";
+ }
+
+ code += " return " + methodPrefix + ".end" + Verbose(struct_def) +
"(builder);\n";
- } else {
- code += ") {\n";
- code += " " + object_name + ".start" + Verbose(struct_def) +
- "(builder);\n";
+ code += "}\n";
+ if (lang_.language == IDLOptions::kJs) code += "\n";
}
+ }
- std::string methodPrefix =
- lang_.language == IDLOptions::kTs ? struct_def.name : object_name;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated)
- continue;
-
- code += " " + methodPrefix + ".add" + MakeCamel(field.name) + "(";
- code += "builder, " + GetArgName(field) + ");\n";
- }
-
- code += " return " + methodPrefix + ".end" + Verbose(struct_def) +
- "(builder);\n";
+ if (!struct_def.fixed && parser_.services_.vec.size() != 0 &&
+ lang_.language == IDLOptions::kTs) {
+ auto name = Verbose(struct_def, "");
+ code += "\n";
+ code += "serialize():Uint8Array {\n";
+ code += " return this.bb!.bytes();\n";
code += "}\n";
- if (lang_.language == IDLOptions::kJs)
- code += "\n";
+
+ code += "\n";
+ code += "static deserialize(buffer: Uint8Array):"+ name +" {\n";
+ code += " return " + name + ".getRootAs" + name +
+ "(new flatbuffers.ByteBuffer(buffer))\n";
+ code += "}\n";
}
if (lang_.language == IDLOptions::kTs) {
- if (!object_namespace.empty()) {
+ if (parser_.opts.generate_object_based_api) {
+ std::string obj_api_class;
+ std::string obj_api_unpack_func;
+ GenObjApi(parser_, struct_def, obj_api_unpack_func, obj_api_class,
+ imported_files);
+
+ code += obj_api_unpack_func + "}\n" + obj_api_class;
+ } else {
code += "}\n";
}
- code += "}\n";
+ if (!object_namespace.empty()) { code += "}\n"; }
}
}
+
+ static bool HasNullDefault(const FieldDef &field) {
+ return field.optional && field.value.constant == "null";
+ }
- std::string GetArgType(const FieldDef &field) {
- if (field.value.type.enum_def)
- return GenPrefixedTypeName(GenTypeName(field.value.type, true),
- field.value.type.enum_def->file);
- return GenTypeName(field.value.type, true);
+ std::string GetArgType(const FieldDef &field, bool allowNull) {
+ auto type_name = GenTypeName(field.value.type, true, allowNull && field.optional);
+
+ if (field.value.type.enum_def) {
+ if (IsScalar(field.value.type.base_type)) {
+ return GenPrefixedTypeName(type_name, field.value.type.enum_def->file);
+ }
+ }
+
+ return type_name;
}
static std::string GetArgName(const FieldDef &field) {
@@ -1372,12 +2139,10 @@
return argname;
}
- std::string Verbose(const StructDef &struct_def,
- const char* prefix = "")
- {
+ std::string Verbose(const StructDef &struct_def, const char *prefix = "") {
return parser_.opts.js_ts_short_names ? "" : prefix + struct_def.name;
}
-};
+}; // namespace jsts
} // namespace jsts
bool GenerateJSTS(const Parser &parser, const std::string &path,
@@ -1389,11 +2154,12 @@
std::string JSTSMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
FLATBUFFERS_ASSERT(parser.opts.lang <= IDLOptions::kMAX);
- const auto &lang = GetJsLangParams(parser.opts.lang);
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
- std::string make_rule = GeneratedFileName(path, filebase, lang) + ": ";
+ jsts::JsTsGenerator 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) {