Squashed 'third_party/flatbuffers/' changes from 338393f85..e5f331db9
e5f331db9 [TS] Add single-file ts codegen & bazel rule for typescript (#7161)
2f84c6038 Apply Namer to Go code gen (#7150)
d64839651 [Lobster] file_identifier support
777e78d8d [Lobster] support unsigned integer reads
4016c549d Apply Namer to Python code gen (#7146)
40827b21b Fix missing 'break' (#7151)
65a10b6e3 Implement a config based name manager and use it in Rust codegen (#7144)
8db2fef3f [TS] Escape keywords in typescript object names (#7137)
9ed132304 Fix 64-bit numeric enum values in typescript (#7135)
1a4c40566 updated npm to 2.0.6
318594e4b prevent name clash (#7133)
3d903302c [Rust] Add length checks to arrays and vectors. (#7130)
c9571d989 Replaced ToDasherCase with ConvertCase (#7131)
3694b830a Use ConvertCase instead of Make{Upper,Lower,Snake} implementations (#7127)
0471fa807 remove stall reference to version
914344ea9 some minor help edits
b40266c56 Use target_compile_features to target C++11 (#7122)
8a9303d46 update proto tests with alaised enum (#7121)
30c4bf47f Trigger fuzzing CI only on relevant changes (#7120)
46ce45601 remove auto generate code from cmakelists (#7119)
433312c55 add the missing checkNullConditionnal code in the "GenObjApi" function when the field is scalar optional (#7114)
9c52ec374 Add deps attribute to flatbuffer_cc_library (#7107)
70e2f49bf fixed string-json -> strict-json typo
5ac0367ed [TS] Fix generation of reserved words in object api (#7106) (#7115)
5d101afb5 Fix minor typo in WhitePaper.md (#7108)
06f4af11b Go optional scalars (#7104)
57e338f81 explicitly use windows-2019 to unblock ci (#7105)
615616cb5 Change Rust generated file defaults (#7101)
3413c3300 Fixed FlexBuffers verifier fuzzer timing out
69f5660a4 Fixed Parser not checking size of union types vector
d5add9fca Fixed FlexBuffers ToString unquoted non-ident keys
15df50eb7 Remove @ExperimentalUnsignedTypes annotation from kotlin code generator. (#7092)
a94132a45 Swift FlatBufferBuilder.sizedByteArray to ByteBuffer.toArray() (#7093)
48befb6be [TS] Refactor away circular ref (#7099)
b30069133 Add reflection support for python (#7026)
faadbc10e Add CreateVector overload to accept array like (#7095)
ed6ae8d32 explicitly defined std::allocator (#7094)
e910bddbc [JS] Add ".js" suffix to all import statements to generate a browser compatible mjs version. (#7086)
c85fb690f Add Parsing Completed function for Rust (#7084)
c1daa6ba0 rust: Bump thiserror version and remove git dependency (#7080)
4c71c7b02 replace framework include of flatbuffers (#7079)
f5664d33f fix go_test implement error (#7012)
39c8a19ce fixed comparator for native_inline (#7076)
826193ff6 skip generating reflection.fbs in generate_scripts (#7077)
fd0d1ed92 update C++ generator to emit scoped enums in vector of unions (#7075)
424988f30 replaced removed xml tag
b2550dbaa removed BSD-3-Clause license and Zlib licenses (#7073)
a2b238960 Fixed default value of bool in struct for Swift (#7072)
619b78437 one last dart omit local (#7070)
68a766154 more omit type annotations for dart local variables (#7069)
7dac9961f omit type annotations for dart local variables (#7067)
c65c389c6 add xmlns to .Net (#7066)
6446dcf3d Updates swift gen licence for grpc code (#7063)
e090d8da1 Fixed long cast to int in flexbufferbuilder.java (#7059)
bc901436d clang format on codebase (#7058)
240be9b5a attempt to remove appveyor (#7056)
bc366a7f9 Provide a short help text and default in error case (#6992)
14b19d446 Use FindPython3 (#7055)
9e6f17b94 remove BIICODE
c3801ad37 Update readme.md
4f3b24db0 Fixes a bug where bools arent being nil when marked optional (#7051)
1d294a31b Implement Serialize on generated rust types (#7022)
dd8fccfb1 Cmake 3.16 de-facto minimum version (#7049)
7089c9ecd Convert flatbuffers_version_string to inline function (#7046)
43203984f [C++] Support C++ object copies and moves (#5988)
5993338ee [ts] Builder incorrectly serializing empty strings (#7047)
19920db39 Include a SizePrefixed..HasIdentifier for c++. (#6871)
dbbaeac85 Use `${PYTHON_EXECUTABLE}` instead of `py` in cmake (#7042)
028f0fde6 'flattest': Add --test_path option (#7041)
87343631b Added support for clang-cl on windows (CMake) (#7038)
1fbfaf5c5 Fix/cmake build grpc (#7028)
4421375bb Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare (#7023)
162ad7a37 Fix comment with line orders - Rust should be last. (#7037)
a0a6c3f8c Use actions/checkout@v2, which fixes security vulnerability. (#7036)
a2d38fbb9 Add --warnings-as-errors to flatc compiler. (#7034)
9ef1524d3 Emit include for bfbs-gen-embed (#7031)
0c9de0352 Upgraded GRPC version to 1.42.0 (#7033)
a783bc926 chore: dart 2.0.5 release changes (#6983)
aff818ceb rust: Allow for usage in no_std environment (#6989)
d7b75417f Make flatbuffer builder deterministic (#6993)
a42e89897 Added verifier alignment checking to table fields (#7018)
96cc2f3ee BuildFlatBuffers.cmake: fix arguments not passed properly to flatc (#7013)
3250a1f8d Add initial C# vector of unions support to the documentation. (#6880)
ace4a37f2 [TS/JS] BigInt implementation (#6998)
f28c2b293 Avoid implicit conversion from float to double. (#7003)
96f3cf690 Rearrange #include directives to pass to compilation with a particular DSP toolchain (#7000)
b3edfdbfb Reverting grpc generated file suffix (#6995)
b8aaccee8 Disable parsing of nested_flatbuffers as bytes by default
2dc8ae774 Enable OSS-Fuzz on CI
5b0d49112 Updated FlexBuffers fuzzer
d8b7041d7 Added alignment checking to FlexBuffers verifier
5a0c3366c FlexBuffers verifier additionally checks for nesting
f8148b8da Made FlexBuffers reuse tracker track types
a22b1b626 Prevent shadow with _{{FIELD_NAME}} (#6991)
4264daadd FlexBuffers fuzzer fixes
3cbc120a0 Refractor Flatc Options (#6987)
8dcd2682c [CMake] Add option for disable universal on OSX (#6990)
b78002ff3 Validate C# json/object-api options (#6985)
c555ee8fa Add .NET test to github workflows (#6982)
b92bb0584 [CMake]: Fix version in pkgconfig file (#6986)
956d11569 re-enabled FlexBuffer JSON in fuzzer
e367ca32a Verifier for FlexBuffers (#6977)
705f27f6e [CMake]: Fix python command for mingw environment (#6984)
5fc87f4c4 Enable --gen-onefile in Python (#6953)
11749095a Make idl_parser deterministic (#6976)
d0cede9c9 Bumping to Version 2.0.5 (#6967)
fcc2bee0b Fix typo in variable name (#6973)
e08da4dea remove Appveyor's Vs2010 and 13 builds (#6969)
18538c401 [TS] Fix reserved words as arguments (#6955) (#6956)
e57f4ab2d Update stale bot version and provide away to exempt issues with the not-stale label (#6968)
deed68db5 missing generated files (#6966)
061d61f3f Lua Generator using IR. (#6940)
cffe0c454 FixedTypedVector: add const to ElementType() and size() (#6965)
fadd40e40 Have grpc include file with correct filename-suffix given to flatc (#6954)
e47dc0e46 Removed test/generate_code.{sh|bat} (#6873)
5c5475479 switched to windows-lastest, removed deadcode (#6948)
4f7f6dc30 Restore FlatBufferBuilder::kFileIdentifierLength. (#6960)
0fadaf391 Enable verifier on nested_flatbuffers
4d0e9a870 Turn off nested FlatBuffers/FlexBuffers for the fuzzer
c05f6783a invalid conditional running genrate_code.py (#6952)
a14f4052c rust: remove needless borrow (#6922)
9e4ca857b Vector Downward GetSize optimization (#6925)
a2b99084b Fix flexbuffers clang-analyzer warning (#6947)
85b4effac test: fix undefined order of functio parameters. (#6946)
790f41154 [cmake] Fix getting version info from tags during the build (#6936)
e89de4411 clang-all (#6941)
256ab3798 WIP: Dart release 2.0 (#6927)
a59288a01 Add benchmarks to Linux CI (#6928)
587bbd49a [C++] Fix compile failure on Object API union construction for struct member (#6923)
a9c341545 Fix integer overflow warnings
8aa18b629 fixed cmp0048 error (#6932)
d727579b6 fuzzers: fix typo in file path (#6931)
97a30171c Added Raw C++ benchmarks (#6924)
0989fc5e5 Added Google benchmarks (and gtests) (#6920)
927175ea2 [Java] lookup by byteArray is giving back wrong entry (#6915)
6748c373b Removal of support for FLATBUFFERS_CPP98_STL (#6918)
3fab0c6ee move [[ ]] to calling sites (#6914)
6c8c29155 [C++] Split flatbuffers.h into separate files (#6868)
fd4ff23da Keep methods with struct name and switch them to default (#6879)
f8b69e330 [Python] Verify EnumDef is not generated in GenUnionCreator (#6903)
c0394bb09 Support `--conform` for vector of unions (#6883)
8433eb108 Typo fixes in comments of flatbuffers.h and flexbuffers.h (#6901)
f2f9380c8 [Java] Prevent generation of enum names when underlying type is long (#6781) (#6895)
e672dabfe [C++] Fix memory leak when using grpc (#6896) (#6897)
9a4ca2764 Output errors / warnings on stderr instead of stdout (#6881)
4c7a9c10d Adds JSON encoding to swift (#6874)
38295a187 [Kotlin] Fix missing escape for struct construction statements (#6877)
31bb0b972 add working directory (#6878)
45e5642e9 Default Arguments for Mutators C++ [Updated] (#6872)
a592f4c89 [Cmake] Add a post build command after flatc to run the new generate_code.py script. (#6866)
b9d43a557 dart - add Packable interface (#6846)
2ece9e25b Bumped package.json to 2.0.4
2dd212637 Fix linker errors on (Free|Open)BSD. (#6860)
f63c130c2 Improves documentation, and adding DocC (#6784)
e2b26ee19 Make and generate_code.sh generate same outputs (#6855)
9d686bf43 Include subdirectories in published npm package (#6850)
1d26daff3 Use ArrayBuffer type for JS flexbuffer's toObject (#6851)
e72e18d9f feat(build): compile "universal" libraries and executables for Mac (#6852)
354d97f6d fixed errant itemgroup element in C# test project (#6854)
6f7a57eaa [C#] Using 'global::' as qualifying_start_ within BaseGenerator (#6767)
90baa1444 Dart: binary lists (typed_data) (#6839)
0a3b017f0 Delete IDLOptions::lang (#6841)
47d35f105 BugFix: Optional enum when it is null (#6835)
8fb8c2ce1 [C#] Use @ for keyword escaping (#6834)
1d063d87c [C++] Let builder accept custom-alloc std::vector (#6814)
338331b55 Changes to support binary schema file loading and parsing (flatc) (#6823)
156a30c75 Move Apple-specific build flags to Clang section (#6802)
550d2f904 Issue error if jsonschema has no root type defined #6821 (#6831)
c3a38242e Fix typos in docs (#6829)
74c3d7eba [C++] Add mutable version of LookupByKey and test (#6826)
db6eae5c4 Add html and latex to gitignore (#6819)
0e9d79c35 [Java] Avoid casting ByteBuffer to Buffer (#6785)
b20c4d3aa [C++] Add GetMutableSizePrefixedRoot and generate GetMutableSizePrefixedXxx functions (#6815)
ae145293c flattests_cpp17 doesn't compile with Visual Studio 2017: warning C4100: 'indent': unreferenced formal parameter (#6811)
e3c76a5cd Dart lints (#6808)
4b9123baf fix parser string=null (#6810)
f89e0b1a6 Refactor idl_gen_rust and Rust generated code to use consistent whitespace (#6809)
273f6084e Fix Rust keyword inconsistency (#6794)
4a0879458 [C#] Remove superfluous semicolon in C# structs (#6791)
d6f51ea16 fix ptr in flatbuffers cpp tutorial (#6787)
067dce6e7 [C#] Handle keywords (#6775)
2ca5f0e72 [C#] Respect command line parameter for file name extension and suffix (#6779)
f20d2253a update Java version to 2.0.3
390d438e2 [Kotlin] Fix CI by changing compiler to Java 11 (#6783)
6fb2c90d9 avoiding even more NoSuchMethod exceptions (#6729)
a7b527d94 java: Use maven profile to target Java 8 bytecode (#6764)
5d77820b3 [C++] Using calculated fields_number for field_names size (#6769)
909ce970a [C++] Use UnPackTo instead of UnPack if pointer exists (#6725)
35e2cac6e Store vtables sorted in Rust builder (#6765)
c39fc9dd9 [C++] Use nullptr instead of 0 in generated headers (#6762)
775c6567d [C++] Fix compiler warning -Wredundant-parens in clang (#6761)
97d9527f6 Dart 2.0 release prep (#6759)
e01205466 [C++] Use proper gRPC C++ API when using MemoryBuffer Slice (#6756)
5235133f3 Dart - make ascii optimization optional in StringReader, same as in writeString() (#6758)
c871df770 Dart - change table building to assert() instead of exceptions (#6754)
a6eeeb3b9 Dart - inline small functions to increase performance (#6755)
3dd02144d [C#] Fix field name struct name collision (#6744) (#6757)
e77926f0e [C#] Add Union Constructor Utility for ObjectAPI. (#6105)
ac2348202 Dart - fixup writeString() return type after previous merges (#6753)
8be8a0a71 [C++] Fix union type handling on object api in C++17 (#6745)
12e341e4f Rework how Rust generated files are laid out (#6731)
c36672d80 Dart - optimize writeString for ASCII (#6736)
2bfc8e9f0 Dart - make writeString() argument non-nullable (#6737)
674a9f2aa fix lints in rust tests (#6743)
016e6aa13 Add a split on ':' to build_defs.bzl (#6742)
65700441d Dart - make vTable fixed size (expect the number of fields when creating) (#6735)
dd5bb55ca Dart - make vTable deduplication optional (#6734)
e8423da1b Dart - regenerate example after recent flatc changes (#6733)
0980e39c9 flexbuffers: Add variant of Blob() that takes a key (#6730)
e73fab27d Dart - store empty vectors instead of NULL (#6728)
92ae532e4 Dart - finish/lowFinish/buffer changes (#6712)
7482b25f8 Remove ubuntu1604 from presubmit.yml (#6715)
3f77dc9a0 Dart - unpack() must use eager list reader (#6723)
838c93b84 Dart - fix flex-builder compilation error (#6722)
089f48a4a Dart - make sure added padding is zeroed, same as in C++ (#6716)
bf3470c16 Fix UB in CreateVectorOfStructs in case of an empty vector: avoid calling memcpy in this case (#6726)
8f8196e13 Fix 6348 (#6717)
8ab35b2a5 Dart - add custom allocator support (#6711)
c0ba2870c Fix typo in docu (#6714)
22498cf3a [C++] add make_span for Array<T,N> (#6663)
bd37e67ac [C++] Fix a -Wdeprecated-copy warning. (#6708)
a6ee33557 Dart null safety (#6696)
71d43f3be Make --bfbs-filenames default to location of first schema file. (#6705)
c8db1ca5d Jsonschema add prop comments (#6617)
962751a6e Improve generated comparisons for tables (#6486)
06fd6d640 Replace filenames in reflection with filenames+includes. (#6703)
acce4ac3f Fix incorrect assertion usage. (#6702)
8fd7861b7 Fix warning about deprecated module: imp (#6362)
c58ae9422 Add the file a symbol is declared in to Reflection (#6613)
2cf7bb796 Intermediate Representation docs (#6685)
4e3a66c14 Dart object API (#6682)
d959e2320 dart - change Builder.reset() to reuse an existing buffer (#6661)
a9fb54088 use improved versioning (#6691)
337eb8b8f update docs - structs can't be roots (#6690)
6415ef05d [Python] [Codegen] Fixes nested structs with underscore names (#6686)
f069396d1 [C++] flatc --cpp-field-case-style option to permit camel-case field names in C++ (#6669)
021177af0 Fix snap version formatting (#6683)
e1e9f9373 [C++/grpc] added hiding of unused variables in the generated code (#6677)
15110094e Fix GitHub Actions CI gcc/clang versions
093badb0a Use unoptimized path for ReadUInt64 for win32 build as the optimized path crashes. (#6681)
752c7b576 avoiding more NoSuchMethod exceptions (#6671)
7c3e267e1 [Java] ObjectAPI implementation (#6521) (#6582)
baaffbaed npm update to 2.0.3 and script fix
4cb3f222b [TS] Fix module reference in package.json (#6676)
eabdbda75 [TS] Generate entry point module (#6674)
bec23700f Prepare for Java 2.0.1 release
12f2eedad Update CI to GCC/Clang 11
221eeb231 Fix typo in C++ doc (#6664)
813d3632e avoiding NoSuchMethod exception (#6658)
d84bccb0c Removed most heap allocations in builder (#6662)
b4e67f9bf Dart test fix (#6660)
54c11932f [Java] Flexbuffers - Negative signed object length (#6651)
fbcb3c423 [TS/JS] Updates the grpc (#6654)
8937dcfd7 Updates go lang support to allow other languages to communicate with it (#6653)
512d5a689 Update readme.md to point to security policy
a92cb5dd7 Create Security.md
d151dcbb9 Revert "[C++] Removed most heap allocations in builder (#6620)" (#6659)
f1884c66f Fix gRPC test to use EndVector without specifying the length. (#6646)
72730ecd8 [C++] Removed most heap allocations in builder (#6620)
fe2bc2b0a Added README for Rust Flatbuffers (before publishing v=2.0) (#6652)
4867c9456 Fixed generation of c++ code with flags (#6637)
ef0eb3701 Ran clang-format-all.sh. Removed default --style=file parameter (#6639)
f83ee1af5 [idl_parser] Check structs and enums do not clash in a namespace (#6562)
a5175c513 Implements verifier and code gen for swift (#6373)
04b10f5a3 Deprecate EnumVal.object (#6612)
c121c0345 Fixed Java gRPC version number dependency
8fd10606c Implement Serialize for flexbuffer::Reader (#6635)
a1730fcea [Swift] Updated cocoapods to 2.0.0 (#6634)
a9a295fec More missing version changes
5c01ad387 Dart generated code update
42ca1b914 Swift/Kotlin generated code version updates
6ed780dbd C++/Rust version changes
3412fab8e C#/Java generated code version updates
8a7d013f8 Updated main version numbers to 2.0
170af5978 [Go] Add missing namespace when using Object API (#6633)
c8c16de16 Fix reverse iterators for Vector and Array (#6626)
4525cd9c5 [Lua] manipulate byte array as string (#6624)
47361baf6 [C++] Fix union copy constructor to work with nested structs (#6552) (#6607)
8a582883a Updates swift generated monster sample file (#6616)
a4bb8f0c2 [Lua] Avoid infinite loop when creating empty string (#6614)
82aed82b8 Added support for Lua 5.1, 5.2 and 5.4 (#6606)
60ff76630 [TS] Remove wrong and obsolete NS prefix use (#6604)
a27c7d809 Fixed LuaJIT when not compiled with COMPAT mode (#6605)
363220823 removed unneeded type prefixing (#6601)
6b44c605b Bump Rust to 0.9.0 (#6610)
d3cd78a87 [Lua] Add LuaJIT support (#6584)
8fa3dfdb5 Introduce new_from_vec in Rust (also fix formatting) (#6599)
29379e8e4 fix typo in CppUsage.md (#6595)
14725d6c3 [Lua] GetRootAs can accept strings. Made Luatest Benchmarks optional (#6593)
16836ff95 Add advance feature indicators to reflection (#6546)
c87179e73 Rust Remove SafeSliceAccess for Arrays, and fix miri. (#6592)
c24031c36 Mark endian_scalar as unsafe. (#6588)
4ccc52c7a [swift] Implements union strings (#6589)
b82fe0738 [Rust] Fix small mistyping (#6585)
1e7f6c8c7 [TS] Commit the generated tests code (#6579)
84714b109 chore: ensure bash is used to generate code (#6577)
1045d7dd4 [Lua] Fix EnforceNumberAndPack for bool type (#6576)
0c7777596 [TS] Remove duplicated build-ts ci (#6575)
c43ba1752 [Rust] Specify Minimum Supported Rust Version (#6573)
da3bb64ef [Rust] Add support for fixed size arrays (#6548)
151900ba9 [Kotlin][FlexBuffers] Add support for Kotlin-iOS (#6564)
c012f29f9 silenced clippy warning (#6565)
df2df21ec [Kotlin] Bump kotlinx.benchmark dependency to 0.3.0 (#6560)
408e4db4a [TS] Add Build TS to CI jobs (#6524)
4d2364f34 [Kotlin][FlexBuffers] Add support for Kotlin-JS (#6554)
261cf3b20 Default-empty vectors of enums (#6505)
cd67261bb [CI] fixes buildkite (#6544)
1aa0c2f6a Limit formatter to pull requests only (#6540)
4133a39df Rust structz (#6539)
1c26d2a1a [Kotlin][FlexBuffers] JSON support for Flexbuffers (#6417)
276b1bc34 [grpc] Support latest version of grpc PoC (#6338)
124654ffc fixed packing structs (#6530)
3b7d1e86b [GO] Tries to add go format to the CI (#6518)
78f0c0d1d [C++] #6501 - Problem when mapping a native type multiple times (#6514)
c992eafb5 [fuzzer] Add `monster_debug` target (#6513)
ef8dd7792 [Swift] Removes allman rule (#6519)
69b329fc8 [flexbuffers, json] Parse `nan` and `inf` (#6512)
6543ba529 fixed packing structs in nested buffers (#6509)
0e453ac35 [idl_parser] Add kTokenNumericConstant token (#6432)
e9b4ae69d Remove `flatbuffers.pc` from the repository (#6508)
fc4fffea4 Bump grpc to 1.0.0 (#6507)
b240ab704 Move Traits struct and Create method out of --cpp-static-reflection. (#6503)
9a4f1f434 Disable x64-specific optimizations for ARM64EC ReadInt64 (#6506)
fac64918d Add --cpp-static-reflection to generate_code.bat. (#6502)
a69815f72 [C++17] Add compile-time reflection for fields. (#6324)
4033ff589 fixed invalid TS call and added test files (#6495)
a08357251 disable clippy (#6494)
5319dedb1 [idl_parser, JSON] Disable parsing of JSON for incomplete schemes (#6493)
bd4e0b30a [idl_parser] Track included files by hash (#6434)
bf9061200 fix for noUncheckedIndexedAccess in ts (#6474)
8142fedd1 Working on a python example plus fixing python grpc code (#6456)
c0be1cb7a [rust] Remove debug code (#6475)
8cccdfba5 Revert "[C#] Fix truncated ArraySegment<byte> if elementSize != 1 (#6462)" (#6488)
cbbbaa61b [C#] Fix truncated ArraySegment<byte> if elementSize != 1 (#6462)
ffc2ef77c [CI] Adds Code Generation tests on Github Actions (#6482)
1da6f4f18 [CMake] generate pkg-config flatbuffers.pc file (#6455)
b5da526e6 [Swift] Moves grpc example to grpc/examples (#6479)
3b5365762 [TS] Moves grpc code to examples folder (#6476)
e2f5438ac Fixes grammer (#6477)
5e3613f73 Fix sample_binary.py to use latest EndVector without a size. (#6478)
e6b911d40 updated JS docs to reflect current status (#6436)
0c7ae5816 [Go] Working on a go example plus fixing go grpc code (#6448)
ae603b977 [Swift] adds support for default vectors and strings (#6461)
7f47718b6 Update Building.md (#6473)
54dc09e8a GetUOffsetT must get value by GetUint32 not GetInt32 (#6072)
334c6be49 Fix a typo in Swift codegen (#6470)
4174c10e7 [rust] Genericize flexbuffer reader (#6450)
a20f606c2 [Swift] Renaming protocols (#6469)
a72a20827 Update swift docs (#6460)
86401e078 Default strings and vectors: Parser + Rust support (#6421)
6af37e672 [CMake] Renames BUILD files (#6457)
1b88655b0 [Build, cmake] Add -Werror override option (#6429)
0b15916e5 [C++]Fix extra char generation for byte type during json schema generation (#6276)
60eed0ca6 Updating working code (#6441)
0f83367f5 JSON schema - tailing double quotes for maximum (#6452)
fee095410 [idl_parser] Validate `force_align` on all possible paths (#6430)
6f3e45eca Implement Rust object API defaults (#6444)
815d3e820 Upgrade swift grpc to alpha 24 (#6439)
76e7a0ff5 [fuzzer] Limit parser_fuzzer execution time (#6431)
6d91096a2 This commit contains the initial implementation of Flexbuffers in Kotlin. The code was ported based (#6387)
13d9e3585 Better python generated code naming (#6336)
6effe431b Rust: remove inner attributes (#6410)
efcbdc769 [Rust] Ensure unions are referenced with the correct path (#6422)
e581013e3 Refactor FieldDef to model presense as an enum rather than 2 bools. (#6420)
0984d4328 [c++] Apply NativeName before WrapInNameSpace in idl_gen_cpp.cpp (#6419)
786f69b24 Formats cpp code (#6349)
1da0a2dfa Rust Object API (#6070)
796ed68fa Clarify that (Flat|Flex)Buffers do not deduplicate vector elements (#6415)
7b1ee31d8 Clarify that FlatBuffers unions do not support scalars (#6416)
4aff1198d Explain how FlatBuffers encodes unions (#6414)
ad3a729f9 dart Builder - expose finished buffer size (#6403)
52e217706 Remove invalid claim that Protocol Buffers does not support unions (#6413)
760c65755 [TS/JS] New gen TS code gen (#6302)
75c859e98 [idl_parser] Improve symbols lookup thru parent namespaces (#6407)
91b0958c4 Search for includes in the directory containg the current file (#6371)
8008dde11 Upgrade Rust dependencies (#6406)
c81cf8249 [TS/JS] New gen TS code gen prequel to preserve history (#6404)
8573108bb Unset FieldDef.optional if its key (#6402)
7abe612b5 [fuzzer] Fix the binary schema loading in the monster_fuzzer (#6396)
408cf5802 Fix Rust UB problems (#6393)
39e115fdb Define Vector::value_type for STL compatibility (#6394)
85719669c [fuzzer] Debug the monster_tets.bfbs on clusterfuzz server (#6392)
809fe49c7 Fix up scripts, fix generated enum value for strong mode, regenerate files (#6389)
41253e574 [go] tests/GoTest.sh: Fix flags.Parse location to work on new go SDKs. (#6388)
08d2ce844 fix Dart Builder._writeString() - always write trailing zero byte (#6390)
a15a8d930 fix Dart Builder.reset() - clear vTables (#6386)
83ce29cc2 [C++, JSON] Fix nullptr access when reading a key with a default value. (#6375)
4363c1d2c Fix generated EndVector. (#6385)
1bf1ec027 Implements type promotion for Java enum (#6382)
080097653 Delete label_notify.yml
795408115 Disabled PHP CI (#6381)
46545e627 fixed warnings (#6355)
0168178a1 Fix multiple fbs code generation failure (#6365)
82836a62b [idl_parser] Improve stack overflow protection (#6364)
e7430bbeb [idl_parser] Check the range of explicitly set field's id value (#6363)
24dd85fd2 Generate code to encode and decode nested flatbuffers in Python. (#6354)
57f68e289 [Rust] Shared String (#6367)
44cf2bde1 Updates license date to 2021 (#6378)
be37d4da1 include_prefix support for rust (#6330)
4e79d129c [Swift] Rebuild the way swift handles structs from scratch (#6326)
05192553f Fix typos in usage/comments; Make rust generator respect to --filenam… (#6342)
f2511d7d4 Renaming infinity variables in test.cpp (#6340)
f8b203c9c Add vectorNumElements attribute to Builder for simpler vector creation. (#6328)
8ab7c7e2c [CI] Adds formatter to CI (#6272)
7e0039028 Fix Max CI build path (#6333)
65c415911 Generate nullable properties in C# object-based API for optional scalars. (without -gen-mutable) (#6273)
a9e91116d [Python] Commit some orphan python genfile diffs. (#6325)
80a745d9b Fixed missing ending quotes in labeller (#6327)
9fca5e4f4 Add flatc option to inhibit all warnings #6005 (#6301)
92a806b4e [fuzzer] Rename fuzzing dictionaries for `oss-fuzz` (#6318)
9c9baf6d5 bumprust (#6322)
aafc5dc95 Set default initialSize for Builder to 0 (#6310)
442949bc1 Rust Flatbuffers Verifier (#6269)
9064072e8 Version message should be a "STATUS" to avoid going to stderr. (#6316)
fd4c1b5ff Replace std::string and const char* CreateSharedString with string_view (#6315)
bc7eb8ade [fuzzer] Fix mistakes in the `parser` and `scalar` fuzzers. (#6314)
fc960f367 Add default to offset param of Python generated GetRootAs (#6312)
f437f0f7e [fuzzer] Fix loading of schema in monster_fuzzer (#6308)
7f33cf682 [C++] Switch `flatc` to `--cpp-std c++11` C++ code generator (#6306)
8d9eae9ac [idl_parser] Unify parsing of NaN values read from .fbs and .json files (#6296)
2046bffa4 Moved various language tests from AppVeyor to GitHub Actions (#6300)
git-subtree-dir: third_party/flatbuffers
git-subtree-split: e5f331db998a808f78cf5a4880e6f5d0a321c4d0
Signed-off-by: James Kuszmaul <jabukuszmaul+collab@gmail.com>
Change-Id: I37f8aaf007fc86226cfa250169a87807afa64a78
diff --git a/src/idl_gen_python.cpp b/src/idl_gen_python.cpp
index 1260673..8426b6e 100644
--- a/src/idl_gen_python.cpp
+++ b/src/idl_gen_python.cpp
@@ -26,10 +26,42 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
+#include "namer.h"
namespace flatbuffers {
namespace python {
+std::set<std::string> PythonKeywords() {
+ return { "False", "None", "True", "and", "as", "assert",
+ "break", "class", "continue", "def", "del", "elif",
+ "else", "except", "finally", "for", "from", "global",
+ "if", "import", "in", "is", "lambda", "nonlocal",
+ "not", "or", "pass", "raise", "return", "try",
+ "while", "with", "yield" };
+}
+
+Namer::Config PythonDefaultConfig() {
+ return { /*types=*/Case::kKeep,
+ /*constants=*/Case::kScreamingSnake,
+ /*methods=*/Case::kUpperCamel,
+ /*functions=*/Case::kUpperCamel,
+ /*fields=*/Case::kLowerCamel,
+ /*variable=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/".",
+ /*namespaces=*/Case::kKeep, // Packages in python.
+ /*namespace_seperator=*/".",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"",
+ /*filename_extension=*/".py" };
+}
+
// Hardcode spaces per indentation.
const CommentConfig def_comment = { nullptr, "#", nullptr };
const std::string Indent = " ";
@@ -40,20 +72,13 @@
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "" /* not used */,
"" /* not used */, "py"),
- float_const_gen_("float('nan')", "float('inf')", "float('-inf')") {
- static const char *const keywords[] = {
- "False", "None", "True", "and", "as", "assert", "break",
- "class", "continue", "def", "del", "elif", "else", "except",
- "finally", "for", "from", "global", "if", "import", "in",
- "is", "lambda", "nonlocal", "not", "or", "pass", "raise",
- "return", "try", "while", "with", "yield"
- };
- keywords_.insert(std::begin(keywords), std::end(keywords));
- }
+ float_const_gen_("float('nan')", "float('inf')", "float('-inf')"),
+ namer_({ PythonDefaultConfig().WithFlagOptions(parser.opts, path),
+ PythonKeywords() }) {}
// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that.
- std::string OffsetPrefix(const FieldDef &field) {
+ std::string OffsetPrefix(const FieldDef &field) const {
return "\n" + Indent + Indent +
"o = flatbuffers.number_types.UOffsetTFlags.py_type" +
"(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" +
@@ -61,85 +86,64 @@
}
// Begin a class declaration.
- void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
+ void BeginClass(const StructDef &struct_def, std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "class " + NormalizedName(struct_def) + "(object):\n";
+ code += "class " + namer_.Type(struct_def.name) + "(object):\n";
code += Indent + "__slots__ = ['_tab']";
code += "\n\n";
}
// Begin enum code with a class declaration.
- void BeginEnum(const std::string &class_name, std::string *code_ptr) {
+ void BeginEnum(const EnumDef &enum_def, std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "class " + class_name + "(object):\n";
- }
-
- std::string EscapeKeyword(const std::string &name) const {
- return keywords_.find(name) == keywords_.end() ? name : name + "_";
- }
-
- std::string NormalizedName(const Definition &definition) const {
- return EscapeKeyword(definition.name);
- }
-
- std::string NormalizedName(const EnumVal &ev) const {
- return EscapeKeyword(ev.name);
- }
-
- // Converts the name of a definition into upper Camel format.
- std::string MakeUpperCamel(const Definition &definition) const {
- return MakeCamel(NormalizedName(definition), true);
- }
-
- // Converts the name of a definition into lower Camel format.
- std::string MakeLowerCamel(const Definition &definition) const {
- auto name = MakeCamel(NormalizedName(definition), false);
- name[0] = CharToLower(name[0]);
- return name;
+ code += "class " + namer_.Type(enum_def.name) + "(object):\n";
}
// Starts a new line and then indents.
- std::string GenIndents(int num) {
+ std::string GenIndents(int num) const {
return "\n" + std::string(num * Indent.length(), ' ');
}
// A single enum member.
void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code += Indent;
- code += NormalizedName(ev);
+ code += namer_.Variant(ev.name);
code += " = ";
code += enum_def.ToString(ev) + "\n";
}
- // End enum code.
- void EndEnum(std::string *code_ptr) {
- auto &code = *code_ptr;
- code += "\n";
- }
-
// Initialize a new struct or table from existing data.
void NewRootTypeFromBuffer(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
+ const std::string struct_type = namer_.Type(struct_def.name);
code += Indent + "@classmethod\n";
code += Indent + "def GetRootAs";
- code += NormalizedName(struct_def);
- code += "(cls, buf, offset):";
+ code += "(cls, buf, offset=0):";
code += "\n";
code += Indent + Indent;
code += "n = flatbuffers.encode.Get";
code += "(flatbuffers.packer.uoffset, buf, offset)\n";
- code += Indent + Indent + "x = " + NormalizedName(struct_def) + "()\n";
+ code += Indent + Indent + "x = " + struct_type + "()\n";
code += Indent + Indent + "x.Init(buf, n + offset)\n";
code += Indent + Indent + "return x\n";
code += "\n";
+
+ // Add an alias with the old name
+ code += Indent + "@classmethod\n";
+ code += Indent + "def GetRootAs" + struct_type + "(cls, buf, offset=0):\n";
+ code +=
+ Indent + Indent +
+ "\"\"\"This method is deprecated. Please switch to GetRootAs.\"\"\"\n";
+ code += Indent + Indent + "return cls.GetRootAs(buf, offset)\n";
}
// Initialize an existing object with other data, to avoid an allocation.
- void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) {
+ void InitializeExisting(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
@@ -150,11 +154,11 @@
// Get the length of a vector.
void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "Length(self";
+ code += namer_.Method(field.name) + "Length(self";
code += "):" + OffsetPrefix(field);
code += Indent + Indent + Indent + "return self._tab.VectorLen(o)\n";
code += Indent + Indent + "return 0\n\n";
@@ -162,11 +166,11 @@
// Determines whether a vector is none or not.
void GetVectorIsNone(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "IsNone(self";
+ code += namer_.Method(field.name) + "IsNone(self";
code += "):";
code += GenIndents(2) +
"o = flatbuffers.number_types.UOffsetTFlags.py_type" +
@@ -177,11 +181,12 @@
// Get the value of a struct's scalar.
void GetScalarFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self): return " + getter;
code += "self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(";
code += NumToString(field.value.offset) + "))\n";
@@ -189,11 +194,11 @@
// Get the value of a table's scalar.
void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self):";
code += OffsetPrefix(field);
getter += "o + self._tab.Pos)";
@@ -214,10 +219,11 @@
// Get a struct by initializing an existing struct.
// Specific to Struct.
void GetStructFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self, obj):\n";
code += Indent + Indent + "obj.Init(self._tab.Bytes, self._tab.Pos + ";
code += NumToString(field.value.offset) + ")";
@@ -226,11 +232,11 @@
// Get the value of a fixed size array.
void GetArrayOfStruct(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
const auto vec_type = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
if (IsStruct(vec_type)) {
code += "(self, obj, i):\n";
code += Indent + Indent + "obj.Init(self._tab.Bytes, self._tab.Pos + ";
@@ -251,10 +257,10 @@
// Get a struct by initializing an existing struct.
// Specific to Table.
void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self):";
code += OffsetPrefix(field);
if (field.value.type.struct_def->fixed) {
@@ -276,10 +282,10 @@
// Get the value of a string.
void GetStringField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self):";
code += OffsetPrefix(field);
code += Indent + Indent + Indent + "return " + GenGetter(field.value.type);
@@ -289,10 +295,10 @@
// Get the value of a union from an object.
void GetUnionField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "(self):";
+ code += namer_.Method(field.name) + "(self):";
code += OffsetPrefix(field);
// TODO(rw): this works and is not the good way to it:
@@ -313,27 +319,33 @@
// Generate the package reference when importing a struct or enum from its
// module.
- std::string GenPackageReference(const Type &type) {
- Namespace *namespaces;
+ std::string GenPackageReference(const Type &type) const {
if (type.struct_def) {
- namespaces = type.struct_def->defined_namespace;
+ return GenPackageReference(*type.struct_def);
} else if (type.enum_def) {
- namespaces = type.enum_def->defined_namespace;
+ return GenPackageReference(*type.enum_def);
} else {
return "." + GenTypeGet(type);
}
-
- return namespaces->GetFullyQualifiedName(GenTypeGet(type));
+ }
+ std::string GenPackageReference(const EnumDef &enum_def) const {
+ return namer_.NamespacedType(enum_def.defined_namespace->components,
+ enum_def.name);
+ }
+ std::string GenPackageReference(const StructDef &struct_def) const {
+ return namer_.NamespacedType(struct_def.defined_namespace->components,
+ struct_def.name);
}
// Get the value of a vector's struct member.
void GetMemberOfVectorOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self, j):" + OffsetPrefix(field);
code += Indent + Indent + Indent + "x = self._tab.Vector(o)\n";
code += Indent + Indent + Indent;
@@ -357,12 +369,12 @@
// argument to conveniently set the zero value for the result.
void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self, j):";
code += OffsetPrefix(field);
code += Indent + Indent + Indent + "a = self._tab.Vector(o)\n";
@@ -382,7 +394,7 @@
// than iterating over the vector element by element.
void GetVectorOfNonStructAsNumpy(const StructDef &struct_def,
const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
@@ -391,13 +403,13 @@
if (!(IsScalar(vectortype.base_type))) { return; }
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "AsNumpy(self):";
+ code += namer_.Method(field.name) + "AsNumpy(self):";
code += OffsetPrefix(field);
code += Indent + Indent + Indent;
code += "return ";
code += "self._tab.GetVectorAsNumpy(flatbuffers.number_types.";
- code += MakeCamel(GenTypeGet(field.value.type));
+ code += namer_.Method(GenTypeGet(field.value.type));
code += "Flags, o)\n";
if (IsString(vectortype)) {
@@ -408,12 +420,51 @@
code += "\n";
}
+ std::string NestedFlatbufferType(std::string unqualified_name) const {
+ StructDef* nested_root = parser_.LookupStruct(unqualified_name);
+ std::string qualified_name;
+ if (nested_root == nullptr) {
+ qualified_name = namer_.NamespacedType(
+ parser_.current_namespace_->components, unqualified_name);
+ // Double check qualified name just to be sure it exists.
+ nested_root = parser_.LookupStruct(qualified_name);
+ }
+ FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
+ return qualified_name;
+ }
+
+ // Returns a nested flatbuffer as itself.
+ void GetVectorAsNestedFlatbuffer(const StructDef &struct_def,
+ const FieldDef &field,
+ std::string *code_ptr) const {
+ auto nested = field.attributes.Lookup("nested_flatbuffer");
+ if (!nested) { return; } // There is no nested flatbuffer.
+
+ const std::string unqualified_name = nested->constant;
+ const std::string qualified_name = NestedFlatbufferType(unqualified_name);
+
+ auto &code = *code_ptr;
+ GenReceiver(struct_def, code_ptr);
+ code += namer_.Method(field.name) + "NestedRoot(self):";
+
+ code += OffsetPrefix(field);
+
+ code += Indent + Indent + Indent;
+ code += "from " + qualified_name + " import " + unqualified_name + "\n";
+ code += Indent + Indent + Indent + "return " + unqualified_name;
+ code += ".GetRootAs" + unqualified_name;
+ code += "(self._tab.Bytes, self._tab.Vector(o))\n";
+ code += Indent + Indent + "return 0\n";
+ code += "\n";
+ }
+
// Begin the creator function signature.
- void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
+ void BeginBuilderArgs(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code += "\n";
- code += "def Create" + NormalizedName(struct_def);
+ code += "def Create" + namer_.Type(struct_def.name);
code += "(builder";
}
@@ -423,7 +474,7 @@
const std::string nameprefix,
const std::string namesuffix, bool has_field_name,
const std::string fieldname_suffix,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
@@ -436,21 +487,21 @@
// a nested struct, prefix the name with the field name.
auto subprefix = nameprefix;
if (has_field_name) {
- subprefix += NormalizedName(field) + fieldname_suffix;
+ subprefix += namer_.Field(field.name) + fieldname_suffix;
}
StructBuilderArgs(*field.value.type.struct_def, subprefix, namesuffix,
has_field_name, fieldname_suffix, code_ptr);
} else {
auto &code = *code_ptr;
code += std::string(", ") + nameprefix;
- if (has_field_name) { code += MakeCamel(NormalizedName(field), false); }
+ if (has_field_name) { code += namer_.Field(field.name); }
code += namesuffix;
}
}
}
// End the creator function signature.
- void EndBuilderArgs(std::string *code_ptr) {
+ void EndBuilderArgs(std::string *code_ptr) const {
auto &code = *code_ptr;
code += "):\n";
}
@@ -459,7 +510,7 @@
// padding.
void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
std::string *code_ptr, size_t index = 0,
- bool in_array = false) {
+ bool in_array = false) const {
auto &code = *code_ptr;
std::string indent(index * 4, ' ');
code +=
@@ -475,9 +526,10 @@
code +=
indent + " builder.Pad(" + NumToString(field.padding) + ")\n";
if (IsStruct(field_type)) {
- StructBuilderBody(*field_type.struct_def,
- (nameprefix + (NormalizedName(field) + "_")).c_str(),
- code_ptr, index, in_array);
+ StructBuilderBody(
+ *field_type.struct_def,
+ (nameprefix + (namer_.Field(field.name) + "_")).c_str(), code_ptr,
+ index, in_array);
} else {
const auto index_var = "_idx" + NumToString(index);
if (IsArray(field_type)) {
@@ -489,12 +541,12 @@
if (IsStruct(type)) {
StructBuilderBody(
*field_type.struct_def,
- (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr,
+ (nameprefix + (namer_.Field(field.name) + "_")).c_str(), code_ptr,
index + 1, in_array);
} else {
code += IsArray(field_type) ? " " : "";
code += indent + " builder.Prepend" + GenMethod(field) + "(";
- code += nameprefix + MakeCamel(NormalizedName(field), false);
+ code += nameprefix + namer_.Variable(field.name);
size_t array_cnt = index + (IsArray(field_type) ? 1 : 0);
for (size_t i = 0; in_array && i < array_cnt; i++) {
code += "[_idx" + NumToString(i) + "-1]";
@@ -505,53 +557,76 @@
}
}
- void EndBuilderBody(std::string *code_ptr) {
+ void EndBuilderBody(std::string *code_ptr) const {
auto &code = *code_ptr;
code += " return builder.Offset()\n";
}
// Get the value of a table's starting offset.
- void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
+ void GetStartOfTable(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "def " + NormalizedName(struct_def) + "Start";
- code += "(builder): ";
+ const auto struct_type = namer_.Type(struct_def.name);
+ // Generate method with struct name.
+ code += "def " + struct_type + "Start(builder): ";
code += "builder.StartObject(";
code += NumToString(struct_def.fields.vec.size());
code += ")\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct name.
+ code += "def Start(builder):\n";
+ code += Indent + "return " + struct_type + "Start(builder)\n";
+ }
}
// Set the value of a table's field.
void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- const size_t offset, std::string *code_ptr) {
+ const size_t offset, std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "def " + NormalizedName(struct_def) + "Add" +
- MakeCamel(NormalizedName(field));
+ const std::string field_var = namer_.Variable(field.name);
+ const std::string field_method = namer_.Method(field.name);
+
+ // Generate method with struct name.
+ code += "def " + namer_.Type(struct_def.name) + "Add" + field_method;
code += "(builder, ";
- code += MakeCamel(NormalizedName(field), false);
+ code += field_var;
code += "): ";
code += "builder.Prepend";
code += GenMethod(field) + "Slot(";
code += NumToString(offset) + ", ";
if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
code += "flatbuffers.number_types.UOffsetTFlags.py_type";
- code += "(";
- code += MakeCamel(NormalizedName(field), false) + ")";
+ code += "(" + field_var + ")";
} else {
- code += MakeCamel(NormalizedName(field), false);
+ code += field_var;
}
code += ", ";
code += IsFloat(field.value.type.base_type)
? float_const_gen_.GenFloatConstant(field)
: field.value.constant;
code += ")\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct name.
+ code += "def Add" + field_method + "(builder, " + field_var + "):\n";
+ code += Indent + "return " + namer_.Type(struct_def.name) + "Add" +
+ field_method;
+ code += "(builder, ";
+ code += field_var;
+ code += ")\n";
+ }
}
// Set the value of one of the members of a table's vector.
void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "def " + NormalizedName(struct_def) + "Start";
- code += MakeCamel(NormalizedName(field));
+ const std::string struct_type = namer_.Type(struct_def.name);
+ const std::string field_method = namer_.Method(field.name);
+
+ // Generate method with struct name.
+ code += "def " + struct_type + "Start" + field_method;
code += "Vector(builder, numElems): return builder.StartVector(";
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
@@ -559,26 +634,79 @@
code += NumToString(elem_size);
code += ", numElems, " + NumToString(alignment);
code += ")\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct name.
+ code += "def Start" + field_method + "Vector(builder, numElems):\n";
+ code += Indent + "return " + struct_type + "Start";
+ code += field_method + "Vector(builder, numElems)\n";
+ }
+ }
+
+ // Set the value of one of the members of a table's vector and fills in the
+ // elements from a bytearray. This is for simplifying the use of nested
+ // flatbuffers.
+ void BuildVectorOfTableFromBytes(const StructDef &struct_def,
+ const FieldDef &field,
+ std::string *code_ptr) const {
+ auto nested = field.attributes.Lookup("nested_flatbuffer");
+ if (!nested) { return; } // There is no nested flatbuffer.
+
+ auto &code = *code_ptr;
+ const std::string field_method = namer_.Method(field.name);
+ const std::string struct_type = namer_.Type(struct_def.name);
+
+ // Generate method with struct and field name.
+ code += "def " + struct_type + "Make" + field_method;
+ code += "VectorFromBytes(builder, bytes):\n";
+ code += Indent + "builder.StartVector(";
+ auto vector_type = field.value.type.VectorType();
+ auto alignment = InlineAlignment(vector_type);
+ auto elem_size = InlineSize(vector_type);
+ code += NumToString(elem_size);
+ code += ", len(bytes), " + NumToString(alignment);
+ code += ")\n";
+ code += Indent + "builder.head = builder.head - len(bytes)\n";
+ code += Indent + "builder.Bytes[builder.head : builder.head + len(bytes)]";
+ code += " = bytes\n";
+ code += Indent + "return builder.EndVector()\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct and field name.
+ code += "def Make" + field_method + "VectorFromBytes(builder, bytes):\n";
+ code += Indent + "return " + struct_type + "Make" + field_method +
+ "VectorFromBytes(builder, bytes)\n";
+ }
}
// Get the offset of the end of a table.
- void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
+ void GetEndOffsetOnTable(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "def " + NormalizedName(struct_def) + "End";
+
+ // Generate method with struct name.
+ code += "def " + namer_.Type(struct_def.name) + "End";
code += "(builder): ";
code += "return builder.EndObject()\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct name.
+ code += "def End(builder):\n";
+ code +=
+ Indent + "return " + namer_.Type(struct_def.name) + "End(builder)";
+ }
}
// Generate the receiver for function signatures.
- void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
+ void GenReceiver(const StructDef &struct_def, std::string *code_ptr) const {
auto &code = *code_ptr;
- code += Indent + "# " + NormalizedName(struct_def) + "\n";
+ code += Indent + "# " + namer_.Type(struct_def.name) + "\n";
code += Indent + "def ";
}
// Generate a struct field, conditioned on its child type(s).
void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
GenComment(field.doc_comment, code_ptr, &def_comment, Indent.c_str());
if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) {
@@ -607,6 +735,7 @@
} else {
GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
GetVectorOfNonStructAsNumpy(struct_def, field, code_ptr);
+ GetVectorAsNestedFlatbuffer(struct_def, field, code_ptr);
}
break;
}
@@ -621,7 +750,8 @@
}
// Generate struct sizeof.
- void GenStructSizeOf(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStructSizeOf(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code += Indent + "@classmethod\n";
code += Indent + "def SizeOf(cls):\n";
@@ -631,7 +761,8 @@
}
// Generate table constructors, conditioned on its members' types.
- void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
+ void GenTableBuilders(const StructDef &struct_def,
+ std::string *code_ptr) const {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
@@ -643,6 +774,7 @@
BuildFieldOfTable(struct_def, field, offset, code_ptr);
if (IsVector(field.value.type)) {
BuildVectorOfTable(struct_def, field, code_ptr);
+ BuildVectorOfTableFromBytes(struct_def, field, code_ptr);
}
}
@@ -651,7 +783,7 @@
// Generate function to check for proper file identifier
void GenHasFileIdentifier(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
std::string escapedID;
// In the event any of file_identifier characters are special(NULL, \, etc),
@@ -663,7 +795,7 @@
}
code += Indent + "@classmethod\n";
- code += Indent + "def " + NormalizedName(struct_def);
+ code += Indent + "def " + namer_.Type(struct_def.name);
code += "BufferHasIdentifier(cls, buf, offset, size_prefixed=False):";
code += "\n";
code += Indent + Indent;
@@ -674,7 +806,7 @@
}
// Generates struct or table methods.
- void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStruct(const StructDef &struct_def, std::string *code_ptr) const {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, &def_comment);
@@ -712,23 +844,24 @@
}
void GenReceiverForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- code += GenIndents(1) + "# " + NormalizedName(struct_def) + "T";
+ code += GenIndents(1) + "# " + namer_.ObjectType(struct_def.name);
code += GenIndents(1) + "def ";
}
void BeginClassForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code += "\n";
- code += "class " + NormalizedName(struct_def) + "T(object):";
+ code += "class " + namer_.ObjectType(struct_def.name) + "(object):";
code += "\n";
}
// Gets the accoresponding python builtin type of a BaseType for scalars and
// string.
- std::string GetBasePythonTypeForScalarAndString(const BaseType &base_type) {
+ std::string GetBasePythonTypeForScalarAndString(
+ const BaseType &base_type) const {
if (IsBool(base_type)) {
return "bool";
} else if (IsFloat(base_type)) {
@@ -743,7 +876,7 @@
}
}
- std::string GetDefaultValue(const FieldDef &field) {
+ std::string GetDefaultValue(const FieldDef &field) const {
BaseType base_type = field.value.type.base_type;
if (IsBool(base_type)) {
return field.value.constant == "0" ? "False" : "True";
@@ -759,7 +892,7 @@
void GenUnionInit(const FieldDef &field, std::string *field_types_ptr,
std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) {
+ std::set<std::string> *import_typing_list) const {
// Gets all possible types in the union.
import_typing_list->insert("Union");
auto &field_types = *field_types_ptr;
@@ -774,7 +907,7 @@
std::string field_type;
switch (ev.union_type.base_type) {
case BASE_TYPE_STRUCT:
- field_type = GenTypeGet(ev.union_type) + "T";
+ field_type = namer_.ObjectType(ev.union_type.struct_def->name);
if (parser_.opts.include_dependence_headers) {
auto package_reference = GenPackageReference(ev.union_type);
field_type = package_reference + "." + field_type;
@@ -794,45 +927,43 @@
// Gets the import lists for the union.
if (parser_.opts.include_dependence_headers) {
- // The package reference is generated based on enum_def, instead
- // of struct_def in field.type. That's why GenPackageReference() is
- // not used.
- Namespace *namespaces = field.value.type.enum_def->defined_namespace;
- auto package_reference = namespaces->GetFullyQualifiedName(
- MakeUpperCamel(*(field.value.type.enum_def)));
- auto union_name = MakeUpperCamel(*(field.value.type.enum_def));
+ const auto package_reference =
+ GenPackageReference(*field.value.type.enum_def);
import_list->insert("import " + package_reference);
}
}
- void GenStructInit(const FieldDef &field, std::string *field_type_ptr,
+ void GenStructInit(const FieldDef &field, std::string *out_ptr,
std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) {
+ std::set<std::string> *import_typing_list) const {
import_typing_list->insert("Optional");
- auto &field_type = *field_type_ptr;
+ auto &output = *out_ptr;
+ const Type &type = field.value.type;
+ const std::string object_type = namer_.ObjectType(type.struct_def->name);
if (parser_.opts.include_dependence_headers) {
- auto package_reference = GenPackageReference(field.value.type);
- field_type = package_reference + "." + TypeName(field) + "T]";
+ auto package_reference = GenPackageReference(type);
+ output = package_reference + "." + object_type + "]";
import_list->insert("import " + package_reference);
} else {
- field_type = TypeName(field) + "T]";
+ output = object_type + "]";
}
- field_type = "Optional[" + field_type;
+ output = "Optional[" + output;
}
void GenVectorInit(const FieldDef &field, std::string *field_type_ptr,
std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) {
+ std::set<std::string> *import_typing_list) const {
import_typing_list->insert("List");
auto &field_type = *field_type_ptr;
- auto base_type = field.value.type.VectorType().base_type;
+ const Type &vector_type = field.value.type.VectorType();
+ const BaseType base_type = vector_type.base_type;
if (base_type == BASE_TYPE_STRUCT) {
- field_type = GenTypeGet(field.value.type.VectorType()) + "T]";
+ const std::string object_type =
+ namer_.ObjectType(GenTypeGet(vector_type));
+ field_type = object_type + "]";
if (parser_.opts.include_dependence_headers) {
- auto package_reference =
- GenPackageReference(field.value.type.VectorType());
- field_type = package_reference + "." +
- GenTypeGet(field.value.type.VectorType()) + "T]";
+ auto package_reference = GenPackageReference(vector_type);
+ field_type = package_reference + "." + object_type + "]";
import_list->insert("import " + package_reference);
}
field_type = "List[" + field_type;
@@ -843,7 +974,7 @@
}
void GenInitialize(const StructDef &struct_def, std::string *code_ptr,
- std::set<std::string> *import_list) {
+ std::set<std::string> *import_list) const {
std::string code;
std::set<std::string> import_typing_list;
for (auto it = struct_def.fields.vec.begin();
@@ -874,11 +1005,11 @@
break;
}
- auto default_value = GetDefaultValue(field);
+ const auto default_value = GetDefaultValue(field);
// Wrties the init statement.
- auto field_instance_name = MakeLowerCamel(field);
- code += GenIndents(2) + "self." + field_instance_name + " = " +
- default_value + " # type: " + field_type;
+ const auto field_field = namer_.Field(field.name);
+ code += GenIndents(2) + "self." + field_field + " = " + default_value +
+ " # type: " + field_type;
}
// Writes __init__ method.
@@ -914,46 +1045,44 @@
}
// Removes the import of the struct itself, if applied.
- auto package_reference =
- struct_def.defined_namespace->GetFullyQualifiedName(
- MakeUpperCamel(struct_def));
- auto struct_import = "import " + package_reference;
+ auto struct_import = "import " + GenPackageReference(struct_def);
import_list->erase(struct_import);
}
- void InitializeFromBuf(const StructDef &struct_def, std::string *code_ptr) {
+ void InitializeFromBuf(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto instance_name = MakeLowerCamel(struct_def);
- auto struct_name = NormalizedName(struct_def);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const auto struct_type = namer_.Type(struct_def.name);
code += GenIndents(1) + "@classmethod";
code += GenIndents(1) + "def InitFromBuf(cls, buf, pos):";
- code += GenIndents(2) + instance_name + " = " + struct_name + "()";
- code += GenIndents(2) + instance_name + ".Init(buf, pos)";
- code += GenIndents(2) + "return cls.InitFromObj(" + instance_name + ")";
+ code += GenIndents(2) + struct_var + " = " + struct_type + "()";
+ code += GenIndents(2) + struct_var + ".Init(buf, pos)";
+ code += GenIndents(2) + "return cls.InitFromObj(" + struct_var + ")";
code += "\n";
}
void InitializeFromObjForObject(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto instance_name = MakeLowerCamel(struct_def);
- auto struct_name = NormalizedName(struct_def);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const auto struct_object = namer_.ObjectType(struct_def.name);
code += GenIndents(1) + "@classmethod";
- code += GenIndents(1) + "def InitFromObj(cls, " + instance_name + "):";
- code += GenIndents(2) + "x = " + struct_name + "T()";
- code += GenIndents(2) + "x._UnPack(" + instance_name + ")";
+ code += GenIndents(1) + "def InitFromObj(cls, " + struct_var + "):";
+ code += GenIndents(2) + "x = " + struct_object + "()";
+ code += GenIndents(2) + "x._UnPack(" + struct_var + ")";
code += GenIndents(2) + "return x";
code += "\n";
}
void GenUnPackForStruct(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto struct_instance_name = MakeLowerCamel(struct_def);
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
auto field_type = TypeName(field);
if (parser_.opts.include_dependence_headers) {
@@ -961,16 +1090,14 @@
field_type = package_reference + "." + TypeName(field);
}
- code += GenIndents(2) + "if " + struct_instance_name + "." +
- field_accessor_name + "(";
+ code += GenIndents(2) + "if " + struct_var + "." + field_method + "(";
// if field is a struct, we need to create an instance for it first.
if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) {
code += field_type + "()";
}
code += ") is not None:";
- code += GenIndents(3) + "self." + field_instance_name + " = " + field_type +
- "T.InitFromObj(" + struct_instance_name + "." +
- field_accessor_name + "(";
+ code += GenIndents(3) + "self." + field_field + " = " + field_type +
+ "T.InitFromObj(" + struct_var + "." + field_method + "(";
// A struct's accessor requires a struct buf instance.
if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) {
code += field_type + "()";
@@ -979,82 +1106,81 @@
}
void GenUnPackForUnion(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
- auto union_name = MakeUpperCamel(*(field.value.type.enum_def));
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const EnumDef &enum_def = *field.value.type.enum_def;
+ auto union_type = namer_.Namespace(enum_def.name);
if (parser_.opts.include_dependence_headers) {
- Namespace *namespaces = field.value.type.enum_def->defined_namespace;
- auto package_reference = namespaces->GetFullyQualifiedName(
- MakeUpperCamel(*(field.value.type.enum_def)));
- union_name = package_reference + "." + union_name;
+ union_type = GenPackageReference(enum_def) + "." + union_type;
}
- code += GenIndents(2) + "self." + field_instance_name + " = " + union_name +
- "Creator(" + "self." + field_instance_name + "Type, " +
- struct_instance_name + "." + field_accessor_name + "())";
+ code += GenIndents(2) + "self." + field_field + " = " + union_type +
+ "Creator(" + "self." + field_field + "Type, " + struct_var + "." +
+ field_method + "())";
}
void GenUnPackForStructVector(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
- code += GenIndents(2) + "if not " + struct_instance_name + "." +
- field_accessor_name + "IsNone():";
- code += GenIndents(3) + "self." + field_instance_name + " = []";
- code += GenIndents(3) + "for i in range(" + struct_instance_name + "." +
- field_accessor_name + "Length()):";
+ code += GenIndents(2) + "if not " + struct_var + "." + field_method +
+ "IsNone():";
+ code += GenIndents(3) + "self." + field_field + " = []";
+ code += GenIndents(3) + "for i in range(" + struct_var + "." +
+ field_method + "Length()):";
- auto field_type_name = TypeName(field);
- auto one_instance = field_type_name + "_";
+ auto field_type = TypeName(field);
+ auto one_instance = field_type + "_";
one_instance[0] = CharToLower(one_instance[0]);
if (parser_.opts.include_dependence_headers) {
auto package_reference = GenPackageReference(field.value.type);
- field_type_name = package_reference + "." + TypeName(field);
+ field_type = package_reference + "." + TypeName(field);
}
- code += GenIndents(4) + "if " + struct_instance_name + "." +
- field_accessor_name + "(i) is None:";
- code += GenIndents(5) + "self." + field_instance_name + ".append(None)";
+ code += GenIndents(4) + "if " + struct_var + "." + field_method +
+ "(i) is None:";
+ code += GenIndents(5) + "self." + field_field + ".append(None)";
code += GenIndents(4) + "else:";
- code += GenIndents(5) + one_instance + " = " + field_type_name +
- "T.InitFromObj(" + struct_instance_name + "." +
- field_accessor_name + "(i))";
- code += GenIndents(5) + "self." + field_instance_name + ".append(" +
- one_instance + ")";
+ code += GenIndents(5) + one_instance + " = " + field_type +
+ "T.InitFromObj(" + struct_var + "." + field_method + "(i))";
+ code +=
+ GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
}
void GenUnpackforScalarVectorHelper(const StructDef &struct_def,
const FieldDef &field,
- std::string *code_ptr, int indents) {
+ std::string *code_ptr,
+ int indents) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
- code += GenIndents(indents) + "self." + field_instance_name + " = []";
- code += GenIndents(indents) + "for i in range(" + struct_instance_name +
- "." + field_accessor_name + "Length()):";
- code += GenIndents(indents + 1) + "self." + field_instance_name +
- ".append(" + struct_instance_name + "." + field_accessor_name +
- "(i))";
+ code += GenIndents(indents) + "self." + field_field + " = []";
+ code += GenIndents(indents) + "for i in range(" + struct_var + "." +
+ field_method + "Length()):";
+ code += GenIndents(indents + 1) + "self." + field_field + ".append(" +
+ struct_var + "." + field_method + "(i))";
}
void GenUnPackForScalarVector(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
- code += GenIndents(2) + "if not " + struct_instance_name + "." +
- field_accessor_name + "IsNone():";
+ code += GenIndents(2) + "if not " + struct_var + "." + field_method +
+ "IsNone():";
// String does not have the AsNumpy method.
if (!(IsScalar(field.value.type.VectorType().base_type))) {
@@ -1067,23 +1193,23 @@
// If numpy exists, use the AsNumpy method to optimize the unpack speed.
code += GenIndents(3) + "else:";
- code += GenIndents(4) + "self." + field_instance_name + " = " +
- struct_instance_name + "." + field_accessor_name + "AsNumpy()";
+ code += GenIndents(4) + "self." + field_field + " = " + struct_var + "." +
+ field_method + "AsNumpy()";
}
void GenUnPackForScalar(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
- code += GenIndents(2) + "self." + field_instance_name + " = " +
- struct_instance_name + "." + field_accessor_name + "()";
+ code += GenIndents(2) + "self." + field_field + " = " + struct_var + "." +
+ field_method + "()";
}
// Generates the UnPack method for the object class.
- void GenUnPack(const StructDef &struct_def, std::string *code_ptr) {
+ void GenUnPack(const StructDef &struct_def, std::string *code_ptr) const {
std::string code;
// Items that needs to be imported. No duplicate modules will be imported.
std::set<std::string> import_list;
@@ -1122,12 +1248,11 @@
// Writes import statements and code into the generated file.
auto &code_base = *code_ptr;
- auto struct_instance_name = MakeLowerCamel(struct_def);
- auto struct_name = MakeUpperCamel(struct_def);
+ const auto struct_var = namer_.Variable(struct_def.name);
GenReceiverForObjectAPI(struct_def, code_ptr);
- code_base += "_UnPack(self, " + struct_instance_name + "):";
- code_base += GenIndents(2) + "if " + struct_instance_name + " is None:";
+ code_base += "_UnPack(self, " + struct_var + "):";
+ code_base += GenIndents(2) + "if " + struct_var + " is None:";
code_base += GenIndents(3) + "return";
// Write the import statements.
@@ -1141,13 +1266,14 @@
code_base += "\n";
}
- void GenPackForStruct(const StructDef &struct_def, std::string *code_ptr) {
+ void GenPackForStruct(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto struct_name = MakeUpperCamel(struct_def);
+ const auto struct_fn = namer_.Function(struct_def.name);
GenReceiverForObjectAPI(struct_def, code_ptr);
code += "Pack(self, builder):";
- code += GenIndents(2) + "return Create" + struct_name + "(builder";
+ code += GenIndents(2) + "return Create" + struct_fn + "(builder";
StructBuilderArgs(struct_def,
/* nameprefix = */ "self.",
@@ -1160,67 +1286,61 @@
void GenPackForStructVectorField(const StructDef &struct_def,
const FieldDef &field,
std::string *code_prefix_ptr,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code_prefix = *code_prefix_ptr;
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto struct_name = NormalizedName(struct_def);
- auto field_accessor_name = MakeUpperCamel(field);
+ const auto field_field = namer_.Field(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
+ const auto field_method = namer_.Method(field.name);
// Creates the field.
- code_prefix +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
+ code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
if (field.value.type.struct_def->fixed) {
- code_prefix += GenIndents(3) + struct_name + "Start" +
- field_accessor_name + "Vector(builder, len(self." +
- field_instance_name + "))";
+ code_prefix += GenIndents(3) + struct_type + "Start" + field_method +
+ "Vector(builder, len(self." + field_field + "))";
code_prefix += GenIndents(3) + "for i in reversed(range(len(self." +
- field_instance_name + "))):";
+ field_field + "))):";
code_prefix +=
- GenIndents(4) + "self." + field_instance_name + "[i].Pack(builder)";
- code_prefix += GenIndents(3) + field_instance_name +
- " = builder.EndVector(len(self." + field_instance_name +
- "))";
+ GenIndents(4) + "self." + field_field + "[i].Pack(builder)";
+ code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
} else {
// If the vector is a struct vector, we need to first build accessor for
// each struct element.
- code_prefix += GenIndents(3) + field_instance_name + "list = []";
+ code_prefix += GenIndents(3) + field_field + "list = []";
code_prefix += GenIndents(3);
- code_prefix += "for i in range(len(self." + field_instance_name + ")):";
- code_prefix += GenIndents(4) + field_instance_name + "list.append(self." +
- field_instance_name + "[i].Pack(builder))";
+ code_prefix += "for i in range(len(self." + field_field + ")):";
+ code_prefix += GenIndents(4) + field_field + "list.append(self." +
+ field_field + "[i].Pack(builder))";
- code_prefix += GenIndents(3) + struct_name + "Start" +
- field_accessor_name + "Vector(builder, len(self." +
- field_instance_name + "))";
+ code_prefix += GenIndents(3) + struct_type + "Start" + field_method +
+ "Vector(builder, len(self." + field_field + "))";
code_prefix += GenIndents(3) + "for i in reversed(range(len(self." +
- field_instance_name + "))):";
+ field_field + "))):";
code_prefix += GenIndents(4) + "builder.PrependUOffsetTRelative" + "(" +
- field_instance_name + "list[i])";
- code_prefix += GenIndents(3) + field_instance_name +
- " = builder.EndVector(len(self." + field_instance_name +
- "))";
+ field_field + "list[i])";
+ code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
}
// Adds the field into the struct.
- code += GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
+ field_field + ")";
}
void GenPackForScalarVectorFieldHelper(const StructDef &struct_def,
const FieldDef &field,
- std::string *code_ptr, int indents) {
+ std::string *code_ptr,
+ int indents) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_name = NormalizedName(struct_def);
- auto vectortype = field.value.type.VectorType();
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
+ const auto vectortype = field.value.type.VectorType();
- code += GenIndents(indents) + struct_name + "Start" + field_accessor_name +
- "Vector(builder, len(self." + field_instance_name + "))";
+ code += GenIndents(indents) + struct_type + "Start" + field_method +
+ "Vector(builder, len(self." + field_field + "))";
code += GenIndents(indents) + "for i in reversed(range(len(self." +
- field_instance_name + "))):";
+ field_field + "))):";
code += GenIndents(indents + 1) + "builder.Prepend";
std::string type_name;
@@ -1245,120 +1365,109 @@
void GenPackForScalarVectorField(const StructDef &struct_def,
const FieldDef &field,
std::string *code_prefix_ptr,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
auto &code_prefix = *code_prefix_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_name = NormalizedName(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
// Adds the field into the struct.
- code += GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
+ field_field + ")";
// Creates the field.
- code_prefix +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
+ code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
// If the vector is a string vector, we need to first build accessor for
// each string element. And this generated code, needs to be
// placed ahead of code_prefix.
auto vectortype = field.value.type.VectorType();
if (IsString(vectortype)) {
- code_prefix += GenIndents(3) + MakeLowerCamel(field) + "list = []";
- code_prefix += GenIndents(3) + "for i in range(len(self." +
- field_instance_name + ")):";
- code_prefix += GenIndents(4) + MakeLowerCamel(field) +
- "list.append(builder.CreateString(self." +
- field_instance_name + "[i]))";
+ code_prefix += GenIndents(3) + field_field + "list = []";
+ code_prefix +=
+ GenIndents(3) + "for i in range(len(self." + field_field + ")):";
+ code_prefix += GenIndents(4) + field_field +
+ "list.append(builder.CreateString(self." + field_field +
+ "[i]))";
GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 3);
- code_prefix += "(" + MakeLowerCamel(field) + "list[i])";
- code_prefix += GenIndents(3) + field_instance_name +
- " = builder.EndVector(len(self." + field_instance_name +
- "))";
+ code_prefix += "(" + field_field + "list[i])";
+ code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
return;
}
code_prefix += GenIndents(3) + "if np is not None and type(self." +
- field_instance_name + ") is np.ndarray:";
- code_prefix += GenIndents(4) + field_instance_name +
- " = builder.CreateNumpyVector(self." + field_instance_name +
- ")";
+ field_field + ") is np.ndarray:";
+ code_prefix += GenIndents(4) + field_field +
+ " = builder.CreateNumpyVector(self." + field_field + ")";
code_prefix += GenIndents(3) + "else:";
GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 4);
- code_prefix += "(self." + field_instance_name + "[i])";
- code_prefix += GenIndents(4) + field_instance_name +
- " = builder.EndVector(len(self." + field_instance_name +
- "))";
+ code_prefix += "(self." + field_field + "[i])";
+ code_prefix += GenIndents(4) + field_field + " = builder.EndVector()";
}
void GenPackForStructField(const StructDef &struct_def, const FieldDef &field,
std::string *code_prefix_ptr,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code_prefix = *code_prefix_ptr;
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
-
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_name = NormalizedName(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
if (field.value.type.struct_def->fixed) {
// Pure struct fields need to be created along with their parent
// structs.
- code +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code += GenIndents(3) + field_instance_name + " = self." +
- field_instance_name + ".Pack(builder)";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + field_field + " = self." + field_field +
+ ".Pack(builder)";
} else {
// Tables need to be created before their parent structs are created.
- code_prefix +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code_prefix += GenIndents(3) + field_instance_name + " = self." +
- field_instance_name + ".Pack(builder)";
- code +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
+ code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
+ code_prefix += GenIndents(3) + field_field + " = self." + field_field +
+ ".Pack(builder)";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
}
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
+ field_field + ")";
}
void GenPackForUnionField(const StructDef &struct_def, const FieldDef &field,
std::string *code_prefix_ptr,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code_prefix = *code_prefix_ptr;
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
-
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_name = NormalizedName(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
// TODO(luwa): TypeT should be moved under the None check as well.
- code_prefix +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code_prefix += GenIndents(3) + field_instance_name + " = self." +
- field_instance_name + ".Pack(builder)";
- code += GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
+ code_prefix += GenIndents(3) + field_field + " = self." + field_field +
+ ".Pack(builder)";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
+ field_field + ")";
}
- void GenPackForTable(const StructDef &struct_def, std::string *code_ptr) {
+ void GenPackForTable(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code_base = *code_ptr;
std::string code, code_prefix;
- auto struct_instance_name = MakeLowerCamel(struct_def);
- auto struct_name = NormalizedName(struct_def);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const auto struct_type = namer_.Type(struct_def.name);
GenReceiverForObjectAPI(struct_def, code_ptr);
code_base += "Pack(self, builder):";
- code += GenIndents(2) + struct_name + "Start(builder)";
+ code += GenIndents(2) + struct_type + "Start(builder)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
- auto field_accessor_name = MakeUpperCamel(field);
- auto field_instance_name = MakeLowerCamel(field);
+ const auto field_method = namer_.Method(field.name);
+ const auto field_field = namer_.Field(field.name);
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
@@ -1383,37 +1492,34 @@
break;
}
case BASE_TYPE_STRING: {
- code_prefix += GenIndents(2) + "if self." + field_instance_name +
- " is not None:";
- code_prefix += GenIndents(3) + field_instance_name +
- " = builder.CreateString(self." + field_instance_name +
- ")";
- code += GenIndents(2) + "if self." + field_instance_name +
- " is not None:";
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code_prefix +=
+ GenIndents(2) + "if self." + field_field + " is not None:";
+ code_prefix += GenIndents(3) + field_field +
+ " = builder.CreateString(self." + field_field + ")";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + struct_type + "Add" + field_method +
+ "(builder, " + field_field + ")";
break;
}
default:
// Generates code for scalar values. If the value equals to the
// default value, builder will automatically ignore it. So we don't
// need to check the value ahead.
- code += GenIndents(2) + struct_name + "Add" + field_accessor_name +
- "(builder, self." + field_instance_name + ")";
+ code += GenIndents(2) + struct_type + "Add" + field_method +
+ "(builder, self." + field_field + ")";
break;
}
}
- code += GenIndents(2) + struct_instance_name + " = " + struct_name +
- "End(builder)";
- code += GenIndents(2) + "return " + struct_instance_name;
+ code += GenIndents(2) + struct_var + " = " + struct_type + "End(builder)";
+ code += GenIndents(2) + "return " + struct_var;
code_base += code_prefix + code;
code_base += "\n";
}
void GenStructForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
if (struct_def.generated) return;
std::set<std::string> import_list;
@@ -1447,14 +1553,14 @@
}
void GenUnionCreatorForStruct(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto union_name = NormalizedName(enum_def);
- auto field_name = NormalizedName(ev);
- auto field_type = GenTypeGet(ev.union_type) + "T";
+ const auto union_type = namer_.Type(enum_def.name);
+ const auto variant = namer_.Variant(ev.name);
+ auto field_type = namer_.ObjectType(GenTypeGet(ev.union_type));
- code += GenIndents(1) + "if unionType == " + union_name + "()." +
- field_name + ":";
+ code += GenIndents(1) + "if unionType == " + union_type + "()." +
+ variant + ":";
if (parser_.opts.include_dependence_headers) {
auto package_reference = GenPackageReference(ev.union_type);
code += GenIndents(2) + "import " + package_reference;
@@ -1465,25 +1571,27 @@
}
void GenUnionCreatorForString(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto union_name = NormalizedName(enum_def);
- auto field_name = NormalizedName(ev);
+ const auto union_type = namer_.Type(enum_def.name);
+ const auto variant = namer_.Variant(ev.name);
- code += GenIndents(1) + "if unionType == " + union_name + "()." +
- field_name + ":";
+ code += GenIndents(1) + "if unionType == " + union_type + "()." +
+ variant + ":";
code += GenIndents(2) + "tab = Table(table.Bytes, table.Pos)";
code += GenIndents(2) + "union = tab.String(table.Pos)";
code += GenIndents(2) + "return union";
}
// Creates an union object based on union type.
- void GenUnionCreator(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenUnionCreator(const EnumDef &enum_def, std::string *code_ptr) const {
+ if (enum_def.generated) return;
+
auto &code = *code_ptr;
- auto union_name = MakeUpperCamel(enum_def);
+ const auto enum_fn = namer_.Function(enum_def.name);
code += "\n";
- code += "def " + union_name + "Creator(unionType, table):";
+ code += "def " + enum_fn + "Creator(unionType, table):";
code += GenIndents(1) + "from flatbuffers.table import Table";
code += GenIndents(1) + "if not isinstance(table, Table):";
code += GenIndents(2) + "return None";
@@ -1506,39 +1614,38 @@
}
// Generate enum declarations.
- void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenEnum(const EnumDef &enum_def, std::string *code_ptr) const {
if (enum_def.generated) return;
GenComment(enum_def.doc_comment, code_ptr, &def_comment);
- BeginEnum(NormalizedName(enum_def), code_ptr);
+ BeginEnum(enum_def, code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, &def_comment, Indent.c_str());
EnumMember(enum_def, ev, code_ptr);
}
- EndEnum(code_ptr);
}
// Returns the function name that is able to read a value of the given type.
- std::string GenGetter(const Type &type) {
+ std::string GenGetter(const Type &type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: return "self._tab.String(";
case BASE_TYPE_UNION: return "self._tab.Union(";
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
default:
return "self._tab.Get(flatbuffers.number_types." +
- MakeCamel(GenTypeGet(type)) + "Flags, ";
+ namer_.Method(GenTypeGet(type)) + "Flags, ";
}
}
// Returns the method name for use with add/put calls.
- std::string GenMethod(const FieldDef &field) {
+ std::string GenMethod(const FieldDef &field) const {
return (IsScalar(field.value.type.base_type) || IsArray(field.value.type))
- ? MakeCamel(GenTypeBasic(field.value.type))
+ ? namer_.Method(GenTypeBasic(field.value.type))
: (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
}
- std::string GenTypeBasic(const Type &type) {
+ std::string GenTypeBasic(const Type &type) const {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -1552,7 +1659,7 @@
: type.base_type];
}
- std::string GenTypePointer(const Type &type) {
+ std::string GenTypePointer(const Type &type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: return "string";
case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
@@ -1563,16 +1670,17 @@
}
}
- std::string GenTypeGet(const Type &type) {
+ std::string GenTypeGet(const Type &type) const {
return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
- std::string TypeName(const FieldDef &field) {
+ std::string TypeName(const FieldDef &field) const {
return GenTypeGet(field.value.type);
}
// Create a struct with a builder and the struct's arguments.
- void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStructBuilder(const StructDef &struct_def,
+ std::string *code_ptr) const {
BeginBuilderArgs(struct_def, code_ptr);
StructBuilderArgs(struct_def,
/* nameprefix = */ "",
@@ -1586,13 +1694,21 @@
}
bool generate() {
- if (!generateEnums()) return false;
- if (!generateStructs()) return false;
+ std::string one_file_code;
+ if (!generateEnums(&one_file_code)) return false;
+ if (!generateStructs(&one_file_code)) return false;
+
+ if (parser_.opts.one_file) {
+ // Legacy file format uses keep casing.
+ return SaveType(file_name_ + "_generated.py", *parser_.current_namespace_,
+ one_file_code, true);
+ }
+
return true;
}
private:
- bool generateEnums() {
+ bool generateEnums(std::string *one_file_code) const {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
@@ -1601,12 +1717,19 @@
if (parser_.opts.generate_object_based_api & enum_def.is_union) {
GenUnionCreator(enum_def, &enumcode);
}
- if (!SaveType(enum_def, enumcode, false)) return false;
+
+ if (parser_.opts.one_file && !enumcode.empty()) {
+ *one_file_code += enumcode + "\n\n";
+ } else {
+ if (!SaveType(namer_.File(enum_def.name, SkipFile::Suffix),
+ *enum_def.defined_namespace, enumcode, false))
+ return false;
+ }
}
return true;
}
- bool generateStructs() {
+ bool generateStructs(std::string *one_file_code) const {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
@@ -1615,14 +1738,21 @@
if (parser_.opts.generate_object_based_api) {
GenStructForObjectAPI(struct_def, &declcode);
}
- if (!SaveType(struct_def, declcode, true)) return false;
+
+ if (parser_.opts.one_file && !declcode.empty()) {
+ *one_file_code += declcode + "\n\n";
+ } else {
+ if (!SaveType(namer_.File(struct_def.name, SkipFile::Suffix),
+ *struct_def.defined_namespace, declcode, true))
+ return false;
+ }
}
return true;
}
// Begin by declaring namespace and imports.
void BeginFile(const std::string &name_space_name, const bool needs_imports,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code = code + "# " + FlatBuffersGeneratedWarning() + "\n\n";
code += "# namespace: " + name_space_name + "\n\n";
@@ -1634,30 +1764,32 @@
}
// Save out the generated code for a Python Table type.
- bool SaveType(const Definition &def, const std::string &classcode,
- bool needs_imports) {
+ bool SaveType(const std::string &defname, const Namespace &ns,
+ const std::string &classcode, bool needs_imports) const {
if (!classcode.length()) return true;
- std::string namespace_dir = path_;
- auto &namespaces = def.defined_namespace->components;
- for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
- if (it != namespaces.begin()) namespace_dir += kPathSeparator;
- namespace_dir += *it;
- std::string init_py_filename = namespace_dir + "/__init__.py";
- SaveFile(init_py_filename.c_str(), "", false);
+ std::string code = "";
+ BeginFile(LastNamespacePart(ns), needs_imports, &code);
+ code += classcode;
+
+ const std::string directories =
+ parser_.opts.one_file ? path_ : namer_.Directories(ns.components);
+ EnsureDirExists(directories);
+
+ for (size_t i = path_.size() + 1; i != std::string::npos;
+ i = directories.find(kPathSeparator, i + 1)) {
+ const std::string init_py =
+ directories.substr(0, i) + kPathSeparator + "__init__.py";
+ SaveFile(init_py.c_str(), "", false);
}
- std::string code = "";
- BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code);
- code += classcode;
- std::string filename =
- NamespaceDir(*def.defined_namespace) + NormalizedName(def) + ".py";
+ const std::string filename = directories + defname;
return SaveFile(filename.c_str(), code, false);
}
private:
- std::unordered_set<std::string> keywords_;
const SimpleFloatConstantGenerator float_const_gen_;
+ const Namer namer_;
};
} // namespace python