Skip to content

Commit

Permalink
Escape rust name in enum value variants
Browse files Browse the repository at this point in the history
CC #257
  • Loading branch information
stepancheg committed Dec 3, 2017
1 parent f7ef45c commit 4a582fc
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
8 changes: 8 additions & 0 deletions protobuf-test/src/common/v2/test_ident_pb.proto
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
10 changes: 3 additions & 7 deletions protobuf/src/codegen/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
))
});
});
Expand Down
15 changes: 15 additions & 0 deletions protobuf/src/descriptorx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4a582fc

Please sign in to comment.