rush-sh 0.8.0

A POSIX sh-compatible shell written in Rust
Documentation
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Variable and wildcard expansion functionality for the Rush shell.
//!
//! This module handles the expansion of shell variables, command substitutions,
//! arithmetic expressions, and wildcard patterns in command arguments.

use crate::parser::Ast;
use crate::state::ShellState;

/// Expand variables in a list of argument strings.
///
/// Processes each argument through [`expand_variables_in_string`] to perform
/// variable expansion, command substitution, and arithmetic evaluation.
///
/// # Arguments
/// * `args` - Slice of argument strings to expand
/// * `shell_state` - Mutable reference to shell state for variable lookups
///
/// # Returns
/// Vector of expanded argument strings
pub(crate) fn expand_variables_in_args(args: &[String], shell_state: &mut ShellState) -> Vec<String> {
    let mut expanded_args = Vec::new();

    for arg in args {
        // Expand variables within the argument string
        let expanded_arg = expand_variables_in_string(arg, shell_state);
        expanded_args.push(expanded_arg);
    }

    expanded_args
}

/// Expands shell-style variables, command substitutions, arithmetic expressions, and backtick substitutions inside a string.
///
/// This function processes `$VAR` and positional/special parameters (`$1`, `$?`, `$#`, `$*`, `$@`, `$$`, `$0`), command substitutions using `$(...)` and backticks, and arithmetic expansions using `$((...))`, producing the resulting string with substitutions applied. Undefined numeric positional parameters and the documented special parameters expand to an empty string; other undefined variable names are left as literal `$NAME`. Arithmetic evaluation errors are rendered as an error message (colorized when the shell state enables colors). Command substitutions are parsed and executed using the current shell state; on failure the original substitution text is preserved.
///
/// # Examples
///
/// ```no_run
/// use rush_sh::ShellState;
/// use rush_sh::executor::expand_variables_in_string;
/// // assume `shell_state` is a mutable ShellState with VAR=hello
/// let mut shell_state = ShellState::new();
/// shell_state.set_var("VAR", "hello".to_string());
/// let input = "Value:$VAR";
/// let out = expand_variables_in_string(input, &mut shell_state);
/// assert_eq!(out, "Value:hello");
/// ```
///
/// # Errors
///
/// Returns `Err` if input cannot be tokenized
pub fn expand_variables_in_string(input: &str, shell_state: &mut ShellState) -> String {
    let mut result = String::new();
    let mut chars = input.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '$' {
            // Check for command substitution $(...) or arithmetic expansion $((...))
            if let Some(&'(') = chars.peek() {
                chars.next(); // consume first (

                // Check if this is arithmetic expansion $((...))
                if let Some(&'(') = chars.peek() {
                    // Arithmetic expansion $((...))
                    chars.next(); // consume second (
                    let mut arithmetic_expr = String::new();
                    let mut paren_depth = 1;
                    let mut found_closing = false;

                    while let Some(c) = chars.next() {
                        if c == '(' {
                            paren_depth += 1;
                            arithmetic_expr.push(c);
                        } else if c == ')' {
                            paren_depth -= 1;
                            if paren_depth == 0 {
                                // Found the first closing ) - check for second )
                                if let Some(&')') = chars.peek() {
                                    chars.next(); // consume the second )
                                    found_closing = true;
                                    break;
                                } else {
                                    // Missing second closing paren, treat as error
                                    result.push_str("$((");
                                    result.push_str(&arithmetic_expr);
                                    result.push(')');
                                    break;
                                }
                            }
                            arithmetic_expr.push(c);
                        } else {
                            arithmetic_expr.push(c);
                        }
                    }

                    if found_closing {
                        // First expand variables in the arithmetic expression
                        // The arithmetic evaluator expects variable names without $ prefix
                        // So we need to expand $VAR to the value before evaluation
                        let mut expanded_expr = String::new();
                        let mut expr_chars = arithmetic_expr.chars().peekable();

                        while let Some(ch) = expr_chars.next() {
                            if ch == '$' {
                                // Expand variable
                                let mut var_name = String::new();
                                if let Some(&c) = expr_chars.peek() {
                                    if c == '?'
                                        || c == '$'
                                        || c == '0'
                                        || c == '#'
                                        || c == '*'
                                        || c == '@'
                                        || c == '!'
                                        || c.is_ascii_digit()
                                    {
                                        var_name.push(c);
                                        expr_chars.next();
                                    } else {
                                        while let Some(&c) = expr_chars.peek() {
                                            if c.is_alphanumeric() || c == '_' {
                                                var_name.push(c);
                                                expr_chars.next();
                                            } else {
                                                break;
                                            }
                                        }
                                    }
                                }

                                if !var_name.is_empty() {
                                    if let Some(value) = shell_state.get_var(&var_name) {
                                        expanded_expr.push_str(&value);
                                    } else {
                                        // Variable not found, use 0 for arithmetic
                                        expanded_expr.push('0');
                                    }
                                } else {
                                    expanded_expr.push('$');
                                }
                            } else {
                                expanded_expr.push(ch);
                            }
                        }

                        match crate::arithmetic::evaluate_arithmetic_expression(
                            &expanded_expr,
                            shell_state,
                        ) {
                            Ok(value) => {
                                result.push_str(&value.to_string());
                            }
                            Err(e) => {
                                // On arithmetic error, display a proper error message
                                if shell_state.colors_enabled {
                                    result.push_str(&format!(
                                        "{}arithmetic error: {}{}",
                                        shell_state.color_scheme.error, e, "\x1b[0m"
                                    ));
                                } else {
                                    result.push_str(&format!("arithmetic error: {}", e));
                                }
                            }
                        }
                    } else {
                        // Didn't find proper closing - keep as literal
                        result.push_str("$((");
                        result.push_str(&arithmetic_expr);
                        // Note: we don't add closing parens since they weren't in the input
                    }
                    continue;
                }

                // Regular command substitution $(...)
                let mut sub_command = String::new();
                let mut paren_depth = 1;

                for c in chars.by_ref() {
                    if c == '(' {
                        paren_depth += 1;
                        sub_command.push(c);
                    } else if c == ')' {
                        paren_depth -= 1;
                        if paren_depth == 0 {
                            break;
                        }
                        sub_command.push(c);
                    } else {
                        sub_command.push(c);
                    }
                }

                // Execute the command substitution within the current shell context
                // Parse and execute the command using our own lexer/parser/executor
                if let Ok(tokens) = crate::lexer::lex(&sub_command, shell_state) {
                    // Expand aliases before parsing
                    let expanded_tokens = match crate::lexer::expand_aliases(
                        tokens,
                        shell_state,
                        &mut std::collections::HashSet::new(),
                    ) {
                        Ok(t) => t,
                        Err(_) => {
                            // Alias expansion error, keep literal
                            result.push_str("$(");
                            result.push_str(&sub_command);
                            result.push(')');
                            continue;
                        }
                    };

                    match crate::parser::parse(expanded_tokens) {
                        Ok(ast) => {
                            // Execute within current shell context and capture output
                            match super::execute_and_capture_output(ast, shell_state) {
                                Ok(output) => {
                                    result.push_str(&output);
                                }
                                Err(_) => {
                                    // On failure, keep the literal
                                    result.push_str("$(");
                                    result.push_str(&sub_command);
                                    result.push(')');
                                }
                            }
                        }
                        Err(_parse_err) => {
                            // Parse error - try to handle as function call if it looks like one
                            let tokens_str = sub_command.trim();
                            if tokens_str.contains(' ') {
                                // Split by spaces and check if first token looks like a function call
                                let parts: Vec<&str> = tokens_str.split_whitespace().collect();
                                if let Some(first_token) = parts.first()
                                    && shell_state.get_function(first_token).is_some()
                                {
                                    // This is a function call, create AST manually
                                    let function_call = Ast::FunctionCall {
                                        name: first_token.to_string(),
                                        args: parts[1..].iter().map(|s| s.to_string()).collect(),
                                    };
                                    match super::execute_and_capture_output(function_call, shell_state) {
                                        Ok(output) => {
                                            result.push_str(&output);
                                            continue;
                                        }
                                        Err(_) => {
                                            // Fall back to literal
                                        }
                                    }
                                }
                            }
                            // Keep the literal
                            result.push_str("$(");
                            result.push_str(&sub_command);
                            result.push(')');
                        }
                    }
                } else {
                    // Lex error, keep literal
                    result.push_str("$(");
                    result.push_str(&sub_command);
                    result.push(')');
                }
            } else if let Some(&'{') = chars.peek() {
                // ${VAR} syntax
                chars.next(); // consume the {
                let mut var_name = String::new();
                let mut found_closing = false;

                // Read until we find the closing }
                for c in chars.by_ref() {
                    if c == '}' {
                        found_closing = true;
                        break;
                    }
                    var_name.push(c);
                }

                if found_closing && !var_name.is_empty() {
                    if let Some(value) = shell_state.get_var(&var_name) {
                        result.push_str(&value);
                    } else {
                        // Variable not found - for positional parameters and special variables, expand to empty string
                        // For other variables, keep the literal
                        if var_name.chars().next().unwrap().is_ascii_digit()
                            || var_name == "?"
                            || var_name == "$"
                            || var_name == "0"
                            || var_name == "#"
                            || var_name == "*"
                            || var_name == "@"
                            || var_name == "!"
                        {
                            // Expand to empty string for undefined positional parameters and special variables
                        } else {
                            // Keep the literal for regular variables
                            result.push_str("${");
                            result.push_str(&var_name);
                            result.push('}');
                        }
                    }
                } else {
                    // Malformed ${...} - keep as literal
                    result.push_str("${");
                    result.push_str(&var_name);
                    if !found_closing {
                        // No closing brace found
                    }
                }
            } else {
                // Regular variable
                let mut var_name = String::new();
                let mut next_ch = chars.peek();

                // Handle special single-character variables first
                if let Some(&c) = next_ch {
                    if c == '?' || c == '$' || c == '0' || c == '#' || c == '*' || c == '@' || c == '!' {
                        var_name.push(c);
                        chars.next(); // consume the character
                    } else if c.is_ascii_digit() {
                        // Positional parameter
                        var_name.push(c);
                        chars.next();
                    } else {
                        // Regular variable name (including multi-character special variables like LINENO)
                        while let Some(&c) = next_ch {
                            if c.is_alphanumeric() || c == '_' {
                                var_name.push(c);
                                chars.next(); // consume the character
                                next_ch = chars.peek();
                            } else {
                                break;
                            }
                        }
                    }
                }

                if !var_name.is_empty() {
                    if let Some(value) = shell_state.get_var(&var_name) {
                        result.push_str(&value);
                    } else {
                        // Variable not found - for positional parameters and special variables, expand to empty string
                        // For other variables, keep the literal
                        if var_name.chars().next().unwrap().is_ascii_digit()
                            || var_name == "?"
                            || var_name == "$"
                            || var_name == "0"
                            || var_name == "#"
                            || var_name == "*"
                            || var_name == "@"
                            || var_name == "!"
                        {
                            // Expand to empty string for undefined positional parameters and special variables
                        } else {
                            // Keep the literal for regular variables
                            result.push('$');
                            result.push_str(&var_name);
                        }
                    }
                } else {
                    result.push('$');
                }
            }
        } else if ch == '`' {
            // Backtick command substitution
            let mut sub_command = String::new();

            for c in chars.by_ref() {
                if c == '`' {
                    break;
                }
                sub_command.push(c);
            }

            // Execute the command substitution
            if let Ok(tokens) = crate::lexer::lex(&sub_command, shell_state) {
                // Expand aliases before parsing
                let expanded_tokens = match crate::lexer::expand_aliases(
                    tokens,
                    shell_state,
                    &mut std::collections::HashSet::new(),
                ) {
                    Ok(t) => t,
                    Err(_) => {
                        // Alias expansion error, keep literal
                        result.push('`');
                        result.push_str(&sub_command);
                        result.push('`');
                        continue;
                    }
                };

                if let Ok(ast) = crate::parser::parse(expanded_tokens) {
                    // Execute and capture output
                    match super::execute_and_capture_output(ast, shell_state) {
                        Ok(output) => {
                            result.push_str(&output);
                        }
                        Err(_) => {
                            // On failure, keep the literal
                            result.push('`');
                            result.push_str(&sub_command);
                            result.push('`');
                        }
                    }
                } else {
                    // Parse error, keep literal
                    result.push('`');
                    result.push_str(&sub_command);
                    result.push('`');
                }
            } else {
                // Lex error, keep literal
                result.push('`');
                result.push_str(&sub_command);
                result.push('`');
            }
        } else {
            result.push(ch);
        }
    }

    result
}

/// Expand shell-style wildcard patterns in a list of arguments unless the `noglob` option is set.
///
/// Patterns containing `*`, `?`, or `[` are replaced by the sorted list of matching filesystem paths. If a pattern has no matches or is an invalid pattern, the original literal argument is kept. If the shell state's `noglob` option is enabled, all arguments are returned unchanged.
///
/// # Examples
///
/// ```
/// // Note: expand_wildcards is a private function
/// // This example is for documentation only
/// ```
pub(crate) fn expand_wildcards(args: &[String], shell_state: &ShellState) -> Result<Vec<String>, String> {
    let mut expanded_args = Vec::new();

    for arg in args {
        // Skip wildcard expansion if noglob option (-f) is enabled
        if shell_state.options.noglob {
            expanded_args.push(arg.clone());
            continue;
        }
        
        if arg.contains('*') || arg.contains('?') || arg.contains('[') {
            // Try to expand wildcard
            match glob::glob(arg) {
                Ok(paths) => {
                    let mut matches: Vec<String> = paths
                        .filter_map(|p| p.ok())
                        .map(|p| p.to_string_lossy().to_string())
                        .collect();
                    if matches.is_empty() {
                        // No matches, keep literal
                        expanded_args.push(arg.clone());
                    } else {
                        // Sort for consistent behavior
                        matches.sort();
                        expanded_args.extend(matches);
                    }
                }
                Err(_e) => {
                    // Invalid pattern, keep literal
                    expanded_args.push(arg.clone());
                }
            }
        } else {
            expanded_args.push(arg.clone());
        }
    }
    Ok(expanded_args)
}