From 184f57962e46edd910b4ddb2e0ca33ee4ab555ea Mon Sep 17 00:00:00 2001 From: Stepan Koltsov Date: Sun, 3 Dec 2017 00:34:00 +0000 Subject: [PATCH] Escape rust name in enum value variants CC #257 --- protobuf-test/src/common/v2/test_ident_pb.proto | 8 ++++++++ protobuf/src/codegen/enums.rs | 10 +++------- protobuf/src/descriptorx.rs | 15 +++++++++++++++ 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/protobuf-test/src/common/v2/test_ident_pb.proto b/protobuf-test/src/common/v2/test_ident_pb.proto index fb236fb87..261961c91 100644 --- a/protobuf-test/src/common/v2/test_ident_pb.proto +++ b/protobuf-test/src/common/v2/test_ident_pb.proto @@ -33,3 +33,11 @@ message TestType { repeated string struct = 2; repeated uint32 ref = 3; } + +// enum value which is a keyword + +enum MyLittleEnum { + UNKNOWN = 0; + fn = 2; + self = 3; +} diff --git a/protobuf/src/codegen/enums.rs b/protobuf/src/codegen/enums.rs index 3e08ef4e0..23c755162 100644 --- a/protobuf/src/codegen/enums.rs +++ b/protobuf/src/codegen/enums.rs @@ -19,18 +19,14 @@ impl EnumValueGen { } } - // value name - fn name<'a>(&'a self) -> &'a str { - self.proto.get_name() - } - // enum value fn number(&self) -> i32 { self.proto.get_number() } + // name of enum variant in generated rust code fn rust_name_inner(&self) -> String { - self.name().to_string() + self.proto.rust_name() } pub fn rust_name_outer(&self) -> String { @@ -262,7 +258,7 @@ impl<'a> EnumGen<'a> { w.write_line(&format!( "{}::{}", &self.type_name, - &self.enum_with_scope.values()[0].get_name() + &self.enum_with_scope.values()[0].rust_name() )) }); }); diff --git a/protobuf/src/descriptorx.rs b/protobuf/src/descriptorx.rs index b6dc19898..7baaa8b3d 100644 --- a/protobuf/src/descriptorx.rs +++ b/protobuf/src/descriptorx.rs @@ -434,6 +434,21 @@ impl<'a> EnumWithScope<'a> { } } +pub trait EnumValueDescriptorEx { + fn rust_name(&self) -> String; +} + +impl EnumValueDescriptorEx for EnumValueDescriptorProto { + fn rust_name(&self) -> String { + let mut r = String::new(); + if rust::is_rust_keyword(self.get_name()) { + r.push_str("value_"); + } + r.push_str(self.get_name()); + r + } +} + impl<'a> WithScope<'a> for EnumWithScope<'a> { fn get_scope(&self) -> &Scope<'a> { &self.scope