From 98fa64674c4cf09414bf0041b09ffabbd98a088d Mon Sep 17 00:00:00 2001 From: Dikshant Neupane Date: Fri, 27 Nov 2026 17:38:28 +0000 Subject: [PATCH 1/7] tr: classify character classes by the current locale In a single-byte locale such as en_US.ISO-8859-1, `tr -d '[:cntrl:]'` kept the C1 bytes 0x80 to 0x9F because every class expanded from a fixed ASCII table and nothing read LC_CTYPE. The ASCII tables are unchanged. Bytes 128 to 255 classified by the C library in the current locale are chained after them, computed once into tables the set paths reuse. In multibyte locales the tables stay ASCII-only, so multibyte characters are never split. --- Cargo.lock | 1 + fuzz/Cargo.lock | 1 + src/uu/tr/Cargo.toml | 3 +- src/uu/tr/src/operation.rs | 210 ++++++++++++++++++++++++++++--------- tests/by-util/test_tr.rs | 52 +++++++++ 5 files changed, 217 insertions(+), 50 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a91bde503c..dc73257973d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4199,6 +4199,7 @@ dependencies = [ "clap", "codspeed-divan-compat", "fluent", + "libc", "memchr", "nom 8.0.0", "rustix", diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 6b14180bd41..fc6dcb12e14 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -1768,6 +1768,7 @@ dependencies = [ "bytecount", "clap", "fluent", + "libc", "memchr", "nom", "uucore", diff --git a/src/uu/tr/Cargo.toml b/src/uu/tr/Cargo.toml index d17b671ca68..1b94c8f5411 100644 --- a/src/uu/tr/Cargo.toml +++ b/src/uu/tr/Cargo.toml @@ -20,9 +20,10 @@ doctest = false bytecount = { workspace = true, features = ["runtime-dispatch-simd"] } clap = { workspace = true } fluent = { workspace = true } +libc = { workspace = true } memchr = { workspace = true } nom = { workspace = true } -uucore = { workspace = true, features = ["fs", "signals"] } +uucore = { workspace = true, features = ["fs", "i18n-charmap", "signals"] } [dev-dependencies] divan = { workspace = true } diff --git a/src/uu/tr/src/operation.rs b/src/uu/tr/src/operation.rs index 32474d648e3..cbbc60edc4a 100644 --- a/src/uu/tr/src/operation.rs +++ b/src/uu/tr/src/operation.rs @@ -23,6 +23,7 @@ use std::{ ops::Range, }; use uucore::error::{FromIo, UError, UResult}; +use uucore::i18n::charmap::{Encoding, locale_encoding}; use uucore::translate; use uucore::show_warning; @@ -226,66 +227,165 @@ pub enum Sequence { Class(Class), } +/// Initialise the process locale from the environment, as `dd` does. +/// Windows is excluded: setlocale selects the ANSI code page, classifying high bytes. +#[cfg(not(any(target_os = "wasi", target_os = "windows")))] +fn init_locale() { + // SAFETY: setlocale is called with a valid C string, as in `dd`. + unsafe { + libc::setlocale(libc::LC_CTYPE, c"".as_ptr()); + } +} + +#[cfg(any(target_os = "wasi", target_os = "windows"))] +fn init_locale() {} + +/// Whether a high byte belongs to a class in the current locale. +/// Only asked about bytes 128 and above; ASCII is handled separately. +#[cfg(not(target_os = "wasi"))] +fn locale_is_member(class: Class, byte: u8) -> bool { + // SAFETY: the is* functions take a byte in range and only read locale state. + let result = unsafe { + match class { + Class::Alnum => libc::isalnum(i32::from(byte)), + Class::Alpha => libc::isalpha(i32::from(byte)), + Class::Blank => libc::isblank(i32::from(byte)), + Class::Control => libc::iscntrl(i32::from(byte)), + Class::Digit => libc::isdigit(i32::from(byte)), + Class::Graph => libc::isgraph(i32::from(byte)), + Class::Lower => libc::islower(i32::from(byte)), + Class::Print => libc::isprint(i32::from(byte)), + Class::Punct => libc::ispunct(i32::from(byte)), + Class::Space => libc::isspace(i32::from(byte)), + Class::Upper => libc::isupper(i32::from(byte)), + Class::Xdigit => libc::isxdigit(i32::from(byte)), + } + }; + result != 0 +} + +#[cfg(target_os = "wasi")] +fn locale_is_member(_class: Class, _byte: u8) -> bool { + false +} + +/// All classes, in enum declaration order, so `Class as usize` indexes [`LocaleTables::members`]. +const ALL_CLASSES: [Class; 12] = [ + Class::Alnum, + Class::Alpha, + Class::Blank, + Class::Control, + Class::Digit, + Class::Graph, + Class::Lower, + Class::Print, + Class::Punct, + Class::Space, + Class::Upper, + Class::Xdigit, +]; + +/// The locale class tables, computed once per `solve_set_characters` call from the current locale. +pub(crate) struct LocaleTables { + /// Full members (ASCII, then locale high bytes) for each class. + members: [Vec; 12], +} + +impl LocaleTables { + fn build() -> Self { + // Only trust the C library classification in a single-byte locale: in a + // multibyte locale it also matches high bytes, cutting characters in half. + let single_byte = locale_encoding() == Encoding::SingleByte; + Self::build_for(single_byte) + } + + fn build_for(single_byte: bool) -> Self { + let members: [Vec; 12] = ALL_CLASSES.map(|class| { + let mut members: Vec = class.ascii_members().collect(); + if single_byte { + members.extend(class.locale_members()); + } + members + }); + Self { members } + } + + fn members(&self, class: Class) -> &[u8] { + &self.members[class as usize] + } +} + +impl Class { + /// The class members that do not depend on the locale. + fn ascii_members(self) -> Box> { + match self { + Self::Alnum => Box::new((b'0'..=b'9').chain(b'A'..=b'Z').chain(b'a'..=b'z')), + Self::Alpha => Box::new((b'A'..=b'Z').chain(b'a'..=b'z')), + Self::Blank => Box::new(unicode_table::BLANK.iter().copied()), + Self::Control => Box::new((0..=31).chain(std::iter::once(127))), + Self::Digit => Box::new(b'0'..=b'9'), + Self::Graph => Box::new( + (48..=57) + .chain(65..=90) + .chain(97..=122) + .chain(33..=47) + .chain(58..=64) + .chain(91..=96) + .chain(123..=126), + ), + Self::Print => Box::new( + (48..=57) + .chain(65..=90) + .chain(97..=122) + .chain(33..=47) + .chain(58..=64) + .chain(91..=96) + .chain(123..=126) + .chain(std::iter::once(b' ')), + ), + Self::Punct => Box::new((33..=47).chain(58..=64).chain(91..=96).chain(123..=126)), + Self::Space => Box::new(unicode_table::SPACES.iter().copied()), + Self::Xdigit => Box::new((b'0'..=b'9').chain(b'A'..=b'F').chain(b'a'..=b'f')), + Self::Lower => Box::new(b'a'..=b'z'), + Self::Upper => Box::new(b'A'..=b'Z'), + } + } + + /// The class members above ASCII in the current locale, in byte order. + fn locale_members(self) -> Box> { + let class = self; + Box::new((128..=u8::MAX).filter(move |byte| locale_is_member(class, *byte))) + } +} + impl Sequence { - pub fn flatten(&self) -> Box> { + pub fn flatten<'a>(&'a self, tables: &'a LocaleTables) -> Box + 'a> { match self { Self::Char(c) | Self::Equivalence(c) => Box::new(std::iter::once(*c)), Self::CharRange(l, r) => Box::new(*l..=*r), Self::CharStar(c) => Box::new(std::iter::repeat(*c)), Self::CharRepeat(c, n) => Box::new(std::iter::repeat_n(*c, *n)), - Self::Class(class) => match class { - Class::Alnum => Box::new((b'0'..=b'9').chain(b'A'..=b'Z').chain(b'a'..=b'z')), - Class::Alpha => Box::new((b'A'..=b'Z').chain(b'a'..=b'z')), - Class::Blank => Box::new(unicode_table::BLANK.iter().copied()), - Class::Control => Box::new((0..=31).chain(std::iter::once(127))), - Class::Digit => Box::new(b'0'..=b'9'), - Class::Graph => Box::new( - (48..=57) // digit - .chain(65..=90) // uppercase - .chain(97..=122) // lowercase - // punctuations - .chain(33..=47) - .chain(58..=64) - .chain(91..=96) - .chain(123..=126), - ), - Class::Print => Box::new( - (48..=57) // digit - .chain(65..=90) // uppercase - .chain(97..=122) // lowercase - // punctuations - .chain(33..=47) - .chain(58..=64) - .chain(91..=96) - .chain(123..=126) - .chain(std::iter::once(32)), // space - ), - Class::Punct => Box::new((33..=47).chain(58..=64).chain(91..=96).chain(123..=126)), - Class::Space => Box::new(unicode_table::SPACES.iter().copied()), - Class::Xdigit => Box::new((b'0'..=b'9').chain(b'A'..=b'F').chain(b'a'..=b'f')), - Class::Lower => Box::new(b'a'..=b'z'), - Class::Upper => Box::new(b'A'..=b'Z'), - }, + Self::Class(class) => Box::new(tables.members(*class).iter().copied()), } } /// How many characters the sequence expands to, without expanding it: /// the count of a `[c*n]` repeat can be far too large to materialize. - fn expanded_len(&self) -> usize { + fn expanded_len(&self, tables: &LocaleTables) -> usize { match self { Self::Char(_) | Self::Equivalence(_) => 1, Self::CharRange(l, r) => usize::from(*r) - usize::from(*l) + 1, // A star is only sized once it has been turned into a repeat. Self::CharStar(_) => 0, Self::CharRepeat(_, n) => *n, - Self::Class(_) => self.flatten().count(), + Self::Class(_) => self.flatten(tables).count(), } } /// The expanded length of a set. Widened so that repeat counts close to /// `usize::MAX` still add up exactly and positions keep their order. - fn expanded_len_of(set: &[Self]) -> u128 { - set.iter().map(|s| s.expanded_len() as u128).sum() + fn expanded_len_of(set: &[Self], tables: &LocaleTables) -> u128 { + set.iter().map(|s| s.expanded_len(tables) as u128).sum() } /// The characters of a set, in order, as runs of a repeated character. @@ -293,13 +393,16 @@ impl Sequence { /// A `[c*n]` repeat is a single run however large `n` is; everything else /// expands to runs of one character. Empty runs are left out, and a star /// must have been turned into a repeat first. - fn runs(set: &[Self]) -> impl Iterator + '_ { + fn runs<'a>( + set: &'a [Self], + tables: &'a LocaleTables, + ) -> impl Iterator + 'a { set.iter() .flat_map(|s| -> Box> { match s { Self::CharRepeat(c, n) => Box::new(std::iter::once((*c, *n))), Self::CharStar(_) => Box::new(std::iter::empty()), - _ => Box::new(s.flatten().map(|c| (c, 1))), + _ => Box::new(s.flatten(tables).map(|c| (c, 1))), } }) .filter(|(_, n)| *n > 0) @@ -320,10 +423,14 @@ impl Sequence { /// The complement of the characters that a set holds, or that its first /// `len` positions hold, one run per character. - fn complement_of_prefix(set: &[Self], len: Option) -> Vec<(u8, usize)> { + fn complement_of_prefix( + set: &[Self], + len: Option, + tables: &LocaleTables, + ) -> Vec<(u8, usize)> { let mut present = [false; 256]; let mut remaining = len; - for (c, n) in Self::runs(set) { + for (c, n) in Self::runs(set, tables) { if remaining == Some(0) { break; } @@ -344,6 +451,10 @@ impl Sequence { truncate_set1_flag: bool, translating: bool, ) -> Result<(Vec, Vec), SequenceError> { + // The class tables are built once here, after the locale is initialised. + init_locale(); + let tables = LocaleTables::build(); + let is_char_star = |s: &&Self| -> bool { matches!(s, Self::CharStar(_)) }; let set1 = Self::parse_set(set1_str).map_err(|(error, span)| SequenceError { @@ -398,15 +509,15 @@ impl Sequence { // be far too large for that. Both are handled as runs of one character // instead, and only the lengths are ever computed in full. let mut set1_runs: Vec<(u8, usize)> = if complement_flag { - Self::complement_of_prefix(&set1, None) + Self::complement_of_prefix(&set1, None, &tables) } else { - Self::runs(&set1).collect() + Self::runs(&set1, &tables).collect() }; let set1_len = Self::runs_len(&set1_runs); // A star has no length of its own until it is turned into a repeat, // so this is the length of everything else in set2. - let set2_fixed_len = Self::expanded_len_of(&set2); + let set2_fixed_len = Self::expanded_len_of(&set2, &tables); let star_compensate_len = usize::try_from(set1_len.saturating_sub(set2_fixed_len)).unwrap_or(usize::MAX); @@ -426,7 +537,7 @@ impl Sequence { if translating && !complement_flag { for (set2_pos, set2_item) in set2.iter().enumerate() { if matches!(set2_item, Self::Class(_)) { - let set2_part_solved_len = Self::expanded_len_of(&set2[..set2_pos]); + let set2_part_solved_len = Self::expanded_len_of(&set2[..set2_pos], &tables); // Like GNU, a class that starts past the end of set1 is never // used, so it needs no partner there. if set2_part_solved_len > set1_len { @@ -437,7 +548,8 @@ impl Sequence { for (set1_pos, set1_item) in set1.iter().enumerate() { // only upper/lower can pair with upper/lower if matches!(set1_item, Self::Class(Class::Upper | Class::Lower)) - && Self::expanded_len_of(&set1[..set1_pos]) == set2_part_solved_len + && Self::expanded_len_of(&set1[..set1_pos], &tables) + == set2_part_solved_len { class_matches = true; break; @@ -454,7 +566,7 @@ impl Sequence { } } - let set2_runs: Vec<(u8, usize)> = Self::runs(&set2).collect(); + let set2_runs: Vec<(u8, usize)> = Self::runs(&set2, &tables).collect(); let set2_len = Self::runs_len(&set2_runs); // Calculate the set of unique characters in set2 @@ -469,7 +581,7 @@ impl Sequence { // That means we must first truncate the expanded, non-complemented // source set, then complement the truncated prefix to recover the // final translation domain. - set1_runs = Self::complement_of_prefix(&set1, Some(set2_len)); + set1_runs = Self::complement_of_prefix(&set1, Some(set2_len), &tables); // After expansion the complemented domain may be larger than set2. // Re-check the complement validity constraint. if set2_uniques.len() > 1 || set1_runs.len() as u128 > set2_len { diff --git a/tests/by-util/test_tr.rs b/tests/by-util/test_tr.rs index 73a85bd4117..799fb98c013 100644 --- a/tests/by-util/test_tr.rs +++ b/tests/by-util/test_tr.rs @@ -1558,6 +1558,58 @@ fn test_stdin_is_socket() { .stdout_is(";;"); } +#[cfg(unix)] +#[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] +#[test] +fn test_classes_follow_single_byte_locale() { + // Compile a Latin-1 locale into the scenario's tmp dir. + let (at, _ucmd) = at_and_ucmd!(); + let compiled = std::process::Command::new("localedef") + .args(["-i", "en_US", "-f", "ISO-8859-1"]) + .arg(at.plus("en_US.ISO-8859-1")) + .output() + .is_ok_and(|output| output.status.success()); + assert!( + compiled, + "localedef failed to compile the Latin-1 test locale" + ); + let locpath = at.as_string(); + // In Latin-1, 0x9b is a control character, so -d [:cntrl:] removes it. + new_ucmd!() + .env("LOCPATH", &locpath) + .env("LC_ALL", "en_US.ISO-8859-1") + .args(&["-d", "[:cntrl:]"]) + .pipe_in([b'h', b'e', b'l', b'l', b'o', 0x9b, b'3', b'1', b'm']) + .succeeds() + .stdout_is_bytes(b"hello31m"); +} + +#[cfg(unix)] +#[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] +#[test] +fn test_classes_ignore_high_bytes_in_utf8_locale() { + // Compile a UTF-8 locale into the scenario's tmp dir. + let (at, _ucmd) = at_and_ucmd!(); + let compiled = std::process::Command::new("localedef") + .args(["-i", "en_US", "-f", "UTF-8"]) + .arg(at.plus("en_US.UTF-8")) + .output() + .is_ok_and(|output| output.status.success()); + assert!( + compiled, + "localedef failed to compile the UTF-8 test locale" + ); + let locpath = at.as_string(); + // In UTF-8, high bytes are never class members, so -d [:alpha:] must not split é. + new_ucmd!() + .env("LOCPATH", &locpath) + .env("LC_ALL", "en_US.UTF-8") + .args(&["-d", "[:alpha:]"]) + .pipe_in([b'a', 0xc3, 0xa9, b'b']) + .succeeds() + .stdout_is_bytes([0xc3, 0xa9]); +} + #[cfg(all(feature = "feat_diagnostics", not(wasi_runner)))] mod diagnostics { use super::*; From 7d2e2354b203eb4b93960cf70de3620400e26b00 Mon Sep 17 00:00:00 2001 From: Dikshant Neupane Date: Fri, 27 Nov 2026 18:44:52 +0000 Subject: [PATCH 2/7] tr: use installed locales for the class tests on FreeBSD and macOS The glibc-style localedef invocation fails on FreeBSD and macOS: their localedef takes source-file pathnames and no locale sources are installed. Use the installed en_US.ISO8859-1 / en_US.UTF-8 locales there instead, and skip the single-byte test on macOS, which ships no single-byte locale. --- tests/by-util/test_tr.rs | 74 +++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 27 deletions(-) diff --git a/tests/by-util/test_tr.rs b/tests/by-util/test_tr.rs index 799fb98c013..b4d9bb33d23 100644 --- a/tests/by-util/test_tr.rs +++ b/tests/by-util/test_tr.rs @@ -1558,26 +1558,54 @@ fn test_stdin_is_socket() { .stdout_is(";;"); } -#[cfg(unix)] -#[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] -#[test] -fn test_classes_follow_single_byte_locale() { - // Compile a Latin-1 locale into the scenario's tmp dir. - let (at, _ucmd) = at_and_ucmd!(); +// Returns (`LC_ALL`, optional `LOCPATH`): on Linux the locale is compiled +// with localedef into the scenario tmp dir, while FreeBSD and macOS use the +// installed system locale, as their localedef needs locale sources that are +// not installed there. +#[cfg(all(unix, target_os = "linux"))] +fn locale_test_env( + at: &uutests::util::AtPath, + charmap: &str, + glibc_name: &str, + _system_name: &str, +) -> (String, Option) { let compiled = std::process::Command::new("localedef") - .args(["-i", "en_US", "-f", "ISO-8859-1"]) - .arg(at.plus("en_US.ISO-8859-1")) + .args(["-i", "en_US", "-f", charmap]) + .arg(at.plus(glibc_name)) .output() .is_ok_and(|output| output.status.success()); assert!( compiled, - "localedef failed to compile the Latin-1 test locale" + "localedef failed to compile the {glibc_name} test locale" ); - let locpath = at.as_string(); + (glibc_name.to_string(), Some(at.as_string())) +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn locale_test_env( + _at: &uutests::util::AtPath, + _charmap: &str, + _glibc_name: &str, + system_name: &str, +) -> (String, Option) { + (system_name.to_string(), None) +} + +#[cfg(unix)] +#[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] +// macOS ships no single-byte locale, so this test has nothing to run against there. +#[cfg(not(target_os = "macos"))] +#[test] +fn test_classes_follow_single_byte_locale() { + let (at, _ucmd) = at_and_ucmd!(); + let (locale, locpath) = + locale_test_env(&at, "ISO-8859-1", "en_US.ISO-8859-1", "en_US.ISO8859-1"); + let mut cmd = new_ucmd!(); + if let Some(locpath) = locpath { + cmd.env("LOCPATH", locpath); + } // In Latin-1, 0x9b is a control character, so -d [:cntrl:] removes it. - new_ucmd!() - .env("LOCPATH", &locpath) - .env("LC_ALL", "en_US.ISO-8859-1") + cmd.env("LC_ALL", locale) .args(&["-d", "[:cntrl:]"]) .pipe_in([b'h', b'e', b'l', b'l', b'o', 0x9b, b'3', b'1', b'm']) .succeeds() @@ -1588,22 +1616,14 @@ fn test_classes_follow_single_byte_locale() { #[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] #[test] fn test_classes_ignore_high_bytes_in_utf8_locale() { - // Compile a UTF-8 locale into the scenario's tmp dir. let (at, _ucmd) = at_and_ucmd!(); - let compiled = std::process::Command::new("localedef") - .args(["-i", "en_US", "-f", "UTF-8"]) - .arg(at.plus("en_US.UTF-8")) - .output() - .is_ok_and(|output| output.status.success()); - assert!( - compiled, - "localedef failed to compile the UTF-8 test locale" - ); - let locpath = at.as_string(); + let (locale, locpath) = locale_test_env(&at, "UTF-8", "en_US.UTF-8", "en_US.UTF-8"); + let mut cmd = new_ucmd!(); + if let Some(locpath) = locpath { + cmd.env("LOCPATH", locpath); + } // In UTF-8, high bytes are never class members, so -d [:alpha:] must not split é. - new_ucmd!() - .env("LOCPATH", &locpath) - .env("LC_ALL", "en_US.UTF-8") + cmd.env("LC_ALL", locale) .args(&["-d", "[:alpha:]"]) .pipe_in([b'a', 0xc3, 0xa9, b'b']) .succeeds() From bb70e37ab4040161408321d38256c8d9cd566739 Mon Sep 17 00:00:00 2001 From: Dikshant Neupane Date: Fri, 27 Nov 2026 18:01:47 +0000 Subject: [PATCH 3/7] tr: convert case classes through the current locale Translating between [:lower:] and [:upper:] now converts each character with tolower/toupper in the current locale, so unequal locale class sizes do not break translation. A set2 upper/lower class paired with the opposite-case class in set1 is replaced by the case conversion of that set1 class. --- src/uu/tr/src/operation.rs | 121 ++++++++++++++++++++++++++++++++----- tests/by-util/test_tr.rs | 73 +++++++++++++++++++++- 2 files changed, 176 insertions(+), 18 deletions(-) diff --git a/src/uu/tr/src/operation.rs b/src/uu/tr/src/operation.rs index cbbc60edc4a..9f122ac00a1 100644 --- a/src/uu/tr/src/operation.rs +++ b/src/uu/tr/src/operation.rs @@ -200,7 +200,7 @@ impl Error for SequenceError {} impl UError for SequenceError {} -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Class { Alnum, Alpha, @@ -216,6 +216,16 @@ pub enum Class { Xdigit, } +impl Class { + fn opposite_case(self) -> Self { + if self == Self::Upper { + Self::Lower + } else { + Self::Upper + } + } +} + #[derive(Debug, Clone, Copy)] pub enum Sequence { Char(u8), @@ -225,6 +235,8 @@ pub enum Sequence { CharStar(u8), CharRepeat(u8, usize), Class(Class), + /// The opposite class converted to this case, for a paired case class. + CaseConverted(Class), } /// Initialise the process locale from the environment, as `dd` does. @@ -269,6 +281,28 @@ fn locale_is_member(_class: Class, _byte: u8) -> bool { false } +/// Convert one byte to the given case in the current locale. +#[cfg(not(target_os = "wasi"))] +fn convert_case(c: u8, to: Class) -> u8 { + // SAFETY: tolower/toupper take a byte value or EOF. + let converted = unsafe { + match to { + Class::Upper => libc::toupper(i32::from(c)), + _ => libc::tolower(i32::from(c)), + } + }; + converted as u8 +} + +/// ASCII-only case conversion, for targets without a C library locale. +#[cfg(target_os = "wasi")] +fn convert_case(c: u8, to: Class) -> u8 { + match to { + Class::Upper => c.to_ascii_uppercase(), + _ => c.to_ascii_lowercase(), + } +} + /// All classes, in enum declaration order, so `Class as usize` indexes [`LocaleTables::members`]. const ALL_CLASSES: [Class; 12] = [ Class::Alnum, @@ -289,6 +323,9 @@ const ALL_CLASSES: [Class; 12] = [ pub(crate) struct LocaleTables { /// Full members (ASCII, then locale high bytes) for each class. members: [Vec; 12], + /// Each byte converted to upper/lower case in the current locale. + lower_to_upper: [u8; 256], + upper_to_lower: [u8; 256], } impl LocaleTables { @@ -307,12 +344,31 @@ impl LocaleTables { } members }); - Self { members } + let mut lower_to_upper = [0; 256]; + let mut upper_to_lower = [0; 256]; + for byte in 0..=255u8 { + lower_to_upper[byte as usize] = convert_case(byte, Class::Upper); + upper_to_lower[byte as usize] = convert_case(byte, Class::Lower); + } + Self { + members, + lower_to_upper, + upper_to_lower, + } } fn members(&self, class: Class) -> &[u8] { &self.members[class as usize] } + + /// Converts `c` to the target case of a `CaseConverted` sequence. + fn converted(&self, c: u8, to: Class) -> u8 { + if to == Class::Upper { + self.lower_to_upper[c as usize] + } else { + self.upper_to_lower[c as usize] + } + } } impl Class { @@ -366,6 +422,13 @@ impl Sequence { Self::CharStar(c) => Box::new(std::iter::repeat(*c)), Self::CharRepeat(c, n) => Box::new(std::iter::repeat_n(*c, *n)), Self::Class(class) => Box::new(tables.members(*class).iter().copied()), + Self::CaseConverted(to) => Box::new( + tables + .members(to.opposite_case()) + .iter() + .copied() + .map(move |c| tables.converted(c, *to)), + ), } } @@ -379,6 +442,7 @@ impl Sequence { Self::CharStar(_) => 0, Self::CharRepeat(_, n) => *n, Self::Class(_) => self.flatten(tables).count(), + Self::CaseConverted(to) => Self::Class(to.opposite_case()).expanded_len(tables), } } @@ -388,6 +452,16 @@ impl Sequence { set.iter().map(|s| s.expanded_len(tables) as u128).sum() } + /// The class in `set` starting at `prefix_len`, if any. + fn class_at(set: &[Self], prefix_len: u128, tables: &LocaleTables) -> Option { + set.iter().enumerate().find_map(|(pos, item)| match item { + Self::Class(class) if Self::expanded_len_of(&set[..pos], tables) == prefix_len => { + Some(*class) + } + _ => None, + }) + } + /// The characters of a set, in order, as runs of a repeated character. /// /// A `[c*n]` repeat is a single run however large `n` is; everything else @@ -531,6 +605,29 @@ impl Sequence { }) .collect(); + // A set2 case class paired with the opposite class in set1 becomes its case conversion. + if translating { + let mut converted_set2 = Vec::with_capacity(set2.len()); + let mut set2_prefix_len: u128 = 0; + for set2_item in set2 { + let mut replacement = None; + if let Self::Class(to) = set2_item + && matches!(to, Class::Upper | Class::Lower) + && Self::class_at(&set1, set2_prefix_len, &tables) == Some(to.opposite_case()) + { + replacement = Some(Self::CaseConverted(to)); + } + if let Some(converted) = replacement { + set2_prefix_len += converted.expanded_len(&tables) as u128; + converted_set2.push(converted); + } else { + set2_prefix_len += set2_item.expanded_len(&tables) as u128; + converted_set2.push(set2_item); + } + } + set2 = converted_set2; + } + // For every upper/lower in set2, there must be an upper/lower in set1 at the same position. The position is calculated by expanding everything before the upper/lower in both sets // This only applies when translating. With `-d -s`, set2 is only the set to squeeze. // With -c, set1 positions are those of the complement, so there is nothing to match. @@ -544,19 +641,11 @@ impl Sequence { continue; } - let mut class_matches = false; - for (set1_pos, set1_item) in set1.iter().enumerate() { - // only upper/lower can pair with upper/lower - if matches!(set1_item, Self::Class(Class::Upper | Class::Lower)) - && Self::expanded_len_of(&set1[..set1_pos], &tables) - == set2_part_solved_len - { - class_matches = true; - break; - } - } - - if !class_matches { + // only upper/lower can pair with upper/lower + if !matches!( + Self::class_at(&set1, set2_part_solved_len, &tables), + Some(Class::Upper | Class::Lower) + ) { return Err(SequenceError::whole_set( BadSequence::ClassInSet2NotMatchedBySet1, 2, @@ -595,7 +684,7 @@ impl Sequence { } else if translating && matches!( set2.last().copied(), - Some(Self::Class(Class::Upper | Class::Lower)) + Some(Self::Class(Class::Upper | Class::Lower) | Self::CaseConverted(_)) ) { return Err(SequenceError::whole_set( diff --git a/tests/by-util/test_tr.rs b/tests/by-util/test_tr.rs index b4d9bb33d23..490b0d3fe73 100644 --- a/tests/by-util/test_tr.rs +++ b/tests/by-util/test_tr.rs @@ -1612,6 +1612,65 @@ fn test_classes_follow_single_byte_locale() { .stdout_is_bytes(b"hello31m"); } +#[cfg(unix)] +#[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] +// Android and macOS ship no single-byte locale, so this test has nothing to run against there. +#[cfg(not(any(target_os = "macos", target_os = "android")))] +#[test] +fn test_case_folding_follows_single_byte_locale() { + let (at, _ucmd) = at_and_ucmd!(); + let (locale, locpath) = + locale_test_env(&at, "ISO-8859-1", "en_US.ISO-8859-1", "en_US.ISO8859-1"); + // In Latin-1, 0xE9 folds to 0xC9 and 0xC7 folds to 0xE7. + let mut cmd = new_ucmd!(); + if let Some(locpath) = &locpath { + cmd.env("LOCPATH", locpath); + } + cmd.env("LC_ALL", &locale) + .args(&["[:lower:]", "[:upper:]"]) + .pipe_in([b'a', 0xe9, b'b']) + .succeeds() + .stdout_is_bytes([b'A', 0xc9, b'B']); + let mut cmd = new_ucmd!(); + if let Some(locpath) = &locpath { + cmd.env("LOCPATH", locpath); + } + cmd.env("LC_ALL", &locale) + .args(&["[:upper:]", "[:lower:]"]) + .pipe_in([b'A', 0xc7, b'B']) + .succeeds() + .stdout_is_bytes([b'a', 0xe7, b'b']); + // Paired case classes must align by case, not by position: in Latin-1 + // [:lower:] has more members than [:upper:]. + let mut cmd = new_ucmd!(); + if let Some(locpath) = &locpath { + cmd.env("LOCPATH", locpath); + } + cmd.env("LC_ALL", &locale) + .args(&["ab[:lower:]", "0-1[:upper:]"]) + .pipe_in(b"abc.xyz") + .succeeds() + .stdout_is("ABC.XYZ"); + let mut cmd = new_ucmd!(); + if let Some(locpath) = &locpath { + cmd.env("LOCPATH", locpath); + } + cmd.env("LC_ALL", &locale) + .args(&["[:upper:]- ", "[:lower:]_"]) + .pipe_in(b"ABC- XYZ") + .succeeds() + .stdout_is("abc__xyz"); + let mut cmd = new_ucmd!(); + if let Some(locpath) = &locpath { + cmd.env("LOCPATH", locpath); + } + cmd.env("LC_ALL", &locale) + .args(&["-t", "[:lower:]a", "[:upper:]0"]) + .pipe_in(b"a") + .succeeds() + .stdout_is("0"); +} + #[cfg(unix)] #[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] #[test] @@ -1619,15 +1678,25 @@ fn test_classes_ignore_high_bytes_in_utf8_locale() { let (at, _ucmd) = at_and_ucmd!(); let (locale, locpath) = locale_test_env(&at, "UTF-8", "en_US.UTF-8", "en_US.UTF-8"); let mut cmd = new_ucmd!(); - if let Some(locpath) = locpath { + if let Some(locpath) = &locpath { cmd.env("LOCPATH", locpath); } // In UTF-8, high bytes are never class members, so -d [:alpha:] must not split é. - cmd.env("LC_ALL", locale) + cmd.env("LC_ALL", &locale) .args(&["-d", "[:alpha:]"]) .pipe_in([b'a', 0xc3, 0xa9, b'b']) .succeeds() .stdout_is_bytes([0xc3, 0xa9]); + // In UTF-8, case conversion only touches ASCII, so é is left alone. + let mut cmd = new_ucmd!(); + if let Some(locpath) = &locpath { + cmd.env("LOCPATH", locpath); + } + cmd.env("LC_ALL", &locale) + .args(&["[:lower:]", "[:upper:]"]) + .pipe_in([b'a', 0xc3, 0xa9, b'b']) + .succeeds() + .stdout_is_bytes([b'A', 0xc3, 0xa9, b'B']); } #[cfg(all(feature = "feat_diagnostics", not(wasi_runner)))] From 865b821a9e43bc46b207f8639bac6b13a6c36944 Mon Sep 17 00:00:00 2001 From: Dikshant Neupane Date: Fri, 27 Nov 2026 20:02:19 +0000 Subject: [PATCH 4/7] tr: skip Latin-1 class test on Android Bionic only knows the C and C.UTF-8 locales, so en_US.ISO8859-1 can never load there. --- tests/by-util/test_tr.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/by-util/test_tr.rs b/tests/by-util/test_tr.rs index 490b0d3fe73..a8c051b46fe 100644 --- a/tests/by-util/test_tr.rs +++ b/tests/by-util/test_tr.rs @@ -1593,8 +1593,8 @@ fn locale_test_env( #[cfg(unix)] #[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] -// macOS ships no single-byte locale, so this test has nothing to run against there. -#[cfg(not(target_os = "macos"))] +// macOS and Android ship no single-byte locale, so this test has nothing to run against there. +#[cfg(not(any(target_os = "macos", target_os = "android")))] #[test] fn test_classes_follow_single_byte_locale() { let (at, _ucmd) = at_and_ucmd!(); From 1df40e85dbe3a7b6ae50bd143a7b290436872aee Mon Sep 17 00:00:00 2001 From: Dikshant Neupane Date: Fri, 27 Nov 2026 20:43:48 +0000 Subject: [PATCH 5/7] tr: test [:alpha:] instead of [:cntrl:] in the single-byte locale test FreeBSD's Latin-1 cntrl class holds only C0 and DEL, so 0x9b is not a control character there and the test failed. 0xe9 is alpha in Latin-1 on both glibc and FreeBSD, and not in the C locale, so the test still fails loudly if the locale does not load. --- tests/by-util/test_tr.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/by-util/test_tr.rs b/tests/by-util/test_tr.rs index a8c051b46fe..05c67885051 100644 --- a/tests/by-util/test_tr.rs +++ b/tests/by-util/test_tr.rs @@ -1604,12 +1604,14 @@ fn test_classes_follow_single_byte_locale() { if let Some(locpath) = locpath { cmd.env("LOCPATH", locpath); } - // In Latin-1, 0x9b is a control character, so -d [:cntrl:] removes it. + // 0xe9 is alpha in Latin-1 but not in the C locale, so a failed locale + // load fails this test instead of passing silently. FreeBSD's Latin-1 + // [:cntrl:] holds no C1 controls, so 0x9b cannot be used here. cmd.env("LC_ALL", locale) - .args(&["-d", "[:cntrl:]"]) - .pipe_in([b'h', b'e', b'l', b'l', b'o', 0x9b, b'3', b'1', b'm']) + .args(&["-d", "[:alpha:]"]) + .pipe_in([b'h', b'e', b'l', b'l', b'o', 0xe9, b'3', b'1', b'm']) .succeeds() - .stdout_is_bytes(b"hello31m"); + .stdout_is_bytes(b"31"); } #[cfg(unix)] From b7cfba4423ad76c618c0e8cb2fd55edd81dfe2a6 Mon Sep 17 00:00:00 2001 From: Dikshant Neupane Date: Fri, 27 Nov 2026 22:35:26 +0000 Subject: [PATCH 6/7] tr: gate single-byte locale tests out on OpenBSD --- tests/by-util/test_tr.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/by-util/test_tr.rs b/tests/by-util/test_tr.rs index 05c67885051..7fad1833b78 100644 --- a/tests/by-util/test_tr.rs +++ b/tests/by-util/test_tr.rs @@ -1593,8 +1593,9 @@ fn locale_test_env( #[cfg(unix)] #[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] -// macOS and Android ship no single-byte locale, so this test has nothing to run against there. -#[cfg(not(any(target_os = "macos", target_os = "android")))] +// macOS, Android and OpenBSD ship no single-byte locale, so this test has +// nothing to run against there. +#[cfg(not(any(target_os = "macos", target_os = "android", target_os = "openbsd")))] #[test] fn test_classes_follow_single_byte_locale() { let (at, _ucmd) = at_and_ucmd!(); @@ -1616,8 +1617,9 @@ fn test_classes_follow_single_byte_locale() { #[cfg(unix)] #[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")] -// Android and macOS ship no single-byte locale, so this test has nothing to run against there. -#[cfg(not(any(target_os = "macos", target_os = "android")))] +// macOS, Android and OpenBSD ship no single-byte locale, so this test has +// nothing to run against there. +#[cfg(not(any(target_os = "macos", target_os = "android", target_os = "openbsd")))] #[test] fn test_case_folding_follows_single_byte_locale() { let (at, _ucmd) = at_and_ucmd!(); From 820eb8cb1ec1cabf35e9f811e6c92838a8d5c3aa Mon Sep 17 00:00:00 2001 From: Dikshant Neupane Date: Mon, 30 Nov 2026 10:24:14 +0000 Subject: [PATCH 7/7] tr: call setlocale once in uumain and simplify case conversion Move the setlocale call out of Sequence::solve_set_characters into uumain, so a parsing function no longer changes the process locale. Collapse the replacement option and the two branches in the case-conversion loop into a single let item. --- src/uu/tr/src/operation.rs | 24 ++++++++++-------------- src/uu/tr/src/tr.rs | 3 ++- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/uu/tr/src/operation.rs b/src/uu/tr/src/operation.rs index 9f122ac00a1..e289560bcbe 100644 --- a/src/uu/tr/src/operation.rs +++ b/src/uu/tr/src/operation.rs @@ -241,8 +241,9 @@ pub enum Sequence { /// Initialise the process locale from the environment, as `dd` does. /// Windows is excluded: setlocale selects the ANSI code page, classifying high bytes. +/// Called once from `uumain`; parsing functions must not change the process locale. #[cfg(not(any(target_os = "wasi", target_os = "windows")))] -fn init_locale() { +pub(crate) fn init_locale() { // SAFETY: setlocale is called with a valid C string, as in `dd`. unsafe { libc::setlocale(libc::LC_CTYPE, c"".as_ptr()); @@ -250,7 +251,7 @@ fn init_locale() { } #[cfg(any(target_os = "wasi", target_os = "windows"))] -fn init_locale() {} +pub(crate) fn init_locale() {} /// Whether a high byte belongs to a class in the current locale. /// Only asked about bytes 128 and above; ASCII is handled separately. @@ -525,8 +526,7 @@ impl Sequence { truncate_set1_flag: bool, translating: bool, ) -> Result<(Vec, Vec), SequenceError> { - // The class tables are built once here, after the locale is initialised. - init_locale(); + // The class tables are built once here; the locale was initialised in uumain. let tables = LocaleTables::build(); let is_char_star = |s: &&Self| -> bool { matches!(s, Self::CharStar(_)) }; @@ -610,20 +610,16 @@ impl Sequence { let mut converted_set2 = Vec::with_capacity(set2.len()); let mut set2_prefix_len: u128 = 0; for set2_item in set2 { - let mut replacement = None; - if let Self::Class(to) = set2_item + let item = if let Self::Class(to) = set2_item && matches!(to, Class::Upper | Class::Lower) && Self::class_at(&set1, set2_prefix_len, &tables) == Some(to.opposite_case()) { - replacement = Some(Self::CaseConverted(to)); - } - if let Some(converted) = replacement { - set2_prefix_len += converted.expanded_len(&tables) as u128; - converted_set2.push(converted); + Self::CaseConverted(to) } else { - set2_prefix_len += set2_item.expanded_len(&tables) as u128; - converted_set2.push(set2_item); - } + set2_item + }; + set2_prefix_len += item.expanded_len(&tables) as u128; + converted_set2.push(item); } set2 = converted_set2; } diff --git a/src/uu/tr/src/tr.rs b/src/uu/tr/src/tr.rs index 7b12d8c2678..4395548f267 100644 --- a/src/uu/tr/src/tr.rs +++ b/src/uu/tr/src/tr.rs @@ -11,7 +11,7 @@ mod unicode_table; use clap::{Arg, ArgAction, Command, value_parser}; use operation::{ DeleteOperation, Sequence, SqueezeOperation, SymbolTranslator, TranslateOperation, - flush_output, translate_input, + flush_output, init_locale, translate_input, }; use simd::process_input; use std::ffi::OsString; @@ -36,6 +36,7 @@ mod options { #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { + init_locale(); let args: Vec = args.collect(); // Kept for the caret in set diagnostics, which needs the sets as typed. let set_args = uucore::diagnostics::capture(&args);