blob: 51e018a00930740d8c02007b294940ae0a1e0c9a [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
19#include <sstream>
20#include <string>
21
22#include "flatbuffers/code_generators.h"
23#include "flatbuffers/flatbuffers.h"
24#include "flatbuffers/idl.h"
25#include "flatbuffers/util.h"
Austin Schuh2dd86a92022-09-14 21:19:23 -070026#include "idl_namer.h"
Austin Schuhe89fa2d2019-08-14 20:24:23 -070027
28#ifdef _WIN32
29# include <direct.h>
30# define PATH_SEPARATOR "\\"
31# define mkdir(n, m) _mkdir(n)
32#else
33# include <sys/stat.h>
34# define PATH_SEPARATOR "/"
35#endif
36
37namespace flatbuffers {
38
Austin Schuhe89fa2d2019-08-14 20:24:23 -070039namespace go {
40
Austin Schuh2dd86a92022-09-14 21:19:23 -070041namespace {
42
Austin Schuhe89fa2d2019-08-14 20:24:23 -070043// see https://golang.org/ref/spec#Keywords
Austin Schuh2dd86a92022-09-14 21:19:23 -070044static std::set<std::string> GoKeywords() {
James Kuszmaul8e62b022022-03-22 09:33:25 -070045 return {
46 "break", "default", "func", "interface", "select",
47 "case", "defer", "go", "map", "struct",
48 "chan", "else", "goto", "package", "switch",
49 "const", "fallthrough", "if", "range", "type",
50 "continue", "for", "import", "return", "var",
51 };
52}
Austin Schuhe89fa2d2019-08-14 20:24:23 -070053
Austin Schuh2dd86a92022-09-14 21:19:23 -070054static Namer::Config GoDefaultConfig() {
James Kuszmaul8e62b022022-03-22 09:33:25 -070055 // Note that the functions with user defined types in the name use
56 // upper camel case for all but the user defined type itself, which is keep
57 // cased. Despite being a function, we interpret it as a Type.
58 return { /*types=*/Case::kKeep,
59 /*constants=*/Case::kUnknown,
60 /*methods=*/Case::kUpperCamel,
61 /*functions=*/Case::kUpperCamel,
62 /*fields=*/Case::kUpperCamel,
63 /*variables=*/Case::kLowerCamel,
64 /*variants=*/Case::kKeep,
65 /*enum_variant_seperator=*/"", // I.e. Concatenate.
Austin Schuh2dd86a92022-09-14 21:19:23 -070066 /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
James Kuszmaul8e62b022022-03-22 09:33:25 -070067 /*namespaces=*/Case::kKeep,
68 /*namespace_seperator=*/"__",
69 /*object_prefix=*/"",
70 /*object_suffix=*/"T",
71 /*keyword_prefix=*/"",
72 /*keyword_suffix=*/"_",
73 /*filenames=*/Case::kKeep,
74 /*directories=*/Case::kKeep,
75 /*output_path=*/"",
76 /*filename_suffix=*/"",
77 /*filename_extension=*/".go" };
Austin Schuhe89fa2d2019-08-14 20:24:23 -070078}
79
Austin Schuh2dd86a92022-09-14 21:19:23 -070080} // namespace
81
Austin Schuhe89fa2d2019-08-14 20:24:23 -070082class GoGenerator : public BaseGenerator {
83 public:
84 GoGenerator(const Parser &parser, const std::string &path,
85 const std::string &file_name, const std::string &go_namespace)
86 : BaseGenerator(parser, path, file_name, "" /* not used*/,
Austin Schuh272c6132020-11-14 16:37:52 -080087 "" /* not used */, "go"),
James Kuszmaul8e62b022022-03-22 09:33:25 -070088 cur_name_space_(nullptr),
Austin Schuh2dd86a92022-09-14 21:19:23 -070089 namer_(WithFlagOptions(GoDefaultConfig(), parser.opts, path),
90 GoKeywords()) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070091 std::istringstream iss(go_namespace);
92 std::string component;
93 while (std::getline(iss, component, '.')) {
94 go_namespace_.components.push_back(component);
95 }
96 }
97
98 bool generate() {
99 std::string one_file_code;
Austin Schuh272c6132020-11-14 16:37:52 -0800100 bool needs_imports = false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700101 for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
102 ++it) {
103 tracked_imported_namespaces_.clear();
Austin Schuh272c6132020-11-14 16:37:52 -0800104 needs_imports = false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700105 std::string enumcode;
106 GenEnum(**it, &enumcode);
Austin Schuh272c6132020-11-14 16:37:52 -0800107 if ((*it)->is_union && parser_.opts.generate_object_based_api) {
108 GenNativeUnion(**it, &enumcode);
109 GenNativeUnionPack(**it, &enumcode);
110 GenNativeUnionUnPack(**it, &enumcode);
111 needs_imports = true;
112 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700113 if (parser_.opts.one_file) {
114 one_file_code += enumcode;
115 } else {
Austin Schuh272c6132020-11-14 16:37:52 -0800116 if (!SaveType(**it, enumcode, needs_imports, true)) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700117 }
118 }
119
120 for (auto it = parser_.structs_.vec.begin();
121 it != parser_.structs_.vec.end(); ++it) {
122 tracked_imported_namespaces_.clear();
123 std::string declcode;
124 GenStruct(**it, &declcode);
125 if (parser_.opts.one_file) {
126 one_file_code += declcode;
127 } else {
128 if (!SaveType(**it, declcode, true, false)) return false;
129 }
130 }
131
132 if (parser_.opts.one_file) {
133 std::string code = "";
134 const bool is_enum = !parser_.enums_.vec.empty();
135 BeginFile(LastNamespacePart(go_namespace_), true, is_enum, &code);
136 code += one_file_code;
Austin Schuh272c6132020-11-14 16:37:52 -0800137 const std::string filename =
138 GeneratedFileName(path_, file_name_, parser_.opts);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700139 return SaveFile(filename.c_str(), code, false);
140 }
141
142 return true;
143 }
144
145 private:
146 Namespace go_namespace_;
147 Namespace *cur_name_space_;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700148 const IdlNamer namer_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700149
150 struct NamespacePtrLess {
151 bool operator()(const Namespace *a, const Namespace *b) const {
152 return *a < *b;
153 }
154 };
155 std::set<const Namespace *, NamespacePtrLess> tracked_imported_namespaces_;
156
157 // Most field accessors need to retrieve and test the field offset first,
158 // this is the prefix code for that.
159 std::string OffsetPrefix(const FieldDef &field) {
160 return "{\n\to := flatbuffers.UOffsetT(rcv._tab.Offset(" +
161 NumToString(field.value.offset) + "))\n\tif o != 0 {\n";
162 }
163
164 // Begin a class declaration.
165 void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
166 std::string &code = *code_ptr;
167
Austin Schuh2dd86a92022-09-14 21:19:23 -0700168 code += "type " + namer_.Type(struct_def) + " struct {\n\t";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700169
170 // _ is reserved in flatbuffers field names, so no chance of name conflict:
171 code += "_tab ";
172 code += struct_def.fixed ? "flatbuffers.Struct" : "flatbuffers.Table";
173 code += "\n}\n\n";
174 }
175
176 // Construct the name of the type for this enum.
177 std::string GetEnumTypeName(const EnumDef &enum_def) {
Austin Schuh272c6132020-11-14 16:37:52 -0800178 return WrapInNameSpaceAndTrack(enum_def.defined_namespace,
Austin Schuh2dd86a92022-09-14 21:19:23 -0700179 namer_.Type(enum_def));
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700180 }
181
182 // Create a type for the enum values.
183 void GenEnumType(const EnumDef &enum_def, std::string *code_ptr) {
184 std::string &code = *code_ptr;
185 code += "type " + GetEnumTypeName(enum_def) + " ";
186 code += GenTypeBasic(enum_def.underlying_type) + "\n\n";
187 }
188
189 // Begin enum code with a class declaration.
190 void BeginEnum(std::string *code_ptr) {
191 std::string &code = *code_ptr;
192 code += "const (\n";
193 }
194
195 // A single enum member.
196 void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
197 size_t max_name_length, std::string *code_ptr) {
198 std::string &code = *code_ptr;
199 code += "\t";
Austin Schuh2dd86a92022-09-14 21:19:23 -0700200 code += namer_.EnumVariant(enum_def, ev);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700201 code += " ";
202 code += std::string(max_name_length - ev.name.length(), ' ');
203 code += GetEnumTypeName(enum_def);
204 code += " = ";
205 code += enum_def.ToString(ev) + "\n";
206 }
207
208 // End enum code.
209 void EndEnum(std::string *code_ptr) {
210 std::string &code = *code_ptr;
211 code += ")\n\n";
212 }
213
214 // Begin enum name map.
215 void BeginEnumNames(const EnumDef &enum_def, std::string *code_ptr) {
216 std::string &code = *code_ptr;
217 code += "var EnumNames";
218 code += enum_def.name;
219 code += " = map[" + GetEnumTypeName(enum_def) + "]string{\n";
220 }
221
222 // A single enum name member.
223 void EnumNameMember(const EnumDef &enum_def, const EnumVal &ev,
224 size_t max_name_length, std::string *code_ptr) {
225 std::string &code = *code_ptr;
226 code += "\t";
Austin Schuh2dd86a92022-09-14 21:19:23 -0700227 code += namer_.EnumVariant(enum_def, ev);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700228 code += ": ";
229 code += std::string(max_name_length - ev.name.length(), ' ');
230 code += "\"";
231 code += ev.name;
232 code += "\",\n";
233 }
234
235 // End enum name map.
236 void EndEnumNames(std::string *code_ptr) {
237 std::string &code = *code_ptr;
238 code += "}\n\n";
239 }
240
241 // Generate String() method on enum type.
242 void EnumStringer(const EnumDef &enum_def, std::string *code_ptr) {
243 std::string &code = *code_ptr;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700244 const std::string enum_type = namer_.Type(enum_def);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700245 code += "func (v " + enum_type + ") String() string {\n";
246 code += "\tif s, ok := EnumNames" + enum_type + "[v]; ok {\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700247 code += "\t\treturn s\n";
248 code += "\t}\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800249 code += "\treturn \"" + enum_def.name;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700250 code += "(\" + strconv.FormatInt(int64(v), 10) + \")\"\n";
251 code += "}\n\n";
252 }
253
254 // Begin enum value map.
255 void BeginEnumValues(const EnumDef &enum_def, std::string *code_ptr) {
256 std::string &code = *code_ptr;
257 code += "var EnumValues";
Austin Schuh2dd86a92022-09-14 21:19:23 -0700258 code += namer_.Type(enum_def);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700259 code += " = map[string]" + GetEnumTypeName(enum_def) + "{\n";
260 }
261
262 // A single enum value member.
263 void EnumValueMember(const EnumDef &enum_def, const EnumVal &ev,
264 size_t max_name_length, std::string *code_ptr) {
265 std::string &code = *code_ptr;
266 code += "\t\"";
267 code += ev.name;
268 code += "\": ";
269 code += std::string(max_name_length - ev.name.length(), ' ');
Austin Schuh2dd86a92022-09-14 21:19:23 -0700270 code += namer_.EnumVariant(enum_def, ev);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700271 code += ",\n";
272 }
273
274 // End enum value map.
275 void EndEnumValues(std::string *code_ptr) {
276 std::string &code = *code_ptr;
277 code += "}\n\n";
278 }
279
280 // Initialize a new struct or table from existing data.
281 void NewRootTypeFromBuffer(const StructDef &struct_def,
282 std::string *code_ptr) {
283 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700284 const std::string size_prefix[] = { "", "SizePrefixed" };
Austin Schuh2dd86a92022-09-14 21:19:23 -0700285 const std::string struct_type = namer_.Type(struct_def);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700286
Austin Schuh272c6132020-11-14 16:37:52 -0800287 for (int i = 0; i < 2; i++) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700288 code += "func Get" + size_prefix[i] + "RootAs" + struct_type;
Austin Schuh272c6132020-11-14 16:37:52 -0800289 code += "(buf []byte, offset flatbuffers.UOffsetT) ";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700290 code += "*" + struct_type + "";
Austin Schuh272c6132020-11-14 16:37:52 -0800291 code += " {\n";
292 if (i == 0) {
293 code += "\tn := flatbuffers.GetUOffsetT(buf[offset:])\n";
294 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700295 code +=
296 "\tn := "
297 "flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800298 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700299 code += "\tx := &" + struct_type + "{}\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800300 if (i == 0) {
301 code += "\tx.Init(buf, n+offset)\n";
302 } else {
303 code += "\tx.Init(buf, n+offset+flatbuffers.SizeUint32)\n";
304 }
305 code += "\treturn x\n";
306 code += "}\n\n";
307 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700308 }
309
310 // Initialize an existing object with other data, to avoid an allocation.
311 void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) {
312 std::string &code = *code_ptr;
313
314 GenReceiver(struct_def, code_ptr);
315 code += " Init(buf []byte, i flatbuffers.UOffsetT) ";
316 code += "{\n";
317 code += "\trcv._tab.Bytes = buf\n";
318 code += "\trcv._tab.Pos = i\n";
319 code += "}\n\n";
320 }
321
322 // Implement the table accessor
323 void GenTableAccessor(const StructDef &struct_def, std::string *code_ptr) {
324 std::string &code = *code_ptr;
325
326 GenReceiver(struct_def, code_ptr);
327 code += " Table() flatbuffers.Table ";
328 code += "{\n";
329
330 if (struct_def.fixed) {
331 code += "\treturn rcv._tab.Table\n";
332 } else {
333 code += "\treturn rcv._tab\n";
334 }
335 code += "}\n\n";
336 }
337
338 // Get the length of a vector.
339 void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
340 std::string *code_ptr) {
341 std::string &code = *code_ptr;
342
343 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700344 code += " " + namer_.Function(field) + "Length(";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700345 code += ") int " + OffsetPrefix(field);
346 code += "\t\treturn rcv._tab.VectorLen(o)\n\t}\n";
347 code += "\treturn 0\n}\n\n";
348 }
349
350 // Get a [ubyte] vector as a byte slice.
351 void GetUByteSlice(const StructDef &struct_def, const FieldDef &field,
352 std::string *code_ptr) {
353 std::string &code = *code_ptr;
354
355 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700356 code += " " + namer_.Function(field) + "Bytes(";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700357 code += ") []byte " + OffsetPrefix(field);
358 code += "\t\treturn rcv._tab.ByteVector(o + rcv._tab.Pos)\n\t}\n";
359 code += "\treturn nil\n}\n\n";
360 }
361
362 // Get the value of a struct's scalar.
363 void GetScalarFieldOfStruct(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800364 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700365 std::string &code = *code_ptr;
366 std::string getter = GenGetter(field.value.type);
367 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700368 code += " " + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700369 code += "() " + TypeName(field) + " {\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800370 code += "\treturn " +
371 CastToEnum(field.value.type,
372 getter + "(rcv._tab.Pos + flatbuffers.UOffsetT(" +
373 NumToString(field.value.offset) + "))");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700374 code += "\n}\n";
375 }
376
377 // Get the value of a table's scalar.
Austin Schuh272c6132020-11-14 16:37:52 -0800378 void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700379 std::string *code_ptr) {
380 std::string &code = *code_ptr;
381 std::string getter = GenGetter(field.value.type);
382 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700383 code += " " + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700384 code += "() " + TypeName(field) + " ";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700385 code += OffsetPrefix(field);
386 if (field.IsScalarOptional()) {
387 code += "\t\tv := ";
388 } else {
389 code += "\t\treturn ";
390 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700391 code += CastToEnum(field.value.type, getter + "(o + rcv._tab.Pos)");
Austin Schuh2dd86a92022-09-14 21:19:23 -0700392 if (field.IsScalarOptional()) { code += "\n\t\treturn &v"; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700393 code += "\n\t}\n";
394 code += "\treturn " + GenConstant(field) + "\n";
395 code += "}\n\n";
396 }
397
398 // Get a struct by initializing an existing struct.
399 // Specific to Struct.
400 void GetStructFieldOfStruct(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800401 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700402 std::string &code = *code_ptr;
403 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700404 code += " " + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700405 code += "(obj *" + TypeName(field);
406 code += ") *" + TypeName(field);
407 code += " {\n";
408 code += "\tif obj == nil {\n";
409 code += "\t\tobj = new(" + TypeName(field) + ")\n";
410 code += "\t}\n";
411 code += "\tobj.Init(rcv._tab.Bytes, rcv._tab.Pos+";
412 code += NumToString(field.value.offset) + ")";
413 code += "\n\treturn obj\n";
414 code += "}\n";
415 }
416
417 // Get a struct by initializing an existing struct.
418 // Specific to Table.
Austin Schuh272c6132020-11-14 16:37:52 -0800419 void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700420 std::string *code_ptr) {
421 std::string &code = *code_ptr;
422 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700423 code += " " + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700424 code += "(obj *";
425 code += TypeName(field);
426 code += ") *" + TypeName(field) + " " + OffsetPrefix(field);
427 if (field.value.type.struct_def->fixed) {
428 code += "\t\tx := o + rcv._tab.Pos\n";
429 } else {
430 code += "\t\tx := rcv._tab.Indirect(o + rcv._tab.Pos)\n";
431 }
432 code += "\t\tif obj == nil {\n";
433 code += "\t\t\tobj = new(" + TypeName(field) + ")\n";
434 code += "\t\t}\n";
435 code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
436 code += "\t\treturn obj\n\t}\n\treturn nil\n";
437 code += "}\n\n";
438 }
439
440 // Get the value of a string.
Austin Schuh272c6132020-11-14 16:37:52 -0800441 void GetStringField(const StructDef &struct_def, const FieldDef &field,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700442 std::string *code_ptr) {
443 std::string &code = *code_ptr;
444 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700445 code += " " + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700446 code += "() " + TypeName(field) + " ";
447 code += OffsetPrefix(field) + "\t\treturn " + GenGetter(field.value.type);
448 code += "(o + rcv._tab.Pos)\n\t}\n\treturn nil\n";
449 code += "}\n\n";
450 }
451
452 // Get the value of a union from an object.
453 void GetUnionField(const StructDef &struct_def, const FieldDef &field,
454 std::string *code_ptr) {
455 std::string &code = *code_ptr;
456 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700457 code += " " + namer_.Function(field) + "(";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700458 code += "obj " + GenTypePointer(field.value.type) + ") bool ";
459 code += OffsetPrefix(field);
460 code += "\t\t" + GenGetter(field.value.type);
461 code += "(obj, o)\n\t\treturn true\n\t}\n";
462 code += "\treturn false\n";
463 code += "}\n\n";
464 }
465
466 // Get the value of a vector's struct member.
467 void GetMemberOfVectorOfStruct(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800468 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700469 std::string &code = *code_ptr;
470 auto vectortype = field.value.type.VectorType();
471
472 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700473 code += " " + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700474 code += "(obj *" + TypeName(field);
475 code += ", j int) bool " + OffsetPrefix(field);
476 code += "\t\tx := rcv._tab.Vector(o)\n";
477 code += "\t\tx += flatbuffers.UOffsetT(j) * ";
478 code += NumToString(InlineSize(vectortype)) + "\n";
479 if (!(vectortype.struct_def->fixed)) {
480 code += "\t\tx = rcv._tab.Indirect(x)\n";
481 }
482 code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
483 code += "\t\treturn true\n\t}\n";
484 code += "\treturn false\n";
485 code += "}\n\n";
486 }
487
488 // Get the value of a vector's non-struct member.
489 void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
490 const FieldDef &field,
491 std::string *code_ptr) {
492 std::string &code = *code_ptr;
493 auto vectortype = field.value.type.VectorType();
494
495 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700496 code += " " + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700497 code += "(j int) " + TypeName(field) + " ";
498 code += OffsetPrefix(field);
499 code += "\t\ta := rcv._tab.Vector(o)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800500 code += "\t\treturn " +
501 CastToEnum(field.value.type,
502 GenGetter(field.value.type) +
503 "(a + flatbuffers.UOffsetT(j*" +
504 NumToString(InlineSize(vectortype)) + "))");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700505 code += "\n\t}\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800506 if (IsString(vectortype)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700507 code += "\treturn nil\n";
508 } else if (vectortype.base_type == BASE_TYPE_BOOL) {
509 code += "\treturn false\n";
510 } else {
511 code += "\treturn 0\n";
512 }
513 code += "}\n\n";
514 }
515
516 // Begin the creator function signature.
517 void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
518 std::string &code = *code_ptr;
519
520 if (code.substr(code.length() - 2) != "\n\n") {
521 // a previous mutate has not put an extra new line
522 code += "\n";
523 }
524 code += "func Create" + struct_def.name;
525 code += "(builder *flatbuffers.Builder";
526 }
527
528 // Recursively generate arguments for a constructor, to deal with nested
529 // structs.
530 void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix,
531 std::string *code_ptr) {
532 for (auto it = struct_def.fields.vec.begin();
533 it != struct_def.fields.vec.end(); ++it) {
534 auto &field = **it;
535 if (IsStruct(field.value.type)) {
536 // Generate arguments for a struct inside a struct. To ensure names
537 // don't clash, and to make it obvious these arguments are constructing
538 // a nested struct, prefix the name with the field name.
539 StructBuilderArgs(*field.value.type.struct_def,
540 (nameprefix + (field.name + "_")).c_str(), code_ptr);
541 } else {
542 std::string &code = *code_ptr;
543 code += std::string(", ") + nameprefix;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700544 code += namer_.Variable(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700545 code += " " + TypeName(field);
546 }
547 }
548 }
549
550 // End the creator function signature.
551 void EndBuilderArgs(std::string *code_ptr) {
552 std::string &code = *code_ptr;
553 code += ") flatbuffers.UOffsetT {\n";
554 }
555
556 // Recursively generate struct construction statements and instert manual
557 // padding.
Austin Schuh272c6132020-11-14 16:37:52 -0800558 void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
559 std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700560 std::string &code = *code_ptr;
561 code += "\tbuilder.Prep(" + NumToString(struct_def.minalign) + ", ";
562 code += NumToString(struct_def.bytesize) + ")\n";
563 for (auto it = struct_def.fields.vec.rbegin();
564 it != struct_def.fields.vec.rend(); ++it) {
565 auto &field = **it;
566 if (field.padding)
567 code += "\tbuilder.Pad(" + NumToString(field.padding) + ")\n";
568 if (IsStruct(field.value.type)) {
569 StructBuilderBody(*field.value.type.struct_def,
570 (nameprefix + (field.name + "_")).c_str(), code_ptr);
571 } else {
572 code += "\tbuilder.Prepend" + GenMethod(field) + "(";
Austin Schuh272c6132020-11-14 16:37:52 -0800573 code += CastToBaseType(field.value.type,
Austin Schuh2dd86a92022-09-14 21:19:23 -0700574 nameprefix + namer_.Variable(field)) +
Austin Schuh272c6132020-11-14 16:37:52 -0800575 ")\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700576 }
577 }
578 }
579
580 void EndBuilderBody(std::string *code_ptr) {
581 std::string &code = *code_ptr;
582 code += "\treturn builder.Offset()\n";
583 code += "}\n";
584 }
585
586 // Get the value of a table's starting offset.
587 void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
588 std::string &code = *code_ptr;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700589 code += "func " + namer_.Type(struct_def) + "Start";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700590 code += "(builder *flatbuffers.Builder) {\n";
591 code += "\tbuilder.StartObject(";
592 code += NumToString(struct_def.fields.vec.size());
593 code += ")\n}\n";
594 }
595
596 // Set the value of a table's field.
597 void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
598 const size_t offset, std::string *code_ptr) {
599 std::string &code = *code_ptr;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700600 const std::string field_var = namer_.Variable(field);
601 code += "func " + namer_.Type(struct_def) + "Add" + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700602 code += "(builder *flatbuffers.Builder, ";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700603 code += field_var + " ";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700604 if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
605 code += "flatbuffers.UOffsetT";
606 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700607 code += GenTypeGet(field.value.type);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700608 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700609 code += ") {\n\t";
610 code += "builder.Prepend";
611 code += GenMethod(field);
612 if (field.IsScalarOptional()) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700613 code += "(";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700614 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700615 code += "Slot(" + NumToString(offset) + ", ";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700616 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700617 if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
618 code += "flatbuffers.UOffsetT";
619 code += "(" + field_var + ")";
620 } else {
621 code += CastToBaseType(field.value.type, field_var);
622 }
623 if (field.IsScalarOptional()) {
624 code += ")\n";
625 code += "\tbuilder.Slot(" + NumToString(offset);
626 } else {
627 code += ", " + GenConstant(field);
628 }
629 code += ")\n";
630 code += "}\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700631 }
632
633 // Set the value of one of the members of a table's vector.
Austin Schuh272c6132020-11-14 16:37:52 -0800634 void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
635 std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700636 std::string &code = *code_ptr;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700637 code += "func " + namer_.Type(struct_def) + "Start";
638 code += namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700639 code += "Vector(builder *flatbuffers.Builder, numElems int) ";
640 code += "flatbuffers.UOffsetT {\n\treturn builder.StartVector(";
641 auto vector_type = field.value.type.VectorType();
642 auto alignment = InlineAlignment(vector_type);
643 auto elem_size = InlineSize(vector_type);
644 code += NumToString(elem_size);
645 code += ", numElems, " + NumToString(alignment);
646 code += ")\n}\n";
647 }
648
649 // Get the offset of the end of a table.
650 void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
651 std::string &code = *code_ptr;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700652 code += "func " + namer_.Type(struct_def) + "End";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700653 code += "(builder *flatbuffers.Builder) flatbuffers.UOffsetT ";
654 code += "{\n\treturn builder.EndObject()\n}\n";
655 }
656
657 // Generate the receiver for function signatures.
658 void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
659 std::string &code = *code_ptr;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700660 code += "func (rcv *" + namer_.Type(struct_def) + ")";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700661 }
662
663 // Generate a struct field getter, conditioned on its child type(s).
Austin Schuh272c6132020-11-14 16:37:52 -0800664 void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
665 std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700666 GenComment(field.doc_comment, code_ptr, nullptr, "");
667 if (IsScalar(field.value.type.base_type)) {
668 if (struct_def.fixed) {
669 GetScalarFieldOfStruct(struct_def, field, code_ptr);
670 } else {
671 GetScalarFieldOfTable(struct_def, field, code_ptr);
672 }
673 } else {
674 switch (field.value.type.base_type) {
675 case BASE_TYPE_STRUCT:
676 if (struct_def.fixed) {
677 GetStructFieldOfStruct(struct_def, field, code_ptr);
678 } else {
679 GetStructFieldOfTable(struct_def, field, code_ptr);
680 }
681 break;
Austin Schuh272c6132020-11-14 16:37:52 -0800682 case BASE_TYPE_STRING:
683 GetStringField(struct_def, field, code_ptr);
684 break;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700685 case BASE_TYPE_VECTOR: {
686 auto vectortype = field.value.type.VectorType();
687 if (vectortype.base_type == BASE_TYPE_STRUCT) {
688 GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
689 } else {
690 GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
691 }
692 break;
693 }
694 case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
695 default: FLATBUFFERS_ASSERT(0);
696 }
697 }
Austin Schuh272c6132020-11-14 16:37:52 -0800698 if (IsVector(field.value.type)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700699 GetVectorLen(struct_def, field, code_ptr);
700 if (field.value.type.element == BASE_TYPE_UCHAR) {
701 GetUByteSlice(struct_def, field, code_ptr);
702 }
703 }
704 }
705
706 // Mutate the value of a struct's scalar.
707 void MutateScalarFieldOfStruct(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800708 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700709 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700710 std::string setter =
711 "rcv._tab.Mutate" + namer_.Method(GenTypeBasic(field.value.type));
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700712 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700713 code += " Mutate" + namer_.Function(field);
714 code +=
715 "(n " + GenTypeGet(field.value.type) + ") bool {\n\treturn " + setter;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700716 code += "(rcv._tab.Pos+flatbuffers.UOffsetT(";
717 code += NumToString(field.value.offset) + "), ";
718 code += CastToBaseType(field.value.type, "n") + ")\n}\n\n";
719 }
720
721 // Mutate the value of a table's scalar.
722 void MutateScalarFieldOfTable(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800723 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700724 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700725 std::string setter = "rcv._tab.Mutate" +
726 namer_.Method(GenTypeBasic(field.value.type)) + "Slot";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700727 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700728 code += " Mutate" + namer_.Function(field);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700729 code += "(n " + GenTypeGet(field.value.type) + ") bool {\n\treturn ";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700730 code += setter + "(" + NumToString(field.value.offset) + ", ";
731 code += CastToBaseType(field.value.type, "n") + ")\n";
732 code += "}\n\n";
733 }
734
735 // Mutate an element of a vector of scalars.
736 void MutateElementOfVectorOfNonStruct(const StructDef &struct_def,
737 const FieldDef &field,
738 std::string *code_ptr) {
739 std::string &code = *code_ptr;
740 auto vectortype = field.value.type.VectorType();
James Kuszmaul8e62b022022-03-22 09:33:25 -0700741 std::string setter =
742 "rcv._tab.Mutate" + namer_.Method(GenTypeBasic(vectortype));
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700743 GenReceiver(struct_def, code_ptr);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700744 code += " Mutate" + namer_.Function(field);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700745 code += "(j int, n " + TypeName(field) + ") bool ";
746 code += OffsetPrefix(field);
747 code += "\t\ta := rcv._tab.Vector(o)\n";
748 code += "\t\treturn " + setter + "(";
749 code += "a+flatbuffers.UOffsetT(j*";
750 code += NumToString(InlineSize(vectortype)) + "), ";
751 code += CastToBaseType(vectortype, "n") + ")\n";
752 code += "\t}\n";
753 code += "\treturn false\n";
754 code += "}\n\n";
755 }
756
757 // Generate a struct field setter, conditioned on its child type(s).
758 void GenStructMutator(const StructDef &struct_def, const FieldDef &field,
759 std::string *code_ptr) {
760 GenComment(field.doc_comment, code_ptr, nullptr, "");
761 if (IsScalar(field.value.type.base_type)) {
762 if (struct_def.fixed) {
763 MutateScalarFieldOfStruct(struct_def, field, code_ptr);
764 } else {
765 MutateScalarFieldOfTable(struct_def, field, code_ptr);
766 }
Austin Schuh272c6132020-11-14 16:37:52 -0800767 } else if (IsVector(field.value.type)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700768 if (IsScalar(field.value.type.element)) {
769 MutateElementOfVectorOfNonStruct(struct_def, field, code_ptr);
770 }
771 }
772 }
773
774 // Generate table constructors, conditioned on its members' types.
775 void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
776 GetStartOfTable(struct_def, code_ptr);
777
778 for (auto it = struct_def.fields.vec.begin();
779 it != struct_def.fields.vec.end(); ++it) {
780 auto &field = **it;
781 if (field.deprecated) continue;
782
783 auto offset = it - struct_def.fields.vec.begin();
784 BuildFieldOfTable(struct_def, field, offset, code_ptr);
Austin Schuh272c6132020-11-14 16:37:52 -0800785 if (IsVector(field.value.type)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700786 BuildVectorOfTable(struct_def, field, code_ptr);
787 }
788 }
789
790 GetEndOffsetOnTable(struct_def, code_ptr);
791 }
792
793 // Generate struct or table methods.
794 void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
795 if (struct_def.generated) return;
796
797 cur_name_space_ = struct_def.defined_namespace;
798
799 GenComment(struct_def.doc_comment, code_ptr, nullptr);
Austin Schuh272c6132020-11-14 16:37:52 -0800800 if (parser_.opts.generate_object_based_api) {
801 GenNativeStruct(struct_def, code_ptr);
802 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700803 BeginClass(struct_def, code_ptr);
804 if (!struct_def.fixed) {
805 // Generate a special accessor for the table that has been declared as
806 // the root type.
807 NewRootTypeFromBuffer(struct_def, code_ptr);
808 }
809 // Generate the Init method that sets the field in a pre-existing
810 // accessor object. This is to allow object reuse.
811 InitializeExisting(struct_def, code_ptr);
812 // Generate _tab accessor
813 GenTableAccessor(struct_def, code_ptr);
814
815 // Generate struct fields accessors
816 for (auto it = struct_def.fields.vec.begin();
817 it != struct_def.fields.vec.end(); ++it) {
818 auto &field = **it;
819 if (field.deprecated) continue;
820
821 GenStructAccessor(struct_def, field, code_ptr);
822 GenStructMutator(struct_def, field, code_ptr);
823 }
824
825 // Generate builders
826 if (struct_def.fixed) {
827 // create a struct constructor function
828 GenStructBuilder(struct_def, code_ptr);
829 } else {
830 // Create a set of functions that allow table construction.
831 GenTableBuilders(struct_def, code_ptr);
832 }
833 }
834
Austin Schuh272c6132020-11-14 16:37:52 -0800835 void GenNativeStruct(const StructDef &struct_def, std::string *code_ptr) {
836 std::string &code = *code_ptr;
837
838 code += "type " + NativeName(struct_def) + " struct {\n";
839 for (auto it = struct_def.fields.vec.begin();
840 it != struct_def.fields.vec.end(); ++it) {
841 const FieldDef &field = **it;
842 if (field.deprecated) continue;
843 if (IsScalar(field.value.type.base_type) &&
844 field.value.type.enum_def != nullptr &&
845 field.value.type.enum_def->is_union)
846 continue;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700847 code += "\t" + namer_.Field(field) + " ";
848 if (field.IsScalarOptional()) { code += "*"; }
849 code += NativeType(field.value.type) + " `json:\"" + field.name + "\"`" +
850 "\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800851 }
852 code += "}\n\n";
853
854 if (!struct_def.fixed) {
855 GenNativeTablePack(struct_def, code_ptr);
856 GenNativeTableUnPack(struct_def, code_ptr);
857 } else {
858 GenNativeStructPack(struct_def, code_ptr);
859 GenNativeStructUnPack(struct_def, code_ptr);
860 }
861 }
862
863 void GenNativeUnion(const EnumDef &enum_def, std::string *code_ptr) {
864 std::string &code = *code_ptr;
865 code += "type " + NativeName(enum_def) + " struct {\n";
Austin Schuh2dd86a92022-09-14 21:19:23 -0700866 code += "\tType " + namer_.Type(enum_def) + "\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800867 code += "\tValue interface{}\n";
868 code += "}\n\n";
869 }
870
871 void GenNativeUnionPack(const EnumDef &enum_def, std::string *code_ptr) {
872 std::string &code = *code_ptr;
873 code += "func (t *" + NativeName(enum_def) +
874 ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
875 code += "\tif t == nil {\n\t\treturn 0\n\t}\n";
876
877 code += "\tswitch t.Type {\n";
878 for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
879 ++it2) {
880 const EnumVal &ev = **it2;
881 if (ev.IsZero()) continue;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700882 code += "\tcase " + namer_.EnumVariant(enum_def, ev) + ":\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800883 code += "\t\treturn t.Value.(" + NativeType(ev.union_type) +
884 ").Pack(builder)\n";
885 }
886 code += "\t}\n";
887 code += "\treturn 0\n";
888 code += "}\n\n";
889 }
890
891 void GenNativeUnionUnPack(const EnumDef &enum_def, std::string *code_ptr) {
892 std::string &code = *code_ptr;
893
Austin Schuh2dd86a92022-09-14 21:19:23 -0700894 code += "func (rcv " + namer_.Type(enum_def) +
Austin Schuh272c6132020-11-14 16:37:52 -0800895 ") UnPack(table flatbuffers.Table) *" + NativeName(enum_def) +
896 " {\n";
897 code += "\tswitch rcv {\n";
898
899 for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
900 ++it2) {
901 const EnumVal &ev = **it2;
902 if (ev.IsZero()) continue;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700903 code += "\tcase " + namer_.EnumVariant(enum_def, ev) + ":\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800904 code += "\t\tx := " + ev.union_type.struct_def->name + "{_tab: table}\n";
905
906 code += "\t\treturn &" +
907 WrapInNameSpaceAndTrack(enum_def.defined_namespace,
908 NativeName(enum_def)) +
Austin Schuh2dd86a92022-09-14 21:19:23 -0700909 "{ Type: " + namer_.EnumVariant(enum_def, ev) +
James Kuszmaul8e62b022022-03-22 09:33:25 -0700910 ", Value: x.UnPack() }\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800911 }
912 code += "\t}\n";
913 code += "\treturn nil\n";
914 code += "}\n\n";
915 }
916
917 void GenNativeTablePack(const StructDef &struct_def, std::string *code_ptr) {
918 std::string &code = *code_ptr;
Austin Schuh2dd86a92022-09-14 21:19:23 -0700919 const std::string struct_type = namer_.Type(struct_def);
Austin Schuh272c6132020-11-14 16:37:52 -0800920
921 code += "func (t *" + NativeName(struct_def) +
922 ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
923 code += "\tif t == nil { return 0 }\n";
924 for (auto it = struct_def.fields.vec.begin();
925 it != struct_def.fields.vec.end(); ++it) {
926 const FieldDef &field = **it;
927 if (field.deprecated) continue;
928 if (IsScalar(field.value.type.base_type)) continue;
929
Austin Schuh2dd86a92022-09-14 21:19:23 -0700930 const std::string field_field = namer_.Field(field);
931 const std::string field_var = namer_.Variable(field);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700932 const std::string offset = field_var + "Offset";
Austin Schuh272c6132020-11-14 16:37:52 -0800933
934 if (IsString(field.value.type)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700935 code +=
936 "\t" + offset + " := builder.CreateString(t." + field_field + ")\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800937 } else if (IsVector(field.value.type) &&
938 field.value.type.element == BASE_TYPE_UCHAR &&
939 field.value.type.enum_def == nullptr) {
940 code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700941 code += "\tif t." + field_field + " != nil {\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800942 code += "\t\t" + offset + " = builder.CreateByteString(t." +
James Kuszmaul8e62b022022-03-22 09:33:25 -0700943 field_field + ")\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800944 code += "\t}\n";
945 } else if (IsVector(field.value.type)) {
946 code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700947 code += "\tif t." + field_field + " != nil {\n";
948 std::string length = field_var + "Length";
949 std::string offsets = field_var + "Offsets";
950 code += "\t\t" + length + " := len(t." + field_field + ")\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800951 if (field.value.type.element == BASE_TYPE_STRING) {
952 code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
953 length + ")\n";
954 code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
955 code += "\t\t\t" + offsets + "[j] = builder.CreateString(t." +
James Kuszmaul8e62b022022-03-22 09:33:25 -0700956 field_field + "[j])\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800957 code += "\t\t}\n";
958 } else if (field.value.type.element == BASE_TYPE_STRUCT &&
959 !field.value.type.struct_def->fixed) {
960 code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
961 length + ")\n";
962 code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700963 code += "\t\t\t" + offsets + "[j] = t." + field_field +
Austin Schuh272c6132020-11-14 16:37:52 -0800964 "[j].Pack(builder)\n";
965 code += "\t\t}\n";
966 }
Austin Schuh2dd86a92022-09-14 21:19:23 -0700967 code += "\t\t" + struct_type + "Start" + namer_.Function(field) +
Austin Schuh272c6132020-11-14 16:37:52 -0800968 "Vector(builder, " + length + ")\n";
969 code += "\t\tfor j := " + length + " - 1; j >= 0; j-- {\n";
970 if (IsScalar(field.value.type.element)) {
971 code += "\t\t\tbuilder.Prepend" +
James Kuszmaul8e62b022022-03-22 09:33:25 -0700972 namer_.Method(GenTypeBasic(field.value.type.VectorType())) +
973 "(" +
Austin Schuh272c6132020-11-14 16:37:52 -0800974 CastToBaseType(field.value.type.VectorType(),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700975 "t." + field_field + "[j]") +
Austin Schuh272c6132020-11-14 16:37:52 -0800976 ")\n";
977 } else if (field.value.type.element == BASE_TYPE_STRUCT &&
978 field.value.type.struct_def->fixed) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700979 code += "\t\t\tt." + field_field + "[j].Pack(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800980 } else {
981 code += "\t\t\tbuilder.PrependUOffsetT(" + offsets + "[j])\n";
982 }
983 code += "\t\t}\n";
984 code += "\t\t" + offset + " = builder.EndVector(" + length + ")\n";
985 code += "\t}\n";
986 } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
987 if (field.value.type.struct_def->fixed) continue;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700988 code += "\t" + offset + " := t." + field_field + ".Pack(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800989 } else if (field.value.type.base_type == BASE_TYPE_UNION) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700990 code += "\t" + offset + " := t." + field_field + ".Pack(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800991 code += "\t\n";
992 } else {
993 FLATBUFFERS_ASSERT(0);
994 }
995 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700996 code += "\t" + struct_type + "Start(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800997 for (auto it = struct_def.fields.vec.begin();
998 it != struct_def.fields.vec.end(); ++it) {
999 const FieldDef &field = **it;
1000 if (field.deprecated) continue;
Austin Schuh2dd86a92022-09-14 21:19:23 -07001001 const std::string field_field = namer_.Field(field);
1002 const std::string field_fn = namer_.Function(field);
1003 const std::string offset = namer_.Variable(field) + "Offset";
Austin Schuh272c6132020-11-14 16:37:52 -08001004
Austin Schuh272c6132020-11-14 16:37:52 -08001005 if (IsScalar(field.value.type.base_type)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001006 std::string prefix;
1007 if (field.IsScalarOptional()) {
1008 code += "\tif t." + field_field + " != nil {\n\t";
1009 prefix = "*";
1010 }
Austin Schuh272c6132020-11-14 16:37:52 -08001011 if (field.value.type.enum_def == nullptr ||
1012 !field.value.type.enum_def->is_union) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001013 code += "\t" + struct_type + "Add" + field_fn + "(builder, " +
1014 prefix + "t." + field_field + ")\n";
1015 }
Austin Schuh2dd86a92022-09-14 21:19:23 -07001016 if (field.IsScalarOptional()) { code += "\t}\n"; }
Austin Schuh272c6132020-11-14 16:37:52 -08001017 } else {
1018 if (field.value.type.base_type == BASE_TYPE_STRUCT &&
1019 field.value.type.struct_def->fixed) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001020 code += "\t" + offset + " := t." + field_field + ".Pack(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001021 } else if (field.value.type.enum_def != nullptr &&
1022 field.value.type.enum_def->is_union) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001023 code += "\tif t." + field_field + " != nil {\n";
1024 code += "\t\t" + struct_type + "Add" +
1025 namer_.Method(field.name + UnionTypeFieldSuffix()) +
1026 "(builder, t." + field_field + ".Type)\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001027 code += "\t}\n";
1028 }
James Kuszmaul8e62b022022-03-22 09:33:25 -07001029 code += "\t" + struct_type + "Add" + field_fn + "(builder, " + offset +
1030 ")\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001031 }
1032 }
James Kuszmaul8e62b022022-03-22 09:33:25 -07001033 code += "\treturn " + struct_type + "End(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001034 code += "}\n\n";
1035 }
1036
1037 void GenNativeTableUnPack(const StructDef &struct_def,
1038 std::string *code_ptr) {
1039 std::string &code = *code_ptr;
Austin Schuh2dd86a92022-09-14 21:19:23 -07001040 const std::string struct_type = namer_.Type(struct_def);
Austin Schuh272c6132020-11-14 16:37:52 -08001041
James Kuszmaul8e62b022022-03-22 09:33:25 -07001042 code += "func (rcv *" + struct_type + ") UnPackTo(t *" +
Austin Schuh272c6132020-11-14 16:37:52 -08001043 NativeName(struct_def) + ") {\n";
1044 for (auto it = struct_def.fields.vec.begin();
1045 it != struct_def.fields.vec.end(); ++it) {
1046 const FieldDef &field = **it;
1047 if (field.deprecated) continue;
Austin Schuh2dd86a92022-09-14 21:19:23 -07001048 const std::string field_field = namer_.Field(field);
1049 const std::string field_var = namer_.Variable(field);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001050 const std::string length = field_var + "Length";
Austin Schuh272c6132020-11-14 16:37:52 -08001051 if (IsScalar(field.value.type.base_type)) {
1052 if (field.value.type.enum_def != nullptr &&
1053 field.value.type.enum_def->is_union)
1054 continue;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001055 code += "\tt." + field_field + " = rcv." + field_field + "()\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001056 } else if (IsString(field.value.type)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001057 code += "\tt." + field_field + " = string(rcv." + field_field + "())\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001058 } else if (IsVector(field.value.type) &&
1059 field.value.type.element == BASE_TYPE_UCHAR &&
1060 field.value.type.enum_def == nullptr) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001061 code += "\tt." + field_field + " = rcv." + field_field + "Bytes()\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001062 } else if (IsVector(field.value.type)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001063 code += "\t" + length + " := rcv." + field_field + "Length()\n";
1064 code += "\tt." + field_field + " = make(" +
Austin Schuh272c6132020-11-14 16:37:52 -08001065 NativeType(field.value.type) + ", " + length + ")\n";
1066 code += "\tfor j := 0; j < " + length + "; j++ {\n";
1067 if (field.value.type.element == BASE_TYPE_STRUCT) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001068 code += "\t\tx := " +
1069 WrapInNameSpaceAndTrack(*field.value.type.struct_def) +
1070 "{}\n";
1071 code += "\t\trcv." + field_field + "(&x, j)\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001072 }
James Kuszmaul8e62b022022-03-22 09:33:25 -07001073 code += "\t\tt." + field_field + "[j] = ";
Austin Schuh272c6132020-11-14 16:37:52 -08001074 if (IsScalar(field.value.type.element)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001075 code += "rcv." + field_field + "(j)";
Austin Schuh272c6132020-11-14 16:37:52 -08001076 } else if (field.value.type.element == BASE_TYPE_STRING) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001077 code += "string(rcv." + field_field + "(j))";
Austin Schuh272c6132020-11-14 16:37:52 -08001078 } else if (field.value.type.element == BASE_TYPE_STRUCT) {
1079 code += "x.UnPack()";
1080 } else {
1081 // TODO(iceboy): Support vector of unions.
1082 FLATBUFFERS_ASSERT(0);
1083 }
1084 code += "\n";
1085 code += "\t}\n";
1086 } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
Austin Schuh272c6132020-11-14 16:37:52 -08001087 code +=
James Kuszmaul8e62b022022-03-22 09:33:25 -07001088 "\tt." + field_field + " = rcv." + field_field + "(nil).UnPack()\n";
1089 } else if (field.value.type.base_type == BASE_TYPE_UNION) {
1090 const std::string field_table = field_var + "Table";
1091 code += "\t" + field_table + " := flatbuffers.Table{}\n";
Austin Schuh2dd86a92022-09-14 21:19:23 -07001092 code +=
1093 "\tif rcv." + namer_.Method(field) + "(&" + field_table + ") {\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001094 code += "\t\tt." + field_field + " = rcv." +
1095 namer_.Method(field.name + UnionTypeFieldSuffix()) +
1096 "().UnPack(" + field_table + ")\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001097 code += "\t}\n";
1098 } else {
1099 FLATBUFFERS_ASSERT(0);
1100 }
1101 }
1102 code += "}\n\n";
1103
James Kuszmaul8e62b022022-03-22 09:33:25 -07001104 code += "func (rcv *" + struct_type + ") UnPack() *" +
Austin Schuh272c6132020-11-14 16:37:52 -08001105 NativeName(struct_def) + " {\n";
1106 code += "\tif rcv == nil { return nil }\n";
1107 code += "\tt := &" + NativeName(struct_def) + "{}\n";
1108 code += "\trcv.UnPackTo(t)\n";
1109 code += "\treturn t\n";
1110 code += "}\n\n";
1111 }
1112
1113 void GenNativeStructPack(const StructDef &struct_def, std::string *code_ptr) {
1114 std::string &code = *code_ptr;
1115
1116 code += "func (t *" + NativeName(struct_def) +
1117 ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
1118 code += "\tif t == nil { return 0 }\n";
Austin Schuh2dd86a92022-09-14 21:19:23 -07001119 code += "\treturn Create" + namer_.Type(struct_def) + "(builder";
Austin Schuh272c6132020-11-14 16:37:52 -08001120 StructPackArgs(struct_def, "", code_ptr);
1121 code += ")\n";
1122 code += "}\n";
1123 }
1124
1125 void StructPackArgs(const StructDef &struct_def, const char *nameprefix,
1126 std::string *code_ptr) {
1127 std::string &code = *code_ptr;
1128 for (auto it = struct_def.fields.vec.begin();
1129 it != struct_def.fields.vec.end(); ++it) {
1130 const FieldDef &field = **it;
1131 if (field.value.type.base_type == BASE_TYPE_STRUCT) {
1132 StructPackArgs(*field.value.type.struct_def,
Austin Schuh2dd86a92022-09-14 21:19:23 -07001133 (nameprefix + namer_.Field(field) + ".").c_str(),
Austin Schuh272c6132020-11-14 16:37:52 -08001134 code_ptr);
1135 } else {
Austin Schuh2dd86a92022-09-14 21:19:23 -07001136 code += std::string(", t.") + nameprefix + namer_.Field(field);
Austin Schuh272c6132020-11-14 16:37:52 -08001137 }
1138 }
1139 }
1140
1141 void GenNativeStructUnPack(const StructDef &struct_def,
1142 std::string *code_ptr) {
1143 std::string &code = *code_ptr;
1144
Austin Schuh2dd86a92022-09-14 21:19:23 -07001145 code += "func (rcv *" + namer_.Type(struct_def) + ") UnPackTo(t *" +
Austin Schuh272c6132020-11-14 16:37:52 -08001146 NativeName(struct_def) + ") {\n";
1147 for (auto it = struct_def.fields.vec.begin();
1148 it != struct_def.fields.vec.end(); ++it) {
1149 const FieldDef &field = **it;
1150 if (field.value.type.base_type == BASE_TYPE_STRUCT) {
Austin Schuh2dd86a92022-09-14 21:19:23 -07001151 code += "\tt." + namer_.Field(field) + " = rcv." +
1152 namer_.Method(field) + "(nil).UnPack()\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001153 } else {
Austin Schuh2dd86a92022-09-14 21:19:23 -07001154 code += "\tt." + namer_.Field(field) + " = rcv." +
1155 namer_.Method(field) + "()\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001156 }
1157 }
1158 code += "}\n\n";
1159
Austin Schuh2dd86a92022-09-14 21:19:23 -07001160 code += "func (rcv *" + namer_.Type(struct_def) + ") UnPack() *" +
Austin Schuh272c6132020-11-14 16:37:52 -08001161 NativeName(struct_def) + " {\n";
1162 code += "\tif rcv == nil { return nil }\n";
1163 code += "\tt := &" + NativeName(struct_def) + "{}\n";
1164 code += "\trcv.UnPackTo(t)\n";
1165 code += "\treturn t\n";
1166 code += "}\n\n";
1167 }
1168
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001169 // Generate enum declarations.
1170 void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
1171 if (enum_def.generated) return;
1172
1173 auto max_name_length = MaxNameLength(enum_def);
1174 cur_name_space_ = enum_def.defined_namespace;
1175
1176 GenComment(enum_def.doc_comment, code_ptr, nullptr);
1177 GenEnumType(enum_def, code_ptr);
1178 BeginEnum(code_ptr);
1179 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
Austin Schuh272c6132020-11-14 16:37:52 -08001180 const EnumVal &ev = **it;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001181 GenComment(ev.doc_comment, code_ptr, nullptr, "\t");
1182 EnumMember(enum_def, ev, max_name_length, code_ptr);
1183 }
1184 EndEnum(code_ptr);
1185
1186 BeginEnumNames(enum_def, code_ptr);
1187 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
Austin Schuh272c6132020-11-14 16:37:52 -08001188 const EnumVal &ev = **it;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001189 EnumNameMember(enum_def, ev, max_name_length, code_ptr);
1190 }
1191 EndEnumNames(code_ptr);
1192
1193 BeginEnumValues(enum_def, code_ptr);
Austin Schuh272c6132020-11-14 16:37:52 -08001194 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001195 auto &ev = **it;
1196 EnumValueMember(enum_def, ev, max_name_length, code_ptr);
1197 }
1198 EndEnumValues(code_ptr);
1199
1200 EnumStringer(enum_def, code_ptr);
1201 }
1202
1203 // Returns the function name that is able to read a value of the given type.
1204 std::string GenGetter(const Type &type) {
1205 switch (type.base_type) {
1206 case BASE_TYPE_STRING: return "rcv._tab.ByteVector";
1207 case BASE_TYPE_UNION: return "rcv._tab.Union";
1208 case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
James Kuszmaul8e62b022022-03-22 09:33:25 -07001209 default: return "rcv._tab.Get" + namer_.Function(GenTypeBasic(type));
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001210 }
1211 }
1212
1213 // Returns the method name for use with add/put calls.
1214 std::string GenMethod(const FieldDef &field) {
1215 return IsScalar(field.value.type.base_type)
James Kuszmaul8e62b022022-03-22 09:33:25 -07001216 ? namer_.Method(GenTypeBasic(field.value.type))
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001217 : (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
1218 }
1219
1220 std::string GenTypeBasic(const Type &type) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001221 // clang-format off
Austin Schuh272c6132020-11-14 16:37:52 -08001222 static const char *ctypename[] = {
1223 #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, ...) \
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001224 #GTYPE,
1225 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
1226 #undef FLATBUFFERS_TD
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001227 };
Austin Schuh272c6132020-11-14 16:37:52 -08001228 // clang-format on
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001229 return ctypename[type.base_type];
1230 }
1231
1232 std::string GenTypePointer(const Type &type) {
1233 switch (type.base_type) {
1234 case BASE_TYPE_STRING: return "[]byte";
1235 case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
1236 case BASE_TYPE_STRUCT: return WrapInNameSpaceAndTrack(*type.struct_def);
1237 case BASE_TYPE_UNION:
1238 // fall through
1239 default: return "*flatbuffers.Table";
1240 }
1241 }
1242
1243 std::string GenTypeGet(const Type &type) {
Austin Schuh272c6132020-11-14 16:37:52 -08001244 if (type.enum_def != nullptr) { return GetEnumTypeName(*type.enum_def); }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001245 return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
1246 }
1247
1248 std::string TypeName(const FieldDef &field) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001249 std::string prefix;
Austin Schuh2dd86a92022-09-14 21:19:23 -07001250 if (field.IsScalarOptional()) { prefix = "*"; }
James Kuszmaul8e62b022022-03-22 09:33:25 -07001251 return prefix + GenTypeGet(field.value.type);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001252 }
1253
1254 // If type is an enum, returns value with a cast to the enum type, otherwise
1255 // returns value as-is.
1256 std::string CastToEnum(const Type &type, std::string value) {
1257 if (type.enum_def == nullptr) {
1258 return value;
1259 } else {
1260 return GenTypeGet(type) + "(" + value + ")";
1261 }
1262 }
1263
1264 // If type is an enum, returns value with a cast to the enum base type,
1265 // otherwise returns value as-is.
1266 std::string CastToBaseType(const Type &type, std::string value) {
1267 if (type.enum_def == nullptr) {
1268 return value;
1269 } else {
1270 return GenTypeBasic(type) + "(" + value + ")";
1271 }
1272 }
1273
1274 std::string GenConstant(const FieldDef &field) {
Austin Schuh2dd86a92022-09-14 21:19:23 -07001275 if (field.IsScalarOptional()) { return "nil"; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001276 switch (field.value.type.base_type) {
Austin Schuh272c6132020-11-14 16:37:52 -08001277 case BASE_TYPE_BOOL:
1278 return field.value.constant == "0" ? "false" : "true";
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001279 default: return field.value.constant;
1280 }
1281 }
1282
James Kuszmaul8e62b022022-03-22 09:33:25 -07001283 std::string NativeName(const StructDef &struct_def) const {
Austin Schuh2dd86a92022-09-14 21:19:23 -07001284 return namer_.ObjectType(struct_def);
Austin Schuh272c6132020-11-14 16:37:52 -08001285 }
1286
James Kuszmaul8e62b022022-03-22 09:33:25 -07001287 std::string NativeName(const EnumDef &enum_def) const {
Austin Schuh2dd86a92022-09-14 21:19:23 -07001288 return namer_.ObjectType(enum_def);
Austin Schuh272c6132020-11-14 16:37:52 -08001289 }
1290
1291 std::string NativeType(const Type &type) {
1292 if (IsScalar(type.base_type)) {
1293 if (type.enum_def == nullptr) {
1294 return GenTypeBasic(type);
1295 } else {
1296 return GetEnumTypeName(*type.enum_def);
1297 }
1298 } else if (IsString(type)) {
1299 return "string";
1300 } else if (IsVector(type)) {
1301 return "[]" + NativeType(type.VectorType());
1302 } else if (type.base_type == BASE_TYPE_STRUCT) {
1303 return "*" + WrapInNameSpaceAndTrack(type.struct_def->defined_namespace,
1304 NativeName(*type.struct_def));
1305 } else if (type.base_type == BASE_TYPE_UNION) {
1306 return "*" + WrapInNameSpaceAndTrack(type.enum_def->defined_namespace,
1307 NativeName(*type.enum_def));
1308 }
1309 FLATBUFFERS_ASSERT(0);
1310 return std::string();
1311 }
1312
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001313 // Create a struct with a builder and the struct's arguments.
1314 void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
1315 BeginBuilderArgs(struct_def, code_ptr);
1316 StructBuilderArgs(struct_def, "", code_ptr);
1317 EndBuilderArgs(code_ptr);
1318
1319 StructBuilderBody(struct_def, "", code_ptr);
1320 EndBuilderBody(code_ptr);
1321 }
1322 // Begin by declaring namespace and imports.
1323 void BeginFile(const std::string &name_space_name, const bool needs_imports,
1324 const bool is_enum, std::string *code_ptr) {
1325 std::string &code = *code_ptr;
Austin Schuh272c6132020-11-14 16:37:52 -08001326 code = code +
1327 "// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001328 code += "package " + name_space_name + "\n\n";
1329 if (needs_imports) {
1330 code += "import (\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001331 if (is_enum) { code += "\t\"strconv\"\n\n"; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001332 if (!parser_.opts.go_import.empty()) {
1333 code += "\tflatbuffers \"" + parser_.opts.go_import + "\"\n";
1334 } else {
1335 code += "\tflatbuffers \"github.com/google/flatbuffers/go\"\n";
1336 }
1337 if (tracked_imported_namespaces_.size() > 0) {
1338 code += "\n";
1339 for (auto it = tracked_imported_namespaces_.begin();
Austin Schuh272c6132020-11-14 16:37:52 -08001340 it != tracked_imported_namespaces_.end(); ++it) {
1341 code += "\t" + NamespaceImportName(*it) + " \"" +
1342 NamespaceImportPath(*it) + "\"\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001343 }
1344 }
1345 code += ")\n\n";
1346 } else {
Austin Schuh272c6132020-11-14 16:37:52 -08001347 if (is_enum) { code += "import \"strconv\"\n\n"; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001348 }
1349 }
1350
1351 // Save out the generated code for a Go Table type.
1352 bool SaveType(const Definition &def, const std::string &classcode,
1353 const bool needs_imports, const bool is_enum) {
1354 if (!classcode.length()) return true;
1355
1356 Namespace &ns = go_namespace_.components.empty() ? *def.defined_namespace
1357 : go_namespace_;
1358 std::string code = "";
1359 BeginFile(LastNamespacePart(ns), needs_imports, is_enum, &code);
1360 code += classcode;
1361 // Strip extra newlines at end of file to make it gofmt-clean.
1362 while (code.length() > 2 && code.substr(code.length() - 2) == "\n\n") {
1363 code.pop_back();
1364 }
Austin Schuh2dd86a92022-09-14 21:19:23 -07001365 std::string directory = namer_.Directories(ns);
1366 std::string file = namer_.File(def, SkipFile::Suffix);
1367 EnsureDirExists(directory);
1368 std::string filename = directory + file;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001369 return SaveFile(filename.c_str(), code, false);
1370 }
1371
1372 // Create the full name of the imported namespace (format: A__B__C).
James Kuszmaul8e62b022022-03-22 09:33:25 -07001373 std::string NamespaceImportName(const Namespace *ns) const {
Austin Schuh2dd86a92022-09-14 21:19:23 -07001374 return namer_.Namespace(*ns);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001375 }
1376
1377 // Create the full path for the imported namespace (format: A/B/C).
James Kuszmaul8e62b022022-03-22 09:33:25 -07001378 std::string NamespaceImportPath(const Namespace *ns) const {
Austin Schuh2dd86a92022-09-14 21:19:23 -07001379 return namer_.Directories(*ns, SkipDir::OutputPathAndTrailingPathSeparator);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001380 }
1381
1382 // Ensure that a type is prefixed with its go package import name if it is
1383 // used outside of its namespace.
1384 std::string WrapInNameSpaceAndTrack(const Namespace *ns,
1385 const std::string &name) {
1386 if (CurrentNameSpace() == ns) return name;
1387
1388 tracked_imported_namespaces_.insert(ns);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001389 return NamespaceImportName(ns) + "." + name;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001390 }
1391
1392 std::string WrapInNameSpaceAndTrack(const Definition &def) {
1393 return WrapInNameSpaceAndTrack(def.defined_namespace, def.name);
1394 }
1395
1396 const Namespace *CurrentNameSpace() const { return cur_name_space_; }
1397
1398 static size_t MaxNameLength(const EnumDef &enum_def) {
1399 size_t max = 0;
Austin Schuh272c6132020-11-14 16:37:52 -08001400 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001401 max = std::max((*it)->name.length(), max);
1402 }
1403 return max;
1404 }
1405};
1406} // namespace go
1407
1408bool GenerateGo(const Parser &parser, const std::string &path,
1409 const std::string &file_name) {
1410 go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace);
1411 return generator.generate();
1412}
1413
1414} // namespace flatbuffers