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 
259     code += "func GetRootAs";
260     code += struct_def.name;
261     code += "(buf []byte, offset flatbuffers.UOffsetT) ";
262     code += "*" + struct_def.name + "";
263     code += " {\n";
264     code += "\tn := flatbuffers.GetUOffsetT(buf[offset:])\n";
265     code += "\tx := &" + struct_def.name + "{}\n";
266     code += "\tx.Init(buf, n+offset)\n";
267     code += "\treturn x\n";
268     code += "}\n\n";
269   }
270 
271   // Initialize an existing object with other data, to avoid an allocation.
InitializeExisting(const StructDef & struct_def,std::string * code_ptr)272   void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) {
273     std::string &code = *code_ptr;
274 
275     GenReceiver(struct_def, code_ptr);
276     code += " Init(buf []byte, i flatbuffers.UOffsetT) ";
277     code += "{\n";
278     code += "\trcv._tab.Bytes = buf\n";
279     code += "\trcv._tab.Pos = i\n";
280     code += "}\n\n";
281   }
282 
283   // Implement the table accessor
GenTableAccessor(const StructDef & struct_def,std::string * code_ptr)284   void GenTableAccessor(const StructDef &struct_def, std::string *code_ptr) {
285     std::string &code = *code_ptr;
286 
287     GenReceiver(struct_def, code_ptr);
288     code += " Table() flatbuffers.Table ";
289     code += "{\n";
290 
291     if (struct_def.fixed) {
292       code += "\treturn rcv._tab.Table\n";
293     } else {
294       code += "\treturn rcv._tab\n";
295     }
296     code += "}\n\n";
297   }
298 
299   // Get the length of a vector.
GetVectorLen(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)300   void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
301                     std::string *code_ptr) {
302     std::string &code = *code_ptr;
303 
304     GenReceiver(struct_def, code_ptr);
305     code += " " + MakeCamel(field.name) + "Length(";
306     code += ") int " + OffsetPrefix(field);
307     code += "\t\treturn rcv._tab.VectorLen(o)\n\t}\n";
308     code += "\treturn 0\n}\n\n";
309   }
310 
311   // Get a [ubyte] vector as a byte slice.
GetUByteSlice(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)312   void GetUByteSlice(const StructDef &struct_def, const FieldDef &field,
313                      std::string *code_ptr) {
314     std::string &code = *code_ptr;
315 
316     GenReceiver(struct_def, code_ptr);
317     code += " " + MakeCamel(field.name) + "Bytes(";
318     code += ") []byte " + OffsetPrefix(field);
319     code += "\t\treturn rcv._tab.ByteVector(o + rcv._tab.Pos)\n\t}\n";
320     code += "\treturn nil\n}\n\n";
321   }
322 
323   // Get the value of a struct's scalar.
GetScalarFieldOfStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)324   void GetScalarFieldOfStruct(const StructDef &struct_def,
325                               const FieldDef &field, std::string *code_ptr) {
326     std::string &code = *code_ptr;
327     std::string getter = GenGetter(field.value.type);
328     GenReceiver(struct_def, code_ptr);
329     code += " " + MakeCamel(field.name);
330     code += "() " + TypeName(field) + " {\n";
331     code += "\treturn " +
332             CastToEnum(field.value.type,
333                        getter + "(rcv._tab.Pos + flatbuffers.UOffsetT(" +
334                            NumToString(field.value.offset) + "))");
335     code += "\n}\n";
336   }
337 
338   // Get the value of a table's scalar.
GetScalarFieldOfTable(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)339   void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
340                              std::string *code_ptr) {
341     std::string &code = *code_ptr;
342     std::string getter = GenGetter(field.value.type);
343     GenReceiver(struct_def, code_ptr);
344     code += " " + MakeCamel(field.name);
345     code += "() " + TypeName(field) + " ";
346     code += OffsetPrefix(field) + "\t\treturn ";
347     code += CastToEnum(field.value.type, getter + "(o + rcv._tab.Pos)");
348     code += "\n\t}\n";
349     code += "\treturn " + GenConstant(field) + "\n";
350     code += "}\n\n";
351   }
352 
353   // Get a struct by initializing an existing struct.
354   // Specific to Struct.
GetStructFieldOfStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)355   void GetStructFieldOfStruct(const StructDef &struct_def,
356                               const FieldDef &field, std::string *code_ptr) {
357     std::string &code = *code_ptr;
358     GenReceiver(struct_def, code_ptr);
359     code += " " + MakeCamel(field.name);
360     code += "(obj *" + TypeName(field);
361     code += ") *" + TypeName(field);
362     code += " {\n";
363     code += "\tif obj == nil {\n";
364     code += "\t\tobj = new(" + TypeName(field) + ")\n";
365     code += "\t}\n";
366     code += "\tobj.Init(rcv._tab.Bytes, rcv._tab.Pos+";
367     code += NumToString(field.value.offset) + ")";
368     code += "\n\treturn obj\n";
369     code += "}\n";
370   }
371 
372   // Get a struct by initializing an existing struct.
373   // Specific to Table.
GetStructFieldOfTable(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)374   void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
375                              std::string *code_ptr) {
376     std::string &code = *code_ptr;
377     GenReceiver(struct_def, code_ptr);
378     code += " " + MakeCamel(field.name);
379     code += "(obj *";
380     code += TypeName(field);
381     code += ") *" + TypeName(field) + " " + OffsetPrefix(field);
382     if (field.value.type.struct_def->fixed) {
383       code += "\t\tx := o + rcv._tab.Pos\n";
384     } else {
385       code += "\t\tx := rcv._tab.Indirect(o + rcv._tab.Pos)\n";
386     }
387     code += "\t\tif obj == nil {\n";
388     code += "\t\t\tobj = new(" + TypeName(field) + ")\n";
389     code += "\t\t}\n";
390     code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
391     code += "\t\treturn obj\n\t}\n\treturn nil\n";
392     code += "}\n\n";
393   }
394 
395   // Get the value of a string.
GetStringField(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)396   void GetStringField(const StructDef &struct_def, const FieldDef &field,
397                       std::string *code_ptr) {
398     std::string &code = *code_ptr;
399     GenReceiver(struct_def, code_ptr);
400     code += " " + MakeCamel(field.name);
401     code += "() " + TypeName(field) + " ";
402     code += OffsetPrefix(field) + "\t\treturn " + GenGetter(field.value.type);
403     code += "(o + rcv._tab.Pos)\n\t}\n\treturn nil\n";
404     code += "}\n\n";
405   }
406 
407   // Get the value of a union from an object.
GetUnionField(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)408   void GetUnionField(const StructDef &struct_def, const FieldDef &field,
409                      std::string *code_ptr) {
410     std::string &code = *code_ptr;
411     GenReceiver(struct_def, code_ptr);
412     code += " " + MakeCamel(field.name) + "(";
413     code += "obj " + GenTypePointer(field.value.type) + ") bool ";
414     code += OffsetPrefix(field);
415     code += "\t\t" + GenGetter(field.value.type);
416     code += "(obj, o)\n\t\treturn true\n\t}\n";
417     code += "\treturn false\n";
418     code += "}\n\n";
419   }
420 
421   // Get the value of a vector's struct member.
GetMemberOfVectorOfStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)422   void GetMemberOfVectorOfStruct(const StructDef &struct_def,
423                                  const FieldDef &field, std::string *code_ptr) {
424     std::string &code = *code_ptr;
425     auto vectortype = field.value.type.VectorType();
426 
427     GenReceiver(struct_def, code_ptr);
428     code += " " + MakeCamel(field.name);
429     code += "(obj *" + TypeName(field);
430     code += ", j int) bool " + OffsetPrefix(field);
431     code += "\t\tx := rcv._tab.Vector(o)\n";
432     code += "\t\tx += flatbuffers.UOffsetT(j) * ";
433     code += NumToString(InlineSize(vectortype)) + "\n";
434     if (!(vectortype.struct_def->fixed)) {
435       code += "\t\tx = rcv._tab.Indirect(x)\n";
436     }
437     code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
438     code += "\t\treturn true\n\t}\n";
439     code += "\treturn false\n";
440     code += "}\n\n";
441   }
442 
443   // Get the value of a vector's non-struct member.
GetMemberOfVectorOfNonStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)444   void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
445                                     const FieldDef &field,
446                                     std::string *code_ptr) {
447     std::string &code = *code_ptr;
448     auto vectortype = field.value.type.VectorType();
449 
450     GenReceiver(struct_def, code_ptr);
451     code += " " + MakeCamel(field.name);
452     code += "(j int) " + TypeName(field) + " ";
453     code += OffsetPrefix(field);
454     code += "\t\ta := rcv._tab.Vector(o)\n";
455     code += "\t\treturn " +
456             CastToEnum(field.value.type,
457                        GenGetter(field.value.type) +
458                            "(a + flatbuffers.UOffsetT(j*" +
459                            NumToString(InlineSize(vectortype)) + "))");
460     code += "\n\t}\n";
461     if (vectortype.base_type == BASE_TYPE_STRING) {
462       code += "\treturn nil\n";
463     } else if (vectortype.base_type == BASE_TYPE_BOOL) {
464       code += "\treturn false\n";
465     } else {
466       code += "\treturn 0\n";
467     }
468     code += "}\n\n";
469   }
470 
471   // Begin the creator function signature.
BeginBuilderArgs(const StructDef & struct_def,std::string * code_ptr)472   void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
473     std::string &code = *code_ptr;
474 
475     if (code.substr(code.length() - 2) != "\n\n") {
476       // a previous mutate has not put an extra new line
477       code += "\n";
478     }
479     code += "func Create" + struct_def.name;
480     code += "(builder *flatbuffers.Builder";
481   }
482 
483   // Recursively generate arguments for a constructor, to deal with nested
484   // structs.
StructBuilderArgs(const StructDef & struct_def,const char * nameprefix,std::string * code_ptr)485   void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix,
486                          std::string *code_ptr) {
487     for (auto it = struct_def.fields.vec.begin();
488          it != struct_def.fields.vec.end(); ++it) {
489       auto &field = **it;
490       if (IsStruct(field.value.type)) {
491         // Generate arguments for a struct inside a struct. To ensure names
492         // don't clash, and to make it obvious these arguments are constructing
493         // a nested struct, prefix the name with the field name.
494         StructBuilderArgs(*field.value.type.struct_def,
495                           (nameprefix + (field.name + "_")).c_str(), code_ptr);
496       } else {
497         std::string &code = *code_ptr;
498         code += std::string(", ") + nameprefix;
499         code += GoIdentity(field.name);
500         code += " " + TypeName(field);
501       }
502     }
503   }
504 
505   // End the creator function signature.
EndBuilderArgs(std::string * code_ptr)506   void EndBuilderArgs(std::string *code_ptr) {
507     std::string &code = *code_ptr;
508     code += ") flatbuffers.UOffsetT {\n";
509   }
510 
511   // Recursively generate struct construction statements and instert manual
512   // padding.
StructBuilderBody(const StructDef & struct_def,const char * nameprefix,std::string * code_ptr)513   void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
514                          std::string *code_ptr) {
515     std::string &code = *code_ptr;
516     code += "\tbuilder.Prep(" + NumToString(struct_def.minalign) + ", ";
517     code += NumToString(struct_def.bytesize) + ")\n";
518     for (auto it = struct_def.fields.vec.rbegin();
519          it != struct_def.fields.vec.rend(); ++it) {
520       auto &field = **it;
521       if (field.padding)
522         code += "\tbuilder.Pad(" + NumToString(field.padding) + ")\n";
523       if (IsStruct(field.value.type)) {
524         StructBuilderBody(*field.value.type.struct_def,
525                           (nameprefix + (field.name + "_")).c_str(), code_ptr);
526       } else {
527         code += "\tbuilder.Prepend" + GenMethod(field) + "(";
528         code += CastToBaseType(field.value.type,
529                                nameprefix + GoIdentity(field.name)) +
530                 ")\n";
531       }
532     }
533   }
534 
EndBuilderBody(std::string * code_ptr)535   void EndBuilderBody(std::string *code_ptr) {
536     std::string &code = *code_ptr;
537     code += "\treturn builder.Offset()\n";
538     code += "}\n";
539   }
540 
541   // Get the value of a table's starting offset.
GetStartOfTable(const StructDef & struct_def,std::string * code_ptr)542   void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
543     std::string &code = *code_ptr;
544     code += "func " + struct_def.name + "Start";
545     code += "(builder *flatbuffers.Builder) {\n";
546     code += "\tbuilder.StartObject(";
547     code += NumToString(struct_def.fields.vec.size());
548     code += ")\n}\n";
549   }
550 
551   // Set the value of a table's field.
BuildFieldOfTable(const StructDef & struct_def,const FieldDef & field,const size_t offset,std::string * code_ptr)552   void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
553                          const size_t offset, std::string *code_ptr) {
554     std::string &code = *code_ptr;
555     code += "func " + struct_def.name + "Add" + MakeCamel(field.name);
556     code += "(builder *flatbuffers.Builder, ";
557     code += GoIdentity(field.name) + " ";
558     if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
559       code += "flatbuffers.UOffsetT";
560     } else {
561       code += TypeName(field);
562     }
563     code += ") {\n";
564     code += "\tbuilder.Prepend";
565     code += GenMethod(field) + "Slot(";
566     code += NumToString(offset) + ", ";
567     if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
568       code += "flatbuffers.UOffsetT";
569       code += "(";
570       code += GoIdentity(field.name) + ")";
571     } else {
572       code += CastToBaseType(field.value.type, GoIdentity(field.name));
573     }
574     code += ", " + GenConstant(field);
575     code += ")\n}\n";
576   }
577 
578   // 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)579   void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
580                           std::string *code_ptr) {
581     std::string &code = *code_ptr;
582     code += "func " + struct_def.name + "Start";
583     code += MakeCamel(field.name);
584     code += "Vector(builder *flatbuffers.Builder, numElems int) ";
585     code += "flatbuffers.UOffsetT {\n\treturn builder.StartVector(";
586     auto vector_type = field.value.type.VectorType();
587     auto alignment = InlineAlignment(vector_type);
588     auto elem_size = InlineSize(vector_type);
589     code += NumToString(elem_size);
590     code += ", numElems, " + NumToString(alignment);
591     code += ")\n}\n";
592   }
593 
594   // Get the offset of the end of a table.
GetEndOffsetOnTable(const StructDef & struct_def,std::string * code_ptr)595   void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
596     std::string &code = *code_ptr;
597     code += "func " + struct_def.name + "End";
598     code += "(builder *flatbuffers.Builder) flatbuffers.UOffsetT ";
599     code += "{\n\treturn builder.EndObject()\n}\n";
600   }
601 
602   // Generate the receiver for function signatures.
GenReceiver(const StructDef & struct_def,std::string * code_ptr)603   void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
604     std::string &code = *code_ptr;
605     code += "func (rcv *" + struct_def.name + ")";
606   }
607 
608   // Generate a struct field getter, conditioned on its child type(s).
GenStructAccessor(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)609   void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
610                          std::string *code_ptr) {
611     GenComment(field.doc_comment, code_ptr, nullptr, "");
612     if (IsScalar(field.value.type.base_type)) {
613       if (struct_def.fixed) {
614         GetScalarFieldOfStruct(struct_def, field, code_ptr);
615       } else {
616         GetScalarFieldOfTable(struct_def, field, code_ptr);
617       }
618     } else {
619       switch (field.value.type.base_type) {
620         case BASE_TYPE_STRUCT:
621           if (struct_def.fixed) {
622             GetStructFieldOfStruct(struct_def, field, code_ptr);
623           } else {
624             GetStructFieldOfTable(struct_def, field, code_ptr);
625           }
626           break;
627         case BASE_TYPE_STRING:
628           GetStringField(struct_def, field, code_ptr);
629           break;
630         case BASE_TYPE_VECTOR: {
631           auto vectortype = field.value.type.VectorType();
632           if (vectortype.base_type == BASE_TYPE_STRUCT) {
633             GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
634           } else {
635             GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
636           }
637           break;
638         }
639         case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
640         default: FLATBUFFERS_ASSERT(0);
641       }
642     }
643     if (field.value.type.base_type == BASE_TYPE_VECTOR) {
644       GetVectorLen(struct_def, field, code_ptr);
645       if (field.value.type.element == BASE_TYPE_UCHAR) {
646         GetUByteSlice(struct_def, field, code_ptr);
647       }
648     }
649   }
650 
651   // Mutate the value of a struct's scalar.
MutateScalarFieldOfStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)652   void MutateScalarFieldOfStruct(const StructDef &struct_def,
653                                  const FieldDef &field, std::string *code_ptr) {
654     std::string &code = *code_ptr;
655     std::string type = MakeCamel(GenTypeBasic(field.value.type));
656     std::string setter = "rcv._tab.Mutate" + type;
657     GenReceiver(struct_def, code_ptr);
658     code += " Mutate" + MakeCamel(field.name);
659     code += "(n " + TypeName(field) + ") bool {\n\treturn " + setter;
660     code += "(rcv._tab.Pos+flatbuffers.UOffsetT(";
661     code += NumToString(field.value.offset) + "), ";
662     code += CastToBaseType(field.value.type, "n") + ")\n}\n\n";
663   }
664 
665   // Mutate the value of a table's scalar.
MutateScalarFieldOfTable(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)666   void MutateScalarFieldOfTable(const StructDef &struct_def,
667                                 const FieldDef &field, std::string *code_ptr) {
668     std::string &code = *code_ptr;
669     std::string type = MakeCamel(GenTypeBasic(field.value.type));
670     std::string setter = "rcv._tab.Mutate" + type + "Slot";
671     GenReceiver(struct_def, code_ptr);
672     code += " Mutate" + MakeCamel(field.name);
673     code += "(n " + TypeName(field) + ") bool {\n\treturn ";
674     code += setter + "(" + NumToString(field.value.offset) + ", ";
675     code += CastToBaseType(field.value.type, "n") + ")\n";
676     code += "}\n\n";
677   }
678 
679   // Mutate an element of a vector of scalars.
MutateElementOfVectorOfNonStruct(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)680   void MutateElementOfVectorOfNonStruct(const StructDef &struct_def,
681                                         const FieldDef &field,
682                                         std::string *code_ptr) {
683     std::string &code = *code_ptr;
684     auto vectortype = field.value.type.VectorType();
685     std::string type = MakeCamel(GenTypeBasic(vectortype));
686     std::string setter = "rcv._tab.Mutate" + type;
687     GenReceiver(struct_def, code_ptr);
688     code += " Mutate" + MakeCamel(field.name);
689     code += "(j int, n " + TypeName(field) + ") bool ";
690     code += OffsetPrefix(field);
691     code += "\t\ta := rcv._tab.Vector(o)\n";
692     code += "\t\treturn " + setter + "(";
693     code += "a+flatbuffers.UOffsetT(j*";
694     code += NumToString(InlineSize(vectortype)) + "), ";
695     code += CastToBaseType(vectortype, "n") + ")\n";
696     code += "\t}\n";
697     code += "\treturn false\n";
698     code += "}\n\n";
699   }
700 
701   // Generate a struct field setter, conditioned on its child type(s).
GenStructMutator(const StructDef & struct_def,const FieldDef & field,std::string * code_ptr)702   void GenStructMutator(const StructDef &struct_def, const FieldDef &field,
703                         std::string *code_ptr) {
704     GenComment(field.doc_comment, code_ptr, nullptr, "");
705     if (IsScalar(field.value.type.base_type)) {
706       if (struct_def.fixed) {
707         MutateScalarFieldOfStruct(struct_def, field, code_ptr);
708       } else {
709         MutateScalarFieldOfTable(struct_def, field, code_ptr);
710       }
711     } else if (field.value.type.base_type == BASE_TYPE_VECTOR) {
712       if (IsScalar(field.value.type.element)) {
713         MutateElementOfVectorOfNonStruct(struct_def, field, code_ptr);
714       }
715     }
716   }
717 
718   // Generate table constructors, conditioned on its members' types.
GenTableBuilders(const StructDef & struct_def,std::string * code_ptr)719   void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
720     GetStartOfTable(struct_def, code_ptr);
721 
722     for (auto it = struct_def.fields.vec.begin();
723          it != struct_def.fields.vec.end(); ++it) {
724       auto &field = **it;
725       if (field.deprecated) continue;
726 
727       auto offset = it - struct_def.fields.vec.begin();
728       BuildFieldOfTable(struct_def, field, offset, code_ptr);
729       if (field.value.type.base_type == BASE_TYPE_VECTOR) {
730         BuildVectorOfTable(struct_def, field, code_ptr);
731       }
732     }
733 
734     GetEndOffsetOnTable(struct_def, code_ptr);
735   }
736 
737   // Generate struct or table methods.
GenStruct(const StructDef & struct_def,std::string * code_ptr)738   void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
739     if (struct_def.generated) return;
740 
741     cur_name_space_ = struct_def.defined_namespace;
742 
743     GenComment(struct_def.doc_comment, code_ptr, nullptr);
744     if (parser_.opts.generate_object_based_api) {
745       GenNativeStruct(struct_def, code_ptr);
746     }
747     BeginClass(struct_def, code_ptr);
748     if (!struct_def.fixed) {
749       // Generate a special accessor for the table that has been declared as
750       // the root type.
751       NewRootTypeFromBuffer(struct_def, code_ptr);
752     }
753     // Generate the Init method that sets the field in a pre-existing
754     // accessor object. This is to allow object reuse.
755     InitializeExisting(struct_def, code_ptr);
756     // Generate _tab accessor
757     GenTableAccessor(struct_def, code_ptr);
758 
759     // Generate struct fields accessors
760     for (auto it = struct_def.fields.vec.begin();
761          it != struct_def.fields.vec.end(); ++it) {
762       auto &field = **it;
763       if (field.deprecated) continue;
764 
765       GenStructAccessor(struct_def, field, code_ptr);
766       GenStructMutator(struct_def, field, code_ptr);
767     }
768 
769     // Generate builders
770     if (struct_def.fixed) {
771       // create a struct constructor function
772       GenStructBuilder(struct_def, code_ptr);
773     } else {
774       // Create a set of functions that allow table construction.
775       GenTableBuilders(struct_def, code_ptr);
776     }
777   }
778 
GenNativeStruct(const StructDef & struct_def,std::string * code_ptr)779   void GenNativeStruct(const StructDef &struct_def, std::string *code_ptr) {
780     std::string &code = *code_ptr;
781 
782     code += "type " + NativeName(struct_def) + " struct {\n";
783     for (auto it = struct_def.fields.vec.begin();
784          it != struct_def.fields.vec.end(); ++it) {
785       const FieldDef &field = **it;
786       if (field.deprecated) continue;
787       if (IsScalar(field.value.type.base_type) &&
788           field.value.type.enum_def != nullptr &&
789           field.value.type.enum_def->is_union)
790         continue;
791       code += "\t" + MakeCamel(field.name) + " " +
792               NativeType(field.value.type) + "\n";
793     }
794     code += "}\n\n";
795 
796     if (!struct_def.fixed) {
797       GenNativeTablePack(struct_def, code_ptr);
798       GenNativeTableUnPack(struct_def, code_ptr);
799     } else {
800       GenNativeStructPack(struct_def, code_ptr);
801       GenNativeStructUnPack(struct_def, code_ptr);
802     }
803   }
804 
GenNativeUnion(const EnumDef & enum_def,std::string * code_ptr)805   void GenNativeUnion(const EnumDef &enum_def, std::string *code_ptr) {
806     std::string &code = *code_ptr;
807     code += "type " + NativeName(enum_def) + " struct {\n";
808     code += "\tType " + enum_def.name + "\n";
809     code += "\tValue interface{}\n";
810     code += "}\n\n";
811   }
812 
GenNativeUnionPack(const EnumDef & enum_def,std::string * code_ptr)813   void GenNativeUnionPack(const EnumDef &enum_def, std::string *code_ptr) {
814     std::string &code = *code_ptr;
815     code += "func (t *" + NativeName(enum_def) +
816             ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
817     code += "\tif t == nil {\n\t\treturn 0\n\t}\n";
818 
819     code += "\tswitch t.Type {\n";
820     for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
821          ++it2) {
822       const EnumVal &ev = **it2;
823       if (ev.IsZero()) continue;
824       code += "\tcase " + enum_def.name + ev.name + ":\n";
825       code += "\t\treturn t.Value.(" + NativeType(ev.union_type) +
826               ").Pack(builder)\n";
827     }
828     code += "\t}\n";
829     code += "\treturn 0\n";
830     code += "}\n\n";
831   }
832 
GenNativeUnionUnPack(const EnumDef & enum_def,std::string * code_ptr)833   void GenNativeUnionUnPack(const EnumDef &enum_def, std::string *code_ptr) {
834     std::string &code = *code_ptr;
835 
836     code += "func (rcv " + enum_def.name +
837             ") UnPack(table flatbuffers.Table) *" + NativeName(enum_def) +
838             " {\n";
839     code += "\tswitch rcv {\n";
840 
841     for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
842          ++it2) {
843       const EnumVal &ev = **it2;
844       if (ev.IsZero()) continue;
845       code += "\tcase " + enum_def.name + ev.name + ":\n";
846       code += "\t\tx := " + ev.union_type.struct_def->name + "{_tab: table}\n";
847 
848       code += "\t\treturn &" +
849               WrapInNameSpaceAndTrack(enum_def.defined_namespace,
850                                       NativeName(enum_def)) +
851               "{ Type: " + enum_def.name + ev.name + ", Value: x.UnPack() }\n";
852     }
853     code += "\t}\n";
854     code += "\treturn nil\n";
855     code += "}\n\n";
856   }
857 
GenNativeTablePack(const StructDef & struct_def,std::string * code_ptr)858   void GenNativeTablePack(const StructDef &struct_def, std::string *code_ptr) {
859     std::string &code = *code_ptr;
860 
861     code += "func (t *" + NativeName(struct_def) +
862             ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
863     code += "\tif t == nil { return 0 }\n";
864     for (auto it = struct_def.fields.vec.begin();
865          it != struct_def.fields.vec.end(); ++it) {
866       const FieldDef &field = **it;
867       if (field.deprecated) continue;
868       if (IsScalar(field.value.type.base_type)) continue;
869 
870       std::string offset = MakeCamel(field.name, false) + "Offset";
871 
872       if (field.value.type.base_type == BASE_TYPE_STRING) {
873         code += "\t" + offset + " := builder.CreateString(t." +
874                 MakeCamel(field.name) + ")\n";
875       } else if (field.value.type.base_type == BASE_TYPE_VECTOR &&
876                  field.value.type.element == BASE_TYPE_UCHAR &&
877                  field.value.type.enum_def == nullptr) {
878         code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
879         code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
880         code += "\t\t" + offset + " = builder.CreateByteString(t." +
881                 MakeCamel(field.name) + ")\n";
882         code += "\t}\n";
883       } else if (field.value.type.base_type == BASE_TYPE_VECTOR) {
884         code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
885         code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
886         std::string length = MakeCamel(field.name, false) + "Length";
887         std::string offsets = MakeCamel(field.name, false) + "Offsets";
888         code += "\t\t" + length + " := len(t." + MakeCamel(field.name) + ")\n";
889         if (field.value.type.element == BASE_TYPE_STRING) {
890           code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
891                   length + ")\n";
892           code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
893           code += "\t\t\t" + offsets + "[j] = builder.CreateString(t." +
894                   MakeCamel(field.name) + "[j])\n";
895           code += "\t\t}\n";
896         } else if (field.value.type.element == BASE_TYPE_STRUCT &&
897                    !field.value.type.struct_def->fixed) {
898           code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
899                   length + ")\n";
900           code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
901           code += "\t\t\t" + offsets + "[j] = t." + MakeCamel(field.name) +
902                   "[j].Pack(builder)\n";
903           code += "\t\t}\n";
904         }
905         code += "\t\t" + struct_def.name + "Start" + MakeCamel(field.name) +
906                 "Vector(builder, " + length + ")\n";
907         code += "\t\tfor j := " + length + " - 1; j >= 0; j-- {\n";
908         if (IsScalar(field.value.type.element)) {
909           code += "\t\t\tbuilder.Prepend" +
910                   MakeCamel(GenTypeBasic(field.value.type.VectorType())) + "(" +
911                   CastToBaseType(field.value.type.VectorType(),
912                                  "t." + MakeCamel(field.name) + "[j]") +
913                   ")\n";
914         } else if (field.value.type.element == BASE_TYPE_STRUCT &&
915                    field.value.type.struct_def->fixed) {
916           code += "\t\t\tt." + MakeCamel(field.name) + "[j].Pack(builder)\n";
917         } else {
918           code += "\t\t\tbuilder.PrependUOffsetT(" + offsets + "[j])\n";
919         }
920         code += "\t\t}\n";
921         code += "\t\t" + offset + " = builder.EndVector(" + length + ")\n";
922         code += "\t}\n";
923       } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
924         if (field.value.type.struct_def->fixed) continue;
925         code += "\t" + offset + " := t." + MakeCamel(field.name) +
926                 ".Pack(builder)\n";
927       } else if (field.value.type.base_type == BASE_TYPE_UNION) {
928         code += "\t" + offset + " := t." + MakeCamel(field.name) +
929                 ".Pack(builder)\n";
930         code += "\t\n";
931       } else {
932         FLATBUFFERS_ASSERT(0);
933       }
934     }
935     code += "\t" + struct_def.name + "Start(builder)\n";
936     for (auto it = struct_def.fields.vec.begin();
937          it != struct_def.fields.vec.end(); ++it) {
938       const FieldDef &field = **it;
939       if (field.deprecated) continue;
940 
941       std::string offset = MakeCamel(field.name, false) + "Offset";
942       if (IsScalar(field.value.type.base_type)) {
943         if (field.value.type.enum_def == nullptr ||
944             !field.value.type.enum_def->is_union) {
945           code += "\t" + struct_def.name + "Add" + MakeCamel(field.name) +
946                   "(builder, t." + MakeCamel(field.name) + ")\n";
947         }
948       } else {
949         if (field.value.type.base_type == BASE_TYPE_STRUCT &&
950             field.value.type.struct_def->fixed) {
951           code += "\t" + offset + " := t." + MakeCamel(field.name) +
952                   ".Pack(builder)\n";
953         } else if (field.value.type.enum_def != nullptr &&
954                    field.value.type.enum_def->is_union) {
955           code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
956           code += "\t\t" + struct_def.name + "Add" +
957                   MakeCamel(field.name + UnionTypeFieldSuffix()) +
958                   "(builder, t." + MakeCamel(field.name) + ".Type)\n";
959           code += "\t}\n";
960         }
961         code += "\t" + struct_def.name + "Add" + MakeCamel(field.name) +
962                 "(builder, " + offset + ")\n";
963       }
964     }
965     code += "\treturn " + struct_def.name + "End(builder)\n";
966     code += "}\n\n";
967   }
968 
GenNativeTableUnPack(const StructDef & struct_def,std::string * code_ptr)969   void GenNativeTableUnPack(const StructDef &struct_def,
970                             std::string *code_ptr) {
971     std::string &code = *code_ptr;
972 
973     code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" +
974             NativeName(struct_def) + ") {\n";
975     for (auto it = struct_def.fields.vec.begin();
976          it != struct_def.fields.vec.end(); ++it) {
977       const FieldDef &field = **it;
978       if (field.deprecated) continue;
979       std::string field_name_camel = MakeCamel(field.name);
980       std::string length = MakeCamel(field.name, false) + "Length";
981       if (IsScalar(field.value.type.base_type)) {
982         if (field.value.type.enum_def != nullptr &&
983             field.value.type.enum_def->is_union)
984           continue;
985         code +=
986             "\tt." + field_name_camel + " = rcv." + field_name_camel + "()\n";
987       } else if (field.value.type.base_type == BASE_TYPE_STRING) {
988         code += "\tt." + field_name_camel + " = string(rcv." +
989                 field_name_camel + "())\n";
990       } else if (field.value.type.base_type == BASE_TYPE_VECTOR &&
991                  field.value.type.element == BASE_TYPE_UCHAR &&
992                  field.value.type.enum_def == nullptr) {
993         code += "\tt." + field_name_camel + " = rcv." + field_name_camel +
994                 "Bytes()\n";
995       } else if (field.value.type.base_type == BASE_TYPE_VECTOR) {
996         code += "\t" + length + " := rcv." + field_name_camel + "Length()\n";
997         code += "\tt." + field_name_camel + " = make(" +
998                 NativeType(field.value.type) + ", " + length + ")\n";
999         code += "\tfor j := 0; j < " + length + "; j++ {\n";
1000         if (field.value.type.element == BASE_TYPE_STRUCT) {
1001           code += "\t\tx := " + field.value.type.struct_def->name + "{}\n";
1002           code += "\t\trcv." + field_name_camel + "(&x, j)\n";
1003         }
1004         code += "\t\tt." + field_name_camel + "[j] = ";
1005         if (IsScalar(field.value.type.element)) {
1006           code += "rcv." + field_name_camel + "(j)";
1007         } else if (field.value.type.element == BASE_TYPE_STRING) {
1008           code += "string(rcv." + field_name_camel + "(j))";
1009         } else if (field.value.type.element == BASE_TYPE_STRUCT) {
1010           code += "x.UnPack()";
1011         } else {
1012           // TODO(iceboy): Support vector of unions.
1013           FLATBUFFERS_ASSERT(0);
1014         }
1015         code += "\n";
1016         code += "\t}\n";
1017       } else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
1018         code += "\tt." + field_name_camel + " = rcv." + field_name_camel +
1019                 "(nil).UnPack()\n";
1020       } else if (field.value.type.base_type == BASE_TYPE_UNION) {
1021         std::string field_table = MakeCamel(field.name, false) + "Table";
1022         code += "\t" + field_table + " := flatbuffers.Table{}\n";
1023         code +=
1024             "\tif rcv." + MakeCamel(field.name) + "(&" + field_table + ") {\n";
1025         code += "\t\tt." + field_name_camel + " = rcv." +
1026                 MakeCamel(field.name + UnionTypeFieldSuffix()) + "().UnPack(" +
1027                 field_table + ")\n";
1028         code += "\t}\n";
1029       } else {
1030         FLATBUFFERS_ASSERT(0);
1031       }
1032     }
1033     code += "}\n\n";
1034 
1035     code += "func (rcv *" + struct_def.name + ") UnPack() *" +
1036             NativeName(struct_def) + " {\n";
1037     code += "\tif rcv == nil { return nil }\n";
1038     code += "\tt := &" + NativeName(struct_def) + "{}\n";
1039     code += "\trcv.UnPackTo(t)\n";
1040     code += "\treturn t\n";
1041     code += "}\n\n";
1042   }
1043 
GenNativeStructPack(const StructDef & struct_def,std::string * code_ptr)1044   void GenNativeStructPack(const StructDef &struct_def, std::string *code_ptr) {
1045     std::string &code = *code_ptr;
1046 
1047     code += "func (t *" + NativeName(struct_def) +
1048             ") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
1049     code += "\tif t == nil { return 0 }\n";
1050     code += "\treturn Create" + struct_def.name + "(builder";
1051     StructPackArgs(struct_def, "", code_ptr);
1052     code += ")\n";
1053     code += "}\n";
1054   }
1055 
StructPackArgs(const StructDef & struct_def,const char * nameprefix,std::string * code_ptr)1056   void StructPackArgs(const StructDef &struct_def, const char *nameprefix,
1057                       std::string *code_ptr) {
1058     std::string &code = *code_ptr;
1059     for (auto it = struct_def.fields.vec.begin();
1060          it != struct_def.fields.vec.end(); ++it) {
1061       const FieldDef &field = **it;
1062       if (field.value.type.base_type == BASE_TYPE_STRUCT) {
1063         StructPackArgs(*field.value.type.struct_def,
1064                        (nameprefix + MakeCamel(field.name) + ".").c_str(),
1065                        code_ptr);
1066       } else {
1067         code += std::string(", t.") + nameprefix + MakeCamel(field.name);
1068       }
1069     }
1070   }
1071 
GenNativeStructUnPack(const StructDef & struct_def,std::string * code_ptr)1072   void GenNativeStructUnPack(const StructDef &struct_def,
1073                              std::string *code_ptr) {
1074     std::string &code = *code_ptr;
1075 
1076     code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" +
1077             NativeName(struct_def) + ") {\n";
1078     for (auto it = struct_def.fields.vec.begin();
1079          it != struct_def.fields.vec.end(); ++it) {
1080       const FieldDef &field = **it;
1081       if (field.value.type.base_type == BASE_TYPE_STRUCT) {
1082         code += "\tt." + MakeCamel(field.name) + " = rcv." +
1083                 MakeCamel(field.name) + "(nil).UnPack()\n";
1084       } else {
1085         code += "\tt." + MakeCamel(field.name) + " = rcv." +
1086                 MakeCamel(field.name) + "()\n";
1087       }
1088     }
1089     code += "}\n\n";
1090 
1091     code += "func (rcv *" + struct_def.name + ") UnPack() *" +
1092             NativeName(struct_def) + " {\n";
1093     code += "\tif rcv == nil { return nil }\n";
1094     code += "\tt := &" + NativeName(struct_def) + "{}\n";
1095     code += "\trcv.UnPackTo(t)\n";
1096     code += "\treturn t\n";
1097     code += "}\n\n";
1098   }
1099 
1100   // Generate enum declarations.
GenEnum(const EnumDef & enum_def,std::string * code_ptr)1101   void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
1102     if (enum_def.generated) return;
1103 
1104     auto max_name_length = MaxNameLength(enum_def);
1105     cur_name_space_ = enum_def.defined_namespace;
1106 
1107     GenComment(enum_def.doc_comment, code_ptr, nullptr);
1108     GenEnumType(enum_def, code_ptr);
1109     BeginEnum(code_ptr);
1110     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1111       const EnumVal &ev = **it;
1112       GenComment(ev.doc_comment, code_ptr, nullptr, "\t");
1113       EnumMember(enum_def, ev, max_name_length, code_ptr);
1114     }
1115     EndEnum(code_ptr);
1116 
1117     BeginEnumNames(enum_def, code_ptr);
1118     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1119       const EnumVal &ev = **it;
1120       EnumNameMember(enum_def, ev, max_name_length, code_ptr);
1121     }
1122     EndEnumNames(code_ptr);
1123 
1124     BeginEnumValues(enum_def, code_ptr);
1125     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1126       auto &ev = **it;
1127       EnumValueMember(enum_def, ev, max_name_length, code_ptr);
1128     }
1129     EndEnumValues(code_ptr);
1130 
1131     EnumStringer(enum_def, code_ptr);
1132   }
1133 
1134   // Returns the function name that is able to read a value of the given type.
GenGetter(const Type & type)1135   std::string GenGetter(const Type &type) {
1136     switch (type.base_type) {
1137       case BASE_TYPE_STRING: return "rcv._tab.ByteVector";
1138       case BASE_TYPE_UNION: return "rcv._tab.Union";
1139       case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
1140       default: return "rcv._tab.Get" + MakeCamel(GenTypeBasic(type));
1141     }
1142   }
1143 
1144   // Returns the method name for use with add/put calls.
GenMethod(const FieldDef & field)1145   std::string GenMethod(const FieldDef &field) {
1146     return IsScalar(field.value.type.base_type)
1147                ? MakeCamel(GenTypeBasic(field.value.type))
1148                : (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
1149   }
1150 
GenTypeBasic(const Type & type)1151   std::string GenTypeBasic(const Type &type) {
1152     // clang-format off
1153     static const char *ctypename[] = {
1154       #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, ...) \
1155         #GTYPE,
1156         FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
1157       #undef FLATBUFFERS_TD
1158     };
1159     // clang-format on
1160     return ctypename[type.base_type];
1161   }
1162 
GenTypePointer(const Type & type)1163   std::string GenTypePointer(const Type &type) {
1164     switch (type.base_type) {
1165       case BASE_TYPE_STRING: return "[]byte";
1166       case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
1167       case BASE_TYPE_STRUCT: return WrapInNameSpaceAndTrack(*type.struct_def);
1168       case BASE_TYPE_UNION:
1169         // fall through
1170       default: return "*flatbuffers.Table";
1171     }
1172   }
1173 
GenTypeGet(const Type & type)1174   std::string GenTypeGet(const Type &type) {
1175     if (type.enum_def != nullptr) { return GetEnumTypeName(*type.enum_def); }
1176     return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
1177   }
1178 
TypeName(const FieldDef & field)1179   std::string TypeName(const FieldDef &field) {
1180     return GenTypeGet(field.value.type);
1181   }
1182 
1183   // If type is an enum, returns value with a cast to the enum type, otherwise
1184   // returns value as-is.
CastToEnum(const Type & type,std::string value)1185   std::string CastToEnum(const Type &type, std::string value) {
1186     if (type.enum_def == nullptr) {
1187       return value;
1188     } else {
1189       return GenTypeGet(type) + "(" + value + ")";
1190     }
1191   }
1192 
1193   // If type is an enum, returns value with a cast to the enum base type,
1194   // otherwise returns value as-is.
CastToBaseType(const Type & type,std::string value)1195   std::string CastToBaseType(const Type &type, std::string value) {
1196     if (type.enum_def == nullptr) {
1197       return value;
1198     } else {
1199       return GenTypeBasic(type) + "(" + value + ")";
1200     }
1201   }
1202 
GenConstant(const FieldDef & field)1203   std::string GenConstant(const FieldDef &field) {
1204     switch (field.value.type.base_type) {
1205       case BASE_TYPE_BOOL:
1206         return field.value.constant == "0" ? "false" : "true";
1207       default: return field.value.constant;
1208     }
1209   }
1210 
NativeName(const StructDef & struct_def)1211   std::string NativeName(const StructDef &struct_def) {
1212     return parser_.opts.object_prefix + struct_def.name +
1213            parser_.opts.object_suffix;
1214   }
1215 
NativeName(const EnumDef & enum_def)1216   std::string NativeName(const EnumDef &enum_def) {
1217     return parser_.opts.object_prefix + enum_def.name +
1218            parser_.opts.object_suffix;
1219   }
1220 
NativeType(const Type & type)1221   std::string NativeType(const Type &type) {
1222     if (IsScalar(type.base_type)) {
1223       if (type.enum_def == nullptr) {
1224         return GenTypeBasic(type);
1225       } else {
1226         return GetEnumTypeName(*type.enum_def);
1227       }
1228     } else if (type.base_type == BASE_TYPE_STRING) {
1229       return "string";
1230     } else if (type.base_type == BASE_TYPE_VECTOR) {
1231       return "[]" + NativeType(type.VectorType());
1232     } else if (type.base_type == BASE_TYPE_STRUCT) {
1233       return "*" + WrapInNameSpaceAndTrack(type.struct_def->defined_namespace,
1234                                            NativeName(*type.struct_def));
1235     } else if (type.base_type == BASE_TYPE_UNION) {
1236       return "*" + WrapInNameSpaceAndTrack(type.enum_def->defined_namespace,
1237                                            NativeName(*type.enum_def));
1238     }
1239     FLATBUFFERS_ASSERT(0);
1240     return std::string();
1241   }
1242 
1243   // Create a struct with a builder and the struct's arguments.
GenStructBuilder(const StructDef & struct_def,std::string * code_ptr)1244   void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
1245     BeginBuilderArgs(struct_def, code_ptr);
1246     StructBuilderArgs(struct_def, "", code_ptr);
1247     EndBuilderArgs(code_ptr);
1248 
1249     StructBuilderBody(struct_def, "", code_ptr);
1250     EndBuilderBody(code_ptr);
1251   }
1252   // 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)1253   void BeginFile(const std::string &name_space_name, const bool needs_imports,
1254                  const bool is_enum, std::string *code_ptr) {
1255     std::string &code = *code_ptr;
1256     code = code +
1257            "// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n";
1258     code += "package " + name_space_name + "\n\n";
1259     if (needs_imports) {
1260       code += "import (\n";
1261       if (is_enum) { code += "\t\"strconv\"\n\n"; }
1262       if (!parser_.opts.go_import.empty()) {
1263         code += "\tflatbuffers \"" + parser_.opts.go_import + "\"\n";
1264       } else {
1265         code += "\tflatbuffers \"github.com/google/flatbuffers/go\"\n";
1266       }
1267       if (tracked_imported_namespaces_.size() > 0) {
1268         code += "\n";
1269         for (auto it = tracked_imported_namespaces_.begin();
1270              it != tracked_imported_namespaces_.end(); ++it) {
1271           code += "\t" + NamespaceImportName(*it) + " \"" +
1272                   NamespaceImportPath(*it) + "\"\n";
1273         }
1274       }
1275       code += ")\n\n";
1276     } else {
1277       if (is_enum) { code += "import \"strconv\"\n\n"; }
1278     }
1279   }
1280 
1281   // 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)1282   bool SaveType(const Definition &def, const std::string &classcode,
1283                 const bool needs_imports, const bool is_enum) {
1284     if (!classcode.length()) return true;
1285 
1286     Namespace &ns = go_namespace_.components.empty() ? *def.defined_namespace
1287                                                      : go_namespace_;
1288     std::string code = "";
1289     BeginFile(LastNamespacePart(ns), needs_imports, is_enum, &code);
1290     code += classcode;
1291     // Strip extra newlines at end of file to make it gofmt-clean.
1292     while (code.length() > 2 && code.substr(code.length() - 2) == "\n\n") {
1293       code.pop_back();
1294     }
1295     std::string filename = NamespaceDir(ns) + def.name + ".go";
1296     return SaveFile(filename.c_str(), code, false);
1297   }
1298 
1299   // Create the full name of the imported namespace (format: A__B__C).
NamespaceImportName(const Namespace * ns)1300   std::string NamespaceImportName(const Namespace *ns) {
1301     std::string s = "";
1302     for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
1303       if (s.size() == 0) {
1304         s += *it;
1305       } else {
1306         s += "__" + *it;
1307       }
1308     }
1309     return s;
1310   }
1311 
1312   // Create the full path for the imported namespace (format: A/B/C).
NamespaceImportPath(const Namespace * ns)1313   std::string NamespaceImportPath(const Namespace *ns) {
1314     std::string s = "";
1315     for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
1316       if (s.size() == 0) {
1317         s += *it;
1318       } else {
1319         s += "/" + *it;
1320       }
1321     }
1322     return s;
1323   }
1324 
1325   // Ensure that a type is prefixed with its go package import name if it is
1326   // used outside of its namespace.
WrapInNameSpaceAndTrack(const Namespace * ns,const std::string & name)1327   std::string WrapInNameSpaceAndTrack(const Namespace *ns,
1328                                       const std::string &name) {
1329     if (CurrentNameSpace() == ns) return name;
1330 
1331     tracked_imported_namespaces_.insert(ns);
1332 
1333     std::string import_name = NamespaceImportName(ns);
1334     return import_name + "." + name;
1335   }
1336 
WrapInNameSpaceAndTrack(const Definition & def)1337   std::string WrapInNameSpaceAndTrack(const Definition &def) {
1338     return WrapInNameSpaceAndTrack(def.defined_namespace, def.name);
1339   }
1340 
CurrentNameSpace() const1341   const Namespace *CurrentNameSpace() const { return cur_name_space_; }
1342 
MaxNameLength(const EnumDef & enum_def)1343   static size_t MaxNameLength(const EnumDef &enum_def) {
1344     size_t max = 0;
1345     for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
1346       max = std::max((*it)->name.length(), max);
1347     }
1348     return max;
1349   }
1350 };
1351 }  // namespace go
1352 
GenerateGo(const Parser & parser,const std::string & path,const std::string & file_name)1353 bool GenerateGo(const Parser &parser, const std::string &path,
1354                 const std::string &file_name) {
1355   go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace);
1356   return generator.generate();
1357 }
1358 
1359 }  // namespace flatbuffers
1360