forked from google/flatbuffers
/
idl_gen_csharp.cpp
2252 lines (2159 loc) · 87.3 KB
/
idl_gen_csharp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// independent from idl_parser, since this code is not needed for most clients
#include <unordered_set>
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
static TypedFloatConstantGenerator CSharpFloatGen("Double.", "Single.", "NaN",
"PositiveInfinity",
"NegativeInfinity");
static CommentConfig comment_config = {
nullptr,
"///",
nullptr,
};
namespace csharp {
class CSharpGenerator : public BaseGenerator {
struct FieldArrayLength {
std::string name;
int length;
};
public:
CSharpGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name,
parser.opts.cs_global_alias ? "global::" : "", ".", "cs"),
cur_name_space_(nullptr) {
// clang-format off
// List of keywords retrieved from here:
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/
// One per line to ease comparisons to that list are easier
static const char *const keywords[] = {
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"fixed",
"float",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"stackalloc",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"virtual",
"void",
"volatile",
"while",
nullptr,
// clang-format on
};
for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
}
CSharpGenerator &operator=(const CSharpGenerator &);
bool generate() {
std::string one_file_code;
cur_name_space_ = parser_.current_namespace_;
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
std::string enumcode;
auto &enum_def = **it;
if (!parser_.opts.one_file) cur_name_space_ = enum_def.defined_namespace;
GenEnum(enum_def, &enumcode, parser_.opts);
if (parser_.opts.one_file) {
one_file_code += enumcode;
} else {
if (!SaveType(enum_def.name, *enum_def.defined_namespace, enumcode,
false, parser_.opts))
return false;
}
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
std::string declcode;
auto &struct_def = **it;
if (!parser_.opts.one_file)
cur_name_space_ = struct_def.defined_namespace;
GenStruct(struct_def, &declcode, parser_.opts);
if (parser_.opts.one_file) {
one_file_code += declcode;
} else {
if (!SaveType(struct_def.name, *struct_def.defined_namespace, declcode,
true, parser_.opts))
return false;
}
}
if (parser_.opts.one_file) {
return SaveType(file_name_, *parser_.current_namespace_, one_file_code,
true, parser_.opts);
}
return true;
}
private:
std::unordered_set<std::string> keywords_;
std::string EscapeKeyword(const std::string &name) const {
return keywords_.find(name) == keywords_.end() ? name : "@" + name;
}
std::string Name(const FieldDef &field) const {
std::string name = ConvertCase(field.name, Case::kUpperCamel);
return EscapeKeyword(name);
}
std::string Name(const Definition &def) const {
return EscapeKeyword(def.name);
}
std::string NamespacedName(const Definition &def) const {
return WrapInNameSpace(def.defined_namespace, Name(def));
}
std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
// Save out the generated code for a single class while adding
// declaration boilerplate.
bool SaveType(const std::string &defname, const Namespace &ns,
const std::string &classcode, bool needs_includes,
const IDLOptions &options) const {
if (!classcode.length()) return true;
std::string code =
"// <auto-generated>\n"
"// " +
std::string(FlatBuffersGeneratedWarning()) +
"\n"
"// </auto-generated>\n\n";
std::string namespace_name = FullNamespace(".", ns);
if (!namespace_name.empty()) {
code += "namespace " + namespace_name + "\n{\n\n";
}
if (needs_includes) {
code += "using global::System;\n";
code += "using global::System.Collections.Generic;\n";
code += "using global::Google.FlatBuffers;\n\n";
}
code += classcode;
if (!namespace_name.empty()) { code += "\n}\n"; }
auto filename = NamespaceDir(ns) + defname;
if (options.one_file) { filename += options.filename_suffix; }
filename +=
options.filename_extension.empty() ? ".cs" : options.filename_extension;
return SaveFile(filename.c_str(), code, false);
}
const Namespace *CurrentNameSpace() const { return cur_name_space_; }
std::string GenTypeBasic(const Type &type, bool enableLangOverrides) const {
// clang-format off
static const char * const csharp_typename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, ...) \
#NTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
// clang-format on
if (enableLangOverrides) {
if (IsEnum(type)) return NamespacedName(*type.enum_def);
if (type.base_type == BASE_TYPE_STRUCT) {
return "Offset<" + NamespacedName(*type.struct_def) + ">";
}
}
return csharp_typename[type.base_type];
}
inline std::string GenTypeBasic(const Type &type) const {
return GenTypeBasic(type, true);
}
std::string GenTypePointer(const Type &type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: return "string";
case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
case BASE_TYPE_STRUCT: return NamespacedName(*type.struct_def);
case BASE_TYPE_UNION: return "TTable";
default: return "Table";
}
}
std::string GenTypeGet(const Type &type) const {
return IsScalar(type.base_type)
? GenTypeBasic(type)
: (IsArray(type) ? GenTypeGet(type.VectorType())
: GenTypePointer(type));
}
std::string GenOffsetType(const StructDef &struct_def) const {
return "Offset<" + NamespacedName(struct_def) + ">";
}
std::string GenOffsetConstruct(const StructDef &struct_def,
const std::string &variable_name) const {
return "new Offset<" + NamespacedName(struct_def) + ">(" + variable_name +
")";
}
// Casts necessary to correctly read serialized data
std::string DestinationCast(const Type &type) const {
if (IsSeries(type)) {
return DestinationCast(type.VectorType());
} else {
if (IsEnum(type)) return "(" + NamespacedName(*type.enum_def) + ")";
}
return "";
}
// Cast statements for mutator method parameters.
// In Java, parameters representing unsigned numbers need to be cast down to
// their respective type. For example, a long holding an unsigned int value
// would be cast down to int before being put onto the buffer. In C#, one cast
// directly cast an Enum to its underlying type, which is essential before
// putting it onto the buffer.
std::string SourceCast(const Type &type,
const bool isOptional = false) const {
if (IsSeries(type)) {
return SourceCast(type.VectorType());
} else {
if (IsEnum(type))
return "(" + GenTypeBasic(type, false) + (isOptional ? "?" : "") + ")";
}
return "";
}
std::string SourceCastBasic(const Type &type, const bool isOptional) const {
return IsScalar(type.base_type) ? SourceCast(type, isOptional) : "";
}
std::string GenEnumDefaultValue(const FieldDef &field) const {
auto &value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
auto &enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
return enum_val ? (NamespacedName(enum_def) + "." + Name(*enum_val))
: value.constant;
}
std::string GenDefaultValue(const FieldDef &field,
bool enableLangOverrides) const {
// If it is an optional scalar field, the default is null
if (field.IsScalarOptional()) { return "null"; }
auto &value = field.value;
if (enableLangOverrides) {
// handles both enum case and vector of enum case
if (value.type.enum_def != nullptr &&
value.type.base_type != BASE_TYPE_UNION) {
return GenEnumDefaultValue(field);
}
}
auto longSuffix = "";
switch (value.type.base_type) {
case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
case BASE_TYPE_ULONG: return value.constant;
case BASE_TYPE_UINT:
case BASE_TYPE_LONG: return value.constant + longSuffix;
default:
if (IsFloat(value.type.base_type))
return CSharpFloatGen.GenFloatConstant(field);
else
return value.constant;
}
}
std::string GenDefaultValue(const FieldDef &field) const {
return GenDefaultValue(field, true);
}
std::string GenDefaultValueBasic(const FieldDef &field,
bool enableLangOverrides) const {
auto &value = field.value;
if (!IsScalar(value.type.base_type)) {
if (enableLangOverrides) {
switch (value.type.base_type) {
case BASE_TYPE_STRING: return "default(StringOffset)";
case BASE_TYPE_STRUCT:
return "default(Offset<" + NamespacedName(*value.type.struct_def) +
">)";
case BASE_TYPE_VECTOR: return "default(VectorOffset)";
default: break;
}
}
return "0";
}
return GenDefaultValue(field, enableLangOverrides);
}
std::string GenDefaultValueBasic(const FieldDef &field) const {
return GenDefaultValueBasic(field, true);
}
void GenEnum(EnumDef &enum_def, std::string *code_ptr,
const IDLOptions &opts) const {
std::string &code = *code_ptr;
if (enum_def.generated) return;
// Generate enum definitions of the form:
// public static (final) int name = value;
// In Java, we use ints rather than the Enum feature, because we want them
// to map directly to how they're used in C/C++ and file formats.
// That, and Java Enums are expensive, and not universally liked.
GenComment(enum_def.doc_comment, code_ptr, &comment_config);
if (opts.cs_gen_json_serializer && opts.generate_object_based_api) {
code +=
"[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters."
"StringEnumConverter))]\n";
}
// In C# this indicates enumeration values can be treated as bit flags.
if (enum_def.attributes.Lookup("bit_flags")) {
code += "[System.FlagsAttribute]\n";
}
if (enum_def.attributes.Lookup("private")) {
code += "internal ";
} else {
code += "public ";
}
code += "enum " + Name(enum_def);
code += " : " + GenTypeBasic(enum_def.underlying_type, false);
code += "\n{\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, &comment_config, " ");
code += " ";
code += Name(ev) + " = ";
code += enum_def.ToString(ev);
code += ",\n";
}
// Close the class
code += "};\n\n";
if (opts.generate_object_based_api) {
GenEnum_ObjectAPI(enum_def, code_ptr, opts);
}
}
bool HasUnionStringValue(const EnumDef &enum_def) const {
if (!enum_def.is_union) return false;
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &val = **it;
if (IsString(val.union_type)) { return true; }
}
return false;
}
// Returns the function name that is able to read a value of the given type.
std::string GenGetter(const Type &type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: return "__p.__string";
case BASE_TYPE_STRUCT: return "__p.__struct";
case BASE_TYPE_UNION: return "__p.__union";
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
case BASE_TYPE_ARRAY: return GenGetter(type.VectorType());
default: {
std::string getter = "__p.bb.Get";
if (type.base_type == BASE_TYPE_BOOL) {
getter = "0!=" + getter;
} else if (GenTypeBasic(type, false) != "byte") {
getter += ConvertCase(GenTypeBasic(type, false), Case::kUpperCamel);
}
return getter;
}
}
}
std::string GetObjectConstructor(flatbuffers::StructDef &struct_def,
const std::string &data_buffer,
const std::string &offset) const {
// Use the generated type directly, to properly handle default values that
// might not be written to the buffer.
return "new " + Name(struct_def) + "().__assign(" + offset + ", " +
data_buffer + ")";
}
// Returns the function name that is able to read a value of the given type.
std::string GenGetterForLookupByKey(flatbuffers::StructDef &struct_def,
flatbuffers::FieldDef *key_field,
const std::string &data_buffer,
const std::string &offset) const {
// Use the generated type directly, to properly handle default values that
// might not be written to the buffer.
return GetObjectConstructor(struct_def, data_buffer, offset) + "." +
Name(*key_field);
}
// Direct mutation is only allowed for scalar fields.
// Hence a setter method will only be generated for such fields.
std::string GenSetter(const Type &type) const {
if (IsScalar(type.base_type)) {
std::string setter = "__p.bb.Put";
if (GenTypeBasic(type, false) != "byte" &&
type.base_type != BASE_TYPE_BOOL) {
setter += ConvertCase(GenTypeBasic(type, false), Case::kUpperCamel);
}
return setter;
} else {
return "";
}
}
// Returns the method name for use with add/put calls.
std::string GenMethod(const Type &type) const {
return IsScalar(type.base_type)
? ConvertCase(GenTypeBasic(type, false), Case::kUpperCamel)
: (IsStruct(type) ? "Struct" : "Offset");
}
// Recursively generate arguments for a constructor, to deal with nested
// structs.
void GenStructArgs(const StructDef &struct_def, std::string *code_ptr,
const char *nameprefix, size_t array_count = 0) const {
std::string &code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
const auto &field_type = field.value.type;
const auto array_field = IsArray(field_type);
const auto &type = array_field ? field_type.VectorType() : field_type;
const auto array_cnt = array_field ? (array_count + 1) : array_count;
if (IsStruct(type)) {
// Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious these arguments are constructing
// a nested struct, prefix the name with the field name.
GenStructArgs(*field_type.struct_def, code_ptr,
(nameprefix + (EscapeKeyword(field.name) + "_")).c_str(),
array_cnt);
} else {
code += ", ";
code += GenTypeBasic(type);
if (field.IsScalarOptional()) { code += "?"; }
if (array_cnt > 0) {
code += "[";
for (size_t i = 1; i < array_cnt; i++) code += ",";
code += "]";
}
code += " ";
code += nameprefix;
code += Name(field);
}
}
}
// Recusively generate struct construction statements of the form:
// builder.putType(name);
// and insert manual padding.
void GenStructBody(const StructDef &struct_def, std::string *code_ptr,
const char *nameprefix, size_t index = 0,
bool in_array = false) const {
std::string &code = *code_ptr;
std::string indent((index + 1) * 2, ' ');
code += indent + " builder.Prep(";
code += NumToString(struct_def.minalign) + ", ";
code += NumToString(struct_def.bytesize) + ");\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
auto &field = **it;
const auto &field_type = field.value.type;
if (field.padding) {
code += indent + " builder.Pad(";
code += NumToString(field.padding) + ");\n";
}
if (IsStruct(field_type)) {
GenStructBody(*field_type.struct_def, code_ptr,
(nameprefix + (field.name + "_")).c_str(), index,
in_array);
} else {
const auto &type =
IsArray(field_type) ? field_type.VectorType() : field_type;
const auto index_var = "_idx" + NumToString(index);
if (IsArray(field_type)) {
code += indent + " for (int " + index_var + " = ";
code += NumToString(field_type.fixed_length);
code += "; " + index_var + " > 0; " + index_var + "--) {\n";
in_array = true;
}
if (IsStruct(type)) {
GenStructBody(*field_type.struct_def, code_ptr,
(nameprefix + (field.name + "_")).c_str(), index + 1,
in_array);
} else {
code += IsArray(field_type) ? " " : "";
code += indent + " builder.Put";
code += GenMethod(type) + "(";
code += SourceCast(type);
auto argname = nameprefix + Name(field);
code += argname;
size_t array_cnt = index + (IsArray(field_type) ? 1 : 0);
if (array_cnt > 0) {
code += "[";
for (size_t i = 0; in_array && i < array_cnt; i++) {
code += "_idx" + NumToString(i) + "-1";
if (i != (array_cnt - 1)) code += ",";
}
code += "]";
}
code += ");\n";
}
if (IsArray(field_type)) { code += indent + " }\n"; }
}
}
}
std::string GenOffsetGetter(flatbuffers::FieldDef *key_field,
const char *num = nullptr) const {
std::string key_offset =
"Table.__offset(" + NumToString(key_field->value.offset) + ", ";
if (num) {
key_offset += num;
key_offset += ".Value, builder.DataBuffer)";
} else {
key_offset += "bb.Length";
key_offset += " - tableOffset, bb)";
}
return key_offset;
}
std::string GenKeyGetter(flatbuffers::StructDef &struct_def,
flatbuffers::FieldDef *key_field) const {
// Get the getter for the key of the struct.
return GenGetterForLookupByKey(struct_def, key_field, "builder.DataBuffer",
"builder.DataBuffer.Length - o1.Value") +
".CompareTo(" +
GenGetterForLookupByKey(struct_def, key_field, "builder.DataBuffer",
"builder.DataBuffer.Length - o2.Value") +
")";
}
void GenStruct(StructDef &struct_def, std::string *code_ptr,
const IDLOptions &opts) const {
if (struct_def.generated) return;
std::string &code = *code_ptr;
// Generate a struct accessor class, with methods of the form:
// public type name() { return bb.getType(i + offset); }
// or for tables of the form:
// public type name() {
// int o = __offset(offset); return o != 0 ? bb.getType(o + i) : default;
// }
GenComment(struct_def.doc_comment, code_ptr, &comment_config);
if (struct_def.attributes.Lookup("private")) {
code += "internal ";
} else {
code += "public ";
}
if (struct_def.attributes.Lookup("csharp_partial")) {
// generate a partial class for this C# struct/table
code += "partial ";
}
code += "struct " + struct_def.name;
code += " : IFlatbufferObject";
code += "\n{\n";
code += " private ";
code += struct_def.fixed ? "Struct" : "Table";
code += " __p;\n";
code += " public ByteBuffer ByteBuffer { get { return __p.bb; } }\n";
if (!struct_def.fixed) {
// Generate version check method.
// Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {";
code += " FlatBufferConstants.";
code += "FLATBUFFERS_22_9_29(); ";
code += "}\n";
// Generate a special accessor for the table that when used as the root
// of a FlatBuffer
std::string method_name = "GetRootAs" + struct_def.name;
std::string method_signature =
" public static " + struct_def.name + " " + method_name;
// create convenience method that doesn't require an existing object
code += method_signature + "(ByteBuffer _bb) ";
code += "{ return " + method_name + "(_bb, new " + struct_def.name +
"()); }\n";
// create method that allows object reuse
code +=
method_signature + "(ByteBuffer _bb, " + struct_def.name + " obj) { ";
code += "return (obj.__assign(_bb.GetInt(_bb.Position";
code += ") + _bb.Position";
code += ", _bb)); }\n";
if (parser_.root_struct_def_ == &struct_def) {
if (parser_.file_identifier_.length()) {
// Check if a buffer has the identifier.
code += " public static ";
code += "bool " + struct_def.name;
code += "BufferHasIdentifier(ByteBuffer _bb) { return ";
code += "Table.__has_identifier(_bb, \"";
code += parser_.file_identifier_;
code += "\"); }\n";
}
}
}
// Generate the __init method that sets the field in a pre-existing
// accessor object. This is to allow object reuse.
code += " public void __init(int _i, ByteBuffer _bb) ";
code += "{ ";
code += "__p = new ";
code += struct_def.fixed ? "Struct" : "Table";
code += "(_i, _bb); ";
code += "}\n";
code +=
" public " + struct_def.name + " __assign(int _i, ByteBuffer _bb) ";
code += "{ __init(_i, _bb); return this; }\n\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
GenComment(field.doc_comment, code_ptr, &comment_config, " ");
std::string type_name = GenTypeGet(field.value.type);
std::string type_name_dest = GenTypeGet(field.value.type);
std::string conditional_cast = "";
std::string optional = "";
if (!struct_def.fixed &&
(field.value.type.base_type == BASE_TYPE_STRUCT ||
field.value.type.base_type == BASE_TYPE_UNION ||
(IsVector(field.value.type) &&
(field.value.type.element == BASE_TYPE_STRUCT ||
field.value.type.element == BASE_TYPE_UNION)))) {
optional = "?";
conditional_cast = "(" + type_name_dest + optional + ")";
}
if (field.IsScalarOptional()) { optional = "?"; }
std::string dest_mask = "";
std::string dest_cast = DestinationCast(field.value.type);
std::string src_cast = SourceCast(field.value.type);
std::string field_name_camel = Name(field);
if (field_name_camel == struct_def.name) { field_name_camel += "_"; }
std::string method_start =
" public " + type_name_dest + optional + " " + field_name_camel;
std::string obj = "(new " + type_name + "())";
// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that:
auto offset_prefix =
IsArray(field.value.type)
? " { return "
: (" { int o = __p.__offset(" + NumToString(field.value.offset) +
"); return o != 0 ? ");
// Generate the accessors that don't do object reuse.
if (field.value.type.base_type == BASE_TYPE_STRUCT) {
} else if (IsVector(field.value.type) &&
field.value.type.element == BASE_TYPE_STRUCT) {
} else if (field.value.type.base_type == BASE_TYPE_UNION ||
(IsVector(field.value.type) &&
field.value.type.VectorType().base_type == BASE_TYPE_UNION)) {
method_start += "<TTable>";
type_name = type_name_dest;
}
std::string getter = dest_cast + GenGetter(field.value.type);
code += method_start;
std::string default_cast = "";
// only create default casts for c# scalars or vectors of scalars
if ((IsScalar(field.value.type.base_type) ||
(IsVector(field.value.type) &&
IsScalar(field.value.type.element)))) {
// For scalars, default value will be returned by GetDefaultValue().
// If the scalar is an enum, GetDefaultValue() returns an actual c# enum
// that doesn't need to be casted. However, default values for enum
// elements of vectors are integer literals ("0") and are still casted
// for clarity.
// If the scalar is optional and enum, we still need the cast.
if ((field.value.type.enum_def == nullptr ||
IsVector(field.value.type)) ||
(IsEnum(field.value.type) && field.IsScalarOptional())) {
default_cast = "(" + type_name_dest + optional + ")";
}
}
std::string member_suffix = "; ";
if (IsScalar(field.value.type.base_type)) {
code += " { get";
member_suffix += "} ";
if (struct_def.fixed) {
code += " { return " + getter;
code += "(__p.bb_pos + ";
code += NumToString(field.value.offset) + ")";
code += dest_mask;
} else {
code += offset_prefix + getter;
code += "(o + __p.bb_pos)" + dest_mask;
code += " : " + default_cast;
code += GenDefaultValue(field);
}
} else {
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT:
code += " { get";
member_suffix += "} ";
if (struct_def.fixed) {
code += " { return " + obj + ".__assign(" + "__p.";
code += "bb_pos + " + NumToString(field.value.offset) + ", ";
code += "__p.bb)";
} else {
code += offset_prefix + conditional_cast;
code += obj + ".__assign(";
code += field.value.type.struct_def->fixed
? "o + __p.bb_pos"
: "__p.__indirect(o + __p.bb_pos)";
code += ", __p.bb) : null";
}
break;
case BASE_TYPE_STRING:
code += " { get";
member_suffix += "} ";
code += offset_prefix + getter + "(o + " + "__p.";
code += "bb_pos) : null";
break;
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_UNION) {
conditional_cast = "(TTable?)";
getter += "<TTable>";
}
code += "(";
if (vectortype.base_type == BASE_TYPE_STRUCT) {
getter = obj + ".__assign";
} else if (vectortype.base_type == BASE_TYPE_UNION) {
}
code += "int j)";
const auto body = offset_prefix + conditional_cast + getter + "(";
if (vectortype.base_type == BASE_TYPE_UNION) {
code += " where TTable : struct, IFlatbufferObject" + body;
} else {
code += body;
}
std::string index = "__p.";
if (IsArray(field.value.type)) {
index += "bb_pos + " + NumToString(field.value.offset) + " + ";
} else {
index += "__vector(o) + ";
}
index += "j * " + NumToString(InlineSize(vectortype));
if (vectortype.base_type == BASE_TYPE_STRUCT) {
code += vectortype.struct_def->fixed
? index
: "__p.__indirect(" + index + ")";
code += ", __p.bb";
} else {
code += index;
}
code += ")" + dest_mask;
if (!IsArray(field.value.type)) {
code += " : ";
code +=
field.value.type.element == BASE_TYPE_BOOL
? "false"
: (IsScalar(field.value.type.element) ? default_cast + "0"
: "null");
}
if (vectortype.base_type == BASE_TYPE_UNION &&
HasUnionStringValue(*vectortype.enum_def)) {
code += member_suffix;
code += "}\n";
code += " public string " + Name(field) + "AsString(int j)";
code += offset_prefix + GenGetter(Type(BASE_TYPE_STRING));
code += "(" + index + ") : null";
}
break;
}
case BASE_TYPE_UNION:
code += "() where TTable : struct, IFlatbufferObject";
code += offset_prefix + "(TTable?)" + getter;
code += "<TTable>(o + __p.bb_pos) : null";
if (HasUnionStringValue(*field.value.type.enum_def)) {
code += member_suffix;
code += "}\n";
code += " public string " + Name(field) + "AsString()";
code += offset_prefix + GenGetter(Type(BASE_TYPE_STRING));
code += "(o + __p.bb_pos) : null";
}
// As<> accesors for Unions
// Loop through all the possible union types and generate an As
// accessor that casts to the correct type.
for (auto uit = field.value.type.enum_def->Vals().begin();
uit != field.value.type.enum_def->Vals().end(); ++uit) {
auto val = *uit;
if (val->union_type.base_type == BASE_TYPE_NONE) { continue; }
auto union_field_type_name = GenTypeGet(val->union_type);
code += member_suffix + "}\n";
if (val->union_type.base_type == BASE_TYPE_STRUCT &&
val->union_type.struct_def->attributes.Lookup("private")) {
code += " internal ";
} else {
code += " public ";
}
code += union_field_type_name + " ";
code += field_name_camel + "As" + val->name + "() { return ";
code += field_name_camel;
if (IsString(val->union_type)) {
code += "AsString()";
} else {
code += "<" + union_field_type_name + ">().Value";
}
}
break;
default: FLATBUFFERS_ASSERT(0);
}
}
code += member_suffix;
code += "}\n";
if (IsVector(field.value.type)) {
auto camel_name = Name(field);
if (camel_name == struct_def.name) { camel_name += "_"; }
code += " public int " + camel_name;
code += "Length";
code += " { get";
code += offset_prefix;
code += "__p.__vector_len(o) : 0; ";
code += "} ";
code += "}\n";
// See if we should generate a by-key accessor.
if (field.value.type.element == BASE_TYPE_STRUCT &&
!field.value.type.struct_def->fixed) {
auto &sd = *field.value.type.struct_def;
auto &fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
auto &key_field = **kit;
if (key_field.key) {
auto qualified_name = NamespacedName(sd);
code += " public " + qualified_name + "? ";
code += Name(field) + "ByKey(";
code += GenTypeGet(key_field.value.type) + " key)";
code += offset_prefix;
code += qualified_name + ".__lookup_by_key(";
code += "__p.__vector(o), key, ";
code += "__p.bb) : null; ";
code += "}\n";
break;
}
}
}
}
// Generate a ByteBuffer accessor for strings & vectors of scalars.
if ((IsVector(field.value.type) &&
IsScalar(field.value.type.VectorType().base_type)) ||
IsString(field.value.type)) {
code += "#if ENABLE_SPAN_T\n";
code += " public Span<" + GenTypeBasic(field.value.type.VectorType()) +
"> Get";
code += Name(field);
code += "Bytes() { return ";
code += "__p.__vector_as_span<" +
GenTypeBasic(field.value.type.VectorType()) + ">(";
code += NumToString(field.value.offset);
code +=
", " + NumToString(SizeOf(field.value.type.VectorType().base_type));
code += "); }\n";
code += "#else\n";
code += " public ArraySegment<byte>? Get";
code += Name(field);
code += "Bytes() { return ";
code += "__p.__vector_as_arraysegment(";
code += NumToString(field.value.offset);
code += "); }\n";
code += "#endif\n";
// For direct blockcopying the data into a typed array
code += " public ";
code += GenTypeBasic(field.value.type.VectorType());
code += "[] Get";
code += Name(field);
code += "Array() { ";
if (IsEnum(field.value.type.VectorType())) {
// Since __vector_as_array does not work for enum types,
// fill array using an explicit loop.
code += "int o = __p.__offset(";
code += NumToString(field.value.offset);
code += "); if (o == 0) return null; int p = ";
code += "__p.__vector(o); int l = ";
code += "__p.__vector_len(o); ";
code += GenTypeBasic(field.value.type.VectorType());
code += "[] a = new ";
code += GenTypeBasic(field.value.type.VectorType());
code += "[l]; for (int i = 0; i < l; i++) { a[i] = " + getter;
code += "(p + i * ";
code += NumToString(InlineSize(field.value.type.VectorType()));
code += "); } return a;";
} else {
code += "return ";
code += "__p.__vector_as_array<";
code += GenTypeBasic(field.value.type.VectorType());
code += ">(";
code += NumToString(field.value.offset);
code += ");";
}
code += " }\n";
}
// generate object accessors if is nested_flatbuffer
if (field.nested_flatbuffer) {
auto nested_type_name = NamespacedName(*field.nested_flatbuffer);
auto nested_method_name =
Name(field) + "As" + field.nested_flatbuffer->name;
auto get_nested_method_name = nested_method_name;
get_nested_method_name = "Get" + nested_method_name;
conditional_cast = "(" + nested_type_name + "?)";
obj = "(new " + nested_type_name + "())";
code += " public " + nested_type_name + "? ";
code += get_nested_method_name + "(";
code += ") { int o = __p.__offset(";
code += NumToString(field.value.offset) + "); ";
code += "return o != 0 ? " + conditional_cast + obj + ".__assign(";
code += "__p.";
code += "__indirect(__p.__vector(o)), ";