From aaff7f274b457dd49fc713033c936a5a3814014f Mon Sep 17 00:00:00 2001 From: Max Burke Date: Mon, 28 Oct 2019 12:26:33 -0700 Subject: [PATCH] Bugfix for Rust generation of union fields named with language keywords Looking at ParseField, it appears that in the case of unions, an extra field with a `UnionTypeFieldSuffix` is added to the type definition, however, if the name of this field is a keyword in the target language, it isn't escaped. For example, if generating code for rust for a union field named `type`, flatc will generate a (non-keyword escaped) field named `type_type` for this hidden union field, and one (keyword escaped) called `type_` for the actual union contents. When the union accessors are generated, they refer to this `type_type` field, but they will escape it mistakenly, generating code like this: ``` #[inline] #[allow(non_snake_case)] pub fn type__as_int(&self) -> Option> { if self.type__type() == Type::Int { self.type_().map(|u| Int::init_from_table(u)) } else { None } } ``` Which will fail to build because the field is called `self.type_type()`, not `self.type__type()`. --- src/idl_gen_rust.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp index 936ac8369..0952ecf4a 100644 --- a/src/idl_gen_rust.cpp +++ b/src/idl_gen_rust.cpp @@ -1310,6 +1310,7 @@ class RustGenerator : public BaseGenerator { auto u = field.value.type.enum_def; code_.SetValue("FIELD_NAME", Name(field)); + code_.SetValue("FIELD_TYPE_FIELD_NAME", field.name); for (auto u_it = u->Vals().begin(); u_it != u->Vals().end(); ++u_it) { auto &ev = **u_it; @@ -1328,7 +1329,7 @@ class RustGenerator : public BaseGenerator { 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_ += " if self.{{FIELD_TYPE_FIELD_NAME}}_type() == {{U_ELEMENT_ENUM_TYPE}} {"; code_ += " self.{{FIELD_NAME}}().map(|u| " "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))"; code_ += " } else {";