Skip to content

Commit d9669b2

Browse files
committed
fix(word): seven faults from the review of #242, with regression tests
- parser: the statement splitters walk bytes and looped for ever on an unquoted non-ASCII letter (`echo é` hung); only an ASCII letter can start a keyword. - glob: brace expansion used character counts as byte offsets and panicked on `'é'{a,b}`. - parser: ${...} parsing sliced at character counts; it now uses byte offsets (${é}, ${é:-x}). - parser: ${X:2:N} with a huge N overflowed; the end is now saturating. - parser: a quoted or escaped parenthesis no longer ends $(...). - word: a quoted hyphen inside [...] is written last in the class, where it cannot form a range; quoted *, ? and [ stay bare inside a class. - word: a tilde whose prefix has a quoted piece is not expanded. - word, parser: an unbraced parameter followed by a literal is written back with braces, so an AND-OR list reads $A''b as ${A}b, not $Ab. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0136P7ZnLF9EM2PnNxFaCFov
1 parent 093e86a commit d9669b2

5 files changed

Lines changed: 264 additions & 52 deletions

File tree

‎CHANGELOG.adoc‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2727
- An expansion error (such as a glob limit from #191) fails the command with
2828
exit status 1 and does not run it. With a redirection the status was 127.
2929

30+
=== Fixed — 2026-11-18 (review of #242)
31+
32+
- An unquoted non-ASCII letter no longer hangs the shell: `echo é` did not
33+
return, because the statement splitter did not advance past it.
34+
- `'é'{a,b}` and `${é:-x}` no longer panic or misread the word: brace and
35+
parameter expansion used character counts as byte offsets.
36+
- `${X:2:N}` with a very large `N` gives the rest of the value; it panicked
37+
on overflow.
38+
- A quoted or escaped parenthesis no longer ends a command substitution:
39+
`$(echo ')')`.
40+
- A quoted hyphen in a bracket expression is a member, not a range:
41+
`[a'-'z]*.txt` no longer matches `m.txt`.
42+
- `~'local'/x` keeps its tilde: a quoted piece in the tilde prefix stops
43+
the expansion.
44+
- `$A''suffix && true` expands `A`: in an AND-OR list the word was read
45+
back as `$Asuffix`.
46+
3047
=== Changed — 2026-11-18 (typed words)
3148

3249
- New module `src/word.rs`: a `Word` keeps the quoting of each of its pieces

‎impl/rust-cli/src/glob.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -728,7 +728,8 @@ fn expand_braces_limited(pattern: &str, remaining: usize) -> Vec<String> {
728728
}
729729

730730
// Find first unescaped {
731-
let chars = pattern.chars().enumerate().peekable();
731+
// Byte offsets, not character counts: the slices below index bytes.
732+
let chars = pattern.char_indices();
732733
let mut brace_start = None;
733734
let mut brace_depth = 0;
734735
let mut escaped = false;

‎impl/rust-cli/src/parser.rs‎

Lines changed: 54 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -960,9 +960,31 @@ fn parse_variable(
960960
fn parse_command_sub_dollar(chars: &mut std::iter::Peekable<std::str::Chars>) -> Result<String> {
961961
let mut cmd = String::new();
962962
let mut depth = 1; // Parenthesis depth: nested $(), $((expr)) and (...)
963+
// A parenthesis that is quoted or escaped is text, not nesting.
964+
let mut single = false;
965+
let mut double = false;
966+
let mut escaped = false;
963967

964968
for ch in chars.by_ref() {
969+
if escaped {
970+
escaped = false;
971+
cmd.push(ch);
972+
continue;
973+
}
965974
match ch {
975+
'\\' if !single => {
976+
escaped = true;
977+
cmd.push(ch);
978+
}
979+
'\'' if !double => {
980+
single = !single;
981+
cmd.push(ch);
982+
}
983+
'"' if !single => {
984+
double = !double;
985+
cmd.push(ch);
986+
}
987+
_ if single || double => cmd.push(ch),
966988
'(' => {
967989
// Every `(` nests, so the `)` that closes `$((1+2))` or
968990
// `$(echo $(pwd))` belongs to the substitution.
@@ -1556,7 +1578,7 @@ fn split_on_top_level(input: &str, split_on_newline: bool) -> Vec<&str> {
15561578
}
15571579
_ if !in_single_quote && !in_double_quote && paren_depth == 0
15581580
// Check for keyword at word boundary
1559-
&& (ch.is_alphabetic() || ch == '_') =>
1581+
&& (ch.is_ascii_alphabetic() || ch == '_') =>
15601582
{
15611583
let word_start = i;
15621584
while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
@@ -2139,12 +2161,12 @@ fn parse_parameter_expansion(content: &str) -> Result<ParameterExpansion, String
21392161
return Err("Empty parameter expansion".to_string());
21402162
}
21412163

2142-
let chars: Vec<char> = content.chars().collect();
2143-
#[allow(unused_assignments)]
2144-
let mut pos = 0;
2164+
// Offsets are bytes. Every operator is one ASCII byte, so a `+ 1` step
2165+
// stays on a character boundary whatever the name contains.
2166+
let bytes = content.as_bytes();
21452167

21462168
// Check for length operator: ${#VAR}
2147-
if chars[0] == '#' {
2169+
if bytes[0] == b'#' {
21482170
let var_name = content[1..].to_string();
21492171
return Ok(ParameterExpansion {
21502172
var_name,
@@ -2153,28 +2175,27 @@ fn parse_parameter_expansion(content: &str) -> Result<ParameterExpansion, String
21532175
}
21542176

21552177
// Extract variable name (until operator or end)
2156-
let var_name_end = chars
2157-
.iter()
2158-
.position(|&c| matches!(c, ':' | '-' | '=' | '+' | '?'))
2159-
.unwrap_or(chars.len());
2178+
let var_name_end = content
2179+
.find([':', '-', '=', '+', '?'])
2180+
.unwrap_or(content.len());
21602181

21612182
let var_name = content[..var_name_end].to_string();
21622183

21632184
// If no operator, simple expansion
2164-
if var_name_end == chars.len() {
2185+
if var_name_end == content.len() {
21652186
return Ok(ParameterExpansion {
21662187
var_name,
21672188
operation: ExpansionOp::Simple,
21682189
});
21692190
}
21702191

2171-
pos = var_name_end;
2172-
let check_null = chars[pos] == ':';
2192+
let mut pos = var_name_end;
2193+
let check_null = bytes[pos] == b':';
21732194
if check_null {
21742195
pos += 1; // Skip ':'
21752196
}
21762197

2177-
if pos >= chars.len() {
2198+
if pos >= content.len() {
21782199
// ${VAR:} with nothing after - try substring with offset 0
21792200
return Ok(ParameterExpansion {
21802201
var_name,
@@ -2185,8 +2206,10 @@ fn parse_parameter_expansion(content: &str) -> Result<ParameterExpansion, String
21852206
});
21862207
}
21872208

2188-
let op_char = chars[pos];
2189-
let rest = &content[pos + 1..];
2209+
let Some(op_char) = content[pos..].chars().next() else {
2210+
return Err("Empty parameter expansion".to_string());
2211+
};
2212+
let rest = &content[pos + op_char.len_utf8()..];
21902213

21912214
// Disambiguate operators from substring syntax
21922215
// - ${VAR-X}, ${VAR:-X} → Default operator (dash immediately after var or colon)
@@ -2378,7 +2401,7 @@ fn apply_substring(value: &str, offset: i32, length: Option<usize>) -> String {
23782401

23792402
match length {
23802403
Some(n) => {
2381-
let end = (start + n).min(chars.len());
2404+
let end = start.saturating_add(n).min(chars.len());
23822405
chars[start..end].iter().collect()
23832406
}
23842407
None => chars[start..].iter().collect(),
@@ -2574,31 +2597,13 @@ fn quoted_word_to_string(word: &QuotedWord) -> String {
25742597
result.push_str(s);
25752598
}
25762599
}
2577-
WordPart::Variable(name) => {
2578-
// This shouldn't happen in single quotes (tokenizer prevents it)
2579-
// but handle it anyway
2580-
if word.quote_type != QuoteType::Single {
2581-
result.push('$');
2582-
result.push_str(name);
2583-
} else {
2584-
// In single quotes, escape the $
2585-
result.push('\\');
2586-
result.push('$');
2587-
result.push_str(name);
2588-
}
2589-
}
2590-
WordPart::BracedVariable(name) => {
2591-
// This shouldn't happen in single quotes
2592-
if word.quote_type != QuoteType::Single {
2593-
result.push_str("${");
2594-
result.push_str(name);
2595-
result.push('}');
2596-
} else {
2597-
// In single quotes, escape the $
2598-
result.push_str("\\${");
2599-
result.push_str(name);
2600-
result.push('}');
2601-
}
2600+
// The tokenizer makes a variable part only outside single quotes,
2601+
// so it is always an expansion, whatever quotes follow in the word.
2602+
// Braces keep a following literal out of the name (`$A''b`).
2603+
WordPart::Variable(name) | WordPart::BracedVariable(name) => {
2604+
result.push_str("${");
2605+
result.push_str(name);
2606+
result.push('}');
26022607
}
26032608
WordPart::CommandSub(cmd) => {
26042609
// Command substitution - keep as-is for now
@@ -2856,7 +2861,10 @@ fn split_control_keywords<'a>(input: &'a str, keywords: &[&str]) -> Vec<(&'a str
28562861
in_double_quote = !in_double_quote;
28572862
i += 1;
28582863
}
2859-
_ if !in_single_quote && !in_double_quote && (ch.is_alphabetic() || ch == '_') => {
2864+
_ if !in_single_quote
2865+
&& !in_double_quote
2866+
&& (ch.is_ascii_alphabetic() || ch == '_') =>
2867+
{
28602868
let word_start = i;
28612869
while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
28622870
i += 1;
@@ -3260,7 +3268,10 @@ pub fn is_incomplete_control_structure(input: &str) -> bool {
32603268
in_double_quote = !in_double_quote;
32613269
i += 1;
32623270
}
3263-
_ if !in_single_quote && !in_double_quote && (ch.is_alphabetic() || ch == '_') => {
3271+
_ if !in_single_quote
3272+
&& !in_double_quote
3273+
&& (ch.is_ascii_alphabetic() || ch == '_') =>
3274+
{
32643275
let word_start = i;
32653276
while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
32663277
i += 1;

‎impl/rust-cli/src/word.rs‎

Lines changed: 115 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ fn fmt_literal(f: &mut fmt::Formatter<'_>, text: &str, quote: Quote) -> fmt::Res
198198
/// Writes the word back as shell source that parses to the same word.
199199
impl fmt::Display for Word {
200200
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201-
for segment in &self.segments {
201+
for (index, segment) in self.segments.iter().enumerate() {
202202
match segment {
203203
Segment::Literal { text, quote } => fmt_literal(f, text, *quote)?,
204204
Segment::Parameter {
@@ -207,7 +207,13 @@ impl fmt::Display for Word {
207207
quote,
208208
} => {
209209
let open = if quote.is_quoted() { "\"" } else { "" };
210-
if *braced {
210+
// `$A''b` must not come back as `$Ab`: brace the name when
211+
// the text after it could continue it.
212+
let runs_on = self.segments.get(index + 1).is_some_and(|next| {
213+
matches!(next, Segment::Literal { text, quote: Quote::None }
214+
if text.starts_with(|c: char| c.is_alphanumeric() || c == '_'))
215+
}) && expr.starts_with(|c: char| c.is_alphabetic() || c == '_');
216+
if *braced || runs_on {
211217
write!(f, "{open}${{{expr}}}{open}")?;
212218
} else {
213219
write!(f, "{open}${expr}{open}")?;
@@ -339,7 +345,14 @@ fn expand_segments(
339345
match segment {
340346
Segment::Literal { text, quote } => {
341347
if !quote.is_quoted() {
342-
if index == 0 && text.starts_with('~') {
348+
// The tilde prefix runs to the first unquoted `/`. It ends in this
349+
// segment only if the segment has a `/` or is the whole word;
350+
// otherwise a quoted piece or an expansion is part of the
351+
// prefix, and the tilde stays literal (`~'local'/x`).
352+
if index == 0
353+
&& text.starts_with('~')
354+
&& (text.contains('/') || word.segments.len() == 1)
355+
{
343356
let (prefix, rest) = text.split_at(text.find('/').unwrap_or(text.len()));
344357
let expanded = crate::parser::expand_tilde(prefix);
345358
if expanded != prefix {
@@ -463,16 +476,46 @@ fn glob_fields(
463476
fn glob_pattern(encoded: &str) -> Option<String> {
464477
let mut pattern = String::with_capacity(encoded.len());
465478
let mut active = false;
479+
// Inside an unquoted `[...]`: how many members so far, and whether a
480+
// quoted `-` waits to be written last, where it cannot form a range.
481+
let mut class: Option<usize> = None;
482+
let mut hyphen = false;
466483
let mut chars = encoded.chars();
467484
while let Some(ch) = chars.next() {
468485
if ch == '\\' {
469-
if let Some(next) = chars.next() {
470-
pattern.push_str(&::glob::Pattern::escape(&next.to_string()));
486+
let Some(next) = chars.next() else { continue };
487+
match (class.as_mut(), next) {
488+
(Some(_), '-') => hyphen = true,
489+
// `*`, `?` and `[` are already literal inside a class.
490+
(Some(members), '*' | '?' | '[') => {
491+
*members += 1;
492+
pattern.push(next);
493+
}
494+
(members, _) => {
495+
if let Some(members) = members {
496+
*members += 1;
497+
}
498+
pattern.push_str(&::glob::Pattern::escape(&next.to_string()));
499+
}
471500
}
472-
} else {
473-
active |= matches!(ch, '*' | '?' | '[');
474-
pattern.push(ch);
501+
continue;
475502
}
503+
active |= matches!(ch, '*' | '?' | '[');
504+
match class.as_mut() {
505+
None if ch == '[' => class = Some(0),
506+
None => {}
507+
// `]` first in a class (after `!` or `^`) is a member, not the end.
508+
Some(members) if ch == ']' && *members > 0 => {
509+
if std::mem::take(&mut hyphen) {
510+
pattern.push('-');
511+
}
512+
class = None;
513+
}
514+
Some(members) if *members == 0 && matches!(ch, '!' | '^') && pattern.ends_with('[') => {
515+
}
516+
Some(members) => *members += 1,
517+
}
518+
pattern.push(ch);
476519
}
477520
active.then_some(pattern)
478521
}
@@ -702,6 +745,70 @@ mod tests {
702745
assert_eq!(Word::literal("plain"), "plain");
703746
}
704747

748+
#[test]
749+
fn display_keeps_a_literal_out_of_an_unbraced_name() {
750+
let mut w = Word::new();
751+
w.push_parameter("A".to_string(), false, Quote::None);
752+
w.push_str("suffix", Quote::None);
753+
assert_eq!(w.to_string(), "${A}suffix");
754+
755+
std::env::remove_var("Asuffix");
756+
let dir = fixture(&[]);
757+
let mut state = ShellState::new(dir.path().to_str().unwrap()).unwrap();
758+
state.set_variable("A", "x");
759+
let out = expand_words_in(
760+
&[w],
761+
&mut state,
762+
ProcessSubs::Refuse,
763+
dir.path(),
764+
&GlobLimits::DEFAULT,
765+
)
766+
.unwrap();
767+
assert_eq!(out.fields, ["xsuffix"]);
768+
}
769+
770+
#[test]
771+
fn a_quoted_hyphen_in_a_bracket_is_not_a_range() {
772+
// [a'-'z]*.txt
773+
assert_eq!(glob_pattern("[a\\-z]*.txt"), Some("[az-]*.txt".to_string()));
774+
let dir = fixture(&["-.txt", "a.txt", "m.txt", "z.txt"]);
775+
let w = word(&[
776+
("[a", Quote::None),
777+
("-", Quote::Single),
778+
("z]*.txt", Quote::None),
779+
]);
780+
assert_eq!(expand_in(dir.path(), &[w]), ["-.txt", "a.txt", "z.txt"]);
781+
}
782+
783+
#[test]
784+
fn a_tilde_with_a_quoted_prefix_is_not_expanded() {
785+
let dir = fixture(&[]);
786+
let quoted = word(&[
787+
("~", Quote::None),
788+
("local", Quote::Single),
789+
("/x", Quote::None),
790+
]);
791+
assert_eq!(expand_in(dir.path(), &[quoted]), ["~local/x"]);
792+
// An unquoted slash ends the prefix, so this one still expands.
793+
let slash = word(&[
794+
("~/", Quote::None),
795+
("local", Quote::Single),
796+
("/x", Quote::None),
797+
]);
798+
let got = expand_in(dir.path(), &[slash]);
799+
assert!(
800+
got[0].ends_with("/local/x") && !got[0].starts_with('~'),
801+
"{got:?}"
802+
);
803+
}
804+
805+
#[test]
806+
fn a_non_ascii_character_before_a_brace_does_not_panic() {
807+
let dir = fixture(&[]);
808+
let w = word(&[("é", Quote::Single), ("{a,b}", Quote::None)]);
809+
assert_eq!(expand_in(dir.path(), &[w]), ["éa", "éb"]);
810+
}
811+
705812
#[test]
706813
fn glob_pattern_escapes_quoted_metacharacters() {
707814
assert_eq!(glob_pattern("\\*a*"), Some("[*]a*".to_string()));

0 commit comments

Comments
 (0)