Skip to content

Commit

Permalink
Add underscore at the end of known common members for C# properties
Browse files Browse the repository at this point in the history
This won't remove all possibilities of naming collisions, but will address the simplest ones.
The "test" is just to add all the reserved names in a proto file: if the generated code builds, it works.
Note that before this change, using any of these field names would result in a compile-time error, so this is not a breaking change.

Generated code is in the next commit.

Fixes #8810
  • Loading branch information
jskeet committed Jul 19, 2022
1 parent ddf2c6b commit a5889a3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
16 changes: 15 additions & 1 deletion csharp/protos/unittest_issues.proto
Original file line number Diff line number Diff line change
Expand Up @@ -169,4 +169,18 @@ message OneofWithNoneName {
string x = 1;
string y = 2;
}
}
}

// Issue 8810
message DisambiguateCommonMembers {
int32 equals = 1;
int32 to_string = 2;
int32 get_hash_code = 3;
int32 write_to = 4;
int32 clone = 5;
int32 calculate_size = 6;
int32 descriptor = 7;
int32 merge_from = 8;
int32 on_construction = 9;
int32 parser = 10;
}
17 changes: 13 additions & 4 deletions src/google/protobuf/compiler/csharp/csharp_helpers.cc
Original file line number Diff line number Diff line change
Expand Up @@ -381,13 +381,22 @@ std::string GetFieldConstantName(const FieldDescriptor* field) {
std::string GetPropertyName(const FieldDescriptor* descriptor) {
// TODO(jtattermusch): consider introducing csharp_property_name field option
std::string property_name = UnderscoresToPascalCase(GetFieldName(descriptor));
// Avoid either our own type name or reserved names. Note that not all names
// are reserved - a field called to_string, write_to etc would still cause a problem.
// Avoid either our own type name or reserved names.
// There are various ways of ending up with naming collisions, but we try to avoid obvious
// ones.
// ones. In particular, we avoid the names of all the members we generate or inherit.
if (property_name == descriptor->containing_type()->name()
|| property_name == "Types"
|| property_name == "Descriptor") {
|| property_name == "Descriptor"
|| property_name == "Equals"
|| property_name == "ToString"
|| property_name == "GetHashCode"
|| property_name == "WriteTo"
|| property_name == "Clone"
|| property_name == "CalculateSize"
|| property_name == "Descriptor"
|| property_name == "MergeFrom"
|| property_name == "OnConstruction"
|| property_name == "Parser") {
property_name += "_";
}
return property_name;
Expand Down

0 comments on commit a5889a3

Please sign in to comment.