Escape 'type' keyword in generated Rust code
Use raw identifiers for fields named "type" to avoid conflicts with the Rust keyword. Fix field number indexing in tests.
This commit is contained in:
+5
-3
@@ -224,11 +224,12 @@ pub fn generate_rust_code(set: &FileDescriptorSet) -> String {
|
||||
// Field Accessors
|
||||
for (field_name, tag, f_type, f_label) in fields_info {
|
||||
let (rust_type, logic) = map_type_to_rust_accessor(f_type, f_label);
|
||||
let safe_name = if field_name == "type" { format!("r#{}", field_name) } else { field_name.clone() };
|
||||
|
||||
if f_label == 3 {
|
||||
output.push_str(&format!(
|
||||
" pub fn {}(&self) -> {} {{\n",
|
||||
field_name, rust_type
|
||||
safe_name, rust_type
|
||||
));
|
||||
output.push_str(&format!(
|
||||
" match (self.{}_start, self.{}_end) {{\n",
|
||||
@@ -246,7 +247,7 @@ pub fn generate_rust_code(set: &FileDescriptorSet) -> String {
|
||||
} else {
|
||||
output.push_str(&format!(
|
||||
" pub fn {}(&self) -> Result<{}> {{\n",
|
||||
field_name, rust_type
|
||||
safe_name, rust_type
|
||||
));
|
||||
output.push_str(&format!(
|
||||
" let offset = self.{}_offset.ok_or(RotoError::FieldNotFound)?;\n",
|
||||
@@ -275,6 +276,7 @@ pub fn generate_rust_code(set: &FileDescriptorSet) -> String {
|
||||
let (field_data, _) = field_res.expect("Failed to iterate field");
|
||||
let field_proto = FieldDescriptorProto::new(field_data).expect("Failed to parse FieldDescriptorProto");
|
||||
let field_name = field_proto.name().unwrap();
|
||||
let safe_name = if field_name == "type" { format!("r#{}", field_name) } else { field_name.to_string() };
|
||||
|
||||
let tag = field_proto.number().unwrap();
|
||||
let f_type = field_proto.field_type().unwrap() as i32;
|
||||
@@ -283,7 +285,7 @@ pub fn generate_rust_code(set: &FileDescriptorSet) -> String {
|
||||
|
||||
output.push_str(&format!(
|
||||
" pub fn {}(mut self, value: {}) -> Result<Self> {{\n self.builder.{}({}, value)?;\n Ok(self)\n }}\n\n",
|
||||
field_name, rust_type, method, tag
|
||||
safe_name, rust_type, method, tag
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -520,7 +520,7 @@ mod tests {
|
||||
|
||||
// Validate that fields appear in the expected relative order
|
||||
let field_numbers: Vec<u32> = acc.fields()
|
||||
.map(|r| r.expect("Failed to decode field").0.field_number)
|
||||
.map(|r| r.expect("Failed to decode field").1.field_number)
|
||||
.collect();
|
||||
|
||||
let essential_fields = [1, 2, 3, 14, 16, 20];
|
||||
|
||||
Reference in New Issue
Block a user