blob: 8426b6e0930b7b4b45e7673dbbf1c9c6d32e3ed3 [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001/*
2 * Copyright 2014 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// independent from idl_parser, since this code is not needed for most clients
18
Austin Schuh272c6132020-11-14 16:37:52 -080019#include <cctype>
20#include <set>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070021#include <string>
Austin Schuh272c6132020-11-14 16:37:52 -080022#include <unordered_set>
23#include <vector>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070024
25#include "flatbuffers/code_generators.h"
26#include "flatbuffers/flatbuffers.h"
27#include "flatbuffers/idl.h"
28#include "flatbuffers/util.h"
James Kuszmaul8e62b022022-03-22 09:33:25 -070029#include "namer.h"
Austin Schuhe89fa2d2019-08-14 20:24:23 -070030
Austin Schuhe89fa2d2019-08-14 20:24:23 -070031namespace flatbuffers {
32namespace python {
33
James Kuszmaul8e62b022022-03-22 09:33:25 -070034std::set<std::string> PythonKeywords() {
35 return { "False", "None", "True", "and", "as", "assert",
36 "break", "class", "continue", "def", "del", "elif",
37 "else", "except", "finally", "for", "from", "global",
38 "if", "import", "in", "is", "lambda", "nonlocal",
39 "not", "or", "pass", "raise", "return", "try",
40 "while", "with", "yield" };
41}
42
43Namer::Config PythonDefaultConfig() {
44 return { /*types=*/Case::kKeep,
45 /*constants=*/Case::kScreamingSnake,
46 /*methods=*/Case::kUpperCamel,
47 /*functions=*/Case::kUpperCamel,
48 /*fields=*/Case::kLowerCamel,
49 /*variable=*/Case::kLowerCamel,
50 /*variants=*/Case::kKeep,
51 /*enum_variant_seperator=*/".",
52 /*namespaces=*/Case::kKeep, // Packages in python.
53 /*namespace_seperator=*/".",
54 /*object_prefix=*/"",
55 /*object_suffix=*/"T",
56 /*keyword_prefix=*/"",
57 /*keyword_suffix=*/"_",
58 /*filenames=*/Case::kKeep,
59 /*directories=*/Case::kKeep,
60 /*output_path=*/"",
61 /*filename_suffix=*/"",
62 /*filename_extension=*/".py" };
63}
64
Austin Schuhe89fa2d2019-08-14 20:24:23 -070065// Hardcode spaces per indentation.
66const CommentConfig def_comment = { nullptr, "#", nullptr };
67const std::string Indent = " ";
68
69class PythonGenerator : public BaseGenerator {
70 public:
71 PythonGenerator(const Parser &parser, const std::string &path,
72 const std::string &file_name)
73 : BaseGenerator(parser, path, file_name, "" /* not used */,
Austin Schuh272c6132020-11-14 16:37:52 -080074 "" /* not used */, "py"),
James Kuszmaul8e62b022022-03-22 09:33:25 -070075 float_const_gen_("float('nan')", "float('inf')", "float('-inf')"),
76 namer_({ PythonDefaultConfig().WithFlagOptions(parser.opts, path),
77 PythonKeywords() }) {}
Austin Schuhe89fa2d2019-08-14 20:24:23 -070078
79 // Most field accessors need to retrieve and test the field offset first,
80 // this is the prefix code for that.
James Kuszmaul8e62b022022-03-22 09:33:25 -070081 std::string OffsetPrefix(const FieldDef &field) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070082 return "\n" + Indent + Indent +
Austin Schuh272c6132020-11-14 16:37:52 -080083 "o = flatbuffers.number_types.UOffsetTFlags.py_type" +
84 "(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" +
85 Indent + Indent + "if o != 0:\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -070086 }
87
88 // Begin a class declaration.
James Kuszmaul8e62b022022-03-22 09:33:25 -070089 void BeginClass(const StructDef &struct_def, std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -080090 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -070091 code += "class " + namer_.Type(struct_def.name) + "(object):\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -070092 code += Indent + "__slots__ = ['_tab']";
93 code += "\n\n";
94 }
95
96 // Begin enum code with a class declaration.
James Kuszmaul8e62b022022-03-22 09:33:25 -070097 void BeginEnum(const EnumDef &enum_def, std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -080098 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -070099 code += "class " + namer_.Type(enum_def.name) + "(object):\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800100 }
101
102 // Starts a new line and then indents.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700103 std::string GenIndents(int num) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800104 return "\n" + std::string(num * Indent.length(), ' ');
105 }
106
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700107 // A single enum member.
108 void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700109 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800110 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700111 code += Indent;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700112 code += namer_.Variant(ev.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700113 code += " = ";
114 code += enum_def.ToString(ev) + "\n";
115 }
116
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700117 // Initialize a new struct or table from existing data.
118 void NewRootTypeFromBuffer(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700119 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800120 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700121 const std::string struct_type = namer_.Type(struct_def.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700122
123 code += Indent + "@classmethod\n";
124 code += Indent + "def GetRootAs";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700125 code += "(cls, buf, offset=0):";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700126 code += "\n";
127 code += Indent + Indent;
128 code += "n = flatbuffers.encode.Get";
129 code += "(flatbuffers.packer.uoffset, buf, offset)\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700130 code += Indent + Indent + "x = " + struct_type + "()\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700131 code += Indent + Indent + "x.Init(buf, n + offset)\n";
132 code += Indent + Indent + "return x\n";
133 code += "\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700134
135 // Add an alias with the old name
136 code += Indent + "@classmethod\n";
137 code += Indent + "def GetRootAs" + struct_type + "(cls, buf, offset=0):\n";
138 code +=
139 Indent + Indent +
140 "\"\"\"This method is deprecated. Please switch to GetRootAs.\"\"\"\n";
141 code += Indent + Indent + "return cls.GetRootAs(buf, offset)\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700142 }
143
144 // Initialize an existing object with other data, to avoid an allocation.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700145 void InitializeExisting(const StructDef &struct_def,
146 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800147 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700148
149 GenReceiver(struct_def, code_ptr);
150 code += "Init(self, buf, pos):\n";
151 code += Indent + Indent + "self._tab = flatbuffers.table.Table(buf, pos)\n";
152 code += "\n";
153 }
154
155 // Get the length of a vector.
156 void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700157 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800158 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700159
160 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700161 code += namer_.Method(field.name) + "Length(self";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700162 code += "):" + OffsetPrefix(field);
163 code += Indent + Indent + Indent + "return self._tab.VectorLen(o)\n";
164 code += Indent + Indent + "return 0\n\n";
165 }
166
Austin Schuh272c6132020-11-14 16:37:52 -0800167 // Determines whether a vector is none or not.
168 void GetVectorIsNone(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700169 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800170 auto &code = *code_ptr;
171
172 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700173 code += namer_.Method(field.name) + "IsNone(self";
Austin Schuh272c6132020-11-14 16:37:52 -0800174 code += "):";
175 code += GenIndents(2) +
176 "o = flatbuffers.number_types.UOffsetTFlags.py_type" +
177 "(self._tab.Offset(" + NumToString(field.value.offset) + "))";
178 code += GenIndents(2) + "return o == 0";
179 code += "\n\n";
180 }
181
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700182 // Get the value of a struct's scalar.
183 void GetScalarFieldOfStruct(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700184 const FieldDef &field,
185 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800186 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700187 std::string getter = GenGetter(field.value.type);
188 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700189 code += namer_.Method(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700190 code += "(self): return " + getter;
191 code += "self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(";
192 code += NumToString(field.value.offset) + "))\n";
193 }
194
195 // Get the value of a table's scalar.
Austin Schuh272c6132020-11-14 16:37:52 -0800196 void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700197 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800198 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700199 std::string getter = GenGetter(field.value.type);
200 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700201 code += namer_.Method(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700202 code += "(self):";
203 code += OffsetPrefix(field);
204 getter += "o + self._tab.Pos)";
205 auto is_bool = IsBool(field.value.type.base_type);
Austin Schuh272c6132020-11-14 16:37:52 -0800206 if (is_bool) { getter = "bool(" + getter + ")"; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700207 code += Indent + Indent + Indent + "return " + getter + "\n";
208 std::string default_value;
209 if (is_bool) {
210 default_value = field.value.constant == "0" ? "False" : "True";
211 } else {
212 default_value = IsFloat(field.value.type.base_type)
213 ? float_const_gen_.GenFloatConstant(field)
214 : field.value.constant;
215 }
216 code += Indent + Indent + "return " + default_value + "\n\n";
217 }
218
219 // Get a struct by initializing an existing struct.
220 // Specific to Struct.
221 void GetStructFieldOfStruct(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700222 const FieldDef &field,
223 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800224 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700225 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700226 code += namer_.Method(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700227 code += "(self, obj):\n";
228 code += Indent + Indent + "obj.Init(self._tab.Bytes, self._tab.Pos + ";
229 code += NumToString(field.value.offset) + ")";
230 code += "\n" + Indent + Indent + "return obj\n\n";
231 }
232
233 // Get the value of a fixed size array.
234 void GetArrayOfStruct(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700235 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800236 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700237 const auto vec_type = field.value.type.VectorType();
238 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700239 code += namer_.Method(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700240 if (IsStruct(vec_type)) {
241 code += "(self, obj, i):\n";
242 code += Indent + Indent + "obj.Init(self._tab.Bytes, self._tab.Pos + ";
243 code += NumToString(field.value.offset) + " + i * ";
244 code += NumToString(InlineSize(vec_type));
245 code += ")\n" + Indent + Indent + "return obj\n\n";
246 } else {
247 auto getter = GenGetter(vec_type);
248 code += "(self): return [" + getter;
249 code += "self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(";
250 code += NumToString(field.value.offset) + " + i * ";
251 code += NumToString(InlineSize(vec_type));
252 code += ")) for i in range(";
253 code += NumToString(field.value.type.fixed_length) + ")]\n";
254 }
255 }
256
257 // Get a struct by initializing an existing struct.
258 // Specific to Table.
Austin Schuh272c6132020-11-14 16:37:52 -0800259 void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700260 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800261 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700262 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700263 code += namer_.Method(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700264 code += "(self):";
265 code += OffsetPrefix(field);
266 if (field.value.type.struct_def->fixed) {
267 code += Indent + Indent + Indent + "x = o + self._tab.Pos\n";
268 } else {
269 code += Indent + Indent + Indent;
270 code += "x = self._tab.Indirect(o + self._tab.Pos)\n";
271 }
Austin Schuh272c6132020-11-14 16:37:52 -0800272 if (parser_.opts.include_dependence_headers) {
273 code += Indent + Indent + Indent;
274 code += "from " + GenPackageReference(field.value.type) + " import " +
275 TypeName(field) + "\n";
276 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700277 code += Indent + Indent + Indent + "obj = " + TypeName(field) + "()\n";
278 code += Indent + Indent + Indent + "obj.Init(self._tab.Bytes, x)\n";
279 code += Indent + Indent + Indent + "return obj\n";
280 code += Indent + Indent + "return None\n\n";
281 }
282
283 // Get the value of a string.
284 void GetStringField(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700285 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800286 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700287 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700288 code += namer_.Method(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700289 code += "(self):";
290 code += OffsetPrefix(field);
291 code += Indent + Indent + Indent + "return " + GenGetter(field.value.type);
292 code += "o + self._tab.Pos)\n";
293 code += Indent + Indent + "return None\n\n";
294 }
295
296 // Get the value of a union from an object.
297 void GetUnionField(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700298 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800299 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700300 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700301 code += namer_.Method(field.name) + "(self):";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700302 code += OffsetPrefix(field);
303
304 // TODO(rw): this works and is not the good way to it:
305 bool is_native_table = TypeName(field) == "*flatbuffers.Table";
306 if (is_native_table) {
Austin Schuh272c6132020-11-14 16:37:52 -0800307 code +=
308 Indent + Indent + Indent + "from flatbuffers.table import Table\n";
309 } else if (parser_.opts.include_dependence_headers) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700310 code += Indent + Indent + Indent;
Austin Schuh272c6132020-11-14 16:37:52 -0800311 code += "from " + GenPackageReference(field.value.type) + " import " +
312 TypeName(field) + "\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700313 }
314 code += Indent + Indent + Indent + "obj = Table(bytearray(), 0)\n";
315 code += Indent + Indent + Indent + GenGetter(field.value.type);
316 code += "obj, o)\n" + Indent + Indent + Indent + "return obj\n";
317 code += Indent + Indent + "return None\n\n";
318 }
319
Austin Schuh272c6132020-11-14 16:37:52 -0800320 // Generate the package reference when importing a struct or enum from its
321 // module.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700322 std::string GenPackageReference(const Type &type) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800323 if (type.struct_def) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700324 return GenPackageReference(*type.struct_def);
Austin Schuh272c6132020-11-14 16:37:52 -0800325 } else if (type.enum_def) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700326 return GenPackageReference(*type.enum_def);
Austin Schuh272c6132020-11-14 16:37:52 -0800327 } else {
328 return "." + GenTypeGet(type);
329 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700330 }
331 std::string GenPackageReference(const EnumDef &enum_def) const {
332 return namer_.NamespacedType(enum_def.defined_namespace->components,
333 enum_def.name);
334 }
335 std::string GenPackageReference(const StructDef &struct_def) const {
336 return namer_.NamespacedType(struct_def.defined_namespace->components,
337 struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -0800338 }
339
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700340 // Get the value of a vector's struct member.
341 void GetMemberOfVectorOfStruct(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700342 const FieldDef &field,
343 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800344 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700345 auto vectortype = field.value.type.VectorType();
346
347 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700348 code += namer_.Method(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700349 code += "(self, j):" + OffsetPrefix(field);
350 code += Indent + Indent + Indent + "x = self._tab.Vector(o)\n";
351 code += Indent + Indent + Indent;
352 code += "x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * ";
353 code += NumToString(InlineSize(vectortype)) + "\n";
354 if (!(vectortype.struct_def->fixed)) {
355 code += Indent + Indent + Indent + "x = self._tab.Indirect(x)\n";
356 }
Austin Schuh272c6132020-11-14 16:37:52 -0800357 if (parser_.opts.include_dependence_headers) {
358 code += Indent + Indent + Indent;
359 code += "from " + GenPackageReference(field.value.type) + " import " +
360 TypeName(field) + "\n";
361 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700362 code += Indent + Indent + Indent + "obj = " + TypeName(field) + "()\n";
363 code += Indent + Indent + Indent + "obj.Init(self._tab.Bytes, x)\n";
364 code += Indent + Indent + Indent + "return obj\n";
365 code += Indent + Indent + "return None\n\n";
366 }
367
368 // Get the value of a vector's non-struct member. Uses a named return
369 // argument to conveniently set the zero value for the result.
370 void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
371 const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700372 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800373 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700374 auto vectortype = field.value.type.VectorType();
375
376 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700377 code += namer_.Method(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700378 code += "(self, j):";
379 code += OffsetPrefix(field);
380 code += Indent + Indent + Indent + "a = self._tab.Vector(o)\n";
381 code += Indent + Indent + Indent;
382 code += "return " + GenGetter(field.value.type);
383 code += "a + flatbuffers.number_types.UOffsetTFlags.py_type(j * ";
384 code += NumToString(InlineSize(vectortype)) + "))\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800385 if (IsString(vectortype)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700386 code += Indent + Indent + "return \"\"\n";
387 } else {
388 code += Indent + Indent + "return 0\n";
389 }
390 code += "\n";
391 }
392
393 // Returns a non-struct vector as a numpy array. Much faster
394 // than iterating over the vector element by element.
395 void GetVectorOfNonStructAsNumpy(const StructDef &struct_def,
396 const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700397 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800398 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700399 auto vectortype = field.value.type.VectorType();
400
401 // Currently, we only support accessing as numpy array if
402 // the vector type is a scalar.
403 if (!(IsScalar(vectortype.base_type))) { return; }
404
405 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700406 code += namer_.Method(field.name) + "AsNumpy(self):";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700407 code += OffsetPrefix(field);
408
409 code += Indent + Indent + Indent;
410 code += "return ";
411 code += "self._tab.GetVectorAsNumpy(flatbuffers.number_types.";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700412 code += namer_.Method(GenTypeGet(field.value.type));
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700413 code += "Flags, o)\n";
414
Austin Schuh272c6132020-11-14 16:37:52 -0800415 if (IsString(vectortype)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700416 code += Indent + Indent + "return \"\"\n";
417 } else {
418 code += Indent + Indent + "return 0\n";
419 }
420 code += "\n";
421 }
422
James Kuszmaul8e62b022022-03-22 09:33:25 -0700423 std::string NestedFlatbufferType(std::string unqualified_name) const {
424 StructDef* nested_root = parser_.LookupStruct(unqualified_name);
425 std::string qualified_name;
426 if (nested_root == nullptr) {
427 qualified_name = namer_.NamespacedType(
428 parser_.current_namespace_->components, unqualified_name);
429 // Double check qualified name just to be sure it exists.
430 nested_root = parser_.LookupStruct(qualified_name);
431 }
432 FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
433 return qualified_name;
434 }
435
436 // Returns a nested flatbuffer as itself.
437 void GetVectorAsNestedFlatbuffer(const StructDef &struct_def,
438 const FieldDef &field,
439 std::string *code_ptr) const {
440 auto nested = field.attributes.Lookup("nested_flatbuffer");
441 if (!nested) { return; } // There is no nested flatbuffer.
442
443 const std::string unqualified_name = nested->constant;
444 const std::string qualified_name = NestedFlatbufferType(unqualified_name);
445
446 auto &code = *code_ptr;
447 GenReceiver(struct_def, code_ptr);
448 code += namer_.Method(field.name) + "NestedRoot(self):";
449
450 code += OffsetPrefix(field);
451
452 code += Indent + Indent + Indent;
453 code += "from " + qualified_name + " import " + unqualified_name + "\n";
454 code += Indent + Indent + Indent + "return " + unqualified_name;
455 code += ".GetRootAs" + unqualified_name;
456 code += "(self._tab.Bytes, self._tab.Vector(o))\n";
457 code += Indent + Indent + "return 0\n";
458 code += "\n";
459 }
460
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700461 // Begin the creator function signature.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700462 void BeginBuilderArgs(const StructDef &struct_def,
463 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800464 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700465
466 code += "\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700467 code += "def Create" + namer_.Type(struct_def.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700468 code += "(builder";
469 }
470
471 // Recursively generate arguments for a constructor, to deal with nested
472 // structs.
473 void StructBuilderArgs(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800474 const std::string nameprefix,
475 const std::string namesuffix, bool has_field_name,
476 const std::string fieldname_suffix,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700477 std::string *code_ptr) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700478 for (auto it = struct_def.fields.vec.begin();
Austin Schuh272c6132020-11-14 16:37:52 -0800479 it != struct_def.fields.vec.end(); ++it) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700480 auto &field = **it;
481 const auto &field_type = field.value.type;
482 const auto &type =
483 IsArray(field_type) ? field_type.VectorType() : field_type;
484 if (IsStruct(type)) {
485 // Generate arguments for a struct inside a struct. To ensure names
486 // don't clash, and to make it obvious these arguments are constructing
487 // a nested struct, prefix the name with the field name.
Austin Schuh272c6132020-11-14 16:37:52 -0800488 auto subprefix = nameprefix;
489 if (has_field_name) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700490 subprefix += namer_.Field(field.name) + fieldname_suffix;
Austin Schuh272c6132020-11-14 16:37:52 -0800491 }
492 StructBuilderArgs(*field.value.type.struct_def, subprefix, namesuffix,
493 has_field_name, fieldname_suffix, code_ptr);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700494 } else {
Austin Schuh272c6132020-11-14 16:37:52 -0800495 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700496 code += std::string(", ") + nameprefix;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700497 if (has_field_name) { code += namer_.Field(field.name); }
Austin Schuh272c6132020-11-14 16:37:52 -0800498 code += namesuffix;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700499 }
500 }
501 }
502
503 // End the creator function signature.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700504 void EndBuilderArgs(std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800505 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700506 code += "):\n";
507 }
508
509 // Recursively generate struct construction statements and instert manual
510 // padding.
511 void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
512 std::string *code_ptr, size_t index = 0,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700513 bool in_array = false) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800514 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700515 std::string indent(index * 4, ' ');
516 code +=
517 indent + " builder.Prep(" + NumToString(struct_def.minalign) + ", ";
518 code += NumToString(struct_def.bytesize) + ")\n";
519 for (auto it = struct_def.fields.vec.rbegin();
Austin Schuh272c6132020-11-14 16:37:52 -0800520 it != struct_def.fields.vec.rend(); ++it) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700521 auto &field = **it;
522 const auto &field_type = field.value.type;
523 const auto &type =
524 IsArray(field_type) ? field_type.VectorType() : field_type;
525 if (field.padding)
526 code +=
527 indent + " builder.Pad(" + NumToString(field.padding) + ")\n";
528 if (IsStruct(field_type)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700529 StructBuilderBody(
530 *field_type.struct_def,
531 (nameprefix + (namer_.Field(field.name) + "_")).c_str(), code_ptr,
532 index, in_array);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700533 } else {
534 const auto index_var = "_idx" + NumToString(index);
535 if (IsArray(field_type)) {
536 code += indent + " for " + index_var + " in range(";
537 code += NumToString(field_type.fixed_length);
538 code += " , 0, -1):\n";
539 in_array = true;
540 }
541 if (IsStruct(type)) {
542 StructBuilderBody(
543 *field_type.struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700544 (nameprefix + (namer_.Field(field.name) + "_")).c_str(), code_ptr,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700545 index + 1, in_array);
546 } else {
547 code += IsArray(field_type) ? " " : "";
548 code += indent + " builder.Prepend" + GenMethod(field) + "(";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700549 code += nameprefix + namer_.Variable(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700550 size_t array_cnt = index + (IsArray(field_type) ? 1 : 0);
551 for (size_t i = 0; in_array && i < array_cnt; i++) {
552 code += "[_idx" + NumToString(i) + "-1]";
553 }
554 code += ")\n";
555 }
556 }
557 }
558 }
559
James Kuszmaul8e62b022022-03-22 09:33:25 -0700560 void EndBuilderBody(std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800561 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700562 code += " return builder.Offset()\n";
563 }
564
565 // Get the value of a table's starting offset.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700566 void GetStartOfTable(const StructDef &struct_def,
567 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800568 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700569 const auto struct_type = namer_.Type(struct_def.name);
570 // Generate method with struct name.
571 code += "def " + struct_type + "Start(builder): ";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700572 code += "builder.StartObject(";
573 code += NumToString(struct_def.fields.vec.size());
574 code += ")\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700575
576 if (!parser_.opts.one_file) {
577 // Generate method without struct name.
578 code += "def Start(builder):\n";
579 code += Indent + "return " + struct_type + "Start(builder)\n";
580 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700581 }
582
583 // Set the value of a table's field.
Austin Schuh272c6132020-11-14 16:37:52 -0800584 void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700585 const size_t offset, std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800586 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700587 const std::string field_var = namer_.Variable(field.name);
588 const std::string field_method = namer_.Method(field.name);
589
590 // Generate method with struct name.
591 code += "def " + namer_.Type(struct_def.name) + "Add" + field_method;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700592 code += "(builder, ";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700593 code += field_var;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700594 code += "): ";
595 code += "builder.Prepend";
596 code += GenMethod(field) + "Slot(";
597 code += NumToString(offset) + ", ";
598 if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
599 code += "flatbuffers.number_types.UOffsetTFlags.py_type";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700600 code += "(" + field_var + ")";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700601 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700602 code += field_var;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700603 }
604 code += ", ";
605 code += IsFloat(field.value.type.base_type)
606 ? float_const_gen_.GenFloatConstant(field)
607 : field.value.constant;
608 code += ")\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700609
610 if (!parser_.opts.one_file) {
611 // Generate method without struct name.
612 code += "def Add" + field_method + "(builder, " + field_var + "):\n";
613 code += Indent + "return " + namer_.Type(struct_def.name) + "Add" +
614 field_method;
615 code += "(builder, ";
616 code += field_var;
617 code += ")\n";
618 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700619 }
620
621 // Set the value of one of the members of a table's vector.
Austin Schuh272c6132020-11-14 16:37:52 -0800622 void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700623 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800624 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700625 const std::string struct_type = namer_.Type(struct_def.name);
626 const std::string field_method = namer_.Method(field.name);
627
628 // Generate method with struct name.
629 code += "def " + struct_type + "Start" + field_method;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700630 code += "Vector(builder, numElems): return builder.StartVector(";
631 auto vector_type = field.value.type.VectorType();
632 auto alignment = InlineAlignment(vector_type);
633 auto elem_size = InlineSize(vector_type);
634 code += NumToString(elem_size);
635 code += ", numElems, " + NumToString(alignment);
636 code += ")\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700637
638 if (!parser_.opts.one_file) {
639 // Generate method without struct name.
640 code += "def Start" + field_method + "Vector(builder, numElems):\n";
641 code += Indent + "return " + struct_type + "Start";
642 code += field_method + "Vector(builder, numElems)\n";
643 }
644 }
645
646 // Set the value of one of the members of a table's vector and fills in the
647 // elements from a bytearray. This is for simplifying the use of nested
648 // flatbuffers.
649 void BuildVectorOfTableFromBytes(const StructDef &struct_def,
650 const FieldDef &field,
651 std::string *code_ptr) const {
652 auto nested = field.attributes.Lookup("nested_flatbuffer");
653 if (!nested) { return; } // There is no nested flatbuffer.
654
655 auto &code = *code_ptr;
656 const std::string field_method = namer_.Method(field.name);
657 const std::string struct_type = namer_.Type(struct_def.name);
658
659 // Generate method with struct and field name.
660 code += "def " + struct_type + "Make" + field_method;
661 code += "VectorFromBytes(builder, bytes):\n";
662 code += Indent + "builder.StartVector(";
663 auto vector_type = field.value.type.VectorType();
664 auto alignment = InlineAlignment(vector_type);
665 auto elem_size = InlineSize(vector_type);
666 code += NumToString(elem_size);
667 code += ", len(bytes), " + NumToString(alignment);
668 code += ")\n";
669 code += Indent + "builder.head = builder.head - len(bytes)\n";
670 code += Indent + "builder.Bytes[builder.head : builder.head + len(bytes)]";
671 code += " = bytes\n";
672 code += Indent + "return builder.EndVector()\n";
673
674 if (!parser_.opts.one_file) {
675 // Generate method without struct and field name.
676 code += "def Make" + field_method + "VectorFromBytes(builder, bytes):\n";
677 code += Indent + "return " + struct_type + "Make" + field_method +
678 "VectorFromBytes(builder, bytes)\n";
679 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700680 }
681
682 // Get the offset of the end of a table.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700683 void GetEndOffsetOnTable(const StructDef &struct_def,
684 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800685 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700686
687 // Generate method with struct name.
688 code += "def " + namer_.Type(struct_def.name) + "End";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700689 code += "(builder): ";
690 code += "return builder.EndObject()\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700691
692 if (!parser_.opts.one_file) {
693 // Generate method without struct name.
694 code += "def End(builder):\n";
695 code +=
696 Indent + "return " + namer_.Type(struct_def.name) + "End(builder)";
697 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700698 }
699
700 // Generate the receiver for function signatures.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700701 void GenReceiver(const StructDef &struct_def, std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800702 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700703 code += Indent + "# " + namer_.Type(struct_def.name) + "\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700704 code += Indent + "def ";
705 }
706
707 // Generate a struct field, conditioned on its child type(s).
Austin Schuh272c6132020-11-14 16:37:52 -0800708 void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700709 std::string *code_ptr) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700710 GenComment(field.doc_comment, code_ptr, &def_comment, Indent.c_str());
711 if (IsScalar(field.value.type.base_type)) {
712 if (struct_def.fixed) {
713 GetScalarFieldOfStruct(struct_def, field, code_ptr);
714 } else {
715 GetScalarFieldOfTable(struct_def, field, code_ptr);
716 }
717 } else if (IsArray(field.value.type)) {
718 GetArrayOfStruct(struct_def, field, code_ptr);
719 } else {
720 switch (field.value.type.base_type) {
721 case BASE_TYPE_STRUCT:
722 if (struct_def.fixed) {
723 GetStructFieldOfStruct(struct_def, field, code_ptr);
724 } else {
725 GetStructFieldOfTable(struct_def, field, code_ptr);
726 }
727 break;
Austin Schuh272c6132020-11-14 16:37:52 -0800728 case BASE_TYPE_STRING:
729 GetStringField(struct_def, field, code_ptr);
730 break;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700731 case BASE_TYPE_VECTOR: {
732 auto vectortype = field.value.type.VectorType();
733 if (vectortype.base_type == BASE_TYPE_STRUCT) {
734 GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
735 } else {
736 GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
737 GetVectorOfNonStructAsNumpy(struct_def, field, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700738 GetVectorAsNestedFlatbuffer(struct_def, field, code_ptr);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700739 }
740 break;
741 }
742 case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
743 default: FLATBUFFERS_ASSERT(0);
744 }
745 }
Austin Schuh272c6132020-11-14 16:37:52 -0800746 if (IsVector(field.value.type) || IsArray(field.value.type)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700747 GetVectorLen(struct_def, field, code_ptr);
Austin Schuh272c6132020-11-14 16:37:52 -0800748 GetVectorIsNone(struct_def, field, code_ptr);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700749 }
750 }
751
Austin Schuh272c6132020-11-14 16:37:52 -0800752 // Generate struct sizeof.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700753 void GenStructSizeOf(const StructDef &struct_def,
754 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800755 auto &code = *code_ptr;
756 code += Indent + "@classmethod\n";
757 code += Indent + "def SizeOf(cls):\n";
758 code +=
759 Indent + Indent + "return " + NumToString(struct_def.bytesize) + "\n";
760 code += "\n";
761 }
762
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700763 // Generate table constructors, conditioned on its members' types.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700764 void GenTableBuilders(const StructDef &struct_def,
765 std::string *code_ptr) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700766 GetStartOfTable(struct_def, code_ptr);
767
768 for (auto it = struct_def.fields.vec.begin();
Austin Schuh272c6132020-11-14 16:37:52 -0800769 it != struct_def.fields.vec.end(); ++it) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700770 auto &field = **it;
771 if (field.deprecated) continue;
772
773 auto offset = it - struct_def.fields.vec.begin();
774 BuildFieldOfTable(struct_def, field, offset, code_ptr);
Austin Schuh272c6132020-11-14 16:37:52 -0800775 if (IsVector(field.value.type)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700776 BuildVectorOfTable(struct_def, field, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700777 BuildVectorOfTableFromBytes(struct_def, field, code_ptr);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700778 }
779 }
780
781 GetEndOffsetOnTable(struct_def, code_ptr);
782 }
783
784 // Generate function to check for proper file identifier
785 void GenHasFileIdentifier(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700786 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800787 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700788 std::string escapedID;
789 // In the event any of file_identifier characters are special(NULL, \, etc),
790 // problems occur. To prevent this, convert all chars to their hex-escaped
791 // equivalent.
792 for (auto it = parser_.file_identifier_.begin();
793 it != parser_.file_identifier_.end(); ++it) {
794 escapedID += "\\x" + IntToStringHex(*it, 2);
795 }
796
797 code += Indent + "@classmethod\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700798 code += Indent + "def " + namer_.Type(struct_def.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700799 code += "BufferHasIdentifier(cls, buf, offset, size_prefixed=False):";
800 code += "\n";
801 code += Indent + Indent;
802 code += "return flatbuffers.util.BufferHasIdentifier(buf, offset, b\"";
803 code += escapedID;
804 code += "\", size_prefixed=size_prefixed)\n";
805 code += "\n";
806 }
Austin Schuh272c6132020-11-14 16:37:52 -0800807
808 // Generates struct or table methods.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700809 void GenStruct(const StructDef &struct_def, std::string *code_ptr) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700810 if (struct_def.generated) return;
811
812 GenComment(struct_def.doc_comment, code_ptr, &def_comment);
813 BeginClass(struct_def, code_ptr);
814 if (!struct_def.fixed) {
815 // Generate a special accessor for the table that has been declared as
816 // the root type.
817 NewRootTypeFromBuffer(struct_def, code_ptr);
Austin Schuh272c6132020-11-14 16:37:52 -0800818 if (parser_.file_identifier_.length()) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700819 // Generate a special function to test file_identifier
820 GenHasFileIdentifier(struct_def, code_ptr);
821 }
Austin Schuh272c6132020-11-14 16:37:52 -0800822 } else {
823 // Generates the SizeOf method for all structs.
824 GenStructSizeOf(struct_def, code_ptr);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700825 }
Austin Schuh272c6132020-11-14 16:37:52 -0800826 // Generates the Init method that sets the field in a pre-existing
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700827 // accessor object. This is to allow object reuse.
828 InitializeExisting(struct_def, code_ptr);
829 for (auto it = struct_def.fields.vec.begin();
Austin Schuh272c6132020-11-14 16:37:52 -0800830 it != struct_def.fields.vec.end(); ++it) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700831 auto &field = **it;
832 if (field.deprecated) continue;
833
834 GenStructAccessor(struct_def, field, code_ptr);
835 }
836
837 if (struct_def.fixed) {
Austin Schuh272c6132020-11-14 16:37:52 -0800838 // creates a struct constructor function
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700839 GenStructBuilder(struct_def, code_ptr);
840 } else {
Austin Schuh272c6132020-11-14 16:37:52 -0800841 // Creates a set of functions that allow table construction.
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700842 GenTableBuilders(struct_def, code_ptr);
843 }
844 }
845
Austin Schuh272c6132020-11-14 16:37:52 -0800846 void GenReceiverForObjectAPI(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700847 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800848 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700849 code += GenIndents(1) + "# " + namer_.ObjectType(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -0800850 code += GenIndents(1) + "def ";
851 }
852
853 void BeginClassForObjectAPI(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700854 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800855 auto &code = *code_ptr;
856 code += "\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700857 code += "class " + namer_.ObjectType(struct_def.name) + "(object):";
Austin Schuh272c6132020-11-14 16:37:52 -0800858 code += "\n";
859 }
860
861 // Gets the accoresponding python builtin type of a BaseType for scalars and
862 // string.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700863 std::string GetBasePythonTypeForScalarAndString(
864 const BaseType &base_type) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800865 if (IsBool(base_type)) {
866 return "bool";
867 } else if (IsFloat(base_type)) {
868 return "float";
869 } else if (IsInteger(base_type)) {
870 return "int";
871 } else if (base_type == BASE_TYPE_STRING) {
872 return "str";
873 } else {
874 FLATBUFFERS_ASSERT(false && "base_type is not a scalar or string type.");
875 return "";
876 }
877 }
878
James Kuszmaul8e62b022022-03-22 09:33:25 -0700879 std::string GetDefaultValue(const FieldDef &field) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800880 BaseType base_type = field.value.type.base_type;
881 if (IsBool(base_type)) {
882 return field.value.constant == "0" ? "False" : "True";
883 } else if (IsFloat(base_type)) {
884 return float_const_gen_.GenFloatConstant(field);
885 } else if (IsInteger(base_type)) {
886 return field.value.constant;
887 } else {
888 // For string, struct, and table.
889 return "None";
890 }
891 }
892
893 void GenUnionInit(const FieldDef &field, std::string *field_types_ptr,
894 std::set<std::string> *import_list,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700895 std::set<std::string> *import_typing_list) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800896 // Gets all possible types in the union.
897 import_typing_list->insert("Union");
898 auto &field_types = *field_types_ptr;
899 field_types = "Union[";
900
901 std::string separator_string = ", ";
902 auto enum_def = field.value.type.enum_def;
903 for (auto it = enum_def->Vals().begin(); it != enum_def->Vals().end();
904 ++it) {
905 auto &ev = **it;
906 // Union only supports string and table.
907 std::string field_type;
908 switch (ev.union_type.base_type) {
909 case BASE_TYPE_STRUCT:
James Kuszmaul8e62b022022-03-22 09:33:25 -0700910 field_type = namer_.ObjectType(ev.union_type.struct_def->name);
Austin Schuh272c6132020-11-14 16:37:52 -0800911 if (parser_.opts.include_dependence_headers) {
912 auto package_reference = GenPackageReference(ev.union_type);
913 field_type = package_reference + "." + field_type;
914 import_list->insert("import " + package_reference);
915 }
916 break;
917 case BASE_TYPE_STRING: field_type += "str"; break;
918 case BASE_TYPE_NONE: field_type += "None"; break;
919 default: break;
920 }
921 field_types += field_type + separator_string;
922 }
923
924 // Removes the last separator_string.
925 field_types.erase(field_types.length() - separator_string.size());
926 field_types += "]";
927
928 // Gets the import lists for the union.
929 if (parser_.opts.include_dependence_headers) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700930 const auto package_reference =
931 GenPackageReference(*field.value.type.enum_def);
Austin Schuh272c6132020-11-14 16:37:52 -0800932 import_list->insert("import " + package_reference);
933 }
934 }
935
James Kuszmaul8e62b022022-03-22 09:33:25 -0700936 void GenStructInit(const FieldDef &field, std::string *out_ptr,
Austin Schuh272c6132020-11-14 16:37:52 -0800937 std::set<std::string> *import_list,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700938 std::set<std::string> *import_typing_list) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800939 import_typing_list->insert("Optional");
James Kuszmaul8e62b022022-03-22 09:33:25 -0700940 auto &output = *out_ptr;
941 const Type &type = field.value.type;
942 const std::string object_type = namer_.ObjectType(type.struct_def->name);
Austin Schuh272c6132020-11-14 16:37:52 -0800943 if (parser_.opts.include_dependence_headers) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700944 auto package_reference = GenPackageReference(type);
945 output = package_reference + "." + object_type + "]";
Austin Schuh272c6132020-11-14 16:37:52 -0800946 import_list->insert("import " + package_reference);
947 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700948 output = object_type + "]";
Austin Schuh272c6132020-11-14 16:37:52 -0800949 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700950 output = "Optional[" + output;
Austin Schuh272c6132020-11-14 16:37:52 -0800951 }
952
953 void GenVectorInit(const FieldDef &field, std::string *field_type_ptr,
954 std::set<std::string> *import_list,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700955 std::set<std::string> *import_typing_list) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800956 import_typing_list->insert("List");
957 auto &field_type = *field_type_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700958 const Type &vector_type = field.value.type.VectorType();
959 const BaseType base_type = vector_type.base_type;
Austin Schuh272c6132020-11-14 16:37:52 -0800960 if (base_type == BASE_TYPE_STRUCT) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700961 const std::string object_type =
962 namer_.ObjectType(GenTypeGet(vector_type));
963 field_type = object_type + "]";
Austin Schuh272c6132020-11-14 16:37:52 -0800964 if (parser_.opts.include_dependence_headers) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700965 auto package_reference = GenPackageReference(vector_type);
966 field_type = package_reference + "." + object_type + "]";
Austin Schuh272c6132020-11-14 16:37:52 -0800967 import_list->insert("import " + package_reference);
968 }
969 field_type = "List[" + field_type;
970 } else {
971 field_type =
972 "List[" + GetBasePythonTypeForScalarAndString(base_type) + "]";
973 }
974 }
975
976 void GenInitialize(const StructDef &struct_def, std::string *code_ptr,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700977 std::set<std::string> *import_list) const {
Austin Schuh272c6132020-11-14 16:37:52 -0800978 std::string code;
979 std::set<std::string> import_typing_list;
980 for (auto it = struct_def.fields.vec.begin();
981 it != struct_def.fields.vec.end(); ++it) {
982 auto &field = **it;
983 if (field.deprecated) continue;
984
985 // Determines field type, default value, and typing imports.
986 auto base_type = field.value.type.base_type;
987 std::string field_type;
988 switch (base_type) {
989 case BASE_TYPE_UNION: {
990 GenUnionInit(field, &field_type, import_list, &import_typing_list);
991 break;
992 }
993 case BASE_TYPE_STRUCT: {
994 GenStructInit(field, &field_type, import_list, &import_typing_list);
995 break;
996 }
997 case BASE_TYPE_VECTOR:
998 case BASE_TYPE_ARRAY: {
999 GenVectorInit(field, &field_type, import_list, &import_typing_list);
1000 break;
1001 }
1002 default:
1003 // Scalar or sting fields.
1004 field_type = GetBasePythonTypeForScalarAndString(base_type);
1005 break;
1006 }
1007
James Kuszmaul8e62b022022-03-22 09:33:25 -07001008 const auto default_value = GetDefaultValue(field);
Austin Schuh272c6132020-11-14 16:37:52 -08001009 // Wrties the init statement.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001010 const auto field_field = namer_.Field(field.name);
1011 code += GenIndents(2) + "self." + field_field + " = " + default_value +
1012 " # type: " + field_type;
Austin Schuh272c6132020-11-14 16:37:52 -08001013 }
1014
1015 // Writes __init__ method.
1016 auto &code_base = *code_ptr;
1017 GenReceiverForObjectAPI(struct_def, code_ptr);
1018 code_base += "__init__(self):";
1019 if (code.empty()) {
1020 code_base += GenIndents(2) + "pass";
1021 } else {
1022 code_base += code;
1023 }
1024 code_base += "\n";
1025
1026 // Merges the typing imports into import_list.
1027 if (!import_typing_list.empty()) {
1028 // Adds the try statement.
1029 std::string typing_imports = "try:";
1030 typing_imports += GenIndents(1) + "from typing import ";
1031 std::string separator_string = ", ";
1032 for (auto it = import_typing_list.begin(); it != import_typing_list.end();
1033 ++it) {
1034 const std::string &im = *it;
1035 typing_imports += im + separator_string;
1036 }
1037 // Removes the last separator_string.
1038 typing_imports.erase(typing_imports.length() - separator_string.size());
1039
1040 // Adds the except statement.
1041 typing_imports += "\n";
1042 typing_imports += "except:";
1043 typing_imports += GenIndents(1) + "pass";
1044 import_list->insert(typing_imports);
1045 }
1046
1047 // Removes the import of the struct itself, if applied.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001048 auto struct_import = "import " + GenPackageReference(struct_def);
Austin Schuh272c6132020-11-14 16:37:52 -08001049 import_list->erase(struct_import);
1050 }
1051
James Kuszmaul8e62b022022-03-22 09:33:25 -07001052 void InitializeFromBuf(const StructDef &struct_def,
1053 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001054 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001055 const auto struct_var = namer_.Variable(struct_def.name);
1056 const auto struct_type = namer_.Type(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001057
1058 code += GenIndents(1) + "@classmethod";
1059 code += GenIndents(1) + "def InitFromBuf(cls, buf, pos):";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001060 code += GenIndents(2) + struct_var + " = " + struct_type + "()";
1061 code += GenIndents(2) + struct_var + ".Init(buf, pos)";
1062 code += GenIndents(2) + "return cls.InitFromObj(" + struct_var + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001063 code += "\n";
1064 }
1065
1066 void InitializeFromObjForObject(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001067 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001068 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001069 const auto struct_var = namer_.Variable(struct_def.name);
1070 const auto struct_object = namer_.ObjectType(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001071
1072 code += GenIndents(1) + "@classmethod";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001073 code += GenIndents(1) + "def InitFromObj(cls, " + struct_var + "):";
1074 code += GenIndents(2) + "x = " + struct_object + "()";
1075 code += GenIndents(2) + "x._UnPack(" + struct_var + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001076 code += GenIndents(2) + "return x";
1077 code += "\n";
1078 }
1079
1080 void GenUnPackForStruct(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001081 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001082 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001083 const auto struct_var = namer_.Variable(struct_def.name);
1084 const auto field_field = namer_.Field(field.name);
1085 const auto field_method = namer_.Method(field.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001086 auto field_type = TypeName(field);
1087
1088 if (parser_.opts.include_dependence_headers) {
1089 auto package_reference = GenPackageReference(field.value.type);
1090 field_type = package_reference + "." + TypeName(field);
1091 }
1092
James Kuszmaul8e62b022022-03-22 09:33:25 -07001093 code += GenIndents(2) + "if " + struct_var + "." + field_method + "(";
Austin Schuh272c6132020-11-14 16:37:52 -08001094 // if field is a struct, we need to create an instance for it first.
1095 if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) {
1096 code += field_type + "()";
1097 }
1098 code += ") is not None:";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001099 code += GenIndents(3) + "self." + field_field + " = " + field_type +
1100 "T.InitFromObj(" + struct_var + "." + field_method + "(";
Austin Schuh272c6132020-11-14 16:37:52 -08001101 // A struct's accessor requires a struct buf instance.
1102 if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) {
1103 code += field_type + "()";
1104 }
1105 code += "))";
1106 }
1107
1108 void GenUnPackForUnion(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001109 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001110 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001111 const auto field_field = namer_.Field(field.name);
1112 const auto field_method = namer_.Method(field.name);
1113 const auto struct_var = namer_.Variable(struct_def.name);
1114 const EnumDef &enum_def = *field.value.type.enum_def;
1115 auto union_type = namer_.Namespace(enum_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001116
1117 if (parser_.opts.include_dependence_headers) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001118 union_type = GenPackageReference(enum_def) + "." + union_type;
Austin Schuh272c6132020-11-14 16:37:52 -08001119 }
James Kuszmaul8e62b022022-03-22 09:33:25 -07001120 code += GenIndents(2) + "self." + field_field + " = " + union_type +
1121 "Creator(" + "self." + field_field + "Type, " + struct_var + "." +
1122 field_method + "())";
Austin Schuh272c6132020-11-14 16:37:52 -08001123 }
1124
1125 void GenUnPackForStructVector(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001126 const FieldDef &field,
1127 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001128 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001129 const auto field_field = namer_.Field(field.name);
1130 const auto field_method = namer_.Method(field.name);
1131 const auto struct_var = namer_.Variable(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001132
James Kuszmaul8e62b022022-03-22 09:33:25 -07001133 code += GenIndents(2) + "if not " + struct_var + "." + field_method +
1134 "IsNone():";
1135 code += GenIndents(3) + "self." + field_field + " = []";
1136 code += GenIndents(3) + "for i in range(" + struct_var + "." +
1137 field_method + "Length()):";
Austin Schuh272c6132020-11-14 16:37:52 -08001138
James Kuszmaul8e62b022022-03-22 09:33:25 -07001139 auto field_type = TypeName(field);
1140 auto one_instance = field_type + "_";
Austin Schuh272c6132020-11-14 16:37:52 -08001141 one_instance[0] = CharToLower(one_instance[0]);
1142
1143 if (parser_.opts.include_dependence_headers) {
1144 auto package_reference = GenPackageReference(field.value.type);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001145 field_type = package_reference + "." + TypeName(field);
Austin Schuh272c6132020-11-14 16:37:52 -08001146 }
1147
James Kuszmaul8e62b022022-03-22 09:33:25 -07001148 code += GenIndents(4) + "if " + struct_var + "." + field_method +
1149 "(i) is None:";
1150 code += GenIndents(5) + "self." + field_field + ".append(None)";
Austin Schuh272c6132020-11-14 16:37:52 -08001151 code += GenIndents(4) + "else:";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001152 code += GenIndents(5) + one_instance + " = " + field_type +
1153 "T.InitFromObj(" + struct_var + "." + field_method + "(i))";
1154 code +=
1155 GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001156 }
1157
1158 void GenUnpackforScalarVectorHelper(const StructDef &struct_def,
1159 const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001160 std::string *code_ptr,
1161 int indents) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001162 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001163 const auto field_field = namer_.Field(field.name);
1164 const auto field_method = namer_.Method(field.name);
1165 const auto struct_var = namer_.Variable(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001166
James Kuszmaul8e62b022022-03-22 09:33:25 -07001167 code += GenIndents(indents) + "self." + field_field + " = []";
1168 code += GenIndents(indents) + "for i in range(" + struct_var + "." +
1169 field_method + "Length()):";
1170 code += GenIndents(indents + 1) + "self." + field_field + ".append(" +
1171 struct_var + "." + field_method + "(i))";
Austin Schuh272c6132020-11-14 16:37:52 -08001172 }
1173
1174 void GenUnPackForScalarVector(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001175 const FieldDef &field,
1176 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001177 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001178 const auto field_field = namer_.Field(field.name);
1179 const auto field_method = namer_.Method(field.name);
1180 const auto struct_var = namer_.Variable(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001181
James Kuszmaul8e62b022022-03-22 09:33:25 -07001182 code += GenIndents(2) + "if not " + struct_var + "." + field_method +
1183 "IsNone():";
Austin Schuh272c6132020-11-14 16:37:52 -08001184
1185 // String does not have the AsNumpy method.
1186 if (!(IsScalar(field.value.type.VectorType().base_type))) {
1187 GenUnpackforScalarVectorHelper(struct_def, field, code_ptr, 3);
1188 return;
1189 }
1190
1191 code += GenIndents(3) + "if np is None:";
1192 GenUnpackforScalarVectorHelper(struct_def, field, code_ptr, 4);
1193
1194 // If numpy exists, use the AsNumpy method to optimize the unpack speed.
1195 code += GenIndents(3) + "else:";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001196 code += GenIndents(4) + "self." + field_field + " = " + struct_var + "." +
1197 field_method + "AsNumpy()";
Austin Schuh272c6132020-11-14 16:37:52 -08001198 }
1199
1200 void GenUnPackForScalar(const StructDef &struct_def, const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001201 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001202 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001203 const auto field_field = namer_.Field(field.name);
1204 const auto field_method = namer_.Method(field.name);
1205 const auto struct_var = namer_.Variable(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001206
James Kuszmaul8e62b022022-03-22 09:33:25 -07001207 code += GenIndents(2) + "self." + field_field + " = " + struct_var + "." +
1208 field_method + "()";
Austin Schuh272c6132020-11-14 16:37:52 -08001209 }
1210
1211 // Generates the UnPack method for the object class.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001212 void GenUnPack(const StructDef &struct_def, std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001213 std::string code;
1214 // Items that needs to be imported. No duplicate modules will be imported.
1215 std::set<std::string> import_list;
1216
1217 for (auto it = struct_def.fields.vec.begin();
1218 it != struct_def.fields.vec.end(); ++it) {
1219 auto &field = **it;
1220 if (field.deprecated) continue;
1221
1222 auto field_type = TypeName(field);
1223 switch (field.value.type.base_type) {
1224 case BASE_TYPE_STRUCT: {
1225 GenUnPackForStruct(struct_def, field, &code);
1226 break;
1227 }
1228 case BASE_TYPE_UNION: {
1229 GenUnPackForUnion(struct_def, field, &code);
1230 break;
1231 }
1232 case BASE_TYPE_VECTOR: {
1233 auto vectortype = field.value.type.VectorType();
1234 if (vectortype.base_type == BASE_TYPE_STRUCT) {
1235 GenUnPackForStructVector(struct_def, field, &code);
1236 } else {
1237 GenUnPackForScalarVector(struct_def, field, &code);
1238 }
1239 break;
1240 }
1241 case BASE_TYPE_ARRAY: {
1242 GenUnPackForScalarVector(struct_def, field, &code);
1243 break;
1244 }
1245 default: GenUnPackForScalar(struct_def, field, &code);
1246 }
1247 }
1248
1249 // Writes import statements and code into the generated file.
1250 auto &code_base = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001251 const auto struct_var = namer_.Variable(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001252
1253 GenReceiverForObjectAPI(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001254 code_base += "_UnPack(self, " + struct_var + "):";
1255 code_base += GenIndents(2) + "if " + struct_var + " is None:";
Austin Schuh272c6132020-11-14 16:37:52 -08001256 code_base += GenIndents(3) + "return";
1257
1258 // Write the import statements.
1259 for (std::set<std::string>::iterator it = import_list.begin();
1260 it != import_list.end(); ++it) {
1261 code_base += GenIndents(2) + *it;
1262 }
1263
1264 // Write the code.
1265 code_base += code;
1266 code_base += "\n";
1267 }
1268
James Kuszmaul8e62b022022-03-22 09:33:25 -07001269 void GenPackForStruct(const StructDef &struct_def,
1270 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001271 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001272 const auto struct_fn = namer_.Function(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001273
1274 GenReceiverForObjectAPI(struct_def, code_ptr);
1275 code += "Pack(self, builder):";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001276 code += GenIndents(2) + "return Create" + struct_fn + "(builder";
Austin Schuh272c6132020-11-14 16:37:52 -08001277
1278 StructBuilderArgs(struct_def,
1279 /* nameprefix = */ "self.",
1280 /* namesuffix = */ "",
1281 /* has_field_name = */ true,
1282 /* fieldname_suffix = */ ".", code_ptr);
1283 code += ")\n";
1284 }
1285
1286 void GenPackForStructVectorField(const StructDef &struct_def,
1287 const FieldDef &field,
1288 std::string *code_prefix_ptr,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001289 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001290 auto &code_prefix = *code_prefix_ptr;
1291 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001292 const auto field_field = namer_.Field(field.name);
1293 const auto struct_type = namer_.Type(struct_def.name);
1294 const auto field_method = namer_.Method(field.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001295
1296 // Creates the field.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001297 code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
Austin Schuh272c6132020-11-14 16:37:52 -08001298 if (field.value.type.struct_def->fixed) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001299 code_prefix += GenIndents(3) + struct_type + "Start" + field_method +
1300 "Vector(builder, len(self." + field_field + "))";
Austin Schuh272c6132020-11-14 16:37:52 -08001301 code_prefix += GenIndents(3) + "for i in reversed(range(len(self." +
James Kuszmaul8e62b022022-03-22 09:33:25 -07001302 field_field + "))):";
Austin Schuh272c6132020-11-14 16:37:52 -08001303 code_prefix +=
James Kuszmaul8e62b022022-03-22 09:33:25 -07001304 GenIndents(4) + "self." + field_field + "[i].Pack(builder)";
1305 code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
Austin Schuh272c6132020-11-14 16:37:52 -08001306 } else {
1307 // If the vector is a struct vector, we need to first build accessor for
1308 // each struct element.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001309 code_prefix += GenIndents(3) + field_field + "list = []";
Austin Schuh272c6132020-11-14 16:37:52 -08001310 code_prefix += GenIndents(3);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001311 code_prefix += "for i in range(len(self." + field_field + ")):";
1312 code_prefix += GenIndents(4) + field_field + "list.append(self." +
1313 field_field + "[i].Pack(builder))";
Austin Schuh272c6132020-11-14 16:37:52 -08001314
James Kuszmaul8e62b022022-03-22 09:33:25 -07001315 code_prefix += GenIndents(3) + struct_type + "Start" + field_method +
1316 "Vector(builder, len(self." + field_field + "))";
Austin Schuh272c6132020-11-14 16:37:52 -08001317 code_prefix += GenIndents(3) + "for i in reversed(range(len(self." +
James Kuszmaul8e62b022022-03-22 09:33:25 -07001318 field_field + "))):";
Austin Schuh272c6132020-11-14 16:37:52 -08001319 code_prefix += GenIndents(4) + "builder.PrependUOffsetTRelative" + "(" +
James Kuszmaul8e62b022022-03-22 09:33:25 -07001320 field_field + "list[i])";
1321 code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
Austin Schuh272c6132020-11-14 16:37:52 -08001322 }
1323
1324 // Adds the field into the struct.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001325 code += GenIndents(2) + "if self." + field_field + " is not None:";
1326 code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
1327 field_field + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001328 }
1329
1330 void GenPackForScalarVectorFieldHelper(const StructDef &struct_def,
1331 const FieldDef &field,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001332 std::string *code_ptr,
1333 int indents) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001334 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001335 const auto field_field = namer_.Field(field.name);
1336 const auto field_method = namer_.Method(field.name);
1337 const auto struct_type = namer_.Type(struct_def.name);
1338 const auto vectortype = field.value.type.VectorType();
Austin Schuh272c6132020-11-14 16:37:52 -08001339
James Kuszmaul8e62b022022-03-22 09:33:25 -07001340 code += GenIndents(indents) + struct_type + "Start" + field_method +
1341 "Vector(builder, len(self." + field_field + "))";
Austin Schuh272c6132020-11-14 16:37:52 -08001342 code += GenIndents(indents) + "for i in reversed(range(len(self." +
James Kuszmaul8e62b022022-03-22 09:33:25 -07001343 field_field + "))):";
Austin Schuh272c6132020-11-14 16:37:52 -08001344 code += GenIndents(indents + 1) + "builder.Prepend";
1345
1346 std::string type_name;
1347 switch (vectortype.base_type) {
1348 case BASE_TYPE_BOOL: type_name = "Bool"; break;
1349 case BASE_TYPE_CHAR: type_name = "Byte"; break;
1350 case BASE_TYPE_UCHAR: type_name = "Uint8"; break;
1351 case BASE_TYPE_SHORT: type_name = "Int16"; break;
1352 case BASE_TYPE_USHORT: type_name = "Uint16"; break;
1353 case BASE_TYPE_INT: type_name = "Int32"; break;
1354 case BASE_TYPE_UINT: type_name = "Uint32"; break;
1355 case BASE_TYPE_LONG: type_name = "Int64"; break;
1356 case BASE_TYPE_ULONG: type_name = "Uint64"; break;
1357 case BASE_TYPE_FLOAT: type_name = "Float32"; break;
1358 case BASE_TYPE_DOUBLE: type_name = "Float64"; break;
1359 case BASE_TYPE_STRING: type_name = "UOffsetTRelative"; break;
1360 default: type_name = "VOffsetT"; break;
1361 }
1362 code += type_name;
1363 }
1364
1365 void GenPackForScalarVectorField(const StructDef &struct_def,
1366 const FieldDef &field,
1367 std::string *code_prefix_ptr,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001368 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001369 auto &code = *code_ptr;
1370 auto &code_prefix = *code_prefix_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001371 const auto field_field = namer_.Field(field.name);
1372 const auto field_method = namer_.Method(field.name);
1373 const auto struct_type = namer_.Type(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001374
1375 // Adds the field into the struct.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001376 code += GenIndents(2) + "if self." + field_field + " is not None:";
1377 code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
1378 field_field + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001379
1380 // Creates the field.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001381 code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
Austin Schuh272c6132020-11-14 16:37:52 -08001382 // If the vector is a string vector, we need to first build accessor for
1383 // each string element. And this generated code, needs to be
1384 // placed ahead of code_prefix.
1385 auto vectortype = field.value.type.VectorType();
1386 if (IsString(vectortype)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001387 code_prefix += GenIndents(3) + field_field + "list = []";
1388 code_prefix +=
1389 GenIndents(3) + "for i in range(len(self." + field_field + ")):";
1390 code_prefix += GenIndents(4) + field_field +
1391 "list.append(builder.CreateString(self." + field_field +
1392 "[i]))";
Austin Schuh272c6132020-11-14 16:37:52 -08001393 GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 3);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001394 code_prefix += "(" + field_field + "list[i])";
1395 code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
Austin Schuh272c6132020-11-14 16:37:52 -08001396 return;
1397 }
1398
1399 code_prefix += GenIndents(3) + "if np is not None and type(self." +
James Kuszmaul8e62b022022-03-22 09:33:25 -07001400 field_field + ") is np.ndarray:";
1401 code_prefix += GenIndents(4) + field_field +
1402 " = builder.CreateNumpyVector(self." + field_field + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001403 code_prefix += GenIndents(3) + "else:";
1404 GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 4);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001405 code_prefix += "(self." + field_field + "[i])";
1406 code_prefix += GenIndents(4) + field_field + " = builder.EndVector()";
Austin Schuh272c6132020-11-14 16:37:52 -08001407 }
1408
1409 void GenPackForStructField(const StructDef &struct_def, const FieldDef &field,
1410 std::string *code_prefix_ptr,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001411 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001412 auto &code_prefix = *code_prefix_ptr;
1413 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001414 const auto field_field = namer_.Field(field.name);
1415 const auto field_method = namer_.Method(field.name);
1416 const auto struct_type = namer_.Type(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001417
1418 if (field.value.type.struct_def->fixed) {
1419 // Pure struct fields need to be created along with their parent
1420 // structs.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001421 code += GenIndents(2) + "if self." + field_field + " is not None:";
1422 code += GenIndents(3) + field_field + " = self." + field_field +
1423 ".Pack(builder)";
Austin Schuh272c6132020-11-14 16:37:52 -08001424 } else {
1425 // Tables need to be created before their parent structs are created.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001426 code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
1427 code_prefix += GenIndents(3) + field_field + " = self." + field_field +
1428 ".Pack(builder)";
1429 code += GenIndents(2) + "if self." + field_field + " is not None:";
Austin Schuh272c6132020-11-14 16:37:52 -08001430 }
1431
James Kuszmaul8e62b022022-03-22 09:33:25 -07001432 code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
1433 field_field + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001434 }
1435
1436 void GenPackForUnionField(const StructDef &struct_def, const FieldDef &field,
1437 std::string *code_prefix_ptr,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001438 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001439 auto &code_prefix = *code_prefix_ptr;
1440 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001441 const auto field_field = namer_.Field(field.name);
1442 const auto field_method = namer_.Method(field.name);
1443 const auto struct_type = namer_.Type(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001444
1445 // TODO(luwa): TypeT should be moved under the None check as well.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001446 code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
1447 code_prefix += GenIndents(3) + field_field + " = self." + field_field +
1448 ".Pack(builder)";
1449 code += GenIndents(2) + "if self." + field_field + " is not None:";
1450 code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
1451 field_field + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001452 }
1453
James Kuszmaul8e62b022022-03-22 09:33:25 -07001454 void GenPackForTable(const StructDef &struct_def,
1455 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001456 auto &code_base = *code_ptr;
1457 std::string code, code_prefix;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001458 const auto struct_var = namer_.Variable(struct_def.name);
1459 const auto struct_type = namer_.Type(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001460
1461 GenReceiverForObjectAPI(struct_def, code_ptr);
1462 code_base += "Pack(self, builder):";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001463 code += GenIndents(2) + struct_type + "Start(builder)";
Austin Schuh272c6132020-11-14 16:37:52 -08001464 for (auto it = struct_def.fields.vec.begin();
1465 it != struct_def.fields.vec.end(); ++it) {
1466 auto &field = **it;
1467 if (field.deprecated) continue;
1468
James Kuszmaul8e62b022022-03-22 09:33:25 -07001469 const auto field_method = namer_.Method(field.name);
1470 const auto field_field = namer_.Field(field.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001471
1472 switch (field.value.type.base_type) {
1473 case BASE_TYPE_STRUCT: {
1474 GenPackForStructField(struct_def, field, &code_prefix, &code);
1475 break;
1476 }
1477 case BASE_TYPE_UNION: {
1478 GenPackForUnionField(struct_def, field, &code_prefix, &code);
1479 break;
1480 }
1481 case BASE_TYPE_VECTOR: {
1482 auto vectortype = field.value.type.VectorType();
1483 if (vectortype.base_type == BASE_TYPE_STRUCT) {
1484 GenPackForStructVectorField(struct_def, field, &code_prefix, &code);
1485 } else {
1486 GenPackForScalarVectorField(struct_def, field, &code_prefix, &code);
1487 }
1488 break;
1489 }
1490 case BASE_TYPE_ARRAY: {
1491 GenPackForScalarVectorField(struct_def, field, &code_prefix, &code);
1492 break;
1493 }
1494 case BASE_TYPE_STRING: {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001495 code_prefix +=
1496 GenIndents(2) + "if self." + field_field + " is not None:";
1497 code_prefix += GenIndents(3) + field_field +
1498 " = builder.CreateString(self." + field_field + ")";
1499 code += GenIndents(2) + "if self." + field_field + " is not None:";
1500 code += GenIndents(3) + struct_type + "Add" + field_method +
1501 "(builder, " + field_field + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001502 break;
1503 }
1504 default:
1505 // Generates code for scalar values. If the value equals to the
1506 // default value, builder will automatically ignore it. So we don't
1507 // need to check the value ahead.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001508 code += GenIndents(2) + struct_type + "Add" + field_method +
1509 "(builder, self." + field_field + ")";
Austin Schuh272c6132020-11-14 16:37:52 -08001510 break;
1511 }
1512 }
1513
James Kuszmaul8e62b022022-03-22 09:33:25 -07001514 code += GenIndents(2) + struct_var + " = " + struct_type + "End(builder)";
1515 code += GenIndents(2) + "return " + struct_var;
Austin Schuh272c6132020-11-14 16:37:52 -08001516
1517 code_base += code_prefix + code;
1518 code_base += "\n";
1519 }
1520
1521 void GenStructForObjectAPI(const StructDef &struct_def,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001522 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001523 if (struct_def.generated) return;
1524
1525 std::set<std::string> import_list;
1526 std::string code;
1527
1528 // Creates an object class for a struct or a table
1529 BeginClassForObjectAPI(struct_def, &code);
1530
1531 GenInitialize(struct_def, &code, &import_list);
1532
1533 InitializeFromBuf(struct_def, &code);
1534
1535 InitializeFromObjForObject(struct_def, &code);
1536
1537 GenUnPack(struct_def, &code);
1538
1539 if (struct_def.fixed) {
1540 GenPackForStruct(struct_def, &code);
1541 } else {
1542 GenPackForTable(struct_def, &code);
1543 }
1544
1545 // Adds the imports at top.
1546 auto &code_base = *code_ptr;
1547 code_base += "\n";
1548 for (auto it = import_list.begin(); it != import_list.end(); it++) {
1549 auto im = *it;
1550 code_base += im + "\n";
1551 }
1552 code_base += code;
1553 }
1554
1555 void GenUnionCreatorForStruct(const EnumDef &enum_def, const EnumVal &ev,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001556 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001557 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001558 const auto union_type = namer_.Type(enum_def.name);
1559 const auto variant = namer_.Variant(ev.name);
1560 auto field_type = namer_.ObjectType(GenTypeGet(ev.union_type));
Austin Schuh272c6132020-11-14 16:37:52 -08001561
James Kuszmaul8e62b022022-03-22 09:33:25 -07001562 code += GenIndents(1) + "if unionType == " + union_type + "()." +
1563 variant + ":";
Austin Schuh272c6132020-11-14 16:37:52 -08001564 if (parser_.opts.include_dependence_headers) {
1565 auto package_reference = GenPackageReference(ev.union_type);
1566 code += GenIndents(2) + "import " + package_reference;
1567 field_type = package_reference + "." + field_type;
1568 }
1569 code += GenIndents(2) + "return " + field_type +
1570 ".InitFromBuf(table.Bytes, table.Pos)";
1571 }
1572
1573 void GenUnionCreatorForString(const EnumDef &enum_def, const EnumVal &ev,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001574 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001575 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001576 const auto union_type = namer_.Type(enum_def.name);
1577 const auto variant = namer_.Variant(ev.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001578
James Kuszmaul8e62b022022-03-22 09:33:25 -07001579 code += GenIndents(1) + "if unionType == " + union_type + "()." +
1580 variant + ":";
Austin Schuh272c6132020-11-14 16:37:52 -08001581 code += GenIndents(2) + "tab = Table(table.Bytes, table.Pos)";
1582 code += GenIndents(2) + "union = tab.String(table.Pos)";
1583 code += GenIndents(2) + "return union";
1584 }
1585
1586 // Creates an union object based on union type.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001587 void GenUnionCreator(const EnumDef &enum_def, std::string *code_ptr) const {
1588 if (enum_def.generated) return;
1589
Austin Schuh272c6132020-11-14 16:37:52 -08001590 auto &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001591 const auto enum_fn = namer_.Function(enum_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001592
1593 code += "\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001594 code += "def " + enum_fn + "Creator(unionType, table):";
Austin Schuh272c6132020-11-14 16:37:52 -08001595 code += GenIndents(1) + "from flatbuffers.table import Table";
1596 code += GenIndents(1) + "if not isinstance(table, Table):";
1597 code += GenIndents(2) + "return None";
1598
1599 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1600 auto &ev = **it;
1601 // Union only supports string and table.
1602 switch (ev.union_type.base_type) {
1603 case BASE_TYPE_STRUCT:
1604 GenUnionCreatorForStruct(enum_def, ev, &code);
1605 break;
1606 case BASE_TYPE_STRING:
1607 GenUnionCreatorForString(enum_def, ev, &code);
1608 break;
1609 default: break;
1610 }
1611 }
1612 code += GenIndents(1) + "return None";
1613 code += "\n";
1614 }
1615
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001616 // Generate enum declarations.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001617 void GenEnum(const EnumDef &enum_def, std::string *code_ptr) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001618 if (enum_def.generated) return;
1619
1620 GenComment(enum_def.doc_comment, code_ptr, &def_comment);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001621 BeginEnum(enum_def, code_ptr);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001622 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1623 auto &ev = **it;
1624 GenComment(ev.doc_comment, code_ptr, &def_comment, Indent.c_str());
1625 EnumMember(enum_def, ev, code_ptr);
1626 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001627 }
1628
1629 // Returns the function name that is able to read a value of the given type.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001630 std::string GenGetter(const Type &type) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001631 switch (type.base_type) {
1632 case BASE_TYPE_STRING: return "self._tab.String(";
1633 case BASE_TYPE_UNION: return "self._tab.Union(";
1634 case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
1635 default:
1636 return "self._tab.Get(flatbuffers.number_types." +
James Kuszmaul8e62b022022-03-22 09:33:25 -07001637 namer_.Method(GenTypeGet(type)) + "Flags, ";
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001638 }
1639 }
1640
1641 // Returns the method name for use with add/put calls.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001642 std::string GenMethod(const FieldDef &field) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001643 return (IsScalar(field.value.type.base_type) || IsArray(field.value.type))
James Kuszmaul8e62b022022-03-22 09:33:25 -07001644 ? namer_.Method(GenTypeBasic(field.value.type))
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001645 : (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
1646 }
1647
James Kuszmaul8e62b022022-03-22 09:33:25 -07001648 std::string GenTypeBasic(const Type &type) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001649 // clang-format off
Austin Schuh272c6132020-11-14 16:37:52 -08001650 static const char *ctypename[] = {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001651 #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
Austin Schuh272c6132020-11-14 16:37:52 -08001652 CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, ...) \
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001653 #PTYPE,
1654 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
1655 #undef FLATBUFFERS_TD
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001656 };
Austin Schuh272c6132020-11-14 16:37:52 -08001657 // clang-format on
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001658 return ctypename[IsArray(type) ? type.VectorType().base_type
1659 : type.base_type];
1660 }
1661
James Kuszmaul8e62b022022-03-22 09:33:25 -07001662 std::string GenTypePointer(const Type &type) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001663 switch (type.base_type) {
1664 case BASE_TYPE_STRING: return "string";
1665 case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
1666 case BASE_TYPE_STRUCT: return type.struct_def->name;
1667 case BASE_TYPE_UNION:
1668 // fall through
1669 default: return "*flatbuffers.Table";
1670 }
1671 }
1672
James Kuszmaul8e62b022022-03-22 09:33:25 -07001673 std::string GenTypeGet(const Type &type) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001674 return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
1675 }
1676
James Kuszmaul8e62b022022-03-22 09:33:25 -07001677 std::string TypeName(const FieldDef &field) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001678 return GenTypeGet(field.value.type);
1679 }
1680
1681 // Create a struct with a builder and the struct's arguments.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001682 void GenStructBuilder(const StructDef &struct_def,
1683 std::string *code_ptr) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001684 BeginBuilderArgs(struct_def, code_ptr);
Austin Schuh272c6132020-11-14 16:37:52 -08001685 StructBuilderArgs(struct_def,
1686 /* nameprefix = */ "",
1687 /* namesuffix = */ "",
1688 /* has_field_name = */ true,
1689 /* fieldname_suffix = */ "_", code_ptr);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001690 EndBuilderArgs(code_ptr);
1691
1692 StructBuilderBody(struct_def, "", code_ptr);
1693 EndBuilderBody(code_ptr);
1694 }
1695
1696 bool generate() {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001697 std::string one_file_code;
1698 if (!generateEnums(&one_file_code)) return false;
1699 if (!generateStructs(&one_file_code)) return false;
1700
1701 if (parser_.opts.one_file) {
1702 // Legacy file format uses keep casing.
1703 return SaveType(file_name_ + "_generated.py", *parser_.current_namespace_,
1704 one_file_code, true);
1705 }
1706
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001707 return true;
1708 }
1709
1710 private:
James Kuszmaul8e62b022022-03-22 09:33:25 -07001711 bool generateEnums(std::string *one_file_code) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001712 for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
1713 ++it) {
1714 auto &enum_def = **it;
1715 std::string enumcode;
1716 GenEnum(enum_def, &enumcode);
Austin Schuh272c6132020-11-14 16:37:52 -08001717 if (parser_.opts.generate_object_based_api & enum_def.is_union) {
1718 GenUnionCreator(enum_def, &enumcode);
1719 }
James Kuszmaul8e62b022022-03-22 09:33:25 -07001720
1721 if (parser_.opts.one_file && !enumcode.empty()) {
1722 *one_file_code += enumcode + "\n\n";
1723 } else {
1724 if (!SaveType(namer_.File(enum_def.name, SkipFile::Suffix),
1725 *enum_def.defined_namespace, enumcode, false))
1726 return false;
1727 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001728 }
1729 return true;
1730 }
1731
James Kuszmaul8e62b022022-03-22 09:33:25 -07001732 bool generateStructs(std::string *one_file_code) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001733 for (auto it = parser_.structs_.vec.begin();
1734 it != parser_.structs_.vec.end(); ++it) {
1735 auto &struct_def = **it;
1736 std::string declcode;
1737 GenStruct(struct_def, &declcode);
Austin Schuh272c6132020-11-14 16:37:52 -08001738 if (parser_.opts.generate_object_based_api) {
1739 GenStructForObjectAPI(struct_def, &declcode);
1740 }
James Kuszmaul8e62b022022-03-22 09:33:25 -07001741
1742 if (parser_.opts.one_file && !declcode.empty()) {
1743 *one_file_code += declcode + "\n\n";
1744 } else {
1745 if (!SaveType(namer_.File(struct_def.name, SkipFile::Suffix),
1746 *struct_def.defined_namespace, declcode, true))
1747 return false;
1748 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001749 }
1750 return true;
1751 }
1752
1753 // Begin by declaring namespace and imports.
1754 void BeginFile(const std::string &name_space_name, const bool needs_imports,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001755 std::string *code_ptr) const {
Austin Schuh272c6132020-11-14 16:37:52 -08001756 auto &code = *code_ptr;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001757 code = code + "# " + FlatBuffersGeneratedWarning() + "\n\n";
1758 code += "# namespace: " + name_space_name + "\n\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001759 if (needs_imports) {
1760 code += "import flatbuffers\n";
1761 code += "from flatbuffers.compat import import_numpy\n";
1762 code += "np = import_numpy()\n\n";
1763 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001764 }
1765
1766 // Save out the generated code for a Python Table type.
James Kuszmaul8e62b022022-03-22 09:33:25 -07001767 bool SaveType(const std::string &defname, const Namespace &ns,
1768 const std::string &classcode, bool needs_imports) const {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001769 if (!classcode.length()) return true;
1770
James Kuszmaul8e62b022022-03-22 09:33:25 -07001771 std::string code = "";
1772 BeginFile(LastNamespacePart(ns), needs_imports, &code);
1773 code += classcode;
1774
1775 const std::string directories =
1776 parser_.opts.one_file ? path_ : namer_.Directories(ns.components);
1777 EnsureDirExists(directories);
1778
1779 for (size_t i = path_.size() + 1; i != std::string::npos;
1780 i = directories.find(kPathSeparator, i + 1)) {
1781 const std::string init_py =
1782 directories.substr(0, i) + kPathSeparator + "__init__.py";
1783 SaveFile(init_py.c_str(), "", false);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001784 }
1785
James Kuszmaul8e62b022022-03-22 09:33:25 -07001786 const std::string filename = directories + defname;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001787 return SaveFile(filename.c_str(), code, false);
1788 }
Austin Schuh272c6132020-11-14 16:37:52 -08001789
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001790 private:
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001791 const SimpleFloatConstantGenerator float_const_gen_;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001792 const Namer namer_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001793};
1794
1795} // namespace python
1796
1797bool GeneratePython(const Parser &parser, const std::string &path,
1798 const std::string &file_name) {
1799 python::PythonGenerator generator(parser, path, file_name);
1800 return generator.generate();
1801}
1802
1803} // namespace flatbuffers