Skip to main content

nu_protocol/engine/
engine_state.rs

1use crate::{
2    BlockId, Config, DeclId, FileId, GetSpan, Handlers, HistoryConfig, JobId, Module, ModuleId,
3    OverlayId, ShellError, SignalAction, Signals, Signature, Span, SpanId, Type, TypeAlias,
4    TypeAliasId, Value, VarId, VirtualPathId,
5    ast::{Block, Expr},
6    debugger::{Debugger, NoopDebugger},
7    engine::{
8        CachedFile, Command, DEFAULT_OVERLAY_NAME, EnvName, EnvVars, OverlayFrame, PromptState,
9        ScopeFrame, Stack, StateDelta, Variable, VisibilityStack,
10        description::{Doccomments, build_desc},
11        signature_cache::SignatureCache,
12    },
13    eval_const::create_nu_constant,
14    report_error::ReportLog,
15    shell_error::{generic::GenericError, io::IoError},
16};
17use fancy_regex::Regex;
18use lru::LruCache;
19use nu_config::NushellConfigDirs;
20use nu_path::AbsolutePathBuf;
21use nu_utils::time::Instant;
22use std::{
23    borrow::Cow,
24    collections::{HashMap, HashSet},
25    num::NonZeroUsize,
26    path::PathBuf,
27    sync::{
28        Arc, Mutex, MutexGuard, OnceLock, PoisonError,
29        atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},
30        mpsc::Sender,
31        mpsc::channel,
32    },
33    time::Duration,
34};
35
36type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>;
37
38#[cfg(feature = "plugin")]
39use crate::{PluginRegistryFile, PluginRegistryItem, RegisteredPlugin};
40
41use super::{Closure, CurrentJob, Jobs, Mail, Mailbox, ThreadJob};
42
43/// Configure whether the current working directory may be updated when [`EngineState::merge_env`]
44/// is called.
45///
46/// During testing, this is causing issues, so this may disable it.
47pub static UPDATE_CWD: AtomicBool = AtomicBool::new(true);
48
49#[derive(Clone, Debug)]
50pub enum VirtualPath {
51    File(FileId),
52    Dir(Vec<VirtualPathId>),
53}
54
55#[derive(Debug, Default)]
56pub struct ReplState {
57    pub buffer: String,
58    // A byte position, as `EditCommand::MoveToPosition` is also a byte position
59    pub cursor_pos: usize,
60    /// Immediately accept the buffer on the next loop.
61    pub accept: bool,
62}
63
64#[derive(Debug)]
65pub struct IsDebugging(AtomicBool);
66
67impl IsDebugging {
68    pub fn new(val: bool) -> Self {
69        IsDebugging(AtomicBool::new(val))
70    }
71}
72
73impl Clone for IsDebugging {
74    fn clone(&self) -> Self {
75        IsDebugging(AtomicBool::new(self.0.load(Ordering::Relaxed)))
76    }
77}
78
79/// A file index remembered across lookups (see [`FileHint::contents`]). An `EngineState` is shared
80/// between threads, and a `StateWorkingSet` must be `Sync`, so this is an atomic; a clone starts
81/// from the same index.
82#[derive(Default)]
83pub(super) struct FileHint(AtomicUsize);
84
85impl Clone for FileHint {
86    fn clone(&self) -> Self {
87        Self(AtomicUsize::new(self.0.load(Ordering::Relaxed)))
88    }
89}
90
91impl FileHint {
92    /// The contents of `span` in the file of `files` that contains it, if any.
93    ///
94    /// The parser looks up span after span in the same file, so this checks the file the last
95    /// lookup found before scanning `files`, and remembers the file a scan finds. Only an empty
96    /// span on a boundary between files is in more than one file, and each gives the same empty
97    /// slice, so the result is always what the scan alone returns.
98    pub(super) fn contents<'a>(&self, files: &'a [CachedFile], span: Span) -> Option<&'a [u8]> {
99        let file = match files.get(self.0.load(Ordering::Relaxed)) {
100            Some(file) if file.covered_span.contains_span(span) => file,
101            _ => {
102                let (index, file) = files
103                    .iter()
104                    .enumerate()
105                    .find(|(_, file)| file.covered_span.contains_span(span))?;
106                self.0.store(index, Ordering::Relaxed);
107                file
108            }
109        };
110        let start = span.start - file.covered_span.start;
111        let end = span.end - file.covered_span.start;
112        Some(&file.content[start..end])
113    }
114}
115
116/// The core global engine state. This includes all global definitions as well as any global state that
117/// will persist for the whole session.
118///
119/// Declarations, variables, blocks, and other forms of data are held in the global state and referenced
120/// elsewhere using their IDs. These IDs are simply their index into the global state. This allows us to
121/// more easily handle creating blocks, binding variables and callsites, and more, because each of these
122/// will refer to the corresponding IDs rather than their definitions directly. At runtime, this means
123/// less copying and smaller structures.
124///
125/// Many of the larger objects in this structure are stored within `Arc` to decrease the cost of
126/// cloning `EngineState`. While `Arc`s are generally immutable, they can be modified using
127/// `Arc::make_mut`, which automatically clones to a new allocation if there are other copies of
128/// the `Arc` already in use, but will let us modify the `Arc` directly if we have the only
129/// reference to it.
130///
131/// Note that the runtime stack is not part of this global state. Runtime stacks are handled differently,
132/// but they also rely on using IDs rather than full definitions.
133#[derive(Clone, derive_more::Debug)]
134pub struct EngineState {
135    // `files`, `virtual_paths`, `vars`, `spans` and `scope` are in `Arc`s for the same reason as
136    // `blocks` below: commands that run a closure (`each`, `where`, ...) clone the engine state
137    // every time they are called, so a closure that calls one runs that clone once per value.
138    files: Arc<Vec<CachedFile>>,
139    /// The index in `files` of the file the last span lookup found (see
140    /// [`Self::try_get_file_contents`]).
141    #[debug(skip)]
142    last_file_hit: FileHint,
143    pub(super) virtual_paths: Arc<Vec<(String, VirtualPath)>>,
144    vars: Arc<Vec<Variable>>,
145    #[debug("{:?}", decls.iter().map(|c| c.name()).collect::<Vec<_>>())]
146    decls: Arc<Vec<Box<dyn Command + 'static>>>,
147    // The Vec is wrapped in Arc so that if we don't need to modify the list, we can just clone
148    // the reference and not have to clone each individual Arc inside. These lists can be
149    // especially long, so it helps
150    #[debug("{:?}", blocks.iter().map(|b| &b.signature.name))]
151    pub(super) blocks: Arc<Vec<Arc<Block>>>,
152    #[debug("{:?}", modules.iter().map(|m| String::from_utf8_lossy(&m.name)))]
153    pub(super) modules: Arc<Vec<Arc<Module>>>,
154    #[debug("{:?}", type_aliases.iter().map(|alias| &alias.name))]
155    pub(super) type_aliases: Arc<Vec<TypeAlias>>,
156    pub spans: Arc<Vec<Span>>,
157    doccomments: Doccomments,
158    /// Use [`Arc::make_mut`] to change it.
159    pub scope: Arc<ScopeFrame>,
160    signals: Signals,
161    pub signal_handlers: Option<Handlers>,
162    pub env_vars: Arc<EnvVars>,
163    pub previous_env_vars: Arc<HashMap<EnvName, Value>>,
164    /// Live config. Replace it with [`Self::set_config`] so [`Self::config_epoch`] stays in sync.
165    pub config: Arc<Config>,
166    /// Incremented when [`Self::config`] is replaced (`set_config`, `merge_env`).
167    config_epoch: u64,
168    pub pipeline_externals_state: Arc<(AtomicU32, AtomicU32)>,
169    pub repl_state: Arc<Mutex<ReplState>>,
170    /// Shared source of truth for the interactive prompt's rendered content. The
171    /// REPL fills it each cycle from `$env.PROMPT_COMMAND` and friends; a
172    /// background job's `commandline set-prompt` overwrites individual segments
173    /// and triggers an in-place repaint. Shared with every job that clones this
174    /// engine state.
175    pub prompt_state: Arc<PromptState>,
176    pub table_decl_id: Option<DeclId>,
177    /// Signatures of [`Self::decls`], built on first use by the parser. Clones share it, so that
178    /// cloning stays cheap; a clone that appends declarations while sharing it starts over with an
179    /// empty cache of its own (see [`Self::merge_delta`]).
180    #[debug(skip)]
181    pub(super) signature_cache: Arc<SignatureCache>,
182    #[cfg(feature = "plugin")]
183    pub plugin_path: Option<PathBuf>,
184    #[cfg(feature = "plugin")]
185    #[debug("{:?}", plugins.iter().map(|rp| rp.identity().name()).collect::<Vec<_>>())]
186    plugins: Vec<Arc<dyn RegisteredPlugin>>,
187    /// Resolved configuration directories and file paths.
188    ///
189    /// Populated once at startup by `nu_config::resolve_paths()` in `main.rs`.
190    /// All downstream code (config-file loading, `$nu` constant generation,
191    /// history backend, etc.) reads from this struct.
192    pub config_dirs: NushellConfigDirs,
193
194    pub history_enabled: bool,
195    pub history_session_id: i64,
196    /// Whether the startup-only `$env.config.history.*` options are locked from further
197    /// changes (currently `path`, `max_size`, `file_format`, `isolation`).
198    ///
199    /// Set to `true` once the REPL has finished initializing reedline's history backend.
200    /// After that point, changing any of these options would have no effect on the live
201    /// history, so attempts to mutate them are rejected with an error instead of being
202    /// silently ignored.
203    pub history_locked_after_startup: bool,
204    // Path to the file Nushell is currently evaluating, or None if we're in an interactive session.
205    pub file: Option<PathBuf>,
206    pub regex_cache: Arc<Mutex<LruCache<String, Regex>>>,
207    pub is_interactive: bool,
208    /// Whether evaluation returns to a REPL prompt, unlike commands or scripts run with `-i`.
209    pub is_repl: bool,
210    /// When true with [`Self::is_interactive`], REPL user-line evaluation may store `$ans`.
211    ///
212    /// Set only around true REPL command evaluation (`do_run_cmd`), not config/env/banner
213    /// startup, so startup scripts do not overwrite interactive last-result.
214    pub capture_repl_last_result: bool,
215    pub is_login: bool,
216    pub is_lsp: bool,
217    pub is_mcp: bool,
218    /// Running as the Debug Adapter Protocol server (`nu --dap`). Like
219    /// `is_lsp`/`is_mcp`, this means stdout is a protocol stream, so anything
220    /// that would print to it must go to stderr instead.
221    pub is_dap: bool,
222    /// When startup began: the top of `main` for the `nu` binary, otherwise when this engine
223    /// was created. See [`EngineState::startup_time`].
224    startup_start: Instant,
225    /// How long startup took, once [`EngineState::finish_startup`] has been called.
226    startup_time: Option<Duration>,
227    is_debugging: IsDebugging,
228    pub debugger: Arc<Mutex<Box<dyn Debugger>>>,
229    pub report_log: Arc<Mutex<ReportLog>>,
230
231    pub jobs: Arc<Mutex<Jobs>>,
232
233    // The job being executed with this engine state, or None if main thread
234    pub current_job: CurrentJob,
235
236    pub root_job_sender: Sender<Mail>,
237
238    // When there are background jobs that are not auto_kill, interactive `exit` checks this flag:
239    // - if false, it warns about those jobs and sets this flag
240    // - if true, it kills all jobs and exits
241    // If all jobs have auto_kill, exit kills them and exits without warning.
242    //
243    // This ensures that running exit twice will terminate the program correctly
244    pub exit_warning_given: Arc<AtomicBool>,
245}
246
247// The max number of compiled regexes to keep around in a LRU cache, arbitrarily chosen
248const REGEX_CACHE_SIZE: usize = 100; // must be nonzero, otherwise will panic
249
250pub const NU_VARIABLE_ID: VarId = VarId::new(0);
251pub const IN_VARIABLE_ID: VarId = VarId::new(1);
252pub const ENV_VARIABLE_ID: VarId = VarId::new(2);
253/// Interactive last-result special variable.
254///
255/// The user-facing name is [`LAST_RESULT_VAR_NAME`] (e.g. `$ans`). Change that constant
256/// if the public name should differ; keep this ID stable.
257pub const LAST_VARIABLE_ID: VarId = VarId::new(3);
258/// Identifier for the last-result special variable **without** the `$` sigil.
259///
260/// Change this single constant to rename the binding site-wide (e.g. `"ans"` → `$ans`).
261/// The name is reserved (cannot be rebound with `let` / `mut` / `const`). Not user-configurable.
262///
263/// With a positive `max_last_result_size`, `$ans` is `{ last, exit_code, duration, command }`.
264/// With size `0`, `$ans` is `{ exit_code, duration, command }` (`last` omitted). `command` is
265/// the exact last REPL source (same buffer reedline stores in history). Resolved from
266/// the stack's last-result slot, not from captured locals — keep capture-discovery
267/// `>` checks in sync with this being the last special var id.
268pub const LAST_RESULT_VAR_NAME: &str = "ans";
269// NOTE: If you add more specials after LAST_VARIABLE_ID, update capture discovery
270// (`var_id > LAST_VARIABLE_ID`) and any other special-id thresholds.
271
272// The first span is unknown span
273pub const UNKNOWN_SPAN_ID: SpanId = SpanId::new(0);
274
275impl EngineState {
276    pub fn new() -> Self {
277        let (send, recv) = channel::<Mail>();
278
279        Self {
280            files: Arc::new(vec![]),
281            last_file_hit: FileHint::default(),
282            virtual_paths: Arc::new(vec![]),
283            vars: Arc::new(vec![
284                Variable::new(Span::new(0, 0), Type::Any, false),
285                Variable::new(Span::new(0, 0), Type::Any, false),
286                Variable::new(Span::new(0, 0), Type::Any, false),
287                Variable::new(Span::new(0, 0), Type::Any, false),
288                Variable::new(Span::new(0, 0), Type::Any, false),
289            ]),
290            decls: Arc::new(vec![]),
291            blocks: Arc::new(vec![]),
292            modules: Arc::new(vec![Arc::new(Module::new(
293                DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
294            ))]),
295            type_aliases: Arc::new(vec![]),
296            spans: Arc::new(vec![Span::unknown()]),
297            doccomments: Doccomments::new(),
298            // make sure we have some default overlay:
299            scope: Arc::new(ScopeFrame::with_empty_overlay(
300                DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
301                ModuleId::new(0),
302                false,
303            )),
304            signal_handlers: None,
305            signals: Signals::empty(),
306            env_vars: Arc::new(
307                [(DEFAULT_OVERLAY_NAME.to_string(), HashMap::new())]
308                    .into_iter()
309                    .collect(),
310            ),
311            previous_env_vars: Arc::new(HashMap::new()),
312            config: Arc::new(Config::default()),
313            config_epoch: 0,
314            pipeline_externals_state: Arc::new((AtomicU32::new(0), AtomicU32::new(0))),
315            repl_state: Arc::new(Mutex::new(ReplState {
316                buffer: "".to_string(),
317                cursor_pos: 0,
318                accept: false,
319            })),
320            prompt_state: Arc::new(PromptState::new()),
321            table_decl_id: None,
322            signature_cache: Arc::default(),
323            #[cfg(feature = "plugin")]
324            plugin_path: None,
325            #[cfg(feature = "plugin")]
326            plugins: vec![],
327            config_dirs: NushellConfigDirs::empty(),
328            history_enabled: true,
329            history_session_id: 0,
330            history_locked_after_startup: false,
331            file: None,
332            regex_cache: Arc::new(Mutex::new(LruCache::new(
333                NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
334            ))),
335            is_interactive: false,
336            is_repl: false,
337            capture_repl_last_result: false,
338            is_login: false,
339            is_lsp: false,
340            is_mcp: false,
341            is_dap: false,
342            startup_start: Instant::now(),
343            startup_time: None,
344            is_debugging: IsDebugging::new(false),
345            debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
346            report_log: Arc::default(),
347            jobs: Arc::new(Mutex::new(Jobs::default())),
348            current_job: CurrentJob {
349                id: JobId::new(0),
350                root: JobId::new(0),
351                background_thread_job: None,
352                mailbox: Arc::new(Mutex::new(Mailbox::new(recv))),
353            },
354            root_job_sender: send,
355            exit_warning_given: Arc::new(AtomicBool::new(false)),
356        }
357    }
358
359    pub fn signals(&self) -> &Signals {
360        &self.signals
361    }
362
363    /// Return a compiled regex, reusing the process-wide LRU cache when possible.
364    ///
365    /// On lock contention (or a poisoned mutex), compiles without touching the cache.
366    pub fn get_cached_regex(&self, pattern: &str) -> Result<Regex, fancy_regex::Error> {
367        match self.regex_cache.try_lock() {
368            Ok(mut cache) => cache
369                .try_get_or_insert_ref(pattern, || Regex::new(pattern))
370                .cloned(),
371            Err(_) => Regex::new(pattern),
372        }
373    }
374
375    /// Compile `pattern` via [`Self::get_cached_regex`], mapping failures to
376    /// [`ShellError::InvalidValue`] at `span`.
377    pub fn compile_regex(&self, pattern: &str, span: Span) -> Result<Regex, ShellError> {
378        self.get_cached_regex(pattern)
379            .map_err(|err| invalid_regex_value(pattern, err, span))
380    }
381
382    pub fn reset_signals(&mut self) {
383        self.signals.reset();
384        if let Some(ref handlers) = self.signal_handlers {
385            handlers.run(SignalAction::Reset);
386        }
387    }
388
389    pub fn set_signals(&mut self, signals: Signals) {
390        self.signals = signals;
391    }
392
393    /// Merges a `StateDelta` onto the current state. These deltas come from a system, like the parser, that
394    /// creates a new set of definitions and visible symbols in the current scope. We make this transactional
395    /// as there are times when we want to run the parser and immediately throw away the results (namely:
396    /// syntax highlighting and completions).
397    ///
398    /// When we want to preserve what the parser has created, we can take its output (the `StateDelta`) and
399    /// use this function to merge it into the global state.
400    pub fn merge_delta(&mut self, mut delta: StateDelta) -> Result<(), ShellError> {
401        // Take the mutable reference and extend the permanent state from the working set,
402        // avoiding potentially cloning the Arcs if we aren't adding anything
403        if !delta.files.is_empty() {
404            Arc::make_mut(&mut self.files).extend(delta.files);
405        }
406        if !delta.virtual_paths.is_empty() {
407            Arc::make_mut(&mut self.virtual_paths).extend(delta.virtual_paths);
408        }
409        if !delta.vars.is_empty() {
410            Arc::make_mut(&mut self.vars).extend(delta.vars);
411        }
412        if !delta.spans.is_empty() {
413            Arc::make_mut(&mut self.spans).extend(delta.spans);
414        }
415        self.doccomments.merge_with(delta.doccomments);
416
417        if !delta.decls.is_empty() {
418            // Clones that share the signature cache must agree on every declaration it holds, so
419            // an engine that adds declarations the other clones don't have stops sharing it. It
420            // starts over with an empty cache rather than a copy. Copying would clone every
421            // signature and remembered output type, while later parses rebuild only the entries
422            // they use.
423            Arc::make_mut(&mut self.decls).extend(delta.decls);
424            match Arc::get_mut(&mut self.signature_cache) {
425                Some(cache) => cache.effective.resize_with(self.decls.len(), OnceLock::new),
426                None => self.signature_cache = Arc::new(SignatureCache::new(self.decls.len())),
427            }
428        }
429        if !delta.blocks.is_empty() {
430            Arc::make_mut(&mut self.blocks).extend(delta.blocks);
431        }
432        if !delta.modules.is_empty() {
433            Arc::make_mut(&mut self.modules).extend(delta.modules);
434        }
435        if !delta.type_aliases.is_empty() {
436            Arc::make_mut(&mut self.type_aliases).extend(delta.type_aliases);
437        }
438
439        let first = delta.scope.remove(0);
440        let scope = Arc::make_mut(&mut self.scope);
441
442        for (delta_name, delta_overlay) in first.clone().overlays {
443            if let Some((_, existing_overlay)) = scope
444                .overlays
445                .iter_mut()
446                .find(|(name, _)| name == &delta_name)
447            {
448                // Updating existing overlay
449                for item in delta_overlay.decls.into_iter() {
450                    existing_overlay.decls.insert(item.0, item.1);
451                }
452                for item in delta_overlay.vars.into_iter() {
453                    existing_overlay.insert_variable(item.0, item.1);
454                }
455                for item in delta_overlay.modules.into_iter() {
456                    existing_overlay.modules.insert(item.0, item.1);
457                }
458                existing_overlay
459                    .type_aliases
460                    .extend(delta_overlay.type_aliases);
461
462                existing_overlay
463                    .visibility
464                    .merge_with(delta_overlay.visibility);
465            } else {
466                // New overlay was added to the delta
467                scope.overlays.push((delta_name, delta_overlay));
468            }
469        }
470
471        // A variable that `unlet` hid at the top level is gone for later source too, from
472        // whichever overlay binds it. This comes after the merge above, which records the
473        // variables that the delta's own bindings shadow.
474        for var_id in &first.hidden_vars {
475            for (_, overlay) in &mut scope.overlays {
476                overlay.vars.retain(|_, bound| *bound != *var_id);
477            }
478        }
479
480        // Overlays the delta added are in `scope` now, so their ids can be looked up
481        let mut activated_ids = Self::translate_overlay_ids(scope, &first);
482
483        let mut removed_ids = vec![];
484
485        for name in &first.removed_overlays {
486            if let Some(overlay_id) = scope.find_overlay(name) {
487                removed_ids.push(overlay_id);
488            }
489        }
490
491        // Remove overlays removed in delta
492        scope.active_overlays.retain(|id| !removed_ids.contains(id));
493
494        // Move overlays activated in the delta to be first
495        scope
496            .active_overlays
497            .retain(|id| !activated_ids.contains(id));
498        scope.active_overlays.append(&mut activated_ids);
499
500        #[cfg(feature = "plugin")]
501        if !delta.plugins.is_empty() {
502            for plugin in std::mem::take(&mut delta.plugins) {
503                // Connect plugins to the signal handlers
504                if let Some(handlers) = &self.signal_handlers {
505                    plugin.clone().configure_signal_handler(handlers)?;
506                }
507
508                // Replace plugins that overlap in identity.
509                if let Some(existing) = self
510                    .plugins
511                    .iter_mut()
512                    .find(|p| p.identity().name() == plugin.identity().name())
513                {
514                    // Stop the existing plugin, so that the new plugin definitely takes over
515                    existing.stop()?;
516                    *existing = plugin;
517                } else {
518                    self.plugins.push(plugin);
519                }
520            }
521        }
522
523        #[cfg(feature = "plugin")]
524        if !delta.plugin_registry_items.is_empty() {
525            // Update the plugin file with the new signatures.
526            if self.plugin_path.is_some() {
527                self.update_plugin_file(std::mem::take(&mut delta.plugin_registry_items))?;
528            }
529        }
530
531        Ok(())
532    }
533
534    /// Remove the variables that `unlet` deleted at runtime (`stack.deletions`) from the active
535    /// overlay, so later source no longer sees them, and clear the list. `unlet` on a constant
536    /// already took effect while parsing, for the block it's in (see `parse_pipeline_element`), so
537    /// a constant unlet in a nested block stays for later source.
538    pub fn merge_deletions(&mut self, stack: &mut Stack) {
539        for var_id in stack.deletions.drain(..) {
540            if self.get_constant(var_id).is_some() {
541                continue;
542            }
543            let scope = Arc::make_mut(&mut self.scope);
544            if let Some(active_id) = scope.active_overlays.last()
545                && let Some((_, overlay)) = scope.overlays.get_mut(active_id.get())
546            {
547                overlay.vars.retain(|_, v| *v != var_id);
548            }
549        }
550    }
551
552    /// Merge the environment from the runtime Stack into the engine state
553    pub fn merge_env(&mut self, stack: &mut Stack) -> Result<(), ShellError> {
554        for mut scope in stack.env_vars.drain(..) {
555            for (overlay_name, mut env) in Arc::make_mut(&mut scope).drain() {
556                if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
557                    // Updating existing overlay
558                    env_vars.extend(env.drain());
559                } else {
560                    // Pushing a new overlay
561                    Arc::make_mut(&mut self.env_vars).insert(overlay_name, env);
562                }
563            }
564        }
565
566        if UPDATE_CWD.load(Ordering::Relaxed) {
567            let cwd = self.cwd(Some(stack))?;
568            std::env::set_current_dir(cwd)
569                .map_err(|err| IoError::new_internal(err, "Could not set current dir"))?;
570        }
571
572        if let Some(config) = stack.config.take() {
573            // If config was updated in the stack, replace it.
574            self.replace_config(config);
575
576            // Make plugin GC config changes take effect immediately.
577            #[cfg(feature = "plugin")]
578            self.update_plugin_gc_configs(&self.config.plugin_gc);
579        }
580
581        Ok(())
582    }
583
584    /// Clean up unused variables from a Stack to prevent memory leaks.
585    /// This removes variables that are no longer referenced by any overlay or alias.
586    pub fn cleanup_stack_variables(&mut self, stack: &mut Stack) {
587        // Only take the scope for writing when there is something to drain.
588        if self
589            .scope
590            .overlays
591            .iter()
592            .all(|(_, frame)| frame.shadowed_vars.is_empty())
593        {
594            return;
595        }
596
597        let mut shadowed_vars = HashSet::new();
598        for (_, frame) in Arc::make_mut(&mut self.scope).overlays.iter_mut() {
599            shadowed_vars.extend(frame.shadowed_vars.drain(..));
600        }
601
602        // Collect VarIds still referenced by alias definitions so we don't
603        // remove them — doing so would cause a VariableNotFoundAtRuntime error
604        // when the alias is invoked after the variable has been re-bound.
605        let mut alias_var_ids = HashSet::new();
606        for decl in self.decls.iter() {
607            if let Some(alias) = decl.as_alias() {
608                collect_alias_var_ids(&alias.wrapped_call, &mut alias_var_ids);
609            }
610        }
611
612        // Remove variables from stack that are shadowed and not referenced by any alias
613        stack.vars.retain(|(var_id, _)| {
614            !shadowed_vars.contains(var_id) || alias_var_ids.contains(var_id)
615        });
616    }
617
618    pub fn active_overlay_ids<'a, 'b>(
619        &'b self,
620        removed_overlays: &'a [Vec<u8>],
621    ) -> impl DoubleEndedIterator<Item = &'b OverlayId> + 'a
622    where
623        'b: 'a,
624    {
625        self.scope.active_overlays.iter().filter(|id| {
626            !removed_overlays
627                .iter()
628                .any(|name| name == self.get_overlay_name(**id))
629        })
630    }
631
632    pub fn active_overlays<'a, 'b>(
633        &'b self,
634        removed_overlays: &'a [Vec<u8>],
635    ) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
636    where
637        'b: 'a,
638    {
639        self.active_overlay_ids(removed_overlays)
640            .map(|id| self.get_overlay(*id))
641    }
642
643    pub fn active_overlay_names<'a, 'b>(
644        &'b self,
645        removed_overlays: &'a [Vec<u8>],
646    ) -> impl DoubleEndedIterator<Item = &'b [u8]> + 'a
647    where
648        'b: 'a,
649    {
650        self.active_overlay_ids(removed_overlays)
651            .map(|id| self.get_overlay_name(*id))
652    }
653
654    /// Translate overlay IDs from other to IDs in self
655    /// The ids in `scope` of the overlays active in `other`, matched by name.
656    fn translate_overlay_ids(scope: &ScopeFrame, other: &ScopeFrame) -> Vec<OverlayId> {
657        let other_names = other.active_overlays.iter().map(|other_id| {
658            &other
659                .overlays
660                .get(other_id.get())
661                .expect("internal error: missing overlay")
662                .0
663        });
664
665        other_names
666            .map(|other_name| {
667                scope
668                    .find_overlay(other_name)
669                    .expect("internal error: missing overlay")
670            })
671            .collect()
672    }
673
674    pub fn last_overlay_name(&self, removed_overlays: &[Vec<u8>]) -> &[u8] {
675        self.active_overlay_names(removed_overlays)
676            .last()
677            .expect("internal error: no active overlays")
678    }
679
680    pub fn last_overlay(&self, removed_overlays: &[Vec<u8>]) -> &OverlayFrame {
681        self.active_overlay_ids(removed_overlays)
682            .last()
683            .map(|id| self.get_overlay(*id))
684            .expect("internal error: no active overlays")
685    }
686
687    pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
688        &self
689            .scope
690            .overlays
691            .get(overlay_id.get())
692            .expect("internal error: missing overlay")
693            .0
694    }
695
696    pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
697        &self
698            .scope
699            .overlays
700            .get(overlay_id.get())
701            .expect("internal error: missing overlay")
702            .1
703    }
704
705    pub fn render_env_vars(&self) -> HashMap<&str, &Value> {
706        let mut result: HashMap<&str, &Value> = HashMap::new();
707
708        for overlay_name in self.active_overlay_names(&[]) {
709            let name = String::from_utf8_lossy(overlay_name);
710            if let Some(env_vars) = self.env_vars.get(name.as_ref()) {
711                result.extend(env_vars.iter().map(|(k, v)| (k.as_str(), v)));
712            }
713        }
714
715        result
716    }
717
718    pub fn add_env_var(&mut self, name: String, val: Value) {
719        let overlay_name = String::from_utf8_lossy(self.last_overlay_name(&[])).to_string();
720
721        if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
722            env_vars.insert(EnvName::from(name), val);
723        } else {
724            Arc::make_mut(&mut self.env_vars).insert(
725                overlay_name,
726                [(EnvName::from(name), val)].into_iter().collect(),
727            );
728        }
729    }
730
731    pub fn get_env_var(&self, name: &str) -> Option<&Value> {
732        for overlay_id in self.scope.active_overlays.iter().rev() {
733            let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
734            if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref())
735                && let Some(val) = env_vars.get(&EnvName::from(name))
736            {
737                return Some(val);
738            }
739        }
740
741        None
742    }
743
744    #[cfg(feature = "plugin")]
745    pub fn plugins(&self) -> &[Arc<dyn RegisteredPlugin>] {
746        &self.plugins
747    }
748
749    #[cfg(feature = "plugin")]
750    fn update_plugin_file(&self, updated_items: Vec<PluginRegistryItem>) -> Result<(), ShellError> {
751        // Updating the signatures plugin file with the added signatures
752        use std::fs::File;
753
754        let plugin_path = self.plugin_path.as_ref().ok_or_else(|| {
755            ShellError::Generic(
756                GenericError::new_internal("Plugin file path not set", "")
757                    .with_help("you may be running nu with --no-config-file"),
758            )
759        })?;
760
761        // Read the current contents of the plugin file if it exists
762        let mut contents = match File::open(plugin_path.as_path()) {
763            Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
764            Err(err) => {
765                if err.kind() == std::io::ErrorKind::NotFound {
766                    Ok(PluginRegistryFile::default())
767                } else {
768                    Err(ShellError::Io(IoError::new_internal_with_path(
769                        err,
770                        "Failed to open plugin file",
771                        PathBuf::from(plugin_path),
772                    )))
773                }
774            }
775        }?;
776
777        // Update the given signatures
778        for item in updated_items {
779            contents.upsert_plugin(item);
780        }
781
782        // Write it to the same path
783        let plugin_file = File::create(plugin_path.as_path()).map_err(|err| {
784            IoError::new_internal_with_path(
785                err,
786                "Failed to write plugin file",
787                PathBuf::from(plugin_path),
788            )
789        })?;
790
791        contents.write_to(plugin_file, None)
792    }
793
794    /// Update plugins with new garbage collection config
795    #[cfg(feature = "plugin")]
796    fn update_plugin_gc_configs(&self, plugin_gc: &crate::PluginGcConfigs) {
797        for plugin in &self.plugins {
798            plugin.set_gc_config(plugin_gc.get(plugin.identity().name()));
799        }
800    }
801
802    pub fn num_files(&self) -> usize {
803        self.files.len()
804    }
805
806    pub fn num_virtual_paths(&self) -> usize {
807        self.virtual_paths.len()
808    }
809
810    pub fn num_vars(&self) -> usize {
811        self.vars.len()
812    }
813
814    pub fn num_decls(&self) -> usize {
815        self.decls.len()
816    }
817
818    pub fn num_blocks(&self) -> usize {
819        self.blocks.len()
820    }
821
822    pub fn num_modules(&self) -> usize {
823        self.modules.len()
824    }
825
826    pub fn num_spans(&self) -> usize {
827        self.spans.len()
828    }
829    pub fn print_vars(&self) {
830        for var in self.vars.iter().enumerate() {
831            println!("var{}: {:?}", var.0, var.1);
832        }
833    }
834
835    pub fn print_decls(&self) {
836        for decl in self.decls.iter().enumerate() {
837            println!("decl{}: {:?}", decl.0, decl.1.signature());
838        }
839    }
840
841    pub fn print_blocks(&self) {
842        for block in self.blocks.iter().enumerate() {
843            println!("block{}: {:?}", block.0, block.1);
844        }
845    }
846
847    pub fn print_contents(&self) {
848        for cached_file in self.files.iter() {
849            let string = String::from_utf8_lossy(&cached_file.content);
850            println!("{string}");
851        }
852    }
853
854    /// Find the [`DeclId`](crate::DeclId) corresponding to a declaration with `name`.
855    ///
856    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
857    pub fn find_decl(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<DeclId> {
858        let mut visibility = VisibilityStack::default();
859
860        for overlay_frame in self.active_overlays(removed_overlays).rev() {
861            visibility.push(&overlay_frame.visibility);
862
863            if let Some(decl_id) = overlay_frame.get_decl(name)
864                && visibility.is_decl_id_visible(&decl_id)
865            {
866                return Some(decl_id);
867            }
868        }
869
870        None
871    }
872
873    /// Find the name of the declaration corresponding to `decl_id`.
874    ///
875    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
876    pub fn find_decl_name(&self, decl_id: DeclId, removed_overlays: &[Vec<u8>]) -> Option<&[u8]> {
877        let mut visibility = VisibilityStack::default();
878
879        for overlay_frame in self.active_overlays(removed_overlays).rev() {
880            visibility.push(&overlay_frame.visibility);
881
882            if visibility.is_decl_id_visible(&decl_id) {
883                for (name, id) in overlay_frame.decls.iter() {
884                    if id == &decl_id {
885                        return Some(name);
886                    }
887                }
888            }
889        }
890
891        None
892    }
893
894    /// Find the [`OverlayId`](crate::OverlayId) corresponding to `name`.
895    ///
896    /// Searches all overlays, not just active overlays. To search only in active overlays, use [`find_active_overlay`](EngineState::find_active_overlay)
897    pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
898        self.scope.find_overlay(name)
899    }
900
901    /// Find the [`OverlayId`](crate::OverlayId) of the active overlay corresponding to `name`.
902    ///
903    /// Searches only active overlays. To search in all overlays, use [`find_overlay`](EngineState::find_active_overlay)
904    pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
905        self.scope.find_active_overlay(name)
906    }
907
908    /// Find the [`ModuleId`](crate::ModuleId) corresponding to `name`.
909    ///
910    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
911    pub fn find_module(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<ModuleId> {
912        for overlay_frame in self.active_overlays(removed_overlays).rev() {
913            if let Some(module_id) = overlay_frame.modules.get(name) {
914                return Some(*module_id);
915            }
916        }
917
918        None
919    }
920
921    /// Find the [`TypeAliasId`] corresponding to `name`.
922    ///
923    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
924    pub fn find_type_alias(
925        &self,
926        name: &[u8],
927        removed_overlays: &[Vec<u8>],
928    ) -> Option<TypeAliasId> {
929        let mut visibility = VisibilityStack::default();
930
931        for overlay_frame in self.active_overlays(removed_overlays).rev() {
932            visibility.push(&overlay_frame.visibility);
933
934            if let Some(type_alias_id) = overlay_frame.type_aliases.get(name)
935                && visibility.is_type_alias_id_visible(type_alias_id)
936            {
937                return Some(*type_alias_id);
938            }
939        }
940
941        None
942    }
943
944    pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
945        self.doccomments.get_module_comments(module_id)
946    }
947
948    #[cfg(feature = "plugin")]
949    pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
950        let mut unique_plugin_decls = HashMap::new();
951
952        // Make sure there are no duplicate decls: Newer one overwrites the older one
953        for decl in self.decls.iter().filter(|d| d.is_plugin()) {
954            unique_plugin_decls.insert(decl.name(), decl);
955        }
956
957        let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
958            unique_plugin_decls.into_iter().collect();
959
960        // Sort the plugins by name so we don't end up with a random plugin file each time
961        plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
962        plugin_decls.into_iter().map(|(_, decl)| decl)
963    }
964
965    pub fn which_module_has_decl(
966        &self,
967        decl_name: &[u8],
968        removed_overlays: &[Vec<u8>],
969    ) -> Option<&[u8]> {
970        for overlay_frame in self.active_overlays(removed_overlays).rev() {
971            for (module_name, module_id) in overlay_frame.modules.iter() {
972                let module = self.get_module(*module_id);
973                if module.has_decl(decl_name) {
974                    return Some(module_name);
975                }
976            }
977        }
978
979        None
980    }
981
982    /// Apply a function to all commands. The function accepts a command name and its DeclId
983    pub fn traverse_commands(&self, mut f: impl FnMut(&[u8], DeclId)) {
984        for overlay_frame in self.active_overlays(&[]).rev() {
985            for (name, decl_id) in &overlay_frame.decls {
986                if overlay_frame.visibility.is_decl_id_visible(decl_id) {
987                    f(name, *decl_id);
988                }
989            }
990        }
991    }
992
993    pub fn get_span_contents(&self, span: Span) -> &[u8] {
994        self.try_get_file_contents(span).unwrap_or(&[0u8; 0])
995    }
996
997    pub fn try_get_file_contents(&self, span: Span) -> Option<&[u8]> {
998        self.last_file_hit.contents(&self.files, span)
999    }
1000
1001    /// If the span's content starts with the given prefix, return two subspans
1002    /// corresponding to this prefix, and the rest of the content.
1003    pub fn span_match_prefix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
1004        let contents = self.get_span_contents(span);
1005
1006        if contents.starts_with(prefix) {
1007            span.split_at(prefix.len())
1008        } else {
1009            None
1010        }
1011    }
1012
1013    /// If the span's content ends with the given postfix, return two subspans
1014    /// corresponding to the rest of the content, and this postfix.
1015    pub fn span_match_postfix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
1016        let contents = self.get_span_contents(span);
1017
1018        if contents.ends_with(prefix) {
1019            span.split_at(span.len() - prefix.len())
1020        } else {
1021            None
1022        }
1023    }
1024
1025    /// Get the global config from the engine state.
1026    ///
1027    /// Use [`Stack::get_config()`] instead whenever the `Stack` is available, as it takes into
1028    /// account local changes to `$env.config`.
1029    pub fn get_config(&self) -> &Arc<Config> {
1030        &self.config
1031    }
1032
1033    /// Identity of the current config object. Changes when `$env.config` is rewritten.
1034    pub fn config_epoch(&self) -> u64 {
1035        self.config_epoch
1036    }
1037
1038    fn replace_config(&mut self, conf: Arc<Config>) {
1039        self.config_epoch = self.config_epoch.wrapping_add(1);
1040        self.config = conf;
1041    }
1042
1043    pub fn set_config(&mut self, conf: impl Into<Arc<Config>>) {
1044        let conf = conf.into();
1045
1046        #[cfg(feature = "plugin")]
1047        if conf.plugin_gc != self.config.plugin_gc {
1048            // Make plugin GC config changes take effect immediately.
1049            self.update_plugin_gc_configs(&conf.plugin_gc);
1050        }
1051
1052        self.replace_config(conf);
1053    }
1054
1055    /// Fetch the configuration for a plugin
1056    ///
1057    /// The `plugin` must match the registered name of a plugin.  For `plugin add
1058    /// nu_plugin_example` the plugin name to use will be `"example"`
1059    pub fn get_plugin_config(&self, plugin: &str) -> Option<&Value> {
1060        self.config.plugins.get(plugin)
1061    }
1062
1063    /// Returns the configuration settings for command history or `None` if history is disabled
1064    pub fn history_config(&self) -> Option<HistoryConfig> {
1065        self.history_enabled.then(|| self.config.history.clone())
1066    }
1067
1068    /// Resolve the history file path using the already-resolved config dirs.
1069    ///
1070    /// Returns `None` when history is disabled or the history path is set to
1071    /// [`HistoryPath::Disabled`].
1072    pub fn history_path(&self) -> Option<std::path::PathBuf> {
1073        self.history_config()?
1074            .file_path(&self.config_dirs.config_home)
1075    }
1076
1077    pub fn get_var(&self, var_id: VarId) -> &Variable {
1078        self.vars
1079            .get(var_id.get())
1080            .expect("internal error: missing variable")
1081    }
1082
1083    pub fn get_constant(&self, var_id: VarId) -> Option<&Value> {
1084        let var = self.get_var(var_id);
1085        var.const_val.as_ref()
1086    }
1087
1088    pub fn generate_nu_constant(&mut self) {
1089        let nu_const = create_nu_constant(self, Span::unknown());
1090        Arc::make_mut(&mut self.vars)[NU_VARIABLE_ID.get()].const_val = Some(nu_const);
1091    }
1092
1093    pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
1094        self.decls
1095            .get(decl_id.get())
1096            .expect("internal error: missing declaration")
1097            .as_ref()
1098    }
1099
1100    /// Get all commands within scope, sorted by the commands' names
1101    pub fn get_decls_sorted(&self, include_hidden: bool) -> Vec<(Vec<u8>, DeclId)> {
1102        let mut decls_map = HashMap::new();
1103
1104        for overlay_frame in self.active_overlays(&[]) {
1105            let new_decls = if include_hidden {
1106                overlay_frame.decls.clone()
1107            } else {
1108                overlay_frame
1109                    .decls
1110                    .clone()
1111                    .into_iter()
1112                    .filter(|(_, id)| overlay_frame.visibility.is_decl_id_visible(id))
1113                    .collect()
1114            };
1115
1116            decls_map.extend(new_decls);
1117        }
1118
1119        let mut decls: Vec<(Vec<u8>, DeclId)> = decls_map.into_iter().collect();
1120
1121        decls.sort_by(|a, b| a.0.cmp(&b.0));
1122        decls
1123    }
1124
1125    pub fn get_signature(&self, decl: &dyn Command) -> Signature {
1126        if let Some(block_id) = decl.block_id() {
1127            *self.blocks[block_id.get()].signature.clone()
1128        } else {
1129            decl.signature()
1130        }
1131    }
1132
1133    /// Shared version of [`EngineState::get_signature`] for the declaration `decl_id`.
1134    ///
1135    /// The signature is built the first time it is asked for and then shared from the signature
1136    /// cache (see `SignatureCache`), so a command called once per value doesn't rebuild its
1137    /// signature on every call.
1138    pub fn get_signature_shared(&self, decl_id: DeclId) -> Arc<Signature> {
1139        match self.cached_signature(decl_id) {
1140            Some(signature) => Arc::clone(signature),
1141            None => Arc::new(self.get_signature(self.get_decl(decl_id))),
1142        }
1143    }
1144
1145    /// [`EngineState::get_signature`] for the declaration `decl_id`, borrowed from the signature
1146    /// cache like [`EngineState::get_signature_shared`] shares it. Borrowing doesn't touch the
1147    /// `Arc`'s reference count, which every thread calling the same command at once (`par-each`)
1148    /// would otherwise update.
1149    pub fn get_signature_cached(&self, decl_id: DeclId) -> Cow<'_, Signature> {
1150        match self.cached_signature(decl_id) {
1151            Some(signature) => Cow::Borrowed(signature),
1152            None => Cow::Owned(self.get_signature(self.get_decl(decl_id))),
1153        }
1154    }
1155
1156    /// The signature cache's entry for `decl_id`, built the first time it's asked for. Every
1157    /// declaration has an entry (see [`EngineState::merge_delta`]); `None` would mean one is
1158    /// missing, and the callers build the signature instead.
1159    fn cached_signature(&self, decl_id: DeclId) -> Option<&Arc<Signature>> {
1160        let entry = self.signature_cache.effective.get(decl_id.get())?;
1161        Some(entry.get_or_init(|| Arc::new(self.get_signature(self.get_decl(decl_id)))))
1162    }
1163
1164    /// Get the signature of a command as a call by `name` in the current scope sees it.
1165    ///
1166    /// The signature is named `name`, which can differ from the declared name: a module command
1167    /// declared as `foo bar` is `spam foo bar` after `use spam`, and an alias of an internal
1168    /// command carries a copy of the wrapped command's signature, so `alias st = str trim` would
1169    /// otherwise be named `str trim`.
1170    ///
1171    /// For an alias of an internal command, the positional parameters the alias already passes
1172    /// are dropped, because the parser matches a call's arguments to the parameters after them
1173    /// (see `parse_internal_call`): `alias home = cd ~` takes no `path`. Flags the alias passes
1174    /// stay listed.
1175    pub fn get_signature_in_scope(&self, name: String, decl_id: DeclId) -> Signature {
1176        let decl = self.get_decl(decl_id);
1177        let mut signature = self.get_signature(decl).update_from_command(decl);
1178        signature.name = name;
1179
1180        if let Some(alias) = decl.as_alias()
1181            && let Expr::Call(call) = &alias.wrapped_call.expr
1182        {
1183            // Arguments fill the required parameters first, then the optional ones, and
1184            // `...rest` takes any number, the order `Signature::get_positional` uses.
1185            let passed = call.positional_iter().count();
1186            let required = passed.min(signature.required_positional.len());
1187            signature.required_positional.drain(..required);
1188            let optional = (passed - required).min(signature.optional_positional.len());
1189            signature.optional_positional.drain(..optional);
1190        }
1191
1192        signature
1193    }
1194
1195    /// Get signatures of all commands within scope with their decl ids, sorted by name.
1196    ///
1197    /// Each signature is the one [`get_signature_in_scope`](Self::get_signature_in_scope) gives
1198    /// for the name. A command in scope under several names is listed once per name.
1199    ///
1200    /// Unless `include_hidden` is set, each name is resolved with `find_decl`, the lookup the
1201    /// parser uses, so the list holds the names a call can use, each with the command it runs.
1202    /// `get_decls_sorted(false)` isn't enough on its own: it checks each overlay against its own
1203    /// visibility, but a `hide` of a command from an earlier overlay is recorded in the overlay
1204    /// active at the time.
1205    pub fn get_signatures_and_declids(&self, include_hidden: bool) -> Vec<(Signature, DeclId)> {
1206        self.get_decls_sorted(true)
1207            .into_iter()
1208            .filter_map(|(name, id)| {
1209                let id = if include_hidden {
1210                    id
1211                } else {
1212                    self.find_decl(&name, &[])?
1213                };
1214                Some((name, id))
1215            })
1216            .map(|(name, id)| {
1217                let name = String::from_utf8_lossy(&name).into_owned();
1218                (self.get_signature_in_scope(name, id), id)
1219            })
1220            .collect()
1221    }
1222
1223    pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
1224        self.blocks
1225            .get(block_id.get())
1226            .expect("internal error: missing block")
1227    }
1228
1229    /// Optionally get a block by id, if it exists
1230    ///
1231    /// Use this instead of [`.get_block()`](Self::get_block) whenever the
1232    /// `BlockId` comes from a runtime value instead of the current parse,
1233    /// because such a block may legitimately be missing (see
1234    /// [`get_closure_block`](Self::get_closure_block)).
1235    pub fn try_get_block(&self, block_id: BlockId) -> Option<&Arc<Block>> {
1236        self.blocks.get(block_id.get())
1237    }
1238
1239    /// Get the block a closure refers to, or an error when that block is not
1240    /// available in this engine state.
1241    ///
1242    /// Closures can be passed between jobs. A job may have been spawned before
1243    /// the closure was parsed, so its cloned engine state may not contain the
1244    /// referenced block. Unlike [`get_block`](Self::get_block), this reports
1245    /// that case as a regular shell error instead of panicking.
1246    pub fn get_closure_block(
1247        &self,
1248        closure: &Closure,
1249        span: Span,
1250    ) -> Result<&Arc<Block>, ShellError> {
1251        self.try_get_block(closure.block_id).ok_or_else(|| {
1252            ShellError::Generic(GenericError::new(
1253                "Closure cannot be evaluated",
1254                format!(
1255                    "the closure refers to a block that is not available in this engine state (block {})",
1256                    closure.block_id.get()
1257                ),
1258                span,
1259            )
1260            .with_help(super::MISSING_CLOSURE_BLOCK_HELP))
1261        })
1262    }
1263
1264    pub fn get_module(&self, module_id: ModuleId) -> &Module {
1265        self.modules
1266            .get(module_id.get())
1267            .expect("internal error: missing module")
1268    }
1269
1270    pub fn get_type_alias(&self, type_alias_id: TypeAliasId) -> &TypeAlias {
1271        self.type_aliases
1272            .get(type_alias_id.get())
1273            .expect("internal error: missing type alias")
1274    }
1275
1276    pub fn num_type_aliases(&self) -> usize {
1277        self.type_aliases.len()
1278    }
1279
1280    pub fn get_virtual_path(&self, virtual_path_id: VirtualPathId) -> &(String, VirtualPath) {
1281        self.virtual_paths
1282            .get(virtual_path_id.get())
1283            .expect("internal error: missing virtual path")
1284    }
1285
1286    pub fn next_span_start(&self) -> usize {
1287        if let Some(cached_file) = self.files.last() {
1288            cached_file.covered_span.end
1289        } else {
1290            0
1291        }
1292    }
1293
1294    pub fn files(
1295        &self,
1296    ) -> impl DoubleEndedIterator<Item = &CachedFile> + ExactSizeIterator<Item = &CachedFile> {
1297        self.files.iter()
1298    }
1299
1300    pub fn add_file(&mut self, filename: Arc<str>, content: Arc<[u8]>) -> FileId {
1301        let next_span_start = self.next_span_start();
1302        let next_span_end = next_span_start + content.len();
1303
1304        let covered_span = Span::new(next_span_start, next_span_end);
1305
1306        Arc::make_mut(&mut self.files).push(CachedFile {
1307            name: filename,
1308            content,
1309            covered_span,
1310        });
1311
1312        FileId::new(self.num_files() - 1)
1313    }
1314
1315    pub fn build_desc(&self, spans: &[Span]) -> (String, String) {
1316        let comment_lines: Vec<&[u8]> = spans
1317            .iter()
1318            .map(|span| self.get_span_contents(*span))
1319            .collect();
1320        build_desc(&comment_lines)
1321    }
1322
1323    pub fn build_module_desc(&self, module_id: ModuleId) -> Option<(String, String)> {
1324        self.get_module_comments(module_id)
1325            .map(|comment_spans| self.build_desc(comment_spans))
1326    }
1327
1328    /// Returns the current working directory, which is guaranteed to be an
1329    /// absolute path without trailing slashes (unless it's the root path), but
1330    /// might contain symlink components.
1331    ///
1332    /// If `stack` is supplied, also considers modifications to the working
1333    /// directory on the stack that have yet to be merged into the engine state.
1334    pub fn cwd(&self, stack: Option<&Stack>) -> Result<AbsolutePathBuf, ShellError> {
1335        // Helper function to create a simple generic error.
1336        fn error(msg: &str, cwd: impl AsRef<nu_path::Path>) -> ShellError {
1337            ShellError::Generic(
1338                GenericError::new_internal(
1339                    msg.to_string(),
1340                    format!("$env.PWD = {}", cwd.as_ref().display()),
1341                )
1342                .with_help("Use `cd` to reset $env.PWD into a good state"),
1343            )
1344        }
1345
1346        // Retrieve $env.PWD from the stack or the engine state.
1347        let pwd = if let Some(stack) = stack {
1348            stack.get_env_var(self, "PWD")
1349        } else {
1350            self.get_env_var("PWD")
1351        };
1352
1353        let pwd = pwd.ok_or_else(|| error("$env.PWD not found", ""))?;
1354
1355        if let Ok(pwd) = pwd.as_str() {
1356            let path = AbsolutePathBuf::try_from(pwd)
1357                .map_err(|_| error("$env.PWD is not an absolute path", pwd))?;
1358
1359            // Technically, a root path counts as "having trailing slashes", but
1360            // for the purpose of PWD, a root path is acceptable.
1361            if path.parent().is_some() && nu_path::has_trailing_slash(path.as_ref()) {
1362                Err(error("$env.PWD contains trailing slashes", &path))
1363            } else if !path.exists() {
1364                Err(error("$env.PWD points to a non-existent directory", &path))
1365            } else if !path.is_dir() {
1366                Err(error("$env.PWD points to a non-directory", &path))
1367            } else {
1368                Ok(path)
1369            }
1370        } else {
1371            Err(error("$env.PWD is not a string", format!("{pwd:?}")))
1372        }
1373    }
1374
1375    /// Like `EngineState::cwd()`, but returns a String instead of a PathBuf for convenience.
1376    pub fn cwd_as_string(&self, stack: Option<&Stack>) -> Result<String, ShellError> {
1377        let cwd = self.cwd(stack)?;
1378        cwd.into_os_string()
1379            .into_string()
1380            .map_err(|err| ShellError::NonUtf8Custom {
1381                msg: format!("The current working directory is not a valid utf-8 string: {err:?}"),
1382                span: Span::unknown(),
1383            })
1384    }
1385
1386    // TODO: see if we can completely get rid of this
1387    pub fn get_file_contents(&self) -> &[CachedFile] {
1388        &self.files
1389    }
1390
1391    /// How long startup took (`$nu.startup-time`), or how long it has taken so far while it is
1392    /// still running, for example while the config files are being evaluated.
1393    ///
1394    /// Like the timers in bash and zsh, startup is measured from inside the shell, not from
1395    /// process creation, so it leaves out the time the operating system spends starting the
1396    /// executable, and `exec nu` does not count the program it replaced.
1397    pub fn startup_time(&self) -> Duration {
1398        self.startup_time
1399            .unwrap_or_else(|| self.startup_start.elapsed())
1400    }
1401
1402    /// Sets when startup began. `nu` calls this with the time it reads at the top of `main`.
1403    pub fn set_startup_start(&mut self, startup_start: Instant) {
1404        self.startup_start = startup_start;
1405    }
1406
1407    /// Ends startup: from now on [`EngineState::startup_time`] stays at the time it took, and
1408    /// later calls keep the first value. Regenerates `$nu` so it shows that time, along with any
1409    /// other changes made during startup. Returns the startup time.
1410    pub fn finish_startup(&mut self) -> Duration {
1411        let startup_time = *self
1412            .startup_time
1413            .get_or_insert_with(|| self.startup_start.elapsed());
1414        self.generate_nu_constant();
1415        startup_time
1416    }
1417
1418    pub fn activate_debugger(
1419        &self,
1420        debugger: Box<dyn Debugger>,
1421    ) -> Result<(), PoisonDebuggerError<'_>> {
1422        let mut locked_debugger = self.debugger.lock()?;
1423        *locked_debugger = debugger;
1424        locked_debugger.activate();
1425        self.is_debugging.0.store(true, Ordering::Relaxed);
1426        Ok(())
1427    }
1428
1429    pub fn deactivate_debugger(&self) -> Result<Box<dyn Debugger>, PoisonDebuggerError<'_>> {
1430        let mut locked_debugger = self.debugger.lock()?;
1431        locked_debugger.deactivate();
1432        let ret = std::mem::replace(&mut *locked_debugger, Box::new(NoopDebugger));
1433        self.is_debugging.0.store(false, Ordering::Relaxed);
1434        Ok(ret)
1435    }
1436
1437    pub fn is_debugging(&self) -> bool {
1438        self.is_debugging.0.load(Ordering::Relaxed)
1439    }
1440
1441    pub fn recover_from_panic(&mut self) {
1442        if Mutex::is_poisoned(&self.repl_state) {
1443            self.repl_state = Arc::new(Mutex::new(ReplState {
1444                buffer: "".to_string(),
1445                cursor_pos: 0,
1446                accept: false,
1447            }));
1448        }
1449        if Mutex::is_poisoned(&self.jobs) {
1450            self.jobs = Arc::new(Mutex::new(Jobs::default()));
1451        }
1452        if Mutex::is_poisoned(&self.regex_cache) {
1453            self.regex_cache = Arc::new(Mutex::new(LruCache::new(
1454                NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
1455            )));
1456        }
1457    }
1458
1459    /// Reset mutable per-session state after cloning a shared engine template.
1460    pub fn make_session_state_unique(&mut self) {
1461        let (send, recv) = channel();
1462
1463        self.pipeline_externals_state = Arc::new((AtomicU32::new(0), AtomicU32::new(0)));
1464        self.repl_state = Default::default();
1465        self.report_log = Default::default();
1466        self.prompt_state = Arc::new(PromptState::new());
1467        self.jobs = Default::default();
1468        self.current_job = CurrentJob {
1469            id: JobId::new(0),
1470            root: JobId::new(0),
1471            background_thread_job: None,
1472            mailbox: Arc::new(Mutex::new(Mailbox::new(recv))),
1473        };
1474        self.root_job_sender = send;
1475        self.exit_warning_given = Default::default();
1476        self.regex_cache = Arc::new(Mutex::new(LruCache::new(
1477            NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
1478        )));
1479        self.is_debugging = IsDebugging::new(false);
1480        self.debugger = Arc::new(Mutex::new(Box::new(NoopDebugger)));
1481    }
1482
1483    /// Add new span and return its ID
1484    pub fn add_span(&mut self, span: Span) -> SpanId {
1485        Arc::make_mut(&mut self.spans).push(span);
1486        SpanId::new(self.num_spans() - 1)
1487    }
1488
1489    /// Find ID of a span (should be avoided if possible)
1490    pub fn find_span_id(&self, span: Span) -> Option<SpanId> {
1491        self.spans
1492            .iter()
1493            .position(|sp| sp == &span)
1494            .map(SpanId::new)
1495    }
1496
1497    // Determines whether the current state is being held by a background job
1498    pub fn is_background_job(&self) -> bool {
1499        self.current_job.background_thread_job.is_some()
1500    }
1501
1502    // Gets the thread job entry
1503    pub fn current_thread_job(&self) -> Option<&ThreadJob> {
1504        self.current_job.background_thread_job.as_ref()
1505    }
1506}
1507
1508/// Collect all `VarId`s referenced by `Expr::Var` nodes in `expr`.
1509/// This is used by [`EngineState::cleanup_stack_variables`] to avoid removing
1510/// variables that are still referenced by alias definitions.
1511fn collect_alias_var_ids(expr: &crate::ast::Expression, var_ids: &mut HashSet<VarId>) {
1512    let mut queue = vec![expr];
1513
1514    while let Some(e) = queue.pop() {
1515        match &e.expr {
1516            Expr::Var(id) => {
1517                var_ids.insert(*id);
1518            }
1519            Expr::Call(call) => {
1520                for arg in &call.arguments {
1521                    if let Some(sub_expr) = arg.expr() {
1522                        queue.push(sub_expr);
1523                    }
1524                }
1525            }
1526            Expr::ExternalCall(head, args) => {
1527                queue.push(head);
1528                for arg in args.iter() {
1529                    queue.push(arg.expr());
1530                }
1531            }
1532            Expr::FullCellPath(fcp) => queue.push(&fcp.head),
1533            _ => {}
1534        }
1535    }
1536}
1537
1538impl GetSpan for &EngineState {
1539    /// Get existing span
1540    fn get_span(&self, span_id: SpanId) -> Span {
1541        *self
1542            .spans
1543            .get(span_id.get())
1544            .expect("internal error: missing span")
1545    }
1546}
1547
1548impl Default for EngineState {
1549    fn default() -> Self {
1550        Self::new()
1551    }
1552}
1553
1554/// Map a fancy-regex compile failure to [`ShellError::InvalidValue`].
1555///
1556/// Shared by [`EngineState::compile_regex`] and call sites that compile with
1557/// options that bypass the LRU cache (for example a custom backtrack limit).
1558pub fn invalid_regex_value(pattern: &str, err: fancy_regex::Error, span: Span) -> ShellError {
1559    ShellError::InvalidValue {
1560        valid: "a valid regular expression".into(),
1561        actual: format!("'{pattern}' ({err})"),
1562        span,
1563    }
1564}
1565
1566#[cfg(test)]
1567mod engine_state_tests {
1568    use crate::engine::StateWorkingSet;
1569    use std::str::{Utf8Error, from_utf8};
1570
1571    use super::*;
1572
1573    #[test]
1574    fn add_file_gives_id() {
1575        let engine_state = EngineState::new();
1576        let mut engine_state = StateWorkingSet::new(&engine_state);
1577        let id = engine_state.add_file("test.nu", &[]);
1578
1579        assert_eq!(id, FileId::new(0));
1580    }
1581
1582    /// An engine that appends declarations to a signature cache it shares with a clone starts
1583    /// over with its own empty cache; one that doesn't share it keeps it.
1584    #[test]
1585    fn merging_declarations_stops_sharing_the_signature_cache() {
1586        let merge_a_decl = |engine_state: &mut EngineState| {
1587            let mut working_set = StateWorkingSet::new(engine_state);
1588            working_set.add_decl(Signature::new("foo").predeclare());
1589            let delta = working_set.render();
1590            engine_state
1591                .merge_delta(delta)
1592                .expect("merging a declaration");
1593        };
1594
1595        let mut engine_state = EngineState::new();
1596        let clone = engine_state.clone();
1597        assert!(Arc::ptr_eq(
1598            &engine_state.signature_cache,
1599            &clone.signature_cache
1600        ));
1601        merge_a_decl(&mut engine_state);
1602        assert!(!Arc::ptr_eq(
1603            &engine_state.signature_cache,
1604            &clone.signature_cache
1605        ));
1606
1607        let cache = Arc::as_ptr(&engine_state.signature_cache);
1608        merge_a_decl(&mut engine_state);
1609        assert_eq!(Arc::as_ptr(&engine_state.signature_cache), cache);
1610    }
1611
1612    #[test]
1613    fn merging_into_a_clone_leaves_the_original_unchanged() {
1614        let engine_state = EngineState::new();
1615        let mut clone = engine_state.clone();
1616        assert!(Arc::ptr_eq(&engine_state.scope, &clone.scope));
1617        assert!(Arc::ptr_eq(&engine_state.vars, &clone.vars));
1618
1619        let mut working_set = StateWorkingSet::new(&clone);
1620        working_set.add_decl(Signature::new("foo").predeclare());
1621        working_set.add_variable(b"bar".to_vec(), Span::unknown(), Type::Int, false);
1622        let _ = working_set.add_file("baz", b"qux");
1623        let delta = working_set.render();
1624        clone.merge_delta(delta).expect("merging a delta");
1625
1626        assert!(clone.find_decl(b"foo", &[]).is_some());
1627        assert!(engine_state.find_decl(b"foo", &[]).is_none());
1628        assert_eq!(clone.num_vars(), engine_state.num_vars() + 1);
1629        assert_eq!(clone.num_files(), engine_state.num_files() + 1);
1630    }
1631
1632    #[test]
1633    fn shared_signature_is_built_once() {
1634        let mut engine_state = EngineState::new();
1635        let mut working_set = StateWorkingSet::new(&engine_state);
1636        let decl_id = working_set.add_decl(Signature::new("foo").predeclare());
1637        let delta = working_set.render();
1638        engine_state
1639            .merge_delta(delta)
1640            .expect("merging a declaration");
1641
1642        let signature = engine_state.get_signature_shared(decl_id);
1643        assert_eq!(signature.name, "foo");
1644        assert!(Arc::ptr_eq(
1645            &signature,
1646            &engine_state.get_signature_shared(decl_id)
1647        ));
1648        assert!(matches!(
1649            engine_state.get_signature_cached(decl_id),
1650            Cow::Borrowed(cached) if std::ptr::eq(cached, &*signature)
1651        ));
1652
1653        // A clone that adds a declaration gets a cache of its own, with an entry for each one.
1654        let mut clone = engine_state.clone();
1655        let mut working_set = StateWorkingSet::new(&clone);
1656        let bar_id = working_set.add_decl(Signature::new("bar").predeclare());
1657        let delta = working_set.render();
1658        clone.merge_delta(delta).expect("merging a declaration");
1659        for id in [decl_id, bar_id] {
1660            assert!(matches!(clone.get_signature_cached(id), Cow::Borrowed(_)));
1661        }
1662    }
1663
1664    #[test]
1665    fn file_contents_lookup_finds_what_a_scan_finds() {
1666        let mut engine_state = EngineState::new();
1667        for (index, content) in ["", "abc", "", "", "de", "f", ""].iter().enumerate() {
1668            engine_state.add_file(format!("file{index}").into(), content.as_bytes().into());
1669        }
1670        let end = engine_state.next_span_start();
1671        let scan = |span: Span| {
1672            engine_state.files.iter().find_map(|file| {
1673                file.covered_span.contains_span(span).then(|| {
1674                    &file.content
1675                        [span.start - file.covered_span.start..span.end - file.covered_span.start]
1676                })
1677            })
1678        };
1679        let spans: Vec<Span> = (0..=end + 1)
1680            .flat_map(|start| (start..=end + 1).map(move |span_end| Span::new(start, span_end)))
1681            .collect();
1682        // Both orders, so that the remembered file is sometimes right and sometimes not.
1683        for span in spans.iter().chain(spans.iter().rev()) {
1684            assert_eq!(
1685                engine_state.try_get_file_contents(*span),
1686                scan(*span),
1687                "{span:?}"
1688            );
1689        }
1690    }
1691
1692    #[test]
1693    fn get_cached_regex_reuses_compiled_patterns() {
1694        let engine_state = EngineState::new();
1695        let pattern = r"[^\w]+";
1696
1697        let first = engine_state
1698            .get_cached_regex(pattern)
1699            .expect("pattern should compile");
1700        assert!(first.is_match("!!!").unwrap_or(false));
1701
1702        {
1703            let cache = engine_state.regex_cache.lock().expect("cache lock");
1704            assert_eq!(cache.len(), 1);
1705            assert!(cache.peek(pattern).is_some());
1706        }
1707
1708        let second = engine_state
1709            .get_cached_regex(pattern)
1710            .expect("pattern should compile from cache");
1711        assert!(second.is_match("!!!").unwrap_or(false));
1712
1713        {
1714            let cache = engine_state.regex_cache.lock().expect("cache lock");
1715            assert_eq!(cache.len(), 1, "second lookup should not grow the cache");
1716        }
1717    }
1718
1719    #[test]
1720    fn get_cached_regex_does_not_store_invalid_patterns() {
1721        let engine_state = EngineState::new();
1722
1723        assert!(engine_state.get_cached_regex("(").is_err());
1724
1725        let cache = engine_state.regex_cache.lock().expect("cache lock");
1726        assert_eq!(cache.len(), 0);
1727    }
1728
1729    #[test]
1730    fn add_file_gives_id_including_parent() {
1731        let mut engine_state = EngineState::new();
1732        let parent_id = engine_state.add_file("test.nu".into(), Arc::new([]));
1733
1734        let mut working_set = StateWorkingSet::new(&engine_state);
1735        let working_set_id = working_set.add_file("child.nu", &[]);
1736
1737        assert_eq!(parent_id, FileId::new(0));
1738        assert_eq!(working_set_id, FileId::new(1));
1739    }
1740
1741    #[test]
1742    fn merge_states() -> Result<(), ShellError> {
1743        let mut engine_state = EngineState::new();
1744        engine_state.add_file("test.nu".into(), Arc::new([]));
1745
1746        let delta = {
1747            let mut working_set = StateWorkingSet::new(&engine_state);
1748            let _ = working_set.add_file("child.nu", &[]);
1749            working_set.render()
1750        };
1751
1752        engine_state.merge_delta(delta)?;
1753
1754        assert_eq!(engine_state.num_files(), 2);
1755        assert_eq!(&*engine_state.files[0].name, "test.nu");
1756        assert_eq!(&*engine_state.files[1].name, "child.nu");
1757
1758        Ok(())
1759    }
1760
1761    #[test]
1762    fn list_variables() -> Result<(), Utf8Error> {
1763        let varname = "something";
1764        let varname_with_sigil = "$".to_owned() + varname;
1765        let engine_state = EngineState::new();
1766        let mut working_set = StateWorkingSet::new(&engine_state);
1767        working_set.add_variable(
1768            varname.as_bytes().into(),
1769            Span { start: 0, end: 1 },
1770            Type::Int,
1771            false,
1772        );
1773        let variables = working_set
1774            .list_variables()
1775            .into_iter()
1776            .map(from_utf8)
1777            .collect::<Result<Vec<&str>, Utf8Error>>()?;
1778        assert_eq!(variables, vec![varname_with_sigil]);
1779        Ok(())
1780    }
1781
1782    #[test]
1783    fn get_plugin_config() {
1784        let mut engine_state = EngineState::new();
1785
1786        assert!(
1787            engine_state.get_plugin_config("example").is_none(),
1788            "Unexpected plugin configuration"
1789        );
1790
1791        let mut plugins = HashMap::new();
1792        plugins.insert("example".into(), Value::string("value", Span::test_data()));
1793
1794        let mut config = Config::clone(engine_state.get_config());
1795        config.plugins = plugins;
1796
1797        engine_state.set_config(config);
1798
1799        assert!(
1800            engine_state.get_plugin_config("example").is_some(),
1801            "Plugin configuration not found"
1802        );
1803    }
1804}
1805
1806#[cfg(test)]
1807mod test_cwd {
1808    //! Here're the test cases we need to cover:
1809    //!
1810    //! `EngineState::cwd()` computes the result from `self.env_vars["PWD"]` and
1811    //! optionally `stack.env_vars["PWD"]`.
1812    //!
1813    //! PWD may be unset in either `env_vars`.
1814    //! PWD should NOT be an empty string.
1815    //! PWD should NOT be a non-string value.
1816    //! PWD should NOT be a relative path.
1817    //! PWD should NOT contain trailing slashes.
1818    //! PWD may point to a directory or a symlink to directory.
1819    //! PWD should NOT point to a file or a symlink to file.
1820    //! PWD should NOT point to non-existent entities in the filesystem.
1821
1822    use crate::{
1823        Value,
1824        engine::{EngineState, Stack},
1825    };
1826    use nu_path::{AbsolutePath, Path, assert_path_eq};
1827    use tempfile::{NamedTempFile, TempDir};
1828
1829    /// Creates a symlink. Works on both Unix and Windows.
1830    #[cfg(any(unix, windows))]
1831    fn symlink(
1832        original: impl AsRef<AbsolutePath>,
1833        link: impl AsRef<AbsolutePath>,
1834    ) -> std::io::Result<()> {
1835        let original = original.as_ref();
1836        let link = link.as_ref();
1837
1838        #[cfg(unix)]
1839        {
1840            std::os::unix::fs::symlink(original, link)
1841        }
1842        #[cfg(windows)]
1843        {
1844            if original.is_dir() {
1845                std::os::windows::fs::symlink_dir(original, link)
1846            } else {
1847                std::os::windows::fs::symlink_file(original, link)
1848            }
1849        }
1850    }
1851
1852    /// Create an engine state initialized with the given PWD.
1853    fn engine_state_with_pwd(path: impl AsRef<Path>) -> EngineState {
1854        let mut engine_state = EngineState::new();
1855        engine_state.add_env_var(
1856            "PWD".into(),
1857            Value::test_string(path.as_ref().to_str().unwrap()),
1858        );
1859        engine_state
1860    }
1861
1862    /// Create a stack initialized with the given PWD.
1863    fn stack_with_pwd(path: impl AsRef<Path>) -> Stack {
1864        let mut stack = Stack::new();
1865        stack.add_env_var(
1866            "PWD".into(),
1867            Value::test_string(path.as_ref().to_str().unwrap()),
1868        );
1869        stack
1870    }
1871
1872    #[test]
1873    fn pwd_not_set() {
1874        let engine_state = EngineState::new();
1875        engine_state.cwd(None).unwrap_err();
1876    }
1877
1878    #[test]
1879    fn pwd_is_empty_string() {
1880        let engine_state = engine_state_with_pwd("");
1881        engine_state.cwd(None).unwrap_err();
1882    }
1883
1884    #[test]
1885    fn pwd_is_non_string_value() {
1886        let mut engine_state = EngineState::new();
1887        engine_state.add_env_var("PWD".into(), Value::test_glob("*"));
1888        engine_state.cwd(None).unwrap_err();
1889    }
1890
1891    #[test]
1892    fn pwd_is_relative_path() {
1893        let engine_state = engine_state_with_pwd("./foo");
1894
1895        engine_state.cwd(None).unwrap_err();
1896    }
1897
1898    #[test]
1899    fn pwd_has_trailing_slash() {
1900        let dir = TempDir::new().unwrap();
1901        let engine_state = engine_state_with_pwd(dir.path().join(""));
1902
1903        engine_state.cwd(None).unwrap_err();
1904    }
1905
1906    #[test]
1907    fn pwd_points_to_root() {
1908        #[cfg(windows)]
1909        let root = Path::new(r"C:\");
1910        #[cfg(not(windows))]
1911        let root = Path::new("/");
1912
1913        let engine_state = engine_state_with_pwd(root);
1914        let cwd = engine_state.cwd(None).unwrap();
1915        assert_path_eq!(cwd, root);
1916    }
1917
1918    #[test]
1919    fn pwd_points_to_normal_file() {
1920        let file = NamedTempFile::new().unwrap();
1921        let engine_state = engine_state_with_pwd(file.path());
1922
1923        engine_state.cwd(None).unwrap_err();
1924    }
1925
1926    #[test]
1927    fn pwd_points_to_normal_directory() {
1928        let dir = TempDir::new().unwrap();
1929        let engine_state = engine_state_with_pwd(dir.path());
1930
1931        let cwd = engine_state.cwd(None).unwrap();
1932        assert_path_eq!(cwd, dir.path());
1933    }
1934
1935    #[test]
1936    fn pwd_points_to_symlink_to_file() {
1937        let file = NamedTempFile::new().unwrap();
1938        let temp_file = AbsolutePath::try_new(file.path()).unwrap();
1939        let dir = TempDir::new().unwrap();
1940        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1941
1942        let link = temp.join("link");
1943        symlink(temp_file, &link).unwrap();
1944        let engine_state = engine_state_with_pwd(&link);
1945
1946        engine_state.cwd(None).unwrap_err();
1947    }
1948
1949    #[test]
1950    fn pwd_points_to_symlink_to_directory() {
1951        let dir = TempDir::new().unwrap();
1952        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1953
1954        let link = temp.join("link");
1955        symlink(temp, &link).unwrap();
1956        let engine_state = engine_state_with_pwd(&link);
1957
1958        let cwd = engine_state.cwd(None).unwrap();
1959        assert_path_eq!(cwd, link);
1960    }
1961
1962    #[test]
1963    fn pwd_points_to_broken_symlink() {
1964        let dir = TempDir::new().unwrap();
1965        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1966        let other_dir = TempDir::new().unwrap();
1967        let other_temp = AbsolutePath::try_new(other_dir.path()).unwrap();
1968
1969        let link = temp.join("link");
1970        symlink(other_temp, &link).unwrap();
1971        let engine_state = engine_state_with_pwd(&link);
1972
1973        drop(other_dir);
1974        engine_state.cwd(None).unwrap_err();
1975    }
1976
1977    #[test]
1978    fn pwd_points_to_nonexistent_entity() {
1979        let engine_state = engine_state_with_pwd(TempDir::new().unwrap().path());
1980
1981        engine_state.cwd(None).unwrap_err();
1982    }
1983
1984    #[test]
1985    fn stack_pwd_not_set() {
1986        let dir = TempDir::new().unwrap();
1987        let engine_state = engine_state_with_pwd(dir.path());
1988        let stack = Stack::new();
1989
1990        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1991        assert_eq!(cwd, dir.path());
1992    }
1993
1994    #[test]
1995    fn stack_pwd_is_empty_string() {
1996        let dir = TempDir::new().unwrap();
1997        let engine_state = engine_state_with_pwd(dir.path());
1998        let stack = stack_with_pwd("");
1999
2000        engine_state.cwd(Some(&stack)).unwrap_err();
2001    }
2002
2003    #[test]
2004    fn stack_pwd_points_to_normal_directory() {
2005        let dir1 = TempDir::new().unwrap();
2006        let dir2 = TempDir::new().unwrap();
2007        let engine_state = engine_state_with_pwd(dir1.path());
2008        let stack = stack_with_pwd(dir2.path());
2009
2010        let cwd = engine_state.cwd(Some(&stack)).unwrap();
2011        assert_path_eq!(cwd, dir2.path());
2012    }
2013
2014    #[test]
2015    fn stack_pwd_points_to_normal_directory_with_symlink_components() {
2016        let dir = TempDir::new().unwrap();
2017        let temp = AbsolutePath::try_new(dir.path()).unwrap();
2018
2019        // `/tmp/dir/link` points to `/tmp/dir`, then we set PWD to `/tmp/dir/link/foo`
2020        let link = temp.join("link");
2021        symlink(temp, &link).unwrap();
2022        let foo = link.join("foo");
2023        std::fs::create_dir(temp.join("foo")).unwrap();
2024        let engine_state = EngineState::new();
2025        let stack = stack_with_pwd(&foo);
2026
2027        let cwd = engine_state.cwd(Some(&stack)).unwrap();
2028        assert_path_eq!(cwd, foo);
2029    }
2030}