diff options
author | Derek Bailey <derekbailey@google.com> | 2019-11-07 12:22:54 -0800 |
---|---|---|
committer | Wouter van Oortmerssen <aardappel@gmail.com> | 2019-11-07 12:22:54 -0800 |
commit | f0f0efe7b8bb1e32e7ea21b17bdea28835ad81c4 (patch) | |
tree | eb0c5f977400166f7c6f8067d7764d9753aa1ea3 /src/idl_gen_rust.cpp | |
parent | e837d5a296c725d141802777808aaff944e7b427 (diff) | |
download | flatbuffers-f0f0efe7b8bb1e32e7ea21b17bdea28835ad81c4.tar.gz flatbuffers-f0f0efe7b8bb1e32e7ea21b17bdea28835ad81c4.tar.bz2 flatbuffers-f0f0efe7b8bb1e32e7ea21b17bdea28835ad81c4.zip |
[C++] Refactor to conform to Google C++ style guide (#5608)
* Automatic refractor of C++ headers to Google C++ style guide
* Automatic refractor of C++ source to Google C++ style guide
* Automatic refractor of C++ tests to Google C++ style guide
* Fixed clang-format issues by running clang-format twice to correct itself. Kotlin was missing clang-format on after turning it off, so it was changed,
Diffstat (limited to 'src/idl_gen_rust.cpp')
-rw-r--r-- | src/idl_gen_rust.cpp | 579 |
1 files changed, 294 insertions, 285 deletions
diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp index 936ac836..3c23f2f9 100644 --- a/src/idl_gen_rust.cpp +++ b/src/idl_gen_rust.cpp @@ -40,9 +40,7 @@ std::string MakeSnakeCase(const std::string &in) { } else if (!islower(in[i])) { // Prevent duplicate underscores for Upper_Snake_Case strings // and UPPERCASE strings. - if (islower(in[i - 1])) { - s += '_'; - } + if (islower(in[i - 1])) { s += '_'; } s += static_cast<char>(tolower(in[i])); } else { s += in[i]; @@ -200,77 +198,19 @@ class RustGenerator : public BaseGenerator { // 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", + "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", + "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", + "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. // @@ -281,13 +221,9 @@ class RustGenerator : public BaseGenerator { // 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 }; + "follow", "push", "size", "alignment", "to_little_endian", + "from_little_endian", nullptr + }; for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw); } @@ -310,8 +246,7 @@ class RustGenerator : public BaseGenerator { // 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) { + ns_it != parser_.namespaces_.end(); ++ns_it) { const auto &ns = *ns_it; // Generate code for all the enum declarations. @@ -381,8 +316,12 @@ class RustGenerator : public BaseGenerator { case ftBool: case ftEnumKey: case ftUnionKey: - case ftUnionValue: { return false; } - default: { return true; } + case ftUnionValue: { + return false; + } + default: { + return true; + } } } @@ -393,13 +332,9 @@ class RustGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) { - continue; - } + if (field.deprecated) { continue; } - if (TableBuilderTypeNeedsLifetime(field.value.type)) { - return true; - } + if (TableBuilderTypeNeedsLifetime(field.value.type)) { return true; } } return false; @@ -410,14 +345,18 @@ class RustGenerator : public BaseGenerator { bool StructMemberAccessNeedsCopy(const Type &type) const { switch (GetFullType(type)) { case ftInteger: // requires endian swap - case ftFloat: // requires endian swap - case ftBool: // no endian-swap, but do the copy for UX consistency - case ftEnumKey: { return true; } // requires endian swap - case ftStruct: { return false; } // no endian swap + case ftFloat: // requires endian swap + case ftBool: // no endian-swap, but do the copy for UX consistency + case ftEnumKey: { + return true; + } // requires endian swap + case ftStruct: { + return false; + } // no endian swap default: { // logic error: no other types can be struct members. FLATBUFFERS_ASSERT(false && "invalid struct member type"); - return false; // only to satisfy compiler's return analysis + return false; // only to satisfy compiler's return analysis } } } @@ -477,7 +416,7 @@ class RustGenerator : public BaseGenerator { auto s = src->components.begin(); auto d = dst->components.begin(); - for(;;) { + for (;;) { if (s == src->components.end()) { break; } if (d == dst->components.end()) { break; } if (*s != *d) { break; } @@ -486,9 +425,7 @@ class RustGenerator : public BaseGenerator { ++i; } - for (; s != src->components.end(); ++s) { - stream << "super::"; - } + for (; s != src->components.end(); ++s) { stream << "super::"; } for (; d != dst->components.end(); ++d) { stream << MakeSnakeCase(*d) + "::"; } @@ -509,8 +446,12 @@ class RustGenerator : public BaseGenerator { case ftFloat: case ftBool: case ftEnumKey: - case ftUnionKey: { break; } - default: { FLATBUFFERS_ASSERT(false && "incorrect type given");} + case ftUnionKey: { + break; + } + default: { + FLATBUFFERS_ASSERT(false && "incorrect type given"); + } } // clang-format off @@ -560,13 +501,17 @@ class RustGenerator : public BaseGenerator { case ftBool: case ftEnumKey: case ftUnionKey: { - return GetTypeBasic(type); } + return GetTypeBasic(type); + } case ftTable: { return WrapInNameSpace(type.struct_def->defined_namespace, - type.struct_def->name) + "<'a>"; } + type.struct_def->name) + + "<'a>"; + } default: { return WrapInNameSpace(type.struct_def->defined_namespace, - type.struct_def->name); } + type.struct_def->name); + } } } @@ -586,7 +531,8 @@ class RustGenerator : public BaseGenerator { GenComment(enum_def.doc_comment); code_ += "#[allow(non_camel_case_types)]"; code_ += "#[repr({{BASE_TYPE}})]"; - code_ += "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]"; + code_ += + "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]"; code_ += "pub enum " + Name(enum_def) + " {"; for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { @@ -644,8 +590,9 @@ class RustGenerator : public BaseGenerator { code_ += " type Output = {{ENUM_NAME}};"; code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; - code_ += " flatbuffers::emplace_scalar::<{{ENUM_NAME}}>" - "(dst, *self);"; + code_ += + " flatbuffers::emplace_scalar::<{{ENUM_NAME}}>" + "(dst, *self);"; code_ += " }"; code_ += "}"; code_ += ""; @@ -654,7 +601,7 @@ class RustGenerator : public BaseGenerator { auto num_fields = NumToString(enum_def.size()); code_ += "#[allow(non_camel_case_types)]"; code_ += "const ENUM_VALUES_{{ENUM_NAME_CAPS}}:[{{ENUM_NAME}}; " + - num_fields + "] = ["; + num_fields + "] = ["; for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { const auto &ev = **it; auto value = GetEnumValUse(enum_def, ev); @@ -727,8 +674,12 @@ class RustGenerator : public BaseGenerator { std::string GetDefaultScalarValue(const FieldDef &field) { switch (GetFullType(field.value.type)) { - case ftInteger: { return GetDefaultConstant(field); } - case ftFloat: { return GetDefaultConstant(field); } + case ftInteger: { + return GetDefaultConstant(field); + } + case ftFloat: { + return GetDefaultConstant(field); + } case ftBool: { return field.value.constant == "0" ? "false" : "true"; } @@ -742,7 +693,9 @@ class RustGenerator : public BaseGenerator { // All pointer-ish types have a default value of None, because they are // wrapped in Option. - default: { return "None"; } + default: { + return "None"; + } } } @@ -759,7 +712,7 @@ class RustGenerator : public BaseGenerator { // 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; + const Type &type = field.value.type; switch (GetFullType(type)) { case ftInteger: @@ -774,7 +727,7 @@ class RustGenerator : public BaseGenerator { } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime + \ + return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime + ">>>"; } case ftString: { @@ -792,43 +745,43 @@ class RustGenerator : public BaseGenerator { case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", " + typname + ">>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", " + typname + ">>>"; } case ftVectorOfBool: { - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", bool>>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", bool>>>"; } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", " + typname + ">>>"; + 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 + ">>>"; + 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 + ">>>>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime + + ">>>>>"; } case ftVectorOfString: { - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", flatbuffers::ForwardsUOffset<&" + lifetime + \ - " str>>>>"; + 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 + ">>>>"; + 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 + return "INVALID_CODE_GENERATION"; // for return analysis } std::string TableBuilderArgsDefaultValue(const FieldDef &field) { @@ -839,53 +792,56 @@ class RustGenerator : public BaseGenerator { switch (GetFullType(field.value.type)) { case ftUnionKey: case ftEnumKey: { - const std::string basetype = GetTypeBasic(field.value.type); //<- never used + const std::string basetype = + GetTypeBasic(field.value.type); //<- never used return GetDefaultScalarValue(field); } - default: { return GetDefaultScalarValue(field); } + default: { + return GetDefaultScalarValue(field); + } } } std::string TableBuilderArgsAddFuncType(const FieldDef &field, const std::string &lifetime) { - const Type& type = field.value.type; + 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 + ">>"; + 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 + ">>>>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime + + ">>>>"; } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", " + typname + ">>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " + + typname + ">>"; } case ftVectorOfBool: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", bool>>"; } case ftVectorOfString: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ + 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 + ">>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " + + typname + ">>"; } case ftVectorOfUnionValue: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + \ - lifetime + ">>>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + lifetime + + ">>>"; } case ftEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); @@ -919,11 +875,11 @@ class RustGenerator : public BaseGenerator { } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string TableBuilderArgsAddFuncBody(const FieldDef &field) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -947,8 +903,8 @@ class RustGenerator : public BaseGenerator { } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" + \ - typname + ">>"; + return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" + + typname + ">>"; } case ftUnionValue: @@ -964,12 +920,12 @@ class RustGenerator : public BaseGenerator { return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>"; } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string GenTableAccessorFuncReturnType(const FieldDef &field, const std::string &lifetime) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -982,11 +938,13 @@ class RustGenerator : public BaseGenerator { } case ftStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired("&" + lifetime + " " + typname, field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " " + typname, + field.required); } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">", field.required); + return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">", + field.required); } case ftEnumKey: case ftUnionKey: { @@ -995,55 +953,68 @@ class RustGenerator : public BaseGenerator { } case ftUnionValue: { - return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">", field.required); + return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">", + field.required); } case ftString: { - return WrapInOptionIfNotRequired("&" + lifetime + " str", field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " str", + field.required); } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); if (IsOneByte(type.VectorType().base_type)) { - return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", field.required); + return WrapInOptionIfNotRequired( + "&" + lifetime + " [" + typname + "]", field.required); } - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", " + typname + ">", field.required); + return WrapInOptionIfNotRequired( + "flatbuffers::Vector<" + lifetime + ", " + typname + ">", + field.required); } case ftVectorOfBool: { - return WrapInOptionIfNotRequired("&" + lifetime + " [bool]", field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " [bool]", + field.required); } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", " + typname + ">", field.required); + return WrapInOptionIfNotRequired( + "flatbuffers::Vector<" + lifetime + ", " + typname + ">", + field.required); } case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", field.required); + 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); + return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + + typname + "<" + lifetime + ">>>", + field.required); } case ftVectorOfString: { - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<&" + \ - lifetime + " str>>", field.required); + 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 } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string GenTableAccessorFuncBody(const FieldDef &field, const std::string &lifetime, const std::string &offset_prefix) { - const std::string offset_name = offset_prefix + "::" + \ - GetFieldOffsetName(field); - const Type& type = field.value.type; + const std::string offset_name = + offset_prefix + "::" + GetFieldOffsetName(field); + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -1051,42 +1022,51 @@ class RustGenerator : public BaseGenerator { case ftBool: { const auto typname = GetTypeBasic(type); const auto default_value = GetDefaultScalarValue(field); - return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + \ + return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + default_value + ")).unwrap()"; } case ftStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<" + typname + ">(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<" + typname + ">(" + offset_name + ", None)", + field.required); } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" + \ - typname + "<" + lifetime + ">>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + typname + "<" + + lifetime + ">>>(" + offset_name + ", None)", + field.required); } case ftUnionValue: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Table<" + lifetime + ">>>(" + offset_name + \ - ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Table<" + + lifetime + ">>>(" + offset_name + ", None)", + field.required); } case ftUnionKey: case ftEnumKey: { - const auto underlying_typname = GetTypeBasic(type); //<- never used + const auto underlying_typname = GetTypeBasic(type); //<- never used const auto typname = WrapInNameSpace(*type.enum_def); const auto default_value = GetDefaultScalarValue(field); - return "self._tab.get::<" + typname + ">(" + offset_name + \ - ", Some(" + default_value + ")).unwrap()"; + return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + + default_value + ")).unwrap()"; } case ftString: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" + \ - offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" + + offset_name + ", None)", + field.required); } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - std::string s = "self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", " + typname + \ - ">>>(" + offset_name + ", None)"; + std::string s = + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", " + typname + ">>>(" + offset_name + ", None)"; // single-byte values are safe to slice if (IsOneByte(type.VectorType().base_type)) { s += ".map(|v| v.safe_slice())"; @@ -1094,49 +1074,60 @@ class RustGenerator : public BaseGenerator { return AddUnwrapIfRequired(s, field.required); } case ftVectorOfBool: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", bool>>>(" + \ - offset_name + ", None).map(|v| v.safe_slice())", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", bool>>>(" + offset_name + + ", None).map(|v| v.safe_slice())", + field.required); } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", " + typname + ">>>(" + \ - offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", " + typname + ">>>(" + offset_name + ", None)", + field.required); } case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + typname + ">>>(" + \ - offset_name + ", None).map(|v| v.safe_slice() )", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + typname + ">>>(" + offset_name + + ", None).map(|v| v.safe_slice() )", + field.required); } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" + typname + \ - "<" + lifetime + ">>>>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" + + typname + "<" + lifetime + ">>>>>(" + offset_name + ", None)", + field.required); } case ftVectorOfString: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" + \ - lifetime + " str>>>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" + + lifetime + " str>>>>(" + offset_name + ", None)", + field.required); } case ftVectorOfUnionValue: { FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported"); - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } - bool TableFieldReturnsOption(const Type& type) { + bool TableFieldReturnsOption(const Type &type) { switch (GetFullType(type)) { case ftInteger: case ftFloat: case ftBool: case ftEnumKey: - case ftUnionKey: - return false; + case ftUnionKey: return false; default: return true; } } @@ -1172,8 +1163,9 @@ class RustGenerator : public BaseGenerator { code_ += ""; code_ += "impl<'a> {{STRUCT_NAME}}<'a> {"; code_ += " #[inline]"; - code_ += " pub fn init_from_table(table: flatbuffers::Table<'a>) -> " - "Self {"; + code_ += + " pub fn init_from_table(table: flatbuffers::Table<'a>) -> " + "Self {"; code_ += " {{STRUCT_NAME}} {"; code_ += " _tab: table,"; code_ += " }"; @@ -1181,16 +1173,17 @@ class RustGenerator : public BaseGenerator { // Generate a convenient create* function that uses the above builder // to create a table in one function call. - code_.SetValue("MAYBE_US", - struct_def.fields.vec.size() == 0 ? "_" : ""); + code_.SetValue("MAYBE_US", struct_def.fields.vec.size() == 0 ? "_" : ""); code_.SetValue("MAYBE_LT", - TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : ""); + TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : ""); code_ += " #[allow(unused_mut)]"; code_ += " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>("; - code_ += " _fbb: " - "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,"; - code_ += " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})" - " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {"; + code_ += + " _fbb: " + "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,"; + code_ += + " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})" + " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {"; code_ += " let mut builder = {{STRUCT_NAME}}Builder::new(_fbb);"; for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; @@ -1203,8 +1196,9 @@ class RustGenerator : public BaseGenerator { size == SizeOf(field.value.type.base_type))) { code_.SetValue("FIELD_NAME", Name(field)); if (TableFieldReturnsOption(field.value.type)) { - code_ += " if let Some(x) = args.{{FIELD_NAME}} " - "{ builder.add_{{FIELD_NAME}}(x); }"; + code_ += + " if let Some(x) = args.{{FIELD_NAME}} " + "{ builder.add_{{FIELD_NAME}}(x); }"; } else { code_ += " builder.add_{{FIELD_NAME}}(args.{{FIELD_NAME}});"; } @@ -1227,8 +1221,9 @@ class RustGenerator : public BaseGenerator { code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field)); code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset)); - code_ += " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = " - "{{OFFSET_VALUE}};"; + code_ += + " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = " + "{{OFFSET_VALUE}};"; } code_ += ""; } @@ -1266,9 +1261,7 @@ class RustGenerator : public BaseGenerator { code_ += " }"; // Generate a comparison function for this field if it is a key. - if (field.key) { - GenKeyFieldMethods(field); - } + if (field.key) { GenKeyFieldMethods(field); } // Generate a nested flatbuffer field, if applicable. auto nested = field.attributes.Lookup("nested_flatbuffer"); @@ -1285,14 +1278,16 @@ class RustGenerator : public BaseGenerator { code_.SetValue("OFFSET_NAME", offset_prefix + "::" + GetFieldOffsetName(field)); - code_ += " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> " - " Option<{{STRUCT_NAME}}<'a>> {"; + code_ += + " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> " + " Option<{{STRUCT_NAME}}<'a>> {"; code_ += " match self.{{FIELD_NAME}}() {"; code_ += " None => { None }"; code_ += " Some(data) => {"; code_ += " use self::flatbuffers::Follow;"; - code_ += " Some(<flatbuffers::ForwardsUOffset" - "<{{STRUCT_NAME}}<'a>>>::follow(data, 0))"; + code_ += + " Some(<flatbuffers::ForwardsUOffset" + "<{{STRUCT_NAME}}<'a>>>::follow(data, 0))"; code_ += " },"; code_ += " }"; code_ += " }"; @@ -1315,22 +1310,26 @@ class RustGenerator : public BaseGenerator { auto &ev = **u_it; if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; } - auto table_init_type = WrapInNameSpace( - ev.union_type.struct_def->defined_namespace, - ev.union_type.struct_def->name); + auto table_init_type = + WrapInNameSpace(ev.union_type.struct_def->defined_namespace, + ev.union_type.struct_def->name); - code_.SetValue("U_ELEMENT_ENUM_TYPE", - WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev))); + code_.SetValue( + "U_ELEMENT_ENUM_TYPE", + WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev))); code_.SetValue("U_ELEMENT_TABLE_TYPE", table_init_type); code_.SetValue("U_ELEMENT_NAME", MakeSnakeCase(Name(ev))); code_ += " #[inline]"; code_ += " #[allow(non_snake_case)]"; - code_ += " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> " - "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {"; - code_ += " if self.{{FIELD_NAME}}_type() == {{U_ELEMENT_ENUM_TYPE}} {"; - code_ += " self.{{FIELD_NAME}}().map(|u| " - "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))"; + code_ += + " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> " + "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {"; + code_ += + " if self.{{FIELD_NAME}}_type() == {{U_ELEMENT_ENUM_TYPE}} {"; + code_ += + " self.{{FIELD_NAME}}().map(|u| " + "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))"; code_ += " } else {"; code_ += " None"; code_ += " }"; @@ -1344,7 +1343,7 @@ class RustGenerator : public BaseGenerator { // Generate an args struct: code_.SetValue("MAYBE_LT", - TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : ""); + TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : ""); code_ += "pub struct {{STRUCT_NAME}}Args{{MAYBE_LT}} {"; for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { @@ -1363,7 +1362,7 @@ class RustGenerator : public BaseGenerator { code_ += " fn default() -> Self {"; code_ += " {{STRUCT_NAME}}Args {"; for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; if (!field.deprecated) { code_.SetValue("PARAM_VALUE", TableBuilderArgsDefaultValue(field)); @@ -1379,8 +1378,9 @@ class RustGenerator : public BaseGenerator { // Generate a builder struct: code_ += "pub struct {{STRUCT_NAME}}Builder<'a: 'b, 'b> {"; code_ += " fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,"; - code_ += " start_: flatbuffers::WIPOffset<" - "flatbuffers::TableUnfinishedWIPOffset>,"; + code_ += + " start_: flatbuffers::WIPOffset<" + "flatbuffers::TableUnfinishedWIPOffset>,"; code_ += "}"; // Generate builder functions: @@ -1409,13 +1409,15 @@ class RustGenerator : public BaseGenerator { code_.SetValue("FIELD_TYPE", TableBuilderArgsAddFuncType(field, "'b ")); code_.SetValue("FUNC_BODY", TableBuilderArgsAddFuncBody(field)); code_ += " #[inline]"; - code_ += " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: " - "{{FIELD_TYPE}}) {"; + code_ += + " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: " + "{{FIELD_TYPE}}) {"; if (is_scalar) { code_.SetValue("FIELD_DEFAULT_VALUE", TableBuilderAddFuncDefaultValue(field)); - code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, " - "{{FIELD_DEFAULT_VALUE}});"; + code_ += + " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, " + "{{FIELD_DEFAULT_VALUE}});"; } else { code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}});"; } @@ -1438,8 +1440,9 @@ class RustGenerator : public BaseGenerator { // finish() function. code_ += " #[inline]"; - code_ += " pub fn finish(self) -> " - "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {"; + code_ += + " pub fn finish(self) -> " + "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {"; code_ += " let o = self.fbb_.end_table(self.start_);"; for (auto it = struct_def.fields.vec.begin(); @@ -1448,8 +1451,9 @@ class RustGenerator : public BaseGenerator { if (!field.deprecated && field.required) { code_.SetValue("FIELD_NAME", MakeSnakeCase(Name(field))); code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field)); - code_ += " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}}," - "\"{{FIELD_NAME}}\");"; + code_ += + " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}}," + "\"{{FIELD_NAME}}\");"; } } code_ += " flatbuffers::WIPOffset::new(o.value())"; @@ -1466,14 +1470,16 @@ class RustGenerator : public BaseGenerator { code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, "")); code_ += " #[inline]"; - code_ += " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> " - " bool {"; + code_ += + " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> " + " bool {"; code_ += " self.{{FIELD_NAME}}() < o.{{FIELD_NAME}}()"; code_ += " }"; code_ += ""; code_ += " #[inline]"; - code_ += " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> " - " ::std::cmp::Ordering {"; + code_ += + " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> " + " ::std::cmp::Ordering {"; code_ += " let key = self.{{FIELD_NAME}}();"; code_ += " key.cmp(&val)"; code_ += " }"; @@ -1499,10 +1505,12 @@ class RustGenerator : public BaseGenerator { code_ += ""; code_ += "#[inline]"; - code_ += "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}" - "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {"; - code_ += " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>" - "(buf)"; + code_ += + "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}" + "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {"; + code_ += + " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>" + "(buf)"; code_ += "}"; code_ += ""; @@ -1550,13 +1558,15 @@ class RustGenerator : public BaseGenerator { code_ += "}"; code_ += ""; code_ += "#[inline]"; - code_ += "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer" - "<'a, 'b>(" - "fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, " - "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {"; + code_ += + "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer" + "<'a, 'b>(" + "fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, " + "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {"; if (parser_.file_identifier_.length()) { - code_ += " fbb.finish_size_prefixed(root, " - "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));"; + code_ += + " fbb.finish_size_prefixed(root, " + "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));"; } else { code_ += " fbb.finish_size_prefixed(root, None);"; } @@ -1577,8 +1587,8 @@ class RustGenerator : public BaseGenerator { } static void PaddingDefinition(int bits, std::string *code_ptr, int *id) { - *code_ptr += " padding" + NumToString((*id)++) + "__: u" + \ - NumToString(bits) + ","; + *code_ptr += + " padding" + NumToString((*id)++) + "__: u" + NumToString(bits) + ","; } static void PaddingInitializer(int bits, std::string *code_ptr, int *id) { @@ -1644,8 +1654,9 @@ class RustGenerator : public BaseGenerator { code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; code_ += " let src = unsafe {"; - code_ += " ::std::slice::from_raw_parts(" - "self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; + code_ += + " ::std::slice::from_raw_parts(" + "self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; code_ += " };"; code_ += " dst.copy_from_slice(src);"; code_ += " }"; @@ -1656,8 +1667,9 @@ class RustGenerator : public BaseGenerator { code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; code_ += " let src = unsafe {"; - code_ += " ::std::slice::from_raw_parts(" - "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; + code_ += + " ::std::slice::from_raw_parts(" + "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; code_ += " };"; code_ += " dst.copy_from_slice(src);"; code_ += " }"; @@ -1674,14 +1686,12 @@ class RustGenerator : public BaseGenerator { it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; const auto member_name = Name(field) + "_"; - const auto reference = StructMemberAccessNeedsCopy(field.value.type) - ? "" : "&'a "; + const auto reference = + StructMemberAccessNeedsCopy(field.value.type) ? "" : "&'a "; const auto arg_name = "_" + Name(field); const auto arg_type = reference + GetTypeGet(field.value.type); - if (it != struct_def.fields.vec.begin()) { - arg_list += ", "; - } + if (it != struct_def.fields.vec.begin()) { arg_list += ", "; } arg_list += arg_name + ": "; arg_list += arg_type; init_list += " " + member_name; @@ -1717,8 +1727,9 @@ class RustGenerator : public BaseGenerator { auto field_type = TableBuilderArgsAddFuncType(field, "'a"); auto member = "self." + Name(field) + "_"; - auto value = StructMemberAccessNeedsCopy(field.value.type) ? - member + ".from_little_endian()" : member; + auto value = StructMemberAccessNeedsCopy(field.value.type) + ? member + ".from_little_endian()" + : member; code_.SetValue("FIELD_NAME", Name(field)); code_.SetValue("FIELD_TYPE", field_type); @@ -1731,22 +1742,20 @@ class RustGenerator : public BaseGenerator { code_ += " }"; // Generate a comparison function for this field if it is a key. - if (field.key) { - GenKeyFieldMethods(field); - } + if (field.key) { GenKeyFieldMethods(field); } } code_ += "}"; code_ += ""; } void GenNamespaceImports(const int white_spaces) { - std::string indent = std::string(white_spaces, ' '); - code_ += ""; - code_ += indent + "use std::mem;"; - code_ += indent + "use std::cmp::Ordering;"; - code_ += ""; - code_ += indent + "extern crate flatbuffers;"; - code_ += indent + "use self::flatbuffers::EndianScalar;"; + std::string indent = std::string(white_spaces, ' '); + code_ += ""; + code_ += indent + "use std::mem;"; + code_ += indent + "use std::cmp::Ordering;"; + code_ += ""; + code_ += indent + "extern crate flatbuffers;"; + code_ += indent + "use self::flatbuffers::EndianScalar;"; } // Set up the correct namespace. This opens a namespace if the current |