Skip to content

Commit cf0f639

Browse files
tr: classify character classes by the current locale
Closes #15815
1 parent 32b2d60 commit cf0f639

4 files changed

Lines changed: 230 additions & 39 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/uu/tr/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ doctest = false
2020
bytecount = { workspace = true, features = ["runtime-dispatch-simd"] }
2121
clap = { workspace = true }
2222
fluent = { workspace = true }
23+
libc = { workspace = true }
2324
memchr = { workspace = true }
2425
nom = { workspace = true }
2526
uucore = { workspace = true, features = ["fs", "signals"] }

‎src/uu/tr/src/operation.rs‎

Lines changed: 186 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ impl Error for SequenceError {}
183183

184184
impl UError for SequenceError {}
185185

186-
#[derive(Debug, Clone, Copy)]
186+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187187
pub enum Class {
188188
Alnum,
189189
Alpha,
@@ -206,6 +206,131 @@ pub enum Sequence {
206206
CharStar(u8),
207207
CharRepeat(u8, usize),
208208
Class(Class),
209+
/// A set2 upper/lower class paired with an opposite-case class in set1.
210+
/// It expands to the case conversion of each member of the set1 class,
211+
/// so the two sides stay the same length even when the locale's classes
212+
/// have different sizes (for example Latin-1 has more lowercase than
213+
/// uppercase letters).
214+
CaseConverted {
215+
from: Class,
216+
to: Class,
217+
},
218+
}
219+
220+
/// Initialise the process locale from the environment, so the C library
221+
/// classification functions below see the locale the user asked for. This
222+
/// follows the pattern `dd` already uses for its case tables.
223+
#[cfg(not(target_os = "wasi"))]
224+
fn init_locale() {
225+
// SAFETY: setlocale is called with a valid C string, as in `dd`.
226+
unsafe {
227+
libc::setlocale(libc::LC_CTYPE, c"".as_ptr());
228+
}
229+
}
230+
231+
#[cfg(target_os = "wasi")]
232+
fn init_locale() {}
233+
234+
/// Whether a high byte belongs to a class in the current locale, using the
235+
/// C library classification functions. The ASCII members are handled
236+
/// separately, so this is only asked about bytes 128 and above. In the C
237+
/// and UTF-8 locales glibc puts no such byte in any class, so behaviour
238+
/// there is unchanged.
239+
#[cfg(not(target_os = "wasi"))]
240+
fn locale_is_member(class: Class, byte: u8) -> bool {
241+
// SAFETY: the is* functions are called with a byte value in range, as
242+
// `dd` calls tolower/toupper, and they only read process locale state.
243+
let result = unsafe {
244+
match class {
245+
Class::Alnum => libc::isalnum(i32::from(byte)),
246+
Class::Alpha => libc::isalpha(i32::from(byte)),
247+
Class::Blank => libc::isblank(i32::from(byte)),
248+
Class::Control => libc::iscntrl(i32::from(byte)),
249+
Class::Digit => libc::isdigit(i32::from(byte)),
250+
Class::Graph => libc::isgraph(i32::from(byte)),
251+
Class::Lower => libc::islower(i32::from(byte)),
252+
Class::Print => libc::isprint(i32::from(byte)),
253+
Class::Punct => libc::ispunct(i32::from(byte)),
254+
Class::Space => libc::isspace(i32::from(byte)),
255+
Class::Upper => libc::isupper(i32::from(byte)),
256+
Class::Xdigit => libc::isxdigit(i32::from(byte)),
257+
}
258+
};
259+
result != 0
260+
}
261+
262+
#[cfg(target_os = "wasi")]
263+
fn locale_is_member(_class: Class, _byte: u8) -> bool {
264+
false
265+
}
266+
267+
/// Convert one byte to the given case in the current locale, as `dd` does
268+
/// with tolower/toupper. Bytes with no counterpart in the locale map to
269+
/// themselves.
270+
#[cfg(not(target_os = "wasi"))]
271+
fn convert_case(byte: u8, to: Class) -> u8 {
272+
// SAFETY: tolower/toupper are called with a byte value in range.
273+
let converted = unsafe {
274+
match to {
275+
Class::Upper => libc::toupper(i32::from(byte)),
276+
_ => libc::tolower(i32::from(byte)),
277+
}
278+
};
279+
converted as u8
280+
}
281+
282+
#[cfg(target_os = "wasi")]
283+
fn convert_case(byte: u8, to: Class) -> u8 {
284+
match to {
285+
Class::Upper => byte.to_ascii_uppercase(),
286+
_ => byte.to_ascii_lowercase(),
287+
}
288+
}
289+
290+
impl Class {
291+
/// The class members that do not depend on the locale: the tables `tr`
292+
/// has always used, unchanged and in the same order.
293+
fn ascii_members(self) -> Box<dyn Iterator<Item = u8>> {
294+
match self {
295+
Self::Alnum => Box::new((b'0'..=b'9').chain(b'A'..=b'Z').chain(b'a'..=b'z')),
296+
Self::Alpha => Box::new((b'A'..=b'Z').chain(b'a'..=b'z')),
297+
Self::Blank => Box::new(unicode_table::BLANK.iter().copied()),
298+
Self::Control => Box::new((0..=31).chain(std::iter::once(127))),
299+
Self::Digit => Box::new(b'0'..=b'9'),
300+
Self::Graph => Box::new(
301+
(48..=57) // digit
302+
.chain(65..=90) // uppercase
303+
.chain(97..=122) // lowercase
304+
// punctuations
305+
.chain(33..=47)
306+
.chain(58..=64)
307+
.chain(91..=96)
308+
.chain(123..=126),
309+
),
310+
Self::Print => Box::new(
311+
(48..=57) // digit
312+
.chain(65..=90) // uppercase
313+
.chain(97..=122) // lowercase
314+
// punctuations
315+
.chain(33..=47)
316+
.chain(58..=64)
317+
.chain(91..=96)
318+
.chain(123..=126)
319+
.chain(std::iter::once(32)), // space
320+
),
321+
Self::Punct => Box::new((33..=47).chain(58..=64).chain(91..=96).chain(123..=126)),
322+
Self::Space => Box::new(unicode_table::SPACES.iter().copied()),
323+
Self::Xdigit => Box::new((b'0'..=b'9').chain(b'A'..=b'F').chain(b'a'..=b'f')),
324+
Self::Lower => Box::new(b'a'..=b'z'),
325+
Self::Upper => Box::new(b'A'..=b'Z'),
326+
}
327+
}
328+
329+
/// The class members above ASCII in the current locale, in byte order.
330+
fn locale_members(self) -> Box<dyn Iterator<Item = u8>> {
331+
let class = self;
332+
Box::new((128..=u8::MAX).filter(move |byte| locale_is_member(class, *byte)))
333+
}
209334
}
210335

211336
impl Sequence {
@@ -215,39 +340,15 @@ impl Sequence {
215340
Self::CharRange(l, r) => Box::new(*l..=*r),
216341
Self::CharStar(c) => Box::new(std::iter::repeat(*c)),
217342
Self::CharRepeat(c, n) => Box::new(std::iter::repeat_n(*c, *n)),
218-
Self::Class(class) => match class {
219-
Class::Alnum => Box::new((b'0'..=b'9').chain(b'A'..=b'Z').chain(b'a'..=b'z')),
220-
Class::Alpha => Box::new((b'A'..=b'Z').chain(b'a'..=b'z')),
221-
Class::Blank => Box::new(unicode_table::BLANK.iter().copied()),
222-
Class::Control => Box::new((0..=31).chain(std::iter::once(127))),
223-
Class::Digit => Box::new(b'0'..=b'9'),
224-
Class::Graph => Box::new(
225-
(48..=57) // digit
226-
.chain(65..=90) // uppercase
227-
.chain(97..=122) // lowercase
228-
// punctuations
229-
.chain(33..=47)
230-
.chain(58..=64)
231-
.chain(91..=96)
232-
.chain(123..=126),
233-
),
234-
Class::Print => Box::new(
235-
(48..=57) // digit
236-
.chain(65..=90) // uppercase
237-
.chain(97..=122) // lowercase
238-
// punctuations
239-
.chain(33..=47)
240-
.chain(58..=64)
241-
.chain(91..=96)
242-
.chain(123..=126)
243-
.chain(std::iter::once(32)), // space
244-
),
245-
Class::Punct => Box::new((33..=47).chain(58..=64).chain(91..=96).chain(123..=126)),
246-
Class::Space => Box::new(unicode_table::SPACES.iter().copied()),
247-
Class::Xdigit => Box::new((b'0'..=b'9').chain(b'A'..=b'F').chain(b'a'..=b'f')),
248-
Class::Lower => Box::new(b'a'..=b'z'),
249-
Class::Upper => Box::new(b'A'..=b'Z'),
250-
},
343+
Self::Class(class) => Box::new(class.ascii_members().chain(class.locale_members())),
344+
Self::CaseConverted { from, to } => {
345+
let to = *to;
346+
Box::new(
347+
from.ascii_members()
348+
.chain(from.locale_members())
349+
.map(move |byte| convert_case(byte, to)),
350+
)
351+
}
251352
}
252353
}
253354

@@ -260,7 +361,7 @@ impl Sequence {
260361
// A star is only sized once it has been turned into a repeat.
261362
Self::CharStar(_) => 0,
262363
Self::CharRepeat(_, n) => *n,
263-
Self::Class(_) => self.flatten().count(),
364+
Self::Class(_) | Self::CaseConverted { .. } => self.flatten().count(),
264365
}
265366
}
266367

@@ -326,6 +427,10 @@ impl Sequence {
326427
truncate_set1_flag: bool,
327428
translating: bool,
328429
) -> Result<(Vec<u8>, Vec<u8>), SequenceError> {
430+
// Class membership for high bytes comes from the C library, so the
431+
// locale has to be initialised before any class is expanded.
432+
init_locale();
433+
329434
let is_char_star = |s: &&Self| -> bool { matches!(s, Self::CharStar(_)) };
330435

331436
let set1 = Self::parse_set(set1_str).map_err(|(error, span)| SequenceError {
@@ -387,6 +492,46 @@ impl Sequence {
387492
})
388493
.collect();
389494

495+
// When translating, a set2 upper/lower class matched by the opposite
496+
// case class in set1 at the same position is replaced by the case
497+
// conversion of that set1 class. Position is tracked on the
498+
// converted lengths, so anything after the class still pairs by
499+
// position. A converted class is not a class for the checks below.
500+
if translating {
501+
let mut converted_set2 = Vec::with_capacity(set2.len());
502+
let mut set2_prefix_len: u128 = 0;
503+
for set2_item in set2 {
504+
let mut replacement = None;
505+
if let Self::Class(to) = set2_item
506+
&& matches!(to, Class::Upper | Class::Lower)
507+
{
508+
let wanted_from = match to {
509+
Class::Upper => Class::Lower,
510+
_ => Class::Upper,
511+
};
512+
for (set1_pos, set1_item) in set1.iter().enumerate() {
513+
if matches!(set1_item, Self::Class(from) if *from == wanted_from)
514+
&& Self::expanded_len_of(&set1[..set1_pos]) == set2_prefix_len
515+
{
516+
replacement = Some(Self::CaseConverted {
517+
from: wanted_from,
518+
to,
519+
});
520+
break;
521+
}
522+
}
523+
}
524+
if let Some(converted) = replacement {
525+
set2_prefix_len += converted.expanded_len() as u128;
526+
converted_set2.push(converted);
527+
} else {
528+
set2_prefix_len += set2_item.expanded_len() as u128;
529+
converted_set2.push(set2_item);
530+
}
531+
}
532+
set2 = converted_set2;
533+
}
534+
390535
// 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
391536
// This only applies when translating. With `-d -s`, set2 is only the set to squeeze.
392537
for (set2_pos, set2_item) in set2.iter().enumerate() {
@@ -452,10 +597,12 @@ impl Sequence {
452597
}
453598
}
454599
// Otherwise set1 is cut to the length of set2 while pairing below.
455-
} else if matches!(
456-
set2.last().copied(),
457-
Some(Self::Class(Class::Upper | Class::Lower))
458-
) {
600+
} else if translating
601+
&& matches!(
602+
set2.last().copied(),
603+
Some(Self::Class(Class::Upper | Class::Lower) | Self::CaseConverted { .. })
604+
)
605+
{
459606
return Err(SequenceError::whole_set(
460607
BadSequence::Set1LongerSet2EndsInClass,
461608
1,

‎tests/by-util/test_tr.rs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1393,6 +1393,48 @@ fn test_stdin_is_socket() {
13931393
.stdout_is(";;");
13941394
}
13951395

1396+
#[cfg(unix)]
1397+
#[cfg_attr(wasi_runner, ignore = "WASI: the guest does not inherit LC_ALL")]
1398+
#[test]
1399+
fn test_classes_follow_single_byte_locale() {
1400+
// Compile a Latin-1 locale into a scratch directory; return early if
1401+
// localedef is unavailable, so the test never fails for a missing tool.
1402+
let locale_dir = std::env::temp_dir().join(format!("uutils-tr-locale-{}", std::process::id()));
1403+
let compiled = std::process::Command::new("localedef")
1404+
.args(["-i", "en_US", "-f", "ISO-8859-1"])
1405+
.arg(locale_dir.join("en_US.ISO-8859-1"))
1406+
.output()
1407+
.is_ok_and(|output| output.status.success());
1408+
if !compiled {
1409+
return;
1410+
}
1411+
let locale_dir = locale_dir.to_string_lossy().into_owned();
1412+
// In Latin-1, 0x9b is a control character, so deleting [:cntrl:]
1413+
// removes it; under C it is kept, as the existing tests show.
1414+
new_ucmd!()
1415+
.env("LOCPATH", &locale_dir)
1416+
.env("LC_ALL", "en_US.ISO-8859-1")
1417+
.args(&["-d", "[:cntrl:]"])
1418+
.pipe_in([b'h', b'e', b'l', b'l', b'o', 0x9b, b'3', b'1', b'm'])
1419+
.succeeds()
1420+
.stdout_is_bytes(b"hello31m");
1421+
// Case folding follows the locale too: 0xe9 uppercases to 0xc9.
1422+
new_ucmd!()
1423+
.env("LOCPATH", &locale_dir)
1424+
.env("LC_ALL", "en_US.ISO-8859-1")
1425+
.args(&["[:lower:]", "[:upper:]"])
1426+
.pipe_in([0xe9, b'a'])
1427+
.succeeds()
1428+
.stdout_is_bytes([0xc9, b'A']);
1429+
new_ucmd!()
1430+
.env("LOCPATH", &locale_dir)
1431+
.env("LC_ALL", "en_US.ISO-8859-1")
1432+
.args(&["[:upper:]", "[:lower:]"])
1433+
.pipe_in([0xc9, b'A'])
1434+
.succeeds()
1435+
.stdout_is_bytes([0xe9, b'a']);
1436+
}
1437+
13961438
#[cfg(all(feature = "feat_diagnostics", not(wasi_runner)))]
13971439
mod diagnostics {
13981440
use super::*;

0 commit comments

Comments
 (0)