pub fn is_name_start(ch: char) -> bool {
ch == '_' || unicode_ident::is_xid_start(ch)
}
pub fn is_name_continue(ch: char) -> bool {
ch == '_' || unicode_ident::is_xid_continue(ch)
}
pub fn is_name_start_with_dollar(ch: char, dollar_allowed: bool) -> bool {
is_name_start(ch) || (dollar_allowed && ch == '$')
}
pub fn is_name_continue_with_dollar(ch: char, dollar_allowed: bool) -> bool {
is_name_continue(ch) || (dollar_allowed && ch == '$')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ascii_identifiers_are_identifiers() {
for ch in ['a', 'z', 'A', 'Z', '_', '0', '9'] {
assert!(
is_name_continue(ch),
"{ch:?} must be able to continue an identifier"
);
}
for ch in ['0', '9'] {
assert!(
!is_name_start(ch),
"{ch:?} must not be able to start an identifier"
);
}
assert!(!is_name_start('$') && !is_name_continue('$'));
}
#[test]
fn unicode_identifiers_follow_xid() {
for ch in ['é', '中', 'λ', 'Ж'] {
assert!(
is_name_start(ch),
"{ch:?} is XID_Start and must be accepted"
);
assert!(is_name_continue(ch));
}
for ch in ['😀', '@', '#', '-', '.', '+'] {
assert!(!is_name_start(ch), "{ch:?} must not start an identifier");
assert!(!is_name_continue(ch), "{ch:?} must not continue one");
}
}
#[test]
fn dollar_is_gated() {
assert!(is_name_start_with_dollar('$', true));
assert!(!is_name_start_with_dollar('$', false));
}
}