blob: 306a0227fe1a2c64e2b2f97a2ca265bae0254c6a [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"
James Kuszmaul8e62b022022-03-22 09:33:25 -070026#include "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
41// see https://golang.org/ref/spec#Keywords
James Kuszmaul8e62b022022-03-22 09:33:25 -070042std::set<std::string> GoKeywords() {
43 return {
44 "break", "default", "func", "interface", "select",
45 "case", "defer", "go", "map", "struct",
46 "chan", "else", "goto", "package", "switch",
47 "const", "fallthrough", "if", "range", "type",
48 "continue", "for", "import", "return", "var",
49 };
50}
Austin Schuhe89fa2d2019-08-14 20:24:23 -070051
James Kuszmaul8e62b022022-03-22 09:33:25 -070052Namer::Config GoDefaultConfig() {
53 // Note that the functions with user defined types in the name use
54 // upper camel case for all but the user defined type itself, which is keep
55 // cased. Despite being a function, we interpret it as a Type.
56 return { /*types=*/Case::kKeep,
57 /*constants=*/Case::kUnknown,
58 /*methods=*/Case::kUpperCamel,
59 /*functions=*/Case::kUpperCamel,
60 /*fields=*/Case::kUpperCamel,
61 /*variables=*/Case::kLowerCamel,
62 /*variants=*/Case::kKeep,
63 /*enum_variant_seperator=*/"", // I.e. Concatenate.
64 /*namespaces=*/Case::kKeep,
65 /*namespace_seperator=*/"__",
66 /*object_prefix=*/"",
67 /*object_suffix=*/"T",
68 /*keyword_prefix=*/"",
69 /*keyword_suffix=*/"_",
70 /*filenames=*/Case::kKeep,
71 /*directories=*/Case::kKeep,
72 /*output_path=*/"",
73 /*filename_suffix=*/"",
74 /*filename_extension=*/".go" };
Austin Schuhe89fa2d2019-08-14 20:24:23 -070075}
76
77class GoGenerator : public BaseGenerator {
78 public:
79 GoGenerator(const Parser &parser, const std::string &path,
80 const std::string &file_name, const std::string &go_namespace)
81 : BaseGenerator(parser, path, file_name, "" /* not used*/,
Austin Schuh272c6132020-11-14 16:37:52 -080082 "" /* not used */, "go"),
James Kuszmaul8e62b022022-03-22 09:33:25 -070083 cur_name_space_(nullptr),
84 namer_({ GoDefaultConfig().WithFlagOptions(parser.opts, path),
85 GoKeywords() }) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070086 std::istringstream iss(go_namespace);
87 std::string component;
88 while (std::getline(iss, component, '.')) {
89 go_namespace_.components.push_back(component);
90 }
91 }
92
93 bool generate() {
94 std::string one_file_code;
Austin Schuh272c6132020-11-14 16:37:52 -080095 bool needs_imports = false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -070096 for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
97 ++it) {
98 tracked_imported_namespaces_.clear();
Austin Schuh272c6132020-11-14 16:37:52 -080099 needs_imports = false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700100 std::string enumcode;
101 GenEnum(**it, &enumcode);
Austin Schuh272c6132020-11-14 16:37:52 -0800102 if ((*it)->is_union && parser_.opts.generate_object_based_api) {
103 GenNativeUnion(**it, &enumcode);
104 GenNativeUnionPack(**it, &enumcode);
105 GenNativeUnionUnPack(**it, &enumcode);
106 needs_imports = true;
107 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700108 if (parser_.opts.one_file) {
109 one_file_code += enumcode;
110 } else {
Austin Schuh272c6132020-11-14 16:37:52 -0800111 if (!SaveType(**it, enumcode, needs_imports, true)) return false;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700112 }
113 }
114
115 for (auto it = parser_.structs_.vec.begin();
116 it != parser_.structs_.vec.end(); ++it) {
117 tracked_imported_namespaces_.clear();
118 std::string declcode;
119 GenStruct(**it, &declcode);
120 if (parser_.opts.one_file) {
121 one_file_code += declcode;
122 } else {
123 if (!SaveType(**it, declcode, true, false)) return false;
124 }
125 }
126
127 if (parser_.opts.one_file) {
128 std::string code = "";
129 const bool is_enum = !parser_.enums_.vec.empty();
130 BeginFile(LastNamespacePart(go_namespace_), true, is_enum, &code);
131 code += one_file_code;
Austin Schuh272c6132020-11-14 16:37:52 -0800132 const std::string filename =
133 GeneratedFileName(path_, file_name_, parser_.opts);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700134 return SaveFile(filename.c_str(), code, false);
135 }
136
137 return true;
138 }
139
140 private:
141 Namespace go_namespace_;
142 Namespace *cur_name_space_;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700143 const Namer namer_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700144
145 struct NamespacePtrLess {
146 bool operator()(const Namespace *a, const Namespace *b) const {
147 return *a < *b;
148 }
149 };
150 std::set<const Namespace *, NamespacePtrLess> tracked_imported_namespaces_;
151
152 // Most field accessors need to retrieve and test the field offset first,
153 // this is the prefix code for that.
154 std::string OffsetPrefix(const FieldDef &field) {
155 return "{\n\to := flatbuffers.UOffsetT(rcv._tab.Offset(" +
156 NumToString(field.value.offset) + "))\n\tif o != 0 {\n";
157 }
158
159 // Begin a class declaration.
160 void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
161 std::string &code = *code_ptr;
162
James Kuszmaul8e62b022022-03-22 09:33:25 -0700163 code += "type " + namer_.Type(struct_def.name) + " struct {\n\t";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700164
165 // _ is reserved in flatbuffers field names, so no chance of name conflict:
166 code += "_tab ";
167 code += struct_def.fixed ? "flatbuffers.Struct" : "flatbuffers.Table";
168 code += "\n}\n\n";
169 }
170
171 // Construct the name of the type for this enum.
172 std::string GetEnumTypeName(const EnumDef &enum_def) {
Austin Schuh272c6132020-11-14 16:37:52 -0800173 return WrapInNameSpaceAndTrack(enum_def.defined_namespace,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700174 namer_.Type(enum_def.name));
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700175 }
176
177 // Create a type for the enum values.
178 void GenEnumType(const EnumDef &enum_def, std::string *code_ptr) {
179 std::string &code = *code_ptr;
180 code += "type " + GetEnumTypeName(enum_def) + " ";
181 code += GenTypeBasic(enum_def.underlying_type) + "\n\n";
182 }
183
184 // Begin enum code with a class declaration.
185 void BeginEnum(std::string *code_ptr) {
186 std::string &code = *code_ptr;
187 code += "const (\n";
188 }
189
190 // A single enum member.
191 void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
192 size_t max_name_length, std::string *code_ptr) {
193 std::string &code = *code_ptr;
194 code += "\t";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700195 code += namer_.EnumVariant(enum_def.name, ev.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700196 code += " ";
197 code += std::string(max_name_length - ev.name.length(), ' ');
198 code += GetEnumTypeName(enum_def);
199 code += " = ";
200 code += enum_def.ToString(ev) + "\n";
201 }
202
203 // End enum code.
204 void EndEnum(std::string *code_ptr) {
205 std::string &code = *code_ptr;
206 code += ")\n\n";
207 }
208
209 // Begin enum name map.
210 void BeginEnumNames(const EnumDef &enum_def, std::string *code_ptr) {
211 std::string &code = *code_ptr;
212 code += "var EnumNames";
213 code += enum_def.name;
214 code += " = map[" + GetEnumTypeName(enum_def) + "]string{\n";
215 }
216
217 // A single enum name member.
218 void EnumNameMember(const EnumDef &enum_def, const EnumVal &ev,
219 size_t max_name_length, std::string *code_ptr) {
220 std::string &code = *code_ptr;
221 code += "\t";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700222 code += namer_.EnumVariant(enum_def.name, ev.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700223 code += ": ";
224 code += std::string(max_name_length - ev.name.length(), ' ');
225 code += "\"";
226 code += ev.name;
227 code += "\",\n";
228 }
229
230 // End enum name map.
231 void EndEnumNames(std::string *code_ptr) {
232 std::string &code = *code_ptr;
233 code += "}\n\n";
234 }
235
236 // Generate String() method on enum type.
237 void EnumStringer(const EnumDef &enum_def, std::string *code_ptr) {
238 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700239 const std::string enum_type = namer_.Type(enum_def.name);
240 code += "func (v " + enum_type + ") String() string {\n";
241 code += "\tif s, ok := EnumNames" + enum_type + "[v]; ok {\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700242 code += "\t\treturn s\n";
243 code += "\t}\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800244 code += "\treturn \"" + enum_def.name;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700245 code += "(\" + strconv.FormatInt(int64(v), 10) + \")\"\n";
246 code += "}\n\n";
247 }
248
249 // Begin enum value map.
250 void BeginEnumValues(const EnumDef &enum_def, std::string *code_ptr) {
251 std::string &code = *code_ptr;
252 code += "var EnumValues";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700253 code += namer_.Type(enum_def.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700254 code += " = map[string]" + GetEnumTypeName(enum_def) + "{\n";
255 }
256
257 // A single enum value member.
258 void EnumValueMember(const EnumDef &enum_def, const EnumVal &ev,
259 size_t max_name_length, std::string *code_ptr) {
260 std::string &code = *code_ptr;
261 code += "\t\"";
262 code += ev.name;
263 code += "\": ";
264 code += std::string(max_name_length - ev.name.length(), ' ');
James Kuszmaul8e62b022022-03-22 09:33:25 -0700265 code += namer_.EnumVariant(enum_def.name, ev.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700266 code += ",\n";
267 }
268
269 // End enum value map.
270 void EndEnumValues(std::string *code_ptr) {
271 std::string &code = *code_ptr;
272 code += "}\n\n";
273 }
274
275 // Initialize a new struct or table from existing data.
276 void NewRootTypeFromBuffer(const StructDef &struct_def,
277 std::string *code_ptr) {
278 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700279 const std::string size_prefix[] = { "", "SizePrefixed" };
280 const std::string struct_type = namer_.Type(struct_def.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700281
Austin Schuh272c6132020-11-14 16:37:52 -0800282 for (int i = 0; i < 2; i++) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700283 code += "func Get" + size_prefix[i] + "RootAs" + struct_type;
Austin Schuh272c6132020-11-14 16:37:52 -0800284 code += "(buf []byte, offset flatbuffers.UOffsetT) ";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700285 code += "*" + struct_type + "";
Austin Schuh272c6132020-11-14 16:37:52 -0800286 code += " {\n";
287 if (i == 0) {
288 code += "\tn := flatbuffers.GetUOffsetT(buf[offset:])\n";
289 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700290 code +=
291 "\tn := "
292 "flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800293 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700294 code += "\tx := &" + struct_type + "{}\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800295 if (i == 0) {
296 code += "\tx.Init(buf, n+offset)\n";
297 } else {
298 code += "\tx.Init(buf, n+offset+flatbuffers.SizeUint32)\n";
299 }
300 code += "\treturn x\n";
301 code += "}\n\n";
302 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700303 }
304
305 // Initialize an existing object with other data, to avoid an allocation.
306 void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) {
307 std::string &code = *code_ptr;
308
309 GenReceiver(struct_def, code_ptr);
310 code += " Init(buf []byte, i flatbuffers.UOffsetT) ";
311 code += "{\n";
312 code += "\trcv._tab.Bytes = buf\n";
313 code += "\trcv._tab.Pos = i\n";
314 code += "}\n\n";
315 }
316
317 // Implement the table accessor
318 void GenTableAccessor(const StructDef &struct_def, std::string *code_ptr) {
319 std::string &code = *code_ptr;
320
321 GenReceiver(struct_def, code_ptr);
322 code += " Table() flatbuffers.Table ";
323 code += "{\n";
324
325 if (struct_def.fixed) {
326 code += "\treturn rcv._tab.Table\n";
327 } else {
328 code += "\treturn rcv._tab\n";
329 }
330 code += "}\n\n";
331 }
332
333 // Get the length of a vector.
334 void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
335 std::string *code_ptr) {
336 std::string &code = *code_ptr;
337
338 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700339 code += " " + namer_.Function(field.name) + "Length(";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700340 code += ") int " + OffsetPrefix(field);
341 code += "\t\treturn rcv._tab.VectorLen(o)\n\t}\n";
342 code += "\treturn 0\n}\n\n";
343 }
344
345 // Get a [ubyte] vector as a byte slice.
346 void GetUByteSlice(const StructDef &struct_def, const FieldDef &field,
347 std::string *code_ptr) {
348 std::string &code = *code_ptr;
349
350 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700351 code += " " + namer_.Function(field.name) + "Bytes(";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700352 code += ") []byte " + OffsetPrefix(field);
353 code += "\t\treturn rcv._tab.ByteVector(o + rcv._tab.Pos)\n\t}\n";
354 code += "\treturn nil\n}\n\n";
355 }
356
357 // Get the value of a struct's scalar.
358 void GetScalarFieldOfStruct(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800359 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700360 std::string &code = *code_ptr;
361 std::string getter = GenGetter(field.value.type);
362 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700363 code += " " + namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700364 code += "() " + TypeName(field) + " {\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800365 code += "\treturn " +
366 CastToEnum(field.value.type,
367 getter + "(rcv._tab.Pos + flatbuffers.UOffsetT(" +
368 NumToString(field.value.offset) + "))");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700369 code += "\n}\n";
370 }
371
372 // Get the value of a table's scalar.
Austin Schuh272c6132020-11-14 16:37:52 -0800373 void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700374 std::string *code_ptr) {
375 std::string &code = *code_ptr;
376 std::string getter = GenGetter(field.value.type);
377 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700378 code += " " + namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700379 code += "() " + TypeName(field) + " ";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700380 code += OffsetPrefix(field);
381 if (field.IsScalarOptional()) {
382 code += "\t\tv := ";
383 } else {
384 code += "\t\treturn ";
385 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700386 code += CastToEnum(field.value.type, getter + "(o + rcv._tab.Pos)");
James Kuszmaul8e62b022022-03-22 09:33:25 -0700387 if (field.IsScalarOptional()) {
388 code += "\n\t\treturn &v";
389 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700390 code += "\n\t}\n";
391 code += "\treturn " + GenConstant(field) + "\n";
392 code += "}\n\n";
393 }
394
395 // Get a struct by initializing an existing struct.
396 // Specific to Struct.
397 void GetStructFieldOfStruct(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800398 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700399 std::string &code = *code_ptr;
400 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700401 code += " " + namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700402 code += "(obj *" + TypeName(field);
403 code += ") *" + TypeName(field);
404 code += " {\n";
405 code += "\tif obj == nil {\n";
406 code += "\t\tobj = new(" + TypeName(field) + ")\n";
407 code += "\t}\n";
408 code += "\tobj.Init(rcv._tab.Bytes, rcv._tab.Pos+";
409 code += NumToString(field.value.offset) + ")";
410 code += "\n\treturn obj\n";
411 code += "}\n";
412 }
413
414 // Get a struct by initializing an existing struct.
415 // Specific to Table.
Austin Schuh272c6132020-11-14 16:37:52 -0800416 void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700417 std::string *code_ptr) {
418 std::string &code = *code_ptr;
419 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700420 code += " " + namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700421 code += "(obj *";
422 code += TypeName(field);
423 code += ") *" + TypeName(field) + " " + OffsetPrefix(field);
424 if (field.value.type.struct_def->fixed) {
425 code += "\t\tx := o + rcv._tab.Pos\n";
426 } else {
427 code += "\t\tx := rcv._tab.Indirect(o + rcv._tab.Pos)\n";
428 }
429 code += "\t\tif obj == nil {\n";
430 code += "\t\t\tobj = new(" + TypeName(field) + ")\n";
431 code += "\t\t}\n";
432 code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
433 code += "\t\treturn obj\n\t}\n\treturn nil\n";
434 code += "}\n\n";
435 }
436
437 // Get the value of a string.
Austin Schuh272c6132020-11-14 16:37:52 -0800438 void GetStringField(const StructDef &struct_def, const FieldDef &field,
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700439 std::string *code_ptr) {
440 std::string &code = *code_ptr;
441 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700442 code += " " + namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700443 code += "() " + TypeName(field) + " ";
444 code += OffsetPrefix(field) + "\t\treturn " + GenGetter(field.value.type);
445 code += "(o + rcv._tab.Pos)\n\t}\n\treturn nil\n";
446 code += "}\n\n";
447 }
448
449 // Get the value of a union from an object.
450 void GetUnionField(const StructDef &struct_def, const FieldDef &field,
451 std::string *code_ptr) {
452 std::string &code = *code_ptr;
453 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700454 code += " " + namer_.Function(field.name) + "(";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700455 code += "obj " + GenTypePointer(field.value.type) + ") bool ";
456 code += OffsetPrefix(field);
457 code += "\t\t" + GenGetter(field.value.type);
458 code += "(obj, o)\n\t\treturn true\n\t}\n";
459 code += "\treturn false\n";
460 code += "}\n\n";
461 }
462
463 // Get the value of a vector's struct member.
464 void GetMemberOfVectorOfStruct(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800465 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700466 std::string &code = *code_ptr;
467 auto vectortype = field.value.type.VectorType();
468
469 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700470 code += " " + namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700471 code += "(obj *" + TypeName(field);
472 code += ", j int) bool " + OffsetPrefix(field);
473 code += "\t\tx := rcv._tab.Vector(o)\n";
474 code += "\t\tx += flatbuffers.UOffsetT(j) * ";
475 code += NumToString(InlineSize(vectortype)) + "\n";
476 if (!(vectortype.struct_def->fixed)) {
477 code += "\t\tx = rcv._tab.Indirect(x)\n";
478 }
479 code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
480 code += "\t\treturn true\n\t}\n";
481 code += "\treturn false\n";
482 code += "}\n\n";
483 }
484
485 // Get the value of a vector's non-struct member.
486 void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
487 const FieldDef &field,
488 std::string *code_ptr) {
489 std::string &code = *code_ptr;
490 auto vectortype = field.value.type.VectorType();
491
492 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700493 code += " " + namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700494 code += "(j int) " + TypeName(field) + " ";
495 code += OffsetPrefix(field);
496 code += "\t\ta := rcv._tab.Vector(o)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800497 code += "\t\treturn " +
498 CastToEnum(field.value.type,
499 GenGetter(field.value.type) +
500 "(a + flatbuffers.UOffsetT(j*" +
501 NumToString(InlineSize(vectortype)) + "))");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700502 code += "\n\t}\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800503 if (IsString(vectortype)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700504 code += "\treturn nil\n";
505 } else if (vectortype.base_type == BASE_TYPE_BOOL) {
506 code += "\treturn false\n";
507 } else {
508 code += "\treturn 0\n";
509 }
510 code += "}\n\n";
511 }
512
513 // Begin the creator function signature.
514 void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
515 std::string &code = *code_ptr;
516
517 if (code.substr(code.length() - 2) != "\n\n") {
518 // a previous mutate has not put an extra new line
519 code += "\n";
520 }
521 code += "func Create" + struct_def.name;
522 code += "(builder *flatbuffers.Builder";
523 }
524
525 // Recursively generate arguments for a constructor, to deal with nested
526 // structs.
527 void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix,
528 std::string *code_ptr) {
529 for (auto it = struct_def.fields.vec.begin();
530 it != struct_def.fields.vec.end(); ++it) {
531 auto &field = **it;
532 if (IsStruct(field.value.type)) {
533 // Generate arguments for a struct inside a struct. To ensure names
534 // don't clash, and to make it obvious these arguments are constructing
535 // a nested struct, prefix the name with the field name.
536 StructBuilderArgs(*field.value.type.struct_def,
537 (nameprefix + (field.name + "_")).c_str(), code_ptr);
538 } else {
539 std::string &code = *code_ptr;
540 code += std::string(", ") + nameprefix;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700541 code += namer_.Variable(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700542 code += " " + TypeName(field);
543 }
544 }
545 }
546
547 // End the creator function signature.
548 void EndBuilderArgs(std::string *code_ptr) {
549 std::string &code = *code_ptr;
550 code += ") flatbuffers.UOffsetT {\n";
551 }
552
553 // Recursively generate struct construction statements and instert manual
554 // padding.
Austin Schuh272c6132020-11-14 16:37:52 -0800555 void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
556 std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700557 std::string &code = *code_ptr;
558 code += "\tbuilder.Prep(" + NumToString(struct_def.minalign) + ", ";
559 code += NumToString(struct_def.bytesize) + ")\n";
560 for (auto it = struct_def.fields.vec.rbegin();
561 it != struct_def.fields.vec.rend(); ++it) {
562 auto &field = **it;
563 if (field.padding)
564 code += "\tbuilder.Pad(" + NumToString(field.padding) + ")\n";
565 if (IsStruct(field.value.type)) {
566 StructBuilderBody(*field.value.type.struct_def,
567 (nameprefix + (field.name + "_")).c_str(), code_ptr);
568 } else {
569 code += "\tbuilder.Prepend" + GenMethod(field) + "(";
Austin Schuh272c6132020-11-14 16:37:52 -0800570 code += CastToBaseType(field.value.type,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700571 nameprefix + namer_.Variable(field.name)) +
Austin Schuh272c6132020-11-14 16:37:52 -0800572 ")\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700573 }
574 }
575 }
576
577 void EndBuilderBody(std::string *code_ptr) {
578 std::string &code = *code_ptr;
579 code += "\treturn builder.Offset()\n";
580 code += "}\n";
581 }
582
583 // Get the value of a table's starting offset.
584 void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
585 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700586 code += "func " + namer_.Type(struct_def.name) + "Start";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700587 code += "(builder *flatbuffers.Builder) {\n";
588 code += "\tbuilder.StartObject(";
589 code += NumToString(struct_def.fields.vec.size());
590 code += ")\n}\n";
591 }
592
593 // Set the value of a table's field.
594 void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
595 const size_t offset, std::string *code_ptr) {
596 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700597 const std::string field_var = namer_.Variable(field.name);
598 code += "func " + namer_.Type(struct_def.name) + "Add" +
599 namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700600 code += "(builder *flatbuffers.Builder, ";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700601 code += field_var + " ";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700602 if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
603 code += "flatbuffers.UOffsetT";
604 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700605 code += GenTypeGet(field.value.type);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700606 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700607 code += ") {\n\t";
608 code += "builder.Prepend";
609 code += GenMethod(field);
610 if (field.IsScalarOptional()) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700611 code += "(";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700612 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700613 code += "Slot(" + NumToString(offset) + ", ";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700614 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700615 if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
616 code += "flatbuffers.UOffsetT";
617 code += "(" + field_var + ")";
618 } else {
619 code += CastToBaseType(field.value.type, field_var);
620 }
621 if (field.IsScalarOptional()) {
622 code += ")\n";
623 code += "\tbuilder.Slot(" + NumToString(offset);
624 } else {
625 code += ", " + GenConstant(field);
626 }
627 code += ")\n";
628 code += "}\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700629 }
630
631 // Set the value of one of the members of a table's vector.
Austin Schuh272c6132020-11-14 16:37:52 -0800632 void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
633 std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700634 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700635 code += "func " + namer_.Type(struct_def.name) + "Start";
636 code += namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700637 code += "Vector(builder *flatbuffers.Builder, numElems int) ";
638 code += "flatbuffers.UOffsetT {\n\treturn builder.StartVector(";
639 auto vector_type = field.value.type.VectorType();
640 auto alignment = InlineAlignment(vector_type);
641 auto elem_size = InlineSize(vector_type);
642 code += NumToString(elem_size);
643 code += ", numElems, " + NumToString(alignment);
644 code += ")\n}\n";
645 }
646
647 // Get the offset of the end of a table.
648 void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
649 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700650 code += "func " + namer_.Type(struct_def.name) + "End";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700651 code += "(builder *flatbuffers.Builder) flatbuffers.UOffsetT ";
652 code += "{\n\treturn builder.EndObject()\n}\n";
653 }
654
655 // Generate the receiver for function signatures.
656 void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
657 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700658 code += "func (rcv *" + namer_.Type(struct_def.name) + ")";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700659 }
660
661 // Generate a struct field getter, conditioned on its child type(s).
Austin Schuh272c6132020-11-14 16:37:52 -0800662 void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
663 std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700664 GenComment(field.doc_comment, code_ptr, nullptr, "");
665 if (IsScalar(field.value.type.base_type)) {
666 if (struct_def.fixed) {
667 GetScalarFieldOfStruct(struct_def, field, code_ptr);
668 } else {
669 GetScalarFieldOfTable(struct_def, field, code_ptr);
670 }
671 } else {
672 switch (field.value.type.base_type) {
673 case BASE_TYPE_STRUCT:
674 if (struct_def.fixed) {
675 GetStructFieldOfStruct(struct_def, field, code_ptr);
676 } else {
677 GetStructFieldOfTable(struct_def, field, code_ptr);
678 }
679 break;
Austin Schuh272c6132020-11-14 16:37:52 -0800680 case BASE_TYPE_STRING:
681 GetStringField(struct_def, field, code_ptr);
682 break;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700683 case BASE_TYPE_VECTOR: {
684 auto vectortype = field.value.type.VectorType();
685 if (vectortype.base_type == BASE_TYPE_STRUCT) {
686 GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
687 } else {
688 GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
689 }
690 break;
691 }
692 case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
693 default: FLATBUFFERS_ASSERT(0);
694 }
695 }
Austin Schuh272c6132020-11-14 16:37:52 -0800696 if (IsVector(field.value.type)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700697 GetVectorLen(struct_def, field, code_ptr);
698 if (field.value.type.element == BASE_TYPE_UCHAR) {
699 GetUByteSlice(struct_def, field, code_ptr);
700 }
701 }
702 }
703
704 // Mutate the value of a struct's scalar.
705 void MutateScalarFieldOfStruct(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800706 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700707 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700708 std::string setter =
709 "rcv._tab.Mutate" + namer_.Method(GenTypeBasic(field.value.type));
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700710 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700711 code += " Mutate" + namer_.Function(field.name);
712 code += "(n " + GenTypeGet(field.value.type) + ") bool {\n\treturn " + setter;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700713 code += "(rcv._tab.Pos+flatbuffers.UOffsetT(";
714 code += NumToString(field.value.offset) + "), ";
715 code += CastToBaseType(field.value.type, "n") + ")\n}\n\n";
716 }
717
718 // Mutate the value of a table's scalar.
719 void MutateScalarFieldOfTable(const StructDef &struct_def,
Austin Schuh272c6132020-11-14 16:37:52 -0800720 const FieldDef &field, std::string *code_ptr) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700721 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700722 std::string setter = "rcv._tab.Mutate" +
723 namer_.Method(GenTypeBasic(field.value.type)) + "Slot";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700724 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700725 code += " Mutate" + namer_.Function(field.name);
726 code += "(n " + GenTypeGet(field.value.type) + ") bool {\n\treturn ";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700727 code += setter + "(" + NumToString(field.value.offset) + ", ";
728 code += CastToBaseType(field.value.type, "n") + ")\n";
729 code += "}\n\n";
730 }
731
732 // Mutate an element of a vector of scalars.
733 void MutateElementOfVectorOfNonStruct(const StructDef &struct_def,
734 const FieldDef &field,
735 std::string *code_ptr) {
736 std::string &code = *code_ptr;
737 auto vectortype = field.value.type.VectorType();
James Kuszmaul8e62b022022-03-22 09:33:25 -0700738 std::string setter =
739 "rcv._tab.Mutate" + namer_.Method(GenTypeBasic(vectortype));
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700740 GenReceiver(struct_def, code_ptr);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700741 code += " Mutate" + namer_.Function(field.name);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700742 code += "(j int, n " + TypeName(field) + ") bool ";
743 code += OffsetPrefix(field);
744 code += "\t\ta := rcv._tab.Vector(o)\n";
745 code += "\t\treturn " + setter + "(";
746 code += "a+flatbuffers.UOffsetT(j*";
747 code += NumToString(InlineSize(vectortype)) + "), ";
748 code += CastToBaseType(vectortype, "n") + ")\n";
749 code += "\t}\n";
750 code += "\treturn false\n";
751 code += "}\n\n";
752 }
753
754 // Generate a struct field setter, conditioned on its child type(s).
755 void GenStructMutator(const StructDef &struct_def, const FieldDef &field,
756 std::string *code_ptr) {
757 GenComment(field.doc_comment, code_ptr, nullptr, "");
758 if (IsScalar(field.value.type.base_type)) {
759 if (struct_def.fixed) {
760 MutateScalarFieldOfStruct(struct_def, field, code_ptr);
761 } else {
762 MutateScalarFieldOfTable(struct_def, field, code_ptr);
763 }
Austin Schuh272c6132020-11-14 16:37:52 -0800764 } else if (IsVector(field.value.type)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700765 if (IsScalar(field.value.type.element)) {
766 MutateElementOfVectorOfNonStruct(struct_def, field, code_ptr);
767 }
768 }
769 }
770
771 // Generate table constructors, conditioned on its members' types.
772 void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
773 GetStartOfTable(struct_def, code_ptr);
774
775 for (auto it = struct_def.fields.vec.begin();
776 it != struct_def.fields.vec.end(); ++it) {
777 auto &field = **it;
778 if (field.deprecated) continue;
779
780 auto offset = it - struct_def.fields.vec.begin();
781 BuildFieldOfTable(struct_def, field, offset, code_ptr);
Austin Schuh272c6132020-11-14 16:37:52 -0800782 if (IsVector(field.value.type)) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700783 BuildVectorOfTable(struct_def, field, code_ptr);
784 }
785 }
786
787 GetEndOffsetOnTable(struct_def, code_ptr);
788 }
789
790 // Generate struct or table methods.
791 void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
792 if (struct_def.generated) return;
793
794 cur_name_space_ = struct_def.defined_namespace;
795
796 GenComment(struct_def.doc_comment, code_ptr, nullptr);
Austin Schuh272c6132020-11-14 16:37:52 -0800797 if (parser_.opts.generate_object_based_api) {
798 GenNativeStruct(struct_def, code_ptr);
799 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700800 BeginClass(struct_def, code_ptr);
801 if (!struct_def.fixed) {
802 // Generate a special accessor for the table that has been declared as
803 // the root type.
804 NewRootTypeFromBuffer(struct_def, code_ptr);
805 }
806 // Generate the Init method that sets the field in a pre-existing
807 // accessor object. This is to allow object reuse.
808 InitializeExisting(struct_def, code_ptr);
809 // Generate _tab accessor
810 GenTableAccessor(struct_def, code_ptr);
811
812 // Generate struct fields accessors
813 for (auto it = struct_def.fields.vec.begin();
814 it != struct_def.fields.vec.end(); ++it) {
815 auto &field = **it;
816 if (field.deprecated) continue;
817
818 GenStructAccessor(struct_def, field, code_ptr);
819 GenStructMutator(struct_def, field, code_ptr);
820 }
821
822 // Generate builders
823 if (struct_def.fixed) {
824 // create a struct constructor function
825 GenStructBuilder(struct_def, code_ptr);
826 } else {
827 // Create a set of functions that allow table construction.
828 GenTableBuilders(struct_def, code_ptr);
829 }
830 }
831
Austin Schuh272c6132020-11-14 16:37:52 -0800832 void GenNativeStruct(const StructDef &struct_def, std::string *code_ptr) {
833 std::string &code = *code_ptr;
834
835 code += "type " + NativeName(struct_def) + " struct {\n";
836 for (auto it = struct_def.fields.vec.begin();
837 it != struct_def.fields.vec.end(); ++it) {
838 const FieldDef &field = **it;
839 if (field.deprecated) continue;
840 if (IsScalar(field.value.type.base_type) &&
841 field.value.type.enum_def != nullptr &&
842 field.value.type.enum_def->is_union)
843 continue;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700844 code += "\t" + namer_.Field(field.name) + " ";
845 if (field.IsScalarOptional()) {
846 code += "*";
847 }
848 code += NativeType(field.value.type) + "\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800849 }
850 code += "}\n\n";
851
852 if (!struct_def.fixed) {
853 GenNativeTablePack(struct_def, code_ptr);
854 GenNativeTableUnPack(struct_def, code_ptr);
855 } else {
856 GenNativeStructPack(struct_def, code_ptr);
857 GenNativeStructUnPack(struct_def, code_ptr);
858 }
859 }
860
861 void GenNativeUnion(const EnumDef &enum_def, std::string *code_ptr) {
862 std::string &code = *code_ptr;
863 code += "type " + NativeName(enum_def) + " struct {\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700864 code += "\tType " + namer_.Type(enum_def.name) + "\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800865 code += "\tValue interface{}\n";
866 code += "}\n\n";
867 }
868
869 void GenNativeUnionPack(const EnumDef &enum_def, std::string *code_ptr) {
870 std::string &code = *code_ptr;
871 code += "func (t *" + NativeName(enum_def) +
872 ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
873 code += "\tif t == nil {\n\t\treturn 0\n\t}\n";
874
875 code += "\tswitch t.Type {\n";
876 for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
877 ++it2) {
878 const EnumVal &ev = **it2;
879 if (ev.IsZero()) continue;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700880 code += "\tcase " + namer_.EnumVariant(enum_def.name, ev.name) + ":\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800881 code += "\t\treturn t.Value.(" + NativeType(ev.union_type) +
882 ").Pack(builder)\n";
883 }
884 code += "\t}\n";
885 code += "\treturn 0\n";
886 code += "}\n\n";
887 }
888
889 void GenNativeUnionUnPack(const EnumDef &enum_def, std::string *code_ptr) {
890 std::string &code = *code_ptr;
891
James Kuszmaul8e62b022022-03-22 09:33:25 -0700892 code += "func (rcv " + namer_.Type(enum_def.name) +
Austin Schuh272c6132020-11-14 16:37:52 -0800893 ") UnPack(table flatbuffers.Table) *" + NativeName(enum_def) +
894 " {\n";
895 code += "\tswitch rcv {\n";
896
897 for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
898 ++it2) {
899 const EnumVal &ev = **it2;
900 if (ev.IsZero()) continue;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700901 code += "\tcase " + namer_.EnumVariant(enum_def.name, ev.name) + ":\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800902 code += "\t\tx := " + ev.union_type.struct_def->name + "{_tab: table}\n";
903
904 code += "\t\treturn &" +
905 WrapInNameSpaceAndTrack(enum_def.defined_namespace,
906 NativeName(enum_def)) +
James Kuszmaul8e62b022022-03-22 09:33:25 -0700907 "{ Type: " + namer_.EnumVariant(enum_def.name, ev.name) +
908 ", Value: x.UnPack() }\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800909 }
910 code += "\t}\n";
911 code += "\treturn nil\n";
912 code += "}\n\n";
913 }
914
915 void GenNativeTablePack(const StructDef &struct_def, std::string *code_ptr) {
916 std::string &code = *code_ptr;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700917 const std::string struct_type = namer_.Type(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -0800918
919 code += "func (t *" + NativeName(struct_def) +
920 ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
921 code += "\tif t == nil { return 0 }\n";
922 for (auto it = struct_def.fields.vec.begin();
923 it != struct_def.fields.vec.end(); ++it) {
924 const FieldDef &field = **it;
925 if (field.deprecated) continue;
926 if (IsScalar(field.value.type.base_type)) continue;
927
James Kuszmaul8e62b022022-03-22 09:33:25 -0700928 const std::string field_field = namer_.Field(field.name);
929 const std::string field_var = namer_.Variable(field.name);
930 const std::string offset = field_var + "Offset";
Austin Schuh272c6132020-11-14 16:37:52 -0800931
932 if (IsString(field.value.type)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700933 code +=
934 "\t" + offset + " := builder.CreateString(t." + field_field + ")\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800935 } else if (IsVector(field.value.type) &&
936 field.value.type.element == BASE_TYPE_UCHAR &&
937 field.value.type.enum_def == nullptr) {
938 code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700939 code += "\tif t." + field_field + " != nil {\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800940 code += "\t\t" + offset + " = builder.CreateByteString(t." +
James Kuszmaul8e62b022022-03-22 09:33:25 -0700941 field_field + ")\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800942 code += "\t}\n";
943 } else if (IsVector(field.value.type)) {
944 code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700945 code += "\tif t." + field_field + " != nil {\n";
946 std::string length = field_var + "Length";
947 std::string offsets = field_var + "Offsets";
948 code += "\t\t" + length + " := len(t." + field_field + ")\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800949 if (field.value.type.element == BASE_TYPE_STRING) {
950 code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
951 length + ")\n";
952 code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
953 code += "\t\t\t" + offsets + "[j] = builder.CreateString(t." +
James Kuszmaul8e62b022022-03-22 09:33:25 -0700954 field_field + "[j])\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800955 code += "\t\t}\n";
956 } else if (field.value.type.element == BASE_TYPE_STRUCT &&
957 !field.value.type.struct_def->fixed) {
958 code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
959 length + ")\n";
960 code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700961 code += "\t\t\t" + offsets + "[j] = t." + field_field +
Austin Schuh272c6132020-11-14 16:37:52 -0800962 "[j].Pack(builder)\n";
963 code += "\t\t}\n";
964 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700965 code += "\t\t" + struct_type + "Start" + namer_.Function(field.name) +
Austin Schuh272c6132020-11-14 16:37:52 -0800966 "Vector(builder, " + length + ")\n";
967 code += "\t\tfor j := " + length + " - 1; j >= 0; j-- {\n";
968 if (IsScalar(field.value.type.element)) {
969 code += "\t\t\tbuilder.Prepend" +
James Kuszmaul8e62b022022-03-22 09:33:25 -0700970 namer_.Method(GenTypeBasic(field.value.type.VectorType())) +
971 "(" +
Austin Schuh272c6132020-11-14 16:37:52 -0800972 CastToBaseType(field.value.type.VectorType(),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700973 "t." + field_field + "[j]") +
Austin Schuh272c6132020-11-14 16:37:52 -0800974 ")\n";
975 } else if (field.value.type.element == BASE_TYPE_STRUCT &&
976 field.value.type.struct_def->fixed) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700977 code += "\t\t\tt." + field_field + "[j].Pack(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800978 } else {
979 code += "\t\t\tbuilder.PrependUOffsetT(" + offsets + "[j])\n";
980 }
981 code += "\t\t}\n";
982 code += "\t\t" + offset + " = builder.EndVector(" + length + ")\n";
983 code += "\t}\n";
984 } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
985 if (field.value.type.struct_def->fixed) continue;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700986 code += "\t" + offset + " := t." + field_field + ".Pack(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800987 } else if (field.value.type.base_type == BASE_TYPE_UNION) {
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 code += "\t\n";
990 } else {
991 FLATBUFFERS_ASSERT(0);
992 }
993 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700994 code += "\t" + struct_type + "Start(builder)\n";
Austin Schuh272c6132020-11-14 16:37:52 -0800995 for (auto it = struct_def.fields.vec.begin();
996 it != struct_def.fields.vec.end(); ++it) {
997 const FieldDef &field = **it;
998 if (field.deprecated) continue;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700999 const std::string field_field = namer_.Field(field.name);
1000 const std::string field_fn = namer_.Function(field.name);
1001 const std::string offset = namer_.Variable(field.name) + "Offset";
Austin Schuh272c6132020-11-14 16:37:52 -08001002
Austin Schuh272c6132020-11-14 16:37:52 -08001003 if (IsScalar(field.value.type.base_type)) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001004 std::string prefix;
1005 if (field.IsScalarOptional()) {
1006 code += "\tif t." + field_field + " != nil {\n\t";
1007 prefix = "*";
1008 }
Austin Schuh272c6132020-11-14 16:37:52 -08001009 if (field.value.type.enum_def == nullptr ||
1010 !field.value.type.enum_def->is_union) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001011 code += "\t" + struct_type + "Add" + field_fn + "(builder, " +
1012 prefix + "t." + field_field + ")\n";
1013 }
1014 if (field.IsScalarOptional()) {
1015 code += "\t}\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001016 }
1017 } 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;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001040 const std::string struct_type = namer_.Type(struct_def.name);
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;
James Kuszmaul8e62b022022-03-22 09:33:25 -07001048 const std::string field_field = namer_.Field(field.name);
1049 const std::string field_var = namer_.Variable(field.name);
1050 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";
1092 code += "\tif rcv." + namer_.Method(field.name) + "(&" + field_table +
1093 ") {\n";
1094 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";
James Kuszmaul8e62b022022-03-22 09:33:25 -07001119 code += "\treturn Create" + namer_.Type(struct_def.name) + "(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,
James Kuszmaul8e62b022022-03-22 09:33:25 -07001133 (nameprefix + namer_.Field(field.name) + ".").c_str(),
Austin Schuh272c6132020-11-14 16:37:52 -08001134 code_ptr);
1135 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001136 code += std::string(", t.") + nameprefix + namer_.Field(field.name);
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
James Kuszmaul8e62b022022-03-22 09:33:25 -07001145 code += "func (rcv *" + namer_.Type(struct_def.name) + ") 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) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001151 code += "\tt." + namer_.Field(field.name) + " = rcv." +
1152 namer_.Method(field.name) + "(nil).UnPack()\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001153 } else {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001154 code += "\tt." + namer_.Field(field.name) + " = rcv." +
1155 namer_.Method(field.name) + "()\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001156 }
1157 }
1158 code += "}\n\n";
1159
James Kuszmaul8e62b022022-03-22 09:33:25 -07001160 code += "func (rcv *" + namer_.Type(struct_def.name) + ") 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;
1250 if (field.IsScalarOptional()) {
1251 prefix = "*";
1252 }
1253 return prefix + GenTypeGet(field.value.type);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001254 }
1255
1256 // If type is an enum, returns value with a cast to the enum type, otherwise
1257 // returns value as-is.
1258 std::string CastToEnum(const Type &type, std::string value) {
1259 if (type.enum_def == nullptr) {
1260 return value;
1261 } else {
1262 return GenTypeGet(type) + "(" + value + ")";
1263 }
1264 }
1265
1266 // If type is an enum, returns value with a cast to the enum base type,
1267 // otherwise returns value as-is.
1268 std::string CastToBaseType(const Type &type, std::string value) {
1269 if (type.enum_def == nullptr) {
1270 return value;
1271 } else {
1272 return GenTypeBasic(type) + "(" + value + ")";
1273 }
1274 }
1275
1276 std::string GenConstant(const FieldDef &field) {
James Kuszmaul8e62b022022-03-22 09:33:25 -07001277 if (field.IsScalarOptional()) {
1278 return "nil";
1279 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001280 switch (field.value.type.base_type) {
Austin Schuh272c6132020-11-14 16:37:52 -08001281 case BASE_TYPE_BOOL:
1282 return field.value.constant == "0" ? "false" : "true";
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001283 default: return field.value.constant;
1284 }
1285 }
1286
James Kuszmaul8e62b022022-03-22 09:33:25 -07001287 std::string NativeName(const StructDef &struct_def) const {
1288 return namer_.ObjectType(struct_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001289 }
1290
James Kuszmaul8e62b022022-03-22 09:33:25 -07001291 std::string NativeName(const EnumDef &enum_def) const {
1292 return namer_.ObjectType(enum_def.name);
Austin Schuh272c6132020-11-14 16:37:52 -08001293 }
1294
1295 std::string NativeType(const Type &type) {
1296 if (IsScalar(type.base_type)) {
1297 if (type.enum_def == nullptr) {
1298 return GenTypeBasic(type);
1299 } else {
1300 return GetEnumTypeName(*type.enum_def);
1301 }
1302 } else if (IsString(type)) {
1303 return "string";
1304 } else if (IsVector(type)) {
1305 return "[]" + NativeType(type.VectorType());
1306 } else if (type.base_type == BASE_TYPE_STRUCT) {
1307 return "*" + WrapInNameSpaceAndTrack(type.struct_def->defined_namespace,
1308 NativeName(*type.struct_def));
1309 } else if (type.base_type == BASE_TYPE_UNION) {
1310 return "*" + WrapInNameSpaceAndTrack(type.enum_def->defined_namespace,
1311 NativeName(*type.enum_def));
1312 }
1313 FLATBUFFERS_ASSERT(0);
1314 return std::string();
1315 }
1316
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001317 // Create a struct with a builder and the struct's arguments.
1318 void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
1319 BeginBuilderArgs(struct_def, code_ptr);
1320 StructBuilderArgs(struct_def, "", code_ptr);
1321 EndBuilderArgs(code_ptr);
1322
1323 StructBuilderBody(struct_def, "", code_ptr);
1324 EndBuilderBody(code_ptr);
1325 }
1326 // Begin by declaring namespace and imports.
1327 void BeginFile(const std::string &name_space_name, const bool needs_imports,
1328 const bool is_enum, std::string *code_ptr) {
1329 std::string &code = *code_ptr;
Austin Schuh272c6132020-11-14 16:37:52 -08001330 code = code +
1331 "// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001332 code += "package " + name_space_name + "\n\n";
1333 if (needs_imports) {
1334 code += "import (\n";
Austin Schuh272c6132020-11-14 16:37:52 -08001335 if (is_enum) { code += "\t\"strconv\"\n\n"; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001336 if (!parser_.opts.go_import.empty()) {
1337 code += "\tflatbuffers \"" + parser_.opts.go_import + "\"\n";
1338 } else {
1339 code += "\tflatbuffers \"github.com/google/flatbuffers/go\"\n";
1340 }
1341 if (tracked_imported_namespaces_.size() > 0) {
1342 code += "\n";
1343 for (auto it = tracked_imported_namespaces_.begin();
Austin Schuh272c6132020-11-14 16:37:52 -08001344 it != tracked_imported_namespaces_.end(); ++it) {
1345 code += "\t" + NamespaceImportName(*it) + " \"" +
1346 NamespaceImportPath(*it) + "\"\n";
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001347 }
1348 }
1349 code += ")\n\n";
1350 } else {
Austin Schuh272c6132020-11-14 16:37:52 -08001351 if (is_enum) { code += "import \"strconv\"\n\n"; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001352 }
1353 }
1354
1355 // Save out the generated code for a Go Table type.
1356 bool SaveType(const Definition &def, const std::string &classcode,
1357 const bool needs_imports, const bool is_enum) {
1358 if (!classcode.length()) return true;
1359
1360 Namespace &ns = go_namespace_.components.empty() ? *def.defined_namespace
1361 : go_namespace_;
1362 std::string code = "";
1363 BeginFile(LastNamespacePart(ns), needs_imports, is_enum, &code);
1364 code += classcode;
1365 // Strip extra newlines at end of file to make it gofmt-clean.
1366 while (code.length() > 2 && code.substr(code.length() - 2) == "\n\n") {
1367 code.pop_back();
1368 }
James Kuszmaul8e62b022022-03-22 09:33:25 -07001369 std::string filename = namer_.Directories(ns.components) +
1370 namer_.File(def.name, SkipFile::Suffix);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001371 return SaveFile(filename.c_str(), code, false);
1372 }
1373
1374 // Create the full name of the imported namespace (format: A__B__C).
James Kuszmaul8e62b022022-03-22 09:33:25 -07001375 std::string NamespaceImportName(const Namespace *ns) const {
1376 return namer_.Namespace(ns->components);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001377 }
1378
1379 // Create the full path for the imported namespace (format: A/B/C).
James Kuszmaul8e62b022022-03-22 09:33:25 -07001380 std::string NamespaceImportPath(const Namespace *ns) const {
1381 return namer_.Directories(ns->components,
1382 SkipDir::OutputPathAndTrailingPathSeparator);
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001383 }
1384
1385 // Ensure that a type is prefixed with its go package import name if it is
1386 // used outside of its namespace.
1387 std::string WrapInNameSpaceAndTrack(const Namespace *ns,
1388 const std::string &name) {
1389 if (CurrentNameSpace() == ns) return name;
1390
1391 tracked_imported_namespaces_.insert(ns);
James Kuszmaul8e62b022022-03-22 09:33:25 -07001392 return NamespaceImportName(ns) + "." + name;
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001393 }
1394
1395 std::string WrapInNameSpaceAndTrack(const Definition &def) {
1396 return WrapInNameSpaceAndTrack(def.defined_namespace, def.name);
1397 }
1398
1399 const Namespace *CurrentNameSpace() const { return cur_name_space_; }
1400
1401 static size_t MaxNameLength(const EnumDef &enum_def) {
1402 size_t max = 0;
Austin Schuh272c6132020-11-14 16:37:52 -08001403 for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001404 max = std::max((*it)->name.length(), max);
1405 }
1406 return max;
1407 }
1408};
1409} // namespace go
1410
1411bool GenerateGo(const Parser &parser, const std::string &path,
1412 const std::string &file_name) {
1413 go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace);
1414 return generator.generate();
1415}
1416
1417} // namespace flatbuffers