idl_gen_python.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /*
  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. // independent from idl_parser, since this code is not needed for most clients
  17. #include <string>
  18. #include "flatbuffers/flatbuffers.h"
  19. #include "flatbuffers/idl.h"
  20. #include "flatbuffers/util.h"
  21. #include "flatbuffers/code_generators.h"
  22. namespace flatbuffers {
  23. namespace python {
  24. static std::string GenGetter(const Type &type);
  25. static std::string GenMethod(const FieldDef &field);
  26. static void GenStructBuilder(const StructDef &struct_def,
  27. std::string *code_ptr);
  28. static void GenReceiver(const StructDef &struct_def, std::string *code_ptr);
  29. static std::string GenTypeBasic(const Type &type);
  30. static std::string GenTypeGet(const Type &type);
  31. static std::string TypeName(const FieldDef &field);
  32. // Hardcode spaces per indentation.
  33. const std::string Indent = " ";
  34. // Most field accessors need to retrieve and test the field offset first,
  35. // this is the prefix code for that.
  36. std::string OffsetPrefix(const FieldDef &field) {
  37. return "\n" + Indent + Indent +
  38. "o = flatbuffers.number_types.UOffsetTFlags.py_type" +
  39. "(self._tab.Offset(" +
  40. NumToString(field.value.offset) +
  41. "))\n" + Indent + Indent + "if o != 0:\n";
  42. }
  43. // Begin a class declaration.
  44. static void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
  45. std::string &code = *code_ptr;
  46. code += "class " + struct_def.name + "(object):\n";
  47. code += Indent + "__slots__ = ['_tab']";
  48. code += "\n\n";
  49. }
  50. // Begin enum code with a class declaration.
  51. static void BeginEnum(const std::string class_name, std::string *code_ptr) {
  52. std::string &code = *code_ptr;
  53. code += "class " + class_name + "(object):\n";
  54. }
  55. // A single enum member.
  56. static void EnumMember(const EnumVal ev, std::string *code_ptr) {
  57. std::string &code = *code_ptr;
  58. code += Indent;
  59. code += ev.name;
  60. code += " = ";
  61. code += NumToString(ev.value) + "\n";
  62. }
  63. // End enum code.
  64. static void EndEnum(std::string *code_ptr) {
  65. std::string &code = *code_ptr;
  66. code += "\n";
  67. }
  68. // Initialize a new struct or table from existing data.
  69. static void NewRootTypeFromBuffer(const StructDef &struct_def,
  70. std::string *code_ptr) {
  71. std::string &code = *code_ptr;
  72. code += Indent + "@classmethod\n";
  73. code += Indent + "def GetRootAs";
  74. code += struct_def.name;
  75. code += "(cls, buf, offset):";
  76. code += "\n";
  77. code += Indent + Indent;
  78. code += "n = flatbuffers.encode.Get";
  79. code += "(flatbuffers.packer.uoffset, buf, offset)\n";
  80. code += Indent + Indent + "x = " + struct_def.name + "()\n";
  81. code += Indent + Indent + "x.Init(buf, n + offset)\n";
  82. code += Indent + Indent + "return x\n";
  83. code += "\n";
  84. }
  85. // Initialize an existing object with other data, to avoid an allocation.
  86. static void InitializeExisting(const StructDef &struct_def,
  87. std::string *code_ptr) {
  88. std::string &code = *code_ptr;
  89. GenReceiver(struct_def, code_ptr);
  90. code += "Init(self, buf, pos):\n";
  91. code += Indent + Indent + "self._tab = flatbuffers.table.Table(buf, pos)\n";
  92. code += "\n";
  93. }
  94. // Get the length of a vector.
  95. static void GetVectorLen(const StructDef &struct_def,
  96. const FieldDef &field,
  97. std::string *code_ptr) {
  98. std::string &code = *code_ptr;
  99. GenReceiver(struct_def, code_ptr);
  100. code += MakeCamel(field.name) + "Length(self";
  101. code += "):" + OffsetPrefix(field);
  102. code += Indent + Indent + Indent + "return self._tab.VectorLen(o)\n";
  103. code += Indent + Indent + "return 0\n\n";
  104. }
  105. // Get the value of a struct's scalar.
  106. static void GetScalarFieldOfStruct(const StructDef &struct_def,
  107. const FieldDef &field,
  108. std::string *code_ptr) {
  109. std::string &code = *code_ptr;
  110. std::string getter = GenGetter(field.value.type);
  111. GenReceiver(struct_def, code_ptr);
  112. code += MakeCamel(field.name);
  113. code += "(self): return " + getter;
  114. code += "self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(";
  115. code += NumToString(field.value.offset) + "))\n";
  116. }
  117. // Get the value of a table's scalar.
  118. static void GetScalarFieldOfTable(const StructDef &struct_def,
  119. const FieldDef &field,
  120. std::string *code_ptr) {
  121. std::string &code = *code_ptr;
  122. std::string getter = GenGetter(field.value.type);
  123. GenReceiver(struct_def, code_ptr);
  124. code += MakeCamel(field.name);
  125. code += "(self):";
  126. code += OffsetPrefix(field);
  127. code += Indent + Indent + Indent + "return " + getter;
  128. code += "o + self._tab.Pos)\n";
  129. code += Indent + Indent + "return " + field.value.constant + "\n\n";
  130. }
  131. // Get a struct by initializing an existing struct.
  132. // Specific to Struct.
  133. static void GetStructFieldOfStruct(const StructDef &struct_def,
  134. const FieldDef &field,
  135. std::string *code_ptr) {
  136. std::string &code = *code_ptr;
  137. GenReceiver(struct_def, code_ptr);
  138. code += MakeCamel(field.name);
  139. code += "(self, obj):\n";
  140. code += Indent + Indent + "obj.Init(self._tab.Bytes, self._tab.Pos + ";
  141. code += NumToString(field.value.offset) + ")";
  142. code += "\n" + Indent + Indent + "return obj\n\n";
  143. }
  144. // Get a struct by initializing an existing struct.
  145. // Specific to Table.
  146. static void GetStructFieldOfTable(const StructDef &struct_def,
  147. const FieldDef &field,
  148. std::string *code_ptr) {
  149. std::string &code = *code_ptr;
  150. GenReceiver(struct_def, code_ptr);
  151. code += MakeCamel(field.name);
  152. code += "(self):";
  153. code += OffsetPrefix(field);
  154. if (field.value.type.struct_def->fixed) {
  155. code += Indent + Indent + Indent + "x = o + self._tab.Pos\n";
  156. } else {
  157. code += Indent + Indent + Indent;
  158. code += "x = self._tab.Indirect(o + self._tab.Pos)\n";
  159. }
  160. code += Indent + Indent + Indent;
  161. code += "from ." + TypeName(field) + " import " + TypeName(field) + "\n";
  162. code += Indent + Indent + Indent + "obj = " + TypeName(field) + "()\n";
  163. code += Indent + Indent + Indent + "obj.Init(self._tab.Bytes, x)\n";
  164. code += Indent + Indent + Indent + "return obj\n";
  165. code += Indent + Indent + "return None\n\n";
  166. }
  167. // Get the value of a string.
  168. static void GetStringField(const StructDef &struct_def,
  169. const FieldDef &field,
  170. std::string *code_ptr) {
  171. std::string &code = *code_ptr;
  172. GenReceiver(struct_def, code_ptr);
  173. code += MakeCamel(field.name);
  174. code += "(self):";
  175. code += OffsetPrefix(field);
  176. code += Indent + Indent + Indent + "return " + GenGetter(field.value.type);
  177. code += "o + self._tab.Pos)\n";
  178. code += Indent + Indent + "return \"\"\n\n";
  179. }
  180. // Get the value of a union from an object.
  181. static void GetUnionField(const StructDef &struct_def,
  182. const FieldDef &field,
  183. std::string *code_ptr) {
  184. std::string &code = *code_ptr;
  185. GenReceiver(struct_def, code_ptr);
  186. code += MakeCamel(field.name) + "(self):";
  187. code += OffsetPrefix(field);
  188. // TODO(rw): this works and is not the good way to it:
  189. bool is_native_table = TypeName(field) == "*flatbuffers.Table";
  190. if (is_native_table) {
  191. code += Indent + Indent + Indent + "from flatbuffers.table import Table\n";
  192. } else {
  193. code += Indent + Indent + Indent;
  194. code += "from ." + TypeName(field) + " import " + TypeName(field) + "\n";
  195. }
  196. code += Indent + Indent + Indent + "obj = Table(bytearray(), 0)\n";
  197. code += Indent + Indent + Indent + GenGetter(field.value.type);
  198. code += "obj, o)\n" + Indent + Indent + Indent + "return obj\n";
  199. code += Indent + Indent + "return None\n\n";
  200. }
  201. // Get the value of a vector's struct member.
  202. static void GetMemberOfVectorOfStruct(const StructDef &struct_def,
  203. const FieldDef &field,
  204. std::string *code_ptr) {
  205. std::string &code = *code_ptr;
  206. auto vectortype = field.value.type.VectorType();
  207. GenReceiver(struct_def, code_ptr);
  208. code += MakeCamel(field.name);
  209. code += "(self, j):" + OffsetPrefix(field);
  210. code += Indent + Indent + Indent + "x = self._tab.Vector(o)\n";
  211. code += Indent + Indent + Indent;
  212. code += "x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * ";
  213. code += NumToString(InlineSize(vectortype)) + "\n";
  214. if (!(vectortype.struct_def->fixed)) {
  215. code += Indent + Indent + Indent + "x = self._tab.Indirect(x)\n";
  216. }
  217. code += Indent + Indent + Indent;
  218. code += "from ." + TypeName(field) + " import " + TypeName(field) + "\n";
  219. code += Indent + Indent + Indent + "obj = " + TypeName(field) + "()\n";
  220. code += Indent + Indent + Indent + "obj.Init(self._tab.Bytes, x)\n";
  221. code += Indent + Indent + Indent + "return obj\n";
  222. code += Indent + Indent + "return None\n\n";
  223. }
  224. // Get the value of a vector's non-struct member. Uses a named return
  225. // argument to conveniently set the zero value for the result.
  226. static void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
  227. const FieldDef &field,
  228. std::string *code_ptr) {
  229. std::string &code = *code_ptr;
  230. auto vectortype = field.value.type.VectorType();
  231. GenReceiver(struct_def, code_ptr);
  232. code += MakeCamel(field.name);
  233. code += "(self, j):";
  234. code += OffsetPrefix(field);
  235. code += Indent + Indent + Indent + "a = self._tab.Vector(o)\n";
  236. code += Indent + Indent + Indent;
  237. code += "return " + GenGetter(field.value.type);
  238. code += "a + flatbuffers.number_types.UOffsetTFlags.py_type(j * ";
  239. code += NumToString(InlineSize(vectortype)) + "))\n";
  240. if (vectortype.base_type == BASE_TYPE_STRING) {
  241. code += Indent + Indent + "return \"\"\n";
  242. } else {
  243. code += Indent + Indent + "return 0\n";
  244. }
  245. code += "\n";
  246. }
  247. // Begin the creator function signature.
  248. static void BeginBuilderArgs(const StructDef &struct_def,
  249. std::string *code_ptr) {
  250. std::string &code = *code_ptr;
  251. code += "\n";
  252. code += "def Create" + struct_def.name;
  253. code += "(builder";
  254. }
  255. // Recursively generate arguments for a constructor, to deal with nested
  256. // structs.
  257. static void StructBuilderArgs(const StructDef &struct_def,
  258. const char *nameprefix,
  259. std::string *code_ptr) {
  260. for (auto it = struct_def.fields.vec.begin();
  261. it != struct_def.fields.vec.end();
  262. ++it) {
  263. auto &field = **it;
  264. if (IsStruct(field.value.type)) {
  265. // Generate arguments for a struct inside a struct. To ensure names
  266. // don't clash, and to make it obvious these arguments are constructing
  267. // a nested struct, prefix the name with the field name.
  268. StructBuilderArgs(*field.value.type.struct_def,
  269. (nameprefix + (field.name + "_")).c_str(),
  270. code_ptr);
  271. } else {
  272. std::string &code = *code_ptr;
  273. code += (std::string)", " + nameprefix;
  274. code += MakeCamel(field.name, false);
  275. }
  276. }
  277. }
  278. // End the creator function signature.
  279. static void EndBuilderArgs(std::string *code_ptr) {
  280. std::string &code = *code_ptr;
  281. code += "):\n";
  282. }
  283. // Recursively generate struct construction statements and instert manual
  284. // padding.
  285. static void StructBuilderBody(const StructDef &struct_def,
  286. const char *nameprefix,
  287. std::string *code_ptr) {
  288. std::string &code = *code_ptr;
  289. code += " builder.Prep(" + NumToString(struct_def.minalign) + ", ";
  290. code += NumToString(struct_def.bytesize) + ")\n";
  291. for (auto it = struct_def.fields.vec.rbegin();
  292. it != struct_def.fields.vec.rend();
  293. ++it) {
  294. auto &field = **it;
  295. if (field.padding)
  296. code += " builder.Pad(" + NumToString(field.padding) + ")\n";
  297. if (IsStruct(field.value.type)) {
  298. StructBuilderBody(*field.value.type.struct_def,
  299. (nameprefix + (field.name + "_")).c_str(),
  300. code_ptr);
  301. } else {
  302. code += " builder.Prepend" + GenMethod(field) + "(";
  303. code += nameprefix + MakeCamel(field.name, false) + ")\n";
  304. }
  305. }
  306. }
  307. static void EndBuilderBody(std::string *code_ptr) {
  308. std::string &code = *code_ptr;
  309. code += " return builder.Offset()\n";
  310. }
  311. // Get the value of a table's starting offset.
  312. static void GetStartOfTable(const StructDef &struct_def,
  313. std::string *code_ptr) {
  314. std::string &code = *code_ptr;
  315. code += "def " + struct_def.name + "Start";
  316. code += "(builder): ";
  317. code += "builder.StartObject(";
  318. code += NumToString(struct_def.fields.vec.size());
  319. code += ")\n";
  320. }
  321. // Set the value of a table's field.
  322. static void BuildFieldOfTable(const StructDef &struct_def,
  323. const FieldDef &field,
  324. const size_t offset,
  325. std::string *code_ptr) {
  326. std::string &code = *code_ptr;
  327. code += "def " + struct_def.name + "Add" + MakeCamel(field.name);
  328. code += "(builder, ";
  329. code += MakeCamel(field.name, false);
  330. code += "): ";
  331. code += "builder.Prepend";
  332. code += GenMethod(field) + "Slot(";
  333. code += NumToString(offset) + ", ";
  334. if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
  335. code += "flatbuffers.number_types.UOffsetTFlags.py_type";
  336. code += "(";
  337. code += MakeCamel(field.name, false) + ")";
  338. } else {
  339. code += MakeCamel(field.name, false);
  340. }
  341. code += ", " + field.value.constant;
  342. code += ")\n";
  343. }
  344. // Set the value of one of the members of a table's vector.
  345. static void BuildVectorOfTable(const StructDef &struct_def,
  346. const FieldDef &field,
  347. std::string *code_ptr) {
  348. std::string &code = *code_ptr;
  349. code += "def " + struct_def.name + "Start";
  350. code += MakeCamel(field.name);
  351. code += "Vector(builder, numElems): return builder.StartVector(";
  352. auto vector_type = field.value.type.VectorType();
  353. auto alignment = InlineAlignment(vector_type);
  354. auto elem_size = InlineSize(vector_type);
  355. code += NumToString(elem_size);
  356. code += ", numElems, " + NumToString(alignment);
  357. code += ")\n";
  358. }
  359. // Get the offset of the end of a table.
  360. static void GetEndOffsetOnTable(const StructDef &struct_def,
  361. std::string *code_ptr) {
  362. std::string &code = *code_ptr;
  363. code += "def " + struct_def.name + "End";
  364. code += "(builder): ";
  365. code += "return builder.EndObject()\n";
  366. }
  367. // Generate the receiver for function signatures.
  368. static void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
  369. std::string &code = *code_ptr;
  370. code += Indent + "# " + struct_def.name + "\n";
  371. code += Indent + "def ";
  372. }
  373. // Generate a struct field, conditioned on its child type(s).
  374. static void GenStructAccessor(const StructDef &struct_def,
  375. const FieldDef &field,
  376. std::string *code_ptr) {
  377. GenComment(field.doc_comment, code_ptr, nullptr, "# ");
  378. if (IsScalar(field.value.type.base_type)) {
  379. if (struct_def.fixed) {
  380. GetScalarFieldOfStruct(struct_def, field, code_ptr);
  381. } else {
  382. GetScalarFieldOfTable(struct_def, field, code_ptr);
  383. }
  384. } else {
  385. switch (field.value.type.base_type) {
  386. case BASE_TYPE_STRUCT:
  387. if (struct_def.fixed) {
  388. GetStructFieldOfStruct(struct_def, field, code_ptr);
  389. } else {
  390. GetStructFieldOfTable(struct_def, field, code_ptr);
  391. }
  392. break;
  393. case BASE_TYPE_STRING:
  394. GetStringField(struct_def, field, code_ptr);
  395. break;
  396. case BASE_TYPE_VECTOR: {
  397. auto vectortype = field.value.type.VectorType();
  398. if (vectortype.base_type == BASE_TYPE_STRUCT) {
  399. GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
  400. } else {
  401. GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
  402. }
  403. break;
  404. }
  405. case BASE_TYPE_UNION:
  406. GetUnionField(struct_def, field, code_ptr);
  407. break;
  408. default:
  409. assert(0);
  410. }
  411. }
  412. if (field.value.type.base_type == BASE_TYPE_VECTOR) {
  413. GetVectorLen(struct_def, field, code_ptr);
  414. }
  415. }
  416. // Generate table constructors, conditioned on its members' types.
  417. static void GenTableBuilders(const StructDef &struct_def,
  418. std::string *code_ptr) {
  419. GetStartOfTable(struct_def, code_ptr);
  420. for (auto it = struct_def.fields.vec.begin();
  421. it != struct_def.fields.vec.end();
  422. ++it) {
  423. auto &field = **it;
  424. if (field.deprecated) continue;
  425. auto offset = it - struct_def.fields.vec.begin();
  426. BuildFieldOfTable(struct_def, field, offset, code_ptr);
  427. if (field.value.type.base_type == BASE_TYPE_VECTOR) {
  428. BuildVectorOfTable(struct_def, field, code_ptr);
  429. }
  430. }
  431. GetEndOffsetOnTable(struct_def, code_ptr);
  432. }
  433. // Generate struct or table methods.
  434. static void GenStruct(const StructDef &struct_def,
  435. std::string *code_ptr) {
  436. if (struct_def.generated) return;
  437. GenComment(struct_def.doc_comment, code_ptr, nullptr, "# ");
  438. BeginClass(struct_def, code_ptr);
  439. if (!struct_def.fixed) {
  440. // Generate a special accessor for the table that has been declared as
  441. // the root type.
  442. NewRootTypeFromBuffer(struct_def, code_ptr);
  443. }
  444. // Generate the Init method that sets the field in a pre-existing
  445. // accessor object. This is to allow object reuse.
  446. InitializeExisting(struct_def, code_ptr);
  447. for (auto it = struct_def.fields.vec.begin();
  448. it != struct_def.fields.vec.end();
  449. ++it) {
  450. auto &field = **it;
  451. if (field.deprecated) continue;
  452. GenStructAccessor(struct_def, field, code_ptr);
  453. }
  454. if (struct_def.fixed) {
  455. // create a struct constructor function
  456. GenStructBuilder(struct_def, code_ptr);
  457. } else {
  458. // Create a set of functions that allow table construction.
  459. GenTableBuilders(struct_def, code_ptr);
  460. }
  461. }
  462. // Generate enum declarations.
  463. static void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
  464. if (enum_def.generated) return;
  465. GenComment(enum_def.doc_comment, code_ptr, nullptr, "# ");
  466. BeginEnum(enum_def.name, code_ptr);
  467. for (auto it = enum_def.vals.vec.begin();
  468. it != enum_def.vals.vec.end();
  469. ++it) {
  470. auto &ev = **it;
  471. GenComment(ev.doc_comment, code_ptr, nullptr, "# ");
  472. EnumMember(ev, code_ptr);
  473. }
  474. EndEnum(code_ptr);
  475. }
  476. // Returns the function name that is able to read a value of the given type.
  477. static std::string GenGetter(const Type &type) {
  478. switch (type.base_type) {
  479. case BASE_TYPE_STRING: return "self._tab.String(";
  480. case BASE_TYPE_UNION: return "self._tab.Union(";
  481. case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
  482. default:
  483. return "self._tab.Get(flatbuffers.number_types." + \
  484. MakeCamel(GenTypeGet(type)) + \
  485. "Flags, ";
  486. }
  487. }
  488. // Returns the method name for use with add/put calls.
  489. static std::string GenMethod(const FieldDef &field) {
  490. return IsScalar(field.value.type.base_type)
  491. ? MakeCamel(GenTypeBasic(field.value.type))
  492. : (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
  493. }
  494. static std::string GenTypeBasic(const Type &type) {
  495. static const char *ctypename[] = {
  496. #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
  497. #PTYPE,
  498. FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
  499. #undef FLATBUFFERS_TD
  500. };
  501. return ctypename[type.base_type];
  502. }
  503. static std::string GenTypePointer(const Type &type) {
  504. switch (type.base_type) {
  505. case BASE_TYPE_STRING:
  506. return "string";
  507. case BASE_TYPE_VECTOR:
  508. return GenTypeGet(type.VectorType());
  509. case BASE_TYPE_STRUCT:
  510. return type.struct_def->name;
  511. case BASE_TYPE_UNION:
  512. // fall through
  513. default:
  514. return "*flatbuffers.Table";
  515. }
  516. }
  517. static std::string GenTypeGet(const Type &type) {
  518. return IsScalar(type.base_type)
  519. ? GenTypeBasic(type)
  520. : GenTypePointer(type);
  521. }
  522. static std::string TypeName(const FieldDef &field) {
  523. return GenTypeGet(field.value.type);
  524. }
  525. // Create a struct with a builder and the struct's arguments.
  526. static void GenStructBuilder(const StructDef &struct_def,
  527. std::string *code_ptr) {
  528. BeginBuilderArgs(struct_def, code_ptr);
  529. StructBuilderArgs(struct_def, "", code_ptr);
  530. EndBuilderArgs(code_ptr);
  531. StructBuilderBody(struct_def, "", code_ptr);
  532. EndBuilderBody(code_ptr);
  533. }
  534. class PythonGenerator : public BaseGenerator {
  535. public:
  536. PythonGenerator(const Parser &parser, const std::string &path,
  537. const std::string &file_name)
  538. : BaseGenerator(parser, path, file_name, "" /* not used */,
  539. "" /* not used */){};
  540. bool generate() {
  541. if (!generateEnums()) return false;
  542. if (!generateStructs()) return false;
  543. return true;
  544. }
  545. private:
  546. bool generateEnums() {
  547. for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
  548. ++it) {
  549. auto &enum_def = **it;
  550. std::string enumcode;
  551. GenEnum(enum_def, &enumcode);
  552. if (!SaveType(enum_def, enumcode, false)) return false;
  553. }
  554. return true;
  555. }
  556. bool generateStructs() {
  557. for (auto it = parser_.structs_.vec.begin();
  558. it != parser_.structs_.vec.end(); ++it) {
  559. auto &struct_def = **it;
  560. std::string declcode;
  561. GenStruct(struct_def, &declcode);
  562. if (!SaveType(struct_def, declcode, true)) return false;
  563. }
  564. return true;
  565. }
  566. // Begin by declaring namespace and imports.
  567. void BeginFile(const std::string name_space_name, const bool needs_imports,
  568. std::string *code_ptr) {
  569. std::string &code = *code_ptr;
  570. code = code + "# " + FlatBuffersGeneratedWarning();
  571. code += "# namespace: " + name_space_name + "\n\n";
  572. if (needs_imports) {
  573. code += "import flatbuffers\n\n";
  574. }
  575. }
  576. // Save out the generated code for a Python Table type.
  577. bool SaveType(const Definition &def, const std::string &classcode,
  578. bool needs_imports) {
  579. if (!classcode.length()) return true;
  580. std::string namespace_dir = path_;
  581. auto &namespaces = parser_.namespaces_.back()->components;
  582. for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
  583. if (it != namespaces.begin()) namespace_dir += kPathSeparator;
  584. namespace_dir += *it;
  585. std::string init_py_filename = namespace_dir + "/__init__.py";
  586. SaveFile(init_py_filename.c_str(), "", false);
  587. }
  588. std::string code = "";
  589. BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code);
  590. code += classcode;
  591. std::string filename = NamespaceDir(*def.defined_namespace) +
  592. def.name + ".py";
  593. return SaveFile(filename.c_str(), code, false);
  594. }
  595. };
  596. } // namespace python
  597. bool GeneratePython(const Parser &parser, const std::string &path,
  598. const std::string &file_name) {
  599. python::PythonGenerator generator(parser, path, file_name);
  600. return generator.generate();
  601. }
  602. } // namespace flatbuffers