Skip to main content

shell/
core.rs

1//! The shared shell execution core.
2//!
3//! The Shell layer is split into a shared core and per-shell shells:
4//!
5//! ```text
6//! ShellCore — session state, execution machinery, expansion, resolution
7//!     ├── Bash — bash grammar, bash builtins, bash dialect
8//!     └── Zsh  — zsh grammar (sh-family subset today), zsh builtins, zsh dialect
9//! ```
10//!
11//! The core owns what the shell layer as a whole owns — the
12//! session's working directory, environment, history, aliases, functions,
13//! the command runtime, word expansion, globbing, redirection, and
14//! resolution (alias → function → builtin → external). It is deliberately
15//! language-agnostic about *semantics*: the grammar is parsed by each shell,
16//! and builtins are dispatched through a per-shell [`crate::core::ShellDialect`], so a
17//! builtin named `echo` may (and does) behave differently in Bash than in
18//! Zsh. Mechanisms the shells verified to share (for example `cd`) live
19//! here as core methods that a shell's table may delegate to; everything
20//! else is implemented in the shell's own module.
21//!
22//! The grammar today: both shells parse through [`brush_parser`] (the
23//! sh-family grammar) — this is a shared substrate, not a Bash-ism. Zsh
24//! owns any future zsh-specific grammar on top of this core.
25
26use std::collections::BTreeMap;
27use std::io::Cursor;
28
29use brush_parser::ast;
30use brush_parser::ast::{
31    CaseClauseCommand, CaseItemPostAction, Command, CompoundCommand, IoFileRedirectKind,
32    IoFileRedirectTarget, IoRedirect,
33};
34use brush_parser::{Parser, ParserOptions, SourceInfo};
35
36use engine::{BytesInput, BytesOutput, Input, Output, Pipe, Terminal, VirtualPath};
37
38/// The history cap shared by every shell: shifts oldest out.
39use crate::HISTORY_LIMIT;
40
41/// The deepest nested `execute` a single session permits (functions,
42/// command substitutions, scripts). Real shells recurse until the stack
43/// gives out; a simulation must fail a command instead of aborting the
44/// machine. 200 frames is far beyond any legitimate script while leaving
45/// the call stack safely bounded.
46const MAX_CALL_DEPTH: usize = 200;
47use os::runtime::{
48    CommandResolution, CommandRuntime, Executable, ExitStatus, Launcher, ResolvedExecutable,
49};
50use os::unix::unix_os::UnixOs;
51use os::{Credentials, Environment};
52
53/// How the core dispatches builtins for one shell language.
54///
55/// The runner returns `None` when the name is not a builtin of that shell,
56/// letting resolution continue to external commands.
57pub type BuiltinRunner = fn(
58    &mut ShellCore,
59    &str,
60    &[String],
61    &mut dyn Input,
62    &mut dyn Output,
63    &mut dyn Output,
64) -> Option<ExitStatus>;
65
66/// The per-shell behavior the core depends on: identity, messages, and the
67/// builtin table. Each shell constructs its own dialect.
68pub struct ShellDialect {
69    /// The shell's display name (`"bash"`, `"zsh"`).
70    pub name: &'static str,
71    /// The command-not-found message in this shell's dialect.
72    pub command_not_found: fn(&str) -> String,
73    /// The builtin dispatcher for this shell.
74    pub run_builtin: BuiltinRunner,
75    /// The system-wide startup file this shell sources at session start
76    /// (for example `/etc/zshrc`), or an empty string when none.
77    pub system_rc: &'static str,
78    /// The user startup file name inside the home directory (for example
79    /// `.zshrc`), or an empty string when none.
80    pub user_rc: &'static str,
81    /// Whether `echo` interprets backslash escapes by default (Bash: off;
82    /// Zsh and the BSD echo: on).
83    pub echo_escapes_default: bool,
84    /// The prefix `export` uses when listing the environment (`declare -x `
85    /// in Bash, `export ` in Zsh).
86    pub export_prefix: &'static str,
87    /// The prefix `alias` uses when listing aliases (`alias ` in Bash,
88    /// nothing in Zsh).
89    pub alias_prefix: &'static str,
90}
91
92/// How a name resolves in the shell: the shared precedence walk behind
93/// `type`, `which`, `where`, and `whence`. Each shell's reporter owns the
94/// phrasing; this owns the order (alias → function → builtin → PATH).
95pub struct NameResolution {
96    /// The alias expansion, when the name is an alias.
97    pub alias: Option<String>,
98    /// Whether the name is a function.
99    pub function: bool,
100    /// Whether the name is a builtin of this shell.
101    pub builtin: bool,
102    /// Every PATH hit, in order.
103    pub paths: Vec<String>,
104}
105
106/// Runs an interpreter invocation (`/bin/sh`, `/bin/bash`, `/bin/zsh`)
107/// through a fresh non-interactive [`ShellCore`] speaking the given dialect.
108///
109/// A script is not a separate mechanism: the interpreter paths
110/// are ordinary executables whose behavior *is* this project's shells.
111/// When a command resolves one of them, it runs here — the same parser,
112/// state model, and runtime as the session shell — with the caller's
113/// credentials and streams. This is what makes `sudo sh -c '...'`,
114/// `env bash script.sh`, and launcher-driven shebangs real: on a real
115/// system `/bin/sh` is just a program that reads commands, and here it is
116/// exactly that.
117#[allow(clippy::too_many_arguments)]
118pub(crate) fn run_interpreter_invocation(
119    os: &UnixOs,
120    credentials: Credentials,
121    dialect: ShellDialect,
122    cwd: &VirtualPath,
123    argv: &[String],
124    stdin: &mut dyn Input,
125    stdout: &mut dyn Output,
126    stderr: &mut dyn Output,
127) -> Result<ExitStatus, os::OsError> {
128    let mut shell = ShellCore::new(os, credentials, dialect)?;
129    // A real interpreter starts in the caller's working directory; rc
130    // files are not sourced, like a real non-interactive shell.
131    shell.set_cwd(cwd.clone());
132    Ok(shell.run_script_invocation(argv, stdin, stdout, stderr))
133}
134
135/// The escape sequences shared by the shells' `echo -e` (Bash) and
136/// `echo`/`print` (Zsh): `\a \b \c \e \f \n \r \t \v \\` and up to three
137/// octal digits. One language of escapes, one implementation; `\c`
138/// suppresses everything after it (including the newline the caller adds).
139pub(crate) fn interpret_escapes(text: &str) -> String {
140    let mut out = String::new();
141    let chars: Vec<char> = text.chars().collect();
142    let mut index = 0usize;
143    while index < chars.len() {
144        if chars[index] != '\\' || index + 1 >= chars.len() {
145            out.push(chars[index]);
146            index += 1;
147            continue;
148        }
149        let escaped = chars[index + 1];
150        index += 2;
151        match escaped {
152            'a' => out.push('\u{7}'),
153            'b' => out.push('\u{8}'),
154            'c' => break,
155            'e' => out.push('\u{1b}'),
156            'f' => out.push('\u{c}'),
157            'n' => out.push('\n'),
158            'r' => out.push('\r'),
159            't' => out.push('\t'),
160            'v' => out.push('\u{b}'),
161            '\\' => out.push('\\'),
162            '0'..='7' => {
163                // Up to three octal digits.
164                let mut octal = String::from(escaped);
165                while index < chars.len() && octal.len() < 3 && ('0'..='7').contains(&chars[index])
166                {
167                    octal.push(chars[index]);
168                    index += 1;
169                }
170                if let Ok(value) = u8::from_str_radix(&octal, 8) {
171                    out.push(value as char);
172                }
173            }
174            other => {
175                out.push('\\');
176                out.push(other);
177            }
178        }
179    }
180    out
181}
182
183/// A positional-parameter scope pushed for a function call or script
184/// invocation. Inside the scope, `$0` is the name and `$1`…
185/// are the arguments; scopes nest, so an inner call never clobbers the
186/// caller's parameters.
187struct PositionalFrame {
188    /// `$0`: the function or script name.
189    name: String,
190    /// The arguments: `$1` is `args[0]`.
191    args: Vec<String>,
192}
193
194/// The shared session state and execution machinery.
195///
196/// The core owns the session's working directory, environment, and the
197/// [`CommandRuntime`] that actually launches commands. External commands are
198/// resolved through `PATH` and the runtime's executable bindings; builtins
199/// are dispatched through the [`ShellDialect`] the shell was created with.
200pub struct ShellCore<'os> {
201    /// The OS this shell runs on.
202    os: &'os UnixOs,
203    /// The session credentials.
204    credentials: Credentials,
205    /// The current working directory.
206    cwd: VirtualPath,
207    /// The shell environment (includes per-user variables).
208    environment: Environment,
209    /// The command runtime that launches executables.
210    runtime: CommandRuntime<'os>,
211    /// Command history.
212    history: Vec<String>,
213    /// Aliases.
214    aliases: BTreeMap<String, String>,
215    /// Shell functions, by name, as their defining source.
216    functions: BTreeMap<String, String>,
217    /// Hashed PATH lookups (command hashing).
218    hash: BTreeMap<String, engine::ObjectId>,
219    /// A `break` executed inside a loop (cleared per command line).
220    loop_break: bool,
221    /// A `continue` executed inside a loop (cleared per command line).
222    loop_continue: bool,
223    /// An `exit [N]` executed by the session. When set, the
224    /// shell stops processing the current line and the application stops
225    /// reading input; the value is the process exit status.
226    exit_request: Option<ExitStatus>,
227    /// Positional-parameter frames: functions and script
228    /// invocations push one, restored on return. Empty at the prompt.
229    positionals: Vec<PositionalFrame>,
230    /// The directory stack (`pushd`/`popd`/`dirs`).
231    dir_stack: Vec<VirtualPath>,
232    /// The previous working directory, for `cd -` (OLDPWD).
233    previous_cwd: Option<VirtualPath>,
234    /// Aliases currently being expanded (guards self-referential aliases).
235    expanding_aliases: Vec<String>,
236    /// The current depth of nested [`ShellCore::execute_with_terminal`]
237    /// calls (functions, substitutions, scripts).
238    call_depth: usize,
239    /// The shell language this core executes for.
240    dialect: ShellDialect,
241    /// The interpreter objects (`/bin/sh`, `/bin/bash`, `/bin/zsh`) this
242    /// shell binds itself to. Object identity is stable across
243    /// shells sharing the OS, so any session recognizes them.
244    interpreter_objects: Vec<engine::ObjectId>,
245}
246
247impl<'os> ShellCore<'os> {
248    /// Creates a core for a session, executing in the given shell dialect.
249    pub fn new(
250        os: &'os UnixOs,
251        credentials: Credentials,
252        dialect: ShellDialect,
253    ) -> Result<Self, os::OsError> {
254        let environment = os.environment_for(&credentials);
255        let cwd = credentials
256            .user()
257            .home()
258            .parse::<VirtualPath>()
259            .unwrap_or_else(|_| VirtualPath::root());
260        let runtime = CommandRuntime::new(os)?;
261        let mut environment = environment;
262        environment.set("?", "0");
263        Ok(Self {
264            os,
265            credentials,
266            cwd,
267            environment,
268            runtime,
269            history: Vec::new(),
270            aliases: BTreeMap::new(),
271            functions: BTreeMap::new(),
272            hash: BTreeMap::new(),
273            loop_break: false,
274            loop_continue: false,
275            exit_request: None,
276            positionals: Vec::new(),
277            dir_stack: Vec::new(),
278            previous_cwd: None,
279            expanding_aliases: Vec::new(),
280            call_depth: 0,
281            dialect,
282            interpreter_objects: Vec::new(),
283        })
284    }
285
286    /// The current working directory.
287    pub fn cwd(&self) -> &VirtualPath {
288        &self.cwd
289    }
290
291    /// Sets the working directory (used by non-interactive interpreter
292    /// invocations, which start in the caller's directory).
293    pub fn set_cwd(&mut self, cwd: VirtualPath) {
294        self.cwd = cwd;
295    }
296
297    /// The shell environment.
298    pub fn environment(&self) -> &Environment {
299        &self.environment
300    }
301
302    /// The shell environment, mutable.
303    pub fn environment_mut(&mut self) -> &mut Environment {
304        &mut self.environment
305    }
306
307    /// The credentials this shell runs as.
308    pub fn credentials(&self) -> &Credentials {
309        &self.credentials
310    }
311
312    /// The OS this shell runs on.
313    pub fn os(&self) -> &'os UnixOs {
314        self.os
315    }
316
317    /// Returns the command history.
318    pub fn history(&self) -> &[String] {
319        &self.history
320    }
321
322    /// Records one completed command line.
323    ///
324    /// The interactive application calls this once per executed line — the
325    /// whole of a multi-line construct, not its continuation chunks — so
326    /// `history` shows exactly what the user typed. Internal re-execution
327    /// (rc sourcing, alias expansion, function bodies) never records.
328    pub fn record_history(&mut self, line: &str) {
329        if line.trim().is_empty() {
330            return;
331        }
332        self.history.push(line.to_owned());
333        if self.history.len() > HISTORY_LIMIT {
334            self.history.remove(0);
335        }
336    }
337
338    /// Returns the aliases.
339    pub fn aliases(&self) -> &BTreeMap<String, String> {
340        &self.aliases
341    }
342
343    /// The aliases, mutable.
344    pub fn aliases_mut(&mut self) -> &mut BTreeMap<String, String> {
345        &mut self.aliases
346    }
347
348    /// The functions, mutable.
349    pub fn functions_mut(&mut self) -> &mut BTreeMap<String, String> {
350        &mut self.functions
351    }
352
353    /// Reports the terminal size, exported as `COLUMNS`/`LINES`.
354    pub fn set_terminal_size(&mut self, rows: u16, cols: u16) {
355        self.environment.set("COLUMNS", cols.to_string());
356        self.environment.set("LINES", rows.to_string());
357    }
358
359    /// Sources the dialect's startup files (system-wide then per-user),
360    /// so aliases, functions, and variables from real rc files exist in
361    /// every session. Missing files are simply skipped, as real shells do.
362    pub fn source_startup_files(&mut self) {
363        let mut paths: Vec<String> = Vec::new();
364        if !self.dialect.system_rc.is_empty() {
365            paths.push(self.dialect.system_rc.to_owned());
366        }
367        if !self.dialect.user_rc.is_empty()
368            && let Some(home) = self.environment.get("HOME")
369        {
370            let user_rc = format!("{home}/{}", self.dialect.user_rc);
371            paths.push(user_rc);
372        }
373        let actor = Some(self.credentials.actor());
374        let engine = self.os.engine();
375        for path in paths {
376            let Ok(path) = path.parse::<engine::VirtualPath>() else {
377                continue;
378            };
379            let Some(object) = engine.lookup(actor, &path).ok() else {
380                continue;
381            };
382            let Some(bytes) = engine.read(actor, object).ok().flatten() else {
383                continue;
384            };
385            let source = String::from_utf8_lossy(&bytes).into_owned();
386            let mut stdin = engine::BytesInput::new(Vec::new());
387            let mut stdout = engine::BytesOutput::new();
388            let mut stderr = engine::BytesOutput::new();
389            let _ = self.execute(&source, &mut stdin, &mut stdout, &mut stderr);
390        }
391    }
392
393    /// Binds the interpreter behaviors onto the standard shell programs so
394    /// scripts execute through the same implementation as interactive
395    /// commands: `/bin/sh` and `/bin/bash` speak the Bash
396    /// dialect, `/bin/zsh` speaks the Zsh dialect, wherever those programs
397    /// exist on this system. Shebang interpreters resolve through these
398    /// bindings too.
399    pub fn install_shell_bindings(&mut self) {
400        let actor = Some(self.credentials.actor());
401        let interpreters: Vec<(&str, std::sync::Arc<dyn os::runtime::Command>)> = vec![
402            ("/bin/sh", std::sync::Arc::new(crate::bash::BashInterpreter)),
403            (
404                "/bin/bash",
405                std::sync::Arc::new(crate::bash::BashInterpreter),
406            ),
407            ("/bin/zsh", std::sync::Arc::new(crate::zsh::ZshInterpreter)),
408        ];
409        for (path, interpreter) in interpreters {
410            let Ok(path) = path.parse::<engine::VirtualPath>() else {
411                continue;
412            };
413            if let Ok(object) = self.os.engine().lookup(actor, &path) {
414                self.runtime.register(object, interpreter);
415                self.interpreter_objects.push(object);
416            }
417        }
418    }
419
420    /// Executes a line of shell input.
421    pub fn execute(
422        &mut self,
423        line: &str,
424        stdin: &mut dyn Input,
425        stdout: &mut dyn Output,
426        stderr: &mut dyn Output,
427    ) -> ExitStatus {
428        self.execute_with_terminal(line, stdin, stdout, stderr, None)
429    }
430
431    /// Executes a line, optionally handing a terminal to a command that
432    /// asks for one.
433    pub fn execute_with_terminal(
434        &mut self,
435        line: &str,
436        stdin: &mut dyn Input,
437        stdout: &mut dyn Output,
438        stderr: &mut dyn Output,
439        terminal: Option<&mut dyn Terminal>,
440    ) -> ExitStatus {
441        // The terminal is owned by the caller (the application); internal
442        // re-entry paths return it through the returning variant below.
443        let (status, _terminal) =
444            self.execute_with_terminal_returning(line, stdin, stdout, stderr, terminal);
445        status
446    }
447
448    /// Executes a line internally, returning the terminal.
449    ///
450    /// Alias expansions and function bodies re-enter the executor from
451    /// inside a simple command, so they must hand the terminal back to the
452    /// enclosing command rather than letting it vanish. Every recursion
453    /// path — functions, `$()` substitutions, nested scripts — flows
454    /// through here; the depth cap keeps pathological input from
455    /// overflowing the stack, which would abort the whole machine instead
456    /// of failing a command.
457    fn execute_with_terminal_returning<'t>(
458        &mut self,
459        line: &str,
460        stdin: &mut dyn Input,
461        stdout: &mut dyn Output,
462        stderr: &mut dyn Output,
463        terminal: Option<&'t mut dyn Terminal>,
464    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
465        if self.call_depth >= MAX_CALL_DEPTH {
466            let _ = stderr.write(b"vce: maximum recursion depth exceeded\n");
467            return (ExitStatus::FAILURE, terminal);
468        }
469        self.call_depth += 1;
470        let (status, terminal) = self.execute_at_depth(line, stdin, stdout, stderr, terminal);
471        self.call_depth -= 1;
472        (status, terminal)
473    }
474
475    fn execute_at_depth<'t>(
476        &mut self,
477        line: &str,
478        stdin: &mut dyn Input,
479        stdout: &mut dyn Output,
480        stderr: &mut dyn Output,
481        mut terminal: Option<&'t mut dyn Terminal>,
482    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
483        let line = line.trim();
484        if line.is_empty() {
485            return (ExitStatus::SUCCESS, terminal);
486        }
487
488        let program = match parse_program(line) {
489            Ok(program) => program,
490            Err(error) => {
491                let _ = stderr
492                    .write(format!("{}: syntax error: {error}\n", self.dialect.name).as_bytes());
493                return (ExitStatus::USAGE, terminal);
494            }
495        };
496
497        let mut last_status = ExitStatus::SUCCESS;
498        'commands: for complete_command in program.complete_commands {
499            for item in complete_command.0 {
500                let background = matches!(item.1, ast::SeparatorOperator::Async);
501                let (status, returned) = self.execute_and_or_list(
502                    &item.0,
503                    stdin,
504                    stdout,
505                    stderr,
506                    terminal.take(),
507                    background,
508                );
509                terminal = returned;
510                last_status = status;
511                self.environment.set("?", last_status.code().to_string());
512                // `exit` stops further commands on this line.
513                if self.exit_request.is_some() {
514                    break 'commands;
515                }
516            }
517        }
518        (last_status, terminal)
519    }
520
521    /// The positional value for a key in the innermost frame, if one is
522    /// active: `$0` (the name), `#` (`$#`, the argument count), `@`/`*`
523    /// (all arguments, space-joined), or a decimal index (`1`, `10`).
524    ///
525    /// Crate-visible because word expansion (`expansion`) consults it.
526    pub(crate) fn positional_value(&self, key: &str) -> Option<String> {
527        let frame = self.positionals.last()?;
528        match key {
529            "0" => Some(frame.name.clone()),
530            "#" => Some(frame.args.len().to_string()),
531            "@" | "*" => Some(frame.args.join(" ")),
532            _ => key
533                .parse::<usize>()
534                .ok()
535                .and_then(|index| index.checked_sub(1))
536                .and_then(|index| frame.args.get(index).cloned()),
537        }
538    }
539
540    /// Records an `exit [N]` request and returns its status.
541    ///
542    /// The status argument follows real shells: a missing or non-numeric
543    /// argument means success; an out-of-range value wraps modulo 256
544    /// (`exit 300` exits with status 44, like bash).
545    pub fn request_exit(&mut self, status_argument: Option<&str>) -> ExitStatus {
546        let code = status_argument
547            .and_then(|argument| argument.trim().parse::<i64>().ok())
548            .map_or(0, |value| u8::try_from(value & 0xFF).unwrap_or(0));
549        let status = ExitStatus::new(code);
550        self.exit_request = Some(status);
551        status
552    }
553
554    /// Takes a pending `exit` request, if any.
555    ///
556    /// The application calls this after executing a line: when it returns
557    /// `Some`, the session is over and the carried status is the process
558    /// exit code.
559    pub fn take_exit_request(&mut self) -> Option<ExitStatus> {
560        self.exit_request.take()
561    }
562
563    /// Executes one and-or list (`&&`/`||` semantics).
564    fn execute_and_or_list<'t>(
565        &mut self,
566        list: &ast::AndOrList,
567        stdin: &mut dyn Input,
568        stdout: &mut dyn Output,
569        stderr: &mut dyn Output,
570        terminal: Option<&'t mut dyn Terminal>,
571        background: bool,
572    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
573        let (mut status, mut terminal) =
574            self.execute_pipeline(&list.first, stdin, stdout, stderr, terminal, background);
575        for additional in &list.additional {
576            let (pipeline, should_run) = match additional {
577                ast::AndOr::And(pipeline) => (pipeline, status.is_success()),
578                ast::AndOr::Or(pipeline) => (pipeline, !status.is_success()),
579            };
580            if should_run {
581                (status, terminal) =
582                    self.execute_pipeline(pipeline, stdin, stdout, stderr, terminal, background);
583            }
584        }
585        (status, terminal)
586    }
587
588    /// Executes one pipeline.
589    fn execute_pipeline<'t>(
590        &mut self,
591        pipeline: &ast::Pipeline,
592        stdin: &mut dyn Input,
593        stdout: &mut dyn Output,
594        stderr: &mut dyn Output,
595        terminal: Option<&'t mut dyn Terminal>,
596        background: bool,
597    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
598        let mut status = ExitStatus::SUCCESS;
599        let mut terminal = terminal;
600        if pipeline.seq.len() == 1 {
601            (status, terminal) = self.execute_command(
602                &pipeline.seq[0],
603                stdin,
604                stdout,
605                stderr,
606                terminal,
607                background,
608            );
609        } else {
610            // Multiple stages: connect via Engine pipes.
611            let pipes: Vec<Pipe> = (0..pipeline.seq.len() - 1).map(|_| Pipe::new()).collect();
612            for (index, command) in pipeline.seq.iter().enumerate() {
613                let is_first = index == 0;
614                let is_last = index == pipeline.seq.len() - 1;
615                let stage_term = if is_last { terminal.take() } else { None };
616                let (stage_status, returned_terminal) = if is_first && !is_last {
617                    let mut pipe_out = pipes[0].output();
618                    self.execute_command(command, stdin, &mut pipe_out, stderr, None, false)
619                } else if is_last {
620                    let mut pipe_in = pipes[index - 1].input();
621                    self.execute_command(
622                        command,
623                        &mut pipe_in,
624                        stdout,
625                        stderr,
626                        stage_term,
627                        background,
628                    )
629                } else {
630                    let mut pipe_in = pipes[index - 1].input();
631                    let mut pipe_out = pipes[index].output();
632                    self.execute_command(command, &mut pipe_in, &mut pipe_out, stderr, None, false)
633                };
634                // Only the last stage's return matters: earlier stages ran
635                // without the terminal and must not clobber the one held
636                // for the interactive stage.
637                if is_last {
638                    terminal = returned_terminal;
639                }
640                status = stage_status;
641            }
642        }
643        if pipeline.bang {
644            status = status.negated();
645        }
646        (status, terminal)
647    }
648
649    /// Executes one command: simple, compound, or function definition.
650    fn execute_command<'t>(
651        &mut self,
652        command: &Command,
653        stdin: &mut dyn Input,
654        stdout: &mut dyn Output,
655        stderr: &mut dyn Output,
656        terminal: Option<&'t mut dyn Terminal>,
657        background: bool,
658    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
659        match command {
660            Command::Simple(simple) => {
661                self.execute_simple(simple, stdin, stdout, stderr, terminal, background)
662            }
663            Command::Compound(compound, redirects) => self.execute_compound(
664                compound,
665                redirects.as_ref(),
666                stdin,
667                stdout,
668                stderr,
669                terminal,
670                background,
671            ),
672            Command::Function(function) => {
673                // Define the function, storing its body so later
674                // invocations execute it.
675                self.functions
676                    .insert(function.fname.clone(), function.body.0.to_string());
677                (ExitStatus::SUCCESS, terminal)
678            }
679            Command::ExtendedTest(expr) => {
680                let truth = self.evaluate_extended_test(expr);
681                (
682                    if truth {
683                        ExitStatus::SUCCESS
684                    } else {
685                        ExitStatus::FAILURE
686                    },
687                    terminal,
688                )
689            }
690        }
691    }
692
693    /// Evaluates a `[[ ]]` extended test expression.
694    fn evaluate_extended_test(&mut self, expr: &ast::ExtendedTestExpr) -> bool {
695        use brush_parser::ast::{
696            BinaryPredicate as Bp, ExtendedTestExpr as E, UnaryPredicate as Up,
697        };
698        match expr {
699            E::And(left, right) => {
700                self.evaluate_extended_test(left) && self.evaluate_extended_test(right)
701            }
702            E::Or(left, right) => {
703                self.evaluate_extended_test(left) || self.evaluate_extended_test(right)
704            }
705            E::Not(inner) => !self.evaluate_extended_test(inner),
706            E::Parenthesized(inner) => self.evaluate_extended_test(inner),
707            E::UnaryTest(predicate, word) => {
708                let value = self.expand_word(&word.value);
709                match predicate {
710                    Up::StringHasZeroLength => value.is_empty(),
711                    Up::StringHasNonZeroLength => !value.is_empty(),
712                    Up::ShellVariableIsSetAndAssigned => self.environment.get(&value).is_some(),
713                    Up::FileExists => self.path_exists(&value),
714                    Up::FileExistsAndIsDir => self
715                        .resolve_path(&value)
716                        .is_ok_and(|path| self.is_directory(&path)),
717                    Up::FileExistsAndIsRegularFile => self.resolve_path(&value).is_ok_and(|path| {
718                        self.os
719                            .engine()
720                            .lookup(Some(self.credentials.actor()), &path)
721                            .is_ok_and(|object| {
722                                self.os
723                                    .engine()
724                                    .read(Some(self.credentials.actor()), object)
725                                    .is_ok()
726                            })
727                    }),
728                    Up::FileExistsAndIsReadable => self.resolve_path(&value).is_ok_and(|path| {
729                        self.os
730                            .engine()
731                            .lookup(Some(self.credentials.actor()), &path)
732                            .is_ok_and(|object| {
733                                self.os
734                                    .engine()
735                                    .check(
736                                        Some(self.credentials.actor()),
737                                        engine::Operation::Read,
738                                        object,
739                                    )
740                                    .is_ok()
741                            })
742                    }),
743                    Up::FileExistsAndIsWritable => self.resolve_path(&value).is_ok_and(|path| {
744                        self.os
745                            .engine()
746                            .lookup(Some(self.credentials.actor()), &path)
747                            .is_ok_and(|object| {
748                                self.os
749                                    .engine()
750                                    .check(
751                                        Some(self.credentials.actor()),
752                                        engine::Operation::Write,
753                                        object,
754                                    )
755                                    .is_ok()
756                            })
757                    }),
758                    Up::FileExistsAndIsExecutable => self
759                        .resolve_path(&value)
760                        .is_ok_and(|path| self.executable_path(&path).is_some()),
761                    Up::FileExistsAndIsNotZeroLength => {
762                        self.resolve_path(&value).is_ok_and(|path| {
763                            self.os
764                                .engine()
765                                .lookup(Some(self.credentials.actor()), &path)
766                                .is_ok_and(|object| {
767                                    self.os
768                                        .engine()
769                                        .size(Some(self.credentials.actor()), object)
770                                        .is_ok_and(|size| size > 0)
771                                })
772                        })
773                    }
774                    _ => false,
775                }
776            }
777            E::BinaryTest(predicate, left, right) => {
778                let left = self.expand_word(&left.value);
779                let right = self.expand_word(&right.value);
780                match predicate {
781                    Bp::StringExactlyMatchesString => left == right,
782                    Bp::StringDoesNotExactlyMatchString => left != right,
783                    Bp::StringContainsSubstring => left.contains(&right),
784                    Bp::LeftSortsBeforeRight => left < right,
785                    Bp::LeftSortsAfterRight => left > right,
786                    Bp::StringExactlyMatchesPattern => crate::expansion::glob_match(&left, &right),
787                    Bp::StringDoesNotExactlyMatchPattern => {
788                        !crate::expansion::glob_match(&left, &right)
789                    }
790                    // Arithmetic operands are full expressions, as in real
791                    // shells: `[[ 1+1 -eq 2 ]]` holds.
792                    Bp::ArithmeticEqualTo => {
793                        self.arithmetic_operand(&left) == self.arithmetic_operand(&right)
794                    }
795                    Bp::ArithmeticNotEqualTo => {
796                        self.arithmetic_operand(&left) != self.arithmetic_operand(&right)
797                    }
798                    Bp::ArithmeticLessThan => {
799                        self.arithmetic_operand(&left) < self.arithmetic_operand(&right)
800                    }
801                    Bp::ArithmeticLessThanOrEqualTo => {
802                        self.arithmetic_operand(&left) <= self.arithmetic_operand(&right)
803                    }
804                    Bp::ArithmeticGreaterThan => {
805                        self.arithmetic_operand(&left) > self.arithmetic_operand(&right)
806                    }
807                    Bp::ArithmeticGreaterThanOrEqualTo => {
808                        self.arithmetic_operand(&left) >= self.arithmetic_operand(&right)
809                    }
810                    _ => false,
811                }
812            }
813        }
814    }
815
816    /// Whether a path exists in the virtual filesystem.
817    fn path_exists(&self, value: &str) -> bool {
818        self.resolve_path(value).is_ok_and(|path| {
819            self.os
820                .engine()
821                .lookup(Some(self.credentials.actor()), &path)
822                .is_ok()
823        })
824    }
825
826    /// Evaluates a `[[ ]]` arithmetic operand: a full arithmetic
827    /// expression, so `[[ 1+1 -eq 2 ]]` holds like it does in real shells.
828    /// Garbage reads as 0.
829    fn arithmetic_operand(&mut self, value: &str) -> i64 {
830        self.evaluate_arithmetic(value.trim()).unwrap_or(0)
831    }
832
833    /// Executes a compound command: groups, conditionals, and loops.
834    #[allow(clippy::too_many_arguments)]
835    fn execute_compound<'t>(
836        &mut self,
837        compound: &CompoundCommand,
838        redirects: Option<&ast::RedirectList>,
839        stdin: &mut dyn Input,
840        stdout: &mut dyn Output,
841        stderr: &mut dyn Output,
842        terminal: Option<&'t mut dyn Terminal>,
843        background: bool,
844    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
845        // A single stdout redirect may apply to the whole compound; capture
846        // its output and write the file afterwards.
847        let stdout_redirect = compound_stdout_redirect(redirects);
848        let mut captured = BytesOutput::new();
849        let effective_stdout: &mut dyn Output = if stdout_redirect.is_some() {
850            &mut captured
851        } else {
852            stdout
853        };
854
855        let (status, terminal) = match compound {
856            CompoundCommand::BraceGroup(group) => self.execute_compound_list(
857                &group.0,
858                stdin,
859                effective_stdout,
860                stderr,
861                terminal,
862                background,
863            ),
864            CompoundCommand::IfClause(ifc) => {
865                let (condition_status, terminal) = self.execute_compound_list(
866                    &ifc.condition,
867                    stdin,
868                    effective_stdout,
869                    stderr,
870                    terminal,
871                    false,
872                );
873                if condition_status.is_success() {
874                    self.execute_compound_list(
875                        &ifc.then,
876                        stdin,
877                        effective_stdout,
878                        stderr,
879                        terminal,
880                        background,
881                    )
882                } else if let Some(elses) = &ifc.elses {
883                    // Each `elif` re-evaluates a condition; a bare `else`
884                    // runs unconditionally (`if` semantics).
885                    let mut terminal = terminal;
886                    for else_clause in elses {
887                        match &else_clause.condition {
888                            Some(condition) => {
889                                let (elif_status, returned) = self.execute_compound_list(
890                                    condition,
891                                    stdin,
892                                    effective_stdout,
893                                    stderr,
894                                    terminal.take(),
895                                    false,
896                                );
897                                terminal = returned;
898                                if elif_status.is_success() {
899                                    return self.execute_compound_list(
900                                        &else_clause.body,
901                                        stdin,
902                                        effective_stdout,
903                                        stderr,
904                                        terminal.take(),
905                                        background,
906                                    );
907                                }
908                            }
909                            None => {
910                                return self.execute_compound_list(
911                                    &else_clause.body,
912                                    stdin,
913                                    effective_stdout,
914                                    stderr,
915                                    terminal.take(),
916                                    background,
917                                );
918                            }
919                        }
920                    }
921                    (ExitStatus::SUCCESS, terminal)
922                } else {
923                    (ExitStatus::SUCCESS, terminal)
924                }
925            }
926            CompoundCommand::WhileClause(clause) => self.execute_loop(
927                &clause.0,
928                &clause.1.0,
929                false,
930                stdin,
931                effective_stdout,
932                stderr,
933                terminal,
934                background,
935            ),
936            CompoundCommand::UntilClause(clause) => self.execute_loop(
937                &clause.0,
938                &clause.1.0,
939                true,
940                stdin,
941                effective_stdout,
942                stderr,
943                terminal,
944                background,
945            ),
946            CompoundCommand::ForClause(clause) => {
947                // `for name in values; do ...; done`.
948                let mut last_status = ExitStatus::SUCCESS;
949                let mut terminal = terminal;
950                // A stray `break`/`continue` from outside the loop must not
951                // leak into it.
952                self.loop_break = false;
953                self.loop_continue = false;
954                let values: Vec<String> = match &clause.values {
955                    Some(words) => words
956                        .iter()
957                        .map(|word| self.expand_word(&word.value))
958                        .collect(),
959                    None => Vec::new(),
960                };
961                for value in values {
962                    self.environment.set(&clause.variable_name, value);
963                    let (body_status, returned) = self.execute_compound_list(
964                        &clause.body.0,
965                        stdin,
966                        stdout,
967                        stderr,
968                        terminal.take(),
969                        background,
970                    );
971                    terminal = returned;
972                    last_status = body_status;
973                    // `$?` tracks the most recent command even inside loop
974                    // bodies, as in real shells.
975                    self.environment.set("?", last_status.code().to_string());
976                    if self.loop_break {
977                        self.loop_break = false;
978                        break;
979                    }
980                    if self.loop_continue {
981                        self.loop_continue = false;
982                        continue;
983                    }
984                }
985                (last_status, terminal)
986            }
987            CompoundCommand::Subshell(subshell) => {
988                // A subshell is an isolated copy of the session: variable
989                // changes, `cd`, and `exit` do not escape it.
990                let saved_environment = self.environment.clone();
991                let saved_cwd = self.cwd.clone();
992                let saved_exit_request = self.exit_request;
993                let (status, terminal) = self.execute_compound_list(
994                    &subshell.0,
995                    stdin,
996                    effective_stdout,
997                    stderr,
998                    terminal,
999                    background,
1000                );
1001                self.environment = saved_environment;
1002                self.cwd = saved_cwd;
1003                self.exit_request = saved_exit_request;
1004                (status, terminal)
1005            }
1006            CompoundCommand::CaseClause(clause) => self.execute_case_clause(
1007                clause,
1008                stdin,
1009                effective_stdout,
1010                stderr,
1011                terminal,
1012                background,
1013            ),
1014            CompoundCommand::Arithmetic(command) => {
1015                // `((expr))`: like real shells, status 0 when the result is
1016                // nonzero; assignment operators mutate the environment.
1017                let prepared =
1018                    if command.expr.value.contains('$') || command.expr.value.contains('`') {
1019                        self.expand_word(&command.expr.value)
1020                    } else {
1021                        command.expr.value.clone()
1022                    };
1023                match self.evaluate_arithmetic(&prepared) {
1024                    Some(value) if value != 0 => (ExitStatus::SUCCESS, terminal),
1025                    Some(_) => (ExitStatus::FAILURE, terminal),
1026                    None => {
1027                        let _ = stderr.write(
1028                            format!(
1029                                "{}: invalid arithmetic expression: {}\n",
1030                                self.dialect.name, command.expr.value
1031                            )
1032                            .as_bytes(),
1033                        );
1034                        (ExitStatus::USAGE, terminal)
1035                    }
1036                }
1037            }
1038            _ => {
1039                let _ = stderr.write(
1040                    format!(
1041                        "{}: this construct is not supported by this shell\n",
1042                        self.dialect.name
1043                    )
1044                    .as_bytes(),
1045                );
1046                (ExitStatus::USAGE, terminal)
1047            }
1048        };
1049
1050        if let Some((path, append)) = stdout_redirect
1051            && let Err(error) = self.write_redirect(&path, &captured.into_bytes(), append)
1052        {
1053            let _ = stderr.write(format!("{}: {error}\n", self.dialect.name).as_bytes());
1054            return (ExitStatus::FAILURE, terminal);
1055        }
1056        (status, terminal)
1057    }
1058
1059    /// Executes a `while` or `until` loop.
1060    #[allow(clippy::too_many_arguments)]
1061    fn execute_loop<'t>(
1062        &mut self,
1063        condition: &ast::CompoundList,
1064        body: &ast::CompoundList,
1065        until: bool,
1066        stdin: &mut dyn Input,
1067        stdout: &mut dyn Output,
1068        stderr: &mut dyn Output,
1069        terminal: Option<&'t mut dyn Terminal>,
1070        background: bool,
1071    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
1072        let mut last_status = ExitStatus::SUCCESS;
1073        let mut terminal = terminal;
1074        // A stray `break`/`continue` from outside the loop must not leak
1075        // into it.
1076        self.loop_break = false;
1077        self.loop_continue = false;
1078        loop {
1079            let (condition_status, returned) = self.execute_compound_list(
1080                condition,
1081                stdin,
1082                stdout,
1083                stderr,
1084                terminal.take(),
1085                false,
1086            );
1087            terminal = returned;
1088            let should_run = if until {
1089                !condition_status.is_success()
1090            } else {
1091                condition_status.is_success()
1092            };
1093            if !should_run {
1094                break;
1095            }
1096            (last_status, terminal) = self.execute_compound_list(
1097                body,
1098                stdin,
1099                stdout,
1100                stderr,
1101                terminal.take(),
1102                background,
1103            );
1104            // `$?` tracks the most recent command even inside loop bodies.
1105            self.environment.set("?", last_status.code().to_string());
1106            if self.loop_break {
1107                self.loop_break = false;
1108                break;
1109            }
1110            if self.loop_continue {
1111                self.loop_continue = false;
1112                continue;
1113            }
1114        }
1115        (last_status, terminal)
1116    }
1117
1118    /// Executes a compound list, tracking loop control flow.
1119    fn execute_compound_list<'t>(
1120        &mut self,
1121        list: &ast::CompoundList,
1122        stdin: &mut dyn Input,
1123        stdout: &mut dyn Output,
1124        stderr: &mut dyn Output,
1125        terminal: Option<&'t mut dyn Terminal>,
1126        background: bool,
1127    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
1128        let mut last_status = ExitStatus::SUCCESS;
1129        let mut terminal = terminal;
1130        for item in &list.0 {
1131            let item_background = background || matches!(item.1, ast::SeparatorOperator::Async);
1132            let (status, returned) = self.execute_and_or_list(
1133                &item.0,
1134                stdin,
1135                stdout,
1136                stderr,
1137                terminal.take(),
1138                item_background,
1139            );
1140            terminal = returned;
1141            last_status = status;
1142            // `break`/`continue` from within this list stop further items.
1143            if self.loop_break || self.loop_continue {
1144                break;
1145            }
1146        }
1147        (last_status, terminal)
1148    }
1149
1150    /// Executes a simple command: assignments, argv, and redirections.
1151    fn execute_simple<'t>(
1152        &mut self,
1153        simple: &ast::SimpleCommand,
1154        stdin: &mut dyn Input,
1155        stdout: &mut dyn Output,
1156        stderr: &mut dyn Output,
1157        terminal: Option<&'t mut dyn Terminal>,
1158        background: bool,
1159    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
1160        let mut argv: Vec<String> = Vec::new();
1161        let mut globs: Vec<bool> = Vec::new();
1162        let mut assignments: Vec<(String, String)> = Vec::new();
1163        let mut stdin_redirect: Option<String> = None;
1164        let mut stdout_redirect: Option<(String, bool)> = None;
1165        let mut stderr_redirect: Option<(String, bool)> = None;
1166        let mut stderr_to_stdout = false;
1167        let mut stdout_to_stderr = false;
1168
1169        let collect = |item: &ast::CommandPrefixOrSuffixItem,
1170                       argv: &mut Vec<String>,
1171                       globs: &mut Vec<bool>,
1172                       assignments: &mut Vec<(String, String)>,
1173                       stdin_redirect: &mut Option<String>,
1174                       stdout_redirect: &mut Option<(String, bool)>,
1175                       stderr_redirect: &mut Option<(String, bool)>,
1176                       stderr_to_stdout: &mut bool,
1177                       stdout_to_stderr: &mut bool|
1178         -> Result<(), String> {
1179            match item {
1180                ast::CommandPrefixOrSuffixItem::Word(word) => {
1181                    argv.push(word.value.clone());
1182                    globs.push(true);
1183                }
1184                ast::CommandPrefixOrSuffixItem::AssignmentWord(assignment, _word) => {
1185                    let value = match &assignment.value {
1186                        ast::AssignmentValue::Scalar(word) => word.value.clone(),
1187                        ast::AssignmentValue::Array(_) => {
1188                            return Err("array assignments are not supported".to_owned());
1189                        }
1190                    };
1191                    assignments.push((assignment.name.name_string(), value));
1192                }
1193                ast::CommandPrefixOrSuffixItem::IoRedirect(io) => match io {
1194                    IoRedirect::File(fd, kind, target) => {
1195                        match target {
1196                            IoFileRedirectTarget::Duplicate(duplicate) => {
1197                                // `2>&1` and `1>&2`: merge the streams.
1198                                let duplicate = duplicate.value.parse::<u32>().unwrap_or(u32::MAX);
1199                                match (fd, duplicate) {
1200                                    (Some(2), 1) => *stderr_to_stdout = true,
1201                                    (Some(1), 2) => *stdout_to_stderr = true,
1202                                    (_, 0) => {
1203                                        return Err("stdin duplication is not supported".to_owned());
1204                                    }
1205                                    _ => return Err("this redirection is not supported".to_owned()),
1206                                }
1207                                return Ok(());
1208                            }
1209                            IoFileRedirectTarget::Fd(_) => {
1210                                return Err("fd redirections are not supported".to_owned());
1211                            }
1212                            IoFileRedirectTarget::ProcessSubstitution(_, _) => {
1213                                return Err("process substitution is not supported".to_owned());
1214                            }
1215                            IoFileRedirectTarget::Filename(_) => {}
1216                        }
1217                        let filename = match target {
1218                            IoFileRedirectTarget::Filename(word) => word.value.clone(),
1219                            _ => unreachable!(),
1220                        };
1221                        match kind {
1222                            IoFileRedirectKind::Read if fd.is_none_or(|n| n == 0) => {
1223                                *stdin_redirect = Some(filename);
1224                            }
1225                            IoFileRedirectKind::Write if fd.is_none_or(|n| n == 1) => {
1226                                *stdout_redirect = Some((filename, false));
1227                            }
1228                            IoFileRedirectKind::Append if fd.is_none_or(|n| n == 1) => {
1229                                *stdout_redirect = Some((filename, true));
1230                            }
1231                            IoFileRedirectKind::Write if fd.is_some_and(|n| n == 2) => {
1232                                *stderr_redirect = Some((filename, false));
1233                            }
1234                            IoFileRedirectKind::Append if fd.is_some_and(|n| n == 2) => {
1235                                *stderr_redirect = Some((filename, true));
1236                            }
1237                            _ => return Err("this redirection is not supported".to_owned()),
1238                        }
1239                    }
1240                    IoRedirect::HereDocument(fd, here) => {
1241                        if fd.is_some_and(|n| n != 0) {
1242                            return Err("this redirection is not supported".to_owned());
1243                        }
1244                        let content = here.doc.value.clone();
1245                        let marker = if here.requires_expansion {
1246                            "\0heredoc-expand:"
1247                        } else {
1248                            "\0heredoc:"
1249                        };
1250                        *stdin_redirect = Some(format!("{marker}{content}\0"));
1251                    }
1252                    IoRedirect::HereString(fd, word) => {
1253                        if fd.is_some_and(|n| n != 0) {
1254                            return Err("this redirection is not supported".to_owned());
1255                        }
1256                        *stdin_redirect = Some(format!("\0herestring:{}\0", word.value));
1257                    }
1258                    IoRedirect::OutputAndError(target, append) => {
1259                        *stdout_redirect = Some((target.value.clone(), *append));
1260                    }
1261                },
1262                ast::CommandPrefixOrSuffixItem::ProcessSubstitution(_, _) => {
1263                    return Err("process substitution is not supported".to_owned());
1264                }
1265            }
1266            Ok(())
1267        };
1268
1269        let mut result = Ok(());
1270        if let Some(prefix) = &simple.prefix {
1271            for item in &prefix.0 {
1272                if let Err(error) = collect(
1273                    item,
1274                    &mut argv,
1275                    &mut globs,
1276                    &mut assignments,
1277                    &mut stdin_redirect,
1278                    &mut stdout_redirect,
1279                    &mut stderr_redirect,
1280                    &mut stderr_to_stdout,
1281                    &mut stdout_to_stderr,
1282                ) {
1283                    result = Err(error);
1284                    break;
1285                }
1286            }
1287        }
1288        if result.is_ok()
1289            && let Some(name) = &simple.word_or_name
1290        {
1291            argv.push(name.value.clone());
1292            globs.push(true);
1293        }
1294        if result.is_ok()
1295            && let Some(suffix) = &simple.suffix
1296        {
1297            for item in &suffix.0 {
1298                // Suffix assignments like `echo FOO=bar` are not
1299                // environment prefix assignments — they are regular
1300                // arguments (real shells print `FOO=bar`). Treat them
1301                // as words.
1302                if let ast::CommandPrefixOrSuffixItem::AssignmentWord(assignment, word) = item {
1303                    argv.push(format!(
1304                        "{}={}",
1305                        assignment.name.name_string(),
1306                        match &assignment.value {
1307                            ast::AssignmentValue::Scalar(w) => w.value.clone(),
1308                            ast::AssignmentValue::Array(_) => word.value.clone(),
1309                        }
1310                    ));
1311                    globs.push(false);
1312                    continue;
1313                }
1314                if let Err(error) = collect(
1315                    item,
1316                    &mut argv,
1317                    &mut globs,
1318                    &mut assignments,
1319                    &mut stdin_redirect,
1320                    &mut stdout_redirect,
1321                    &mut stderr_redirect,
1322                    &mut stderr_to_stdout,
1323                    &mut stdout_to_stderr,
1324                ) {
1325                    result = Err(error);
1326                    break;
1327                }
1328            }
1329        }
1330        if let Err(error) = result {
1331            let _ = stderr.write(format!("{}: {error}\n", self.dialect.name).as_bytes());
1332            return (ExitStatus::USAGE, terminal);
1333        }
1334
1335        // Bare assignments (no command name) persist in the shell
1336        // environment; otherwise they prefix the command's environment.
1337        if argv.is_empty() {
1338            for (name, value) in assignments {
1339                let expanded = self.expand_word(&value);
1340                self.environment.set(name, expanded);
1341            }
1342            return (ExitStatus::SUCCESS, terminal);
1343        }
1344        let command_environment = if assignments.is_empty() {
1345            None
1346        } else {
1347            let mut environment = self.environment.clone();
1348            for (name, value) in &assignments {
1349                let expanded = self.expand_word(value);
1350                environment.set(name.clone(), expanded);
1351            }
1352            Some(environment)
1353        };
1354
1355        // Expand words (variables, tilde) with quoting semantics.
1356        let mut expanded_argv: Vec<String> = Vec::new();
1357        let mut expanded_globs: Vec<bool> = Vec::new();
1358        for (raw, glob) in argv.iter().zip(globs.iter()) {
1359            let (expanded, contains_unquoted_glob) = self.expand_word_with_glob(raw);
1360            expanded_argv.push(expanded);
1361            expanded_globs.push(*glob && contains_unquoted_glob);
1362        }
1363
1364        // Expand globs in unquoted words only.
1365        let mut final_argv: Vec<String> = Vec::new();
1366        for (arg, glob) in expanded_argv.iter().zip(expanded_globs.iter()) {
1367            if *glob {
1368                final_argv.extend(self.expand_glob(arg));
1369            } else {
1370                final_argv.push(arg.clone());
1371            }
1372        }
1373        if final_argv.is_empty() {
1374            return (ExitStatus::SUCCESS, terminal);
1375        }
1376
1377        // Alias expansion (alias → function → builtin → external).
1378        // The first word of a simple command expands when it names an alias;
1379        // self-referential aliases stop expanding.
1380        let name = final_argv[0].clone();
1381        if !self.expanding_aliases.contains(&name)
1382            && let Some(expansion) = self.aliases.get(&name).cloned()
1383        {
1384            let rest: Vec<String> = final_argv[1..]
1385                .iter()
1386                .map(|word| shell_quote(word))
1387                .collect();
1388            let line = if rest.is_empty() {
1389                expansion
1390            } else {
1391                format!("{expansion} {}", rest.join(" "))
1392            };
1393            self.expanding_aliases.push(name);
1394            return self.execute_with_terminal_returning(&line, stdin, stdout, stderr, terminal);
1395        }
1396
1397        // Input redirection.
1398        let mut input: Box<dyn Input> = Box::new(BytesInput::new(Vec::new()));
1399        let mut input_is_redirected = false;
1400        if let Some(input_path) = stdin_redirect {
1401            if let Some(content) = heredoc_content(&input_path) {
1402                let content = if heredoc_expands(&input_path) {
1403                    self.expand_word(&String::from_utf8_lossy(&content))
1404                        .into_bytes()
1405                } else {
1406                    content
1407                };
1408                input = Box::new(BytesInput::new(content));
1409            } else {
1410                let expanded = self.expand_word(&input_path);
1411                let path = match self.resolve_path(&expanded) {
1412                    Ok(path) => path,
1413                    Err(error) => {
1414                        let _ = stderr.write(format!("{error}\n").as_bytes());
1415                        return (ExitStatus::FAILURE, terminal);
1416                    }
1417                };
1418                let object = match self
1419                    .os
1420                    .engine()
1421                    .lookup(Some(self.credentials.actor()), &path)
1422                {
1423                    Ok(object) => object,
1424                    Err(error) => {
1425                        let _ = stderr.write(format!("{}: {error}\n", final_argv[0]).as_bytes());
1426                        return (ExitStatus::FAILURE, terminal);
1427                    }
1428                };
1429                let content = match self
1430                    .os
1431                    .engine()
1432                    .read(Some(self.credentials.actor()), object)
1433                {
1434                    Ok(Some(bytes)) => bytes,
1435                    Ok(None) => Vec::new(),
1436                    Err(error) => {
1437                        let _ = stderr.write(format!("{}: {error}\n", final_argv[0]).as_bytes());
1438                        return (ExitStatus::FAILURE, terminal);
1439                    }
1440                };
1441                input = Box::new(BytesInput::new(content));
1442            }
1443            input_is_redirected = true;
1444        }
1445        let effective_stdin: &mut dyn Input = if input_is_redirected {
1446            input.as_mut()
1447        } else {
1448            stdin
1449        };
1450
1451        // Output redirection: capture the command's stdout, then write it to
1452        // the file. Builtins share this path, so `echo x > file` writes only
1453        // to the file (never to the caller's stdout).
1454        let has_redirect = stdout_redirect.is_some();
1455        let has_stderr_redirect = stderr_redirect.is_some();
1456        let mut captured = BytesOutput::new();
1457        let mut captured_stderr = BytesOutput::new();
1458        let mut captured_stdout = BytesOutput::new();
1459        let effective_stdout: &mut dyn Output = if stdout_to_stderr {
1460            &mut captured_stdout
1461        } else if has_redirect {
1462            &mut captured
1463        } else {
1464            stdout
1465        };
1466        // `2>&1` captures stderr into its own buffer and merges it into
1467        // stdout's destination at write-back (a real terminal interleaves;
1468        // the VM approximates by concatenation).
1469        let effective_stderr: &mut dyn Output =
1470            if stderr_to_stdout || has_stderr_redirect || stdout_to_stderr {
1471                &mut captured_stderr
1472            } else {
1473                stderr
1474            };
1475
1476        // Functions and builtins first (function → builtin →
1477        // external).
1478        if name == "break" {
1479            self.loop_break = true;
1480            return (ExitStatus::SUCCESS, terminal);
1481        }
1482        if name == "continue" {
1483            self.loop_continue = true;
1484            return (ExitStatus::SUCCESS, terminal);
1485        }
1486        // Assignments like `export FOO=bar` are parsed as prefix
1487        // assignments by brush-parser. For builtins that handle
1488        // assignments (export), merge them into argv so the builtin
1489        // sees them, mirroring real shells.
1490        let mut builtin_argv = final_argv.clone();
1491        if !assignments.is_empty() && matches!(name.as_str(), "export" | "typeset" | "declare") {
1492            for (key, value) in &assignments {
1493                builtin_argv.push(format!("{key}={value}"));
1494            }
1495        }
1496        let (builtin_status, terminal) = self.try_builtin(
1497            &name,
1498            &builtin_argv,
1499            effective_stdin,
1500            effective_stdout,
1501            effective_stderr,
1502            terminal,
1503        );
1504        if let Some(status) = builtin_status {
1505            if background {
1506                // Builtins do not go through the runtime; record the job so
1507                // `jobs`/`fg`/`bg` stay consistent.
1508                self.runtime
1509                    .record_background_job(final_argv.join(" "), name.clone());
1510            }
1511            // `2>&1` merges stderr into stdout's destination; `1>&2` sends
1512            // stdout to stderr.
1513            if stderr_to_stdout && stderr_redirect.is_none() {
1514                let merged = captured_stderr.bytes().to_vec();
1515                if has_redirect {
1516                    let _ = captured.write(&merged);
1517                } else {
1518                    let _ = stdout.write(&merged);
1519                }
1520            }
1521            if stdout_to_stderr {
1522                let merged = captured_stdout.bytes().to_vec();
1523                let _ = stderr.write(&merged);
1524            }
1525            if let Some((path_str, append)) = &stdout_redirect {
1526                let expanded = self.expand_word(path_str);
1527                let bytes = captured.into_bytes();
1528                if let Err(error) = self.write_redirect(&expanded, &bytes, *append) {
1529                    let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
1530                    return (ExitStatus::FAILURE, terminal);
1531                }
1532            }
1533            if let Some((path_str, append)) = &stderr_redirect {
1534                let expanded = self.expand_word(path_str);
1535                let bytes = captured_stderr.into_bytes();
1536                if let Err(error) = self.write_redirect(&expanded, &bytes, *append) {
1537                    let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
1538                    return (ExitStatus::FAILURE, terminal);
1539                }
1540            }
1541            return (status, terminal);
1542        }
1543
1544        // Resolve external command (with hashing).
1545        let resolution = match self.resolve_with_hash(&name) {
1546            Ok(resolution) => resolution,
1547            Err(error) => {
1548                let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
1549                return (ExitStatus::FAILURE, terminal);
1550            }
1551        };
1552
1553        let resolved = match resolution {
1554            CommandResolution::Found(resolved) => resolved,
1555            CommandResolution::NotFound => {
1556                let _ = stderr.write((self.dialect.command_not_found)(&name).as_bytes());
1557                return (ExitStatus::NOT_FOUND, terminal);
1558            }
1559        };
1560
1561        // A script interpreter (`/bin/sh`, `/bin/bash`, `/bin/zsh`) runs the
1562        // script through this shell — the same implementation, session
1563        // state, and runtime as interactive commands. Like any
1564        // command, the invocation honors the command's redirects, prefix
1565        // environment, and background status.
1566        if let ResolvedExecutable::Bound(executable) = &resolved
1567            && self.interpreter_objects.contains(&executable.object)
1568        {
1569            let status = self.with_prefix_environment(command_environment.as_ref(), |shell| {
1570                if background {
1571                    let pid = shell
1572                        .runtime
1573                        .record_background_job(final_argv.join(" "), executable.name.clone());
1574                    let _ = pid;
1575                }
1576                shell.run_script_invocation(
1577                    &final_argv,
1578                    effective_stdin,
1579                    effective_stdout,
1580                    effective_stderr,
1581                )
1582            });
1583            return (status, terminal);
1584        }
1585
1586        // A shebang script (`#!/bin/zsh`, `#!/usr/bin/env bash`, ...) is
1587        // executed by invoking its interpreter through this shell, so the
1588        // session's shell interprets shell scripts and other
1589        // interpreters resolve normally. For `#!/usr/bin/env NAME`, the
1590        // interpreter is env's argument: the VM's PATH resolution provides
1591        // the same lookup env would perform. Redirects, prefix
1592        // environment, and background status are honored like any command.
1593        if let ResolvedExecutable::Script { shebang, .. } = &resolved {
1594            let interpreter = if shebang.interpreter.ends_with("/env") {
1595                shebang.argument.as_deref().unwrap_or("env")
1596            } else {
1597                shebang.interpreter.as_str()
1598            };
1599            let mut line = shell_quote(interpreter);
1600            if !shebang.interpreter.ends_with("/env")
1601                && let Some(argument) = &shebang.argument
1602            {
1603                line.push(' ');
1604                line.push_str(&shell_quote(argument));
1605            }
1606            for argument in &final_argv {
1607                line.push(' ');
1608                line.push_str(&shell_quote(argument));
1609            }
1610            let status = self.with_prefix_environment(command_environment.as_ref(), |shell| {
1611                if background {
1612                    let pid = shell
1613                        .runtime
1614                        .record_background_job(final_argv.join(" "), interpreter.to_owned());
1615                    let _ = pid;
1616                }
1617                shell.execute(&line, effective_stdin, effective_stdout, effective_stderr)
1618            });
1619            return (status, terminal);
1620        }
1621        let environment = command_environment.as_ref().unwrap_or(&self.environment);
1622        let (result, returned_terminal) = if background {
1623            self.runtime.execute_background(
1624                &resolved,
1625                &final_argv,
1626                &self.credentials,
1627                &self.cwd,
1628                environment,
1629                effective_stdin,
1630                effective_stdout,
1631                effective_stderr,
1632                terminal,
1633            )
1634        } else {
1635            self.runtime.execute(
1636                &resolved,
1637                &final_argv,
1638                &self.credentials,
1639                &self.cwd,
1640                environment,
1641                effective_stdin,
1642                effective_stdout,
1643                effective_stderr,
1644                terminal,
1645            )
1646        };
1647        let status = match result {
1648            Ok(status) => status,
1649            Err(error) => {
1650                let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
1651                return (ExitStatus::FAILURE, returned_terminal);
1652            }
1653        };
1654
1655        if stderr_to_stdout && stderr_redirect.is_none() {
1656            let merged = captured_stderr.bytes().to_vec();
1657            if has_redirect {
1658                let _ = captured.write(&merged);
1659            } else {
1660                let _ = stdout.write(&merged);
1661            }
1662        }
1663        if stdout_to_stderr {
1664            let merged = captured_stdout.bytes().to_vec();
1665            let _ = stderr.write(&merged);
1666        }
1667        if let Some((path_str, append)) = &stdout_redirect {
1668            let expanded = self.expand_word(path_str);
1669            let bytes = captured.into_bytes();
1670            if let Err(error) = self.write_redirect(&expanded, &bytes, *append) {
1671                let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
1672                return (ExitStatus::FAILURE, returned_terminal);
1673            }
1674        }
1675        if let Some((path_str, append)) = &stderr_redirect {
1676            let expanded = self.expand_word(path_str);
1677            let bytes = captured_stderr.into_bytes();
1678            if let Err(error) = self.write_redirect(&expanded, &bytes, *append) {
1679                let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
1680                return (ExitStatus::FAILURE, returned_terminal);
1681            }
1682        }
1683
1684        (status, returned_terminal)
1685    }
1686
1687    /// Executes a `case` clause: the subject word expands once,
1688    /// then each branch's patterns expand and match as globs in order.
1689    /// `;;` ends the clause, `;&` runs the next branch's body
1690    /// unconditionally, and `;;&` keeps matching later branches. A clause
1691    /// nothing matches succeeds, like real shells.
1692    fn execute_case_clause<'t>(
1693        &mut self,
1694        clause: &CaseClauseCommand,
1695        stdin: &mut dyn Input,
1696        stdout: &mut dyn Output,
1697        stderr: &mut dyn Output,
1698        terminal: Option<&'t mut dyn Terminal>,
1699        background: bool,
1700    ) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
1701        let subject = self.expand_word(&clause.value.value);
1702        let mut status = ExitStatus::SUCCESS;
1703        let mut terminal = terminal;
1704        // Set by `;&`: the next branch executes without testing patterns.
1705        let mut forced = false;
1706        for item in &clause.cases {
1707            if !forced {
1708                let matched = item.patterns.iter().any(|pattern| {
1709                    let pattern_text = self.expand_word(&pattern.value);
1710                    crate::expansion::glob_match(&subject, &pattern_text)
1711                });
1712                if !matched {
1713                    continue;
1714                }
1715            }
1716            forced = false;
1717            if let Some(body) = &item.cmd {
1718                let (body_status, returned) = self.execute_compound_list(
1719                    body,
1720                    stdin,
1721                    stdout,
1722                    stderr,
1723                    terminal.take(),
1724                    background,
1725                );
1726                terminal = returned;
1727                status = body_status;
1728            }
1729            match item.post_action {
1730                CaseItemPostAction::ExitCase => break,
1731                CaseItemPostAction::UnconditionallyExecuteNextCaseItem => forced = true,
1732                CaseItemPostAction::ContinueEvaluatingCases => {}
1733            }
1734        }
1735        (status, terminal)
1736    }
1737
1738    /// Executes a script invocation (`sh script.sh`, `bash -c "cmd"`)
1739    /// through this shell.
1740    /// Runs `f` with a command's prefix assignments temporarily visible in
1741    /// the session environment (`FOO=bar sh -c 'echo $FOO'`), restoring the
1742    /// prior values afterwards so the prefix never leaks into the session.
1743    fn with_prefix_environment<R>(
1744        &mut self,
1745        command_environment: Option<&os::Environment>,
1746        f: impl FnOnce(&mut Self) -> R,
1747    ) -> R {
1748        let Some(prefix) = command_environment else {
1749            return f(self);
1750        };
1751        // Snapshot the values the prefix is about to shadow.
1752        let mut prior: Vec<(String, Option<String>)> = Vec::new();
1753        for (key, value) in prefix.iter() {
1754            prior.push((key.to_owned(), self.environment.get(key).map(str::to_owned)));
1755            self.environment.set(key, value);
1756        }
1757        let result = f(self);
1758        for (key, value) in prior.into_iter().rev() {
1759            match value {
1760                Some(value) => self.environment.set(&key, value),
1761                None => {
1762                    self.environment.remove(&key);
1763                }
1764            }
1765        }
1766        result
1767    }
1768
1769    fn run_script_invocation(
1770        &mut self,
1771        argv: &[String],
1772        stdin: &mut dyn Input,
1773        stdout: &mut dyn Output,
1774        stderr: &mut dyn Output,
1775    ) -> ExitStatus {
1776        if argv.get(1).is_some_and(|argument| argument == "-c") {
1777            let script = argv.get(2).cloned().unwrap_or_default();
1778            // After the script text, the first word becomes `$0` and the
1779            // rest are `$1`…, as in real shells.
1780            let mut rest = argv.iter().skip(3).cloned();
1781            let name = rest.next().unwrap_or_else(|| self.dialect.name.to_owned());
1782            self.positionals.push(PositionalFrame {
1783                name,
1784                args: rest.collect(),
1785            });
1786            let status = self.execute(&script, stdin, stdout, stderr);
1787            self.positionals.pop();
1788            return status;
1789        }
1790        let Some(path) = argv.get(1) else {
1791            // `sh` with no arguments reads commands from standard input
1792            // until end of stream, like the real shell. Returns the last
1793            // command's status.
1794            self.positionals.push(PositionalFrame {
1795                name: self.dialect.name.to_owned(),
1796                args: Vec::new(),
1797            });
1798            let mut line = String::new();
1799            let mut status = ExitStatus::SUCCESS;
1800            loop {
1801                match stdin.read_line(&mut line) {
1802                    Ok(true) => {
1803                        status = self.execute(&line, stdin, stdout, stderr);
1804                        line.clear();
1805                        if self.exit_request.is_some() {
1806                            break;
1807                        }
1808                    }
1809                    Ok(false) => break,
1810                    Err(_) => {
1811                        let _ = stderr.write(b"sh: input error\n");
1812                        return ExitStatus::FAILURE;
1813                    }
1814                }
1815            }
1816            self.positionals.pop();
1817            return status;
1818        };
1819        // Script arguments follow the path: `bash script.sh a b` gives
1820        // `$1=a`, `$2=b`, with `$0` the script path.
1821        self.positionals.push(PositionalFrame {
1822            name: path.clone(),
1823            args: argv.iter().skip(2).cloned().collect(),
1824        });
1825        let status = self.execute_script(path, stdin, stdout, stderr);
1826        self.positionals.pop();
1827        status
1828    }
1829
1830    /// Dispatches a function or a builtin (function → builtin).
1831    ///
1832    /// A function call pushes a positional frame (`$0` = the function name,
1833    /// `$1`… = the arguments), so functions can use `$1`, `$#`, `$@`, and
1834    /// the caller's parameters are restored on return.
1835    fn try_builtin<'t>(
1836        &mut self,
1837        name: &str,
1838        argv: &[String],
1839        stdin: &mut dyn Input,
1840        stdout: &mut dyn Output,
1841        stderr: &mut dyn Output,
1842        terminal: Option<&'t mut dyn Terminal>,
1843    ) -> (Option<ExitStatus>, Option<&'t mut dyn Terminal>) {
1844        if let Some(source) = self.functions.get(name).cloned() {
1845            if self.call_depth >= MAX_CALL_DEPTH {
1846                let _ = stderr
1847                    .write(format!("vce: {name}: maximum recursion depth exceeded\n").as_bytes());
1848                return (Some(ExitStatus::FAILURE), terminal);
1849            }
1850            self.positionals.push(PositionalFrame {
1851                name: name.to_owned(),
1852                args: argv.iter().skip(1).cloned().collect(),
1853            });
1854            // A function body is a compound line: the terminal flows
1855            // through it and back to the enclosing command.
1856            let (status, terminal) =
1857                self.execute_with_terminal_returning(&source, stdin, stdout, stderr, terminal);
1858            self.positionals.pop();
1859            return (Some(status), terminal);
1860        }
1861        (
1862            (self.dialect.run_builtin)(self, name, argv, stdin, stdout, stderr),
1863            terminal,
1864        )
1865    }
1866
1867    /// Resolves a command name, consulting the hash table first.
1868    pub fn resolve_with_hash(&mut self, name: &str) -> Result<CommandResolution, os::OsError> {
1869        if let Some(object) = self.hash.get(name).copied() {
1870            if self
1871                .os
1872                .engine()
1873                .metadata(Some(self.credentials.actor()), object)
1874                .is_ok()
1875                && let Some(behavior) = self.runtime.binding(object)
1876            {
1877                return Ok(CommandResolution::Found(ResolvedExecutable::Bound(
1878                    Executable {
1879                        object,
1880                        name: name.to_owned(),
1881                        behavior,
1882                    },
1883                )));
1884            }
1885            self.hash.remove(name);
1886        }
1887        let resolution =
1888            self.runtime
1889                .resolve(name, &self.credentials, &self.cwd, &self.environment)?;
1890        if let CommandResolution::Found(ResolvedExecutable::Bound(executable)) = &resolution {
1891            self.hash.insert(name.to_owned(), executable.object);
1892        }
1893        Ok(resolution)
1894    }
1895
1896    /// Resolves an external command to its filesystem path, without hashing.
1897    pub fn resolve_external_path(&mut self, name: &str) -> Option<String> {
1898        self.resolve_external_paths(name).into_iter().next()
1899    }
1900
1901    /// Every filesystem location that resolves the name as an executable,
1902    /// in PATH order (the Zsh `where` builtin prints them all).
1903    pub fn resolve_external_paths(&mut self, name: &str) -> Vec<String> {
1904        if name.contains('/') {
1905            let path = match self.resolve_path(name) {
1906                Ok(path) => path,
1907                Err(_) => return Vec::new(),
1908            };
1909            return self
1910                .executable_path(&path)
1911                .map(|path| vec![path.to_string()])
1912                .unwrap_or_default();
1913        }
1914        // The usrmerge links make `/bin`, `/sbin`, and `/usr/bin` the same
1915        // directory; one file is reported once, at its first PATH hit.
1916        let mut seen: std::collections::BTreeSet<engine::ObjectId> =
1917            std::collections::BTreeSet::new();
1918        let mut found = Vec::new();
1919        for directory in self.environment.path_entries() {
1920            let candidate = directory.join(&engine::Name::new(name).expect("valid name"));
1921            if let Some(path) = self.executable_path(&candidate)
1922                && let Ok(object) = self
1923                    .os
1924                    .engine()
1925                    .lookup(Some(self.credentials.actor()), &path)
1926                && seen.insert(object)
1927            {
1928                found.push(path.to_string());
1929            }
1930        }
1931        found
1932    }
1933
1934    /// The absolute path of an existing executable, if any.
1935    pub fn executable_path(&self, path: &engine::VirtualPath) -> Option<engine::VirtualPath> {
1936        let actor = Some(self.credentials.actor());
1937        let object = self.os.engine().lookup(actor, path).ok()?;
1938        if self
1939            .os
1940            .engine()
1941            .check(actor, engine::Operation::Execute, object)
1942            .is_ok()
1943        {
1944            Some(path.clone())
1945        } else {
1946            None
1947        }
1948    }
1949
1950    /// The home-relative display form of a path (`/Users/rey` → `~`).
1951    pub fn display_path(&self, path: &engine::VirtualPath) -> String {
1952        if let Some(home) = self.environment.get("HOME")
1953            && let Ok(home_path) = home.parse::<engine::VirtualPath>()
1954            && path.starts_with(&home_path)
1955        {
1956            let mut display = "~".to_owned();
1957            for segment in path.segments().iter().skip(home_path.segments().len()) {
1958                display.push('/');
1959                display.push_str(segment);
1960            }
1961            return display;
1962        }
1963        path.to_string()
1964    }
1965
1966    /// Whether `path` is an existing directory.
1967    pub fn is_directory(&self, path: &engine::VirtualPath) -> bool {
1968        let actor = Some(self.credentials.actor());
1969        match self.os.engine().lookup(actor, path) {
1970            Ok(object) => self.os.engine().children(actor, object).is_ok(),
1971            Err(_) => false,
1972        }
1973    }
1974
1975    /// Expands a glob (`*`, `?`) in an argument via the virtual filesystem.
1976    pub fn expand_glob(&self, pattern: &str) -> Vec<String> {
1977        if !pattern.contains('*') && !pattern.contains('?') {
1978            return vec![pattern.to_owned()];
1979        }
1980        let (directory_text, file_pattern) = match pattern.rfind('/') {
1981            Some(index) => (&pattern[..index], &pattern[index + 1..]),
1982            None => ("", pattern),
1983        };
1984        let directory = if directory_text.is_empty() {
1985            self.cwd.clone()
1986        } else {
1987            match self.resolve_path(directory_text) {
1988                Ok(path) => path,
1989                Err(_) => return vec![pattern.to_owned()],
1990            }
1991        };
1992        let actor = Some(self.credentials.actor());
1993        let object = match self.os.engine().lookup(actor, &directory) {
1994            Ok(object) => object,
1995            Err(_) => return vec![pattern.to_owned()],
1996        };
1997        let mut matches = Vec::new();
1998        if let Ok(entries) = self.os.engine().list(actor, object) {
1999            for (name, _) in entries {
2000                if crate::expansion::glob_match(name.as_str(), file_pattern) {
2001                    let display = if directory_text.is_empty() {
2002                        name.as_str().to_owned()
2003                    } else {
2004                        format!("{directory_text}/{}", name.as_str())
2005                    };
2006                    matches.push(display);
2007                }
2008            }
2009        }
2010        if matches.is_empty() {
2011            vec![pattern.to_owned()]
2012        } else {
2013            matches
2014        }
2015    }
2016
2017    /// Resolves a path argument: absolute paths are used directly, relative
2018    /// paths are joined onto the working directory, honoring `.` and `..`
2019    /// components. An empty argument is an error, like the real tools.
2020    pub fn resolve_path(&self, argument: &str) -> Result<VirtualPath, os::OsError> {
2021        if argument.is_empty() {
2022            return Err(os::OsError::InvalidPathArgument(argument.to_owned()));
2023        }
2024        os::runtime::resolve_path_name(argument, &self.cwd)
2025    }
2026
2027    /// Writes captured output to a redirection target (creating it when
2028    /// needed), or discards it for the null device.
2029    pub fn write_redirect(
2030        &mut self,
2031        path_str: &str,
2032        bytes: &[u8],
2033        append: bool,
2034    ) -> Result<(), os::OsError> {
2035        let path = self.resolve_path(path_str)?;
2036        // The null device discards everything (OS-owned semantics).
2037        if os::fs_util::is_null_device(&path) {
2038            return Ok(());
2039        }
2040        let engine = self.os.engine();
2041        let actor = Some(self.credentials.actor());
2042
2043        // If file exists, either truncate or append.
2044        if let Ok(object) = engine.lookup(actor, &path) {
2045            if append {
2046                engine.append(actor, object, bytes.to_vec())?;
2047            } else {
2048                engine.write(actor, object, bytes.to_vec())?;
2049            }
2050            return Ok(());
2051        }
2052
2053        // Create new file.
2054        let parent_path = path
2055            .parent()
2056            .ok_or_else(|| os::OsError::InvalidPathArgument(path_str.to_owned()))?;
2057        let name_str = path
2058            .name()
2059            .ok_or_else(|| os::OsError::InvalidPathArgument(path_str.to_owned()))?
2060            .to_owned();
2061        let parent = engine.lookup(actor, &parent_path)?;
2062        let name = engine::Name::new(&name_str)?;
2063        engine.create_file_with_options(
2064            actor,
2065            parent,
2066            name,
2067            Some(bytes.to_vec()),
2068            os::unix::attrs::UnixAttrs {
2069                mode: os::FileMode::FILE_644,
2070                gid: self.credentials.effective_gid(),
2071            }
2072            .to_create_options(Some(self.credentials.actor())),
2073        )?;
2074        Ok(())
2075    }
2076
2077    /// Executes a script file line by line.
2078    pub fn execute_script(
2079        &mut self,
2080        script_path: &str,
2081        stdin: &mut dyn Input,
2082        stdout: &mut dyn Output,
2083        stderr: &mut dyn Output,
2084    ) -> ExitStatus {
2085        let path = match self.resolve_path(script_path) {
2086            Ok(path) => path,
2087            Err(error) => {
2088                let _ = stderr.write(format!("{script_path}: {error}\n").as_bytes());
2089                return ExitStatus::FAILURE;
2090            }
2091        };
2092        let object = match self
2093            .os
2094            .engine()
2095            .lookup(Some(self.credentials.actor()), &path)
2096        {
2097            Ok(object) => object,
2098            Err(error) => {
2099                let _ = stderr.write(format!("{script_path}: {error}\n").as_bytes());
2100                return ExitStatus::FAILURE;
2101            }
2102        };
2103        let content = match self
2104            .os
2105            .engine()
2106            .read(Some(self.credentials.actor()), object)
2107        {
2108            Ok(Some(bytes)) => bytes,
2109            Ok(None) => Vec::new(),
2110            Err(error) => {
2111                let _ = stderr.write(format!("{script_path}: {error}\n").as_bytes());
2112                return ExitStatus::FAILURE;
2113            }
2114        };
2115        let text = String::from_utf8_lossy(&content);
2116        let mut last_status = ExitStatus::SUCCESS;
2117        for line in text.lines() {
2118            last_status = self.execute(line, stdin, stdout, stderr);
2119            // `exit` inside a script stops the script; the
2120            // request stays pending so the session ends with its status.
2121            if self.exit_request.is_some() {
2122                break;
2123            }
2124        }
2125        last_status
2126    }
2127
2128    // ------------------------------------------------------------------
2129    // Builtin mechanisms shared between shells, verified to behave the same
2130    // in Bash and Zsh on the reference system. Each shell's builtin table
2131    // decides whether to delegate to these or implement its own semantics.
2132    // ------------------------------------------------------------------
2133
2134    /// The `cd` builtin: changes the working directory, with `cd -`
2135    /// returning to the previous directory (OLDPWD).
2136    pub fn cd_to(
2137        &mut self,
2138        argv: &[String],
2139        stdout: &mut dyn Output,
2140        stderr: &mut dyn Output,
2141    ) -> ExitStatus {
2142        let target = if argv.len() < 2 {
2143            self.environment.get("HOME").unwrap_or("/").to_owned()
2144        } else if argv[1] == "-" {
2145            match &self.previous_cwd {
2146                Some(previous) => previous.to_string(),
2147                None => {
2148                    let _ = stderr.write(b"cd: OLDPWD not set\n");
2149                    return ExitStatus::FAILURE;
2150                }
2151            }
2152        } else {
2153            argv[1].clone()
2154        };
2155
2156        let path = match self.resolve_path(&target) {
2157            Ok(path) => path,
2158            Err(error) => {
2159                let _ = stderr.write(format!("cd: {target}: {error}\n").as_bytes());
2160                return ExitStatus::FAILURE;
2161            }
2162        };
2163
2164        let object = match self
2165            .os
2166            .engine()
2167            .lookup(Some(self.credentials.actor()), &path)
2168        {
2169            Ok(object) => object,
2170            Err(error) => {
2171                let _ = stderr.write(format!("cd: {target}: {error}\n").as_bytes());
2172                return ExitStatus::FAILURE;
2173            }
2174        };
2175
2176        // Verify it is a directory and we have execute permission (via
2177        // children check).
2178        if self
2179            .os
2180            .engine()
2181            .children(Some(self.credentials.actor()), object)
2182            .is_err()
2183        {
2184            let _ = stderr.write(format!("cd: {target}: Not a directory\n").as_bytes());
2185            return ExitStatus::FAILURE;
2186        }
2187
2188        let previous = std::mem::replace(&mut self.cwd, path);
2189        self.previous_cwd = Some(previous);
2190        if argv.get(1).is_some_and(|argument| argument == "-") {
2191            let _ = stdout.write(format!("{}\n", self.cwd).as_bytes());
2192        }
2193        ExitStatus::SUCCESS
2194    }
2195
2196    /// The `pwd` builtin.
2197    pub fn pwd_of(&self, stdout: &mut dyn Output) -> ExitStatus {
2198        let line = format!("{}\n", self.cwd);
2199        let _ = stdout.write(line.as_bytes());
2200        ExitStatus::SUCCESS
2201    }
2202
2203    /// The `jobs` builtin: lists this session's background jobs with their
2204    /// virtual-time state. A pending job shows `Running` until
2205    /// the clock reaches its completion; then it shows `Done`.
2206    pub fn list_jobs(&mut self, stdout: &mut dyn Output) -> ExitStatus {
2207        self.runtime.reconcile();
2208        let now = self.os.engine().time();
2209        let mut index = 0;
2210        for job in self.runtime.jobs().values() {
2211            if !job.background {
2212                continue;
2213            }
2214            index += 1;
2215            let pending = now < job.completion_at;
2216            let line = format!(
2217                "[{}]  {}  {}{}\n",
2218                index,
2219                if pending { "Running" } else { "Done" },
2220                job.command_line,
2221                if pending { " &" } else { "" },
2222            );
2223            let _ = stdout.write(line.as_bytes());
2224        }
2225        ExitStatus::SUCCESS
2226    }
2227
2228    /// Resolves a job spec against the session's background jobs.
2229    ///
2230    /// `%2` is the second job in `jobs` listing order; a bare number is a
2231    /// pid (`fg 1234` also works, like real shells). Returns the pid.
2232    fn resolve_job_spec(&self, argument: Option<&str>) -> Option<u32> {
2233        let argument = argument?;
2234        if let Some(index) = argument.strip_prefix('%') {
2235            let index: usize = index.trim().parse().ok()?;
2236            let pids: Vec<u32> = self
2237                .runtime
2238                .jobs()
2239                .values()
2240                .filter(|job| job.background)
2241                .map(|job| job.pid)
2242                .collect();
2243            pids.get(index.checked_sub(1)?).copied()
2244        } else {
2245            argument.trim().parse().ok()
2246        }
2247    }
2248
2249    /// The `fg` builtin: brings a background job to the foreground. Waiting
2250    /// for a pending job is advancing the virtual clock to its completion
2251    /// time; the invocation's exit status is the job's.
2252    pub fn foreground_job(
2253        &mut self,
2254        argv: &[String],
2255        stdout: &mut dyn Output,
2256        stderr: &mut dyn Output,
2257    ) -> ExitStatus {
2258        self.runtime.reconcile();
2259        let spec = self.resolve_job_spec(argv.get(1).map(String::as_str));
2260        let Some(job) = spec.and_then(|pid| self.runtime.jobs().get(&pid)) else {
2261            let _ = stderr.write(b"fg: no such job\n");
2262            return ExitStatus::FAILURE;
2263        };
2264        let line = job.command_line.clone();
2265        let due = job.completion_at;
2266        let status = job.exit_status;
2267        if self.os.engine().time() < due {
2268            let remaining = due
2269                .as_nanos()
2270                .saturating_sub(self.os.engine().time().as_nanos());
2271            self.os
2272                .engine()
2273                .advance_time(std::time::Duration::from_nanos(remaining));
2274            self.runtime.reconcile();
2275        }
2276        let _ = stdout.write(format!("{line}\n").as_bytes());
2277        status.unwrap_or(ExitStatus::SUCCESS)
2278    }
2279
2280    /// The `bg` builtin: re-reports a background job as running in the
2281    /// background. Execution is sequential, so there is nothing to resume:
2282    /// a pending job is already running, and a finished one stays finished.
2283    pub fn background_job(
2284        &mut self,
2285        argv: &[String],
2286        stdout: &mut dyn Output,
2287        stderr: &mut dyn Output,
2288    ) -> ExitStatus {
2289        self.runtime.reconcile();
2290        let spec = self.resolve_job_spec(argv.get(1).map(String::as_str));
2291        let Some(job) = spec.and_then(|pid| self.runtime.jobs().get(&pid)) else {
2292            let _ = stderr.write(b"bg: no such job\n");
2293            return ExitStatus::FAILURE;
2294        };
2295        let line = job.command_line.clone();
2296        let _ = stdout.write(format!("{line} &\n").as_bytes());
2297        ExitStatus::SUCCESS
2298    }
2299
2300    /// The `wait` builtin: advances the virtual clock until background jobs
2301    /// complete. With no arguments, waits for all pending ones;
2302    /// otherwise waits for each `%spec`/pid argument. Returns the last
2303    /// waited job's exit status.
2304    pub fn wait_for_jobs(&mut self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
2305        self.runtime.reconcile();
2306        let targets: Vec<u32> = if argv.len() <= 1 {
2307            self.runtime
2308                .jobs()
2309                .values()
2310                .filter(|job| job.background && job.state == os::runtime::ProcessState::Running)
2311                .map(|job| job.pid)
2312                .collect()
2313        } else {
2314            let mut targets = Vec::new();
2315            for argument in &argv[1..] {
2316                match self.resolve_job_spec(Some(argument)) {
2317                    Some(pid) => targets.push(pid),
2318                    None => {
2319                        let _ = stderr.write(format!("wait: {argument}: no such job\n").as_bytes());
2320                        return ExitStatus::FAILURE;
2321                    }
2322                }
2323            }
2324            targets
2325        };
2326        let mut last = ExitStatus::SUCCESS;
2327        for pid in targets {
2328            let Some(job) = self.runtime.jobs().get(&pid) else {
2329                let _ = stderr.write(format!("wait: {pid}: no such job\n").as_bytes());
2330                return ExitStatus::FAILURE;
2331            };
2332            let due = job.completion_at;
2333            let status = job.exit_status;
2334            if self.os.engine().time() < due {
2335                let remaining = due
2336                    .as_nanos()
2337                    .saturating_sub(self.os.engine().time().as_nanos());
2338                self.os
2339                    .engine()
2340                    .advance_time(std::time::Duration::from_nanos(remaining));
2341            }
2342            last = status.unwrap_or(ExitStatus::SUCCESS);
2343        }
2344        self.runtime.reconcile();
2345        last
2346    }
2347
2348    /// The `echo` builtin, shared by Bash and Zsh: `-n` suppresses the
2349    /// newline, `-e`/`-E` enable and disable escape processing. The default
2350    /// escape behavior is the dialect's (Bash off, Zsh on).
2351    pub fn builtin_echo(&self, argv: &[String], stdout: &mut dyn Output) -> ExitStatus {
2352        let mut no_newline = false;
2353        let mut escapes = self.dialect.echo_escapes_default;
2354        let mut start = 1;
2355        while let Some(argument) = argv.get(start) {
2356            if argument == "-n" && !no_newline {
2357                no_newline = true;
2358                start += 1;
2359            } else if argument == "-e" {
2360                escapes = true;
2361                start += 1;
2362            } else if argument == "-E" {
2363                escapes = false;
2364                start += 1;
2365            } else {
2366                break;
2367            }
2368        }
2369        let mut output = String::new();
2370        for (index, argument) in argv.iter().skip(start).enumerate() {
2371            if index > 0 {
2372                output.push(' ');
2373            }
2374            output.push_str(argument);
2375        }
2376        if escapes {
2377            output = interpret_escapes(&output);
2378        }
2379        if !no_newline {
2380            output.push('\n');
2381        }
2382        let _ = stdout.write(output.as_bytes());
2383        ExitStatus::SUCCESS
2384    }
2385
2386    /// The `export` builtin, shared by Bash and Zsh: assignments set the
2387    /// environment; with no arguments the listing prefix is the dialect's
2388    /// (`declare -x ` in Bash, `export ` in Zsh).
2389    pub fn builtin_export(
2390        &mut self,
2391        argv: &[String],
2392        stdout: &mut dyn Output,
2393        stderr: &mut dyn Output,
2394    ) -> ExitStatus {
2395        if argv.len() < 2 {
2396            for (key, value) in self.environment().iter() {
2397                let line = format!("{}{key}={value}\n", self.dialect.export_prefix);
2398                let _ = stdout.write(line.as_bytes());
2399            }
2400            return ExitStatus::SUCCESS;
2401        }
2402        for assignment in argv.iter().skip(1) {
2403            if let Some((key, value)) = assignment.split_once('=') {
2404                self.environment_mut().set(key, value);
2405            } else {
2406                let _ =
2407                    stderr.write(format!("export: invalid argument '{assignment}'\n").as_bytes());
2408                return ExitStatus::FAILURE;
2409            }
2410        }
2411        ExitStatus::SUCCESS
2412    }
2413
2414    /// The `history` builtin, identical in Bash and Zsh: prints the
2415    /// numbered command history.
2416    pub fn builtin_history(&self, stdout: &mut dyn Output) -> ExitStatus {
2417        for (index, line) in self.history().iter().enumerate() {
2418            let _ = stdout.write(format!("{:5}  {}\n", index + 1, line).as_bytes());
2419        }
2420        ExitStatus::SUCCESS
2421    }
2422
2423    /// The `alias` builtin, shared by Bash and Zsh: definitions set
2424    /// aliases; with no arguments the listing prefix is the dialect's
2425    /// (`alias ` in Bash, nothing in Zsh).
2426    pub fn builtin_alias(
2427        &mut self,
2428        argv: &[String],
2429        stdout: &mut dyn Output,
2430        stderr: &mut dyn Output,
2431    ) -> ExitStatus {
2432        if argv.len() == 1 {
2433            for (name, expansion) in self.aliases() {
2434                let _ = stdout.write(
2435                    format!("{}{name}='{expansion}'\n", self.dialect.alias_prefix).as_bytes(),
2436                );
2437            }
2438            return ExitStatus::SUCCESS;
2439        }
2440        for definition in argv.iter().skip(1) {
2441            if let Some((name, expansion)) = definition.split_once('=') {
2442                let expansion = expansion.trim_matches('\'').trim_matches('"').to_owned();
2443                self.aliases_mut().insert(name.to_owned(), expansion);
2444            } else if let Some(expansion) = self.aliases().get(definition) {
2445                let _ = stdout.write(
2446                    format!("{}{definition}='{expansion}'\n", self.dialect.alias_prefix).as_bytes(),
2447                );
2448            } else {
2449                let _ = stderr.write(format!("alias: {definition}: not found\n").as_bytes());
2450                return ExitStatus::FAILURE;
2451            }
2452        }
2453        ExitStatus::SUCCESS
2454    }
2455
2456    /// The `unalias` builtin, identical in Bash and Zsh.
2457    pub fn builtin_unalias(&mut self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
2458        if argv.len() < 2 {
2459            let _ = stderr.write(b"unalias: not enough arguments\n");
2460            return ExitStatus::FAILURE;
2461        }
2462        for name in argv.iter().skip(1) {
2463            if name == "-a" {
2464                self.aliases_mut().clear();
2465                continue;
2466            }
2467            if self.aliases_mut().remove(name).is_none() {
2468                let _ = stderr.write(format!("unalias: {name}: not found\n").as_bytes());
2469                return ExitStatus::FAILURE;
2470            }
2471        }
2472        ExitStatus::SUCCESS
2473    }
2474
2475    /// How a name resolves for the `type`/`which`/`where`/`whence` family:
2476    /// one shared precedence walk (alias → function → builtin → PATH), with
2477    /// the phrasing owned by each shell's reporter.
2478    pub fn resolve_name(&mut self, name: &str, is_builtin: fn(&str) -> bool) -> NameResolution {
2479        let alias = self.aliases().get(name).cloned();
2480        let function = self.functions_mut().contains_key(name);
2481        let builtin = is_builtin(name);
2482        let paths = self.resolve_external_paths(name);
2483        NameResolution {
2484            alias,
2485            function,
2486            builtin,
2487            paths,
2488        }
2489    }
2490
2491    /// The `hash` builtin: manages the command hash table.
2492    pub fn hash_table(
2493        &mut self,
2494        argv: &[String],
2495        stdout: &mut dyn Output,
2496        stderr: &mut dyn Output,
2497    ) -> ExitStatus {
2498        if argv.contains(&"-r".to_owned()) {
2499            self.hash.clear();
2500            return ExitStatus::SUCCESS;
2501        }
2502        if argv.len() == 1 {
2503            for (name, object) in &self.hash {
2504                let _ = stdout.write(format!("{name}={object}\n").as_bytes());
2505            }
2506            return ExitStatus::SUCCESS;
2507        }
2508        for name in argv.iter().skip(1) {
2509            if let Some(stripped) = name.strip_prefix('-') {
2510                let _ = stderr.write(format!("hash: invalid option -- '{stripped}'\n").as_bytes());
2511                return ExitStatus::FAILURE;
2512            }
2513            match self
2514                .runtime
2515                .resolve(name, &self.credentials, &self.cwd, &self.environment)
2516            {
2517                Ok(CommandResolution::Found(ResolvedExecutable::Bound(executable))) => {
2518                    self.hash.insert(name.clone(), executable.object);
2519                }
2520                _ => {
2521                    let _ = stderr.write(format!("hash: {name}: not found\n").as_bytes());
2522                    return ExitStatus::FAILURE;
2523                }
2524            }
2525        }
2526        ExitStatus::SUCCESS
2527    }
2528
2529    /// The `dirs` builtin: prints the directory stack, current directory
2530    /// first, with `~` for the home directory.
2531    pub fn print_dirs(&self, stdout: &mut dyn Output) -> ExitStatus {
2532        let mut parts: Vec<String> = vec![self.display_path(&self.cwd)];
2533        for entry in &self.dir_stack {
2534            parts.push(self.display_path(entry));
2535        }
2536        let _ = stdout.write(format!("{}\n", parts.join(" ")).as_bytes());
2537        ExitStatus::SUCCESS
2538    }
2539
2540    /// The `pushd` builtin: pushes the current directory onto the stack and
2541    /// changes to the argument.
2542    pub fn push_directory(
2543        &mut self,
2544        argv: &[String],
2545        stdout: &mut dyn Output,
2546        stderr: &mut dyn Output,
2547    ) -> ExitStatus {
2548        if argv.len() < 2 {
2549            let _ = stderr.write(b"pushd: no other directory\n");
2550            return ExitStatus::FAILURE;
2551        }
2552        let target = &argv[1];
2553        let path = match self.resolve_path(target) {
2554            Ok(path) => path,
2555            Err(error) => {
2556                let _ = stderr.write(format!("pushd: {target}: {error}\n").as_bytes());
2557                return ExitStatus::FAILURE;
2558            }
2559        };
2560        if !self.is_directory(&path) {
2561            let _ = stderr.write(format!("pushd: {target}: Not a directory\n").as_bytes());
2562            return ExitStatus::FAILURE;
2563        }
2564        self.dir_stack.push(self.cwd.clone());
2565        self.cwd = path;
2566        self.print_dirs(stdout)
2567    }
2568
2569    /// The `popd` builtin: pops the top of the directory stack and changes
2570    /// into it.
2571    pub fn pop_directory(
2572        &mut self,
2573        _argv: &[String],
2574        stdout: &mut dyn Output,
2575        stderr: &mut dyn Output,
2576    ) -> ExitStatus {
2577        let Some(previous) = self.dir_stack.pop() else {
2578            let _ = stderr.write(b"popd: directory stack empty\n");
2579            return ExitStatus::FAILURE;
2580        };
2581        self.cwd = previous;
2582        self.print_dirs(stdout)
2583    }
2584
2585    /// The `unset` builtin: removes variables, or functions with `-f`.
2586    pub fn unset_names(&mut self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
2587        let mut functions = false;
2588        let mut names: Vec<&String> = Vec::new();
2589        let mut index = 1usize;
2590        while let Some(argument) = argv.get(index) {
2591            if argument == "-f" {
2592                functions = true;
2593            } else if argument == "-v" {
2594                functions = false;
2595            } else {
2596                names.push(argument);
2597            }
2598            index += 1;
2599        }
2600        if names.is_empty() {
2601            let _ = stderr.write(b"unset: not enough arguments\n");
2602            return ExitStatus::FAILURE;
2603        }
2604        for name in names {
2605            if functions {
2606                self.functions.remove(name.as_str());
2607            } else {
2608                self.environment.remove(name);
2609            }
2610        }
2611        ExitStatus::SUCCESS
2612    }
2613
2614    /// The `source`/`.` builtin: reads the named file and executes it in
2615    /// the current shell.
2616    pub fn source_file(
2617        &mut self,
2618        argv: &[String],
2619        stdin: &mut dyn Input,
2620        stdout: &mut dyn Output,
2621        stderr: &mut dyn Output,
2622    ) -> ExitStatus {
2623        let Some(target) = argv.get(1) else {
2624            let _ = stderr.write(b"source: filename argument required\n");
2625            return ExitStatus::FAILURE;
2626        };
2627        let path = match self.resolve_path(target) {
2628            Ok(path) => path,
2629            Err(error) => {
2630                let _ = stderr.write(format!("source: {target}: {error}\n").as_bytes());
2631                return ExitStatus::FAILURE;
2632            }
2633        };
2634        let object = match self
2635            .os
2636            .engine()
2637            .lookup(Some(self.credentials.actor()), &path)
2638        {
2639            Ok(object) => object,
2640            Err(error) => {
2641                let _ = stderr.write(format!("source: {target}: {error}\n").as_bytes());
2642                return ExitStatus::FAILURE;
2643            }
2644        };
2645        let Some(bytes) = self
2646            .os
2647            .engine()
2648            .read(Some(self.credentials.actor()), object)
2649            .ok()
2650            .flatten()
2651        else {
2652            let _ = stderr.write(format!("source: {target}: not readable\n").as_bytes());
2653            return ExitStatus::FAILURE;
2654        };
2655        let source = String::from_utf8_lossy(&bytes);
2656        // Sourced files see `$0` = their name and `$1`… = any extra
2657        // arguments, as in real shells.
2658        self.positionals.push(PositionalFrame {
2659            name: target.clone(),
2660            args: argv.iter().skip(2).cloned().collect(),
2661        });
2662        let status = self.execute(source.trim_end(), stdin, stdout, stderr);
2663        self.positionals.pop();
2664        status
2665    }
2666
2667    /// The `:` null command: does nothing and succeeds.
2668    pub fn null_command(&self) -> ExitStatus {
2669        ExitStatus::SUCCESS
2670    }
2671
2672    /// The `clear` builtin: emits the terminal clear sequence (including
2673    /// the scrollback erase, like zsh's clear on macOS).
2674    pub fn clear_screen(&self, stdout: &mut dyn Output) -> ExitStatus {
2675        let _ = stdout.write(b"\x1b[3J\x1b[H\x1b[2J");
2676        ExitStatus::SUCCESS
2677    }
2678}
2679
2680/// Parses a line into a program using the brush-parser grammar.
2681fn parse_program(line: &str) -> Result<ast::Program, brush_parser::ParseError> {
2682    let mut parser = Parser::new(
2683        Cursor::new(line.as_bytes()),
2684        &ParserOptions::default(),
2685        &SourceInfo::default(),
2686    );
2687    parser.parse_program()
2688}
2689
2690/// The virtual host name, read from `/etc/hostname` as root.
2691pub fn hostname_from_etc(os: &UnixOs) -> String {
2692    os::unix::unix_os::hostname(os)
2693}
2694
2695/// Returns `true` when `input` is an incomplete shell construct that needs
2696/// more input before it can be executed: an open quote, an unterminated here
2697/// document, or an unfinished compound command.
2698///
2699/// Callers (the application) use this to buffer lines and show a secondary
2700/// prompt, as real shells do.
2701pub fn needs_continuation(input: &str) -> bool {
2702    parse_program(input).is_err_and(|error| match error {
2703        brush_parser::ParseError::ParsingAtEndOfInput => true,
2704        // Only tokenization failures that genuinely mean "input incomplete"
2705        // (unterminated quotes, here-docs, substitutions) continue the
2706        // prompt; a permanently invalid stream is a syntax error, not a
2707        // prompt that never ends.
2708        brush_parser::ParseError::Tokenizing { inner, .. } => inner.is_incomplete(),
2709        brush_parser::ParseError::ParsingNearToken(_) => false,
2710    })
2711}
2712
2713/// The single stdout redirection of a compound command, if any.
2714fn compound_stdout_redirect(redirects: Option<&ast::RedirectList>) -> Option<(String, bool)> {
2715    let list = redirects?;
2716    for redirect in &list.0 {
2717        if let IoRedirect::File(fd, kind, target) = redirect {
2718            let filename = match target {
2719                IoFileRedirectTarget::Filename(word) => Some(word.value.clone()),
2720                _ => None,
2721            };
2722            if let Some(filename) = filename {
2723                let append = matches!(kind, IoFileRedirectKind::Append);
2724                if fd.is_none_or(|n| n == 1) {
2725                    return Some((filename, append));
2726                }
2727            }
2728        }
2729    }
2730    None
2731}
2732
2733/// The content of a here-document or here-string redirection marker.
2734fn heredoc_content(redirect: &str) -> Option<Vec<u8>> {
2735    redirect
2736        .strip_prefix("\0heredoc:")
2737        .or_else(|| redirect.strip_prefix("\0heredoc-expand:"))
2738        .map(|content| content.trim_end_matches('\0').as_bytes().to_vec())
2739        .or_else(|| {
2740            redirect
2741                .strip_prefix("\0herestring:")
2742                .map(|content| content.trim_end_matches('\0').as_bytes().to_vec())
2743        })
2744}
2745
2746/// Whether a here-document marker requests word expansion.
2747fn heredoc_expands(redirect: &str) -> bool {
2748    redirect.starts_with("\0heredoc-expand:")
2749}
2750
2751/// Quotes a word for re-parsing after alias expansion.
2752fn shell_quote(word: &str) -> String {
2753    if word.is_empty()
2754        || word
2755            .chars()
2756            .any(|c| c.is_whitespace() || "\\'\"$`&|;<>()[]{}*?!#~=".contains(c))
2757    {
2758        format!("'{}'", word.replace('\'', "'\\''"))
2759    } else {
2760        word.to_owned()
2761    }
2762}
2763
2764/// `assignment.name` string access across brush AST versions.
2765trait AssignmentNameString {
2766    /// The assignment's variable name.
2767    fn name_string(&self) -> String;
2768}
2769
2770impl AssignmentNameString for ast::AssignmentName {
2771    fn name_string(&self) -> String {
2772        match self {
2773            ast::AssignmentName::VariableName(name) => name.clone(),
2774            ast::AssignmentName::ArrayElementName(name, index) => {
2775                format!("{name}[{index}]")
2776            }
2777        }
2778    }
2779}
2780
2781/// Formats a virtual timestamp as a Unix-style "Last login" line, for
2782/// example `Fri Aug 21 01:16:56` (the macOS convention: weekday, month,
2783/// day, and clock time, with no year).
2784pub fn format_login_line(timestamp: engine::Timestamp) -> String {
2785    os::datetime::format_timestamp(timestamp, "%a %b %d %H:%M:%S")
2786}