Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not replace starting digit with underscore when making identifier #82786

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions core/string/ustring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3974,24 +3974,22 @@ bool String::is_absolute_path() const {
}
}

static _FORCE_INLINE_ bool _is_valid_identifier_bit(int p_index, char32_t p_char) {
if (p_index == 0 && is_digit(p_char)) {
return false; // No start with number plz.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll miss that comment. 👀

}
return is_ascii_identifier_char(p_char);
}

String String::validate_identifier() const {
if (is_empty()) {
return "_"; // Empty string is not a valid identifier;
}

String result = *this;
String result;
if (is_digit(operator[](0))) {
result = "_" + *this;
} else {
result = *this;
}

int len = result.length();
char32_t *buffer = result.ptrw();

for (int i = 0; i < len; i++) {
if (!_is_valid_identifier_bit(i, buffer[i])) {
if (!is_ascii_identifier_char(buffer[i])) {
buffer[i] = '_';
}
}
Expand All @@ -4006,10 +4004,14 @@ bool String::is_valid_identifier() const {
return false;
}

if (is_digit(operator[](0))) {
return false;
}

const char32_t *str = &operator[](0);

for (int i = 0; i < len; i++) {
if (!_is_valid_identifier_bit(i, str[i])) {
if (!is_ascii_identifier_char(str[i])) {
return false;
}
}
Expand Down
2 changes: 1 addition & 1 deletion tests/core/string/test_string.h
Original file line number Diff line number Diff line change
Expand Up @@ -1716,7 +1716,7 @@ TEST_CASE("[String] validate_identifier") {
CHECK(empty_string.validate_identifier() == "_");

String numeric_only = "12345";
CHECK(numeric_only.validate_identifier() == "_2345");
CHECK(numeric_only.validate_identifier() == "_12345");

String name_with_spaces = "Name with spaces";
CHECK(name_with_spaces.validate_identifier() == "Name_with_spaces");
Expand Down
Loading