forked from google/flatbuffers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidl_gen_rust.cpp
2013 lines (1842 loc) · 75.2 KB
/
idl_gen_rust.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 2018 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 "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
// Convert a camelCaseIdentifier or CamelCaseIdentifier to a
// snake_case_identifier.
std::string MakeSnakeCase(const std::string &in) {
std::string s;
for (size_t i = 0; i < in.length(); i++) {
if (i == 0) {
s += CharToLower(in[0]);
} else if (in[i] == '_') {
s += '_';
} else if (!islower(in[i])) {
// Prevent duplicate underscores for Upper_Snake_Case strings
// and UPPERCASE strings.
if (islower(in[i - 1])) { s += '_'; }
s += CharToLower(in[i]);
} else {
s += in[i];
}
}
return s;
}
// Convert a string to all uppercase.
std::string MakeUpper(const std::string &in) {
std::string s;
for (size_t i = 0; i < in.length(); i++) { s += CharToUpper(in[i]); }
return s;
}
// Encapsulate all logical field types in this enum. This allows us to write
// field logic based on type switches, instead of branches on the properties
// set on the Type.
// TODO(rw): for backwards compatibility, we can't use a strict `enum class`
// declaration here. could we use the `-Wswitch-enum` warning to
// achieve the same effect?
enum FullType {
ftInteger = 0,
ftFloat = 1,
ftBool = 2,
ftStruct = 3,
ftTable = 4,
ftEnumKey = 5,
ftUnionKey = 6,
ftUnionValue = 7,
// TODO(rw): bytestring?
ftString = 8,
ftVectorOfInteger = 9,
ftVectorOfFloat = 10,
ftVectorOfBool = 11,
ftVectorOfEnumKey = 12,
ftVectorOfStruct = 13,
ftVectorOfTable = 14,
ftVectorOfString = 15,
ftVectorOfUnionValue = 16,
};
// Convert a Type to a FullType (exhaustive).
FullType GetFullType(const Type &type) {
// N.B. The order of these conditionals matters for some types.
if (IsString(type)) {
return ftString;
} else if (type.base_type == BASE_TYPE_STRUCT) {
if (type.struct_def->fixed) {
return ftStruct;
} else {
return ftTable;
}
} else if (IsVector(type)) {
switch (GetFullType(type.VectorType())) {
case ftInteger: {
return ftVectorOfInteger;
}
case ftFloat: {
return ftVectorOfFloat;
}
case ftBool: {
return ftVectorOfBool;
}
case ftStruct: {
return ftVectorOfStruct;
}
case ftTable: {
return ftVectorOfTable;
}
case ftString: {
return ftVectorOfString;
}
case ftEnumKey: {
return ftVectorOfEnumKey;
}
case ftUnionKey:
case ftUnionValue: {
FLATBUFFERS_ASSERT(false && "vectors of unions are unsupported");
break;
}
default: {
FLATBUFFERS_ASSERT(false && "vector of vectors are unsupported");
}
}
} else if (type.enum_def != nullptr) {
if (type.enum_def->is_union) {
if (type.base_type == BASE_TYPE_UNION) {
return ftUnionValue;
} else if (IsInteger(type.base_type)) {
return ftUnionKey;
} else {
FLATBUFFERS_ASSERT(false && "unknown union field type");
}
} else {
return ftEnumKey;
}
} else if (IsScalar(type.base_type)) {
if (IsBool(type.base_type)) {
return ftBool;
} else if (IsInteger(type.base_type)) {
return ftInteger;
} else if (IsFloat(type.base_type)) {
return ftFloat;
} else {
FLATBUFFERS_ASSERT(false && "unknown number type");
}
}
FLATBUFFERS_ASSERT(false && "completely unknown type");
// this is only to satisfy the compiler's return analysis.
return ftBool;
}
// If the second parameter is false then wrap the first with Option<...>
std::string WrapInOptionIfNotRequired(std::string s, bool required) {
if (required) {
return s;
} else {
return "Option<" + s + ">";
}
}
// If the second parameter is false then add .unwrap()
std::string AddUnwrapIfRequired(std::string s, bool required) {
if (required) {
return s + ".unwrap()";
} else {
return s;
}
}
bool IsBitFlagsEnum(const EnumDef &enum_def) {
return enum_def.attributes.Lookup("bit_flags") != nullptr;
}
bool IsBitFlagsEnum(const FieldDef &field) {
EnumDef* ed = field.value.type.enum_def;
return ed && IsBitFlagsEnum(*ed);
}
namespace rust {
class RustGenerator : public BaseGenerator {
public:
RustGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", "::", "rs"),
cur_name_space_(nullptr) {
const char *keywords[] = {
// list taken from:
// https://doc.rust-lang.org/book/second-edition/appendix-01-keywords.html
//
// we write keywords one per line so that we can easily compare them with
// changes to that webpage in the future.
// currently-used keywords
"as", "break", "const", "continue", "crate", "else", "enum", "extern",
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
"move", "mut", "pub", "ref", "return", "Self", "self", "static", "struct",
"super", "trait", "true", "type", "unsafe", "use", "where", "while",
// future possible keywords
"abstract", "alignof", "become", "box", "do", "final", "macro",
"offsetof", "override", "priv", "proc", "pure", "sizeof", "typeof",
"unsized", "virtual", "yield",
// other rust terms we should not use
"std", "usize", "isize", "u8", "i8", "u16", "i16", "u32", "i32", "u64",
"i64", "u128", "i128", "f32", "f64",
// These are terms the code generator can implement on types.
//
// In Rust, the trait resolution rules (as described at
// https://github.com/rust-lang/rust/issues/26007) mean that, as long
// as we impl table accessors as inherent methods, we'll never create
// conflicts with these keywords. However, that's a fairly nuanced
// implementation detail, and how we implement methods could change in
// the future. as a result, we proactively block these out as reserved
// words.
"follow", "push", "size", "alignment", "to_little_endian",
"from_little_endian", nullptr,
// used by Enum constants
"ENUM_MAX", "ENUM_MIN", "ENUM_VALUES",
};
for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
}
// Iterate through all definitions we haven't generated code for (enums,
// structs, and tables) and output them to a single file.
bool generate() {
code_.Clear();
code_ += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
assert(!cur_name_space_);
// Generate imports for the global scope in case no namespace is used
// in the schema file.
GenNamespaceImports(0);
code_ += "";
// Generate all code in their namespaces, once, because Rust does not
// permit re-opening modules.
//
// TODO(rw): Use a set data structure to reduce namespace evaluations from
// O(n**2) to O(n).
for (auto ns_it = parser_.namespaces_.begin();
ns_it != parser_.namespaces_.end(); ++ns_it) {
const auto &ns = *ns_it;
// Generate code for all the enum declarations.
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
const auto &enum_def = **it;
if (enum_def.defined_namespace != ns) { continue; }
if (!enum_def.generated) {
SetNameSpace(enum_def.defined_namespace);
GenEnum(enum_def);
}
}
// Generate code for all structs.
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
const auto &struct_def = **it;
if (struct_def.defined_namespace != ns) { continue; }
if (struct_def.fixed && !struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
GenStruct(struct_def);
}
}
// Generate code for all tables.
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
const auto &struct_def = **it;
if (struct_def.defined_namespace != ns) { continue; }
if (!struct_def.fixed && !struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
GenTable(struct_def);
}
}
// Generate global helper functions.
if (parser_.root_struct_def_) {
auto &struct_def = *parser_.root_struct_def_;
if (struct_def.defined_namespace != ns) { continue; }
SetNameSpace(struct_def.defined_namespace);
GenRootTableFuncs(struct_def);
}
}
if (cur_name_space_) SetNameSpace(nullptr);
const auto file_path = GeneratedFileName(path_, file_name_, parser_.opts);
const auto final_code = code_.ToString();
return SaveFile(file_path.c_str(), final_code, false);
}
private:
CodeWriter code_;
std::set<std::string> keywords_;
// This tracks the current namespace so we can insert namespace declarations.
const Namespace *cur_name_space_;
const Namespace *CurrentNameSpace() const { return cur_name_space_; }
// Determine if a Type needs a lifetime template parameter when used in the
// Rust builder args.
bool TableBuilderTypeNeedsLifetime(const Type &type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool:
case ftEnumKey:
case ftUnionKey:
case ftUnionValue: {
return false;
}
default: {
return true;
}
}
}
// Determine if a table args rust type needs a lifetime template parameter.
bool TableBuilderArgsNeedsLifetime(const StructDef &struct_def) const {
FLATBUFFERS_ASSERT(!struct_def.fixed);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (field.deprecated) { continue; }
if (TableBuilderTypeNeedsLifetime(field.value.type)) { return true; }
}
return false;
}
std::string EscapeKeyword(const std::string &name) const {
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}
std::string Name(const Definition &def) const {
return EscapeKeyword(def.name);
}
std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
std::string WrapInNameSpace(const Definition &def) const {
return WrapInNameSpace(def.defined_namespace, Name(def));
}
std::string WrapInNameSpace(const Namespace *ns,
const std::string &name) const {
if (CurrentNameSpace() == ns) return name;
std::string prefix = GetRelativeNamespaceTraversal(CurrentNameSpace(), ns);
return prefix + name;
}
// Determine the namespace traversal needed from the Rust crate root.
// This may be useful in the future for referring to included files, but is
// currently unused.
std::string GetAbsoluteNamespaceTraversal(const Namespace *dst) const {
std::stringstream stream;
stream << "::";
for (auto d = dst->components.begin(); d != dst->components.end(); ++d) {
stream << MakeSnakeCase(*d) + "::";
}
return stream.str();
}
// Determine the relative namespace traversal needed to reference one
// namespace from another namespace. This is useful because it does not force
// the user to have a particular file layout. (If we output absolute
// namespace paths, that may require users to organize their Rust crates in a
// particular way.)
std::string GetRelativeNamespaceTraversal(const Namespace *src,
const Namespace *dst) const {
// calculate the path needed to reference dst from src.
// example: f(A::B::C, A::B::C) -> (none)
// example: f(A::B::C, A::B) -> super::
// example: f(A::B::C, A::B::D) -> super::D
// example: f(A::B::C, A) -> super::super::
// example: f(A::B::C, D) -> super::super::super::D
// example: f(A::B::C, D::E) -> super::super::super::D::E
// example: f(A, D::E) -> super::D::E
// does not include leaf object (typically a struct type).
size_t i = 0;
std::stringstream stream;
auto s = src->components.begin();
auto d = dst->components.begin();
for (;;) {
if (s == src->components.end()) { break; }
if (d == dst->components.end()) { break; }
if (*s != *d) { break; }
++s;
++d;
++i;
}
for (; s != src->components.end(); ++s) { stream << "super::"; }
for (; d != dst->components.end(); ++d) {
stream << MakeSnakeCase(*d) + "::";
}
return stream.str();
}
// Generate a comment from the schema.
void GenComment(const std::vector<std::string> &dc, const char *prefix = "") {
std::string text;
::flatbuffers::GenComment(dc, &text, nullptr, prefix);
code_ += text + "\\";
}
// Return a Rust type from the table in idl.h.
std::string GetTypeBasic(const Type &type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool:
case ftEnumKey:
case ftUnionKey: {
break;
}
default: {
FLATBUFFERS_ASSERT(false && "incorrect type given");
}
}
// clang-format off
static const char * const ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
RTYPE, ...) \
#RTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
// clang-format on
if (type.enum_def) { return WrapInNameSpace(*type.enum_def); }
return ctypename[type.base_type];
}
// Look up the native type for an enum. This will always be an integer like
// u8, i32, etc.
std::string GetEnumTypeForDecl(const Type &type) {
const auto ft = GetFullType(type);
if (!(ft == ftEnumKey || ft == ftUnionKey)) {
FLATBUFFERS_ASSERT(false && "precondition failed in GetEnumTypeForDecl");
}
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
RTYPE, ...) \
#RTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
// clang-format on
// Enums can be bools, but their Rust representation must be a u8, as used
// in the repr attribute (#[repr(bool)] is an invalid attribute).
if (type.base_type == BASE_TYPE_BOOL) return "u8";
return ctypename[type.base_type];
}
// Return a Rust type for any type (scalar, table, struct) specifically for
// using a FlatBuffer.
std::string GetTypeGet(const Type &type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool:
case ftEnumKey:
case ftUnionKey: {
return GetTypeBasic(type);
}
case ftTable: {
return WrapInNameSpace(type.struct_def->defined_namespace,
type.struct_def->name) +
"<'a>";
}
default: {
return WrapInNameSpace(type.struct_def->defined_namespace,
type.struct_def->name);
}
}
}
std::string GetEnumValue(const EnumDef &enum_def,
const EnumVal &enum_val) const {
return Name(enum_def) + "::" + Name(enum_val);
}
// 1 suffix since old C++ can't figure out the overload.
void ForAllEnumValues1(const EnumDef &enum_def,
std::function<void(const EnumVal&)> cb) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
const auto &ev = **it;
code_.SetValue("VARIANT", Name(ev));
code_.SetValue("VALUE", enum_def.ToString(ev));
cb(ev);
}
}
void ForAllEnumValues(const EnumDef &enum_def, std::function<void()> cb) {
std::function<void(const EnumVal&)> wrapped = [&](const EnumVal& unused) {
(void) unused;
cb();
};
ForAllEnumValues1(enum_def, wrapped);
}
// Generate an enum declaration,
// an enum string lookup table,
// an enum match function,
// and an enum array of values
void GenEnum(const EnumDef &enum_def) {
code_.SetValue("ENUM_NAME", Name(enum_def));
code_.SetValue("BASE_TYPE", GetEnumTypeForDecl(enum_def.underlying_type));
code_.SetValue("ENUM_NAME_SNAKE", MakeSnakeCase(Name(enum_def)));
code_.SetValue("ENUM_NAME_CAPS", MakeUpper(MakeSnakeCase(Name(enum_def))));
const EnumVal *minv = enum_def.MinValue();
const EnumVal *maxv = enum_def.MaxValue();
FLATBUFFERS_ASSERT(minv && maxv);
code_.SetValue("ENUM_MIN_BASE_VALUE", enum_def.ToString(*minv));
code_.SetValue("ENUM_MAX_BASE_VALUE", enum_def.ToString(*maxv));
if (IsBitFlagsEnum(enum_def)) {
// Defer to the convenient and canonical bitflags crate. We declare it in a
// module to #allow camel case constants in a smaller scope. This matches
// Flatbuffers c-modeled enums where variants are associated constants but
// in camel case.
code_ += "#[allow(non_upper_case_globals)]";
code_ += "mod bitflags_{{ENUM_NAME_SNAKE}} {";
code_ += " flatbuffers::bitflags::bitflags! {";
GenComment(enum_def.doc_comment, " ");
code_ += " pub struct {{ENUM_NAME}}: {{BASE_TYPE}} {";
ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
this->GenComment(ev.doc_comment, " ");
code_ += " const {{VARIANT}} = {{VALUE}};";
});
code_ += " }";
code_ += " }";
code_ += "}";
code_ += "pub use self::bitflags_{{ENUM_NAME_SNAKE}}::{{ENUM_NAME}};";
code_ += "";
code_.SetValue("FROM_BASE", "unsafe { Self::from_bits_unchecked(b) }");
code_.SetValue("INTO_BASE", "self.bits()");
} else {
// Normal, c-modelled enums.
// Deprecated associated constants;
const std::string deprecation_warning =
"#[deprecated(since = \"2.0.0\", note = \"Use associated constants"
" instead. This will no longer be generated in 2021.\")]";
code_ += deprecation_warning;
code_ += "pub const ENUM_MIN_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}}"
" = {{ENUM_MIN_BASE_VALUE}};";
code_ += deprecation_warning;
code_ += "pub const ENUM_MAX_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}}"
" = {{ENUM_MAX_BASE_VALUE}};";
auto num_fields = NumToString(enum_def.size());
code_ += deprecation_warning;
code_ += "#[allow(non_camel_case_types)]";
code_ += "pub const ENUM_VALUES_{{ENUM_NAME_CAPS}}: [{{ENUM_NAME}}; " +
num_fields + "] = [";
ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
code_ += " " + GetEnumValue(enum_def, ev) + ",";
});
code_ += "];";
code_ += "";
GenComment(enum_def.doc_comment);
code_ +=
"#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]";
code_ += "#[repr(transparent)]";
code_ += "pub struct {{ENUM_NAME}}(pub {{BASE_TYPE}});";
code_ += "#[allow(non_upper_case_globals)]";
code_ += "impl {{ENUM_NAME}} {";
ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
this->GenComment(ev.doc_comment, " ");
code_ += " pub const {{VARIANT}}: Self = Self({{VALUE}});";
});
code_ += "";
// Generate Associated constants
code_ += " pub const ENUM_MIN: {{BASE_TYPE}} = {{ENUM_MIN_BASE_VALUE}};";
code_ += " pub const ENUM_MAX: {{BASE_TYPE}} = {{ENUM_MAX_BASE_VALUE}};";
code_ += " pub const ENUM_VALUES: &'static [Self] = &[";
ForAllEnumValues(enum_def, [&](){
code_ += " Self::{{VARIANT}},";
});
code_ += " ];";
code_ += " /// Returns the variant's name or \"\" if unknown.";
code_ += " pub fn variant_name(self) -> Option<&'static str> {";
code_ += " match self {";
ForAllEnumValues(enum_def, [&](){
code_ += " Self::{{VARIANT}} => Some(\"{{VARIANT}}\"),";
});
code_ += " _ => None,";
code_ += " }";
code_ += " }";
code_ += "}";
// Generate Debug. Unknown variants are printed like "<UNKNOWN 42>".
code_ += "impl std::fmt::Debug for {{ENUM_NAME}} {";
code_ += " fn fmt(&self, f: &mut std::fmt::Formatter) ->"
" std::fmt::Result {";
code_ += " if let Some(name) = self.variant_name() {";
code_ += " f.write_str(name)";
code_ += " } else {";
code_ += " f.write_fmt(format_args!(\"<UNKNOWN {:?}>\", self.0))";
code_ += " }";
code_ += " }";
code_ += "}";
if (enum_def.is_union) {
// Generate tyoesafe offset(s) for unions
code_.SetValue("NAME", Name(enum_def));
code_.SetValue("UNION_OFFSET_NAME", Name(enum_def) + "UnionTableOffset");
code_ += "pub struct {{UNION_OFFSET_NAME}} {}";
}
code_.SetValue("FROM_BASE", "Self(b)");
code_.SetValue("INTO_BASE", "self.0");
}
// Generate Follow and Push so we can serialize and stuff.
code_ += "impl<'a> flatbuffers::Follow<'a> for {{ENUM_NAME}} {";
code_ += " type Inner = Self;";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
code_ += " let b = flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf,"
" loc);";
code_ += " {{FROM_BASE}}";
code_ += " }";
code_ += "}";
code_ += "";
code_ += "impl flatbuffers::Push for {{ENUM_NAME}} {";
code_ += " type Output = {{ENUM_NAME}};";
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
code_ += " flatbuffers::emplace_scalar::<{{BASE_TYPE}}>"
"(dst, {{INTO_BASE}});";
code_ += " }";
code_ += "}";
code_ += "";
code_ += "impl flatbuffers::EndianScalar for {{ENUM_NAME}} {";
code_ += " #[inline]";
code_ += " fn to_little_endian(self) -> Self {";
code_ += " let b = {{BASE_TYPE}}::to_le({{INTO_BASE}});";
code_ += " {{FROM_BASE}}";
code_ += " }";
code_ += " #[inline]";
code_ += " fn from_little_endian(self) -> Self {";
code_ += " let b = {{BASE_TYPE}}::from_le({{INTO_BASE}});";
code_ += " {{FROM_BASE}}";
code_ += " }";
code_ += "}";
code_ += "";
// Generate verifier - deferring to the base type.
code_ += "impl<'a> flatbuffers::Verifiable for {{ENUM_NAME}} {";
code_ += " #[inline]";
code_ += " fn run_verifier(";
code_ += " v: &mut flatbuffers::Verifier, pos: usize";
code_ += " ) -> Result<(), flatbuffers::InvalidFlatbuffer> {";
code_ += " use self::flatbuffers::Verifiable;";
code_ += " {{BASE_TYPE}}::run_verifier(v, pos)";
code_ += " }";
code_ += "}";
code_ += "";
// Enums are basically integers.
code_ += "impl flatbuffers::SimpleToVerifyInSlice for {{ENUM_NAME}} {}";
}
std::string GetFieldOffsetName(const FieldDef &field) {
return "VT_" + MakeUpper(Name(field));
}
std::string GetDefaultScalarValue(const FieldDef &field) {
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat: {
return field.optional ? "None" : field.value.constant;
}
case ftBool: {
return field.optional ? "None"
: field.value.constant == "0" ? "false" : "true";
}
case ftUnionKey:
case ftEnumKey: {
if (field.optional) {
return "None";
}
auto ev = field.value.type.enum_def->FindByValue(field.value.constant);
assert(ev);
return WrapInNameSpace(field.value.type.enum_def->defined_namespace,
GetEnumValue(*field.value.type.enum_def, *ev));
}
// All pointer-ish types have a default value of None, because they are
// wrapped in Option.
default: {
return "None";
}
}
}
// Create the return type for fields in the *BuilderArgs structs that are
// used to create Tables.
//
// Note: we could make all inputs to the BuilderArgs be an Option, as well
// as all outputs. But, the UX of Flatbuffers is that the user doesn't get to
// know if the value is default or not, because there are three ways to
// return a default value:
// 1) return a stored value that happens to be the default,
// 2) return a hardcoded value because the relevant vtable field is not in
// the vtable, or
// 3) return a hardcoded value because the vtable field value is set to zero.
std::string TableBuilderArgsDefnType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool: {
const auto typname = GetTypeBasic(type);
return field.optional ? "Option<" + typname + ">" : typname;
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "Option<&" + lifetime + " " + typname + ">";
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime +
">>>";
}
case ftString: {
return "Option<flatbuffers::WIPOffset<&" + lifetime + " str>>";
}
case ftEnumKey:
case ftUnionKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return field.optional ? "Option<" + typname + ">" : typname;
}
case ftUnionValue: {
return "Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>";
}
case ftVectorOfInteger:
case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", " + typname + ">>>";
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", " + typname + ">>>";
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", " + typname + ">>>";
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime +
">>>>>";
}
case ftVectorOfString: {
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>>";
}
case ftVectorOfUnionValue: {
const auto typname =
WrapInNameSpace(*type.enum_def) + "UnionTableOffset";
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<"
"flatbuffers::Table<" +
lifetime + ">>>>";
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string TableBuilderArgsAddFuncType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
typname + ">>";
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime +
">>>>";
}
case ftVectorOfInteger:
case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
typname + ">>";
}
case ftVectorOfString: {
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>";
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
typname + ">>";
}
case ftVectorOfUnionValue: {
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + lifetime +
">>>";
}
case ftEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return typname;
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "&" + typname + "";
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "flatbuffers::WIPOffset<" + typname + "<" + lifetime + ">>";
}
case ftInteger:
case ftBool:
case ftFloat: {
return GetTypeBasic(type);
}
case ftString: {
return "flatbuffers::WIPOffset<&" + lifetime + " str>";
}
case ftUnionKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return typname;
}
case ftUnionValue: {
return "flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>";
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string TableBuilderArgsAddFuncBody(const FieldDef &field) {
const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftBool:
case ftFloat: {
const auto typname = GetTypeBasic(field.value.type);
return (field.optional ? "self.fbb_.push_slot_always::<"
: "self.fbb_.push_slot::<") +
typname + ">";
}
case ftEnumKey:
case ftUnionKey: {
const auto underlying_typname = GetTypeBasic(type);
return (field.optional ?
"self.fbb_.push_slot_always::<" :
"self.fbb_.push_slot::<") + underlying_typname + ">";
}
case ftStruct: {
const std::string typname = WrapInNameSpace(*type.struct_def);
return "self.fbb_.push_slot_always::<&" + typname + ">";
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" +
typname + ">>";
}
case ftUnionValue:
case ftString:
case ftVectorOfInteger:
case ftVectorOfFloat:
case ftVectorOfBool:
case ftVectorOfEnumKey:
case ftVectorOfStruct:
case ftVectorOfTable:
case ftVectorOfString:
case ftVectorOfUnionValue: {
return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>";
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string GenTableAccessorFuncReturnType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat:
case ftBool: {
const auto typname = GetTypeBasic(type);
return field.optional ? "Option<" + typname + ">" : typname;
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return WrapInOptionIfNotRequired("&" + lifetime + " " + typname,
field.required);
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">",
field.required);
}
case ftEnumKey:
case ftUnionKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return field.optional ? "Option<" + typname + ">" : typname;
}
case ftUnionValue: {
return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">",
field.required);
}
case ftString: {
return WrapInOptionIfNotRequired("&" + lifetime + " str",
field.required);
}
case ftVectorOfInteger:
case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
if (IsOneByte(type.VectorType().base_type)) {
return WrapInOptionIfNotRequired(
"&" + lifetime + " [" + typname + "]", field.required);
}
return WrapInOptionIfNotRequired(
"flatbuffers::Vector<" + lifetime + ", " + typname + ">",
field.required);
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return WrapInOptionIfNotRequired(
"flatbuffers::Vector<" + lifetime + ", " + typname + ">",
field.required);
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]",
field.required);
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<" +
typname + "<" + lifetime + ">>>",
field.required);
}
case ftVectorOfString: {
return WrapInOptionIfNotRequired(
"flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>",
field.required);
}
case ftVectorOfUnionValue: {
FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
// TODO(rw): when we do support these, we should consider using the
// Into trait to convert tables to typesafe union values.
return "INVALID_CODE_GENERATION"; // for return analysis
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string FollowType(const Type &type, const std::string &lifetime) {
// IsVector... This can be made iterative?
const auto WrapForwardsUOffset = [](std::string ty) -> std::string {
return "flatbuffers::ForwardsUOffset<" + ty + ">";