1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
use crate::error::{RableError, Result};
use crate::token::{Token, TokenType};
use super::Lexer;
use super::word_builder::{WordBuilder, WordSpanKind};
impl Lexer {
/// Reads a word token, handling quoting and expansions.
#[allow(clippy::too_many_lines)]
pub(super) fn read_word_token(&mut self, start: usize, line: usize) -> Result<Token> {
let mut wb = WordBuilder::new();
while let Some(c) = self.peek_char() {
match c {
// Metacharacters end a word
' ' | '\t' | '\n' | '|' | '&' | ';' | ')' => break,
// < and > are metacharacters, but <( and >( are process substitution
'<' | '>' => {
if !wb.is_empty() && self.input.get(self.pos + 1) == Some(&'(') {
// Process substitution mid-word: cat<(cmd)
self.read_process_sub_into(&mut wb)?;
} else {
break;
}
}
// ( is a metacharacter UNLESS preceded by = (array) or extglob prefix
'(' => {
if wb.ends_with('=') {
// Array assignment: arr=(...) — parse elements directly
self.advance_char();
wb.push('(');
self.read_array_elements(&mut wb)?;
} else if wb.ends_with('@')
|| wb.ends_with('?')
|| wb.ends_with('+')
|| (wb.ends_with('!') && self.config.extglob)
|| (wb.ends_with('*') && self.config.extglob)
{
// Extglob: @(...), ?(...), etc.
self.advance_char();
wb.push('(');
self.read_matched_parens(&mut wb, 1)?;
} else {
break;
}
}
'\'' | '"' | '\\' | '$' | '`' => {
self.read_word_special(&mut wb, c)?;
}
// Extglob: @(...), ?(...), +(...), !(...)
// !( is only extglob when extglob is enabled; otherwise ! is Bang
'@' | '?' | '+' if self.input.get(self.pos + 1) == Some(&'(') => {
self.read_extglob(&mut wb, c)?;
}
// !( and *( are only extglob when extglob mode is enabled
'!' | '*' if self.input.get(self.pos + 1) == Some(&'(') && self.config.extglob => {
self.read_extglob(&mut wb, c)?;
}
// `[` inside a word starts a subscript/bracket context
'[' if !wb.is_empty() && wb.value != "[" && !wb.ends_with('[') => {
self.read_bracket_subscript(&mut wb)?;
}
// Regular character
_ => {
self.advance_char();
wb.push(c);
}
}
}
if wb.is_empty() {
return Err(RableError::parse("unexpected character", start, line));
}
// Check for reserved words at command start, then assignment pattern
let kind = if self.ctx.command_start {
TokenType::reserved_word(&wb.value).unwrap_or_else(|| {
if is_assignment_word(&wb.value) {
TokenType::AssignmentWord
} else {
TokenType::Word
}
})
} else if is_assignment_word(&wb.value) {
TokenType::AssignmentWord
} else {
TokenType::Word
};
// After a word, we're no longer at command start (unless it's a keyword
// that expects another command, or it's an assignment)
self.ctx.command_start = kind.starts_command()
|| kind == TokenType::AssignmentWord
|| matches!(
kind,
TokenType::Then
| TokenType::Else
| TokenType::Elif
| TokenType::Do
| TokenType::Semi
);
Ok(Token::with_spans(kind, wb.value, start, line, wb.spans))
}
/// Reads a quoted string, escape, dollar expansion, or backtick within a word.
pub(super) fn read_word_special(&mut self, wb: &mut WordBuilder, c: char) -> Result<()> {
match c {
'\'' => {
let start = wb.span_start();
self.advance_char();
wb.push('\'');
self.read_single_quoted(wb)?;
wb.record(start, WordSpanKind::SingleQuoted);
}
'"' => {
let start = wb.span_start();
self.advance_char();
wb.push('"');
self.read_double_quoted(wb)?;
wb.record(start, WordSpanKind::DoubleQuoted);
}
'\\' => {
self.advance_char();
if self.peek_char() == Some('\n') {
self.advance_char(); // line continuation — no span
} else {
let start = wb.span_start();
wb.push('\\');
if let Some(next) = self.advance_char() {
wb.push(next);
} else {
// Trailing \ at EOF — bash keeps it as literal \\
wb.push('\\');
}
wb.record(start, WordSpanKind::Escape);
}
}
'$' => {
self.read_dollar(wb)?;
}
'`' => {
let start = wb.span_start();
self.advance_char();
wb.push('`');
self.read_backtick(wb)?;
wb.record(start, WordSpanKind::Backtick);
}
_ => {}
}
Ok(())
}
/// Reads an extglob pattern `@(...)`, `?(...)`, etc.
pub(super) fn read_extglob(&mut self, wb: &mut WordBuilder, prefix: char) -> Result<()> {
let start = wb.span_start();
self.advance_char();
wb.push(prefix);
self.advance_char();
wb.push('(');
self.read_matched_parens(wb, 1)?;
wb.record(start, WordSpanKind::Extglob(prefix));
Ok(())
}
/// Reads a bracket subscript `[...]` inside a word.
pub(super) fn read_bracket_subscript(&mut self, wb: &mut WordBuilder) -> Result<()> {
let start = wb.span_start();
self.advance_char(); // consume [
wb.push('[');
let mut depth = 1;
while let Some(c) = self.peek_char() {
match c {
'[' => {
depth += 1;
self.advance_char();
wb.push(c);
}
']' => {
depth -= 1;
self.advance_char();
wb.push(c);
if depth == 0 {
wb.record(start, WordSpanKind::BracketSubscript);
return Ok(());
}
}
'\'' => {
self.advance_char();
wb.push('\'');
self.read_single_quoted(wb)?;
}
'"' => {
self.advance_char();
wb.push('"');
self.read_double_quoted(wb)?;
}
'\\' => {
self.advance_char();
wb.push('\\');
if let Some(nc) = self.advance_char() {
wb.push(nc);
}
}
'$' => {
self.read_dollar(wb)?;
}
_ => {
self.advance_char();
wb.push(c);
}
}
}
Ok(())
}
/// Reads a process substitution into an existing word value.
pub(super) fn read_process_sub_into(&mut self, wb: &mut WordBuilder) -> Result<()> {
let start = wb.span_start();
let dir = self.advance_char().unwrap_or('<');
wb.push(dir);
self.advance_char(); // (
wb.push('(');
self.read_matched_parens(wb, 1)?;
wb.record(start, WordSpanKind::ProcessSub(dir));
Ok(())
}
/// Reads a process substitution `<(...)` or `>(...)` as a word token.
/// Continues reading word characters after the closing `)`.
pub(super) fn read_process_sub_word(&mut self, start: usize, line: usize) -> Result<Token> {
let mut wb = WordBuilder::new();
let span_start = wb.span_start();
// Read < or >
let dir = self.advance_char().unwrap_or('<');
wb.push(dir);
// Read (
self.advance_char();
wb.push('(');
// Read until matching )
self.read_matched_parens(&mut wb, 1)?;
wb.record(span_start, WordSpanKind::ProcessSub(dir));
// Continue reading word chars after the process substitution
self.continue_word(&mut wb)?;
self.ctx.command_start = false;
Ok(Token::with_spans(
TokenType::Word,
wb.value,
start,
line,
wb.spans,
))
}
/// Continue reading word characters after a special construct.
fn continue_word(&mut self, wb: &mut WordBuilder) -> Result<()> {
while let Some(c) = self.peek_char() {
match c {
' ' | '\t' | '\n' | '|' | '&' | ';' | ')' | '(' => break,
'<' | '>' => {
if self.input.get(self.pos + 1) == Some(&'(') {
self.read_process_sub_into(wb)?;
} else {
break;
}
}
'\'' | '"' | '\\' | '$' | '`' => {
self.read_word_special(wb, c)?;
}
'[' if !wb.is_empty() && wb.value != "[" && !wb.ends_with('[') => {
self.read_bracket_subscript(wb)?;
}
_ => {
self.advance_char();
wb.push(c);
}
}
}
Ok(())
}
/// Reads array elements from `(...)`, producing normalized content.
///
/// Parses individual elements separated by whitespace directly from
/// the input stream, stripping comments. Uses the lexer's existing
/// word-reading facilities for quoting and expansion handling.
/// The opening `(` must already be consumed and pushed to `wb`.
fn read_array_elements(&mut self, wb: &mut WordBuilder) -> Result<()> {
let mut need_space = false;
loop {
// Skip whitespace between elements
while matches!(self.peek_char(), Some(' ' | '\t' | '\n' | '\r')) {
self.advance_char();
}
match self.peek_char() {
Some(')') => {
self.advance_char();
wb.push(')');
return Ok(());
}
Some('#') => {
// Comment — skip to end of line
while matches!(self.peek_char(), Some(c) if c != '\n') {
self.advance_char();
}
}
Some(_) => {
if need_space {
wb.push(' ');
}
self.read_array_element(wb)?;
need_space = true;
}
None => {
return Err(RableError::matched_pair(
"unterminated array",
self.pos,
self.line,
));
}
}
}
}
/// Reads a single array element using the same word-reading logic
/// as `read_word_token`, but with `)` and whitespace as terminators
/// instead of the standard shell metacharacters.
fn read_array_element(&mut self, wb: &mut WordBuilder) -> Result<()> {
while let Some(c) = self.peek_char() {
match c {
' ' | '\t' | '\n' | '\r' | ')' => break,
'<' | '>' => {
if self.input.get(self.pos + 1) == Some(&'(') {
self.read_process_sub_into(wb)?;
} else {
self.advance_char();
wb.push(c);
}
}
'\'' | '"' | '\\' | '$' | '`' => {
self.read_word_special(wb, c)?;
}
'[' if !wb.is_empty() && wb.value != "[" && !wb.ends_with('[') => {
self.read_bracket_subscript(wb)?;
}
_ => {
self.advance_char();
wb.push(c);
}
}
}
Ok(())
}
}
/// Returns true if a word value matches the assignment pattern `NAME=`,
/// `NAME+=`, or `NAME[...]=` / `NAME[...]+=`.
fn is_assignment_word(value: &str) -> bool {
let bytes = value.as_bytes();
// Must start with [a-zA-Z_]
if !matches!(bytes.first(), Some(b'a'..=b'z' | b'A'..=b'Z' | b'_')) {
return false;
}
let mut i = 1;
// Continue with [a-zA-Z_0-9]
while i < bytes.len() {
match bytes[i] {
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' => i += 1,
b'[' => {
// Skip subscript [...] — reject if it contains whitespace
// (bash doesn't allow spaces in assignment subscripts)
i += 1;
let mut depth = 1;
while i < bytes.len() && depth > 0 {
match bytes[i] {
b'[' => depth += 1,
b']' => depth -= 1,
b' ' | b'\t' | b'\n' => return false,
_ => {}
}
i += 1;
}
}
b'+' if i + 1 < bytes.len() && bytes[i + 1] == b'=' => return true,
b'=' => return true,
_ => return false,
}
}
false
}