• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
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"
26 
27 #ifdef _WIN32
28 #  include <direct.h>
29 #  define PATH_SEPARATOR "\\"
30 #  define mkdir(n, m) _mkdir(n)
31 #else
32 #  include <sys/stat.h>
33 #  define PATH_SEPARATOR "/"
34 #endif
35 
36 namespace flatbuffers {
37 
38 namespace go {
39 
40 // see https://golang.org/ref/spec#Keywords
41 static const char *const g_golang_keywords[] = {
42   "break",  "default", "func",        "interface", "select", "case", "defer",
43   "go",     "map",     "struct",      "chan",      "else",   "goto", "package",
44   "switch", "const",   "fallthrough", "if",        "range",  "type", "continue",
45   "for",    "import",  "return",      "var",
46 };
47 
GoIdentity(const std::string & name)48 static std::string GoIdentity(const std::string &name) {
49   for (size_t i = 0;
50        i < sizeof(g_golang_keywords) / sizeof(g_golang_keywords[0]); i++) {
51     if (name == g_golang_keywords[i]) { return MakeCamel(name + "_", false); }
52   }
53 
54   return MakeCamel(name, false);
55 }
56 
57 class GoGenerator : public BaseGenerator {
58  public:
GoGenerator(const Parser & parser,const std::string & path,const std::string & file_name,const std::string & go_namespace)59   GoGenerator(const Parser &parser, const std::string &path,
60               const std::string &file_name, const std::string &go_namespace)
61       : BaseGenerator(parser, path, file_name, "" /* not used*/,
62                       "" /* not used */, "go"),
63         cur_name_space_(nullptr) {
64     std::istringstream iss(go_namespace);
65     std::string component;
66     while (std::getline(iss, component, '.')) {
67       go_namespace_.components.push_back(component);
68     }
69   }
70 
generate()71   bool generate() {
72     std::string one_file_code;
73     bool needs_imports = false;
74     for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
75          ++it) {
76       tracked_imported_namespaces_.clear();
77       needs_imports = false;
78       std::string enumcode;
79       GenEnum(**it, &enumcode);
80       if ((*it)->is_union && parser_.opts.generate_object_based_api) {
81         GenNativeUnion(**it, &enumcode);
82         GenNativeUnionPack(**it, &enumcode);
83         GenNativeUnionUnPack(**it, &enumcode);
84         needs_imports = true;
85       }
86       if (parser_.opts.one_file) {
87         one_file_code += enumcode;
88       } else {
89         if (!SaveType(**it, enumcode, needs_imports, true)) return false;
90       }
91     }
92 
93     for (auto it = parser_.structs_.vec.begin();
94          it != parser_.structs_.vec.end(); ++it) {
95       tracked_imported_namespaces_.clear();
96       std::string declcode;
97       GenStruct(**it, &declcode);
98       if (parser_.opts.one_file) {
99         one_file_code += declcode;
100       } else {
101         if (!SaveType(**it, declcode, true, false)) return false;
102       }
103     }
104 
105     if (parser_.opts.one_file) {
106       std::string code = "";
107       const bool is_enum = !parser_.enums_.vec.empty();
108       BeginFile(LastNamespacePart(go_namespace_), true, is_enum, &code);
109       code += one_file_code;
110       const std::string filename =
111           GeneratedFileName(path_, file_name_, parser_.opts);
112       return SaveFile(filename.c_str(), code, false);
113     }
114 
115     return true;
116   }
117 
118  private:
119   Namespace go_namespace_;
120   Namespace *cur_name_space_;
121 
122   struct NamespacePtrLess {
operator ()flatbuffers::go::GoGenerator::NamespacePtrLess123     bool operator()(const Namespace *a, const Namespace *b) const {
124       return *a < *b;
125     }
126   };
127   std::set<const Namespace *, NamespacePtrLess> tracked_imported_namespaces_;
128 
129   // Most field accessors need to retrieve and test the field offset first,
130   // this is the prefix code for that.
OffsetPrefix(const FieldDef & field)131   std::string OffsetPrefix(const FieldDef &field) {
132     return "{\n\to := flatbuffers.UOffsetT(rcv._tab.Offset(" +
133            NumToString(field.value.offset) + "))\n\tif o != 0 {\n";
134   }
135 
136   // Begin a class declaration.
BeginClass(const StructDef & struct_def,std::string * code_ptr)137   void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
138     std::string &code = *code_ptr;
139 
140     code += "type " + struct_def.name + " struct {\n\t";
141 
142     // _ is reserved in flatbuffers field names, so no chance of name conflict:
143     code += "_tab ";
144     code += struct_def.fixed ? "flatbuffers.Struct" : "flatbuffers.Table";
145     code += "\n}\n\n";
146   }
147 
148   // Construct the name of the type for this enum.
GetEnumTypeName(const EnumDef & enum_def)149   std::string GetEnumTypeName(const EnumDef &enum_def) {
150     return WrapInNameSpaceAndTrack(enum_def.defined_namespace,
151                                    GoIdentity(enum_def.name));
152   }
153 
154   // Create a type for the enum values.
GenEnumType(const EnumDef & enum_def,std::string * code_ptr)155   void GenEnumType(const EnumDef &enum_def, std::string *code_ptr) {
156     std::string &code = *code_ptr;
157     code += "type " + GetEnumTypeName(enum_def) + " ";
158     code += GenTypeBasic(enum_def.underlying_type) + "\n\n";
159   }
160 
161   // Begin enum code with a class declaration.
BeginEnum(std::string * code_ptr)162   void BeginEnum(std::string *code_ptr) {
163     std::string &code = *code_ptr;
164     code += "const (\n";
165   }
166 
167   // A single enum member.
EnumMember(const EnumDef & enum_def,const EnumVal & ev,size_t max_name_length,std::string * code_ptr)168   void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
169                   size_t max_name_length, std::string *code_ptr) {
170     std::string &code = *code_ptr;
171     code += "\t";
172     code += enum_def.name;
173     code += ev.name;
174     code += " ";
175     code += std::string(max_name_length - ev.name.length(), ' ');
176     code += GetEnumTypeName(enum_def);
177     code += " = ";
178     code += enum_def.ToString(ev) + "\n";
179   }
180 
181   // End enum code.
EndEnum(std::string * code_ptr)182   void EndEnum(std::string *code_ptr) {
183     std::string &code = *code_ptr;
184     code += ")\n\n";
185   }
186 
187   // Begin enum name map.
BeginEnumNames(const EnumDef & enum_def,std::string * code_ptr)188   void BeginEnumNames(const EnumDef &enum_def, std::string *code_ptr) {
189     std::string &code = *code_ptr;
190     code += "var EnumNames";
191     code += enum_def.name;
192     code += " = map[" + GetEnumTypeName(enum_def) + "]string{\n";
193   }
194 
195   // A single enum name member.
EnumNameMember(const EnumDef & enum_def,const EnumVal & ev,size_t max_name_length,std::string * code_ptr)196   void EnumNameMember(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";
200     code += enum_def.name;
201     code += ev.name;
202     code += ": ";
203     code += std::string(max_name_length - ev.name.length(), ' ');
204     code += "\"";
205     code += ev.name;
206     code += "\",\n";
207   }
208 
209   // End enum name map.
EndEnumNames(std::string * code_ptr)210   void EndEnumNames(std::string *code_ptr) {
211     std::string &code = *code_ptr;
212     code += "}\n\n";
213   }
214 
215   // Generate String() method on enum type.
EnumStringer(const EnumDef & enum_def,std::string * code_ptr)216   void EnumStringer(const EnumDef &enum_def, std::string *code_ptr) {
217     std::string &code = *code_ptr;
218     code += "func (v " + enum_def.name + ") String() string {\n";
219     code += "\tif s, ok := EnumNames" + enum_def.name + "[v]; ok {\n";
220     code += "\t\treturn s\n";
221     code += "\t}\n";
222     code += "\treturn \"" + enum_def.name;
223     code += "(\" + strconv.FormatInt(int64(v), 10) + \")\"\n";
224     code += "}\n\n";
225   }
226 
227   // Begin enum value map.
BeginEnumValues(const EnumDef & enum_def,std::string * code_ptr)228   void BeginEnumValues(const EnumDef &enum_def, std::string *code_ptr) {
229     std::string &code = *code_ptr;
230     code += "var EnumValues";
231     code += enum_def.name;
232     code += " = map[string]" + GetEnumTypeName(enum_def) + "{\n";
233   }
234 
235   // A single enum value member.
EnumValueMember(const EnumDef & enum_def,const EnumVal & ev,size_t max_name_length,std::string * code_ptr)236   void EnumValueMember(const EnumDef &enum_def, const EnumVal &ev,
237                        size_t max_name_length, std::string *code_ptr) {
238     std::string &code = *code_ptr;
239     code += "\t\"";
240     code += ev.name;
241     code += "\": ";
242     code += std::string(max_name_length - ev.name.length(), ' ');
243     code += enum_def.name;
244     code += ev.name;
245     code += ",\n";
246   }
247 
248   // End enum value map.
EndEnumValues(std::string * code_ptr)249   void EndEnumValues(std::string *code_ptr) {
250     std::string &code = *code_ptr;
251     code += "}\n\n";
252   }
253 
254   // Initialize a new struct or table from existing data.
NewRootTypeFromBuffer(const StructDef & struct_def,std::string * code_ptr)255   void NewRootTypeFromBuffer(const StructDef &struct_def,
256                              std::string *code_ptr) {
257     std::string &code = *code_ptr;
258     std::string size_prefix[] = { "", "SizePrefixed" };
259 
260     for (int i = 0; i < 2; i++) {
261       code += "func Get" + size_prefix[i] + "RootAs";
262       code += struct_def.name;
263       code += "(buf []byte, offset flatbuffers.UOffsetT) ";
264       code += "*" + struct_def.name + "";
265       code += " {\n";
266       if (i == 0) {
267         code += "\tn := flatbuffers.GetUOffsetT(buf[offset:])\n";
268       } else {
269         code +=
270             "\tn := "
271             "flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])\n";
272       }
273       code += "\tx := &" + struct_def.name + "{}\n";
274       if (i == 0) {
275         code += "\tx.Init(buf, n+offset)\n";
276       } else {
277         code += "\tx.Init(buf, n+offset+flatbuffers.SizeUint32)\n";
278       }
279       code += "\treturn x\n";
280       code += "}\n\n";
281     }
282   }
283 
284   // Initialize an existing object with other data, to avoid an allocation.
InitializeExisting(const StructDef & struct_def,std::string * code_ptr)285   void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) {
286     std::string &code = *code_ptr;
287 
288     GenReceiver(struct_def, code_ptr);
289     code += " Init(buf []byte, i flatbuffers.UOffsetT) ";
290     code += "{\n";
291     code += "\trcv._tab.Bytes = buf\n";
292     code += "\trcv._tab.Pos = i\n";
293     code += "}\n\n";
294   }
295 
296   // Implement the table accessor
GenTableAccessor(const StructDef & struct_def,std::string * code_ptr)297   void GenTableAccessor(const StructDef &struct_def, std::string *code_ptr) {
298     std::string &code = *code_ptr;
299 
300     GenReceiver(struct_def, code_ptr);
301     code += " Table() flatbuffers.Table ";
302     code += "{\n";
303 
304     if (struct_def.fixed) {
305       code += "\treturn rcv._tab.Table\n";
306     } else {
307       code += "\treturn rcv._tab\n";
308     }
309     code += "}\n\n";
310   }
311 
312   // Get the length of a vector.
GetVectorLen(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)313   void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
314                     std::string *code_ptr) {
315     std::string &code = *code_ptr;
316 
317     GenReceiver(struct_def, code_ptr);
318     code += " " + MakeCamel(field.name) + "Length(";
319     code += ") int " + OffsetPrefix(field);
320     code += "\t\treturn rcv._tab.VectorLen(o)\n\t}\n";
321     code += "\treturn 0\n}\n\n";
322   }
323 
324   // Get a [ubyte] vector as a byte slice.
GetUByteSlice(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)325   void GetUByteSlice(const StructDef &struct_def, const FieldDef &field,
326                      std::string *code_ptr) {
327     std::string &code = *code_ptr;
328 
329     GenReceiver(struct_def, code_ptr);
330     code += " " + MakeCamel(field.name) + "Bytes(";
331     code += ") []byte " + OffsetPrefix(field);
332     code += "\t\treturn rcv._tab.ByteVector(o + rcv._tab.Pos)\n\t}\n";
333     code += "\treturn nil\n}\n\n";
334   }
335 
336   // Get the value of a struct's scalar.
GetScalarFieldOfStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)337   void GetScalarFieldOfStruct(const StructDef &struct_def,
338                               const FieldDef &field, std::string *code_ptr) {
339     std::string &code = *code_ptr;
340     std::string getter = GenGetter(field.value.type);
341     GenReceiver(struct_def, code_ptr);
342     code += " " + MakeCamel(field.name);
343     code += "() " + TypeName(field) + " {\n";
344     code += "\treturn " +
345             CastToEnum(field.value.type,
346                        getter + "(rcv._tab.Pos + flatbuffers.UOffsetT(" +
347                            NumToString(field.value.offset) + "))");
348     code += "\n}\n";
349   }
350 
351   // Get the value of a table's scalar.
GetScalarFieldOfTable(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)352   void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
353                              std::string *code_ptr) {
354     std::string &code = *code_ptr;
355     std::string getter = GenGetter(field.value.type);
356     GenReceiver(struct_def, code_ptr);
357     code += " " + MakeCamel(field.name);
358     code += "() " + TypeName(field) + " ";
359     code += OffsetPrefix(field) + "\t\treturn ";
360     code += CastToEnum(field.value.type, getter + "(o + rcv._tab.Pos)");
361     code += "\n\t}\n";
362     code += "\treturn " + GenConstant(field) + "\n";
363     code += "}\n\n";
364   }
365 
366   // Get a struct by initializing an existing struct.
367   // Specific to Struct.
GetStructFieldOfStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)368   void GetStructFieldOfStruct(const StructDef &struct_def,
369                               const FieldDef &field, std::string *code_ptr) {
370     std::string &code = *code_ptr;
371     GenReceiver(struct_def, code_ptr);
372     code += " " + MakeCamel(field.name);
373     code += "(obj *" + TypeName(field);
374     code += ") *" + TypeName(field);
375     code += " {\n";
376     code += "\tif obj == nil {\n";
377     code += "\t\tobj = new(" + TypeName(field) + ")\n";
378     code += "\t}\n";
379     code += "\tobj.Init(rcv._tab.Bytes, rcv._tab.Pos+";
380     code += NumToString(field.value.offset) + ")";
381     code += "\n\treturn obj\n";
382     code += "}\n";
383   }
384 
385   // Get a struct by initializing an existing struct.
386   // Specific to Table.
GetStructFieldOfTable(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)387   void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
388                              std::string *code_ptr) {
389     std::string &code = *code_ptr;
390     GenReceiver(struct_def, code_ptr);
391     code += " " + MakeCamel(field.name);
392     code += "(obj *";
393     code += TypeName(field);
394     code += ") *" + TypeName(field) + " " + OffsetPrefix(field);
395     if (field.value.type.struct_def->fixed) {
396       code += "\t\tx := o + rcv._tab.Pos\n";
397     } else {
398       code += "\t\tx := rcv._tab.Indirect(o + rcv._tab.Pos)\n";
399     }
400     code += "\t\tif obj == nil {\n";
401     code += "\t\t\tobj = new(" + TypeName(field) + ")\n";
402     code += "\t\t}\n";
403     code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
404     code += "\t\treturn obj\n\t}\n\treturn nil\n";
405     code += "}\n\n";
406   }
407 
408   // Get the value of a string.
GetStringField(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)409   void GetStringField(const StructDef &struct_def, const FieldDef &field,
410                       std::string *code_ptr) {
411     std::string &code = *code_ptr;
412     GenReceiver(struct_def, code_ptr);
413     code += " " + MakeCamel(field.name);
414     code += "() " + TypeName(field) + " ";
415     code += OffsetPrefix(field) + "\t\treturn " + GenGetter(field.value.type);
416     code += "(o + rcv._tab.Pos)\n\t}\n\treturn nil\n";
417     code += "}\n\n";
418   }
419 
420   // Get the value of a union from an object.
GetUnionField(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)421   void GetUnionField(const StructDef &struct_def, const FieldDef &field,
422                      std::string *code_ptr) {
423     std::string &code = *code_ptr;
424     GenReceiver(struct_def, code_ptr);
425     code += " " + MakeCamel(field.name) + "(";
426     code += "obj " + GenTypePointer(field.value.type) + ") bool ";
427     code += OffsetPrefix(field);
428     code += "\t\t" + GenGetter(field.value.type);
429     code += "(obj, o)\n\t\treturn true\n\t}\n";
430     code += "\treturn false\n";
431     code += "}\n\n";
432   }
433 
434   // Get the value of a vector's struct member.
GetMemberOfVectorOfStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)435   void GetMemberOfVectorOfStruct(const StructDef &struct_def,
436                                  const FieldDef &field, std::string *code_ptr) {
437     std::string &code = *code_ptr;
438     auto vectortype = field.value.type.VectorType();
439 
440     GenReceiver(struct_def, code_ptr);
441     code += " " + MakeCamel(field.name);
442     code += "(obj *" + TypeName(field);
443     code += ", j int) bool " + OffsetPrefix(field);
444     code += "\t\tx := rcv._tab.Vector(o)\n";
445     code += "\t\tx += flatbuffers.UOffsetT(j) * ";
446     code += NumToString(InlineSize(vectortype)) + "\n";
447     if (!(vectortype.struct_def->fixed)) {
448       code += "\t\tx = rcv._tab.Indirect(x)\n";
449     }
450     code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
451     code += "\t\treturn true\n\t}\n";
452     code += "\treturn false\n";
453     code += "}\n\n";
454   }
455 
456   // Get the value of a vector's non-struct member.
GetMemberOfVectorOfNonStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)457   void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
458                                     const FieldDef &field,
459                                     std::string *code_ptr) {
460     std::string &code = *code_ptr;
461     auto vectortype = field.value.type.VectorType();
462 
463     GenReceiver(struct_def, code_ptr);
464     code += " " + MakeCamel(field.name);
465     code += "(j int) " + TypeName(field) + " ";
466     code += OffsetPrefix(field);
467     code += "\t\ta := rcv._tab.Vector(o)\n";
468     code += "\t\treturn " +
469             CastToEnum(field.value.type,
470                        GenGetter(field.value.type) +
471                            "(a + flatbuffers.UOffsetT(j*" +
472                            NumToString(InlineSize(vectortype)) + "))");
473     code += "\n\t}\n";
474     if (IsString(vectortype)) {
475       code += "\treturn nil\n";
476     } else if (vectortype.base_type == BASE_TYPE_BOOL) {
477       code += "\treturn false\n";
478     } else {
479       code += "\treturn 0\n";
480     }
481     code += "}\n\n";
482   }
483 
484   // Begin the creator function signature.
BeginBuilderArgs(const StructDef & struct_def,std::string * code_ptr)485   void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
486     std::string &code = *code_ptr;
487 
488     if (code.substr(code.length() - 2) != "\n\n") {
489       // a previous mutate has not put an extra new line
490       code += "\n";
491     }
492     code += "func Create" + struct_def.name;
493     code += "(builder *flatbuffers.Builder";
494   }
495 
496   // Recursively generate arguments for a constructor, to deal with nested
497   // structs.
StructBuilderArgs(const StructDef & struct_def,const char * nameprefix,std::string * code_ptr)498   void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix,
499                          std::string *code_ptr) {
500     for (auto it = struct_def.fields.vec.begin();
501          it != struct_def.fields.vec.end(); ++it) {
502       auto &field = **it;
503       if (IsStruct(field.value.type)) {
504         // Generate arguments for a struct inside a struct. To ensure names
505         // don't clash, and to make it obvious these arguments are constructing
506         // a nested struct, prefix the name with the field name.
507         StructBuilderArgs(*field.value.type.struct_def,
508                           (nameprefix + (field.name + "_")).c_str(), code_ptr);
509       } else {
510         std::string &code = *code_ptr;
511         code += std::string(", ") + nameprefix;
512         code += GoIdentity(field.name);
513         code += " " + TypeName(field);
514       }
515     }
516   }
517 
518   // End the creator function signature.
EndBuilderArgs(std::string * code_ptr)519   void EndBuilderArgs(std::string *code_ptr) {
520     std::string &code = *code_ptr;
521     code += ") flatbuffers.UOffsetT {\n";
522   }
523 
524   // Recursively generate struct construction statements and instert manual
525   // padding.
StructBuilderBody(const StructDef & struct_def,const char * nameprefix,std::string * code_ptr)526   void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
527                          std::string *code_ptr) {
528     std::string &code = *code_ptr;
529     code += "\tbuilder.Prep(" + NumToString(struct_def.minalign) + ", ";
530     code += NumToString(struct_def.bytesize) + ")\n";
531     for (auto it = struct_def.fields.vec.rbegin();
532          it != struct_def.fields.vec.rend(); ++it) {
533       auto &field = **it;
534       if (field.padding)
535         code += "\tbuilder.Pad(" + NumToString(field.padding) + ")\n";
536       if (IsStruct(field.value.type)) {
537         StructBuilderBody(*field.value.type.struct_def,
538                           (nameprefix + (field.name + "_")).c_str(), code_ptr);
539       } else {
540         code += "\tbuilder.Prepend" + GenMethod(field) + "(";
541         code += CastToBaseType(field.value.type,
542                                nameprefix + GoIdentity(field.name)) +
543                 ")\n";
544       }
545     }
546   }
547 
EndBuilderBody(std::string * code_ptr)548   void EndBuilderBody(std::string *code_ptr) {
549     std::string &code = *code_ptr;
550     code += "\treturn builder.Offset()\n";
551     code += "}\n";
552   }
553 
554   // Get the value of a table's starting offset.
GetStartOfTable(const StructDef & struct_def,std::string * code_ptr)555   void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
556     std::string &code = *code_ptr;
557     code += "func " + struct_def.name + "Start";
558     code += "(builder *flatbuffers.Builder) {\n";
559     code += "\tbuilder.StartObject(";
560     code += NumToString(struct_def.fields.vec.size());
561     code += ")\n}\n";
562   }
563 
564   // Set the value of a table's field.
BuildFieldOfTable(const StructDef & struct_def,const FieldDef & field,const size_t offset,std::string * code_ptr)565   void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
566                          const size_t offset, std::string *code_ptr) {
567     std::string &code = *code_ptr;
568     code += "func " + struct_def.name + "Add" + MakeCamel(field.name);
569     code += "(builder *flatbuffers.Builder, ";
570     code += GoIdentity(field.name) + " ";
571     if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
572       code += "flatbuffers.UOffsetT";
573     } else {
574       code += TypeName(field);
575     }
576     code += ") {\n";
577     code += "\tbuilder.Prepend";
578     code += GenMethod(field) + "Slot(";
579     code += NumToString(offset) + ", ";
580     if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
581       code += "flatbuffers.UOffsetT";
582       code += "(";
583       code += GoIdentity(field.name) + ")";
584     } else {
585       code += CastToBaseType(field.value.type, GoIdentity(field.name));
586     }
587     code += ", " + GenConstant(field);
588     code += ")\n}\n";
589   }
590 
591   // Set the value of one of the members of a table's vector.
BuildVectorOfTable(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)592   void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
593                           std::string *code_ptr) {
594     std::string &code = *code_ptr;
595     code += "func " + struct_def.name + "Start";
596     code += MakeCamel(field.name);
597     code += "Vector(builder *flatbuffers.Builder, numElems int) ";
598     code += "flatbuffers.UOffsetT {\n\treturn builder.StartVector(";
599     auto vector_type = field.value.type.VectorType();
600     auto alignment = InlineAlignment(vector_type);
601     auto elem_size = InlineSize(vector_type);
602     code += NumToString(elem_size);
603     code += ", numElems, " + NumToString(alignment);
604     code += ")\n}\n";
605   }
606 
607   // Get the offset of the end of a table.
GetEndOffsetOnTable(const StructDef & struct_def,std::string * code_ptr)608   void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
609     std::string &code = *code_ptr;
610     code += "func " + struct_def.name + "End";
611     code += "(builder *flatbuffers.Builder) flatbuffers.UOffsetT ";
612     code += "{\n\treturn builder.EndObject()\n}\n";
613   }
614 
615   // Generate the receiver for function signatures.
GenReceiver(const StructDef & struct_def,std::string * code_ptr)616   void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
617     std::string &code = *code_ptr;
618     code += "func (rcv *" + struct_def.name + ")";
619   }
620 
621   // Generate a struct field getter, conditioned on its child type(s).
GenStructAccessor(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)622   void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
623                          std::string *code_ptr) {
624     GenComment(field.doc_comment, code_ptr, nullptr, "");
625     if (IsScalar(field.value.type.base_type)) {
626       if (struct_def.fixed) {
627         GetScalarFieldOfStruct(struct_def, field, code_ptr);
628       } else {
629         GetScalarFieldOfTable(struct_def, field, code_ptr);
630       }
631     } else {
632       switch (field.value.type.base_type) {
633         case BASE_TYPE_STRUCT:
634           if (struct_def.fixed) {
635             GetStructFieldOfStruct(struct_def, field, code_ptr);
636           } else {
637             GetStructFieldOfTable(struct_def, field, code_ptr);
638           }
639           break;
640         case BASE_TYPE_STRING:
641           GetStringField(struct_def, field, code_ptr);
642           break;
643         case BASE_TYPE_VECTOR: {
644           auto vectortype = field.value.type.VectorType();
645           if (vectortype.base_type == BASE_TYPE_STRUCT) {
646             GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
647           } else {
648             GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
649           }
650           break;
651         }
652         case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
653         default: FLATBUFFERS_ASSERT(0);
654       }
655     }
656     if (IsVector(field.value.type)) {
657       GetVectorLen(struct_def, field, code_ptr);
658       if (field.value.type.element == BASE_TYPE_UCHAR) {
659         GetUByteSlice(struct_def, field, code_ptr);
660       }
661     }
662   }
663 
664   // Mutate the value of a struct's scalar.
MutateScalarFieldOfStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)665   void MutateScalarFieldOfStruct(const StructDef &struct_def,
666                                  const FieldDef &field, std::string *code_ptr) {
667     std::string &code = *code_ptr;
668     std::string type = MakeCamel(GenTypeBasic(field.value.type));
669     std::string setter = "rcv._tab.Mutate" + type;
670     GenReceiver(struct_def, code_ptr);
671     code += " Mutate" + MakeCamel(field.name);
672     code += "(n " + TypeName(field) + ") bool {\n\treturn " + setter;
673     code += "(rcv._tab.Pos+flatbuffers.UOffsetT(";
674     code += NumToString(field.value.offset) + "), ";
675     code += CastToBaseType(field.value.type, "n") + ")\n}\n\n";
676   }
677 
678   // Mutate the value of a table's scalar.
MutateScalarFieldOfTable(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)679   void MutateScalarFieldOfTable(const StructDef &struct_def,
680                                 const FieldDef &field, std::string *code_ptr) {
681     std::string &code = *code_ptr;
682     std::string type = MakeCamel(GenTypeBasic(field.value.type));
683     std::string setter = "rcv._tab.Mutate" + type + "Slot";
684     GenReceiver(struct_def, code_ptr);
685     code += " Mutate" + MakeCamel(field.name);
686     code += "(n " + TypeName(field) + ") bool {\n\treturn ";
687     code += setter + "(" + NumToString(field.value.offset) + ", ";
688     code += CastToBaseType(field.value.type, "n") + ")\n";
689     code += "}\n\n";
690   }
691 
692   // Mutate an element of a vector of scalars.
MutateElementOfVectorOfNonStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)693   void MutateElementOfVectorOfNonStruct(const StructDef &struct_def,
694                                         const FieldDef &field,
695                                         std::string *code_ptr) {
696     std::string &code = *code_ptr;
697     auto vectortype = field.value.type.VectorType();
698     std::string type = MakeCamel(GenTypeBasic(vectortype));
699     std::string setter = "rcv._tab.Mutate" + type;
700     GenReceiver(struct_def, code_ptr);
701     code += " Mutate" + MakeCamel(field.name);
702     code += "(j int, n " + TypeName(field) + ") bool ";
703     code += OffsetPrefix(field);
704     code += "\t\ta := rcv._tab.Vector(o)\n";
705     code += "\t\treturn " + setter + "(";
706     code += "a+flatbuffers.UOffsetT(j*";
707     code += NumToString(InlineSize(vectortype)) + "), ";
708     code += CastToBaseType(vectortype, "n") + ")\n";
709     code += "\t}\n";
710     code += "\treturn false\n";
711     code += "}\n\n";
712   }
713 
714   // Generate a struct field setter, conditioned on its child type(s).
GenStructMutator(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)715   void GenStructMutator(const StructDef &struct_def, const FieldDef &field,
716                         std::string *code_ptr) {
717     GenComment(field.doc_comment, code_ptr, nullptr, "");
718     if (IsScalar(field.value.type.base_type)) {
719       if (struct_def.fixed) {
720         MutateScalarFieldOfStruct(struct_def, field, code_ptr);
721       } else {
722         MutateScalarFieldOfTable(struct_def, field, code_ptr);
723       }
724     } else if (IsVector(field.value.type)) {
725       if (IsScalar(field.value.type.element)) {
726         MutateElementOfVectorOfNonStruct(struct_def, field, code_ptr);
727       }
728     }
729   }
730 
731   // Generate table constructors, conditioned on its members' types.
GenTableBuilders(const StructDef & struct_def,std::string * code_ptr)732   void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
733     GetStartOfTable(struct_def, code_ptr);
734 
735     for (auto it = struct_def.fields.vec.begin();
736          it != struct_def.fields.vec.end(); ++it) {
737       auto &field = **it;
738       if (field.deprecated) continue;
739 
740       auto offset = it - struct_def.fields.vec.begin();
741       BuildFieldOfTable(struct_def, field, offset, code_ptr);
742       if (IsVector(field.value.type)) {
743         BuildVectorOfTable(struct_def, field, code_ptr);
744       }
745     }
746 
747     GetEndOffsetOnTable(struct_def, code_ptr);
748   }
749 
750   // Generate struct or table methods.
GenStruct(const StructDef & struct_def,std::string * code_ptr)751   void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
752     if (struct_def.generated) return;
753 
754     cur_name_space_ = struct_def.defined_namespace;
755 
756     GenComment(struct_def.doc_comment, code_ptr, nullptr);
757     if (parser_.opts.generate_object_based_api) {
758       GenNativeStruct(struct_def, code_ptr);
759     }
760     BeginClass(struct_def, code_ptr);
761     if (!struct_def.fixed) {
762       // Generate a special accessor for the table that has been declared as
763       // the root type.
764       NewRootTypeFromBuffer(struct_def, code_ptr);
765     }
766     // Generate the Init method that sets the field in a pre-existing
767     // accessor object. This is to allow object reuse.
768     InitializeExisting(struct_def, code_ptr);
769     // Generate _tab accessor
770     GenTableAccessor(struct_def, code_ptr);
771 
772     // Generate struct fields accessors
773     for (auto it = struct_def.fields.vec.begin();
774          it != struct_def.fields.vec.end(); ++it) {
775       auto &field = **it;
776       if (field.deprecated) continue;
777 
778       GenStructAccessor(struct_def, field, code_ptr);
779       GenStructMutator(struct_def, field, code_ptr);
780     }
781 
782     // Generate builders
783     if (struct_def.fixed) {
784       // create a struct constructor function
785       GenStructBuilder(struct_def, code_ptr);
786     } else {
787       // Create a set of functions that allow table construction.
788       GenTableBuilders(struct_def, code_ptr);
789     }
790   }
791 
GenNativeStruct(const StructDef & struct_def,std::string * code_ptr)792   void GenNativeStruct(const StructDef &struct_def, std::string *code_ptr) {
793     std::string &code = *code_ptr;
794 
795     code += "type " + NativeName(struct_def) + " struct {\n";
796     for (auto it = struct_def.fields.vec.begin();
797          it != struct_def.fields.vec.end(); ++it) {
798       const FieldDef &field = **it;
799       if (field.deprecated) continue;
800       if (IsScalar(field.value.type.base_type) &&
801           field.value.type.enum_def != nullptr &&
802           field.value.type.enum_def->is_union)
803         continue;
804       code += "\t" + MakeCamel(field.name) + " " +
805               NativeType(field.value.type) + "\n";
806     }
807     code += "}\n\n";
808 
809     if (!struct_def.fixed) {
810       GenNativeTablePack(struct_def, code_ptr);
811       GenNativeTableUnPack(struct_def, code_ptr);
812     } else {
813       GenNativeStructPack(struct_def, code_ptr);
814       GenNativeStructUnPack(struct_def, code_ptr);
815     }
816   }
817 
GenNativeUnion(const EnumDef & enum_def,std::string * code_ptr)818   void GenNativeUnion(const EnumDef &enum_def, std::string *code_ptr) {
819     std::string &code = *code_ptr;
820     code += "type " + NativeName(enum_def) + " struct {\n";
821     code += "\tType " + enum_def.name + "\n";
822     code += "\tValue interface{}\n";
823     code += "}\n\n";
824   }
825 
GenNativeUnionPack(const EnumDef & enum_def,std::string * code_ptr)826   void GenNativeUnionPack(const EnumDef &enum_def, std::string *code_ptr) {
827     std::string &code = *code_ptr;
828     code += "func (t *" + NativeName(enum_def) +
829             ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
830     code += "\tif t == nil {\n\t\treturn 0\n\t}\n";
831 
832     code += "\tswitch t.Type {\n";
833     for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
834          ++it2) {
835       const EnumVal &ev = **it2;
836       if (ev.IsZero()) continue;
837       code += "\tcase " + enum_def.name + ev.name + ":\n";
838       code += "\t\treturn t.Value.(" + NativeType(ev.union_type) +
839               ").Pack(builder)\n";
840     }
841     code += "\t}\n";
842     code += "\treturn 0\n";
843     code += "}\n\n";
844   }
845 
GenNativeUnionUnPack(const EnumDef & enum_def,std::string * code_ptr)846   void GenNativeUnionUnPack(const EnumDef &enum_def, std::string *code_ptr) {
847     std::string &code = *code_ptr;
848 
849     code += "func (rcv " + enum_def.name +
850             ") UnPack(table flatbuffers.Table) *" + NativeName(enum_def) +
851             " {\n";
852     code += "\tswitch rcv {\n";
853 
854     for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
855          ++it2) {
856       const EnumVal &ev = **it2;
857       if (ev.IsZero()) continue;
858       code += "\tcase " + enum_def.name + ev.name + ":\n";
859       code += "\t\tx := " + ev.union_type.struct_def->name + "{_tab: table}\n";
860 
861       code += "\t\treturn &" +
862               WrapInNameSpaceAndTrack(enum_def.defined_namespace,
863                                       NativeName(enum_def)) +
864               "{ Type: " + enum_def.name + ev.name + ", Value: x.UnPack() }\n";
865     }
866     code += "\t}\n";
867     code += "\treturn nil\n";
868     code += "}\n\n";
869   }
870 
GenNativeTablePack(const StructDef & struct_def,std::string * code_ptr)871   void GenNativeTablePack(const StructDef &struct_def, std::string *code_ptr) {
872     std::string &code = *code_ptr;
873 
874     code += "func (t *" + NativeName(struct_def) +
875             ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
876     code += "\tif t == nil { return 0 }\n";
877     for (auto it = struct_def.fields.vec.begin();
878          it != struct_def.fields.vec.end(); ++it) {
879       const FieldDef &field = **it;
880       if (field.deprecated) continue;
881       if (IsScalar(field.value.type.base_type)) continue;
882 
883       std::string offset = MakeCamel(field.name, false) + "Offset";
884 
885       if (IsString(field.value.type)) {
886         code += "\t" + offset + " := builder.CreateString(t." +
887                 MakeCamel(field.name) + ")\n";
888       } else if (IsVector(field.value.type) &&
889                  field.value.type.element == BASE_TYPE_UCHAR &&
890                  field.value.type.enum_def == nullptr) {
891         code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
892         code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
893         code += "\t\t" + offset + " = builder.CreateByteString(t." +
894                 MakeCamel(field.name) + ")\n";
895         code += "\t}\n";
896       } else if (IsVector(field.value.type)) {
897         code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
898         code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
899         std::string length = MakeCamel(field.name, false) + "Length";
900         std::string offsets = MakeCamel(field.name, false) + "Offsets";
901         code += "\t\t" + length + " := len(t." + MakeCamel(field.name) + ")\n";
902         if (field.value.type.element == BASE_TYPE_STRING) {
903           code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
904                   length + ")\n";
905           code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
906           code += "\t\t\t" + offsets + "[j] = builder.CreateString(t." +
907                   MakeCamel(field.name) + "[j])\n";
908           code += "\t\t}\n";
909         } else if (field.value.type.element == BASE_TYPE_STRUCT &&
910                    !field.value.type.struct_def->fixed) {
911           code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
912                   length + ")\n";
913           code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
914           code += "\t\t\t" + offsets + "[j] = t." + MakeCamel(field.name) +
915                   "[j].Pack(builder)\n";
916           code += "\t\t}\n";
917         }
918         code += "\t\t" + struct_def.name + "Start" + MakeCamel(field.name) +
919                 "Vector(builder, " + length + ")\n";
920         code += "\t\tfor j := " + length + " - 1; j >= 0; j-- {\n";
921         if (IsScalar(field.value.type.element)) {
922           code += "\t\t\tbuilder.Prepend" +
923                   MakeCamel(GenTypeBasic(field.value.type.VectorType())) + "(" +
924                   CastToBaseType(field.value.type.VectorType(),
925                                  "t." + MakeCamel(field.name) + "[j]") +
926                   ")\n";
927         } else if (field.value.type.element == BASE_TYPE_STRUCT &&
928                    field.value.type.struct_def->fixed) {
929           code += "\t\t\tt." + MakeCamel(field.name) + "[j].Pack(builder)\n";
930         } else {
931           code += "\t\t\tbuilder.PrependUOffsetT(" + offsets + "[j])\n";
932         }
933         code += "\t\t}\n";
934         code += "\t\t" + offset + " = builder.EndVector(" + length + ")\n";
935         code += "\t}\n";
936       } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
937         if (field.value.type.struct_def->fixed) continue;
938         code += "\t" + offset + " := t." + MakeCamel(field.name) +
939                 ".Pack(builder)\n";
940       } else if (field.value.type.base_type == BASE_TYPE_UNION) {
941         code += "\t" + offset + " := t." + MakeCamel(field.name) +
942                 ".Pack(builder)\n";
943         code += "\t\n";
944       } else {
945         FLATBUFFERS_ASSERT(0);
946       }
947     }
948     code += "\t" + struct_def.name + "Start(builder)\n";
949     for (auto it = struct_def.fields.vec.begin();
950          it != struct_def.fields.vec.end(); ++it) {
951       const FieldDef &field = **it;
952       if (field.deprecated) continue;
953 
954       std::string offset = MakeCamel(field.name, false) + "Offset";
955       if (IsScalar(field.value.type.base_type)) {
956         if (field.value.type.enum_def == nullptr ||
957             !field.value.type.enum_def->is_union) {
958           code += "\t" + struct_def.name + "Add" + MakeCamel(field.name) +
959                   "(builder, t." + MakeCamel(field.name) + ")\n";
960         }
961       } else {
962         if (field.value.type.base_type == BASE_TYPE_STRUCT &&
963             field.value.type.struct_def->fixed) {
964           code += "\t" + offset + " := t." + MakeCamel(field.name) +
965                   ".Pack(builder)\n";
966         } else if (field.value.type.enum_def != nullptr &&
967                    field.value.type.enum_def->is_union) {
968           code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
969           code += "\t\t" + struct_def.name + "Add" +
970                   MakeCamel(field.name + UnionTypeFieldSuffix()) +
971                   "(builder, t." + MakeCamel(field.name) + ".Type)\n";
972           code += "\t}\n";
973         }
974         code += "\t" + struct_def.name + "Add" + MakeCamel(field.name) +
975                 "(builder, " + offset + ")\n";
976       }
977     }
978     code += "\treturn " + struct_def.name + "End(builder)\n";
979     code += "}\n\n";
980   }
981 
GenNativeTableUnPack(const StructDef & struct_def,std::string * code_ptr)982   void GenNativeTableUnPack(const StructDef &struct_def,
983                             std::string *code_ptr) {
984     std::string &code = *code_ptr;
985 
986     code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" +
987             NativeName(struct_def) + ") {\n";
988     for (auto it = struct_def.fields.vec.begin();
989          it != struct_def.fields.vec.end(); ++it) {
990       const FieldDef &field = **it;
991       if (field.deprecated) continue;
992       std::string field_name_camel = MakeCamel(field.name);
993       std::string length = MakeCamel(field.name, false) + "Length";
994       if (IsScalar(field.value.type.base_type)) {
995         if (field.value.type.enum_def != nullptr &&
996             field.value.type.enum_def->is_union)
997           continue;
998         code +=
999             "\tt." + field_name_camel + " = rcv." + field_name_camel + "()\n";
1000       } else if (IsString(field.value.type)) {
1001         code += "\tt." + field_name_camel + " = string(rcv." +
1002                 field_name_camel + "())\n";
1003       } else if (IsVector(field.value.type) &&
1004                  field.value.type.element == BASE_TYPE_UCHAR &&
1005                  field.value.type.enum_def == nullptr) {
1006         code += "\tt." + field_name_camel + " = rcv." + field_name_camel +
1007                 "Bytes()\n";
1008       } else if (IsVector(field.value.type)) {
1009         code += "\t" + length + " := rcv." + field_name_camel + "Length()\n";
1010         code += "\tt." + field_name_camel + " = make(" +
1011                 NativeType(field.value.type) + ", " + length + ")\n";
1012         code += "\tfor j := 0; j < " + length + "; j++ {\n";
1013         if (field.value.type.element == BASE_TYPE_STRUCT) {
1014           code += "\t\tx := " +
1015                   WrapInNameSpaceAndTrack(*field.value.type.struct_def) +
1016                   "{}\n";
1017           code += "\t\trcv." + field_name_camel + "(&x, j)\n";
1018         }
1019         code += "\t\tt." + field_name_camel + "[j] = ";
1020         if (IsScalar(field.value.type.element)) {
1021           code += "rcv." + field_name_camel + "(j)";
1022         } else if (field.value.type.element == BASE_TYPE_STRING) {
1023           code += "string(rcv." + field_name_camel + "(j))";
1024         } else if (field.value.type.element == BASE_TYPE_STRUCT) {
1025           code += "x.UnPack()";
1026         } else {
1027           // TODO(iceboy): Support vector of unions.
1028           FLATBUFFERS_ASSERT(0);
1029         }
1030         code += "\n";
1031         code += "\t}\n";
1032       } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
1033         code += "\tt." + field_name_camel + " = rcv." + field_name_camel +
1034                 "(nil).UnPack()\n";
1035       } else if (field.value.type.base_type == BASE_TYPE_UNION) {
1036         std::string field_table = MakeCamel(field.name, false) + "Table";
1037         code += "\t" + field_table + " := flatbuffers.Table{}\n";
1038         code +=
1039             "\tif rcv." + MakeCamel(field.name) + "(&" + field_table + ") {\n";
1040         code += "\t\tt." + field_name_camel + " = rcv." +
1041                 MakeCamel(field.name + UnionTypeFieldSuffix()) + "().UnPack(" +
1042                 field_table + ")\n";
1043         code += "\t}\n";
1044       } else {
1045         FLATBUFFERS_ASSERT(0);
1046       }
1047     }
1048     code += "}\n\n";
1049 
1050     code += "func (rcv *" + struct_def.name + ") UnPack() *" +
1051             NativeName(struct_def) + " {\n";
1052     code += "\tif rcv == nil { return nil }\n";
1053     code += "\tt := &" + NativeName(struct_def) + "{}\n";
1054     code += "\trcv.UnPackTo(t)\n";
1055     code += "\treturn t\n";
1056     code += "}\n\n";
1057   }
1058 
GenNativeStructPack(const StructDef & struct_def,std::string * code_ptr)1059   void GenNativeStructPack(const StructDef &struct_def, std::string *code_ptr) {
1060     std::string &code = *code_ptr;
1061 
1062     code += "func (t *" + NativeName(struct_def) +
1063             ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
1064     code += "\tif t == nil { return 0 }\n";
1065     code += "\treturn Create" + struct_def.name + "(builder";
1066     StructPackArgs(struct_def, "", code_ptr);
1067     code += ")\n";
1068     code += "}\n";
1069   }
1070 
StructPackArgs(const StructDef & struct_def,const char * nameprefix,std::string * code_ptr)1071   void StructPackArgs(const StructDef &struct_def, const char *nameprefix,
1072                       std::string *code_ptr) {
1073     std::string &code = *code_ptr;
1074     for (auto it = struct_def.fields.vec.begin();
1075          it != struct_def.fields.vec.end(); ++it) {
1076       const FieldDef &field = **it;
1077       if (field.value.type.base_type == BASE_TYPE_STRUCT) {
1078         StructPackArgs(*field.value.type.struct_def,
1079                        (nameprefix + MakeCamel(field.name) + ".").c_str(),
1080                        code_ptr);
1081       } else {
1082         code += std::string(", t.") + nameprefix + MakeCamel(field.name);
1083       }
1084     }
1085   }
1086 
GenNativeStructUnPack(const StructDef & struct_def,std::string * code_ptr)1087   void GenNativeStructUnPack(const StructDef &struct_def,
1088                              std::string *code_ptr) {
1089     std::string &code = *code_ptr;
1090 
1091     code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" +
1092             NativeName(struct_def) + ") {\n";
1093     for (auto it = struct_def.fields.vec.begin();
1094          it != struct_def.fields.vec.end(); ++it) {
1095       const FieldDef &field = **it;
1096       if (field.value.type.base_type == BASE_TYPE_STRUCT) {
1097         code += "\tt." + MakeCamel(field.name) + " = rcv." +
1098                 MakeCamel(field.name) + "(nil).UnPack()\n";
1099       } else {
1100         code += "\tt." + MakeCamel(field.name) + " = rcv." +
1101                 MakeCamel(field.name) + "()\n";
1102       }
1103     }
1104     code += "}\n\n";
1105 
1106     code += "func (rcv *" + struct_def.name + ") UnPack() *" +
1107             NativeName(struct_def) + " {\n";
1108     code += "\tif rcv == nil { return nil }\n";
1109     code += "\tt := &" + NativeName(struct_def) + "{}\n";
1110     code += "\trcv.UnPackTo(t)\n";
1111     code += "\treturn t\n";
1112     code += "}\n\n";
1113   }
1114 
1115   // Generate enum declarations.
GenEnum(const EnumDef & enum_def,std::string * code_ptr)1116   void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
1117     if (enum_def.generated) return;
1118 
1119     auto max_name_length = MaxNameLength(enum_def);
1120     cur_name_space_ = enum_def.defined_namespace;
1121 
1122     GenComment(enum_def.doc_comment, code_ptr, nullptr);
1123     GenEnumType(enum_def, code_ptr);
1124     BeginEnum(code_ptr);
1125     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1126       const EnumVal &ev = **it;
1127       GenComment(ev.doc_comment, code_ptr, nullptr, "\t");
1128       EnumMember(enum_def, ev, max_name_length, code_ptr);
1129     }
1130     EndEnum(code_ptr);
1131 
1132     BeginEnumNames(enum_def, code_ptr);
1133     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1134       const EnumVal &ev = **it;
1135       EnumNameMember(enum_def, ev, max_name_length, code_ptr);
1136     }
1137     EndEnumNames(code_ptr);
1138 
1139     BeginEnumValues(enum_def, code_ptr);
1140     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1141       auto &ev = **it;
1142       EnumValueMember(enum_def, ev, max_name_length, code_ptr);
1143     }
1144     EndEnumValues(code_ptr);
1145 
1146     EnumStringer(enum_def, code_ptr);
1147   }
1148 
1149   // Returns the function name that is able to read a value of the given type.
GenGetter(const Type & type)1150   std::string GenGetter(const Type &type) {
1151     switch (type.base_type) {
1152       case BASE_TYPE_STRING: return "rcv._tab.ByteVector";
1153       case BASE_TYPE_UNION: return "rcv._tab.Union";
1154       case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
1155       default: return "rcv._tab.Get" + MakeCamel(GenTypeBasic(type));
1156     }
1157   }
1158 
1159   // Returns the method name for use with add/put calls.
GenMethod(const FieldDef & field)1160   std::string GenMethod(const FieldDef &field) {
1161     return IsScalar(field.value.type.base_type)
1162                ? MakeCamel(GenTypeBasic(field.value.type))
1163                : (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
1164   }
1165 
GenTypeBasic(const Type & type)1166   std::string GenTypeBasic(const Type &type) {
1167     // clang-format off
1168     static const char *ctypename[] = {
1169       #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, ...) \
1170         #GTYPE,
1171         FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
1172       #undef FLATBUFFERS_TD
1173     };
1174     // clang-format on
1175     return ctypename[type.base_type];
1176   }
1177 
GenTypePointer(const Type & type)1178   std::string GenTypePointer(const Type &type) {
1179     switch (type.base_type) {
1180       case BASE_TYPE_STRING: return "[]byte";
1181       case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
1182       case BASE_TYPE_STRUCT: return WrapInNameSpaceAndTrack(*type.struct_def);
1183       case BASE_TYPE_UNION:
1184         // fall through
1185       default: return "*flatbuffers.Table";
1186     }
1187   }
1188 
GenTypeGet(const Type & type)1189   std::string GenTypeGet(const Type &type) {
1190     if (type.enum_def != nullptr) { return GetEnumTypeName(*type.enum_def); }
1191     return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
1192   }
1193 
TypeName(const FieldDef & field)1194   std::string TypeName(const FieldDef &field) {
1195     return GenTypeGet(field.value.type);
1196   }
1197 
1198   // If type is an enum, returns value with a cast to the enum type, otherwise
1199   // returns value as-is.
CastToEnum(const Type & type,std::string value)1200   std::string CastToEnum(const Type &type, std::string value) {
1201     if (type.enum_def == nullptr) {
1202       return value;
1203     } else {
1204       return GenTypeGet(type) + "(" + value + ")";
1205     }
1206   }
1207 
1208   // If type is an enum, returns value with a cast to the enum base type,
1209   // otherwise returns value as-is.
CastToBaseType(const Type & type,std::string value)1210   std::string CastToBaseType(const Type &type, std::string value) {
1211     if (type.enum_def == nullptr) {
1212       return value;
1213     } else {
1214       return GenTypeBasic(type) + "(" + value + ")";
1215     }
1216   }
1217 
GenConstant(const FieldDef & field)1218   std::string GenConstant(const FieldDef &field) {
1219     switch (field.value.type.base_type) {
1220       case BASE_TYPE_BOOL:
1221         return field.value.constant == "0" ? "false" : "true";
1222       default: return field.value.constant;
1223     }
1224   }
1225 
NativeName(const StructDef & struct_def)1226   std::string NativeName(const StructDef &struct_def) {
1227     return parser_.opts.object_prefix + struct_def.name +
1228            parser_.opts.object_suffix;
1229   }
1230 
NativeName(const EnumDef & enum_def)1231   std::string NativeName(const EnumDef &enum_def) {
1232     return parser_.opts.object_prefix + enum_def.name +
1233            parser_.opts.object_suffix;
1234   }
1235 
NativeType(const Type & type)1236   std::string NativeType(const Type &type) {
1237     if (IsScalar(type.base_type)) {
1238       if (type.enum_def == nullptr) {
1239         return GenTypeBasic(type);
1240       } else {
1241         return GetEnumTypeName(*type.enum_def);
1242       }
1243     } else if (IsString(type)) {
1244       return "string";
1245     } else if (IsVector(type)) {
1246       return "[]" + NativeType(type.VectorType());
1247     } else if (type.base_type == BASE_TYPE_STRUCT) {
1248       return "*" + WrapInNameSpaceAndTrack(type.struct_def->defined_namespace,
1249                                            NativeName(*type.struct_def));
1250     } else if (type.base_type == BASE_TYPE_UNION) {
1251       return "*" + WrapInNameSpaceAndTrack(type.enum_def->defined_namespace,
1252                                            NativeName(*type.enum_def));
1253     }
1254     FLATBUFFERS_ASSERT(0);
1255     return std::string();
1256   }
1257 
1258   // Create a struct with a builder and the struct's arguments.
GenStructBuilder(const StructDef & struct_def,std::string * code_ptr)1259   void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
1260     BeginBuilderArgs(struct_def, code_ptr);
1261     StructBuilderArgs(struct_def, "", code_ptr);
1262     EndBuilderArgs(code_ptr);
1263 
1264     StructBuilderBody(struct_def, "", code_ptr);
1265     EndBuilderBody(code_ptr);
1266   }
1267   // Begin by declaring namespace and imports.
BeginFile(const std::string & name_space_name,const bool needs_imports,const bool is_enum,std::string * code_ptr)1268   void BeginFile(const std::string &name_space_name, const bool needs_imports,
1269                  const bool is_enum, std::string *code_ptr) {
1270     std::string &code = *code_ptr;
1271     code = code +
1272            "// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n";
1273     code += "package " + name_space_name + "\n\n";
1274     if (needs_imports) {
1275       code += "import (\n";
1276       if (is_enum) { code += "\t\"strconv\"\n\n"; }
1277       if (!parser_.opts.go_import.empty()) {
1278         code += "\tflatbuffers \"" + parser_.opts.go_import + "\"\n";
1279       } else {
1280         code += "\tflatbuffers \"github.com/google/flatbuffers/go\"\n";
1281       }
1282       if (tracked_imported_namespaces_.size() > 0) {
1283         code += "\n";
1284         for (auto it = tracked_imported_namespaces_.begin();
1285              it != tracked_imported_namespaces_.end(); ++it) {
1286           code += "\t" + NamespaceImportName(*it) + " \"" +
1287                   NamespaceImportPath(*it) + "\"\n";
1288         }
1289       }
1290       code += ")\n\n";
1291     } else {
1292       if (is_enum) { code += "import \"strconv\"\n\n"; }
1293     }
1294   }
1295 
1296   // Save out the generated code for a Go Table type.
SaveType(const Definition & def,const std::string & classcode,const bool needs_imports,const bool is_enum)1297   bool SaveType(const Definition &def, const std::string &classcode,
1298                 const bool needs_imports, const bool is_enum) {
1299     if (!classcode.length()) return true;
1300 
1301     Namespace &ns = go_namespace_.components.empty() ? *def.defined_namespace
1302                                                      : go_namespace_;
1303     std::string code = "";
1304     BeginFile(LastNamespacePart(ns), needs_imports, is_enum, &code);
1305     code += classcode;
1306     // Strip extra newlines at end of file to make it gofmt-clean.
1307     while (code.length() > 2 && code.substr(code.length() - 2) == "\n\n") {
1308       code.pop_back();
1309     }
1310     std::string filename = NamespaceDir(ns) + def.name + ".go";
1311     return SaveFile(filename.c_str(), code, false);
1312   }
1313 
1314   // Create the full name of the imported namespace (format: A__B__C).
NamespaceImportName(const Namespace * ns)1315   std::string NamespaceImportName(const Namespace *ns) {
1316     std::string s = "";
1317     for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
1318       if (s.size() == 0) {
1319         s += *it;
1320       } else {
1321         s += "__" + *it;
1322       }
1323     }
1324     return s;
1325   }
1326 
1327   // Create the full path for the imported namespace (format: A/B/C).
NamespaceImportPath(const Namespace * ns)1328   std::string NamespaceImportPath(const Namespace *ns) {
1329     std::string s = "";
1330     for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
1331       if (s.size() == 0) {
1332         s += *it;
1333       } else {
1334         s += "/" + *it;
1335       }
1336     }
1337     return s;
1338   }
1339 
1340   // Ensure that a type is prefixed with its go package import name if it is
1341   // used outside of its namespace.
WrapInNameSpaceAndTrack(const Namespace * ns,const std::string & name)1342   std::string WrapInNameSpaceAndTrack(const Namespace *ns,
1343                                       const std::string &name) {
1344     if (CurrentNameSpace() == ns) return name;
1345 
1346     tracked_imported_namespaces_.insert(ns);
1347 
1348     std::string import_name = NamespaceImportName(ns);
1349     return import_name + "." + name;
1350   }
1351 
WrapInNameSpaceAndTrack(const Definition & def)1352   std::string WrapInNameSpaceAndTrack(const Definition &def) {
1353     return WrapInNameSpaceAndTrack(def.defined_namespace, def.name);
1354   }
1355 
CurrentNameSpace() const1356   const Namespace *CurrentNameSpace() const { return cur_name_space_; }
1357 
MaxNameLength(const EnumDef & enum_def)1358   static size_t MaxNameLength(const EnumDef &enum_def) {
1359     size_t max = 0;
1360     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1361       max = std::max((*it)->name.length(), max);
1362     }
1363     return max;
1364   }
1365 };
1366 }  // namespace go
1367 
GenerateGo(const Parser & parser,const std::string & path,const std::string & file_name)1368 bool GenerateGo(const Parser &parser, const std::string &path,
1369                 const std::string &file_name) {
1370   go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace);
1371   return generator.generate();
1372 }
1373 
1374 }  // namespace flatbuffers
1375