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