Skip to main content

shrub_core/
shell.rs

1//! Module defining the core shell structure and behavior.
2
3use std::borrow::Cow;
4use std::collections::HashMap;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use tokio::sync::Mutex;
9
10use crate::env::ShellEnvironment;
11use crate::options::RuntimeOptions;
12use crate::{
13    ExecutionControlFlow, ExecutionResult, builtins, error, extensions, functions, interfaces,
14    jobs, keywords, openfiles, pathcache, wellknownvars,
15};
16
17/// Type for storing a key bindings helper.
18pub type KeyBindingsHelper = Arc<Mutex<dyn interfaces::KeyBindings>>;
19
20/// Type alias for shell file descriptors.
21pub type ShellFd = i32;
22
23// NOTE: The submodule files below (e.g., `shell/traps.rs`,
24// `shell/callstack.rs`) contain `impl Shell<SE>` blocks that provide methods
25// coordinating with types defined in the corresponding top-level modules (e.g.,
26// `traps.rs`, `callstack.rs`). This is an intentional layered architecture:
27// top-level modules define domain types and data structures, while
28// shell/ submodules implement Shell methods that operate on those types.
29
30mod builder;
31mod builtin_registry;
32mod callstack;
33mod completion;
34mod env;
35mod execution;
36mod expansion;
37mod fs;
38mod funcs;
39mod history;
40mod initscripts;
41mod io;
42mod job_control;
43mod parsing;
44mod prompts;
45mod readline;
46mod snapshot;
47mod state;
48mod traps;
49
50pub use builder::{CreateOptions, ShellBuilder, ShellBuilderState};
51pub use initscripts::{ProfileLoadBehavior, RcLoadBehavior};
52pub use state::ShellState;
53
54/// Represents an instance of a shell.
55///
56/// # Type Parameters
57///
58/// * `SE` - The shell extensions implementation to use. These extensions are
59///   statically injected into the shell at compile time to provide custom
60///   behavior. When unspecified, defaults to `DefaultShellExtensions`, which
61///   provide standard behavior.
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub struct Shell<SE: extensions::ShellExtensions = extensions::DefaultShellExtensions> {
64    /// Injected error behavior.
65    #[cfg_attr(feature = "serde", serde(skip, default = "default_error_formatter"))]
66    error_formatter: SE::ErrorFormatter,
67
68    /// Trap handler configuration for the shell.
69    traps: crate::traps::TrapHandlerConfig,
70
71    /// Manages files opened and accessible via redirection operators.
72    open_files: openfiles::OpenFiles,
73
74    /// The current working directory.
75    working_dir: PathBuf,
76
77    /// The shell environment, containing shell variables.
78    env: ShellEnvironment,
79
80    /// Shell function definitions.
81    funcs: functions::FunctionEnv,
82
83    /// Runtime shell options.
84    options: RuntimeOptions,
85
86    /// State of managed jobs.
87    /// TODO(serde): Need to warn somehow that jobs cannot be serialized.
88    #[cfg_attr(feature = "serde", serde(skip))]
89    jobs: jobs::JobManager,
90
91    /// Shell aliases.
92    aliases: HashMap<String, String>,
93
94    /// The status of the last completed command.
95    last_exit_status: u8,
96
97    /// Tracks changes to `last_exit_status`. Assignment-only commands observe
98    /// it to tell whether an expansion set a status (see `interp.rs`), so
99    /// code that rolls back `$?` must roll this back too.
100    last_exit_status_change_count: usize,
101
102    /// The status of each of the commands in the last pipeline.
103    last_pipeline_statuses: Vec<u8>,
104
105    /// Clone depth from the original ancestor shell.
106    depth: usize,
107
108    /// Shell name
109    name: Option<String>,
110
111    /// Positional shell arguments (not including shell name).
112    args: Vec<String>,
113
114    /// Shell version
115    version: Option<String>,
116
117    /// Detailed display string for the shell
118    product_display_str: Option<String>,
119
120    /// Function/script call stack.
121    call_stack: crate::callstack::CallStack,
122
123    /// Directory stack used by pushd et al.
124    directory_stack: Vec<PathBuf>,
125
126    /// Programmable completion state.
127    completion: crate::completion::State,
128
129    /// Shell built-in commands.
130    #[cfg_attr(feature = "serde", serde(skip))]
131    builtins: HashMap<String, builtins::Registration<SE>>,
132
133    /// Shell program location cache.
134    program_location_cache: pathcache::PathCache,
135
136    /// Last "SECONDS" captured time.
137    last_stopwatch_time: std::time::SystemTime,
138
139    /// Last "SECONDS" offset requested.
140    last_stopwatch_offset: u32,
141
142    /// Parser implementation to use.
143    #[cfg_attr(feature = "serde", serde(skip))]
144    parser_impl: crate::parser::ParserImpl,
145
146    /// Key bindings for the shell, optionally implemented by an interactive
147    /// shell.
148    #[cfg_attr(feature = "serde", serde(skip))]
149    key_bindings: Option<KeyBindingsHelper>,
150
151    /// History of commands executed in the shell.
152    history: Option<crate::history::History>,
153}
154
155impl<SE: extensions::ShellExtensions> Clone for Shell<SE> {
156    fn clone(&self) -> Self {
157        Self {
158            error_formatter: self.error_formatter.clone(),
159            traps: self.traps.clone(),
160            open_files: self.open_files.clone(),
161            working_dir: self.working_dir.clone(),
162            env: self.env.clone(),
163            funcs: self.funcs.clone(),
164            options: self.options.clone(),
165            jobs: jobs::JobManager::new(),
166            aliases: self.aliases.clone(),
167            last_exit_status: self.last_exit_status,
168            last_exit_status_change_count: self.last_exit_status_change_count,
169            last_pipeline_statuses: self.last_pipeline_statuses.clone(),
170            name: self.name.clone(),
171            args: self.args.clone(),
172            version: self.version.clone(),
173            product_display_str: self.product_display_str.clone(),
174            call_stack: {
175                // Subshells must not inherit the parent's "currently handling
176                // signal X" state; otherwise a trap handler
177                // that spawns a subshell would see itself
178                // as already inside that handler and skip re-entrant delivery.
179                let mut cs = self.call_stack.clone();
180                cs.clear_active_trap_signals();
181                cs
182            },
183            directory_stack: self.directory_stack.clone(),
184            // A subshell of a completion function (e.g. `$(compgen ...)`) is in that
185            // completion too. Like a forked subshell in bash, it changes only its own copy
186            // (e.g. with `compopt`), which its parent doesn't see.
187            completion: self.completion.clone(),
188            builtins: self.builtins.clone(),
189            program_location_cache: self.program_location_cache.clone(),
190            last_stopwatch_time: self.last_stopwatch_time,
191            last_stopwatch_offset: self.last_stopwatch_offset,
192            parser_impl: self.parser_impl,
193            key_bindings: self.key_bindings.clone(),
194            history: self.history.clone(),
195            depth: self.depth + 1,
196        }
197    }
198}
199
200impl<SE: extensions::ShellExtensions> AsRef<Self> for Shell<SE> {
201    fn as_ref(&self) -> &Self {
202        self
203    }
204}
205
206impl<SE: extensions::ShellExtensions> AsMut<Self> for Shell<SE> {
207    fn as_mut(&mut self) -> &mut Self {
208        self
209    }
210}
211
212impl<SE: extensions::ShellExtensions> Shell<SE> {
213    /// Returns a new shell instance created with the given options.
214    /// Does *not* load any configuration files (e.g., bashrc).
215    ///
216    /// # Arguments
217    ///
218    /// * `options` - The options to use when creating the shell.
219    pub(crate) fn new(options: CreateOptions<SE>) -> Result<Self, error::Error> {
220        // Compute runtime options before moving fields out of `options`.
221        let runtime_options = RuntimeOptions::defaults_from(&options);
222
223        // Instantiate the shell with some defaults.
224        let mut shell = Self {
225            error_formatter: options.error_formatter,
226            open_files: openfiles::OpenFiles::new(),
227            options: runtime_options,
228            name: options.shell_name,
229            args: options.shell_args.unwrap_or_default(),
230            version: options.shell_version,
231            product_display_str: options.shell_product_display_str,
232            working_dir: options.working_dir.map_or_else(std::env::current_dir, Ok)?,
233            builtins: options.builtins,
234            parser_impl: options.parser,
235            key_bindings: options.key_bindings,
236            ..Self::default()
237        };
238
239        // Add in any open files provided.
240        shell.open_files.update_from(options.fds.into_iter());
241
242        // TODO(patterns): Without this a script that sets extglob will fail
243        // because we parse the entire script with the same settings.
244        shell.options.extended_globbing = true;
245
246        // If requested, seed parameters from environment.
247        if !options.do_not_inherit_env {
248            wellknownvars::inherit_env_vars(&mut shell)?;
249        }
250
251        // If requested, set well-known variables.
252        if !options.skip_well_known_vars {
253            wellknownvars::init_well_known_vars(&mut shell)?;
254        }
255
256        // Set any provided variables.
257        for (var_name, var_value) in options.vars {
258            shell.env.set_global(var_name, var_value)?;
259        }
260
261        // Set up history, if relevant. The history file itself is loaded later,
262        // once startup files have run, since they may change HISTFILE.
263        if shell.options.enable_command_history {
264            shell.history = Some(crate::history::History::default());
265        }
266
267        Ok(shell)
268    }
269}
270
271impl<SE: extensions::ShellExtensions> Shell<SE> {
272    /// Increments the interactive line offset in the shell by the indicated
273    /// number of lines.
274    ///
275    /// # Arguments
276    ///
277    /// * `delta` - The number of lines to increment the current line offset by.
278    pub fn increment_interactive_line_offset(&mut self, delta: usize) {
279        self.call_stack.increment_current_line_offset(delta);
280    }
281
282    /// Updates the currently executing command in the shell.
283    pub fn set_current_cmd(&mut self, cmd: &impl shrub_parser::ast::Node) {
284        self.call_stack
285            .set_current_pos(cmd.location().map(|span| span.start));
286    }
287
288    /// Updates the `$_` shell variable (last-argument of the previous simple
289    /// command).
290    ///
291    /// Passes `Some(last_arg)` to record the last argument of the just-executed
292    /// command, or `None` to clear `$_` (used for assignment-only statements,
293    /// which bash treats as having no "last argument").
294    ///
295    /// The update is applied in-place so that attributes on `_` (notably
296    /// `readonly`) are preserved: attempting to update a readonly `_` is a
297    /// silent no-op, matching bash's observable stdout behavior.
298    pub(crate) fn update_last_arg_variable(&mut self, last_arg: Option<String>) {
299        // Bash refuses to update a readonly `_`, emitting an error to stderr
300        // on each attempt. We silently skip the update here — the observable
301        // stdout effect ($_ stays unchanged) matches bash; the missing stderr
302        // diagnostics are harmless.
303        if self
304            .env
305            .get_using_policy("_", crate::env::EnvironmentLookup::Anywhere)
306            .is_some_and(|v| v.is_readonly())
307        {
308            return;
309        }
310
311        // Replace the variable entirely (fresh, non-exported). This matches
312        // bash, which never exports `_` — even under `set -a` — and always
313        // clears any previously-set attributes (except readonly, handled
314        // above).
315        let value = last_arg.unwrap_or_default();
316        let _ = self
317            .env
318            .set_global("_", crate::variables::ShellVariable::new(value));
319    }
320
321    /// Captures the state the last command left behind; see
322    /// [`SavedCommandStatus`].
323    pub fn save_command_status(&self) -> SavedCommandStatus {
324        SavedCommandStatus {
325            exit_status: self.last_exit_status,
326            exit_status_change_count: self.last_exit_status_change_count,
327            pipeline_statuses: self.last_pipeline_statuses.clone(),
328            last_arg: self.env_str("_").map(|value| value.into_owned()),
329        }
330    }
331
332    /// Reapplies a snapshot, exit-status change counter included. Consumes it;
333    /// `clone` it to put the same one back more than once, e.g. between
334    /// successive hook functions.
335    ///
336    /// # Arguments
337    ///
338    /// * `saved` - The snapshot to restore.
339    pub fn restore_command_status(&mut self, saved: SavedCommandStatus) {
340        self.last_pipeline_statuses = saved.pipeline_statuses;
341        // Assigned directly rather than through `set_last_exit_status`, which
342        // would bump the change counter we're about to put back.
343        self.last_exit_status = saved.exit_status;
344        self.last_exit_status_change_count = saved.exit_status_change_count;
345        match saved.last_arg {
346            Some(last_arg) => self.update_last_arg_variable(Some(last_arg)),
347            // `_` was unset when the snapshot was taken, so put it back that way. Unsetting
348            // a readonly `_` fails; ignore that, as `update_last_arg_variable` does.
349            None => _ = self.env.unset("_"),
350        }
351    }
352
353    /// Applies errexit semantics to a result if enabled and appropriate.
354    /// This should be called at "statement boundaries" where errexit should be
355    /// checked.
356    ///
357    /// # Arguments
358    ///
359    /// * `result` - The execution result to potentially modify.
360    pub const fn apply_errexit_if_enabled(&self, result: &mut ExecutionResult) {
361        if self.options.exit_on_nonzero_command_exit
362            && !result.is_success()
363            && result.is_normal_flow()
364        {
365            result.next_control_flow = ExecutionControlFlow::ExitShell;
366        }
367    }
368
369    /// Returns the keywords that are reserved by the shell, in the order bash
370    /// lists them.
371    pub(crate) fn get_keywords(&self) -> impl IntoIterator<Item = &'static str> {
372        keywords::keywords(self.options.sh_mode)
373    }
374
375    /// Checks if the given string is a keyword reserved in this shell.
376    ///
377    /// # Arguments
378    ///
379    /// * `s` - The string to check.
380    pub fn is_keyword(&self, s: &str) -> bool {
381        keywords::keywords(self.options.sh_mode).any(|keyword| keyword == s)
382    }
383
384    pub(crate) const fn last_exit_status_change_count(&self) -> usize {
385        self.last_exit_status_change_count
386    }
387}
388
389/// Snapshot of the state the last command left behind: `$?`, `PIPESTATUS`, and
390/// `$_`.
391///
392/// Take one with [`Shell::save_command_status`] and put it back with
393/// [`Shell::restore_command_status`] around anything the user didn't type -- a
394/// shell hook, `PROMPT_COMMAND`, prompt expansion -- so it stays invisible to
395/// the next command.
396#[derive(Clone, Debug)]
397pub struct SavedCommandStatus {
398    exit_status: u8,
399    exit_status_change_count: usize,
400    pipeline_statuses: Vec<u8>,
401    last_arg: Option<String>,
402}
403
404#[inherent::inherent]
405impl<SE: extensions::ShellExtensions> ShellState for Shell<SE> {
406    /// Returns whether or not this shell is a subshell.
407    pub fn is_subshell(&self) -> bool {
408        self.depth > 0
409    }
410
411    /// Returns the last "SECONDS" captured time.
412    pub fn last_stopwatch_time(&self) -> std::time::SystemTime {
413        self.last_stopwatch_time
414    }
415
416    /// Returns the last "SECONDS" offset requested.
417    pub fn last_stopwatch_offset(&self) -> u32 {
418        self.last_stopwatch_offset
419    }
420
421    /// Returns the shell environment containing variables.
422    pub fn env(&self) -> &ShellEnvironment {
423        &self.env
424    }
425
426    /// Returns a mutable reference to the shell environment.
427    pub fn env_mut(&mut self) -> &mut ShellEnvironment {
428        &mut self.env
429    }
430
431    /// Returns the shell's runtime options.
432    pub fn options(&self) -> &RuntimeOptions {
433        &self.options
434    }
435
436    /// Returns a mutable reference to the shell's runtime options.
437    pub fn options_mut(&mut self) -> &mut RuntimeOptions {
438        &mut self.options
439    }
440
441    /// Returns the shell's aliases.
442    pub fn aliases(&self) -> &HashMap<String, String> {
443        &self.aliases
444    }
445
446    /// Returns a mutable reference to the shell's aliases.
447    pub fn aliases_mut(&mut self) -> &mut HashMap<String, String> {
448        &mut self.aliases
449    }
450
451    /// Returns the shell's job manager.
452    pub fn jobs(&self) -> &jobs::JobManager {
453        &self.jobs
454    }
455
456    /// Returns a mutable reference to the shell's job manager.
457    pub fn jobs_mut(&mut self) -> &mut jobs::JobManager {
458        &mut self.jobs
459    }
460
461    /// Returns the shell's trap handler configuration.
462    pub fn traps(&self) -> &crate::traps::TrapHandlerConfig {
463        &self.traps
464    }
465
466    /// Returns a mutable reference to the shell's trap handler configuration.
467    pub fn traps_mut(&mut self) -> &mut crate::traps::TrapHandlerConfig {
468        &mut self.traps
469    }
470
471    /// Returns the shell's directory stack.
472    pub fn directory_stack(&self) -> &[PathBuf] {
473        &self.directory_stack
474    }
475
476    /// Returns a mutable reference to the shell's directory stack.
477    pub fn directory_stack_mut(&mut self) -> &mut Vec<PathBuf> {
478        &mut self.directory_stack
479    }
480
481    /// Returns the statuses of commands in the last pipeline.
482    pub fn last_pipeline_statuses(&self) -> &[u8] {
483        &self.last_pipeline_statuses
484    }
485
486    /// Returns a mutable reference to the statuses of commands in the last
487    /// pipeline.
488    pub fn last_pipeline_statuses_mut(&mut self) -> &mut Vec<u8> {
489        &mut self.last_pipeline_statuses
490    }
491
492    /// Returns the shell's program location cache.
493    pub fn program_location_cache(&self) -> &pathcache::PathCache {
494        &self.program_location_cache
495    }
496
497    /// Returns a mutable reference to the shell's program location cache.
498    pub fn program_location_cache_mut(&mut self) -> &mut pathcache::PathCache {
499        &mut self.program_location_cache
500    }
501
502    /// Returns the shell's completion configuration.
503    pub fn completion_config(&self) -> &crate::completion::Config {
504        &self.completion.config
505    }
506
507    /// Returns a mutable reference to the shell's completion configuration.
508    pub fn completion_config_mut(&mut self) -> &mut crate::completion::Config {
509        &mut self.completion.config
510    }
511
512    /// Returns the shell's open files.
513    pub fn open_files(&self) -> &openfiles::OpenFiles {
514        &self.open_files
515    }
516
517    /// Returns a mutable reference to the shell's open files.
518    pub fn open_files_mut(&mut self) -> &mut openfiles::OpenFiles {
519        &mut self.open_files
520    }
521
522    /// Returns the *current* name of the shell ($0).
523    /// Influenced by the current call stack.
524    pub fn current_shell_name(&self) -> Option<Cow<'_, str>> {
525        for frame in self.call_stack.iter() {
526            // Executed scripts shadow the shell name.
527            if frame.frame_type.is_run_script() {
528                return Some(frame.frame_type.name());
529            }
530        }
531
532        self.name.as_deref().map(|name| name.into())
533    }
534
535    /// Returns the current subshell depth; 0 is returned if this shell is not a
536    /// subshell.
537    pub fn depth(&self) -> usize {
538        self.depth
539    }
540
541    /// Returns the call stack for the shell.
542    pub fn call_stack(&self) -> &crate::callstack::CallStack {
543        &self.call_stack
544    }
545
546    /// Returns the shell's history, if it exists.
547    pub fn history(&self) -> Option<&crate::history::History> {
548        self.history.as_ref()
549    }
550
551    /// Returns a mutable reference to the shell's history, if it exists.
552    pub fn history_mut(&mut self) -> Option<&mut crate::history::History> {
553        self.history.as_mut()
554    }
555
556    /// Returns the shell's official version string (if available).
557    pub fn version(&self) -> Option<&str> {
558        self.version.as_deref()
559    }
560
561    /// Returns the exit status of the last command executed in this shell.
562    pub fn last_exit_status(&self) -> u8 {
563        self.last_exit_status
564    }
565
566    /// Updates the last exit status, bumping `last_exit_status_change_count`.
567    /// To *restore* a status rather than set one, use
568    /// [`Self::restore_command_status`], which puts the counter back too.
569    pub fn set_last_exit_status(&mut self, status: u8) {
570        self.last_exit_status = status;
571        self.last_exit_status_change_count += 1;
572    }
573
574    /// Returns the key bindings helper for the shell.
575    pub fn key_bindings(&self) -> Option<&KeyBindingsHelper> {
576        self.key_bindings.as_ref()
577    }
578
579    /// Sets the key bindings helper for the shell.
580    pub fn set_key_bindings(&mut self, key_bindings: Option<KeyBindingsHelper>) {
581        self.key_bindings = key_bindings;
582    }
583
584    /// Returns the shell's current working directory.
585    pub fn working_dir(&self) -> &Path {
586        &self.working_dir
587    }
588
589    /// Returns a mutable reference to the shell's current working directory.
590    /// This is only accessible within the crate.
591    pub(crate) fn working_dir_mut(&mut self) -> &mut PathBuf {
592        &mut self.working_dir
593    }
594
595    /// Returns the product display name for this shell.
596    pub fn product_display_str(&self) -> Option<&str> {
597        self.product_display_str.as_deref()
598    }
599}
600
601#[cfg(feature = "serde")]
602fn default_error_formatter<EF: extensions::ErrorFormatter>() -> EF {
603    EF::default()
604}
605
606#[cfg(test)]
607#[allow(clippy::panic_in_result_fn, reason = "assertions in a fallible test")]
608mod tests {
609    use super::*;
610
611    /// `$_` round-trips through a snapshot, unset included, so an embedder that
612    /// saves before running commands of its own gets back exactly what was
613    /// there -- not an empty string. (The interactive loop can't reach the
614    /// unset case: every command resets `$_`.)
615    #[tokio::test]
616    async fn saved_command_status_round_trips_last_arg() -> Result<(), error::Error> {
617        let mut shell = Shell::builder()
618            .profile(ProfileLoadBehavior::Skip)
619            .rc(RcLoadBehavior::Skip)
620            .build()
621            .await?;
622
623        shell.update_last_arg_variable(Some(String::from("saved")));
624        let with_value = shell.save_command_status();
625
626        shell.env.unset("_")?;
627        let while_unset = shell.save_command_status();
628
629        shell.restore_command_status(with_value);
630        assert_eq!(shell.env_str("_").as_deref(), Some("saved"));
631
632        shell.restore_command_status(while_unset);
633        assert_eq!(shell.env_str("_"), None);
634
635        Ok(())
636    }
637
638    #[tokio::test]
639    async fn unset_env_str_contract_is_independent_of_ifs_default() -> Result<(), error::Error> {
640        let mut shell = Shell::builder()
641            .profile(ProfileLoadBehavior::Skip)
642            .rc(RcLoadBehavior::Skip)
643            .build()
644            .await?;
645
646        shell.env.set_global(
647            "IFS",
648            crate::ShellVariable::new(crate::ShellValue::Unset(
649                crate::variables::ShellValueUnsetType::Untyped,
650            )),
651        )?;
652        assert_eq!(shell.env_str("IFS").as_deref(), Some(""));
653        assert_eq!(shell.ifs(), " \t\n");
654
655        shell.env.set_global("IFS", crate::ShellVariable::new(""))?;
656        assert_eq!(shell.env_str("IFS").as_deref(), Some(""));
657        assert_eq!(shell.ifs(), "");
658
659        Ok(())
660    }
661}