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

Update identifier Unicode character validation to match Python spec #7209

Merged
merged 2 commits into from
Sep 7, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/ruff_python_stdlib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ license = { workspace = true }
[lib]

[dependencies]
unic-ucd-ident = "0.9.0"
25 changes: 22 additions & 3 deletions crates/ruff_python_stdlib/src/identifiers.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
use unic_ucd_ident::{is_xid_continue, is_xid_start};

use crate::keyword::is_keyword;

/// Returns `true` if a string is a valid Python identifier (e.g., variable
/// name).
pub fn is_identifier(name: &str) -> bool {
// Is the first character a letter or underscore?
let mut chars = name.chars();
if !chars.next().is_some_and(|c| c.is_alphabetic() || c == '_') {
if !chars.next().is_some_and(|c| c == '_' || is_xid_start(c)) {
return false;
}

// Are the rest of the characters letters, digits, or underscores?
if !chars.all(|c| c.is_alphanumeric() || c == '_') {
if !chars.all(|c| c == '_' || is_xid_continue(c)) {
return false;
}

Expand Down Expand Up @@ -76,7 +78,24 @@ pub fn is_migration_name(name: &str) -> bool {

#[cfg(test)]
mod tests {
use crate::identifiers::{is_migration_name, is_module_name};
use crate::identifiers::{is_identifier, is_migration_name, is_module_name};

#[test]
fn valid_identifiers() {
assert!(is_identifier("_abc"));
Copy link
Member

Choose a reason for hiding this comment

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

Nice tests!

assert!(is_identifier("abc"));
assert!(is_identifier("_"));
assert!(is_identifier("a_b_c"));
assert!(is_identifier("abc123"));
assert!(is_identifier("abc_123"));
assert!(is_identifier("漢字"));
assert!(is_identifier("ひらがな"));
assert!(is_identifier("العربية"));
assert!(is_identifier("кириллица"));
assert!(is_identifier("πr"));
assert!(!is_identifier("percentile_co³t"));
assert!(!is_identifier("HelloWorld❤️"));
}

#[test]
fn module_name() {
Expand Down